When would you use pytest `monkeypatch` instead of `unittest.mock.patch`, and what should you patch?
Answer
`monkeypatch` is convenient when a pytest test needs temporary changes to attributes, dictionaries, environment variables, paths or the working directory; pytest automatically restores those changes after the requesting scope finishes. `unittest.mock.patch` is stronger when you need mocks with call assertions, autospec or detailed behavior control. In either case patch the name that the code under test actually looks up, not blindly the object where it was originally defined, and prefer explicit dependency injection when extensive patching starts to dominate the design.
Strong answer includes
- uses monkeypatch for temporary pytest-managed state such as env vars and attributes
- uses mock.patch when call verification or richer Mock behavior is required
- patches where the dependency is looked up and recognizes excessive patching as a design smell
Practical example
A configuration test uses
monkeypatch.setenv("API_URL", "https://stub")because the only goal is temporary process state. A service test uses
patch("orders.client.send", autospec=True)because it must verify that
send()was called once with the exact payload.