Raj*_*ena 6 python django http
我正在为我的django应用程序编写一些测试.在我看来,它使用'HttpResponseRedirect'重定向到其他网址.所以我该如何测试?
Ala*_*air 18
Django TestCase类有一个assertRedirects可以使用的方法.
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)
Run Code Online (Sandbox Code Playgroud)
状态代码301检查它是永久重定向.
ayc*_*dee 15
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/')
Run Code Online (Sandbox Code Playgroud)
测试中还有其他可能有趣的属性.如果您不确定对象上的内容,那么您可以随时进行操作
print dir(response)
Run Code Online (Sandbox Code Playgroud)
编辑DJANGO的当前版本
它现在有点简单,只需:
self.assertEqual(response.get('location'), '/url/we/expect')
Run Code Online (Sandbox Code Playgroud)
我还建议使用反向查找您希望从名称中获取的网址,如果它仍然是您应用中的网址.
| 归档时间: |
|
| 查看次数: |
6896 次 |
| 最近记录: |