简体   繁体   中英

Python unittest: setUpClass(), tearDownClass(), setUpModule() and tearDownModule() 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 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":

unittest.main(verbosity=2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM