我正在尝试为我的更改密码视图编写一个测试,该视图使用PasswordChangeForm。 这是测试:
def test_profile_change_password(self):
self.client.force_login(self.user)
self.user.set_password(self.password)
new_password = random_password()
payload = {
"old_password": self.password,
"new_password1": new_password,
"new_password2": new_password,
}
form = PasswordChangeForm(user=self.user, data=payload)
self.assertTrue(form.is_valid())
response = self.client.get(
reverse_lazy("researcher_ui:change_password"),
)
self.assertEqual(response.template_name, ["researcher_UI/change_password.html"])
response = self.client.post(
reverse_lazy("researcher_ui:change_password"), payload
)
print(response.context['form'].error_messages)
self.assertTrue(form.is_valid())
测试有效,但是当我尝试通过视图处理相同的数据时,出现以下错误:
{'password_mismatch': 'The two password fields didn’t match.', 'password_incorrect': 'Your old password was entered incorrectly. Please enter it again.'}
如果是这种情况,
form.is_valid()
不应该返回True,那么我做错了什么?
可能你有点错了:
form.error_messages
- 它是恒定的,如果验证失败则保留消息。
对于您的情况,您需要
form.errors
print(form.errors)