skaz skaz - 1 year ago 89
Python Question

Django/Python assertRaises with message check

I am relatively new to Python and want to use a

test to check for a
, which works ok. However, I have many
s and I want to make sure the right one is returned. I figured I could pass something into
but it doesn't look like I can, so I figured I would just do an
and check the exception message. However, I don't know how to access it. Is this even a good way to approach this issue? thanks.

class DailyEntriesTests(TestCase):
def test_cant_have_ip_and_user(self):
u = createUser(False)
de = createDailyEntry(u, "", 1)
with self.assertRaises(ValidationError) as cm:

# this line bombs - message doesn't exist. I also tried "error_code" like I saw in the documentation, but that doesn't work


Answer Source

You can just use assertRaisesRegexp.

with self.assertRaisesRegexp(ValidationError, "Both"):

When you use it as a context manager the 2nd argument is a regular expression to search through the exception's string representation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download