This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: with context object for unittest assertRaises()
Type: enhancement Stage:
Components: Library (Lib) Versions:
process
Status: closed Resolution: out of date
Dependencies: Superseder:
Assigned To: Nosy List: blais, pitrou, rhettinger
Priority: normal Keywords:

Created on 2009-02-10 16:59 by blais, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (3)
msg81564 - (view) Author: Martin Blais (blais) * (Python committer) Date: 2009-02-10 16:59
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.)
msg81573 - (view) Author: Antoine Pitrou (pitrou) * (Python committer) Date: 2009-02-10 18:22
This is already done in trunk, you can use it as follows:

with self.assertRaises(ZeroDivisionError):
    1/0
msg81605 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2009-02-10 21:39
Humph!  The time machine strikes again.
History
Date User Action Args
2022-04-11 14:56:45adminsetgithub: 49456
2009-02-10 21:39:19rhettingersetnosy: + rhettinger
messages: + msg81605
2009-02-10 18:22:58pitrousetstatus: open -> closed
resolution: out of date
messages: + msg81573
nosy: + pitrou
2009-02-10 17:07:03blaissettype: enhancement
components: + Library (Lib)
2009-02-10 16:59:26blaiscreate