auth_token 用于 Django 中的单元测试
auth_token for unittest in Django
我一直在尝试使用以下代码测试我的登录系统
from django.test import TestCase, Client
from rest_framework.test import force_authenticate
class DeckTestCase(TestCase):
@classmethod
def setUp(cls):
test_user1 = User.objects.create(first_name='tester',username='test1', password='123', email='testuser@something.com')
def test_if_logged(self):
factory = Client()
user = User.objects.get(username='teste1')
request = factory.post('/login', {'username': 'test1', 'password': '123'}, format='json')
force_authenticate(request,user=user)
print(request)
但我不断收到此响应,即 401(未授权)
<Response status_code=401, "application/json">
有人可以帮助我吗?我不知道如何用 test_if_logged
发送 auth_token
您应该使用 .create_user(…)
[Django-doc] 创建用户,这将为该用户设置 散列 密码:
@classmethod
def setUp(cls):
test_user1 = User.objects.<strong>create_user(</strong>
first_name='tester',
username='test1',
password='123',
email='testuser@something.com'
<strong>)</strong>
我一直在尝试使用以下代码测试我的登录系统
from django.test import TestCase, Client
from rest_framework.test import force_authenticate
class DeckTestCase(TestCase):
@classmethod
def setUp(cls):
test_user1 = User.objects.create(first_name='tester',username='test1', password='123', email='testuser@something.com')
def test_if_logged(self):
factory = Client()
user = User.objects.get(username='teste1')
request = factory.post('/login', {'username': 'test1', 'password': '123'}, format='json')
force_authenticate(request,user=user)
print(request)
但我不断收到此响应,即 401(未授权)
<Response status_code=401, "application/json">
有人可以帮助我吗?我不知道如何用 test_if_logged
您应该使用 .create_user(…)
[Django-doc] 创建用户,这将为该用户设置 散列 密码:
@classmethod
def setUp(cls):
test_user1 = User.objects.<strong>create_user(</strong>
first_name='tester',
username='test1',
password='123',
email='testuser@something.com'
<strong>)</strong>