测试django表单引发ValidationError

时间:2015-05-17 12:42:53

标签: python django unit-testing

我正在测试我的表单会引发验证错误。

我的测试如下:

    def test_register_password_strength(self):
        form_params = {'first_name': 'John',
                       'last_name': 'Doe',
                       'email': 'john@doe.com',
                       '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)

表单以下列方式引发ValidationError

    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())正确断言为false,但当我尝试拨打form.clean_password()时,我收到以下错误:TypeError: object of type 'NoneType' has no len()

self.cleaned_data被调用后,

password没有名为form.is_valid()的元素。

除了调用ValidationErrors之外,还有其他方法可以测试is_valid()吗?

1 个答案:

答案 0 :(得分:6)

而不是使用:

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

考虑使用Form.has_error('password', code='pw_too_short')

此处有更多信息:https://docs.djangoproject.com/en/1.8/ref/forms/api/#django.forms.Form.has_error