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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With