mercredi 24 décembre 2014

Testing django auth'd URLs using Factories to create users

I've been using FactoryBoy to setup objects for my tests and now would like to test @login_required URLs so I've created 3 user factories; StandardUserFactory, StaffUserFactory, SuperUserFactory which are all fairly similar to this;



class StandardUserFactory(DjangoModelFactory):
"""
Standard user factory.
"""
class Meta:
model = User
django_get_or_create = ('username', )

username = factory.Sequence(lambda n: u'stdaccount{}'.format(n))
first_name = u'Standard'
last_name = factory.Sequence(lambda n: u'Account{}'.format(n))
email = factory.lazy_attribute(
lambda u: '{}.{}@test.com'.format(u.first_name, u.last_name)
)
password = factory.PostGenerationMethodCall('set_password', 'password')
is_staff = False
is_active = True
date_joined = str_now()


Then in my test case I'm doing this to try and test that the views you are required to login for work but after the client login I still get a 302;



class TestArticlesViews(TestCase):
def setUp(self):
self.user = StandardUserFactory.create()
self.staff = StaffUserFactory.create()
self.super = SuperUserFactory.create()
self.client = Client()
self.event1 = EventFactory(date='2015-01-10')
self.event2 = EventFactory(date='2015-01-15')
self.event3 = EventFactory(date='2015-03-20')

def test_add_form(self):
# Issue a GET request.
response = self.client.get('/events/add/')

# Check that the response is 302 login require redirect.
self.assertEqual(response.status_code, 302)

login = self.client.login(
username=self.staff.username, password='password'
)
self.assertTrue(login)

# Issue a GET request.
response = self.client.get('/events/add/')

# Check that the response is 200 following login.
self.assertEqual(response.status_code, 200)


Is this way of logging in within a TestCase correct?


Aucun commentaire:

Enregistrer un commentaire