How should I write tests for Forms in Django? How should I write tests for Forms in Django? python python

How should I write tests for Forms in Django?


I think if you just want to test the form, then you should just test the form and not the view where the form is rendered. Example to get an idea:

from django.test import TestCasefrom myapp.forms import MyFormclass 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


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

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

Where "form" is the context variable name for your form, "something" is the field name, and "This field is required." is the exact text of the expected validation error.


The original 2011 answer was

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

But I see now (2018) there is a whole crowd of applicable asserts available:

  • assertRaisesMessage
  • assertFieldOutput
  • assertFormError
  • assertFormsetError

Take your pick.