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

Neil Girdhar mistersheik at gmail.com
Sun Aug 20 21:32:19 EDT 2017


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.

Why not add two methods to unittest.TestCase whose default implementations 
are given below:

class TestCase:

    @contextmanager
    def method_context(self):
        self.setUp()
        try:
            yield
        finally:
            self.tearDown()

    @contextmanager
    def class_context(self):
        self.setUpClass()
        try:
            yield
        finally:
            self.tearDown()


Then, if for example someone wants to use a context manager in setUp, they 
can do so:

class SomeTest(TestCase):

    @contextmanager
    def method_context(self):
        with np.errstate(all='raise'):
            with super().method_context():
                yield

Best,

Neil
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170820/b8eaf654/attachment.html>


More information about the Python-ideas mailing list