在不影响调试器的情况下模拟 os.path.exists

mocking os.path.exists without affecting debugger

我正在为 python 脚本编写单元测试,该脚本通过 os 执行繁重的文件操作,因此我模拟了一些 os 函数。通过以下方式将 os.path 的 return 值修补为 return False 时,我注意到一个奇怪的行为:

@pytest.fixture(autouse=True)
def init_mocks(monkeypatch):
    monkeypatch.setattr(
        mymodule.os.path, "exists", Mock(return_value=False))

我的调试器(在 VSCode 内)根本不工作或表现得很奇怪。 有没有办法在不影响调试器的情况下模拟 os.path?

经过一些研究,我现在明白了,monkeypatching 会影响整个 python 运行时 - 因此也可能影响调试器。 (我发现 os.path.exists 和 os.path.join 都有效果)

因此,为了修补 os.path.exists 同时仍然能够调试,我改为通过上下文管理器修补它:

@pytest.fixture(autouse=True)
def mock_os_path_exists():
    with patch('hdbPackageComposer.os.path.exists', Mock(return_value=True)):
        yield