Django user setup for nose tests

2019-06-09 15:53发布

问题:

I tried seting up a user for nose tests but it doesnot work

in global scope defined:

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

inside a test class defined:

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

The user is saved, which i have tested with the noz.set_trace() but when a test function calls for the same user's login, assertion error is raised:

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>]

the testTestUser function is defined like:

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)

relevant test output is :

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

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

    FAILED (failures=1)

My intention is to test views that have requst.user.is_authenicated() branch.

回答1:

figured it out from : http://www.pukkared.com/2011/07/simulating-user-login-in-a-django-view-unit-test/

the proper code is:

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)