【问题标题】:Django user setup for nose tests鼻子测试的 Django 用户设置
【发布时间】:2013-04-20 05:04:52
【问题描述】:

我尝试设置一个用户进行鼻子测试,但它不起作用

在定义的全局范围内:

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

在定义的测试类中:

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

用户已保存,我已使用 noz.set_trace() 进行了测试 但是当一个测试函数调用同一个用户的登录时,就会引发断言错误:

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_authenicated() 分支的视图。

【问题讨论】:

    标签: python django unit-testing testing nose


    【解决方案1】:

    从: 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)
    

    【讨论】:

      猜你喜欢
      • 2018-09-02
      • 2014-01-19
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      • 2011-06-03
      相关资源
      最近更新 更多