1.Mock and MagicMock
Mock() 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__.
Key features
- Mock() auto-creates any attribute/method accessed on it — no advance definition needed
- Mock(return_value=X) makes calling the mock always return X
- mock.assert_called_once_with(args) checks it was called exactly once, with those args
- mock.call_count and mock.call_args_list record how often and with what args it was called
- MagicMock supports dunder methods (__len__, __iter__, __enter__) plain Mock does not
Mock — assertions worth knowing
- Mock() — records calls, auto-creates attributes
- assert_called_once_with(...) — reads back what was recorded
- MagicMock() — same, plus __len__, __iter__, __enter__
Command
from unittest.mock import Mock, MagicMock
m = Mock(return_value=42)
m(1, 2) # returns 42
m.assert_called_once_with(1, 2)
mm = MagicMock()
mm.__len__.return_value = 5
len(mm) # 5 -- plain Mock has no __len__Mock() records calls and returns whatever you configure; MagicMock() does the same plus supports dunder methods like __len__ that plain Mock does not.