YSC YSC - 1 year ago 193
Python Question

Python unittest: setUpClass(), tearDownClass(), setUpModule() and tearDownModule() are not called

With the

module using python 2.6.6, how to invoke code after all tests have run ?

Please considere the following MCVE:

#!/bin/env python
import unittest

def setUpModule():
print 'setUpModule'

def tearDownModule():
print 'tearDownModule'

class TestClass(unittest.TestCase):
def setUpClass(cls):
print 'setUpClass'

def tearDownClass(cls):
print 'tearDownClass'

def test_trivia(self):

def main():
"""entry point"""

if __name__ == '__main__':

I would expect to see
to appear on the console, but it does not:

$ ./test.py
Ran 1 test in 0.000s


What am I doing wrong?

Answer Source

Answer for Python 2.6:

The Python 2.6 unittest doc does not mention setUpClass, tearDownClass, setUpModule and tearDownModule methods/functions. So they are probably not supported by unittest and not called at all.

However, unittest2 seems to support Python since 2.4. It may brings you features that unittest for Python 2.6 does not support.

Answer for Python 2.7 or higher:

I think you are not doing anything wrong and the setUp* and tearDown* functions/methods are called. I think that unittest is just hidding the printed strings.

Try to provide verbosity level 2 to your call to unittest.main function, it should fix the "problem":

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download