我应该如何在Django中为Forms编写测试?

时间:2011-09-05 05:45:08

标签: python django django-testing

我想在编写测试时模拟Django中我的观点请求。这主要是为了测试表格。这是一个简单测试请求的片段:

from django.tests import TestCase

class MyTests(TestCase):
    def test_forms(self):
        response = self.client.post("/my/form/", {'something':'something'})
        self.assertEqual(response.status_code, 200) # we get our page back with an error

页面始终返回200的响应,无论是否存在表单错误。如何检查我的表单失败以及特定字段(soemthing)是否有错误?

3 个答案:

答案 0 :(得分:219)

我认为如果您只想测试表单,那么您应该只测试表单而不是表单呈现的视图。获得想法的例子:

from django.test import TestCase
from myapp.forms import MyForm

class MyTests(TestCase):
    def test_forms(self):
        form_data = {'something': 'something'}
        form = MyForm(data=form_data)
        self.assertTrue(form.is_valid())
        ... # other tests relating forms, for example checking the form data

答案 1 :(得分:72)

https://docs.djangoproject.com/en/stable/topics/testing/tools/#django.test.SimpleTestCase.assertFormError

from django.tests import TestCase

class MyTests(TestCase):
    def test_forms(self):
        response = self.client.post("/my/form/", {'something':'something'})
        self.assertFormError(response, 'form', 'something', 'This field is required.')

其中“form”是表单的上下文变量名称,“something”是字段名称,“This field is required”。是预期验证错误的确切文本。

答案 2 :(得分:11)

最初的2011年答案是

self.assertContains(response, "Invalid message here", 1, 200)

但我现在看到(2018)there is a whole crowd of applicable asserts available

  • assertRaisesMessage
  • assertFieldOutput
  • assertFormError
  • assertFormsetError

选择。