I have a test which creates a Django object "forgetting" to set one field. It should fail, so I check:
p = Person.objects.create(name='test')
self.assertRaises(ValidationError, p.full_clean)
The forgotten field is birth_date
, so if I intercepted the exception and printed it, the error would be:
{'birth_date': ['This field cannot be blank.']}`
Now I added another field to Person
, which also shouldn't be left blank. The error now would be:
{'birth_date': ['This field cannot be blank.'], 'category': ['This field cannot be blank.']}
With the above code, I silently suppress both errors. I need to test that the code raises a specific validation error. Is there a good way to do it? For now I've this workaround:
try:
p.full_clean()
except ValidationError as e:
self.assertIn('birth_date', dict(e))
self.assertEqual(len(dict(e).keys()), 1, msg="Expected one error, found more")
But if there could have been two different errors with 'birth_date', this would catch either.
Is there a better way?
Aucun commentaire:
Enregistrer un commentaire