error in testing :the exc is Authentication credentials were not provided

22 views Asked by At

I make a test for the /course url, made a login using another endpoint /auth/login in setUP and setUp working fine.

The test is failed. here the error message:

ERROR:root:the exc is Authentication credentials were not provided. and context is {'view': <course.views.CourseApi object at 0x7fe78ba9ad10>, 'args': (), 'kwargs': {}, 'request': <rest_framework.request.Request: GET '/course'>} and response is <Response status_code=403, "text/html; charset=utf-8"> and code 400 WARNING:django.request:Forbidden: /course response headers {'Content-Type': 'application/json', 'Vary': 'Accept, origin', 'Allow': 'GET, POST, PUT, DELETE, HEAD, OPTIONS', 'X-Frame-Options': 'DENY', 'Content-Length': '77', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'same-origin', 'Cross-Origin-Opener-Policy': 'same-origin'} F

Here is the code

from django.test import TestCase
from rest_framework.test import APIClient, force_authenticate
import requests

class TestUrls(TestCase):
    def setUp(self):
        self.client = APIClient()
        # Make a request to login endpoint to obtain the token
        login_url = 'http://127.0.0.1:8000/auth/login'
        login_data = {
            'email': '<my_email>',
            'password': '<my_password>',
            'token': 'Bearer <my_token_str>'
        }
        response = requests.post(login_url, json=login_data)
        print(response.json())

        if response.status_code == 200:
            # Extract the token from the response
            self.token = response.json().get('payload').get('token')
            # Use the obtained token for authentication
            print(self.token)
            force_authenticate(self.client, token=f'Bearer {self.token}')
        else:
            # Handle the case where login fails
            raise AssertionError(f"Failed to log in. Status code: {response.status_code}")

    def test_course_view_url_is_resolved(self):
        headers = {'HTTP_AUTHORIZATION': f'Bearer {self.token}'}
        print("headers", headers)                       
        response = self.client.get('/course', headers=headers)
        print("response headers", response.headers)
        self.assertEqual(response.status_code, 200)

why response.status_code is 403, I printed the headers and got this:

headers {'HTTP_AUTHORIZATION': 'Bearer '}

but the response doen't show the header. How solve it?

0

There are 0 answers