`unittest.mock`
unittest.mock is the standard-library toolkit for test doubles: Mock, MagicMock, AsyncMock, patch, and sentinel. It records calls and can replace names for the duration of a test.
Detailed Explanation
Mock is an object that accepts any attribute access and any call, storing them on call_args_list. MagicMock also implements dunders (__len__, __iter__, /) so you can use the mock as a container or a number if you must. AsyncMock returns awaitables and tracks awaits. spec or autospec=True limits the mock to the real object's API.
patch("pkg.mod.name", ...) is a context manager, a decorator, or a fixture-like start/stop pair. It temporarily sets pkg.mod.name to a mock (or to new=). patch.object(obj, "attr") patches one attribute. patch.dict and patch.environ (via os.environ) exist for mappings. Always patch the name as seen by the code under test.
return_value is what a call returns. side_effect is an exception, a callable, or an iterable of successive results. wraps= delegates to a real object and still records calls.
Assertions: assert_called_once_with(...), assert_not_called, assert_has_calls. mock_calls includes child calls. reset_mock() clears history but not return_value.
create_autospec(func) makes a mock that checks signatures. A wrong keyword argument then fails in the test instead of in production later.
sentinel.NAME is a unique object for identity assertions. DEFAULT is a special side_effect token. You will use sentinels more than DEFAULT.
Keep patches narrow. A module-wide patch in conftest hides I/O from every test, including the one that was supposed to catch a real integration bug. Prefer injecting dependencies; use mock when you cannot.
Code Examples
from unittest.mock import Mock, patch, call
def fetch_user(client, user_id: str) -> dict:
return client.get(f"/users/{user_id}")
def test_fetch():
client = Mock()
client.get.return_value = {"id": "1"}
assert fetch_user(client, "1")["id"] == "1"
client.get.assert_called_once_with("/users/1")def test_side_effect():
fn = Mock(side_effect=[1, 2, RuntimeError("down")])
assert fn() == 1
assert fn() == 2
try:
fn()
except RuntimeError as exc:
assert str(exc) == "down"# patch the lookup site
with patch("time.sleep", return_value=None) as slept:
import time
time.sleep(5)
slept.assert_called_once_with(5)Common Gotchas
Wrong patch target
`from x import y` then `patch("x.y")` does not affect the already-bound name in the importer.
Forgetting `AsyncMock` for `async def`
a plain `Mock` is not awaitable. Tests pass until the production loop tries to await.
`MagicMock` as a spec-less stand-in
`result.typo` is another mock, not an `AttributeError`.
`patch` as a decorator injects the mock as an extra argument
the order is bottom-up, and it is easy to mismatch signatures.