unittest setup

Kent Johnson kent37 at tds.net
Fri Sep 30 18:49:26 EDT 2005


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.

One way to do this is to make a TestSuite subclass that includes your startup and shutdown code.

For example I have some tests that rely on a webserver being started. I have a TestSuite that starts the server, runs the tests and stops the server. This way the server is only started once per test module. Here is the TestSuite class:

class CbServerTestSuite(unittest.TestSuite):
    ''' A test suite that starts an instance of CbServer for the suite '''
    def __init__(self, testCaseClass):
        unittest.TestSuite.__init__(self)
        self.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(testCaseClass))

    def __call__(self, result):
        CbServer.start()
        unittest.TestSuite.__call__(self, result)
        CbServer.stop()


I use it like this:

class MyTest(unittest.TestCase):
    def testWhatever(self):
        pass

def suite():
    return CbServerTestSuite(MyTest)

if __name__=='__main__':
    unittest.TextTestRunner().run(suite())


This runs under Jython (Python 2.1); in more recent Python I think you can override TestSuite.run() instead of __call__().

Kent



More information about the Python-list mailing list