[Python-Dev] setUpClass and setUpModule in unittest

Guido van Rossum guido at python.org
Fri Feb 12 20:48:37 CET 2010

On Fri, Feb 12, 2010 at 7:49 AM, Michael Foord
<fuzzyman at voidspace.org.uk> wrote:
> My *hope* is that we provide a general solution, possibly based on all or
> part of Test Resources, with an easy mechanism for the setUpClass and
> setUpModule but also solves the more general case of sharing fixtures
> between tests. If that doesn't turn out to be possible then we'll go for a
> straight implementation of setUpClass / setUpModule. I'm hoping I can get
> this together in time for the PyCon sprints...

Do you have a reference for Test Resources?

> Here's a current minimal example of using Test Resources. It could be
> simplified further with helper functions and by some of the functionality
> moving into unittest itself. OptimisingTestSuite here ensures that the
> resource is created before first use (MyTempDir.make is called) and disposed
> of when finished with (MyTempDir.clean is called).
> import shutil
> import tempfile
> import testresources
> def load_tests(loader, tests, pattern):
> # this step could be built into the standard loader
> return testresources.OptimisingTestSuite(tests)
> class MyTempDir(testresources.TestResource):
> def make(self, dependency_resources):
> return tempfile.mkdtemp()
> def clean(self, resource):
> shutil.rmtree(resource)
> class MyTest(testresources.ResourcedTestCase):
> resources = [('workdir', MyTempDir())]
> def test_foo(self):
> print self.workdir
> def test_bar(self):
> print self.workdir

This came out with all leading indentation removed, but I think I can
guess what you meant to write.

However from this example I *cannot* guess whether those resources are
set up and torn down per test or per test class. Also the notation

  resources = [('workdir', MyTempDir())]

looks pretty ugly -- if 'workdir' ends up being an instance attribute,
why not make it a dict instead of a list of tuples? Or even better, a
could each resource become a class variable?

--Guido van Rossum (python.org/~guido)

More information about the Python-Dev mailing list