[Python-Dev] setUpClass and setUpModule in unittest

Chris Withers chris at simplistix.co.uk
Fri Feb 12 19:26:04 CET 2010


R. David Murray wrote:
> 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")

This reminds me of the decorators I have available in testfixtures:

http://packages.python.org/testfixtures/mocking.html
http://packages.python.org/testfixtures/logging.html
http://packages.python.org/testfixtures/files.html

(the last of which is a lot prettier in svn, not had a chance to release 
:-S)

Anyway, these I've ended up making available as context managers as well 
as decorators...

But yes, something similar for sharing state between tests and/or doing 
setup for each test would be nice :-)

cheers,

Chris

-- 
Simplistix - Content Management, Batch Processing & Python Consulting
             - http://www.simplistix.co.uk



More information about the Python-Dev mailing list