[issue43913] unittest module cleanup functions not run unless tearDownModule() is defined

Terry J. Reedy report at bugs.python.org
Sat Apr 24 16:34:29 EDT 2021


Terry J. Reedy <tjreedy at udel.edu> added the comment:

import unittest

#def setUpModule(): raise Exception()
#def tearDownModule(): print('module teardown')

unittest.addModuleCleanup(print, 'module cleanup')

class Dummy(unittest.TestCase):
    def test_dummy(self):
        self.addCleanup(print, 'test cleanup')
        self.addClassCleanup(print, 'class cleanup')

unittest.main()
----------------------------------------------
Above verifies the claim in 3.10.0a7.   Only 'test cleanup' and 'class cleanup' print. Uncomment either function and 'module cleanup' is also printed.

https://docs.python.org/3/library/unittest.html#unittest.addModuleCleanu
"""
unittest.addModuleCleanup(function, /, *args, **kwargs)

    Add a function to be called after tearDownModule() to cleanup resources used during the test class. Functions will be called in reverse order to the order they are added (LIFO). They are called with any arguments and keyword arguments passed into addModuleCleanup() when they are added.

    If setUpModule() fails, meaning that tearDownModule() is not called, then any cleanup functions added will still be called.
"""
This seems slightly ambiguous as to behavior when no tearDownModule.  However, the doc for addClassCleanup is exactly parallel.

https://docs.python.org/3/library/unittest.html#unittest.TestCase.addClassCleanup
"""
classmethod addClassCleanup(function, /, *args, **kwargs)

    Add a function to be called after tearDownClass() to cleanup resources used during the test class. Functions will be called in reverse order to the order they are added (LIFO). They are called with any arguments and keyword arguments passed into addClassCleanup() when they are added.

    If setUpClass() fails, meaning that tearDownClass() is not called, then any cleanup functions added will still be called.
"""

The doc for addCleanup is also parallel.  The behavior difference therefore seems like a bug and calling in any case seems more correct.

Ryan, can you prepare a PR?

----------
nosy: +ezio.melotti, michael.foord, rbcollins, terry.reedy

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43913>
_______________________________________


More information about the Python-bugs-list mailing list