Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Testing - Reset all mocks?

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?

like image 260
David A Avatar asked Oct 10 '15 06:10

David A


1 Answers

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.

like image 122
David A Avatar answered Sep 21 '22 11:09

David A