Django用户鼻子测试设置

2024-06-25 22:39:37 发布

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

我试着设置一个用户进行鼻子测试,但没用

在定义的全局范围内:

from django.contrib.auth.models import User
import nose.tools as noz

在定义的测试类内:

^{pr2}$

用户被保存,我用没有设置跟踪() 但当测试函数调用同一用户的登录名时,会引发断言错误:

nosetests --verbosity 1
Creating test database for alias 'default'...
> <app-path>/tests.py(59)testTestUser()
-> response = self.client.login(username=u'test', password=u'test')
(Pdb) User.objects.all()
[<User: test>]

testTestUser函数的定义如下:

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

相关测试输出为:

    noz.assert_equal(response, True)
       AssertionError: False != True

    ----------------------------------------------------------------------
    Ran 1 test in 0.011s

    FAILED (failures=1)

我的目的是测试requst.user.is_授权()分支机构。在


Tags: django用户testimportselfclienttrue定义
1条回答
网友
1楼 · 发布于 2024-06-25 22:39:37

从以下方面得出结论: http://www.pukkared.com/2011/07/simulating-user-login-in-a-django-view-unit-test/

正确的代码是:

def setUp(self):
    self.client = Client()
    user = User.objects.create_user(username="test", password="test")

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

相关问题 更多 >