0
# Mock Objects
1
2
Mock objects provide configurable replacements for Python objects, enabling comprehensive test isolation and behavior verification. The mock library offers several mock classes optimized for different use cases.
3
4
## Capabilities
5
6
### Mock
7
8
The primary mock class that creates callable mock objects with automatic attribute and method creation.
9
10
```python { .api }
11
class Mock:
12
def __init__(
13
self,
14
spec=None,
15
side_effect=None,
16
return_value=None,
17
wraps=None,
18
name=None,
19
spec_set=None,
20
unsafe=False,
21
**kwargs
22
):
23
"""
24
Create a mock object.
25
26
Parameters:
27
- spec: Specification object to validate mock usage against
28
- side_effect: Function to call when mock is called, or exception to raise, or iterable of values
29
- return_value: Value to return when mock is called
30
- wraps: Object to wrap, calls pass through to wrapped object
31
- name: Name of the mock for debugging
32
- spec_set: Like spec but more restrictive
33
- unsafe: Allow access to dangerous attributes
34
- **kwargs: Attributes to set on the mock
35
"""
36
37
def assert_called_with(self, *args, **kwargs):
38
"""Assert the mock was last called with specified arguments."""
39
40
def assert_called_once_with(self, *args, **kwargs):
41
"""Assert the mock was called exactly once with specified arguments."""
42
43
def assert_any_call(self, *args, **kwargs):
44
"""Assert the mock was called with specified arguments at some point."""
45
46
def assert_has_calls(self, calls, any_order=False):
47
"""Assert the mock has been called with the specified calls."""
48
49
def assert_called(self):
50
"""Assert the mock has been called at least once."""
51
52
def assert_called_once(self):
53
"""Assert the mock has been called exactly once."""
54
55
def assert_not_called(self):
56
"""Assert the mock has never been called."""
57
58
def reset_mock(self, visited=None, return_value=False, side_effect=False):
59
"""Reset the mock to initial state."""
60
61
def configure_mock(self, **kwargs):
62
"""Configure the mock with keyword arguments."""
63
64
def attach_mock(self, mock, attribute):
65
"""Attach a mock as an attribute."""
66
67
def mock_add_spec(self, spec, spec_set=False):
68
"""Add a spec to the mock."""
69
70
# Properties
71
called: bool # Whether the mock has been called
72
call_count: int # Number of times the mock has been called
73
call_args: call # Arguments from the last call
74
call_args_list: list # List of all call arguments
75
mock_calls: list # List of all calls including method calls
76
method_calls: list # List of method calls only
77
return_value: object # Value to return when called
78
side_effect: object # Side effect when called
79
```
80
81
### NonCallableMock
82
83
A mock that cannot be called, used for mocking non-callable objects like modules, classes (not instances), or other objects that shouldn't be called.
84
85
```python { .api }
86
class NonCallableMock:
87
def __init__(
88
self,
89
spec=None,
90
wraps=None,
91
name=None,
92
spec_set=None,
93
**kwargs
94
):
95
"""
96
Create a non-callable mock object.
97
98
Similar to Mock but raises TypeError when called.
99
"""
100
101
def assert_called_with(self, *args, **kwargs):
102
"""Raises AssertionError - non-callable mocks cannot be called."""
103
104
def configure_mock(self, **kwargs):
105
"""Configure the mock with keyword arguments."""
106
107
def attach_mock(self, mock, attribute):
108
"""Attach a mock as an attribute."""
109
110
def mock_add_spec(self, spec, spec_set=False):
111
"""Add a spec to the mock."""
112
113
def reset_mock(self, visited=None):
114
"""Reset the mock to initial state."""
115
```
116
117
### MagicMock
118
119
A mock with magic method support, automatically creating mock implementations for Python's special methods like `__str__`, `__iter__`, etc.
120
121
```python { .api }
122
class MagicMock(Mock):
123
def __init__(self, *args, **kwargs):
124
"""
125
Create a mock with magic method support.
126
127
Inherits all Mock functionality and adds automatic magic method creation.
128
Magic methods like __str__, __iter__, __len__ are automatically mocked.
129
"""
130
```
131
132
### NonCallableMagicMock
133
134
A non-callable version of MagicMock, combining the restrictions of NonCallableMock with magic method support.
135
136
```python { .api }
137
class NonCallableMagicMock(NonCallableMock):
138
def __init__(self, *args, **kwargs):
139
"""
140
Create a non-callable mock with magic method support.
141
142
Cannot be called but has automatic magic method creation.
143
"""
144
```
145
146
### AsyncMock
147
148
A mock designed specifically for async/await code, providing proper coroutine support and async method mocking.
149
150
```python { .api }
151
class AsyncMock(Mock):
152
def __init__(self, *args, **kwargs):
153
"""
154
Create a mock for async/await code.
155
156
Returns coroutines when called and properly handles async context managers.
157
Automatically detects when specs are async and creates appropriate mocks.
158
"""
159
160
async def __call__(self, *args, **kwargs):
161
"""Call the async mock, returning a coroutine."""
162
163
def assert_awaited(self):
164
"""Assert the mock has been awaited at least once."""
165
166
def assert_awaited_once(self):
167
"""Assert the mock has been awaited exactly once."""
168
169
def assert_awaited_with(self, *args, **kwargs):
170
"""Assert the mock was last awaited with specified arguments."""
171
172
def assert_awaited_once_with(self, *args, **kwargs):
173
"""Assert the mock was awaited exactly once with specified arguments."""
174
175
def assert_any_await(self, *args, **kwargs):
176
"""Assert the mock was awaited with specified arguments at some point."""
177
178
def assert_has_awaits(self, calls, any_order=False):
179
"""Assert the mock has been awaited with the specified calls."""
180
181
def assert_not_awaited(self):
182
"""Assert the mock has never been awaited."""
183
184
def reset_mock(self, *args, **kwargs):
185
"""Reset the mock including await-specific state."""
186
187
# Properties
188
await_count: int # Number of times the mock has been awaited
189
await_args: call # Arguments from the last await
190
await_args_list: list # List of all await arguments
191
```
192
193
### ThreadingMock
194
195
A thread-safe version of Mock that uses locks to prevent race conditions in multithreaded testing scenarios. Provides additional synchronization methods for waiting on mock calls.
196
197
```python { .api }
198
class ThreadingMock(Mock):
199
DEFAULT_TIMEOUT: float = 10.0 # Default timeout for wait methods
200
201
def __init__(self, *args, **kwargs):
202
"""
203
Create a thread-safe mock object.
204
205
All mock operations are protected by locks to prevent race conditions.
206
Inherits all Mock functionality with thread safety guarantees.
207
"""
208
209
def wait_until_called(self, *, timeout=None):
210
"""
211
Wait until the mock is called at least once.
212
213
Parameters:
214
- timeout: Maximum time to wait in seconds (defaults to DEFAULT_TIMEOUT)
215
216
Returns:
217
True if mock was called within timeout, False otherwise
218
"""
219
220
def wait_until_any_call_with(self, *args, **kwargs):
221
"""
222
Wait until the mock is called with specific arguments.
223
224
Parameters:
225
- *args: Positional arguments to wait for
226
- **kwargs: Keyword arguments to wait for
227
228
Returns:
229
True if mock was called with arguments within timeout, False otherwise
230
"""
231
```
232
233
### PropertyMock
234
235
A mock designed specifically for properties and descriptors, implementing the descriptor protocol.
236
237
```python { .api }
238
class PropertyMock(Mock):
239
def __init__(self, return_value=None, **kwargs):
240
"""
241
Create a mock for property objects.
242
243
Implements descriptor protocol (__get__, __set__, __delete__).
244
Used to mock properties, class methods, and static methods.
245
"""
246
247
def __get__(self, obj, obj_type):
248
"""Descriptor get method."""
249
250
def __set__(self, obj, value):
251
"""Descriptor set method."""
252
253
def __delete__(self, obj):
254
"""Descriptor delete method."""
255
```
256
257
## Common Patterns
258
259
### Basic Mock Usage
260
261
```python
262
from mock import Mock
263
264
# Create and use a simple mock
265
mock_obj = Mock()
266
mock_obj.method.return_value = 'result'
267
result = mock_obj.method('arg')
268
mock_obj.method.assert_called_with('arg')
269
```
270
271
### Mock with Spec
272
273
```python
274
from mock import Mock
275
276
class RealClass:
277
def method(self, arg): pass
278
279
# Mock with spec prevents typos and invalid attribute access
280
mock_obj = Mock(spec=RealClass)
281
mock_obj.method('arg') # Valid
282
# mock_obj.typo() # Would raise AttributeError
283
```
284
285
### Async Mock Usage
286
287
```python
288
from mock import AsyncMock
289
import asyncio
290
291
async def test_async_function():
292
mock_async = AsyncMock()
293
mock_async.return_value = 'async result'
294
295
result = await mock_async('arg')
296
assert result == 'async result'
297
mock_async.assert_awaited_once_with('arg')
298
```
299
300
### ThreadingMock Usage
301
302
```python
303
from mock import ThreadingMock
304
import threading
305
import time
306
307
def test_threaded_function():
308
mock_service = ThreadingMock()
309
310
def worker():
311
time.sleep(0.1) # Simulate work
312
mock_service('worker_call')
313
314
# Start worker thread
315
thread = threading.Thread(target=worker)
316
thread.start()
317
318
# Wait for mock to be called (with timeout)
319
called = mock_service.wait_until_called(timeout=1.0)
320
assert called == True
321
322
# Wait for specific call arguments
323
specific_call = mock_service.wait_until_any_call_with('worker_call')
324
assert specific_call == True
325
326
thread.join()
327
mock_service.assert_called_with('worker_call')
328
```