monkeypatch vs mock.patch: One rule to pick the right Python test tool
In Python testing, both monkeypatch and mock.patch replace attributes and clean up after tests, but choosing between them often comes down to a single question. If a test only needs a function to return a value or be suppressed, monkeypatch is the simpler choice, reading as plain Python with built-in cleanup for environment variables, directories, and sys.path. If a test needs to verify how a function was called — such as checking arguments with assert_called_once_with — MagicMock via mock.patch is the appropriate tool. The two can also be combined, using monkeypatch.setattr to install a MagicMock object, which avoids nested context managers while retaining full assertion capabilities. A key rule for both approaches is to patch where the name is looked up in the module under test, not where it was originally defined.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.

Discussion (0)
Log in to join the discussion and vote.
Log in