unittest: assertRaises() with an instance instead of a type

Terry Reedy tjreedy at udel.edu
Wed Mar 28 20:26:48 CEST 2012


On 3/28/2012 8:28 AM, Ulrich Eckhardt wrote:
> Hi!
>
> I'm currently writing some tests for the error handling of some code. In
> this scenario, I must make sure that both the correct exception is
> raised and that the contained error code is correct:
>
>
> try:
> foo()
> self.fail('exception not raised')
> catch MyException as e:
> self.assertEqual(e.errorcode, SOME_FOO_ERROR)
> catch Exception:
> self.fail('unexpected exception raised')
>
>
> This is tedious to write and read. The docs mention this alternative:
>
>
> with self.assertRaises(MyException) as cm:
> foo()
> self.assertEqual(cm.the_exception.errorcode, SOME_FOO_ERROR)

Exceptions can have multiple attributes. This allows the tester to 
exactly specify what attributes to test.

> This is shorter, but I think there's an alternative syntax possible that
> would be even better:
>
> with self.assertRaises(MyException(SOME_FOO_ERROR)):
> foo()

I presume that if this worked the way you want, all attributes would 
have to match. The message part of builtin exceptions is allowed to 
change, so hard-coding an exact expected message makes tests fragile. 
This is a problem with doctest.

> Here, assertRaises() is not called with an exception type but with an
> exception instance. I'd implement it something like this:
>
> def assertRaises(self, exception, ...):
> # divide input parameter into type and instance
> if isinstance(exception, Exception):
> exception_type = type(exception)
> else:
> exception_type = exception
> exception = None
> # call testee and verify results
> try:
> ...call function here...
> except exception_type as e:
> if not exception is None:
> self.assertEqual(e, exception)

Did you use tabs? They do not get preserved indefinitely, so they are 
bad for posting.

> This of course requires the exception to be equality-comparable.

Equality comparison is by id. So this code will not do what you want.

You can, of course, write a custom AssertX subclass that at least works 
for your custom exception class.

-- 
Terry Jan Reedy




More information about the Python-list mailing list