Python 测试 - 重置所有模拟?

Python Testing - Reset all mocks?

在使用 Python / PyTest 进行单元测试时,如果您没有补丁装饰器或整个代码中的 with patch 块,有没有办法在每个文件/模块避免文件间测试污染?

似乎在一个 Python 测试文件中被模拟的东西在另一个具有相同 return 值的文件中仍然被模拟,这意味着我的模拟在测试和文件之间持续存在(当补丁不使用装饰器或 with patch 块)。

除了打补丁,还有什么解决办法吗?不会碰巧有 mock.reset_all_mocks() 之类的东西吧?

为什么不使用 monkeypatch

The monkeypatch function argument helps you to safely set/delete an attribute, dictionary item or environment variable or to modify sys.path for importing.

您可以:

def test1(monkeypatch):
    monkeypatch.setattr(.....

我最后做的是使用 pytest-mock 库。根据自述文件:

This plugin installs a mocker fixture which is a thin-wrapper around the patching API provided by the excellent mock package, but with the benefit of not having to worry about undoing patches at the end of a test. (Emphasis added.)

所以现在我可以这样做:mocker.patch.object(module, 'method', return_value='hi'),补丁将在测试结束时被删除。 不再需要使用 with,这样如果您在一次测试中有很多模拟或者如果您想在测试期间更改模拟,这个解决方案可以很好地扩展。

猴子修补后,我将在测试结束时撤消它以避免泄漏到其他测试或将修补限制在范围内。

def test1(monkeypatch):
    monkeypatch.setattr(...)
    assert(...)
    monkeypatch.undo()