AttributeError:“ TestSuite”对象没有属性“ client”

时间:2019-12-17 07:42:47

标签: python django django-unittest

我正在为“登录”表单编写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:\Django\webapplication\accounts\tests\test_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

2 个答案:

答案 0 :(得分:2)

问题在于 python unittest模块中没有client;您应该使用django.test

只需将第一行更改为:

from django.test import TestCase

详细了解different test classes available to use

答案 1 :(得分:0)

您需要django.test TestCase,而不是unittest的。