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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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.
回答2:
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.
回答3:
In django 1.6, you could use(not recommended):
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, following is more powerful and concise and no 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)