【发布时间】:2022-01-24 01:17:30
【问题描述】:
我有一个自定义的抽象基本用户和带有 knox 视图的基本登录,我对注册和登录过程进行了一些简单的测试,但是所有的测试用例都未能断言错误:401!=200 并且当我使用 pdb.set_trace 到知道发送的数据它总是有那个错误
(Pdb) res
<Response status_code=401, "application/json">
(Pdb) res.data
{'detail': ErrorDetail(string='Authentication credentials were not provided.', code='not_authenticated')}
这是测试设置
from rest_framework.test import APITestCase
from django.urls import reverse
class TestSetUp(APITestCase):
def setUp(self):
self.register_url = reverse('knox_register')
self.login_url = reverse('knox_login')
self.correct_data = {
'email':"user@gmail.com",
'password': "Abc1234#",
}
self.wrong_email_format = {
'email': "user@gmail",
'password': "Abc1234#",
}
self.missing_data = {
'email':"user@gmail.com",
'password':"",
}
self.wrong_password_format = {
'email': "user@gmail.com",
'password': "123",
}
return super().setUp()
def tearDown(self):
return super().tearDown()
和 test_view
from .test_setup import TestSetUp
import pdb
class TestViews(TestSetUp):
#register with no data
def test_user_cannot_register_with_no_data(self):
res = self.client.post(self.register_url)
self.assertEqual(res.status_code,400)
#register with correct data
def test_user_register(self):
self.client.force_authenticate(None)
res = self.client.post(
self.register_url, self.correct_data, format="json")
#pdb.set_trace()
self.assertEqual(res.status_code,200)
#register with wrong email format
def test_register_with_wrong_email_format(self):
res = self.client.post(
self.register_url, self.wrong_email_format)
self.assertEqual(res.status_code, 400)
# register with wrong password format
def test_register_with_wrong_password_format(self):
res = self.client.post(
self.register_url, self.wrong_password_format)
self.assertEqual(res.status_code, 400)
#register with missing_data
def test_register_with_missing_data(self):
res = self.client.post(
self.register_url, self.missing_data)
self.assertEqual(res.status_code, 400)
#login with correct Credentials
def test_user_login(self):
self.client.post(
self.register_url, self.correct_data,format="json")
res = self.client.post(
self.login_url,self.correct_data, format="json")
#pdb.set_trace()
self.assertEqual(res.status_code,200)
# login with no Credentials
def test_login(self):
res = self.client.post(
self.login_url, self.correct_data, format="json")
# pdb.set_trace()
self.assertEqual(res.status_code, 400)
#login with no data
def test_user_cannot_login_with_no_data(self):
res = self.client.post(self.login_url)
self.assertEqual(res.status_code,400)
【问题讨论】:
标签: django django-views django-testing django-tests django-custom-user