51👍
You can just use assertRaisesRegexp
.
with self.assertRaisesRegexp(ValidationError, "Both"):
de.full_clean()
When you use it as a context manager the 2nd argument is a regular expression to search through the exception’s string representation.
30👍
Since the question is related to Django, you could also use the assertRaisesMessage
context manager when inheriting from django’s TestCase.
from django.test import TestCase
class ExceptionTest(TestCase):
def test_call_raises_exception_with_custom_message(self):
with self.assertRaisesMessage(Exception, 'My custom message!'):
call_that_causes_exception()
Note: The assertRaisesMessage
manager does an in
lookup on the exceptions message: Say your exception raises "My custom message!", asserting for "custom message" passes. Bear this in mind especially if you have multiple (custom) exceptions with similar messages.
(E.g. two different exceptions raising "My custom message! Further details…" and "My custom message! No details." would both pass an assert for "My custom message!").
- [Django]-Return results from multiple models with Django REST Framework
- [Django]-How does the order of mixins affect the derived class?
- [Django]-Django: show the count of related objects in admin list_display
17👍
Nowadays you can use assertRaises
as a context manager. This way you can capture the exception and inspect it later.
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
- [Django]-For Django models, is there a shortcut for seeing if a record exists?
- [Django]-Pre-populate an inline FormSet?
- [Django]-Prepopulate Django (non-Model) Form