Django: How to test for 'HttpResponsePermanentRedirect'

django, http, python

Solution

from django.http import HttpResponsePermanentRedirect
from django.test.client import Client

class MyTestClass(unittest.TestCase):

    def test_my_method(self):

        client = Client()
        response = client.post('/some_url/')

        self.assertEqual(response.status_code, 301)
        self.assertTrue(isinstance(response, HttpResponsePermanentRedirect))
        self.assertEqual(response.META['HTTP_LOCATION'], '/url_we_expect_to_be_redirected_to/')

There are other attributes of the response that might be interesting to test. If you are unsure what is on the object then you can always do a

print dir(response)

EDIT FOR CURRENT VERSIONS OF DJANGO

It's a bit simpler now, just do:

    self.assertEqual(response.get('location'), '/url/we/expect')

I would also suggest using reverse to look up the url you expect from a name, if it is a url in your app anyway.

Problem

I'm writing some tests for my django app.In my view,it redirects to some other url using 'HttpResponseRedirect'.So how can I test that?

Original source