Python Testing - Reset all mocks?

点点圈 提交于 2021-02-06 11:25:12

问题


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 at the end of every file / module to avoid inter-file test pollution?

It seems like something that is mocked in one Python test file remains mocked in other file with the same return value, which means my mocks are persisting between tests and files (when a patch decorator or with patch block is NOT used).

Is there any way around this other than patching? There wouldn't happen to be a mock.reset_all_mocks() or something like that, would there?


回答1:


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.




回答2:


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(.....



回答3:


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()


来源:https://stackoverflow.com/questions/33051263/python-testing-reset-all-mocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!