【发布时间】:2018-07-13 21:22:06
【问题描述】:
这里的问题。我无法使用 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"}'
【问题讨论】:
标签: python django unit-testing django-rest-framework jwt