python - 重定向后测试页面内容不起作用

标签 python django testing

我正在编写一个简单的单元测试方法,用于测试 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 的新手,只是想知道为什么它没有像我预期的那样工作。

谢谢。

最佳答案

  1. 您可以在 client.post 中使用 follow=True,它将在重定向到下一页后模拟浏览器。 See here in the docs .这将允许您使用 assertContains 测试第二页的内容。

  2. 您可以使用 assertRedirects 来测试重定向是否正确发生。检查一下 here in the docs .

关于python - 重定向后测试页面内容不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31596837/

相关文章:

python - 从小长度序列中查找序列

python - 使用 Anaconda (Python) 在 Windows 上安装 Pyomo

Django 1.7 与 Django1.6 与 Django 1.5

javascript - `$getjson` 从 Django 到 javascript 不起作用

java - JBehave 和 Java 可变参数 - 如何将参数传递给可变参数方法?

javascript - 有没有办法通过 cypress 从目标网站访问全局变量?

python - 关键字不能是表达式吗?

python - 如何从包含日期和列表中其他字符串的字符串列表中解析月份?

python - django zip 不等列表

java - 如何从 JMockit 模拟静态方法