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()
?
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.
To create such an error, you can raise a ValidationError from the clean() method. For example: from django import forms from django. core.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With