In Python, a mock is a stand-in object that records how it was used. unittest.mock gives you Mock and MagicMock for fakes, patch to swap a real object for the length of a test, and autospec to keep the fake honest about the real signature. Most mistakes come from patching the wrong name.
What is the difference between Mock and MagicMock?
Mock creates attributes and child mocks as you access them, returns the same child each time, and records calls. MagicMock is a subclass with the magic methods preconfigured. Per the standard library documentation, defaults include __len__ returning 0, __iter__ returning an empty iterator and __bool__ returning True.
That matters in practice. If your code loops over a result or uses with, a plain Mock fails and a MagicMock works. The default is also a trap: len(MagicMock()) is 0 and quietly passes code paths you meant to test with data.
Where do you patch?
Patch the name where it is looked up, not where it is defined. The documentation gives the pattern. If a.py defines SomeClass and b.py does from a import SomeClass, then b holds its own reference. You must use patch('b.SomeClass'). If b instead does import a and calls a.SomeClass, then patch('a.SomeClass') is correct.
This one rule fixes the common complaint that "patch did nothing". The real object was still called because the code under test never used the name you replaced.
Why use autospec?
A bare mock accepts anything. Call it with wrong arguments and it returns a mock. Real code would raise an error. With create_autospec() or patch(..., autospec=True), the mock copies the signature of the real object, so the documentation's example calling a three argument function with a single wrong argument raises a TypeError.
Use it by default for functions and classes you own. When the real API changes, your tests fail instead of passing against an interface that no longer exists.
How do you fake failures and sequences?
side_effect runs when the mock is called, after the call is recorded. It takes an exception, a function, or an iterable.
- An exception class or instance is raised on call. Use it to test your error handling for a timeout or a missing key.
- A function receives the same arguments and its return value is used.
- An iterable returns one item per call, and raises any exception item it meets. When it runs out,
StopIterationis raised.
Constructed example: you want a retry loop tested. Give the mocked network call a side_effect list holding a timeout error, a second timeout error and then a good response. Assert the function returned the good value and that the mock was called three times.
Which assertions fit which question?
assert_called_once_with checks exactly one call with those arguments. assert_called_with checks only the most recent call. assert_any_call passes if the call happened at any point. assert_has_calls checks a sequence. Pick the one that says what you mean, and prefer the strictest.
One more guard: names that begin like assert but are misspelled raise an AttributeError unless you pass unsafe=True. This prevents a typo such as assert_called_onc from silently passing.
How to check or apply this
- Replace bare
Mock()for your own classes withcreate_autospec. - For every
patchtarget, confirm the module you name is the module where the code under test imports the thing. - Use
specorspec_setwhen mocking third party objects you cannot autospec. - Test at least one failure path per external call with
side_effect. - Prefer
assert_called_once_withoverassert called. - Keep mocks at boundaries: network, disk, clock. If you mock your own logic, the test proves little.
Quick check
Why did my patch not take effect?
You likely patched the definition site. Patch the name in the module that looks it up, such as the module that did the import.
When should I use autospec?
Whenever a mock stands in for a real function or class, so wrong argument counts raise errors the way real code would.
Sources
Last reviewed: 18 October 2026.