我该如何为Django中的表单编写测试?

120 投票
3 回答
70849 浏览
提问于 2025-04-17 01:27

我想在写测试的时候模拟对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 个回答

19

最初在2011年的回答是

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

但我现在看到(2018年)有很多适用的断言可以使用

  • assertRaisesMessage
  • assertFieldOutput
  • assertFormError
  • assertFormsetError

你可以随便选择。

87

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.”则是你期望的验证错误的确切文本。

275

我觉得如果你只是想测试表单的话,那就直接测试表单本身,不用去测试表单显示的那个页面。下面有个例子可以让你更明白:

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

撰写回答