0

我正在使用新的自定义用户模型在 django 1.5b 中对注册表单进行单元测试。我想测试我的自定义 clean_email 方法在新用户尝试使用现有电子邮件注册时引发 ValidationError,这是我写的 clean 方法:`

def clean_email(self):

    email = self.cleaned_data["email"]
    try:
        user = MyUser.objects.get(email=email)
        raise forms.ValidationError("This email address already exists.")
    except MyUser.DoesNotExist:
        return email

测试代码:

def test_clean_email(self):
    data = {'email': 'aaaa@gmail.com'}
    form = MyForm(data)
    actual   = form.errors['email']
    expected = [u'This email address already exists.']
    self.assertEqual(actual, expected)

运行测试后我得到了这个:

actual   = form.errors['email']
KeyError: 'email'
4

1 回答 1

0

You have to call form.is_valid() to get form.errors to be populated.

于 2012-12-10T09:18:18.990 回答