YSC YSC - 1 month ago 12
Python Question

python unittest: tearDownXxx() are not called

With the

unittest
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):
@classmethod
def setUpClass(cls):
print 'setUpClass'

@classmethod
def tearDownClass(cls):
print 'tearDownClass'

def test_trivia(self):
self.assertTrue(True)

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

if __name__ == '__main__':
main()


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

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

OK
$


What am I doing wrong?

Answer

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":

unittest.main(verbosity=2)
Comments