2013-04-20 154 views
0

我試圖塞汀了鼻子的測試用戶,但它亙古不變的在全球範圍內的工作鼻子Django的用戶設置測試

定義:測試類的內部

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()分支視圖。

+0

計算出來: – 2013-04-20 05:26:29

回答

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)