Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test django forms raised ValidationError

I'm struggeling to test my forms that raise a validation error.

My test looks like the following:

    def test_register_password_strength(self):
        form_params = {'first_name': 'John',
                       'last_name': 'Doe',
                       'email': '[email protected]',
                       'password': 'a',
                       'password_confirm': 'a',
                       'g-recaptcha-response': 'PASSED'}
        form = RegisterForm(form_params)
        self.assertFalse(form.is_valid())

        try:
            form.clean_password()
            self.fail('Validation Error should be raised')
        except ValidationError as e:
            self.assertEquals('pw_too_short', e.code)

And the form raises the ValidationError in the following way:

    password = forms.CharField(label='Password', widget=forms.PasswordInput)
    widgets = {
        'password': forms.PasswordInput(),
    }

    def clean_password(self):
        password = self.cleaned_data.get('password')

        if len(password) < 7:
            raise ValidationError('Password must be at least 7 characters long.', code='pw_too_short')

        return self.cleaned_data.get('password')

self.assertFalse(form.is_valid()) asserts correctly to false, but when I try to call form.clean_password(), I get the following error: TypeError: object of type 'NoneType' has no len().

self.cleaned_data has no element named password after form.is_valid() was called.

Is there another way of testing the ValidationErrors other than calling is_valid()?

like image 506
amuttsch Avatar asked May 17 '15 12:05

amuttsch


People also ask

How do I check if a form is valid in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

How do I increase validation error in Django?

To create such an error, you can raise a ValidationError from the clean() method. For example: from django import forms from django. core.

How do I display validation error in Django?

To display the form errors, you use form. is_valid() to make sure that it passes validation. Django says the following for custom validations: Note that any errors raised by your Form.

How do I run Testcases in Django?

Open /catalog/tests/test_models.py.TestCase , as shown: from django. test import TestCase # Create your tests here. Often you will add a test class for each model/view/form you want to test, with individual methods for testing specific functionality.


1 Answers

Instead of using :

    try:
        form.clean_password()
        self.fail('Validation Error should be raised')
    except ValidationError as e:
        self.assertEquals('pw_too_short', e.code)

Consider using Form.has_error('password', code='pw_too_short')

More info here : https://docs.djangoproject.com/en/1.8/ref/forms/api/#django.forms.Form.has_error

like image 190
Charlesthk Avatar answered Sep 20 '22 06:09

Charlesthk