[英]Authentication using Django Rest + JWT during tests
在这里提问。 我在使用DRF + JWT测试登录功能时遇到问题。 在测试环境之外一切正常,我可以使用完全相同的方法以管理员身份登录,然后重新获得令牌。
from django.test import TestCase
from django.contrib.auth.models import User
from rest_framework.test import RequestsClient
TEST_USER = {
'username': 'test1',
'email': 'test@test.com',
'password': 'qwe123qwe',
}
BASE_URL = 'http://testserver/'
API_LOGIN = 'http://testserver/' + 'api-token-auth/'
class TestAuthentication(TestCase):
def setUp(self):
User.objects.create(**TEST_USER)
self.requests = RequestsClient()
def test_user_can_login(self):
user = User.objects.first()
self.assertEqual(User.objects.count(), 1)
response = self.requests.post(API_LOGIN, TEST_USER)
print(response.content)
输出为:
b'{“ non_field_errors”:[“无法使用提供的凭据登录。”]}'.. --------------------------- -------------------------------------------在0.018秒内进行了2次测试
我真的很想在测试中包含登录/注销,因为它是我项目的基础。 如果我可以提供更多帮助您的信息,请发表评论,我将一直关注该线程,直到解决为止,我没有更好的办法了:)
编辑:
问题似乎与测试无关...
>>> from django.contrib.auth.models import User
>>> User.objects.create(username="test1", password="qwe123qwe")
>>> r = post("http://127.0.0.1:8000/api-token-auth/", data={'username': 'test1', 'password': 'qwe123qwe'})
>>> r
<Response [400]>
>>> r.content
b'{"non_field_errors":["Unable to log in with provided credentials."]}'
对于超级用户(manage.py createsuperuser),它可以正常工作
>>> r = post("http://127.0.0.1:8000/api-token-auth/", data={'username': 'root', 'password': 'qwe123qwe'})
>>> r.content
b'{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6InJvb3QiLCJleHAiOjE1MTc2NzQ4OTMsImVtYWlsIjoid0B3LnBsIn0.hox4-aggdWB5xG0HNe3vUeVAiVZTPbqe373fdVaERWI"}'
我正在使用django rest令牌并将其用于测试
from rest_framework.test import APIClient
# get token
temp = APIClient()
data = {"username": "testuser", "password": "abc"}
resp = temp.post("/token-auth/", data=data, follow=True)
token = resp.data["token"]
# authenticate using the token header on other API
temp.credentials(HTTP_AUTHORIZATION='Token ' + token)
resp = temp.get("/getMyItems")
print("resp: " + str(resp))
好吧,如果有人在乎问题是我在用
User.objects.create().
创建用户的正确方法是
User.objects.create_user()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.