Django test form errors and validation results in Unit Testing


Testing forms in Unit testing Django is necessary and important. Instead of using “self.client” for opening URL, we can post data into form in the webpage. We want to testing different input into forms and seeing how forms handle these input.

Here is an example how to testing form in Django unit-testing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from django.test import TestCase
from django.test.client import Client
from django.core.urlresolvers import reverse

class FormTestingExample(TestCase):
    """Testing Django Form"""
    def setUp(self):
        self.client = Client()

    def testing_some_form(self):
        data = {"key": "value"}
        response = self.client.post(reverse("app:namespace"), data, follow=True)
        self.assertEqual(response.status_code, 200)

        print response.context[‘your-form’].errors

Yes, all forms results can be accessed in context inside response.
Your form value and errors will be stored inside context.

Here is some example to test form errors and validation:

1
2
3
# Must show error because data invalid
msg = ("Please insert name")
self.assertEqual(response.context[‘my_form’].errors[‘name’][0], msg)

Now you can test all your forms 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.