本文介绍了Django:如何测试'HttpResponsePermanentRedirect'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为我的django应用程序编写一些测试。在我看来,它使用'HttpResponseRedirect'重定向到其他网址。所以我该如何测试?
从django.test.client导入HttpResponsePermanentRedirect
导入客户端
类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')
我还建议使用反向来查找你期望的网址名称,如果它是你的应用程序中的网址。
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?
解决方案
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.
这篇关于Django:如何测试'HttpResponsePermanentRedirect'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
11-02 18:59