Python Glossary Русский

Python 3.8+unittestfunction

unittest.doModuleCleanups()

fixtures

Runs every cleanup registered with addModuleCleanup() in reverse order; normally the test suite calls it for you.

Syntax

unittest.doModuleCleanups()

You only call it by hand when writing your own runner or running tests without a TestSuite: the standard suite does it itself after tearDownModule. An exception in one cleanup does not stop the rest: every function runs, and an exception is raised at the end: the first one before 3.15, an ExceptionGroup with all of them from 3.15. A second call does nothing, because the list is emptied.

Examples

# Python 3.11+
import unittest
def broken():
    raise ValueError('cleanup failed')
unittest.addModuleCleanup(print, 'still runs')
unittest.addModuleCleanup(broken)
try:
    unittest.doModuleCleanups()
except Exception as e:
    print('raised:', type(e).__name__)  # → still runs / raised: — ValueError до 3.15, ExceptionGroup с 3.15
unittest.doModuleCleanups()  # второй вызов — список уже пуст

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy