[英]Testing Django API login using credentials and djoser
I'm currently trying to test my API's endpoint using Django. 我目前正在尝试使用Django测试API的端点。 So far I've used the APITestCase, but I'm having issues when it comes to login and using my token.
到目前为止,我已经使用了APITestCase,但是登录和使用令牌时遇到了问题。
I have a Clark user with a password ('1'), I log him in, retrieve his token and add it to the header before sending my request. 我有一个使用密码('1')的Clark用户,我登录他,检索他的令牌并将其添加到标头中,然后再发送我的请求。 But I'm still getting a "Bad Credential Error".
但是我仍然收到“错误的凭据错误”。
connection_data = {'email':self.clark_user.email, 'password': '1'}
self.client.login(email=self.clark_user.email, password='1')
token = self.client.post(settings.SERVER_HOST+'/api/v1/auth/login', connection_data)
self.client.credentials(HTTP_AUTHORIZATION='Token ' + token.data['auth_token'])
response = self.client.patch(self.url_people, serializer.data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.client.logout()
My stack is the following: 我的堆栈如下:
And 和
Are the lib I use for my tests. 是我用于测试的库。
Django REST framework has APIClient
class which serves this purpose. Django REST框架具有用于实现此目的的
APIClient
类。 I think rather than getting Token
over http, it can pulled out from DB directly. 我认为与其通过HTTP获得
Token
,还可以直接从DB中撤出。 The code looks like 代码看起来像
from rest_framework.authtoken.models import Token
from rest_framework.test import APIClient
# Include an appropriate `Authorization:` header on all requests.
token = Token.objects.get(user__username=self.clark_user.username)
client = APIClient()
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
response = client.patch(self.url_people, serializer.data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
client.logout()
Documentation can be found at Testing Page . 可以在“ 测试页面”中找到文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.