Django 测试:如何从 HTTPResponseRedirect 对象获取 html 字符串

Django test: How to get the html string from a HTTPResponseRedirect object

我有一个测试,其中视图使用 HttpRepsonseRedirect() 重定向。在我的测试中,我将 dict 传递给 POST 请求,该请求通过此 HttpResponseRedirect.

data = {...data...}
response = self.client.post(url, data)

如何检查响应中是否包含字符串 HTML?我做不到:

self.assertContains(response, 'my_string')

self.assertIn(response, 'my_string')

有没有办法从这个响应中访问 HTML 作为字符串?

您可以将参数 follow=True 传递给测试客户端以使其遵循重定向。然后你可以使用 assertContains 检查预期的内容。

data = {...data...}
response = self.client.post(url, data, follow=True)
self.assertContains(response, 'my_string')

Django 提供了一个 assertion functionTestCase.assertInHtml(needle, haystack),您可以使用它来断言给定的 needle(您的 HTML 字符串)在 haystack 中(响应对象中的 HTML)。请注意,HttpResponse 的 HTML 内容在响应对象的 content 属性中作为字节字符串提供,因此您需要像这样对其进行解码:

self.assertInHtml('my_string', response.content.decode())