Django根据响应内容测试主页的html [英] Django testing the html of your homepage against the content of a response
问题描述
如果我有这样的测试...
If I have a test like so...
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
expected_html = render_to_string('home.html', request=request)
self.assertEqual(response.content.decode(), expected_html)
我在大括号中添加表格后,例如{{ form }}
上述测试将失败,因为.html文件将不会仅响应形式呈现表单.因此导致断言不匹配.有没有办法解决这个问题,以便我仍然可以针对响应测试我的html?
As soon as I add a form in curly braces, e.g. {{ form }}
The above test will fail as the .html file will not render the form only the response will. Thus causing the assertion to not match. Is there a way round this so that I can still test my html against the response?
推荐答案
您可以将表单实例传递给render_to_string
函数:
You can pass a form instance to the render_to_string
function:
from django.template import RequestContext
from django.template.loader import render_to_string
form = ModelForm()
context = RequestContext(request, {'form': form})
expected_html = render_to_string('home.html', context)
通常,我要做的就是将这种测试分为其他几个测试,如下所示:
Usually what I do is splitting this kind of test into several other tests, like this:
使用from django.test import TestCase
def setUp(self):
self.user = User.objects.create_user('john', 'john@doe.com', '123')
self.client.login(username='john', password='123')
self.response = self.client.get(r('home'))
首先测试使用了哪个模板:
First test which template was used:
def test_template(self):
self.assertTemplateUsed(self.response, 'home.html')
测试表单:
def test_has_form(self):
form = self.response.context['form']
self.assertIsInstance(form, CreateModelForm)
然后我测试HTML的关键部分:
And then I test the key parts of the HTML:
def test_html(self):
self.assertContains(self.response, '<form')
self.assertContains(self.response, 'type="hidden"', 1)
self.assertContains(self.response, 'type="text"', 2)
self.assertContains(self.response, 'type="radio"', 3)
self.assertContains(self.response, 'type="submit"', 1)
最后,如果渲染的模板具有csrf令牌:
Finally if the rendered template has a csrf token:
def test_csrf(self):
self.assertContains(self.response, 'csrfmiddlewaretoken')
这篇关于Django根据响应内容测试主页的html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!