我正在使用新的自定义用户模型在 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'