How should I write tests for Forms in Django?

Question:

I’d like to simulate requests to my views in Django when I’m writing tests. This is mainly to test the forms. Here’s a snippet of a simple test request:

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

The page always returns a response of 200 whether there’s an form error or not. How can I check that my Form failed and that the particular field (soemthing) had an error?

Asked By: Mridang Agarwalla

||

Answers:

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.

Answered By: John Mee

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 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
Answered By: Torsten Engelbrecht

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.')

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.

Answered By: Shane
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.