Case study: debugging failed assertRaises bug

Duncan Booth duncan.booth at invalid.invalid
Tue Apr 26 05:22:42 EDT 2011

Steven D'Aprano <steve+comp.lang.python at> wrote:

> (1) assertRaises REALLY needs a better error message. If not a custom 
> message, at least it should show the result it got instead of an 
> exception.
If a different exception was thrown then you get an error instead of a 
failure and you are shown the Exception that was thrown, so I think you 
only have an issue if no exception was thrown at all.

If so, here's an alternative way to write your test which might be easier 
to debug:

    def testBadArgType(self):
        # Test failures with bad argument types.
        for d in (None, 23, object(), "spam"):
            with self.assertRaises(TypeError) as cm:
                print(d, "didn't throw the exception")

It is worth remembering that print output doesn't appear unless the test 
fails, so you can leave the tracing statement in the test. Also, 
assertRaises has a weird dual life as a context manager: I never knew that 
before today.

Duncan Booth

More information about the Python-list mailing list