在浏览器中,表单和视图的所有工作都很好,并且可以添加测试以确保视图继续工作。
问题是测试总是返回400
表格:
class DogForm(forms.Form):
dog_name = forms.CharField(max_length=40)
dog_type = forms.CharField(max_length=40)
视图:
class DogRequestView(LoginRequiredMixin, TemplateView):
template_name='dog_request.html'
def get(self, request):
form = DogForm()
return render(request, self.template_name, {'form': form})
def post(self, request):
form = DogForm(request.POST)
process_status = 'initial'
if form.is_valid():
stuff()
return render(request, self.template_name, {'form': form, 'status': process_status})
测试:
class LabTests(TestCase):
def test_DogForm(self):
form_data = {
'dog_name': 'Test name',
'dog_type': 'k9'
}
self.client.login(username="test@acme.com", password="test")
response = self.client.post("/kenel/dog-catalog/dog-request", form_data)
self.assertEqual(response.status_code, 200)
url:
url(r'^kenel/dog-catalog/dog-request$', dog_catalog.DogRequestView.as_view()),
测试输出:
----------------------------------------------------------------------
Traceback (most recent call last):
File "/workspace/NSPF-171805/nsp-dev-portal/cloudlab/tests/test_forms.py", line 32, in test_DogForm
self.assertEqual(response.status_code, 200)
AssertionError: 400 != 200
----------------------------------------------------------------------
答案 0 :(得分:0)
您忘记在帖子中添加“数据”。
response = self.client.post("/kenel/dog-catalog/dog-request", data=form_data)