Python Glossary Русский

Python 3.8+unittestfunction

unittest.addModuleCleanup()

fixtures

Registers a module-level cleanup function: it is called after tearDownModule(), even if setUpModule() failed.

Syntax

unittest.addModuleCleanup(function, /, *args, **kwargs)

The key difference from tearDownModule: that one is skipped if setUpModule() raises, while cleanups registered before the failure still run, so temporary files and connections do not leak. They are called in reverse order of registration (LIFO), like a stack. Register a cleanup right after acquiring the resource, not at the end of setUpModule.

Examples

# Python 3.11+
import unittest
unittest.addModuleCleanup(print, 'first registered')
unittest.addModuleCleanup(print, 'second registered')
unittest.doModuleCleanups()  # → second registered / first registered

See also

Open in the full glossarydocs.python.orgReport an inaccuracy