Mocking
Mocking replaces a real collaborator with a stand-in so a test can run without a network, a clock, or a disk, and so you can assert that a call happened.
Detailed Explanation
A unit test of welcome(user) should not send email. You inject a recording mailer, or you patch app.mail.send with a mock. The first is a fake you wrote. The second is a dynamic object (MagicMock) that accepts any call and records it. Both are test doubles. "Mocking" in Python talk usually means unittest.mock.
Prefer fakes and injection when you own the boundary. A RecordingMail with a .sent list is readable and refactor-friendly. Prefer mocks when the collaborator is a third-party function you cannot inject yet, or when the assertion is "this was called once with this id".
Patch where the name is looked up, not where it is defined. If checkout.py does from stripe import charge, patch checkout.charge, not stripe.charge. The import bound the name already.
Mocks can lie. assert_called_once_with is a precise contract. A mock that returns another mock by default will make result.id pass even when production would have raised. Set return_value, or autospec=True so illegal attributes fail.
Do not mock the system under test. Do not mock a dataclass you could construct. Mock I/O, time, and chaos. Too many mocks mean the test asserts on collaboration, not behaviour; a rename breaks twenty tests and no user-facing behaviour changed.
freezegun, respx, and pytest-httpserver are specialised fakes for time and HTTP. Use them instead of hand-rolled clock mocks when the stack is large.
Code Examples
from unittest.mock import Mock
def welcome(user: str, send) -> None:
send(user, "welcome")
def test_welcome():
send = Mock()
welcome("ada@example.com", send)
send.assert_called_once_with("ada@example.com", "welcome")from unittest.mock import patch
def test_now(monkeypatch=None):
with patch("time.time", return_value=1_700_000_000):
import time
assert time.time() == 1_700_000_000Common Gotchas
Patching the definition instead of the use site
the module under test still has the real function. Patch `module_under_test.name`.
Default mock return values hide bugs
`autospec=True` and explicit `return_value` keep the test honest.
Asserting call count of every helper
you coupled the test to the implementation. Assert the outcome when you can.
pytest's `monkeypatch` and `mocker` wrap the same idea
pick one style in a codebase.