简体   繁体   中英

Unit testing Django Rest API with JWT Authorization fails

I have the following problem: whenever I run my unit tests to test my Django REST API, I get an 401 Unauthorized, even though I paste in the correct Token for the User object I created during the test. However, I expect the response to be a 200..

Here's the code:

class TestWebApi(APITestCase):

  def setUp(self):
      self.factory = APIRequestFactory()
      self.client = Client()
      self.user = User.objects.create_user('testuser', None, '12345a')
      Employee.objects.create(name='Test', surname='Employee1', role="frontend", account=User.objects.get(username='testuser'))

  def test_api_employee(self):
      user = self.user
      token = json.loads(self.client.post('/api/get_jwt_token/', data={'username': 'testuser', 'password': '12345a'}).content)['token']
      response = self.client.get('/api/v2/employees/', HTTP_Authorization="JWT {0}".format(token))
      employees = Employee.objects.all()
      serializer = EmployeeSerializer(employees, many=True)
      self.assertEqual(response.status_code, status.HTTP_200_OK)
      json_response = response.json()
      self.assertEqual(json_response, serializer.data)

Thanks in advance!

I have also struggled quite a lot with this. I found something like this works for me:

from mymodels.models import User
from rest_framework_simplejwt.tokens import RefreshToken

class Test(TestCase):

    def test_1(self):
        user = User.objects.get(username="test-user")
        refresh = RefreshToken.for_user(user)
        access_token = str(refresh.access_token)
        response = self.client.get('/url-to-test/', 
            HTTP_AUTHORIZATION="Bearer " + access_token)
        ...

So, basically, your HTTP_AUTHORIZATION header should use "Bearer".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM