0
# Core Mocking Operations
1
2
Essential mocking functionality for patching functions, methods, and objects. These operations form the foundation of test mocking in pytest-mock, providing the primary interface for replacing real code with mock objects during testing.
3
4
## Capabilities
5
6
### Function and Method Patching
7
8
Patches functions and methods with mock objects, allowing you to control their behavior and verify their usage during tests.
9
10
```python { .api }
11
def patch(
12
self,
13
target: str,
14
new: object = DEFAULT,
15
spec: Optional[object] = None,
16
create: bool = False,
17
spec_set: Optional[object] = None,
18
autospec: Optional[object] = None,
19
new_callable: Optional[Callable] = None,
20
**kwargs: Any
21
) -> MockType:
22
"""
23
Patch a function or method with a mock object.
24
25
Parameters:
26
- target: String path to the target to patch (e.g., 'os.remove', 'mymodule.function')
27
- new: Object to replace the target with (defaults to MagicMock)
28
- spec: Object to use as template for mock attributes
29
- create: Create attribute if it doesn't exist on target
30
- spec_set: Stricter version of spec - only allows existing attributes
31
- autospec: Automatically create spec from target object
32
- new_callable: Factory function to create replacement object
33
34
Returns:
35
Mock object that replaced the target
36
"""
37
```
38
39
Usage examples:
40
41
```python
42
def test_basic_patch(mocker):
43
# Patch with default MagicMock
44
mock_remove = mocker.patch('os.remove')
45
mock_remove.return_value = None
46
47
# Your code that calls os.remove
48
delete_file('test.txt')
49
50
mock_remove.assert_called_once_with('test.txt')
51
52
def test_patch_with_return_value(mocker):
53
# Patch with specific return value
54
mocker.patch('requests.get', return_value=mock_response)
55
56
result = fetch_data('http://api.example.com')
57
assert result == expected_data
58
59
def test_patch_with_autospec(mocker):
60
# Create mock that matches the original function signature
61
mocker.patch('mymodule.complex_function', autospec=True)
62
63
# Mock will enforce correct number/types of arguments
64
mymodule.complex_function('arg1', kwarg='value')
65
```
66
67
### Object Attribute Patching
68
69
Patches specific attributes on objects, allowing targeted mocking of methods, properties, and class attributes.
70
71
```python { .api }
72
def object(
73
self,
74
target: object,
75
attribute: str,
76
new: object = DEFAULT,
77
spec: Optional[object] = None,
78
create: bool = False,
79
spec_set: Optional[object] = None,
80
autospec: Optional[object] = None,
81
new_callable: object = None,
82
**kwargs: Any
83
) -> MockType:
84
"""
85
Patch an attribute on an object with a mock.
86
87
Parameters:
88
- target: Object to patch
89
- attribute: Name of attribute to patch
90
- new: Object to replace the attribute with
91
- spec: Object to use as template for mock attributes
92
- create: Create attribute if it doesn't exist
93
- spec_set: Stricter version of spec
94
- autospec: Automatically create spec from original attribute
95
- new_callable: Factory function to create replacement
96
97
Returns:
98
Mock object that replaced the attribute
99
"""
100
```
101
102
Usage examples:
103
104
```python
105
def test_patch_method(mocker):
106
# Patch a method on a class
107
mock_send = mocker.patch.object(EmailClient, 'send')
108
mock_send.return_value = True
109
110
client = EmailClient()
111
result = client.send('test@example.com', 'Hello')
112
113
assert result is True
114
mock_send.assert_called_once_with('test@example.com', 'Hello')
115
116
def test_patch_instance_method(mocker):
117
# Patch method on specific instance
118
client = EmailClient()
119
mocker.patch.object(client, 'send', return_value=False)
120
121
result = client.send('test@example.com', 'Hello')
122
assert result is False
123
```
124
125
### Context Manager Patching
126
127
Special patching for context managers that suppresses the context manager warning typically shown by pytest-mock.
128
129
```python { .api }
130
def context_manager(
131
self,
132
target: object,
133
attribute: str,
134
new: object = DEFAULT,
135
spec: Optional[object] = None,
136
create: bool = False,
137
spec_set: Optional[object] = None,
138
autospec: Optional[object] = None,
139
new_callable: object = None,
140
**kwargs: Any
141
) -> MockType:
142
"""
143
Patch an attribute without issuing context manager warnings.
144
145
This is equivalent to patch.object except the returned mock
146
does not issue a warning when used as a context manager.
147
148
Parameters: Same as patch.object
149
150
Returns:
151
Mock object that replaced the attribute
152
"""
153
```
154
155
Usage example:
156
157
```python
158
def test_context_manager_mock(mocker):
159
# Mock a context manager without warnings
160
mock_file = mocker.context_manager(builtins, 'open')
161
mock_file.return_value.__enter__.return_value.read.return_value = 'content'
162
163
with open('file.txt') as f:
164
content = f.read()
165
166
assert content == 'content'
167
```
168
169
### Multiple Attribute Patching
170
171
Patches multiple attributes on a single object simultaneously, useful for comprehensive mocking of complex objects.
172
173
```python { .api }
174
def multiple(
175
self,
176
target: object,
177
spec: Optional[object] = None,
178
create: bool = False,
179
spec_set: Optional[object] = None,
180
autospec: Optional[object] = None,
181
new_callable: Optional[object] = None,
182
**kwargs: Any
183
) -> Dict[str, MockType]:
184
"""
185
Patch multiple attributes on a target object.
186
187
Parameters:
188
- target: Object to patch
189
- spec: Object to use as template for all mocks
190
- create: Create attributes if they don't exist
191
- spec_set: Stricter version of spec
192
- autospec: Automatically create specs
193
- new_callable: Factory function for all replacements
194
- **kwargs: attribute_name=replacement_value pairs
195
196
Returns:
197
Dictionary mapping attribute names to their mock objects
198
"""
199
```
200
201
Usage example:
202
203
```python
204
def test_multiple_patches(mocker):
205
# Patch multiple methods at once
206
mocks = mocker.patch.multiple(
207
EmailClient,
208
send=mocker.DEFAULT,
209
connect=mocker.DEFAULT,
210
disconnect=mocker.DEFAULT
211
)
212
213
# Configure individual mocks
214
mocks['send'].return_value = True
215
mocks['connect'].return_value = 'connected'
216
217
client = EmailClient()
218
client.connect()
219
result = client.send('test@example.com', 'Hello')
220
client.disconnect()
221
222
mocks['connect'].assert_called_once()
223
mocks['send'].assert_called_once()
224
mocks['disconnect'].assert_called_once()
225
```
226
227
### Dictionary Patching
228
229
Patches dictionary entries, allowing you to mock configuration, environment variables, and other dictionary-based data.
230
231
```python { .api }
232
def dict(
233
self,
234
in_dict: Union[Mapping[Any, Any], str],
235
values: Union[Mapping[Any, Any], Iterable[Tuple[Any, Any]]] = (),
236
clear: bool = False,
237
**kwargs: Any
238
) -> Any:
239
"""
240
Patch dictionary entries.
241
242
Parameters:
243
- in_dict: Dictionary to patch, or string name for module attribute
244
- values: Dictionary of key-value pairs to set, or iterable of (key, value) tuples
245
- clear: Remove all existing entries before applying patches
246
- **kwargs: Additional key-value pairs to set
247
248
Returns:
249
The patched dictionary
250
"""
251
```
252
253
Usage examples:
254
255
```python
256
def test_environment_variables(mocker):
257
# Mock environment variables
258
mocker.patch.dict('os.environ', {'API_KEY': 'test-key', 'DEBUG': 'true'})
259
260
# Your code that reads environment variables
261
api_key = get_api_key() # reads os.environ['API_KEY']
262
263
assert api_key == 'test-key'
264
265
def test_config_dict(mocker):
266
# Mock application configuration
267
test_config = {'database_url': 'sqlite:///:memory:', 'debug': True}
268
mocker.patch.dict(app.config, test_config, clear=True)
269
270
# Test code that uses app.config
271
setup_database()
272
assert app.config['database_url'] == 'sqlite:///:memory:'
273
```
274
275
### Mock Lifecycle Management
276
277
Control and cleanup mock objects to ensure tests don't interfere with each other.
278
279
```python { .api }
280
def resetall(
281
self,
282
*,
283
return_value: bool = False,
284
side_effect: bool = False
285
) -> None:
286
"""
287
Reset all mocks created by this fixture.
288
289
Parameters:
290
- return_value: Also reset return_value of mocks
291
- side_effect: Also reset side_effect of mocks
292
"""
293
294
def stopall(self) -> None:
295
"""
296
Stop all patches created by this fixture.
297
Can be safely called multiple times.
298
"""
299
300
def stop(self, mock: unittest.mock.MagicMock) -> None:
301
"""
302
Stop a specific patch by its mock object.
303
304
Parameters:
305
- mock: The mock object returned by a patch operation
306
"""
307
```
308
309
Usage examples:
310
311
```python
312
def test_manual_reset(mocker):
313
mock_func = mocker.patch('mymodule.function')
314
mock_func.return_value = 'first'
315
316
# Call and verify
317
assert mymodule.function() == 'first'
318
mock_func.assert_called_once()
319
320
# Reset the mock
321
mocker.resetall()
322
323
# Mock state is reset
324
assert mock_func.call_count == 0
325
mock_func.return_value = 'second'
326
assert mymodule.function() == 'second'
327
328
def test_manual_stop(mocker):
329
mock_func = mocker.patch('mymodule.function')
330
331
# Use the mock
332
mymodule.function()
333
334
# Stop this specific patch early
335
mocker.stop(mock_func)
336
337
# Function is back to normal
338
result = mymodule.function() # Calls real function
339
```