Django: How to test for 'HttpResponsePermanent

2019-06-20 01:33发布

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?

3条回答
贼婆χ
2楼-- · 2019-06-20 01:56
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.

查看更多
祖国的老花朵
3楼-- · 2019-06-20 02:00

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.

查看更多
虎瘦雄心在
4楼-- · 2019-06-20 02:05

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)
查看更多
登录 后发表回答