Jul 15, 2012

Django: Unittest for HttpResponseRedirect method recipe

I like to invent bicycles in my code. They often come in handy and you basically do not rely on Django version... So upon updating your project's Django version in future times you will not have to refactor half of all the code. So...

How do you test http redirects? I usually restrict my time in thinking and write code like if redirect target is hardcoded. And it really is in most of the times. But imagine if you decide to redirect your view response in several places. Or imagine if you're not the only one who owns you'r project's code and there are many collaborators that can change things without warning... And you need to have a test for that view that will test redirects and complex code behavior.

I used to check redirects like so:
response = self.cliet.get('/myview')
self.assertEqual(response.status_code, 302)
# View redirected... All ok...
But  if you have some view that can redirect to things that you need to check. How would you test that?  E.g. your view:
import random

def myview(request):
    url_end = random.choice([1,2,3,4])
    url = '/someplace/' + str(url_end)
    return HttpResponseRedirect(url)
It can produce many urls and you basically can not predict which one it will produce this time. Maybe it's not the best example. However it's quite simple and understandable IMHO. You're view can redirect you to:
Imagine if your program results may depend on that and you must check if the page rendering is properly relayed on that URL that you're redirecting.

How would you check that without relying much into Django variables and producing hacks? Exactly! You name it... Regexp's:
class MyTestCase(TestCase)

    def setUp(self):
        # We are using only logged in client in this test
        self.client.login(username=username, password=password)

    def test_mytest(self):
        response = self.client.get(reverse('myview'))
        # Following redirect in tests
        new_url = self._retrieve_redirect_response_url(response)
        response = self.client.get(new_url)
        self.assertEqual(response.status_code, 200)
        # No errors appeared
    def _retrieve_redirect_response_url(self, response):
        My handy helper:
        parses 302 response object.
        Returns redirect url, parsed by regex.
        self.assertEqual(response.status_code, 302)
        new_url = re.search(
                            # Our REGEXP:
        return new_url
A lot of third party logic exists in this test. But it's partially a live tests snippet with names changed. So you may assume it should be like so and concentrate your thoughts on this approach in general, rather than possible inconsistencies.

Main deed does regexp: "(?P<url>https?://[^\s]+)". Other code is only possible solution to use it in a handy way...  

Anyway, now you can use this snippet in your code to check url that view redirected you to. Only concern that I have here that there are much simpler approaches. But this one is almost Django updates independent. It stringifies your response and parses for url there.

If you want to know about re.search more: http://docs.python.org/howto/regex.html
Writing tests in general: https://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs
Hope this will help someone. Comment your ideas on this! Appreciate your every thought...


  1. Thanks for the redirect test idea. The regex isn't really necessary I think, you can get the URL using:

    redirect_url = dict(response.items())['Location']

  2. For anyone coming here from searching, check out the assertRedirects() in TestCase: https://docs.djangoproject.com/en/1.6/topics/testing/tools/#django.test.SimpleTestCase.assertRedirects