Python Django认证测试

fwzugrvs  于 2023-03-16  发布在  Python
关注(0)|答案(1)|浏览(88)

我想为我的python django应用程序编写测试。对于测试,我需要获得一个API令牌,我尝试通过APIClient使用以下代码:

client = APIClient()
   responce = json.loads(client.post('/api-token-auth/',data={"username":"root", "password":"root"}).content)

但作为回报

{'non_field_errors': ['Unable to login with provided credentials.']}

通过“requests”库和Postman,一切都使用相同的数据

r7xajy2e

r7xajy2e1#

您可能还没有填充测试数据库,Django默认为模型测试创建一个新数据库。(例如:授权测试需要用户记录才能正确授权)
下面是文档中的一行相关内容,说明为什么会这样做:
需要数据库的测试(即模型测试)不会使用“真实的”(生产)数据库。将为测试创建单独的空白数据库。
运行setup函数应该可以帮助你启动你想在测试用例上做的事情:

from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from rest_framework.test import APITestCase

class AuthTestCase(APITestCase):
   def setUp(self):
      get_user_model().objects.create(username="root", "password": make_password("root"))
      return super().setUp()

   def test_login_not_authorized_succeeds(self):
       ....

有关其他信息,请参阅本文档:https://docs.djangoproject.com/en/4.1/topics/testing/overview/#writing-tests

相关问题