[TIP] addCleanup for setUpClass()?

Barry Warsaw barry at python.org
Thu Aug 1 07:11:22 PDT 2013


On Aug 01, 2013, at 02:53 PM, Prasanna Santhanam wrote:

>A lot of our tests share resources created within setUpClass and it
>would be useful to override addCleanup to perform such garbage
>collection when setUpClass fails.

If you can use Python 3.3, or don't mind the external dependency on
contextlib2, then take a look at ExitStack

http://docs.python.org/3/library/contextlib.html#contextlib.ExitStack

You can build up a fairly elaborate state, wrapped in a try/except.  Then if
you get an exception during your setUpClass(), you'd just clear the stack to
reclaim your resources.  Doing almost exactly the same thing in
tearDownClass() reclaims the resources in the case where everything succeeded.

E.g.

    @classmethod
    def setUpClass(cls):
        cls._resources = ExitStack()
        try:
            cls._resources.add_callback(clean_my_thing_up)
            another = cls._resources.enter_context(some_context_manager())
            ...
        except:
            cls._resources.close()
            raise

    @classmethod
    def tearDownClass(cls):
        cls._resources.close()

Of course, the utility of ExitStack isn't limited to unittest.  See also:

http://www.wefearchange.org/2013/05/resource-management-in-python-33-or.html

Cheers,
-Barry
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20130801/d4e281a3/attachment.pgp>


More information about the testing-in-python mailing list