Mock and MagicMock
coreintermediateMock() creates a stand-in object: any attribute or method call on it just returns another Mock, and it records every call so a test can check it later. MagicMock is the same, but also supports dunder methods like __len__ and __iter__.
Think of it as
A Mock is a notepad shaped like an object. Call any method on it, and instead of doing real work, it writes down "you called me with these arguments" and hands back a pre-set (or default) answer — a test can read the notepad afterward.
What we're doing: Create a Mock, call it, and inspect what it recorded — then show MagicMock supporting a dunder method plain Mock does not.
- 3
- Mock(return_value=True) means every call to mock_send returns True, regardless of arguments.
- 4
- This call is recorded — the mock does no real work, but remembers it was called with these two arguments.
- 10
- __len__ is a dunder method — plain Mock() would raise TypeError here; MagicMock implements it by default.
result: True
call_count: 1
len(m): 5Why this works: Mock records every call for later inspection (assert_called_once_with, call_count) instead of doing real work. MagicMock adds the dunder protocol methods Python's built-in functions (len(), iter(), with) rely on, which plain Mock does not implement.
Calling len() on a plain Mock, expecting it to work like MagicMock
Wrong
Better
What you see: TypeError: object of type 'Mock' has no len()
Why: Mock only auto-creates ordinary attributes and methods, not the dunder methods Python's built-ins call directly (len() calls __len__, not a regular method). MagicMock pre-configures the common dunders so they work out of the box.
- Mock() — records calls, auto-creates attributes
- assert_called_once_with(...) — reads back what was recorded
- MagicMock() — same, plus __len__, __iter__, __enter__
Mock — assertions worth knowing
Together
Remember: Mock() records calls and returns whatever you configure; MagicMock() does the same plus supports dunder methods like __len__ that plain Mock does not.
See also: patch and asyncmock · what to mock

