[Python-ideas] Fwd: Please consider adding context manager versions of setUp/tearDown to unittest.TestCase

Nick Coghlan ncoghlan at gmail.com
Tue Aug 22 01:34:52 EDT 2017


Folks, this has come up before, but: please don't post through Google
Groups, as it breaks everyone else's ability to easily reply to the
entire mailing list.

---------- Forwarded message ----------
From: Nick Coghlan <ncoghlan at gmail.com>
Date: 22 August 2017 at 15:32
Subject: Re: [Python-ideas] Please consider adding context manager
versions of setUp/tearDown to unittest.TestCase
To: Neil Girdhar <mistersheik at gmail.com>
Cc: python-ideas <python-ideas at googlegroups.com>


On 21 August 2017 at 11:32, Neil Girdhar <mistersheik at gmail.com> wrote:
> This question describes an example of the problem:
> https://stackoverflow.com/questions/8416208/in-python-is-there-a-good-idiom-for-using-context-managers-in-setup-teardown.
> You want to invoke a context manager in your setup/tearing-down, but the
> easiest way to do that is to override run, which seems ugly.

Using context managers when you can't use a with statement is one of
the main use cases for contextlib.ExitStack():

    def setUp(self):
        self._resource_stack = stack = contextlib.ExitStack()
        self._resource = stack.enter_context(MyResource())

    def tearDown(self):
        self._resource_stack.close()

I posted that as an additional answer to the question:
https://stackoverflow.com/questions/8416208/in-python-is-there-a-good-idiom-for-using-context-managers-in-setup-teardown/45809502#45809502

Cheers,
Nick.

--
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list