Django: how to test "HttpResponsePermanentRedirect"

I am writing some tests for my django application. From my point of view, it redirects to another URL using "HttpResponseRedirect". So how can I check this?

+5
source share
3 answers
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 response attributes that might be interesting for testing. If you do not know what is on the object, you can always do

print dir(response)

EDIT CURRENT VERSIONS OF DJANGO

Now this is a little easier, just do:

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

I also suggest using the opposite to search for the URL that you expect on behalf of if that is the URL in your application.

+14
source

Django TestCase assertRedirects, .

from django.test import TestCase

class MyTestCase(TestCase):

    def test_my_redirect(self): 
        """Tests that /my-url/ permanently redirects to /next-url/"""
        response = self.client.get('/my-url/')
        self.assertRedirects(response, '/next-url/', status_code=301)

301 , .

+17

django 1.6 ( ):

from django.test import TestCase
from django.http import HttpResponsePermanentRedirect

class YourTest(TestCase):
    def test_my_redirect(self):
        response = self.client.get('/url-you-want-to-test/')
        self.assertEqual(response.status_code, 301)# premant 301, temporary 302
        self.assertTrue(isinstance(response, HttpResponsePermanentRedirect))
        self.assertEqual(response.get('location'), 'http://testserver/redirect-url/')

instead, the following is more powerful and concise and http://testserver/need

from django.test import TestCase

class YourTest(TestCase):
    def test1(self):
        response = self.client.get('/url-you-want-to-test/')
        self.assertRedirects(
            response, '/redirect-url/',status_code=301,target_status_code=200)
+2
source

All Articles