django - Django 中单元测试的 auth_token

标签 django django-rest-framework django-testing django-rest-auth

我一直在尝试使用以下代码测试我的登录系统

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>

关于django - Django 中单元测试的 auth_token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70852736/

相关文章:

django - 如何在 matplotlib 中向图形添加绘图?

ajax - 如何将Django错误状态传递给Ajax

python - Django-值错误: "strftime format ends with raw %" when DATE_INPUT_FORMATS and TIME_INPUT_FORMATS are set?

django - Django 中的并发请求

DjangoModelFactory JsonField 返回 Unicode 数据而不是字典数据

python - Django 断言响应包含可能的字符串列表之一

python - django admin 内联编辑外键

Django key 错误

json - 如何序列化django rest中的关系?

django - 如何测试登录过程?