Python单元测试类似于pytest范围=“会话”?

pep*_*uan 6 python python-3.x python-unittest

我们pytest可以定义一个session作用域固定装置,因此以下

@pytest.fixture(scope="session", autouse=True)
def some_fixt():
   ... some setup procedure ...
   yield
   ... some cleanup procedure ...
Run Code Online (Sandbox Code Playgroud)

将在测试会话开始之前自动进行设置,并在测试结束后进行清理。

中有类似的东西吗unittest?我能找到的最好的是setUpModule+ tearDownModule,但这只是每个模块,需要在不同的测试模块之间复制粘贴。


编辑:这是我当前的解决方法:

对于每个测试模块:

from contextlib import ExitStack
...


ModuleResources = ExitStack()

def setUpModule():
    # For funcs/objects that can act as a context_manager
    ModuleResources.enter_context(
        ... something that can act as a context_manager ...
    )
    # For funcs/objects that cannot act as a context manager,
    # but has a "cleanup" method such as "stop" or "close"
    ... invoke setup ...
    ModuleResources.callback(thing.cleanup)


def tearDownModule():
    ModuleResources.close()
Run Code Online (Sandbox Code Playgroud)

当然,问题是我必须为每个测试模块粘贴所有这些代码。所以我在这里寻找更简单的东西。