Reputation: 1244
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()
?
Upvotes: 8
Views: 3948
Reputation: 9684
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
Upvotes: 11