Python Django:如何测试';HttpResponsePermanentRedirect';
我正在为我的django应用程序编写一些测试。在我看来,它使用“HttpResponseRedirect”重定向到其他url。那么我如何测试它呢Python Django:如何测试';HttpResponsePermanentRedirect';,python,django,http,Python,Django,Http,我正在为我的django应用程序编写一些测试。在我看来,它使用“HttpResponseRedirect”重定向到其他url。那么我如何测试它呢 from django.http import HttpResponsePermanentRedirect from django.test.client import Client class MyTestClass(unittest.TestCase): def test_my_method(self): client
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/')
响应的其他属性可能值得测试。如果你不确定物体上有什么东西,那么你可以随时进行检查
print dir(response)
编辑当前版本的DJANGO
现在有点简单了,只需执行以下操作:
self.assertEqual(response.get('location'), '/url/we/expect')
我还建议使用reverse来查找您希望从名称中找到的url,如果它是您应用程序中的url Django
TestCase
类有一个可以使用的方法
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检查它是否为永久重定向。在django 1.6中,您可以使用(不推荐使用): 相反,下面的内容更强大、更简洁,没有
http://testserver/
需要
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)
你能详细说明一下吗?你到底是什么意思?Django 1.4中的最后一行抛出了一个错误:
AttributeError:'HttpResponseRedirect'对象没有属性“META”
Yup,似乎在1.4中发生了更改。相反,您会将response.get('location')
与所需的重定向url进行比较。您是否尝试过执行raiseexception(dir(response))
以了解我们的可用功能?这是否适用于使用Django@JonasG.Drange的任何人?您正在链接到应用程序Django webtest版本1.5.2的错误报告,不是Django本身。在我最初的回答中,我确实建议您可以在get请求中使用follow=False
,以阻止客户端遵循重定向。这是不正确的,所以我删除了它。如文档所述,assertRedirect
方法始终检查状态页面。有一个票证允许assertRedirects
不加载目标页面。这更有意义。谢谢
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)