testingdjango-rest-frameworkjwt

Authenticating with JWT on DRF tests


I've been struggling to find proper information on how to authorize DRF test client via JWT, so I can make tests like.

class TestUserAPI(APITestCase):

    @classmethod
    def setUpTestData(cls):
        users = UserFactory.create_batch(10)
        cls.users_content = json.dumps(
            [{'email': user.email} for user in users]
        )

    def test_GET_users_list(self):
        response = self.client.get('users:user_list_create')
        data = json.loads(response.content)
        assert self.users_content in data

Btw, I'm using jazzband's Simple JWT.

A little help would be appreciated and sorry if you find any grammar errors, english is not my native language.


Solution

  • Usually, I do something like this:

        from rest_framework_simplejwt.tokens import AccessToken
    
        class TestUserAPI(APITestCase):
        
            @classmethod
            def setUpTestData(cls):
                users = UserFactory.create_batch(10)
                cls.users_content = json.dumps(
                    [{'email': user.email} for user in users]
                )
                # create token for an existing user to use later
                self.token = str(AccessToken.for_user(users[0]))
        
            def test_GET_users_list(self):
                self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.token)
                response = self.client.get('users:user_list_create')
                data = json.loads(response.content)
                assert self.users_content in data
    

    NOTE:

    you can use response.json() instead of json.loads(response.content)