标记测试在独立进程中运行

Pet*_*ter 4 python pytest

我正在使用 pytest。我有一个测试,其中涉及检查是否在发生某些事情时没有进行导入。这很容易实现,但是当测试在 pytest 中运行时,它会在与许多其他测试相同的过程中运行,这些测试可能会事先导入该内容。

是否有某种方法可以将测试标记为在其自己的进程中运行?理想情况下会有某种装饰器,例如

@pytest.mark.run_in_isolation
def test_import_not_made():
    ....
Run Code Online (Sandbox Code Playgroud)

但我还没有找到类似的东西。

Fra*_*k T 5

我不知道允许将测试标记为在其自己的进程中运行的 pytest 插件。我要检查的两个是pytest-xdistptyest-xprocess(这里是 pytest 插件列表),尽管它们看起来不像你想要的那样。

我会采用不同的解决方案。我假设您检查模块是否导入的方式是它是否在sys.modules. 因此,我会确保sys.modules在测试运行之前不包含您感兴趣的模块。

这样的事情将确保sys.modules在您的测试运行之前处于干净的状态。

import sys

@pytest.fixture
def clean_sys_modules():
    try:
        del sys.modules['yourmodule']
    except KeyError:
        pass
    assert 'yourmodule' not in sys.modules # Sanity check.

@pytest.mark.usefixtures('clean_sys_modules')
def test_foo():
    # Do the thing you want NOT to do the import.
    assert 'yourmodule' not in sys.modules 
Run Code Online (Sandbox Code Playgroud)