Deepankar Bajpeyi Deepankar Bajpeyi - 5 months ago 30
Python Question

Django : Testing if the page has redirected to the desired url

In my django app, I have an authentication system. So, If I do not log in and try to access some profile's personal info, I get redirected to a login page.

Now, I need to write a test case for this. The responses from the browsers I get is :

GET /myprofile/data/some_id/ HTTP/1.1 302 0
GET /account/login?next=/myprofile/data/some_id/ HTTP/1.1 301 0
GET /account/login?next=/myprofile/data/some_id/ HTTP/1.1 200 6533

How do I write my test ? This what I have so far:

self.client.login(user="user", password="passwd")
response = self.client.get('/myprofile/data/some_id/')
response = self.client.get('/myprofile/data/some_id/')

what could possibly come next ?


Django 1.4:

Django 1.7:

SimpleTestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, host=None, msg_prefix='', fetch_redirect_response=True)

Asserts that the response returned a status_code redirect status, redirected to expected_url (including any GET data), and that the final page was received with target_status_code.

If your request used the follow argument, the expected_url and target_status_code will be the url and status code for the final point of the redirect chain.

The host argument sets a default host if expected_url doesn’t include one (e.g. "/bar/"). If expected_url is an absolute URL that includes a host (e.g. "http://testhost/bar/"), the host parameter will be ignored. Note that the test client doesn’t support fetching external URLs, but the parameter may be useful if you are testing with a custom HTTP host (for example, initializing the test client with Client(HTTP_HOST="testhost").