【问题标题】:How to write testcase for django apis which has jwt?如何为具有 jwt 的 django api 编写测试用例?
【发布时间】:2023-01-10 11:59:57
【问题描述】:

我有实现了 jwt 的 python django 项目。以及用于验证电子邮件的 otp 系统和哈希实现,因此任何人都可以为其编写测试用例。 我不想测试每个模型和序列化程序。只是想测试 api 端点是否有效 如果有人有任何类型的例子可以分享

【问题讨论】:

    标签: python django unit-testing


    【解决方案1】:

    为具有 JWT 认证的 Django API 编写测试用例,您可以按照以下步骤操作:

    首先,您需要创建一个测试客户端来模拟对您的 API 端点的 HTTP 请求。您可以通过创建 django.test.TestCase 的子类并使用 TestCase 类的 client 属性来做到这一点。

    接下来,您需要为每个 API 端点创建一个测试用例。在每个测试用例中,您将需要使用测试客户端模拟对端点的 HTTP 请求,并断言响应具有预期的状态代码和内容。

    对于需要 JWT 身份验证的端点,您需要在请求标头中包含有效的 JWT 令牌。您可以使用 pyjwt 库中的 jwt.encode() 函数生成 JWT 令牌,并将其包含在请求标头中,如下所示:

    headers = {'Authorization': 'Bearer ' + jwt_token}
    response = self.client.get('/api/endpoint', headers=headers)
    

    您还可以在请求正文或查询参数中包含任何其他必要数据,具体取决于端点的要求。 这是您的测试用例的外观:

    from django.test import TestCase
    import jwt
    class APITestCase(TestCase):
    def test_endpoint(self):
        # Generate a JWT token
        payload = {'some': 'payload'}
        jwt_token = jwt.encode(payload, 'secret', algorithm='HS256').decode('utf-8')
    
        # Set the Authorization header with the JWT token
        headers = {'Authorization': 'Bearer ' + jwt_token}
    
        # Send a request to the endpoint
        response = self.client.get('/api/endpoint', headers=headers)
    
        # Assert that the response has the expected status code and content
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {'success': True})
    

    【讨论】:

      猜你喜欢
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      • 2012-03-23
      • 2019-05-26
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多