我正在为登录表单编写 Django 单元测试。下面是我的示例代码。
from unittest import TestCase
from django.contrib.auth.models import User
class TestSuite(TestCase):
def setUp(self):
self.credentials = {
'username': 'testuser',
'password': 'secret'}
User.objects.create_user(**self.credentials)
def test_login(self):
# send login data
response = self.client.post('/accounts/login', self.credentials, follow=True)
# should be logged in now
self.assertTrue(response.context['user'].is_active)
但是当我从控制台执行时,它会抛出以下错误。
追踪
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_login (accounts.tests.test_form.TestSuite)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:Djangowebapplicationaccountsteststest_form.py", line 15, in test_login
response = self.client.post('/accounts/login', self.credentials, follow=True)
AttributeError: 'TestSuite' object has no attribute 'client'
----------------------------------------------------------------------
Ran 1 test in 0.502s
问题是pythonunittest
模块没有client
;您应该使用django.test
.
只需将第一行更改为:
from django.test import TestCase
阅读有关可供使用的不同测试类的更多信息。
你需要 django.test TestCase,而不是 unittest。