【问题标题】:How should I write tests for Forms in Django?我应该如何在 Django 中为表单编写测试?
【发布时间】:2011-11-10 09:07:53
【问题描述】:

我想在编写测试时在 Django 中模拟对我的视图的请求。这主要是为了测试表格。这是一个简单测试请求的 sn-p:

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) 是否有错误?

【问题讨论】:

    标签: python django django-testing


    【解决方案1】:

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

    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。 unit 测试的想法是分别测试每个单元。
    • @Daniel 但是集成测试更有用,也更有可能发现错误。
    • @wobbily_col 发现集成测试中的实际错误也需要更多时间。在单元测试中它更明显。我认为为了获得良好的测试覆盖率,无论如何你都需要它们。
    • 这是检查特定表单错误的方式:self.assertEquals(form.errors['recipient'], [u"That recipient isn't valid"])
    • self.assertEqual(form.is_valid(), True) 可以简化为:self.assertTrue(form.is_valid())
    【解决方案2】:

    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”是字段名称,“此字段是必需的”。是预期验证错误的确切文本。

    【讨论】:

    • 这为我引发了一个 AttibuteError:AttributeError: 'SafeUnicode' object has no attribute 'errors'
    • 对于新手用户:预先创建一个用户并使用self.client.force_login(self.user)作为测试方法的第一行。
    • 我对这个 post() 有一个问题,然后我发现我必须将它作为多部分发送,如下响应 = self.client.post("/form-url/", data= { 'name': 'test123', 'category': 1, 'note': 'note123' }, content_type=django.test.client.MULTIPART_CONTENT) 如果在保存表单时遇到空实例,请检查请求从浏览器发送
    【解决方案3】:

    2011 年的原始答案是

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

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

    • assertRaisesMessage
    • assertFieldOutput
    • assertFormError
    • assertFormsetError

    任你选。

    【讨论】:

      猜你喜欢
      • 2013-08-07
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 2011-11-10
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 2010-10-05
      相关资源
      最近更新 更多