I use the standard unittest module for testing, despite the community’s general protestations about it not being pythonic. It does what I need, except for one thing. It has an assertRaises method that tests that a callable raises an exception of the expected class, but the message that comes with the exception is not checked. So I usually mix this method into my test case base class:
def assertRaisesMsg(self, excClass, msg, callableObj, *args, **kwargs):
""" Just like unittest.TestCase.assertRaises,
but checks that the message is right too.
except excClass, exc:
excMsg = str(exc)
if not msg:
# No message provided: any message is fine.
elif excMsg == msg:
# Message provided, and we got the right message: it passes.
# Message provided, and it didn't match: fail!
"Right exception, wrong message: got '%s' expected '%s'" %
if hasattr(excClass, '__name__'):
excName = excClass.__name__
excName = str(excClass)
"Expected to raise %s, didn't get an exception at all" %
I can call it (for example) like this:
self.assertRaisesMsg(MyException, "Exception message", my_function, (arg1, arg2))
This test line will call my_function(arg1, arg2) and succeed if it raises a MyException with the message “Exception message”. It will fail in all other cases.