[New-bugs-announce] [issue5206] with context object for unittest assertRaises()

Martin Blais report at bugs.python.org
Tue Feb 10 18:00:32 CET 2009


New submission from Martin Blais <blais at furius.ca>:

Here is a useful trick to restore the normal call syntax for delayed
evaluation for assertRaises():

     from contextlib import contextmanager

     @contextmanager
     def raised(exctype):
         try:
             yield
             raise AssertionError("Exception %s not raised." %
exctype.__name__)
         except exctype, e:
             pass

Then you can do this::

    with raised(ValueError):
        rate = foo(arg1, arg2)

Instead of ::

    self.assertRaises(foo, arg1, arg2)

Which means you don't have to break the function from its arguments (it
doesn't look like a function call anymore).

P.S. I know I didn't include self up there in my proposed implementation
but it could be parameterized to get the failureException. 

(This is a second issue:)
However, I really think that all the failUnlessXXX methods should be
taken out of the class and made available at module level so that they
can be reused by py.test tests as well, and they are perhaps even worthy
of their own module. I can't remember a single instance where I had to
override that failureException class...

Comments welcome, I'd be happy to fix this one myself if we can restore
my commit privileges (I think they expired because I didn't use them
since the need-for-speed workshop.)

----------
messages: 81564
nosy: blais
severity: normal
status: open
title: with context object for unittest assertRaises()

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue5206>
_______________________________________


More information about the New-bugs-announce mailing list