Trickiness with unittesting

Peter Otten __peter__ at
Fri Jul 18 15:56:29 EDT 2008

arockstar at wrote:

> Basically, I'm trying to implement a setUp() and TearDown() for a
> python TestSuite (as opposed to an individual test within the suite).
> Sort of.
> I have a few different test suites (call them SuiteA, SuiteB,...). For
> one of the test suites (SuiteA), I need to execute a bit of code (say
> startFoo()) before the first test in SuiteA runs, and once when the
> last test of SuiteA finishes (endFoo()).
> Making this even trickier is that the testing framework combines the
> different suites (SuiteA, SuiteB) as well as individual tests into
> master test suite which my testrunner then runs.
> Also complicating matters is the fact that the testing framework can
> run an *individual* test from any TestSuite: in that case, if I'm
> running SuiteA.test1, I'd want to call startFoo() and endFoo() as
> well.
> I could use a global variable as a flag and see if it's been set
> during the setUp() method of the test cases (which would allow me to
> call startFoo() once when tests from SuiteA are run from the master
> suite), but that doesn't help me with calling endFoo() when the tests
> from SuiteA finish. Plus, it's not very elegant.
> So:
> Given a master test suite comprised of a bunch of different tests from
> different suites, I need to call startFoo() before tests from SuiteA
> are run, and stopFoo() after all the tests from SuiteA have finished
> running.

Here's a glorified version of you global flag idea: 

class Nested(object):
    def __init__(self, start, end):
        self.level = 0
        self._start = start
        self._end = end

    def start(self):
        if self.level == 0:
        self.level += 1

    def end(self):
        assert self.level > 0
        self.level -= 1
        if self.level == 0:

def start_foo():
    print "start foo"

def end_foo():
    print "end foo"

foo = Nested(start_foo, end_foo) 
print "--- 1 ---"
print "--- 2 ---"
print "--- 3 ---"
print "--- 4 ---"
print "--- 5 ---"


More information about the Python-list mailing list