【问题标题】:Authenticating with JWT on DRF tests在 DRF 测试中使用 JWT 进行身份验证
【发布时间】:2023-03-31 03:07:01
【问题描述】:

我一直在努力寻找有关如何通过 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。

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

【问题讨论】:

标签: testing django-rest-framework jwt


【解决方案1】:

通常,我会这样做:

    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)

【讨论】:

    猜你喜欢
    • 2018-07-13
    • 2016-04-07
    • 2023-03-18
    • 2016-12-16
    • 1970-01-01
    • 2023-03-27
    • 2021-05-29
    • 2017-07-30
    • 2018-06-30
    相关资源
    最近更新 更多