您可以使用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)