unittest setup

paul kölle paul at subsignal.org
Sun Sep 25 16:41:45 EDT 2005


Diez B. Roggisch wrote:
> paul kölle wrote:
> 
>>hi all,
>>
>>I noticed that setUp() and tearDown() is run before and after *earch*
>>test* method in my TestCase subclasses. I'd like to run them *once* for
>>each TestCase subclass. How do I do that.
> 
> 
> Create a global/test instance flag.

I'm not sure if I understood what you mean, I tried:

setup = 'down'

class BaseTest(unittest.TestCase):
  def setUp(self):
    global setup
    if setup == 'up':
      print 'Not running setUp() again...'
      return
    ...
    all setup work goes here.
    ...
    setup = 'up'


This didn't work, (tried to reset the flag in the last test* method to
'down', no dice)
and:

class BaseTest(unittest.TestCase):
  def __init__(self, ...):
    unittest.TestCase.__init__(self, ...)
    self.setup = 'down'

  def setUp(self):
    if self.setup == 'up':
      return
    dowork
    self.setup = 'up'

Failed also, I'm not sure why, __init__ was called way too often and
self.setup was always reset to 'down'. I finally gave up and created my
own method which I call in *every* test* method which is ugly, leads to
longer runtime and code duplication.


But at least it encouraged me to read the unittest docs more carefully.
Now I seem to understand that:

TestSuite.addTest(TestCaseSubclass('testSomething'))
TestSuite.addTest(TestCaseSubclass('testSomethingOther'))

will create two instances of TestCaseSubclass, so there is no way that
'testSomethingOther' will ever see what 'testSomething' might have
created if all work is done with instance data right? Initially I
thought it goes like: "run setUp(), run all test* methods, run
tearDown()" and that is what the unittest docs call a "fixture"

<cite python 2.3 docs for unittest>
A test fixture represents the preparation needed to perform one or more
tests, and any associate cleanup actions.
</cite>

but further down:
<cite python 2.3 docs for unittest>
Each instance of the TestCase will only be used to run a single test
method, so a new fixture is created for each test.
</cite>

It seems to me my case is not that exotic, I thought it would be quite
natural to write the boilerplate stuff in setUp() and build on that to
step through the applications state with test* methods each building on
top of each other. Is that the wrong approach? Are there other
frameworks supporting such a style?

thanks
 Paul




More information about the Python-list mailing list