When doing unit-testing with Python / PyTest, if you do you not have patch decorators or with patch
blocks throughout your code, is there a way to reset all mocks a
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()
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.
why don't use 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.
you can:
def test1(monkeypatch):
monkeypatch.setattr(.....