django - django rest frame work API Test case (Authentication needed)
问题描述
I am using (simple JWT rest framework) as a default AUTHENTICATION CLASSES Now I want to write an API test case for one of my view which needed authentication I don't know how to add "access" token and how to use this in rest framework test cases
I will be thankful if you answer to my question
解决方案
您可以使用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)
推荐阅读
- node.js - 如何获得密钥斗篷令牌?
- javascript - 在 cypress 的测试中访问网站提供的 JavaScript 变量
- arrays - Swift:根据在前端另一个创建的数组中保存的 ID 对从后端检索到的对象数组进行排序
- php - PDO 无法在 SELECT 查询中为 NULL 绑定值
- winforms - 由于分辨率差异,我如何通过 Ranorex 单击错误的项目?
- r - 将列中的分类值存储在向量 R 中
- python - 如何在 HTML 中发布查询集的第一个值?
- object - Dataweave - 在 mappedObject 中动态拆分名称字段
- java - 如何让 MacOS (Catalina) 使用自定义 Java 版本?
- python - 如何在字典的循环中获取句柄和标签?