Python Testing - Reset all mocks?
What I ended up doing was using the pytest-mock library. According to the Readme:
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.)
So now I can do: mocker.patch.object(module, 'method', return_value='hi')
, and the patch will be removed at the end of the test.
There is no need to use with
any more so that this solution scales nicely if you have many mocks in one test or if you want to change mocks during the test.
After monkey-patching, I'm undoing it at the end of the test to avoid any leaking to other tests or limit the patching within the scope.
def test1(monkeypatch):
monkeypatch.setattr(...)
assert(...)
monkeypatch.undo()