[Fixed]-Django: Testing redirections when the target URL is also a redirection

28👍

TestCase.assertRedirects(response, expected_url, status_code=302,
target_status_code=200, msg_prefix=”)

Asserts that the response
return a status_code redirect status, it redirected to expected_url
(including any GET data), and 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.

Source: Django docs

There is no harm in double redirection (aside from the extra HTTP requests). Bearing that in mind, Django’s asserting also tests the redirected-to URL if it is a local URL. The default response code that it expects is 200, but as you have a double redirect, being the 301, this fails. So in order to make the test case succeed, is to assert that the redirect also redirects:

self.assertRedirects(response, '/home', status_code=301, target_status_code=301)
👤Bouke

3👍

By default Django’s assertRedirects fetches the status code of the page and tests that it’s OK. You can disable this by setting fetch_redirect_response=False:

self.assertRedirects(response, reverse('app:login'), fetch_redirect_response=False)

Leave a comment