Python Glossary Русский

Python 3.11+unittestfunction

unittest.enterModuleContext()

fixtures

Enters a context manager for the lifetime of all tests in a module and registers its exit as a module cleanup by itself.

Syntax

def setUpModule():
    resource = unittest.enterModuleContext(cm)

It replaces the with + tearDownModule pair where with does not fit: inside setUpModule a with block would close before any test starts. It returns the result of __enter__, like the as clause of with. The exit happens through doModuleCleanups, so it also runs if setUpModule fails after this call. For one class there is TestCase.enterClassContext, for one test self.enterContext.

Examples

import contextlib
import unittest
@contextlib.contextmanager
def resource():
    print('open')
    yield 42
    print('close')
value = unittest.enterModuleContext(resource())
print(value)  # → open / 42
unittest.doModuleCleanups()  # → close

See also

Open in the full glossarydocs.python.orgReport an inaccuracy