[Python-Dev] setUpClass and setUpModule in unittest

R. David Murray rdmurray at bitdance.com
Thu Feb 11 16:56:32 CET 2010


On Thu, 11 Feb 2010 12:41:37 +0000, Michael Foord <fuzzyman at voidspace.org.uk> wrote:
> On 11/02/2010 12:30, Nick Coghlan wrote:
> > The test framework might promise to do the following for each test:
> >
> >    with get_module_cm(test_instance): # However identified
> >      with get_class_cm(test_instance): # However identified
> >        with test_instance: # **
> >          test_instance.test_method()
> 
> Well that is *effectively* how they would work (the semantics) but I
> don't see how that would fit with the design of unittest to make them
> work *specifically* like that - especially not if we are to remain
> compatible with existing unittest extensions.
> 
> If you can come up with a concrete proposal of how to do this then I'm
> happy to listen. I'm not saying it is impossible, but it isn't
> immediately obvious. I don't see any advantage of just using context
> managers for the sake of it and definitely not at the cost of backwards
> incompatibility.

I suspect that Nick is saying that it is worth doing for the sake of it,
as being more "Pythonic" in some sense.

That is, it seems to me that in a modern Python writing something like:


@contextlib.contextmanager
def foo_cm(testcase):
    testcase.bar = some_costly_setup_function()
    yield
    testcase.bar.close()

@contextlib.contextmanager
def foo_test_cm(testcase):
    testcase.baz = Mock(testcase.bar)
    yield


@unittest.case_context(foo_cm)
@unittest.test_context(foo_test_cm)
class TestFoo(unittest.TestCase):

    def test_bar:
        foo = Foo(self.baz, testing=True)
        self.assertTrue("Context managers are cool")


would be easier to write, be more maintainable, and be easier to
understand when reading the code than the equivalent setUp and tearDown
methods would be.

I'm not saying it would be easy to implement, and as you say backward
compatibility is a key concern.

--
R. David Murray                                      www.bitdance.com


More information about the Python-Dev mailing list