How to show the error messages caught by assertRaises() in unittest in Python2.7?
I once preferred the most excellent answer given above by @Robert Rossney. Nowadays, I prefer to use assertRaises as a context manager (a new capability in unittest2) like so:
with self.assertRaises(TypeError) as cm:
failure.fail()
self.assertEqual(
'The registeraddress must be an integer. Given: 1.0',
str(cm.exception)
)
You are looking for assertRaisesRegex, which is available since Python 3.2. From the docs:
self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
int, 'XYZ')
or:
with self.assertRaisesRegex(ValueError, 'literal'):
int('XYZ')
PS: if you are using Python 2.7, then the correct method name is assertRaisesRegexp
.