0
# Special Objects
1
2
The mock library provides several special objects and constants for flexible mock assertions, unique object creation, and advanced testing patterns.
3
4
## Capabilities
5
6
### ANY
7
8
A special object that equals anything, useful in mock assertions when you don't care about specific argument values.
9
10
```python { .api }
11
class _ANY:
12
def __eq__(self, other):
13
"""Always returns True, equals anything."""
14
return True
15
16
def __repr__(self):
17
"""String representation."""
18
return '<ANY>'
19
20
ANY: _ANY
21
```
22
23
### call
24
25
A factory for creating call objects that represent method calls with arguments, used in mock assertions.
26
27
```python { .api }
28
class _Call:
29
def __init__(self, *args, **kwargs):
30
"""
31
Create a call object representing a method call.
32
33
Parameters:
34
- *args: Positional arguments for the call
35
- **kwargs: Keyword arguments for the call
36
"""
37
38
def __eq__(self, other):
39
"""Compare with another call object or actual call."""
40
41
def __repr__(self):
42
"""String representation of the call."""
43
44
def call_list(self):
45
"""Return as a list of calls (for method chains)."""
46
47
call: _Call
48
```
49
50
### sentinel
51
52
A factory for creating unique sentinel objects, useful for creating distinct marker values in tests.
53
54
```python { .api }
55
class _Sentinel:
56
def __getattr__(self, name):
57
"""
58
Create a unique sentinel object for the given name.
59
60
Parameters:
61
- name: Name of the sentinel to create
62
63
Returns:
64
Unique sentinel object that only equals itself
65
"""
66
67
sentinel: _Sentinel
68
```
69
70
### DEFAULT
71
72
A special sentinel value used to represent default behavior in mock side_effect and return_value.
73
74
```python { .api }
75
DEFAULT: object # Special sentinel for default mock behavior
76
```
77
78
### FILTER_DIR
79
80
A boolean constant that controls whether dir() filtering is applied to mock objects.
81
82
```python { .api }
83
FILTER_DIR: bool # Controls dir() filtering on mocks
84
```
85
86
### InvalidSpecError
87
88
Exception raised when an invalid specification is provided to mock objects.
89
90
```python { .api }
91
class InvalidSpecError(Exception):
92
"""
93
Exception raised when an invalid value is used as a mock spec.
94
95
This exception is raised when spec or spec_set parameters
96
contain invalid specifications for mock objects.
97
"""
98
```
99
100
## Usage Patterns
101
102
### Using ANY in Assertions
103
104
```python
105
from mock import Mock, ANY
106
107
mock_func = Mock()
108
mock_func('arg1', 'arg2', kwarg='value')
109
110
# These assertions all pass
111
mock_func.assert_called_with('arg1', 'arg2', kwarg='value') # Exact match
112
mock_func.assert_called_with(ANY, 'arg2', kwarg='value') # ANY for first arg
113
mock_func.assert_called_with('arg1', ANY, kwarg=ANY) # ANY for multiple args
114
mock_func.assert_called_with(ANY, ANY, kwarg=ANY) # ANY for all args
115
```
116
117
### ANY with Complex Objects
118
119
```python
120
from mock import Mock, ANY
121
122
mock_func = Mock()
123
mock_func([1, 2, 3], {'key': 'value'}, some_object)
124
125
# Don't care about specific list contents or dict contents
126
mock_func.assert_called_with(ANY, ANY, some_object)
127
128
# Mix ANY with specific values
129
mock_func.assert_called_with([1, 2, 3], ANY, ANY)
130
```
131
132
### Using call Objects
133
134
```python
135
from mock import Mock, call
136
137
mock_obj = Mock()
138
mock_obj.method('arg1')
139
mock_obj.method('arg2', kwarg='value')
140
mock_obj.other_method()
141
142
# Check specific calls
143
expected_calls = [
144
call.method('arg1'),
145
call.method('arg2', kwarg='value'),
146
call.other_method()
147
]
148
mock_obj.assert_has_calls(expected_calls)
149
150
# Check calls in any order
151
mock_obj.assert_has_calls(expected_calls, any_order=True)
152
```
153
154
### Call Objects for Direct Function Calls
155
156
```python
157
from mock import Mock, call
158
159
mock_func = Mock()
160
mock_func('first', 'call')
161
mock_func('second', kwarg='call')
162
163
# Represent direct function calls
164
expected_calls = [
165
call('first', 'call'),
166
call('second', kwarg='call')
167
]
168
mock_func.assert_has_calls(expected_calls)
169
```
170
171
### Using sentinel Objects
172
173
```python
174
from mock import sentinel
175
176
# Create unique sentinel values
177
UNIQUE_VALUE = sentinel.UNIQUE_VALUE
178
ANOTHER_VALUE = sentinel.ANOTHER_VALUE
179
MISSING = sentinel.MISSING
180
181
# Sentinels are only equal to themselves
182
assert UNIQUE_VALUE == sentinel.UNIQUE_VALUE
183
assert UNIQUE_VALUE != ANOTHER_VALUE
184
assert UNIQUE_VALUE != 'anything else'
185
186
# Useful for default parameters and special values
187
def function_with_default(arg=sentinel.DEFAULT):
188
if arg is sentinel.DEFAULT:
189
return 'no argument provided'
190
return f'argument was: {arg}'
191
192
assert function_with_default() == 'no argument provided'
193
assert function_with_default('value') == 'argument was: value'
194
```
195
196
### Sentinel for Mock Configuration
197
198
```python
199
from mock import Mock, sentinel
200
201
# Use sentinels as distinctive return values
202
mock_obj = Mock()
203
mock_obj.method1.return_value = sentinel.METHOD1_RESULT
204
mock_obj.method2.return_value = sentinel.METHOD2_RESULT
205
206
result1 = mock_obj.method1()
207
result2 = mock_obj.method2()
208
209
assert result1 is sentinel.METHOD1_RESULT
210
assert result2 is sentinel.METHOD2_RESULT
211
assert result1 != result2
212
```
213
214
### Using DEFAULT with side_effect
215
216
```python
217
from mock import Mock, DEFAULT
218
219
def side_effect_func(*args, **kwargs):
220
if args[0] == 'special':
221
return 'special handling'
222
return DEFAULT # Use default mock behavior
223
224
mock_func = Mock(return_value='default result')
225
mock_func.side_effect = side_effect_func
226
227
# Special case uses side_effect
228
result1 = mock_func('special')
229
assert result1 == 'special handling'
230
231
# Other cases use default return_value
232
result2 = mock_func('normal')
233
assert result2 == 'default result'
234
```
235
236
### Complex Assertion Patterns
237
238
```python
239
from mock import Mock, call, ANY
240
241
class TestService:
242
def __init__(self):
243
self.api = Mock()
244
245
def process_items(self, items):
246
for item in items:
247
self.api.process(item['id'], item['data'], timestamp=ANY)
248
if item.get('urgent'):
249
self.api.notify('urgent', item['id'])
250
251
# Test the service
252
service = TestService()
253
items = [
254
{'id': 1, 'data': 'test1'},
255
{'id': 2, 'data': 'test2', 'urgent': True}
256
]
257
service.process_items(items)
258
259
# Verify all expected calls were made
260
expected_calls = [
261
call.process(1, 'test1', timestamp=ANY),
262
call.process(2, 'test2', timestamp=ANY),
263
call.notify('urgent', 2)
264
]
265
service.api.assert_has_calls(expected_calls)
266
```
267
268
### Combining Special Objects
269
270
```python
271
from mock import Mock, call, ANY, sentinel
272
273
mock_service = Mock()
274
275
# Use sentinel for unique values and ANY for flexible matching
276
PROCESSING_STATE = sentinel.PROCESSING
277
COMPLETED_STATE = sentinel.COMPLETED
278
279
mock_service.update_status(item_id=123, status=PROCESSING_STATE, metadata=ANY)
280
mock_service.update_status(item_id=123, status=COMPLETED_STATE, result='success')
281
282
expected_calls = [
283
call.update_status(item_id=123, status=PROCESSING_STATE, metadata=ANY),
284
call.update_status(item_id=123, status=COMPLETED_STATE, result='success')
285
]
286
mock_service.assert_has_calls(expected_calls)
287
```
288
289
### FILTER_DIR Usage
290
291
```python
292
from mock import Mock, FILTER_DIR
293
294
# Control dir() behavior on mocks
295
original_filter = FILTER_DIR
296
297
# Disable filtering to see all mock attributes
298
FILTER_DIR = False
299
mock_obj = Mock()
300
all_attrs = dir(mock_obj) # Shows internal mock attributes
301
302
# Re-enable filtering for cleaner dir() output
303
FILTER_DIR = True
304
clean_attrs = dir(mock_obj) # Shows only user-defined attributes
305
306
# Restore original setting
307
FILTER_DIR = original_filter
308
```