Art of Unit Testing

Christoph Zwerschke cito at online.de
Thu Aug 4 08:27:41 EDT 2005


> Your own feature request for setUpOnce() and tearDownOnce() is
> trivially coded using a global or class variable to restrict running to
> a single occasion.  If that seems unpleasant, then encapsulate the
> logic in a subclass of TestCase, in a decorator, or in a metaclass.

Ok, you can have a setUpOnce() at module level that way, but how do you 
realize tearDownOnce() that way? I think what you really have to do is 
to modify the TestSuite class, not the TestCase class. Then you don't 
have to fool around with global or class variables.

-- Christoph

import unittest

class MyTestCase(unittest.TestCase):
     def setUp(self):
         print "setUp",
     def tearDown(self):
         print "tearDown",
     def test1(self):
         print "test1"
     def test2(self):
         print "test2"

class MyTestSuite(unittest.TestSuite):
     def setUp(self):
         print "setUpAll",
     def tearDown(self):
         print "tearDownAll",
     def run(self, result):
         self.setUp()
         unittest.TestSuite.run(self, result)
         self.tearDown()

if __name__ == '__main__':
     suite = unittest.makeSuite(MyTestCase, suiteClass=MyTestSuite)
     unittest.TextTestRunner().run(suite)



More information about the Python-list mailing list