在 DRF 测试中使用 JWT 进行身份验证

时间:2021-04-25 14:04:55

标签: testing django-rest-framework jwt

我一直在努力寻找有关如何通过 JWT 授权 DRF 测试客户端的正确信息,因此我可以进行类似的测试。

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

顺便说一句,我使用的是 jazzband 的 Simple JWT。

如果您发现任何语法错误,我们将不胜感激并抱歉,英语不是我的母语。

1 个答案:

答案 0 :(得分:0)

通常,我会这样做:

    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
            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

注意

您可以使用 response.json() 代替 json.loads(response.content)