[TIP] RFC: Post-assertRaises assertions WAS: ANN: unittest2 0.4.0 Release

exarkun at twistedmatrix.com exarkun at twistedmatrix.com
Fri Apr 9 06:24:53 PDT 2010

On 01:10 pm, olemis at gmail.com wrote:
>On Thu, Apr 8, 2010 at 5:42 PM, Michael Foord 
><michael at voidspace.org.uk> wrote:
>>Hello all,
>>I'm pleased to announce the release of version 0.4.0 of unittest2.
>>For full details of all the new features, see my blog entry:
>I wanted to know if you have considered support for writing assertions
>targeting the exception object been raised . In my experience that is
>very helpful when testing some kind of systems. For instance, in Trac
>XmlRpcPlugin (<=0.1.6, current trunk ;o) you can find many tests
>(actually all TCs checking for error conditions ;o) like this
>Therefore, we're recently considering [1]_ (not committed yet ;o) to
>adopt this style
>class TracRpcTestCase(unittest.TestCase):
>        # Further code omitted ;o)
>        def assertRaises(self, excClass, callableObj, *args, **kwargs):
>            """Enhanced assertions to detect exceptions."""
>            try:
>                callableObj(*args, **kwargs)
>            except excClass, e:
>                return e
>            except self.failureException :
>                raise
>            except Exception, e :
>                if hasattr(excClass, '__name__'): excName = 
>                else: excName = str(excClass)
>                if hasattr(e, '__name__'): excMsg = e.__name__
>                else: excMsg = str(e)
>                raise self.failureException("\n\nExpected %s\n\nGot %s : 
>%s" % (
>                                        excName, e.__class__.__name__, 
>            else:
>                if hasattr(excClass,'__name__'): excName = 
>                else: excName = str(excClass)
>                raise self.failureException, "Expected %s\n\nNothing
>raised" % excName

Twisted Trial also includes an assertRaises like this.  It has worked 
well for many years in a wide variety of contexts.

Guido seemed to veto the API (<http://mail.python.org/pipermail/python- 

  Hm. I've got to say that returning the exception object is, um, an odd
  API in the set of unittest APIs. I can see how it's sometimes more
  powerful, but I'd say that in many cases assertRaisesWithMessage will
  be easier to write and read. (And making it a regex match would be
  even cooler.)

IMHO, the (lack of) reasoning here is bogus.  In fact, even Guido seems 
to have forgotten that he doesn't like it 

  Antoine Pitrou <pitrou at free.fr> added the comment:
  > Wouldn't it be simpler to make assertRaises return the exception and 
  > the calling code match it as it feels like?

  Hm, that sounds awfully familiar. I can't recall if there was ever a
  good reason not to do this.


More information about the testing-in-python mailing list