我正在编写一个简单的单元测试方法,用于测试 View 在收到 POST 后是否正在重定向。我可以测试预期的 URL 是否与响应对象匹配,但与内容不匹配。
目前的伪劣代码:
def test_example_view_redirects_to_home_after_post(self):
client = Client()
response = client.post('/example/')
# Test location
self.assertEqual(response.get('location'), "http://testserver/")
# Test page content
expected_template = render_to_string('home.html')
self.assertEqual(response.content, expected_template)
测试失败:
AssertionError: b'' != '<html> etc etc...
现阶段的 View 代码可以非常简单:
def example(request):
if request.method == "POST":
return HttpResponseRedirect('/')
else:
return render(request, 'example.html')
我是 TDD 的新手,只是想知道为什么它没有像我预期的那样工作。
谢谢。
最佳答案
您可以在
client.post
中使用follow=True
,它将在重定向到下一页后模拟浏览器。 See here in the docs .这将允许您使用assertContains
测试第二页的内容。您可以使用
assertRedirects
来测试重定向是否正确发生。检查一下 here in the docs .
关于python - 重定向后测试页面内容不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31596837/