small medium large xlarge

13 Aug 2017, 21:32
Cole Swingholm (2 posts)

First of all, love your book, it’s really helped me get started testing in python.

I’m having a problem understanding where monkeypatch and mock should be used. From what I can understand, both are useful in that they undo what you’ve done after using pytests fixtures, however, monkeypatch is included in pytest and mock is an additional plugin.

Monkeypatch can apparently add and delete attributes, set and delete dictionary items, set and delete environment variables, and mess with the path.

Mock is apparently a wrapper around patch, mock and magicmock from the mock library.

In your book, you talk about each of them separately, but to my beginner mind, their utility is maximized while being used together. Create a mock or magicmock instance with patch that and then add or delete attributes as needed with monkeypatch.

Most of the mocking/monkey-patching guides online use the monkeypatch plugin with the mock module or just monkeypatching using python’s everything is an object ideal. It seems it would be most useful to have them as fixtures, where the setup and tear down are automated by pytest.

Am I incorrect in thinking this? Thanks

14 Aug 2017, 14:00
Brian Okken (8 posts)


Since monkeypatch is built in to pytest, it made sense to me to treat it separately from mock. They definitely are related topics.

The pytest monkeypatch is a fixture, and cleans any changes you’ve made after the test is finished.

I do think using mock with fixtures is a good idea. I recommend using pytest-mock for that very purpose.

Although the topics are similar, monkeypatch and mock are also different, and I use them in different places.

monkeypatch is used to change the environment around the code under test. mock can be used in a similar way, but it can also be used to inspect the way the code under test is using dependent functions to check the behavior of the code under test.

I like to use monkeypatch to set up different states to run the code under test.

I use mock to check the behavior of code under test when the behavior is difficult to test otherwise. I also try to limit the use of mock, since I it can unnecessarily couple a test and the code under test.

Some people might use them together in the same test. I guess. But I haven’t ever had a need to.

15 Aug 2017, 00:19
Cole Swingholm (2 posts)

Thanks for the response!

You must be logged in to comment