Login or Sign up

Django test client: state, session, login, nice

Posted by: skyl on Jan. 12, 2010

Client objects are stateful - they will retain cookie (and thus session) details for the lifetime of the Client instance. So, if you have a view that returns 403 if the owner of the object is not the request.user, you might have a test case that looks something like:

>>> from django.test.client import Client
>>> from django.core.urlresolvers import reverse
>>> c = Client()
>>> edit_url = '%s?next=%s' % (reverse('edit_applicant'), reverse('add_company'))
>>> response = c.get(edit_url)
>>> response.status_code
403
>>> c.login(username='23@23.com', password="1")
True
>>> response = c.get(edit_url)
>>> response.status_code
200

After the correct user is logged in, she is able to get the edit_url.

The docs and a robust example of how to use it with unittest

Comments on This Post:

Please Login (or Sign Up) to leave a comment