Djangonose测试用例在从管理命令运行时给出断言错误

2024-03-28 14:34:59 发布

您现在位置:Python中文网/ 问答频道 /正文

在测试.py在

# write code to test the views.
from django.test import Client

# import nose for tests.
import nose.tools as noz

class TestSettings(object):
    """ test the nose test related setup """

    def setup(self):
        self.client = Client()

    def testTestUser(self):
        """ Tests if the django user 'test' is setup properly."""
        # login the test user
        response = self.client.login(username=u'test', password=u'test')    
        noz.assert_equal(response, True)

从管理命令运行此代码时,将给出以下输出:

^{pr2}$

现在,当运行django shell时,相同的命令将给出以下命令:

    $ ./manage.py shell
    Python 2.6.6 (r266:84292, Sep 11 2012, 08:28:27) 
    [GCC 4.4.6 20120305 (Red Hat 4.4.6-4)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    (InteractiveConsole)
    >>> from django.test import Client
    >>> 
    >>> import nose.tools as noz
    >>> 
    >>> client = Client()
    >>> response = client.login(username=u'test', password=u'test')
    >>> noz.assert_equal(response, True)
    >>> 
    >>> 
    >>> response
    True
    >>> 

对于当前场景,用户“test”在django中处于活动状态。在

为什么我在运行管理命令时得到这个错误断言?在


Tags: thedjangopytestimport命令selfclient
2条回答

您是否正在为您的测试创建一个用户名为test和密码为test的用户?或者装载固定装置?我打赌不会。在

当您使用shell时,您是针对设置.py. 当您在测试中时,您正在使用测试数据库,该数据库在每个测试开始时是空的,因此没有用户。在

setUp中,您可以创建一个用户

from django.contrib.auth.models import User
User.objects.create('test', 'test@test.com', 'test')

正如@Kevin London指出的那样

您的setup命令应该是

setUp,但我不认为这与它有多大关系,因为每个TestCase在默认情况下都有一个client。在

看起来它没有继承基测试类,所以它不会在测试之前调用setup方法。我建议继承Django的TestCase类,如the Django documentation on testing。在这种情况下,它看起来像这样:

# write code to test the views.
from django.test import Client
import unittest

# import nose for tests.
import nose.tools as noz

class TestSettings(unittest.TestCase):
    """ test the nose test related setup """

    def setUp(self):  # Note that the unittest requires this to be setUp and not setup
        self.client = Client()

    def testTestUser(self):
        """ Tests if the django user 'test' is setup properly."""
        # login the test user
        response = self.client.login(username=u'test', password=u'test')    
        noz.assert_equal(response, True)

相关问题 更多 >