[TIP] context manager and setUp/tearDown

Robert Collins robertc at robertcollins.net
Mon Feb 11 14:45:20 PST 2013

On 12 February 2013 06:59, Ned Batchelder <ned at nedbatchelder.com> wrote:

> I have been in this same situation, and refactored my context manager to be
> based on an object which I could then use with
> unittest.TestCase.addCleanup().  But now I wonder about code like this
> instead (untested):
> class TestCaseMixin(object):
>     def setup_context_manager(self, cm):
>         val = cm.__enter__()
>         self.addCleanup(functools.partial(cm.__exit__, None, None, None))
>         return val
> Then you can add this to a test case class, and use this:
>     def setUp(self):
>         self.temp = self.setup_context_manager(TemporaryDb())
> and it will be cleaned up automatically

You might like the fixtures Fixture API which similar has addCleanup
and cleanUp calls, and is designed for exactly this sort of thing.
docs - http://pypi.python.org/pypi/fixtures (for any unittest runner)

and some convenience glue in testtools:

Robert Collins <rbtcollins at hp.com>
Distinguished Technologist
HP Cloud Services

More information about the testing-in-python mailing list