How to test custom Django forms to clean / save?

In most cases, I have to change / expand the default form save / clean methods. However, I'm not sure how to test custom save / clean methods.

In most cases, my tests are similar to:

response = self.client.post(reverse('example:view_name'), kwargs={'example, self.example'})
self.assertEqual(200, response.status_code)
self.assertTemplateUsed('example.html', response)

Using self.client.post from the Django TestCase class to capture the response is not enough and certainly does not cover / does not perform selective saving and cleaning.

What is your practice of testing forms? In my opinion, what I did above is wrong, since it is more an integration test that goes through a presentation in order to go to form.

+4
source share
1 answer

​​ is_valid method (clean is_valid); . save.

:

from django.contrib.auth.forms import (UserCreationForm, ...)

...

class UserCreationFormTest(TestCase):

    def test_user_already_exists(self):
        data = {
            'username': 'testclient',
            'password1': 'test123',
            'password2': 'test123',
        }
        form = UserCreationForm(data)
        self.assertFalse(form.is_valid())
        self.assertEqual(
            form["username"].errors,
            [force_text(User._meta.get_field('username').error_messages['unique'])])

( django - django/contrib/auth/tests/test_forms.py).


BTW, assertTemplateUsed response, template_name, ..., template_name, response, .....

:

self.assertTemplateUsed(response, 'example.html')
+3

All Articles