Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to test for 'HttpResponsePermanentRedirect'

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?

like image 854
Rajat Saxena Avatar asked Jul 27 '12 07:07

Rajat Saxena


People also ask

How do I test my Django application?

The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.

How do I run a test case in Django?

Open /catalog/tests/test_models.py.TestCase , as shown: from django. test import TestCase # Create your tests here. Often you will add a test class for each model/view/form you want to test, with individual methods for testing specific functionality.

What is Django test client?

The test client is a Python class that acts as a dummy web browser, allowing you to test your views and interact with your Django-powered application programmatically.


2 Answers

The Django TestCase class has a method assertRedirects that you can use.

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)

Status code 301 checks that it's a permanent redirect.

like image 194
Alasdair Avatar answered Sep 21 '22 01:09

Alasdair


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.

like image 34
aychedee Avatar answered Sep 20 '22 01:09

aychedee