如何从ValidationError访问错误消息?

Saš*_*aba 0 python django

在我的test.py中,我有:

with self.assertRaises(ValidationError):
    validate_zipfile(test_zip_path + '.zip')
Run Code Online (Sandbox Code Playgroud)

这按预期工作。我还想访问此ValidationError引发的错误消息,所以我可以这样做:

self.assertEqual(#error that I extract from the code above, 'Zip file not in correct format.')
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

存储assertRaises()上下文管理器,它具有一个exception属性供您内省引发的异常:

with self.assertRaises(ValidationError) as exception_cm:
    validate_zipfile(test_zip_path + '.zip')

exception = exception_cm.exception
self.assertIn('Zip file not in correct format.', exception.messages)
Run Code Online (Sandbox Code Playgroud)

您可以使用特定于Django的assertRaisesMessage()方法,但要考虑到该测试会执行简单的子字符串测试(例如,在测试较长消息的子字符串时,您可能会遇到误报)。由于ValidationError处理消息列表,因此针对此消息的测试ValidationError.messages将更加可靠。