[TIP] setUp and tearDown behavior

C. Titus Brown ctb at msu.edu
Mon Jan 18 19:29:28 PST 2010

On Tue, Jan 19, 2010 at 11:05:33AM +0800, Red Forks wrote:
> > I am building some tests for a Python installer that copies some files and
> > changes some permissions.
> >
> > Nothing weird there.
> >
> > However, in the test class I am starting with a setUp that basically calls
> > the installer (so the tests can see if everything is where it should be),
> > this is followed by a few assertions and finally a tearDown is called where
> > everything gets uninstalled.
> >
> > When running the tests with nosetests, I see that setUp and tearDown are
> > called for *every* method in my test class (e.g. installs => runs test
> > method => uninstalls ....)
> >
> > Isn't setUp supposed to be run once at the beginning of the class? or is
> > this expected?
> >
> > In case this is expected, is there a way to do it *just once *for all the
> > methods?
> >
> Maybe you need module level setup / teapDown func.

--- file test_foo.py

def setup():
   # run once, then all test fns and classes in module run

def teardown():
   # run once after all test fns/classes

def test_fn():
   # a test fn, run after setup() and before teardown()

class Test_Class(object):
   def setUp(self):
      # run before every test in this class

   def test_method(self):
      # your typical unittest foo

   def tearDown(self):
      # complement to setUp


There are other ways of doing it, too, but this is the most straightforward,
I think.

C. Titus Brown, ctb at msu.edu

More information about the testing-in-python mailing list