Python Testing - Reset all mocks?

后端 未结 3 1281
情书的邮戳
情书的邮戳 2021-02-09 11:05

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

相关标签:
3条回答
  • 2021-02-09 11:23

    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()
    
    0 讨论(0)
  • 2021-02-09 11:31

    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.

    0 讨论(0)
  • 2021-02-09 11:35

    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(.....
    
    0 讨论(0)
提交回复
热议问题