【发布时间】:2020-05-29 12:22:58
【问题描述】:
我使用 (simple JWT rest framework) 作为默认的 AUTHENTICATION CLASSES 现在我想为我的一个需要身份验证的视图编写一个 API 测试用例 我不知道如何添加“访问”令牌以及如何在其余框架测试用例中使用它
如果你能回答我的问题,我将不胜感激
【问题讨论】:
标签: django api testing testcase django-rest-framework-simplejwt
我使用 (simple JWT rest framework) 作为默认的 AUTHENTICATION CLASSES 现在我想为我的一个需要身份验证的视图编写一个 API 测试用例 我不知道如何添加“访问”令牌以及如何在其余框架测试用例中使用它
如果你能回答我的问题,我将不胜感激
【问题讨论】:
标签: django api testing testcase django-rest-framework-simplejwt
您可以使用rest_framework.APITestCase 来执行此操作。
self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)
在此之前,您需要一个访问令牌,您可以从您用于获取 JWT 访问令牌的 API 中获取该令牌。这是我在制作测试用例时所做的:
class BaseAPITestCase(APITestCase):
def get_token(self, email=None, password=None, access=True):
email = self.email if (email is None) else email
password = self.password if (password is None) else password
url = reverse("token_create") # path/url where of API where you get the access token
resp = self.client.post(
url, {"email": email, "password": password}, format="json"
)
self.assertEqual(resp.status_code, status.HTTP_200_OK)
self.assertTrue("access" in resp.data)
self.assertTrue("refresh" in resp.data)
token = resp.data["access"] if access else resp.data["refresh"]
return token
def api_authentication(self, token=None):
token = self.token if (token is None) else token
self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)
【讨论】: