[Baypiggies] Question about unittest, setUp and suites

Aaron Maxwell amax at redsymbol.net
Mon May 4 22:24:42 CEST 2009

Hi Herbert.

On Monday 04 May 2009 11:29:26 am Herbert Pfennig wrote:
> Hi All,
> Long time lurker with a simple question about unittest. I have googled
> around and have not really found a good answer to the following question.
> How do I define a _setUp_ that only get's called before a suite of tests is
> run? (_not_ for every test)

I believe that using a global like you did is the best approach under plain 
unittest.  An alternative is to use a class variable:

import unittest

class T(unittest.TestCase):
    first_time = True
    def setUp(self):
        if T.first_time:
            T.first_time = False
            # initial setup
            print '**doing first-time setup'

    def test_a(self):

    def test_b(self):

if '__main__' == __name__:

It's less maintainable because the class name appears 3 times, and you have to 
remember somehow to update all 3 if it changes.  A workaround is to use 
self.__class__ instead:
    def setUp(self):
        if self.__class__.first_time:
            self.__class__.first_time = False

Some people, like myself, would prefer the global-variable method anyway.  To 
me it seems easier to understand quickly when I look at the code again weeks 
later.  In particular, setting the class attribute is kind of obscure - it 
does what you need because of how unittest processes test cases, but if 
you're not familiar with those internals, you might look at it and go, "Huh? 
how come this works?"  Maybe you could encapsulate it in a well-documented 
function or method.

Anyway, some other test frameworks that build upon unittest have explicit 
support for this test pattern, so if you're doing this a lot you might want 
to look into them.  Nose in particular [0], and possibly py.test as well [1].

[0] http://somethingaboutorange.com/mrl/projects/nose/
[1] http://codespeak.net/py/dist/test/test.html

Aaron Maxwell

More information about the Baypiggies mailing list