我无法在IRC上解决这个问题,希望能在这里找到一些指导。我做了以下测试:
def test_validation_errors_return_hops_list_page(self):
response = self.client.post(
'/beerdb/add/hops',
data={
'name': '',
'min_alpha_acid': '',
'max_alpha_acid': '',
'country': '',
'comments': ''
}, follow=True
)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'homebrewdatabase/addhops.html')
name_validation_error = escape("A hop name is required")
min_alpha_acid_error = escape("You must enter a min alpha acid")
max_alpha_acid_error = escape("You must enter a max alpha acid")
country_error = escape("You must enter a country")
comments_error = escape("You must enter a comment")
self.assertContains(response, name_validation_error)
self.assertContains(response, min_alpha_acid_error)
self.assertContains(response, max_alpha_acid_error)
self.assertContains(response,country_error)
self.assertContains(response, comments_error)
它在self.assertContains(response, name_validation_error)
上失败。追溯到这里:
Failure
Traceback (most recent call last):
File "/Users/USER/workspace/PycharmProjects/hashtagbrews/homebrewdatabase/tests/test_views.py", line 189, in test_validation_errors_return_hops_list_page
self.assertContains(response, name_validation_error)
File "/Users/USER/workspace/Envs/hashtagbrews/lib/python3.4/site-packages/django/test/testcases.py", line 398, in assertContains
msg_prefix + "Couldn't find %s in response" % text_repr)
AssertionError: False is not true : Couldn't find 'A hop name is required' in response
我的观点视图.py当窗体无效时,呈现带有错误的hops.html
模板:
def addhops(request):
add_form = HopForm(request.POST or None)
if request.method == 'POST':
if add_form.is_valid():
Hop.objects.create(name=request.POST['name'],
min_alpha_acid=request.POST['min_alpha_acid'],
max_alpha_acid=request.POST['max_alpha_acid'],
country=request.POST['country'],
comments=request.POST['comments']
)
return redirect('hops_list')
else:
hops_list = Hop.objects.all()
return render(request, 'homebrewdatabase/hops.html', {'hops': hops_list, 'form': add_form})
return render(request, 'homebrewdatabase/addhops.html', {'form': add_form})
当我手动点击这个站点时,我得到的正是我想要的:一个从modal重定向到main hops页面列表,顶部有一个Bootstrap警报框,其中包含一个无序的add错误列表_跳跃。错误. 我已经打印出post请求(self.client.post('url', data={invalid data})
)之后的响应,它只包含模态形式。完成这个测试的正确方法是什么?或者我需要重写我的表单验证吗?你知道吗
这里的问题,如注释中所示,是Django测试客户机在执行post请求之后在
addhops
view方法上运行GET请求。根据视图逻辑,如果方法不是POST,则返回bootstrap模式,该模式不包含设计的表单错误。所以当使用测试客户机时,测试将失败。但是,测试可以改为使用HttpRequest
对象在POST请求中发送无效数据,然后断言内容包含表单错误。所以我重写了测试,使用下面的,通过了我不能断言使用了哪个模板,因为
assertTemplateUsed
是属于测试客户机的方法,但是使用selenium进行的功能测试应该足以检查所需元素是否在呈现视图中。这一点将来可能要改变,但就目前而言,这已经足够了。你知道吗相关问题 更多 >
编程相关推荐