我如何在Django中测试具有表单的视图?
问题描述:
我正在Django中创建一个应用程序,我有一个视图,它接收来自html代码的表单,并在数据库中搜索模型中是否存在表单中指定值的任何模型实例。我如何在Django中测试具有表单的视图?
问题是,我是新的Django,我真的不知道如何测试视图的功能(即:如果视图的响应有一个值的列表导致搜索窗体的值在请求中)。
在这里,我把我的观点的示例代码:
@login_required
def view(request):
# If it's a HTTP POST, we're interested in processing form data.
if request.method == 'POST':
form = Form(data=request.POST)
# If the form is valid
if (form.is_valid()):
resulting_of_search = ModelA.objects.filter(Q(att1=request.POST[attr1]) & ...)
else:
resulting_of_search = []
# Not a HTTP POST, so we render our form using two ModelForm instances.
# These forms will be blank, ready for user input.
else:
form = Form()
resulting_of_search= []
# Render the template depending on the context.
return render(request,
'url/url.html',
{'resulting':resulting_of_search})
答
您是否尝试过Django Testing Tutorial?从本质上讲,你只需要发送一篇文章到你的视图,并测试响应返回你所期望的。
例如..
def test_index_view_with_no_questions(self):
"""
If no questions exist, an appropriate message should be displayed.
"""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['latest_question_list'], [])
从文档两者。你会想改变最后一行,以便声明'结果'在上下文中。或者检查它是否包含您正在查找的结果的特定列表。这样的..
def test_results(self):
response = self.client.get(reverse('ensaioak_bilatu'))
self.assertQuerySetEqual(response.context['resulting'], [...whatever you expect resulting to contain...])
答
从阅读你的答案,我想你是不是问单元测试但只是检查你的观点是否实际工作。首先,您可以使用以下链接在Django网站上提供的代码段:https://docs.djangoproject.com/en/1.8/topics/forms/#the-view。
我做了,但我的问题是:如果我有一个“返回呈现”在视图的结尾如何测试视图的结果? – jartymcfly
我将编辑我的答案以添加示例。 – Alistair
什么意思是“reverse('polls:index')”sentence? – jartymcfly