YSC YSC - 1 year ago 159
Python Question

python unittest: tearDownXxx() 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 or higher:

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.

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 hiding 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