jpayne@68
|
1 # mock.py
|
jpayne@68
|
2 # Test tools for mocking and patching.
|
jpayne@68
|
3 # Maintained by Michael Foord
|
jpayne@68
|
4 # Backport for other versions of Python available from
|
jpayne@68
|
5 # https://pypi.org/project/mock
|
jpayne@68
|
6
|
jpayne@68
|
7 __all__ = (
|
jpayne@68
|
8 'Mock',
|
jpayne@68
|
9 'MagicMock',
|
jpayne@68
|
10 'patch',
|
jpayne@68
|
11 'sentinel',
|
jpayne@68
|
12 'DEFAULT',
|
jpayne@68
|
13 'ANY',
|
jpayne@68
|
14 'call',
|
jpayne@68
|
15 'create_autospec',
|
jpayne@68
|
16 'AsyncMock',
|
jpayne@68
|
17 'FILTER_DIR',
|
jpayne@68
|
18 'NonCallableMock',
|
jpayne@68
|
19 'NonCallableMagicMock',
|
jpayne@68
|
20 'mock_open',
|
jpayne@68
|
21 'PropertyMock',
|
jpayne@68
|
22 'seal',
|
jpayne@68
|
23 )
|
jpayne@68
|
24
|
jpayne@68
|
25
|
jpayne@68
|
26 __version__ = '1.0'
|
jpayne@68
|
27
|
jpayne@68
|
28 import asyncio
|
jpayne@68
|
29 import contextlib
|
jpayne@68
|
30 import io
|
jpayne@68
|
31 import inspect
|
jpayne@68
|
32 import pprint
|
jpayne@68
|
33 import sys
|
jpayne@68
|
34 import builtins
|
jpayne@68
|
35 from types import CodeType, ModuleType, MethodType
|
jpayne@68
|
36 from unittest.util import safe_repr
|
jpayne@68
|
37 from functools import wraps, partial
|
jpayne@68
|
38
|
jpayne@68
|
39
|
jpayne@68
|
40 _builtins = {name for name in dir(builtins) if not name.startswith('_')}
|
jpayne@68
|
41
|
jpayne@68
|
42 FILTER_DIR = True
|
jpayne@68
|
43
|
jpayne@68
|
44 # Workaround for issue #12370
|
jpayne@68
|
45 # Without this, the __class__ properties wouldn't be set correctly
|
jpayne@68
|
46 _safe_super = super
|
jpayne@68
|
47
|
jpayne@68
|
48 def _is_async_obj(obj):
|
jpayne@68
|
49 if _is_instance_mock(obj) and not isinstance(obj, AsyncMock):
|
jpayne@68
|
50 return False
|
jpayne@68
|
51 return asyncio.iscoroutinefunction(obj) or inspect.isawaitable(obj)
|
jpayne@68
|
52
|
jpayne@68
|
53
|
jpayne@68
|
54 def _is_async_func(func):
|
jpayne@68
|
55 if getattr(func, '__code__', None):
|
jpayne@68
|
56 return asyncio.iscoroutinefunction(func)
|
jpayne@68
|
57 else:
|
jpayne@68
|
58 return False
|
jpayne@68
|
59
|
jpayne@68
|
60
|
jpayne@68
|
61 def _is_instance_mock(obj):
|
jpayne@68
|
62 # can't use isinstance on Mock objects because they override __class__
|
jpayne@68
|
63 # The base class for all mocks is NonCallableMock
|
jpayne@68
|
64 return issubclass(type(obj), NonCallableMock)
|
jpayne@68
|
65
|
jpayne@68
|
66
|
jpayne@68
|
67 def _is_exception(obj):
|
jpayne@68
|
68 return (
|
jpayne@68
|
69 isinstance(obj, BaseException) or
|
jpayne@68
|
70 isinstance(obj, type) and issubclass(obj, BaseException)
|
jpayne@68
|
71 )
|
jpayne@68
|
72
|
jpayne@68
|
73
|
jpayne@68
|
74 def _extract_mock(obj):
|
jpayne@68
|
75 # Autospecced functions will return a FunctionType with "mock" attribute
|
jpayne@68
|
76 # which is the actual mock object that needs to be used.
|
jpayne@68
|
77 if isinstance(obj, FunctionTypes) and hasattr(obj, 'mock'):
|
jpayne@68
|
78 return obj.mock
|
jpayne@68
|
79 else:
|
jpayne@68
|
80 return obj
|
jpayne@68
|
81
|
jpayne@68
|
82
|
jpayne@68
|
83 def _get_signature_object(func, as_instance, eat_self):
|
jpayne@68
|
84 """
|
jpayne@68
|
85 Given an arbitrary, possibly callable object, try to create a suitable
|
jpayne@68
|
86 signature object.
|
jpayne@68
|
87 Return a (reduced func, signature) tuple, or None.
|
jpayne@68
|
88 """
|
jpayne@68
|
89 if isinstance(func, type) and not as_instance:
|
jpayne@68
|
90 # If it's a type and should be modelled as a type, use __init__.
|
jpayne@68
|
91 func = func.__init__
|
jpayne@68
|
92 # Skip the `self` argument in __init__
|
jpayne@68
|
93 eat_self = True
|
jpayne@68
|
94 elif not isinstance(func, FunctionTypes):
|
jpayne@68
|
95 # If we really want to model an instance of the passed type,
|
jpayne@68
|
96 # __call__ should be looked up, not __init__.
|
jpayne@68
|
97 try:
|
jpayne@68
|
98 func = func.__call__
|
jpayne@68
|
99 except AttributeError:
|
jpayne@68
|
100 return None
|
jpayne@68
|
101 if eat_self:
|
jpayne@68
|
102 sig_func = partial(func, None)
|
jpayne@68
|
103 else:
|
jpayne@68
|
104 sig_func = func
|
jpayne@68
|
105 try:
|
jpayne@68
|
106 return func, inspect.signature(sig_func)
|
jpayne@68
|
107 except ValueError:
|
jpayne@68
|
108 # Certain callable types are not supported by inspect.signature()
|
jpayne@68
|
109 return None
|
jpayne@68
|
110
|
jpayne@68
|
111
|
jpayne@68
|
112 def _check_signature(func, mock, skipfirst, instance=False):
|
jpayne@68
|
113 sig = _get_signature_object(func, instance, skipfirst)
|
jpayne@68
|
114 if sig is None:
|
jpayne@68
|
115 return
|
jpayne@68
|
116 func, sig = sig
|
jpayne@68
|
117 def checksig(self, /, *args, **kwargs):
|
jpayne@68
|
118 sig.bind(*args, **kwargs)
|
jpayne@68
|
119 _copy_func_details(func, checksig)
|
jpayne@68
|
120 type(mock)._mock_check_sig = checksig
|
jpayne@68
|
121 type(mock).__signature__ = sig
|
jpayne@68
|
122
|
jpayne@68
|
123
|
jpayne@68
|
124 def _copy_func_details(func, funcopy):
|
jpayne@68
|
125 # we explicitly don't copy func.__dict__ into this copy as it would
|
jpayne@68
|
126 # expose original attributes that should be mocked
|
jpayne@68
|
127 for attribute in (
|
jpayne@68
|
128 '__name__', '__doc__', '__text_signature__',
|
jpayne@68
|
129 '__module__', '__defaults__', '__kwdefaults__',
|
jpayne@68
|
130 ):
|
jpayne@68
|
131 try:
|
jpayne@68
|
132 setattr(funcopy, attribute, getattr(func, attribute))
|
jpayne@68
|
133 except AttributeError:
|
jpayne@68
|
134 pass
|
jpayne@68
|
135
|
jpayne@68
|
136
|
jpayne@68
|
137 def _callable(obj):
|
jpayne@68
|
138 if isinstance(obj, type):
|
jpayne@68
|
139 return True
|
jpayne@68
|
140 if isinstance(obj, (staticmethod, classmethod, MethodType)):
|
jpayne@68
|
141 return _callable(obj.__func__)
|
jpayne@68
|
142 if getattr(obj, '__call__', None) is not None:
|
jpayne@68
|
143 return True
|
jpayne@68
|
144 return False
|
jpayne@68
|
145
|
jpayne@68
|
146
|
jpayne@68
|
147 def _is_list(obj):
|
jpayne@68
|
148 # checks for list or tuples
|
jpayne@68
|
149 # XXXX badly named!
|
jpayne@68
|
150 return type(obj) in (list, tuple)
|
jpayne@68
|
151
|
jpayne@68
|
152
|
jpayne@68
|
153 def _instance_callable(obj):
|
jpayne@68
|
154 """Given an object, return True if the object is callable.
|
jpayne@68
|
155 For classes, return True if instances would be callable."""
|
jpayne@68
|
156 if not isinstance(obj, type):
|
jpayne@68
|
157 # already an instance
|
jpayne@68
|
158 return getattr(obj, '__call__', None) is not None
|
jpayne@68
|
159
|
jpayne@68
|
160 # *could* be broken by a class overriding __mro__ or __dict__ via
|
jpayne@68
|
161 # a metaclass
|
jpayne@68
|
162 for base in (obj,) + obj.__mro__:
|
jpayne@68
|
163 if base.__dict__.get('__call__') is not None:
|
jpayne@68
|
164 return True
|
jpayne@68
|
165 return False
|
jpayne@68
|
166
|
jpayne@68
|
167
|
jpayne@68
|
168 def _set_signature(mock, original, instance=False):
|
jpayne@68
|
169 # creates a function with signature (*args, **kwargs) that delegates to a
|
jpayne@68
|
170 # mock. It still does signature checking by calling a lambda with the same
|
jpayne@68
|
171 # signature as the original.
|
jpayne@68
|
172
|
jpayne@68
|
173 skipfirst = isinstance(original, type)
|
jpayne@68
|
174 result = _get_signature_object(original, instance, skipfirst)
|
jpayne@68
|
175 if result is None:
|
jpayne@68
|
176 return mock
|
jpayne@68
|
177 func, sig = result
|
jpayne@68
|
178 def checksig(*args, **kwargs):
|
jpayne@68
|
179 sig.bind(*args, **kwargs)
|
jpayne@68
|
180 _copy_func_details(func, checksig)
|
jpayne@68
|
181
|
jpayne@68
|
182 name = original.__name__
|
jpayne@68
|
183 if not name.isidentifier():
|
jpayne@68
|
184 name = 'funcopy'
|
jpayne@68
|
185 context = {'_checksig_': checksig, 'mock': mock}
|
jpayne@68
|
186 src = """def %s(*args, **kwargs):
|
jpayne@68
|
187 _checksig_(*args, **kwargs)
|
jpayne@68
|
188 return mock(*args, **kwargs)""" % name
|
jpayne@68
|
189 exec (src, context)
|
jpayne@68
|
190 funcopy = context[name]
|
jpayne@68
|
191 _setup_func(funcopy, mock, sig)
|
jpayne@68
|
192 return funcopy
|
jpayne@68
|
193
|
jpayne@68
|
194
|
jpayne@68
|
195 def _setup_func(funcopy, mock, sig):
|
jpayne@68
|
196 funcopy.mock = mock
|
jpayne@68
|
197
|
jpayne@68
|
198 def assert_called_with(*args, **kwargs):
|
jpayne@68
|
199 return mock.assert_called_with(*args, **kwargs)
|
jpayne@68
|
200 def assert_called(*args, **kwargs):
|
jpayne@68
|
201 return mock.assert_called(*args, **kwargs)
|
jpayne@68
|
202 def assert_not_called(*args, **kwargs):
|
jpayne@68
|
203 return mock.assert_not_called(*args, **kwargs)
|
jpayne@68
|
204 def assert_called_once(*args, **kwargs):
|
jpayne@68
|
205 return mock.assert_called_once(*args, **kwargs)
|
jpayne@68
|
206 def assert_called_once_with(*args, **kwargs):
|
jpayne@68
|
207 return mock.assert_called_once_with(*args, **kwargs)
|
jpayne@68
|
208 def assert_has_calls(*args, **kwargs):
|
jpayne@68
|
209 return mock.assert_has_calls(*args, **kwargs)
|
jpayne@68
|
210 def assert_any_call(*args, **kwargs):
|
jpayne@68
|
211 return mock.assert_any_call(*args, **kwargs)
|
jpayne@68
|
212 def reset_mock():
|
jpayne@68
|
213 funcopy.method_calls = _CallList()
|
jpayne@68
|
214 funcopy.mock_calls = _CallList()
|
jpayne@68
|
215 mock.reset_mock()
|
jpayne@68
|
216 ret = funcopy.return_value
|
jpayne@68
|
217 if _is_instance_mock(ret) and not ret is mock:
|
jpayne@68
|
218 ret.reset_mock()
|
jpayne@68
|
219
|
jpayne@68
|
220 funcopy.called = False
|
jpayne@68
|
221 funcopy.call_count = 0
|
jpayne@68
|
222 funcopy.call_args = None
|
jpayne@68
|
223 funcopy.call_args_list = _CallList()
|
jpayne@68
|
224 funcopy.method_calls = _CallList()
|
jpayne@68
|
225 funcopy.mock_calls = _CallList()
|
jpayne@68
|
226
|
jpayne@68
|
227 funcopy.return_value = mock.return_value
|
jpayne@68
|
228 funcopy.side_effect = mock.side_effect
|
jpayne@68
|
229 funcopy._mock_children = mock._mock_children
|
jpayne@68
|
230
|
jpayne@68
|
231 funcopy.assert_called_with = assert_called_with
|
jpayne@68
|
232 funcopy.assert_called_once_with = assert_called_once_with
|
jpayne@68
|
233 funcopy.assert_has_calls = assert_has_calls
|
jpayne@68
|
234 funcopy.assert_any_call = assert_any_call
|
jpayne@68
|
235 funcopy.reset_mock = reset_mock
|
jpayne@68
|
236 funcopy.assert_called = assert_called
|
jpayne@68
|
237 funcopy.assert_not_called = assert_not_called
|
jpayne@68
|
238 funcopy.assert_called_once = assert_called_once
|
jpayne@68
|
239 funcopy.__signature__ = sig
|
jpayne@68
|
240
|
jpayne@68
|
241 mock._mock_delegate = funcopy
|
jpayne@68
|
242
|
jpayne@68
|
243
|
jpayne@68
|
244 def _setup_async_mock(mock):
|
jpayne@68
|
245 mock._is_coroutine = asyncio.coroutines._is_coroutine
|
jpayne@68
|
246 mock.await_count = 0
|
jpayne@68
|
247 mock.await_args = None
|
jpayne@68
|
248 mock.await_args_list = _CallList()
|
jpayne@68
|
249
|
jpayne@68
|
250 # Mock is not configured yet so the attributes are set
|
jpayne@68
|
251 # to a function and then the corresponding mock helper function
|
jpayne@68
|
252 # is called when the helper is accessed similar to _setup_func.
|
jpayne@68
|
253 def wrapper(attr, /, *args, **kwargs):
|
jpayne@68
|
254 return getattr(mock.mock, attr)(*args, **kwargs)
|
jpayne@68
|
255
|
jpayne@68
|
256 for attribute in ('assert_awaited',
|
jpayne@68
|
257 'assert_awaited_once',
|
jpayne@68
|
258 'assert_awaited_with',
|
jpayne@68
|
259 'assert_awaited_once_with',
|
jpayne@68
|
260 'assert_any_await',
|
jpayne@68
|
261 'assert_has_awaits',
|
jpayne@68
|
262 'assert_not_awaited'):
|
jpayne@68
|
263
|
jpayne@68
|
264 # setattr(mock, attribute, wrapper) causes late binding
|
jpayne@68
|
265 # hence attribute will always be the last value in the loop
|
jpayne@68
|
266 # Use partial(wrapper, attribute) to ensure the attribute is bound
|
jpayne@68
|
267 # correctly.
|
jpayne@68
|
268 setattr(mock, attribute, partial(wrapper, attribute))
|
jpayne@68
|
269
|
jpayne@68
|
270
|
jpayne@68
|
271 def _is_magic(name):
|
jpayne@68
|
272 return '__%s__' % name[2:-2] == name
|
jpayne@68
|
273
|
jpayne@68
|
274
|
jpayne@68
|
275 class _SentinelObject(object):
|
jpayne@68
|
276 "A unique, named, sentinel object."
|
jpayne@68
|
277 def __init__(self, name):
|
jpayne@68
|
278 self.name = name
|
jpayne@68
|
279
|
jpayne@68
|
280 def __repr__(self):
|
jpayne@68
|
281 return 'sentinel.%s' % self.name
|
jpayne@68
|
282
|
jpayne@68
|
283 def __reduce__(self):
|
jpayne@68
|
284 return 'sentinel.%s' % self.name
|
jpayne@68
|
285
|
jpayne@68
|
286
|
jpayne@68
|
287 class _Sentinel(object):
|
jpayne@68
|
288 """Access attributes to return a named object, usable as a sentinel."""
|
jpayne@68
|
289 def __init__(self):
|
jpayne@68
|
290 self._sentinels = {}
|
jpayne@68
|
291
|
jpayne@68
|
292 def __getattr__(self, name):
|
jpayne@68
|
293 if name == '__bases__':
|
jpayne@68
|
294 # Without this help(unittest.mock) raises an exception
|
jpayne@68
|
295 raise AttributeError
|
jpayne@68
|
296 return self._sentinels.setdefault(name, _SentinelObject(name))
|
jpayne@68
|
297
|
jpayne@68
|
298 def __reduce__(self):
|
jpayne@68
|
299 return 'sentinel'
|
jpayne@68
|
300
|
jpayne@68
|
301
|
jpayne@68
|
302 sentinel = _Sentinel()
|
jpayne@68
|
303
|
jpayne@68
|
304 DEFAULT = sentinel.DEFAULT
|
jpayne@68
|
305 _missing = sentinel.MISSING
|
jpayne@68
|
306 _deleted = sentinel.DELETED
|
jpayne@68
|
307
|
jpayne@68
|
308
|
jpayne@68
|
309 _allowed_names = {
|
jpayne@68
|
310 'return_value', '_mock_return_value', 'side_effect',
|
jpayne@68
|
311 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
|
jpayne@68
|
312 '_mock_name', '_mock_new_name'
|
jpayne@68
|
313 }
|
jpayne@68
|
314
|
jpayne@68
|
315
|
jpayne@68
|
316 def _delegating_property(name):
|
jpayne@68
|
317 _allowed_names.add(name)
|
jpayne@68
|
318 _the_name = '_mock_' + name
|
jpayne@68
|
319 def _get(self, name=name, _the_name=_the_name):
|
jpayne@68
|
320 sig = self._mock_delegate
|
jpayne@68
|
321 if sig is None:
|
jpayne@68
|
322 return getattr(self, _the_name)
|
jpayne@68
|
323 return getattr(sig, name)
|
jpayne@68
|
324 def _set(self, value, name=name, _the_name=_the_name):
|
jpayne@68
|
325 sig = self._mock_delegate
|
jpayne@68
|
326 if sig is None:
|
jpayne@68
|
327 self.__dict__[_the_name] = value
|
jpayne@68
|
328 else:
|
jpayne@68
|
329 setattr(sig, name, value)
|
jpayne@68
|
330
|
jpayne@68
|
331 return property(_get, _set)
|
jpayne@68
|
332
|
jpayne@68
|
333
|
jpayne@68
|
334
|
jpayne@68
|
335 class _CallList(list):
|
jpayne@68
|
336
|
jpayne@68
|
337 def __contains__(self, value):
|
jpayne@68
|
338 if not isinstance(value, list):
|
jpayne@68
|
339 return list.__contains__(self, value)
|
jpayne@68
|
340 len_value = len(value)
|
jpayne@68
|
341 len_self = len(self)
|
jpayne@68
|
342 if len_value > len_self:
|
jpayne@68
|
343 return False
|
jpayne@68
|
344
|
jpayne@68
|
345 for i in range(0, len_self - len_value + 1):
|
jpayne@68
|
346 sub_list = self[i:i+len_value]
|
jpayne@68
|
347 if sub_list == value:
|
jpayne@68
|
348 return True
|
jpayne@68
|
349 return False
|
jpayne@68
|
350
|
jpayne@68
|
351 def __repr__(self):
|
jpayne@68
|
352 return pprint.pformat(list(self))
|
jpayne@68
|
353
|
jpayne@68
|
354
|
jpayne@68
|
355 def _check_and_set_parent(parent, value, name, new_name):
|
jpayne@68
|
356 value = _extract_mock(value)
|
jpayne@68
|
357
|
jpayne@68
|
358 if not _is_instance_mock(value):
|
jpayne@68
|
359 return False
|
jpayne@68
|
360 if ((value._mock_name or value._mock_new_name) or
|
jpayne@68
|
361 (value._mock_parent is not None) or
|
jpayne@68
|
362 (value._mock_new_parent is not None)):
|
jpayne@68
|
363 return False
|
jpayne@68
|
364
|
jpayne@68
|
365 _parent = parent
|
jpayne@68
|
366 while _parent is not None:
|
jpayne@68
|
367 # setting a mock (value) as a child or return value of itself
|
jpayne@68
|
368 # should not modify the mock
|
jpayne@68
|
369 if _parent is value:
|
jpayne@68
|
370 return False
|
jpayne@68
|
371 _parent = _parent._mock_new_parent
|
jpayne@68
|
372
|
jpayne@68
|
373 if new_name:
|
jpayne@68
|
374 value._mock_new_parent = parent
|
jpayne@68
|
375 value._mock_new_name = new_name
|
jpayne@68
|
376 if name:
|
jpayne@68
|
377 value._mock_parent = parent
|
jpayne@68
|
378 value._mock_name = name
|
jpayne@68
|
379 return True
|
jpayne@68
|
380
|
jpayne@68
|
381 # Internal class to identify if we wrapped an iterator object or not.
|
jpayne@68
|
382 class _MockIter(object):
|
jpayne@68
|
383 def __init__(self, obj):
|
jpayne@68
|
384 self.obj = iter(obj)
|
jpayne@68
|
385 def __next__(self):
|
jpayne@68
|
386 return next(self.obj)
|
jpayne@68
|
387
|
jpayne@68
|
388 class Base(object):
|
jpayne@68
|
389 _mock_return_value = DEFAULT
|
jpayne@68
|
390 _mock_side_effect = None
|
jpayne@68
|
391 def __init__(self, /, *args, **kwargs):
|
jpayne@68
|
392 pass
|
jpayne@68
|
393
|
jpayne@68
|
394
|
jpayne@68
|
395
|
jpayne@68
|
396 class NonCallableMock(Base):
|
jpayne@68
|
397 """A non-callable version of `Mock`"""
|
jpayne@68
|
398
|
jpayne@68
|
399 def __new__(cls, /, *args, **kw):
|
jpayne@68
|
400 # every instance has its own class
|
jpayne@68
|
401 # so we can create magic methods on the
|
jpayne@68
|
402 # class without stomping on other mocks
|
jpayne@68
|
403 bases = (cls,)
|
jpayne@68
|
404 if not issubclass(cls, AsyncMock):
|
jpayne@68
|
405 # Check if spec is an async object or function
|
jpayne@68
|
406 sig = inspect.signature(NonCallableMock.__init__)
|
jpayne@68
|
407 bound_args = sig.bind_partial(cls, *args, **kw).arguments
|
jpayne@68
|
408 spec_arg = [
|
jpayne@68
|
409 arg for arg in bound_args.keys()
|
jpayne@68
|
410 if arg.startswith('spec')
|
jpayne@68
|
411 ]
|
jpayne@68
|
412 if spec_arg:
|
jpayne@68
|
413 # what if spec_set is different than spec?
|
jpayne@68
|
414 if _is_async_obj(bound_args[spec_arg[0]]):
|
jpayne@68
|
415 bases = (AsyncMockMixin, cls,)
|
jpayne@68
|
416 new = type(cls.__name__, bases, {'__doc__': cls.__doc__})
|
jpayne@68
|
417 instance = _safe_super(NonCallableMock, cls).__new__(new)
|
jpayne@68
|
418 return instance
|
jpayne@68
|
419
|
jpayne@68
|
420
|
jpayne@68
|
421 def __init__(
|
jpayne@68
|
422 self, spec=None, wraps=None, name=None, spec_set=None,
|
jpayne@68
|
423 parent=None, _spec_state=None, _new_name='', _new_parent=None,
|
jpayne@68
|
424 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
|
jpayne@68
|
425 ):
|
jpayne@68
|
426 if _new_parent is None:
|
jpayne@68
|
427 _new_parent = parent
|
jpayne@68
|
428
|
jpayne@68
|
429 __dict__ = self.__dict__
|
jpayne@68
|
430 __dict__['_mock_parent'] = parent
|
jpayne@68
|
431 __dict__['_mock_name'] = name
|
jpayne@68
|
432 __dict__['_mock_new_name'] = _new_name
|
jpayne@68
|
433 __dict__['_mock_new_parent'] = _new_parent
|
jpayne@68
|
434 __dict__['_mock_sealed'] = False
|
jpayne@68
|
435
|
jpayne@68
|
436 if spec_set is not None:
|
jpayne@68
|
437 spec = spec_set
|
jpayne@68
|
438 spec_set = True
|
jpayne@68
|
439 if _eat_self is None:
|
jpayne@68
|
440 _eat_self = parent is not None
|
jpayne@68
|
441
|
jpayne@68
|
442 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
|
jpayne@68
|
443
|
jpayne@68
|
444 __dict__['_mock_children'] = {}
|
jpayne@68
|
445 __dict__['_mock_wraps'] = wraps
|
jpayne@68
|
446 __dict__['_mock_delegate'] = None
|
jpayne@68
|
447
|
jpayne@68
|
448 __dict__['_mock_called'] = False
|
jpayne@68
|
449 __dict__['_mock_call_args'] = None
|
jpayne@68
|
450 __dict__['_mock_call_count'] = 0
|
jpayne@68
|
451 __dict__['_mock_call_args_list'] = _CallList()
|
jpayne@68
|
452 __dict__['_mock_mock_calls'] = _CallList()
|
jpayne@68
|
453
|
jpayne@68
|
454 __dict__['method_calls'] = _CallList()
|
jpayne@68
|
455 __dict__['_mock_unsafe'] = unsafe
|
jpayne@68
|
456
|
jpayne@68
|
457 if kwargs:
|
jpayne@68
|
458 self.configure_mock(**kwargs)
|
jpayne@68
|
459
|
jpayne@68
|
460 _safe_super(NonCallableMock, self).__init__(
|
jpayne@68
|
461 spec, wraps, name, spec_set, parent,
|
jpayne@68
|
462 _spec_state
|
jpayne@68
|
463 )
|
jpayne@68
|
464
|
jpayne@68
|
465
|
jpayne@68
|
466 def attach_mock(self, mock, attribute):
|
jpayne@68
|
467 """
|
jpayne@68
|
468 Attach a mock as an attribute of this one, replacing its name and
|
jpayne@68
|
469 parent. Calls to the attached mock will be recorded in the
|
jpayne@68
|
470 `method_calls` and `mock_calls` attributes of this one."""
|
jpayne@68
|
471 inner_mock = _extract_mock(mock)
|
jpayne@68
|
472
|
jpayne@68
|
473 inner_mock._mock_parent = None
|
jpayne@68
|
474 inner_mock._mock_new_parent = None
|
jpayne@68
|
475 inner_mock._mock_name = ''
|
jpayne@68
|
476 inner_mock._mock_new_name = None
|
jpayne@68
|
477
|
jpayne@68
|
478 setattr(self, attribute, mock)
|
jpayne@68
|
479
|
jpayne@68
|
480
|
jpayne@68
|
481 def mock_add_spec(self, spec, spec_set=False):
|
jpayne@68
|
482 """Add a spec to a mock. `spec` can either be an object or a
|
jpayne@68
|
483 list of strings. Only attributes on the `spec` can be fetched as
|
jpayne@68
|
484 attributes from the mock.
|
jpayne@68
|
485
|
jpayne@68
|
486 If `spec_set` is True then only attributes on the spec can be set."""
|
jpayne@68
|
487 self._mock_add_spec(spec, spec_set)
|
jpayne@68
|
488
|
jpayne@68
|
489
|
jpayne@68
|
490 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
|
jpayne@68
|
491 _eat_self=False):
|
jpayne@68
|
492 _spec_class = None
|
jpayne@68
|
493 _spec_signature = None
|
jpayne@68
|
494 _spec_asyncs = []
|
jpayne@68
|
495
|
jpayne@68
|
496 for attr in dir(spec):
|
jpayne@68
|
497 if asyncio.iscoroutinefunction(getattr(spec, attr, None)):
|
jpayne@68
|
498 _spec_asyncs.append(attr)
|
jpayne@68
|
499
|
jpayne@68
|
500 if spec is not None and not _is_list(spec):
|
jpayne@68
|
501 if isinstance(spec, type):
|
jpayne@68
|
502 _spec_class = spec
|
jpayne@68
|
503 else:
|
jpayne@68
|
504 _spec_class = type(spec)
|
jpayne@68
|
505 res = _get_signature_object(spec,
|
jpayne@68
|
506 _spec_as_instance, _eat_self)
|
jpayne@68
|
507 _spec_signature = res and res[1]
|
jpayne@68
|
508
|
jpayne@68
|
509 spec = dir(spec)
|
jpayne@68
|
510
|
jpayne@68
|
511 __dict__ = self.__dict__
|
jpayne@68
|
512 __dict__['_spec_class'] = _spec_class
|
jpayne@68
|
513 __dict__['_spec_set'] = spec_set
|
jpayne@68
|
514 __dict__['_spec_signature'] = _spec_signature
|
jpayne@68
|
515 __dict__['_mock_methods'] = spec
|
jpayne@68
|
516 __dict__['_spec_asyncs'] = _spec_asyncs
|
jpayne@68
|
517
|
jpayne@68
|
518 def __get_return_value(self):
|
jpayne@68
|
519 ret = self._mock_return_value
|
jpayne@68
|
520 if self._mock_delegate is not None:
|
jpayne@68
|
521 ret = self._mock_delegate.return_value
|
jpayne@68
|
522
|
jpayne@68
|
523 if ret is DEFAULT:
|
jpayne@68
|
524 ret = self._get_child_mock(
|
jpayne@68
|
525 _new_parent=self, _new_name='()'
|
jpayne@68
|
526 )
|
jpayne@68
|
527 self.return_value = ret
|
jpayne@68
|
528 return ret
|
jpayne@68
|
529
|
jpayne@68
|
530
|
jpayne@68
|
531 def __set_return_value(self, value):
|
jpayne@68
|
532 if self._mock_delegate is not None:
|
jpayne@68
|
533 self._mock_delegate.return_value = value
|
jpayne@68
|
534 else:
|
jpayne@68
|
535 self._mock_return_value = value
|
jpayne@68
|
536 _check_and_set_parent(self, value, None, '()')
|
jpayne@68
|
537
|
jpayne@68
|
538 __return_value_doc = "The value to be returned when the mock is called."
|
jpayne@68
|
539 return_value = property(__get_return_value, __set_return_value,
|
jpayne@68
|
540 __return_value_doc)
|
jpayne@68
|
541
|
jpayne@68
|
542
|
jpayne@68
|
543 @property
|
jpayne@68
|
544 def __class__(self):
|
jpayne@68
|
545 if self._spec_class is None:
|
jpayne@68
|
546 return type(self)
|
jpayne@68
|
547 return self._spec_class
|
jpayne@68
|
548
|
jpayne@68
|
549 called = _delegating_property('called')
|
jpayne@68
|
550 call_count = _delegating_property('call_count')
|
jpayne@68
|
551 call_args = _delegating_property('call_args')
|
jpayne@68
|
552 call_args_list = _delegating_property('call_args_list')
|
jpayne@68
|
553 mock_calls = _delegating_property('mock_calls')
|
jpayne@68
|
554
|
jpayne@68
|
555
|
jpayne@68
|
556 def __get_side_effect(self):
|
jpayne@68
|
557 delegated = self._mock_delegate
|
jpayne@68
|
558 if delegated is None:
|
jpayne@68
|
559 return self._mock_side_effect
|
jpayne@68
|
560 sf = delegated.side_effect
|
jpayne@68
|
561 if (sf is not None and not callable(sf)
|
jpayne@68
|
562 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
|
jpayne@68
|
563 sf = _MockIter(sf)
|
jpayne@68
|
564 delegated.side_effect = sf
|
jpayne@68
|
565 return sf
|
jpayne@68
|
566
|
jpayne@68
|
567 def __set_side_effect(self, value):
|
jpayne@68
|
568 value = _try_iter(value)
|
jpayne@68
|
569 delegated = self._mock_delegate
|
jpayne@68
|
570 if delegated is None:
|
jpayne@68
|
571 self._mock_side_effect = value
|
jpayne@68
|
572 else:
|
jpayne@68
|
573 delegated.side_effect = value
|
jpayne@68
|
574
|
jpayne@68
|
575 side_effect = property(__get_side_effect, __set_side_effect)
|
jpayne@68
|
576
|
jpayne@68
|
577
|
jpayne@68
|
578 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
|
jpayne@68
|
579 "Restore the mock object to its initial state."
|
jpayne@68
|
580 if visited is None:
|
jpayne@68
|
581 visited = []
|
jpayne@68
|
582 if id(self) in visited:
|
jpayne@68
|
583 return
|
jpayne@68
|
584 visited.append(id(self))
|
jpayne@68
|
585
|
jpayne@68
|
586 self.called = False
|
jpayne@68
|
587 self.call_args = None
|
jpayne@68
|
588 self.call_count = 0
|
jpayne@68
|
589 self.mock_calls = _CallList()
|
jpayne@68
|
590 self.call_args_list = _CallList()
|
jpayne@68
|
591 self.method_calls = _CallList()
|
jpayne@68
|
592
|
jpayne@68
|
593 if return_value:
|
jpayne@68
|
594 self._mock_return_value = DEFAULT
|
jpayne@68
|
595 if side_effect:
|
jpayne@68
|
596 self._mock_side_effect = None
|
jpayne@68
|
597
|
jpayne@68
|
598 for child in self._mock_children.values():
|
jpayne@68
|
599 if isinstance(child, _SpecState) or child is _deleted:
|
jpayne@68
|
600 continue
|
jpayne@68
|
601 child.reset_mock(visited)
|
jpayne@68
|
602
|
jpayne@68
|
603 ret = self._mock_return_value
|
jpayne@68
|
604 if _is_instance_mock(ret) and ret is not self:
|
jpayne@68
|
605 ret.reset_mock(visited)
|
jpayne@68
|
606
|
jpayne@68
|
607
|
jpayne@68
|
608 def configure_mock(self, /, **kwargs):
|
jpayne@68
|
609 """Set attributes on the mock through keyword arguments.
|
jpayne@68
|
610
|
jpayne@68
|
611 Attributes plus return values and side effects can be set on child
|
jpayne@68
|
612 mocks using standard dot notation and unpacking a dictionary in the
|
jpayne@68
|
613 method call:
|
jpayne@68
|
614
|
jpayne@68
|
615 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
|
jpayne@68
|
616 >>> mock.configure_mock(**attrs)"""
|
jpayne@68
|
617 for arg, val in sorted(kwargs.items(),
|
jpayne@68
|
618 # we sort on the number of dots so that
|
jpayne@68
|
619 # attributes are set before we set attributes on
|
jpayne@68
|
620 # attributes
|
jpayne@68
|
621 key=lambda entry: entry[0].count('.')):
|
jpayne@68
|
622 args = arg.split('.')
|
jpayne@68
|
623 final = args.pop()
|
jpayne@68
|
624 obj = self
|
jpayne@68
|
625 for entry in args:
|
jpayne@68
|
626 obj = getattr(obj, entry)
|
jpayne@68
|
627 setattr(obj, final, val)
|
jpayne@68
|
628
|
jpayne@68
|
629
|
jpayne@68
|
630 def __getattr__(self, name):
|
jpayne@68
|
631 if name in {'_mock_methods', '_mock_unsafe'}:
|
jpayne@68
|
632 raise AttributeError(name)
|
jpayne@68
|
633 elif self._mock_methods is not None:
|
jpayne@68
|
634 if name not in self._mock_methods or name in _all_magics:
|
jpayne@68
|
635 raise AttributeError("Mock object has no attribute %r" % name)
|
jpayne@68
|
636 elif _is_magic(name):
|
jpayne@68
|
637 raise AttributeError(name)
|
jpayne@68
|
638 if not self._mock_unsafe:
|
jpayne@68
|
639 if name.startswith(('assert', 'assret')):
|
jpayne@68
|
640 raise AttributeError("Attributes cannot start with 'assert' "
|
jpayne@68
|
641 "or 'assret'")
|
jpayne@68
|
642
|
jpayne@68
|
643 result = self._mock_children.get(name)
|
jpayne@68
|
644 if result is _deleted:
|
jpayne@68
|
645 raise AttributeError(name)
|
jpayne@68
|
646 elif result is None:
|
jpayne@68
|
647 wraps = None
|
jpayne@68
|
648 if self._mock_wraps is not None:
|
jpayne@68
|
649 # XXXX should we get the attribute without triggering code
|
jpayne@68
|
650 # execution?
|
jpayne@68
|
651 wraps = getattr(self._mock_wraps, name)
|
jpayne@68
|
652
|
jpayne@68
|
653 result = self._get_child_mock(
|
jpayne@68
|
654 parent=self, name=name, wraps=wraps, _new_name=name,
|
jpayne@68
|
655 _new_parent=self
|
jpayne@68
|
656 )
|
jpayne@68
|
657 self._mock_children[name] = result
|
jpayne@68
|
658
|
jpayne@68
|
659 elif isinstance(result, _SpecState):
|
jpayne@68
|
660 result = create_autospec(
|
jpayne@68
|
661 result.spec, result.spec_set, result.instance,
|
jpayne@68
|
662 result.parent, result.name
|
jpayne@68
|
663 )
|
jpayne@68
|
664 self._mock_children[name] = result
|
jpayne@68
|
665
|
jpayne@68
|
666 return result
|
jpayne@68
|
667
|
jpayne@68
|
668
|
jpayne@68
|
669 def _extract_mock_name(self):
|
jpayne@68
|
670 _name_list = [self._mock_new_name]
|
jpayne@68
|
671 _parent = self._mock_new_parent
|
jpayne@68
|
672 last = self
|
jpayne@68
|
673
|
jpayne@68
|
674 dot = '.'
|
jpayne@68
|
675 if _name_list == ['()']:
|
jpayne@68
|
676 dot = ''
|
jpayne@68
|
677
|
jpayne@68
|
678 while _parent is not None:
|
jpayne@68
|
679 last = _parent
|
jpayne@68
|
680
|
jpayne@68
|
681 _name_list.append(_parent._mock_new_name + dot)
|
jpayne@68
|
682 dot = '.'
|
jpayne@68
|
683 if _parent._mock_new_name == '()':
|
jpayne@68
|
684 dot = ''
|
jpayne@68
|
685
|
jpayne@68
|
686 _parent = _parent._mock_new_parent
|
jpayne@68
|
687
|
jpayne@68
|
688 _name_list = list(reversed(_name_list))
|
jpayne@68
|
689 _first = last._mock_name or 'mock'
|
jpayne@68
|
690 if len(_name_list) > 1:
|
jpayne@68
|
691 if _name_list[1] not in ('()', '().'):
|
jpayne@68
|
692 _first += '.'
|
jpayne@68
|
693 _name_list[0] = _first
|
jpayne@68
|
694 return ''.join(_name_list)
|
jpayne@68
|
695
|
jpayne@68
|
696 def __repr__(self):
|
jpayne@68
|
697 name = self._extract_mock_name()
|
jpayne@68
|
698
|
jpayne@68
|
699 name_string = ''
|
jpayne@68
|
700 if name not in ('mock', 'mock.'):
|
jpayne@68
|
701 name_string = ' name=%r' % name
|
jpayne@68
|
702
|
jpayne@68
|
703 spec_string = ''
|
jpayne@68
|
704 if self._spec_class is not None:
|
jpayne@68
|
705 spec_string = ' spec=%r'
|
jpayne@68
|
706 if self._spec_set:
|
jpayne@68
|
707 spec_string = ' spec_set=%r'
|
jpayne@68
|
708 spec_string = spec_string % self._spec_class.__name__
|
jpayne@68
|
709 return "<%s%s%s id='%s'>" % (
|
jpayne@68
|
710 type(self).__name__,
|
jpayne@68
|
711 name_string,
|
jpayne@68
|
712 spec_string,
|
jpayne@68
|
713 id(self)
|
jpayne@68
|
714 )
|
jpayne@68
|
715
|
jpayne@68
|
716
|
jpayne@68
|
717 def __dir__(self):
|
jpayne@68
|
718 """Filter the output of `dir(mock)` to only useful members."""
|
jpayne@68
|
719 if not FILTER_DIR:
|
jpayne@68
|
720 return object.__dir__(self)
|
jpayne@68
|
721
|
jpayne@68
|
722 extras = self._mock_methods or []
|
jpayne@68
|
723 from_type = dir(type(self))
|
jpayne@68
|
724 from_dict = list(self.__dict__)
|
jpayne@68
|
725 from_child_mocks = [
|
jpayne@68
|
726 m_name for m_name, m_value in self._mock_children.items()
|
jpayne@68
|
727 if m_value is not _deleted]
|
jpayne@68
|
728
|
jpayne@68
|
729 from_type = [e for e in from_type if not e.startswith('_')]
|
jpayne@68
|
730 from_dict = [e for e in from_dict if not e.startswith('_') or
|
jpayne@68
|
731 _is_magic(e)]
|
jpayne@68
|
732 return sorted(set(extras + from_type + from_dict + from_child_mocks))
|
jpayne@68
|
733
|
jpayne@68
|
734
|
jpayne@68
|
735 def __setattr__(self, name, value):
|
jpayne@68
|
736 if name in _allowed_names:
|
jpayne@68
|
737 # property setters go through here
|
jpayne@68
|
738 return object.__setattr__(self, name, value)
|
jpayne@68
|
739 elif (self._spec_set and self._mock_methods is not None and
|
jpayne@68
|
740 name not in self._mock_methods and
|
jpayne@68
|
741 name not in self.__dict__):
|
jpayne@68
|
742 raise AttributeError("Mock object has no attribute '%s'" % name)
|
jpayne@68
|
743 elif name in _unsupported_magics:
|
jpayne@68
|
744 msg = 'Attempting to set unsupported magic method %r.' % name
|
jpayne@68
|
745 raise AttributeError(msg)
|
jpayne@68
|
746 elif name in _all_magics:
|
jpayne@68
|
747 if self._mock_methods is not None and name not in self._mock_methods:
|
jpayne@68
|
748 raise AttributeError("Mock object has no attribute '%s'" % name)
|
jpayne@68
|
749
|
jpayne@68
|
750 if not _is_instance_mock(value):
|
jpayne@68
|
751 setattr(type(self), name, _get_method(name, value))
|
jpayne@68
|
752 original = value
|
jpayne@68
|
753 value = lambda *args, **kw: original(self, *args, **kw)
|
jpayne@68
|
754 else:
|
jpayne@68
|
755 # only set _new_name and not name so that mock_calls is tracked
|
jpayne@68
|
756 # but not method calls
|
jpayne@68
|
757 _check_and_set_parent(self, value, None, name)
|
jpayne@68
|
758 setattr(type(self), name, value)
|
jpayne@68
|
759 self._mock_children[name] = value
|
jpayne@68
|
760 elif name == '__class__':
|
jpayne@68
|
761 self._spec_class = value
|
jpayne@68
|
762 return
|
jpayne@68
|
763 else:
|
jpayne@68
|
764 if _check_and_set_parent(self, value, name, name):
|
jpayne@68
|
765 self._mock_children[name] = value
|
jpayne@68
|
766
|
jpayne@68
|
767 if self._mock_sealed and not hasattr(self, name):
|
jpayne@68
|
768 mock_name = f'{self._extract_mock_name()}.{name}'
|
jpayne@68
|
769 raise AttributeError(f'Cannot set {mock_name}')
|
jpayne@68
|
770
|
jpayne@68
|
771 return object.__setattr__(self, name, value)
|
jpayne@68
|
772
|
jpayne@68
|
773
|
jpayne@68
|
774 def __delattr__(self, name):
|
jpayne@68
|
775 if name in _all_magics and name in type(self).__dict__:
|
jpayne@68
|
776 delattr(type(self), name)
|
jpayne@68
|
777 if name not in self.__dict__:
|
jpayne@68
|
778 # for magic methods that are still MagicProxy objects and
|
jpayne@68
|
779 # not set on the instance itself
|
jpayne@68
|
780 return
|
jpayne@68
|
781
|
jpayne@68
|
782 obj = self._mock_children.get(name, _missing)
|
jpayne@68
|
783 if name in self.__dict__:
|
jpayne@68
|
784 _safe_super(NonCallableMock, self).__delattr__(name)
|
jpayne@68
|
785 elif obj is _deleted:
|
jpayne@68
|
786 raise AttributeError(name)
|
jpayne@68
|
787 if obj is not _missing:
|
jpayne@68
|
788 del self._mock_children[name]
|
jpayne@68
|
789 self._mock_children[name] = _deleted
|
jpayne@68
|
790
|
jpayne@68
|
791
|
jpayne@68
|
792 def _format_mock_call_signature(self, args, kwargs):
|
jpayne@68
|
793 name = self._mock_name or 'mock'
|
jpayne@68
|
794 return _format_call_signature(name, args, kwargs)
|
jpayne@68
|
795
|
jpayne@68
|
796
|
jpayne@68
|
797 def _format_mock_failure_message(self, args, kwargs, action='call'):
|
jpayne@68
|
798 message = 'expected %s not found.\nExpected: %s\nActual: %s'
|
jpayne@68
|
799 expected_string = self._format_mock_call_signature(args, kwargs)
|
jpayne@68
|
800 call_args = self.call_args
|
jpayne@68
|
801 actual_string = self._format_mock_call_signature(*call_args)
|
jpayne@68
|
802 return message % (action, expected_string, actual_string)
|
jpayne@68
|
803
|
jpayne@68
|
804
|
jpayne@68
|
805 def _get_call_signature_from_name(self, name):
|
jpayne@68
|
806 """
|
jpayne@68
|
807 * If call objects are asserted against a method/function like obj.meth1
|
jpayne@68
|
808 then there could be no name for the call object to lookup. Hence just
|
jpayne@68
|
809 return the spec_signature of the method/function being asserted against.
|
jpayne@68
|
810 * If the name is not empty then remove () and split by '.' to get
|
jpayne@68
|
811 list of names to iterate through the children until a potential
|
jpayne@68
|
812 match is found. A child mock is created only during attribute access
|
jpayne@68
|
813 so if we get a _SpecState then no attributes of the spec were accessed
|
jpayne@68
|
814 and can be safely exited.
|
jpayne@68
|
815 """
|
jpayne@68
|
816 if not name:
|
jpayne@68
|
817 return self._spec_signature
|
jpayne@68
|
818
|
jpayne@68
|
819 sig = None
|
jpayne@68
|
820 names = name.replace('()', '').split('.')
|
jpayne@68
|
821 children = self._mock_children
|
jpayne@68
|
822
|
jpayne@68
|
823 for name in names:
|
jpayne@68
|
824 child = children.get(name)
|
jpayne@68
|
825 if child is None or isinstance(child, _SpecState):
|
jpayne@68
|
826 break
|
jpayne@68
|
827 else:
|
jpayne@68
|
828 children = child._mock_children
|
jpayne@68
|
829 sig = child._spec_signature
|
jpayne@68
|
830
|
jpayne@68
|
831 return sig
|
jpayne@68
|
832
|
jpayne@68
|
833
|
jpayne@68
|
834 def _call_matcher(self, _call):
|
jpayne@68
|
835 """
|
jpayne@68
|
836 Given a call (or simply an (args, kwargs) tuple), return a
|
jpayne@68
|
837 comparison key suitable for matching with other calls.
|
jpayne@68
|
838 This is a best effort method which relies on the spec's signature,
|
jpayne@68
|
839 if available, or falls back on the arguments themselves.
|
jpayne@68
|
840 """
|
jpayne@68
|
841
|
jpayne@68
|
842 if isinstance(_call, tuple) and len(_call) > 2:
|
jpayne@68
|
843 sig = self._get_call_signature_from_name(_call[0])
|
jpayne@68
|
844 else:
|
jpayne@68
|
845 sig = self._spec_signature
|
jpayne@68
|
846
|
jpayne@68
|
847 if sig is not None:
|
jpayne@68
|
848 if len(_call) == 2:
|
jpayne@68
|
849 name = ''
|
jpayne@68
|
850 args, kwargs = _call
|
jpayne@68
|
851 else:
|
jpayne@68
|
852 name, args, kwargs = _call
|
jpayne@68
|
853 try:
|
jpayne@68
|
854 return name, sig.bind(*args, **kwargs)
|
jpayne@68
|
855 except TypeError as e:
|
jpayne@68
|
856 return e.with_traceback(None)
|
jpayne@68
|
857 else:
|
jpayne@68
|
858 return _call
|
jpayne@68
|
859
|
jpayne@68
|
860 def assert_not_called(self):
|
jpayne@68
|
861 """assert that the mock was never called.
|
jpayne@68
|
862 """
|
jpayne@68
|
863 if self.call_count != 0:
|
jpayne@68
|
864 msg = ("Expected '%s' to not have been called. Called %s times.%s"
|
jpayne@68
|
865 % (self._mock_name or 'mock',
|
jpayne@68
|
866 self.call_count,
|
jpayne@68
|
867 self._calls_repr()))
|
jpayne@68
|
868 raise AssertionError(msg)
|
jpayne@68
|
869
|
jpayne@68
|
870 def assert_called(self):
|
jpayne@68
|
871 """assert that the mock was called at least once
|
jpayne@68
|
872 """
|
jpayne@68
|
873 if self.call_count == 0:
|
jpayne@68
|
874 msg = ("Expected '%s' to have been called." %
|
jpayne@68
|
875 (self._mock_name or 'mock'))
|
jpayne@68
|
876 raise AssertionError(msg)
|
jpayne@68
|
877
|
jpayne@68
|
878 def assert_called_once(self):
|
jpayne@68
|
879 """assert that the mock was called only once.
|
jpayne@68
|
880 """
|
jpayne@68
|
881 if not self.call_count == 1:
|
jpayne@68
|
882 msg = ("Expected '%s' to have been called once. Called %s times.%s"
|
jpayne@68
|
883 % (self._mock_name or 'mock',
|
jpayne@68
|
884 self.call_count,
|
jpayne@68
|
885 self._calls_repr()))
|
jpayne@68
|
886 raise AssertionError(msg)
|
jpayne@68
|
887
|
jpayne@68
|
888 def assert_called_with(self, /, *args, **kwargs):
|
jpayne@68
|
889 """assert that the last call was made with the specified arguments.
|
jpayne@68
|
890
|
jpayne@68
|
891 Raises an AssertionError if the args and keyword args passed in are
|
jpayne@68
|
892 different to the last call to the mock."""
|
jpayne@68
|
893 if self.call_args is None:
|
jpayne@68
|
894 expected = self._format_mock_call_signature(args, kwargs)
|
jpayne@68
|
895 actual = 'not called.'
|
jpayne@68
|
896 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
|
jpayne@68
|
897 % (expected, actual))
|
jpayne@68
|
898 raise AssertionError(error_message)
|
jpayne@68
|
899
|
jpayne@68
|
900 def _error_message():
|
jpayne@68
|
901 msg = self._format_mock_failure_message(args, kwargs)
|
jpayne@68
|
902 return msg
|
jpayne@68
|
903 expected = self._call_matcher((args, kwargs))
|
jpayne@68
|
904 actual = self._call_matcher(self.call_args)
|
jpayne@68
|
905 if expected != actual:
|
jpayne@68
|
906 cause = expected if isinstance(expected, Exception) else None
|
jpayne@68
|
907 raise AssertionError(_error_message()) from cause
|
jpayne@68
|
908
|
jpayne@68
|
909
|
jpayne@68
|
910 def assert_called_once_with(self, /, *args, **kwargs):
|
jpayne@68
|
911 """assert that the mock was called exactly once and that that call was
|
jpayne@68
|
912 with the specified arguments."""
|
jpayne@68
|
913 if not self.call_count == 1:
|
jpayne@68
|
914 msg = ("Expected '%s' to be called once. Called %s times.%s"
|
jpayne@68
|
915 % (self._mock_name or 'mock',
|
jpayne@68
|
916 self.call_count,
|
jpayne@68
|
917 self._calls_repr()))
|
jpayne@68
|
918 raise AssertionError(msg)
|
jpayne@68
|
919 return self.assert_called_with(*args, **kwargs)
|
jpayne@68
|
920
|
jpayne@68
|
921
|
jpayne@68
|
922 def assert_has_calls(self, calls, any_order=False):
|
jpayne@68
|
923 """assert the mock has been called with the specified calls.
|
jpayne@68
|
924 The `mock_calls` list is checked for the calls.
|
jpayne@68
|
925
|
jpayne@68
|
926 If `any_order` is False (the default) then the calls must be
|
jpayne@68
|
927 sequential. There can be extra calls before or after the
|
jpayne@68
|
928 specified calls.
|
jpayne@68
|
929
|
jpayne@68
|
930 If `any_order` is True then the calls can be in any order, but
|
jpayne@68
|
931 they must all appear in `mock_calls`."""
|
jpayne@68
|
932 expected = [self._call_matcher(c) for c in calls]
|
jpayne@68
|
933 cause = next((e for e in expected if isinstance(e, Exception)), None)
|
jpayne@68
|
934 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
|
jpayne@68
|
935 if not any_order:
|
jpayne@68
|
936 if expected not in all_calls:
|
jpayne@68
|
937 if cause is None:
|
jpayne@68
|
938 problem = 'Calls not found.'
|
jpayne@68
|
939 else:
|
jpayne@68
|
940 problem = ('Error processing expected calls.\n'
|
jpayne@68
|
941 'Errors: {}').format(
|
jpayne@68
|
942 [e if isinstance(e, Exception) else None
|
jpayne@68
|
943 for e in expected])
|
jpayne@68
|
944 raise AssertionError(
|
jpayne@68
|
945 f'{problem}\n'
|
jpayne@68
|
946 f'Expected: {_CallList(calls)}'
|
jpayne@68
|
947 f'{self._calls_repr(prefix="Actual").rstrip(".")}'
|
jpayne@68
|
948 ) from cause
|
jpayne@68
|
949 return
|
jpayne@68
|
950
|
jpayne@68
|
951 all_calls = list(all_calls)
|
jpayne@68
|
952
|
jpayne@68
|
953 not_found = []
|
jpayne@68
|
954 for kall in expected:
|
jpayne@68
|
955 try:
|
jpayne@68
|
956 all_calls.remove(kall)
|
jpayne@68
|
957 except ValueError:
|
jpayne@68
|
958 not_found.append(kall)
|
jpayne@68
|
959 if not_found:
|
jpayne@68
|
960 raise AssertionError(
|
jpayne@68
|
961 '%r does not contain all of %r in its call list, '
|
jpayne@68
|
962 'found %r instead' % (self._mock_name or 'mock',
|
jpayne@68
|
963 tuple(not_found), all_calls)
|
jpayne@68
|
964 ) from cause
|
jpayne@68
|
965
|
jpayne@68
|
966
|
jpayne@68
|
967 def assert_any_call(self, /, *args, **kwargs):
|
jpayne@68
|
968 """assert the mock has been called with the specified arguments.
|
jpayne@68
|
969
|
jpayne@68
|
970 The assert passes if the mock has *ever* been called, unlike
|
jpayne@68
|
971 `assert_called_with` and `assert_called_once_with` that only pass if
|
jpayne@68
|
972 the call is the most recent one."""
|
jpayne@68
|
973 expected = self._call_matcher((args, kwargs))
|
jpayne@68
|
974 actual = [self._call_matcher(c) for c in self.call_args_list]
|
jpayne@68
|
975 if expected not in actual:
|
jpayne@68
|
976 cause = expected if isinstance(expected, Exception) else None
|
jpayne@68
|
977 expected_string = self._format_mock_call_signature(args, kwargs)
|
jpayne@68
|
978 raise AssertionError(
|
jpayne@68
|
979 '%s call not found' % expected_string
|
jpayne@68
|
980 ) from cause
|
jpayne@68
|
981
|
jpayne@68
|
982
|
jpayne@68
|
983 def _get_child_mock(self, /, **kw):
|
jpayne@68
|
984 """Create the child mocks for attributes and return value.
|
jpayne@68
|
985 By default child mocks will be the same type as the parent.
|
jpayne@68
|
986 Subclasses of Mock may want to override this to customize the way
|
jpayne@68
|
987 child mocks are made.
|
jpayne@68
|
988
|
jpayne@68
|
989 For non-callable mocks the callable variant will be used (rather than
|
jpayne@68
|
990 any custom subclass)."""
|
jpayne@68
|
991 _new_name = kw.get("_new_name")
|
jpayne@68
|
992 if _new_name in self.__dict__['_spec_asyncs']:
|
jpayne@68
|
993 return AsyncMock(**kw)
|
jpayne@68
|
994
|
jpayne@68
|
995 _type = type(self)
|
jpayne@68
|
996 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
|
jpayne@68
|
997 # Any asynchronous magic becomes an AsyncMock
|
jpayne@68
|
998 klass = AsyncMock
|
jpayne@68
|
999 elif issubclass(_type, AsyncMockMixin):
|
jpayne@68
|
1000 if (_new_name in _all_sync_magics or
|
jpayne@68
|
1001 self._mock_methods and _new_name in self._mock_methods):
|
jpayne@68
|
1002 # Any synchronous method on AsyncMock becomes a MagicMock
|
jpayne@68
|
1003 klass = MagicMock
|
jpayne@68
|
1004 else:
|
jpayne@68
|
1005 klass = AsyncMock
|
jpayne@68
|
1006 elif not issubclass(_type, CallableMixin):
|
jpayne@68
|
1007 if issubclass(_type, NonCallableMagicMock):
|
jpayne@68
|
1008 klass = MagicMock
|
jpayne@68
|
1009 elif issubclass(_type, NonCallableMock):
|
jpayne@68
|
1010 klass = Mock
|
jpayne@68
|
1011 else:
|
jpayne@68
|
1012 klass = _type.__mro__[1]
|
jpayne@68
|
1013
|
jpayne@68
|
1014 if self._mock_sealed:
|
jpayne@68
|
1015 attribute = "." + kw["name"] if "name" in kw else "()"
|
jpayne@68
|
1016 mock_name = self._extract_mock_name() + attribute
|
jpayne@68
|
1017 raise AttributeError(mock_name)
|
jpayne@68
|
1018
|
jpayne@68
|
1019 return klass(**kw)
|
jpayne@68
|
1020
|
jpayne@68
|
1021
|
jpayne@68
|
1022 def _calls_repr(self, prefix="Calls"):
|
jpayne@68
|
1023 """Renders self.mock_calls as a string.
|
jpayne@68
|
1024
|
jpayne@68
|
1025 Example: "\nCalls: [call(1), call(2)]."
|
jpayne@68
|
1026
|
jpayne@68
|
1027 If self.mock_calls is empty, an empty string is returned. The
|
jpayne@68
|
1028 output will be truncated if very long.
|
jpayne@68
|
1029 """
|
jpayne@68
|
1030 if not self.mock_calls:
|
jpayne@68
|
1031 return ""
|
jpayne@68
|
1032 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
|
jpayne@68
|
1033
|
jpayne@68
|
1034
|
jpayne@68
|
1035
|
jpayne@68
|
1036 def _try_iter(obj):
|
jpayne@68
|
1037 if obj is None:
|
jpayne@68
|
1038 return obj
|
jpayne@68
|
1039 if _is_exception(obj):
|
jpayne@68
|
1040 return obj
|
jpayne@68
|
1041 if _callable(obj):
|
jpayne@68
|
1042 return obj
|
jpayne@68
|
1043 try:
|
jpayne@68
|
1044 return iter(obj)
|
jpayne@68
|
1045 except TypeError:
|
jpayne@68
|
1046 # XXXX backwards compatibility
|
jpayne@68
|
1047 # but this will blow up on first call - so maybe we should fail early?
|
jpayne@68
|
1048 return obj
|
jpayne@68
|
1049
|
jpayne@68
|
1050
|
jpayne@68
|
1051 class CallableMixin(Base):
|
jpayne@68
|
1052
|
jpayne@68
|
1053 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
|
jpayne@68
|
1054 wraps=None, name=None, spec_set=None, parent=None,
|
jpayne@68
|
1055 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
|
jpayne@68
|
1056 self.__dict__['_mock_return_value'] = return_value
|
jpayne@68
|
1057 _safe_super(CallableMixin, self).__init__(
|
jpayne@68
|
1058 spec, wraps, name, spec_set, parent,
|
jpayne@68
|
1059 _spec_state, _new_name, _new_parent, **kwargs
|
jpayne@68
|
1060 )
|
jpayne@68
|
1061
|
jpayne@68
|
1062 self.side_effect = side_effect
|
jpayne@68
|
1063
|
jpayne@68
|
1064
|
jpayne@68
|
1065 def _mock_check_sig(self, /, *args, **kwargs):
|
jpayne@68
|
1066 # stub method that can be replaced with one with a specific signature
|
jpayne@68
|
1067 pass
|
jpayne@68
|
1068
|
jpayne@68
|
1069
|
jpayne@68
|
1070 def __call__(self, /, *args, **kwargs):
|
jpayne@68
|
1071 # can't use self in-case a function / method we are mocking uses self
|
jpayne@68
|
1072 # in the signature
|
jpayne@68
|
1073 self._mock_check_sig(*args, **kwargs)
|
jpayne@68
|
1074 self._increment_mock_call(*args, **kwargs)
|
jpayne@68
|
1075 return self._mock_call(*args, **kwargs)
|
jpayne@68
|
1076
|
jpayne@68
|
1077
|
jpayne@68
|
1078 def _mock_call(self, /, *args, **kwargs):
|
jpayne@68
|
1079 return self._execute_mock_call(*args, **kwargs)
|
jpayne@68
|
1080
|
jpayne@68
|
1081 def _increment_mock_call(self, /, *args, **kwargs):
|
jpayne@68
|
1082 self.called = True
|
jpayne@68
|
1083 self.call_count += 1
|
jpayne@68
|
1084
|
jpayne@68
|
1085 # handle call_args
|
jpayne@68
|
1086 # needs to be set here so assertions on call arguments pass before
|
jpayne@68
|
1087 # execution in the case of awaited calls
|
jpayne@68
|
1088 _call = _Call((args, kwargs), two=True)
|
jpayne@68
|
1089 self.call_args = _call
|
jpayne@68
|
1090 self.call_args_list.append(_call)
|
jpayne@68
|
1091
|
jpayne@68
|
1092 # initial stuff for method_calls:
|
jpayne@68
|
1093 do_method_calls = self._mock_parent is not None
|
jpayne@68
|
1094 method_call_name = self._mock_name
|
jpayne@68
|
1095
|
jpayne@68
|
1096 # initial stuff for mock_calls:
|
jpayne@68
|
1097 mock_call_name = self._mock_new_name
|
jpayne@68
|
1098 is_a_call = mock_call_name == '()'
|
jpayne@68
|
1099 self.mock_calls.append(_Call(('', args, kwargs)))
|
jpayne@68
|
1100
|
jpayne@68
|
1101 # follow up the chain of mocks:
|
jpayne@68
|
1102 _new_parent = self._mock_new_parent
|
jpayne@68
|
1103 while _new_parent is not None:
|
jpayne@68
|
1104
|
jpayne@68
|
1105 # handle method_calls:
|
jpayne@68
|
1106 if do_method_calls:
|
jpayne@68
|
1107 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
|
jpayne@68
|
1108 do_method_calls = _new_parent._mock_parent is not None
|
jpayne@68
|
1109 if do_method_calls:
|
jpayne@68
|
1110 method_call_name = _new_parent._mock_name + '.' + method_call_name
|
jpayne@68
|
1111
|
jpayne@68
|
1112 # handle mock_calls:
|
jpayne@68
|
1113 this_mock_call = _Call((mock_call_name, args, kwargs))
|
jpayne@68
|
1114 _new_parent.mock_calls.append(this_mock_call)
|
jpayne@68
|
1115
|
jpayne@68
|
1116 if _new_parent._mock_new_name:
|
jpayne@68
|
1117 if is_a_call:
|
jpayne@68
|
1118 dot = ''
|
jpayne@68
|
1119 else:
|
jpayne@68
|
1120 dot = '.'
|
jpayne@68
|
1121 is_a_call = _new_parent._mock_new_name == '()'
|
jpayne@68
|
1122 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
|
jpayne@68
|
1123
|
jpayne@68
|
1124 # follow the parental chain:
|
jpayne@68
|
1125 _new_parent = _new_parent._mock_new_parent
|
jpayne@68
|
1126
|
jpayne@68
|
1127 def _execute_mock_call(self, /, *args, **kwargs):
|
jpayne@68
|
1128 # separate from _increment_mock_call so that awaited functions are
|
jpayne@68
|
1129 # executed separately from their call, also AsyncMock overrides this method
|
jpayne@68
|
1130
|
jpayne@68
|
1131 effect = self.side_effect
|
jpayne@68
|
1132 if effect is not None:
|
jpayne@68
|
1133 if _is_exception(effect):
|
jpayne@68
|
1134 raise effect
|
jpayne@68
|
1135 elif not _callable(effect):
|
jpayne@68
|
1136 result = next(effect)
|
jpayne@68
|
1137 if _is_exception(result):
|
jpayne@68
|
1138 raise result
|
jpayne@68
|
1139 else:
|
jpayne@68
|
1140 result = effect(*args, **kwargs)
|
jpayne@68
|
1141
|
jpayne@68
|
1142 if result is not DEFAULT:
|
jpayne@68
|
1143 return result
|
jpayne@68
|
1144
|
jpayne@68
|
1145 if self._mock_return_value is not DEFAULT:
|
jpayne@68
|
1146 return self.return_value
|
jpayne@68
|
1147
|
jpayne@68
|
1148 if self._mock_wraps is not None:
|
jpayne@68
|
1149 return self._mock_wraps(*args, **kwargs)
|
jpayne@68
|
1150
|
jpayne@68
|
1151 return self.return_value
|
jpayne@68
|
1152
|
jpayne@68
|
1153
|
jpayne@68
|
1154
|
jpayne@68
|
1155 class Mock(CallableMixin, NonCallableMock):
|
jpayne@68
|
1156 """
|
jpayne@68
|
1157 Create a new `Mock` object. `Mock` takes several optional arguments
|
jpayne@68
|
1158 that specify the behaviour of the Mock object:
|
jpayne@68
|
1159
|
jpayne@68
|
1160 * `spec`: This can be either a list of strings or an existing object (a
|
jpayne@68
|
1161 class or instance) that acts as the specification for the mock object. If
|
jpayne@68
|
1162 you pass in an object then a list of strings is formed by calling dir on
|
jpayne@68
|
1163 the object (excluding unsupported magic attributes and methods). Accessing
|
jpayne@68
|
1164 any attribute not in this list will raise an `AttributeError`.
|
jpayne@68
|
1165
|
jpayne@68
|
1166 If `spec` is an object (rather than a list of strings) then
|
jpayne@68
|
1167 `mock.__class__` returns the class of the spec object. This allows mocks
|
jpayne@68
|
1168 to pass `isinstance` tests.
|
jpayne@68
|
1169
|
jpayne@68
|
1170 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
|
jpayne@68
|
1171 or get an attribute on the mock that isn't on the object passed as
|
jpayne@68
|
1172 `spec_set` will raise an `AttributeError`.
|
jpayne@68
|
1173
|
jpayne@68
|
1174 * `side_effect`: A function to be called whenever the Mock is called. See
|
jpayne@68
|
1175 the `side_effect` attribute. Useful for raising exceptions or
|
jpayne@68
|
1176 dynamically changing return values. The function is called with the same
|
jpayne@68
|
1177 arguments as the mock, and unless it returns `DEFAULT`, the return
|
jpayne@68
|
1178 value of this function is used as the return value.
|
jpayne@68
|
1179
|
jpayne@68
|
1180 If `side_effect` is an iterable then each call to the mock will return
|
jpayne@68
|
1181 the next value from the iterable. If any of the members of the iterable
|
jpayne@68
|
1182 are exceptions they will be raised instead of returned.
|
jpayne@68
|
1183
|
jpayne@68
|
1184 * `return_value`: The value returned when the mock is called. By default
|
jpayne@68
|
1185 this is a new Mock (created on first access). See the
|
jpayne@68
|
1186 `return_value` attribute.
|
jpayne@68
|
1187
|
jpayne@68
|
1188 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
|
jpayne@68
|
1189 calling the Mock will pass the call through to the wrapped object
|
jpayne@68
|
1190 (returning the real result). Attribute access on the mock will return a
|
jpayne@68
|
1191 Mock object that wraps the corresponding attribute of the wrapped object
|
jpayne@68
|
1192 (so attempting to access an attribute that doesn't exist will raise an
|
jpayne@68
|
1193 `AttributeError`).
|
jpayne@68
|
1194
|
jpayne@68
|
1195 If the mock has an explicit `return_value` set then calls are not passed
|
jpayne@68
|
1196 to the wrapped object and the `return_value` is returned instead.
|
jpayne@68
|
1197
|
jpayne@68
|
1198 * `name`: If the mock has a name then it will be used in the repr of the
|
jpayne@68
|
1199 mock. This can be useful for debugging. The name is propagated to child
|
jpayne@68
|
1200 mocks.
|
jpayne@68
|
1201
|
jpayne@68
|
1202 Mocks can also be called with arbitrary keyword arguments. These will be
|
jpayne@68
|
1203 used to set attributes on the mock after it is created.
|
jpayne@68
|
1204 """
|
jpayne@68
|
1205
|
jpayne@68
|
1206
|
jpayne@68
|
1207 def _dot_lookup(thing, comp, import_path):
|
jpayne@68
|
1208 try:
|
jpayne@68
|
1209 return getattr(thing, comp)
|
jpayne@68
|
1210 except AttributeError:
|
jpayne@68
|
1211 __import__(import_path)
|
jpayne@68
|
1212 return getattr(thing, comp)
|
jpayne@68
|
1213
|
jpayne@68
|
1214
|
jpayne@68
|
1215 def _importer(target):
|
jpayne@68
|
1216 components = target.split('.')
|
jpayne@68
|
1217 import_path = components.pop(0)
|
jpayne@68
|
1218 thing = __import__(import_path)
|
jpayne@68
|
1219
|
jpayne@68
|
1220 for comp in components:
|
jpayne@68
|
1221 import_path += ".%s" % comp
|
jpayne@68
|
1222 thing = _dot_lookup(thing, comp, import_path)
|
jpayne@68
|
1223 return thing
|
jpayne@68
|
1224
|
jpayne@68
|
1225
|
jpayne@68
|
1226 def _is_started(patcher):
|
jpayne@68
|
1227 # XXXX horrible
|
jpayne@68
|
1228 return hasattr(patcher, 'is_local')
|
jpayne@68
|
1229
|
jpayne@68
|
1230
|
jpayne@68
|
1231 class _patch(object):
|
jpayne@68
|
1232
|
jpayne@68
|
1233 attribute_name = None
|
jpayne@68
|
1234 _active_patches = []
|
jpayne@68
|
1235
|
jpayne@68
|
1236 def __init__(
|
jpayne@68
|
1237 self, getter, attribute, new, spec, create,
|
jpayne@68
|
1238 spec_set, autospec, new_callable, kwargs
|
jpayne@68
|
1239 ):
|
jpayne@68
|
1240 if new_callable is not None:
|
jpayne@68
|
1241 if new is not DEFAULT:
|
jpayne@68
|
1242 raise ValueError(
|
jpayne@68
|
1243 "Cannot use 'new' and 'new_callable' together"
|
jpayne@68
|
1244 )
|
jpayne@68
|
1245 if autospec is not None:
|
jpayne@68
|
1246 raise ValueError(
|
jpayne@68
|
1247 "Cannot use 'autospec' and 'new_callable' together"
|
jpayne@68
|
1248 )
|
jpayne@68
|
1249
|
jpayne@68
|
1250 self.getter = getter
|
jpayne@68
|
1251 self.attribute = attribute
|
jpayne@68
|
1252 self.new = new
|
jpayne@68
|
1253 self.new_callable = new_callable
|
jpayne@68
|
1254 self.spec = spec
|
jpayne@68
|
1255 self.create = create
|
jpayne@68
|
1256 self.has_local = False
|
jpayne@68
|
1257 self.spec_set = spec_set
|
jpayne@68
|
1258 self.autospec = autospec
|
jpayne@68
|
1259 self.kwargs = kwargs
|
jpayne@68
|
1260 self.additional_patchers = []
|
jpayne@68
|
1261
|
jpayne@68
|
1262
|
jpayne@68
|
1263 def copy(self):
|
jpayne@68
|
1264 patcher = _patch(
|
jpayne@68
|
1265 self.getter, self.attribute, self.new, self.spec,
|
jpayne@68
|
1266 self.create, self.spec_set,
|
jpayne@68
|
1267 self.autospec, self.new_callable, self.kwargs
|
jpayne@68
|
1268 )
|
jpayne@68
|
1269 patcher.attribute_name = self.attribute_name
|
jpayne@68
|
1270 patcher.additional_patchers = [
|
jpayne@68
|
1271 p.copy() for p in self.additional_patchers
|
jpayne@68
|
1272 ]
|
jpayne@68
|
1273 return patcher
|
jpayne@68
|
1274
|
jpayne@68
|
1275
|
jpayne@68
|
1276 def __call__(self, func):
|
jpayne@68
|
1277 if isinstance(func, type):
|
jpayne@68
|
1278 return self.decorate_class(func)
|
jpayne@68
|
1279 if inspect.iscoroutinefunction(func):
|
jpayne@68
|
1280 return self.decorate_async_callable(func)
|
jpayne@68
|
1281 return self.decorate_callable(func)
|
jpayne@68
|
1282
|
jpayne@68
|
1283
|
jpayne@68
|
1284 def decorate_class(self, klass):
|
jpayne@68
|
1285 for attr in dir(klass):
|
jpayne@68
|
1286 if not attr.startswith(patch.TEST_PREFIX):
|
jpayne@68
|
1287 continue
|
jpayne@68
|
1288
|
jpayne@68
|
1289 attr_value = getattr(klass, attr)
|
jpayne@68
|
1290 if not hasattr(attr_value, "__call__"):
|
jpayne@68
|
1291 continue
|
jpayne@68
|
1292
|
jpayne@68
|
1293 patcher = self.copy()
|
jpayne@68
|
1294 setattr(klass, attr, patcher(attr_value))
|
jpayne@68
|
1295 return klass
|
jpayne@68
|
1296
|
jpayne@68
|
1297
|
jpayne@68
|
1298 @contextlib.contextmanager
|
jpayne@68
|
1299 def decoration_helper(self, patched, args, keywargs):
|
jpayne@68
|
1300 extra_args = []
|
jpayne@68
|
1301 entered_patchers = []
|
jpayne@68
|
1302 patching = None
|
jpayne@68
|
1303
|
jpayne@68
|
1304 exc_info = tuple()
|
jpayne@68
|
1305 try:
|
jpayne@68
|
1306 for patching in patched.patchings:
|
jpayne@68
|
1307 arg = patching.__enter__()
|
jpayne@68
|
1308 entered_patchers.append(patching)
|
jpayne@68
|
1309 if patching.attribute_name is not None:
|
jpayne@68
|
1310 keywargs.update(arg)
|
jpayne@68
|
1311 elif patching.new is DEFAULT:
|
jpayne@68
|
1312 extra_args.append(arg)
|
jpayne@68
|
1313
|
jpayne@68
|
1314 args += tuple(extra_args)
|
jpayne@68
|
1315 yield (args, keywargs)
|
jpayne@68
|
1316 except:
|
jpayne@68
|
1317 if (patching not in entered_patchers and
|
jpayne@68
|
1318 _is_started(patching)):
|
jpayne@68
|
1319 # the patcher may have been started, but an exception
|
jpayne@68
|
1320 # raised whilst entering one of its additional_patchers
|
jpayne@68
|
1321 entered_patchers.append(patching)
|
jpayne@68
|
1322 # Pass the exception to __exit__
|
jpayne@68
|
1323 exc_info = sys.exc_info()
|
jpayne@68
|
1324 # re-raise the exception
|
jpayne@68
|
1325 raise
|
jpayne@68
|
1326 finally:
|
jpayne@68
|
1327 for patching in reversed(entered_patchers):
|
jpayne@68
|
1328 patching.__exit__(*exc_info)
|
jpayne@68
|
1329
|
jpayne@68
|
1330
|
jpayne@68
|
1331 def decorate_callable(self, func):
|
jpayne@68
|
1332 # NB. Keep the method in sync with decorate_async_callable()
|
jpayne@68
|
1333 if hasattr(func, 'patchings'):
|
jpayne@68
|
1334 func.patchings.append(self)
|
jpayne@68
|
1335 return func
|
jpayne@68
|
1336
|
jpayne@68
|
1337 @wraps(func)
|
jpayne@68
|
1338 def patched(*args, **keywargs):
|
jpayne@68
|
1339 with self.decoration_helper(patched,
|
jpayne@68
|
1340 args,
|
jpayne@68
|
1341 keywargs) as (newargs, newkeywargs):
|
jpayne@68
|
1342 return func(*newargs, **newkeywargs)
|
jpayne@68
|
1343
|
jpayne@68
|
1344 patched.patchings = [self]
|
jpayne@68
|
1345 return patched
|
jpayne@68
|
1346
|
jpayne@68
|
1347
|
jpayne@68
|
1348 def decorate_async_callable(self, func):
|
jpayne@68
|
1349 # NB. Keep the method in sync with decorate_callable()
|
jpayne@68
|
1350 if hasattr(func, 'patchings'):
|
jpayne@68
|
1351 func.patchings.append(self)
|
jpayne@68
|
1352 return func
|
jpayne@68
|
1353
|
jpayne@68
|
1354 @wraps(func)
|
jpayne@68
|
1355 async def patched(*args, **keywargs):
|
jpayne@68
|
1356 with self.decoration_helper(patched,
|
jpayne@68
|
1357 args,
|
jpayne@68
|
1358 keywargs) as (newargs, newkeywargs):
|
jpayne@68
|
1359 return await func(*newargs, **newkeywargs)
|
jpayne@68
|
1360
|
jpayne@68
|
1361 patched.patchings = [self]
|
jpayne@68
|
1362 return patched
|
jpayne@68
|
1363
|
jpayne@68
|
1364
|
jpayne@68
|
1365 def get_original(self):
|
jpayne@68
|
1366 target = self.getter()
|
jpayne@68
|
1367 name = self.attribute
|
jpayne@68
|
1368
|
jpayne@68
|
1369 original = DEFAULT
|
jpayne@68
|
1370 local = False
|
jpayne@68
|
1371
|
jpayne@68
|
1372 try:
|
jpayne@68
|
1373 original = target.__dict__[name]
|
jpayne@68
|
1374 except (AttributeError, KeyError):
|
jpayne@68
|
1375 original = getattr(target, name, DEFAULT)
|
jpayne@68
|
1376 else:
|
jpayne@68
|
1377 local = True
|
jpayne@68
|
1378
|
jpayne@68
|
1379 if name in _builtins and isinstance(target, ModuleType):
|
jpayne@68
|
1380 self.create = True
|
jpayne@68
|
1381
|
jpayne@68
|
1382 if not self.create and original is DEFAULT:
|
jpayne@68
|
1383 raise AttributeError(
|
jpayne@68
|
1384 "%s does not have the attribute %r" % (target, name)
|
jpayne@68
|
1385 )
|
jpayne@68
|
1386 return original, local
|
jpayne@68
|
1387
|
jpayne@68
|
1388
|
jpayne@68
|
1389 def __enter__(self):
|
jpayne@68
|
1390 """Perform the patch."""
|
jpayne@68
|
1391 new, spec, spec_set = self.new, self.spec, self.spec_set
|
jpayne@68
|
1392 autospec, kwargs = self.autospec, self.kwargs
|
jpayne@68
|
1393 new_callable = self.new_callable
|
jpayne@68
|
1394 self.target = self.getter()
|
jpayne@68
|
1395
|
jpayne@68
|
1396 # normalise False to None
|
jpayne@68
|
1397 if spec is False:
|
jpayne@68
|
1398 spec = None
|
jpayne@68
|
1399 if spec_set is False:
|
jpayne@68
|
1400 spec_set = None
|
jpayne@68
|
1401 if autospec is False:
|
jpayne@68
|
1402 autospec = None
|
jpayne@68
|
1403
|
jpayne@68
|
1404 if spec is not None and autospec is not None:
|
jpayne@68
|
1405 raise TypeError("Can't specify spec and autospec")
|
jpayne@68
|
1406 if ((spec is not None or autospec is not None) and
|
jpayne@68
|
1407 spec_set not in (True, None)):
|
jpayne@68
|
1408 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
|
jpayne@68
|
1409
|
jpayne@68
|
1410 original, local = self.get_original()
|
jpayne@68
|
1411
|
jpayne@68
|
1412 if new is DEFAULT and autospec is None:
|
jpayne@68
|
1413 inherit = False
|
jpayne@68
|
1414 if spec is True:
|
jpayne@68
|
1415 # set spec to the object we are replacing
|
jpayne@68
|
1416 spec = original
|
jpayne@68
|
1417 if spec_set is True:
|
jpayne@68
|
1418 spec_set = original
|
jpayne@68
|
1419 spec = None
|
jpayne@68
|
1420 elif spec is not None:
|
jpayne@68
|
1421 if spec_set is True:
|
jpayne@68
|
1422 spec_set = spec
|
jpayne@68
|
1423 spec = None
|
jpayne@68
|
1424 elif spec_set is True:
|
jpayne@68
|
1425 spec_set = original
|
jpayne@68
|
1426
|
jpayne@68
|
1427 if spec is not None or spec_set is not None:
|
jpayne@68
|
1428 if original is DEFAULT:
|
jpayne@68
|
1429 raise TypeError("Can't use 'spec' with create=True")
|
jpayne@68
|
1430 if isinstance(original, type):
|
jpayne@68
|
1431 # If we're patching out a class and there is a spec
|
jpayne@68
|
1432 inherit = True
|
jpayne@68
|
1433 if spec is None and _is_async_obj(original):
|
jpayne@68
|
1434 Klass = AsyncMock
|
jpayne@68
|
1435 else:
|
jpayne@68
|
1436 Klass = MagicMock
|
jpayne@68
|
1437 _kwargs = {}
|
jpayne@68
|
1438 if new_callable is not None:
|
jpayne@68
|
1439 Klass = new_callable
|
jpayne@68
|
1440 elif spec is not None or spec_set is not None:
|
jpayne@68
|
1441 this_spec = spec
|
jpayne@68
|
1442 if spec_set is not None:
|
jpayne@68
|
1443 this_spec = spec_set
|
jpayne@68
|
1444 if _is_list(this_spec):
|
jpayne@68
|
1445 not_callable = '__call__' not in this_spec
|
jpayne@68
|
1446 else:
|
jpayne@68
|
1447 not_callable = not callable(this_spec)
|
jpayne@68
|
1448 if _is_async_obj(this_spec):
|
jpayne@68
|
1449 Klass = AsyncMock
|
jpayne@68
|
1450 elif not_callable:
|
jpayne@68
|
1451 Klass = NonCallableMagicMock
|
jpayne@68
|
1452
|
jpayne@68
|
1453 if spec is not None:
|
jpayne@68
|
1454 _kwargs['spec'] = spec
|
jpayne@68
|
1455 if spec_set is not None:
|
jpayne@68
|
1456 _kwargs['spec_set'] = spec_set
|
jpayne@68
|
1457
|
jpayne@68
|
1458 # add a name to mocks
|
jpayne@68
|
1459 if (isinstance(Klass, type) and
|
jpayne@68
|
1460 issubclass(Klass, NonCallableMock) and self.attribute):
|
jpayne@68
|
1461 _kwargs['name'] = self.attribute
|
jpayne@68
|
1462
|
jpayne@68
|
1463 _kwargs.update(kwargs)
|
jpayne@68
|
1464 new = Klass(**_kwargs)
|
jpayne@68
|
1465
|
jpayne@68
|
1466 if inherit and _is_instance_mock(new):
|
jpayne@68
|
1467 # we can only tell if the instance should be callable if the
|
jpayne@68
|
1468 # spec is not a list
|
jpayne@68
|
1469 this_spec = spec
|
jpayne@68
|
1470 if spec_set is not None:
|
jpayne@68
|
1471 this_spec = spec_set
|
jpayne@68
|
1472 if (not _is_list(this_spec) and not
|
jpayne@68
|
1473 _instance_callable(this_spec)):
|
jpayne@68
|
1474 Klass = NonCallableMagicMock
|
jpayne@68
|
1475
|
jpayne@68
|
1476 _kwargs.pop('name')
|
jpayne@68
|
1477 new.return_value = Klass(_new_parent=new, _new_name='()',
|
jpayne@68
|
1478 **_kwargs)
|
jpayne@68
|
1479 elif autospec is not None:
|
jpayne@68
|
1480 # spec is ignored, new *must* be default, spec_set is treated
|
jpayne@68
|
1481 # as a boolean. Should we check spec is not None and that spec_set
|
jpayne@68
|
1482 # is a bool?
|
jpayne@68
|
1483 if new is not DEFAULT:
|
jpayne@68
|
1484 raise TypeError(
|
jpayne@68
|
1485 "autospec creates the mock for you. Can't specify "
|
jpayne@68
|
1486 "autospec and new."
|
jpayne@68
|
1487 )
|
jpayne@68
|
1488 if original is DEFAULT:
|
jpayne@68
|
1489 raise TypeError("Can't use 'autospec' with create=True")
|
jpayne@68
|
1490 spec_set = bool(spec_set)
|
jpayne@68
|
1491 if autospec is True:
|
jpayne@68
|
1492 autospec = original
|
jpayne@68
|
1493
|
jpayne@68
|
1494 new = create_autospec(autospec, spec_set=spec_set,
|
jpayne@68
|
1495 _name=self.attribute, **kwargs)
|
jpayne@68
|
1496 elif kwargs:
|
jpayne@68
|
1497 # can't set keyword args when we aren't creating the mock
|
jpayne@68
|
1498 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
|
jpayne@68
|
1499 raise TypeError("Can't pass kwargs to a mock we aren't creating")
|
jpayne@68
|
1500
|
jpayne@68
|
1501 new_attr = new
|
jpayne@68
|
1502
|
jpayne@68
|
1503 self.temp_original = original
|
jpayne@68
|
1504 self.is_local = local
|
jpayne@68
|
1505 setattr(self.target, self.attribute, new_attr)
|
jpayne@68
|
1506 if self.attribute_name is not None:
|
jpayne@68
|
1507 extra_args = {}
|
jpayne@68
|
1508 if self.new is DEFAULT:
|
jpayne@68
|
1509 extra_args[self.attribute_name] = new
|
jpayne@68
|
1510 for patching in self.additional_patchers:
|
jpayne@68
|
1511 arg = patching.__enter__()
|
jpayne@68
|
1512 if patching.new is DEFAULT:
|
jpayne@68
|
1513 extra_args.update(arg)
|
jpayne@68
|
1514 return extra_args
|
jpayne@68
|
1515
|
jpayne@68
|
1516 return new
|
jpayne@68
|
1517
|
jpayne@68
|
1518
|
jpayne@68
|
1519 def __exit__(self, *exc_info):
|
jpayne@68
|
1520 """Undo the patch."""
|
jpayne@68
|
1521 if not _is_started(self):
|
jpayne@68
|
1522 return
|
jpayne@68
|
1523
|
jpayne@68
|
1524 if self.is_local and self.temp_original is not DEFAULT:
|
jpayne@68
|
1525 setattr(self.target, self.attribute, self.temp_original)
|
jpayne@68
|
1526 else:
|
jpayne@68
|
1527 delattr(self.target, self.attribute)
|
jpayne@68
|
1528 if not self.create and (not hasattr(self.target, self.attribute) or
|
jpayne@68
|
1529 self.attribute in ('__doc__', '__module__',
|
jpayne@68
|
1530 '__defaults__', '__annotations__',
|
jpayne@68
|
1531 '__kwdefaults__')):
|
jpayne@68
|
1532 # needed for proxy objects like django settings
|
jpayne@68
|
1533 setattr(self.target, self.attribute, self.temp_original)
|
jpayne@68
|
1534
|
jpayne@68
|
1535 del self.temp_original
|
jpayne@68
|
1536 del self.is_local
|
jpayne@68
|
1537 del self.target
|
jpayne@68
|
1538 for patcher in reversed(self.additional_patchers):
|
jpayne@68
|
1539 if _is_started(patcher):
|
jpayne@68
|
1540 patcher.__exit__(*exc_info)
|
jpayne@68
|
1541
|
jpayne@68
|
1542
|
jpayne@68
|
1543 def start(self):
|
jpayne@68
|
1544 """Activate a patch, returning any created mock."""
|
jpayne@68
|
1545 result = self.__enter__()
|
jpayne@68
|
1546 self._active_patches.append(self)
|
jpayne@68
|
1547 return result
|
jpayne@68
|
1548
|
jpayne@68
|
1549
|
jpayne@68
|
1550 def stop(self):
|
jpayne@68
|
1551 """Stop an active patch."""
|
jpayne@68
|
1552 try:
|
jpayne@68
|
1553 self._active_patches.remove(self)
|
jpayne@68
|
1554 except ValueError:
|
jpayne@68
|
1555 # If the patch hasn't been started this will fail
|
jpayne@68
|
1556 pass
|
jpayne@68
|
1557
|
jpayne@68
|
1558 return self.__exit__()
|
jpayne@68
|
1559
|
jpayne@68
|
1560
|
jpayne@68
|
1561
|
jpayne@68
|
1562 def _get_target(target):
|
jpayne@68
|
1563 try:
|
jpayne@68
|
1564 target, attribute = target.rsplit('.', 1)
|
jpayne@68
|
1565 except (TypeError, ValueError):
|
jpayne@68
|
1566 raise TypeError("Need a valid target to patch. You supplied: %r" %
|
jpayne@68
|
1567 (target,))
|
jpayne@68
|
1568 getter = lambda: _importer(target)
|
jpayne@68
|
1569 return getter, attribute
|
jpayne@68
|
1570
|
jpayne@68
|
1571
|
jpayne@68
|
1572 def _patch_object(
|
jpayne@68
|
1573 target, attribute, new=DEFAULT, spec=None,
|
jpayne@68
|
1574 create=False, spec_set=None, autospec=None,
|
jpayne@68
|
1575 new_callable=None, **kwargs
|
jpayne@68
|
1576 ):
|
jpayne@68
|
1577 """
|
jpayne@68
|
1578 patch the named member (`attribute`) on an object (`target`) with a mock
|
jpayne@68
|
1579 object.
|
jpayne@68
|
1580
|
jpayne@68
|
1581 `patch.object` can be used as a decorator, class decorator or a context
|
jpayne@68
|
1582 manager. Arguments `new`, `spec`, `create`, `spec_set`,
|
jpayne@68
|
1583 `autospec` and `new_callable` have the same meaning as for `patch`. Like
|
jpayne@68
|
1584 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
|
jpayne@68
|
1585 the mock object it creates.
|
jpayne@68
|
1586
|
jpayne@68
|
1587 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
|
jpayne@68
|
1588 for choosing which methods to wrap.
|
jpayne@68
|
1589 """
|
jpayne@68
|
1590 if type(target) is str:
|
jpayne@68
|
1591 raise TypeError(
|
jpayne@68
|
1592 f"{target!r} must be the actual object to be patched, not a str"
|
jpayne@68
|
1593 )
|
jpayne@68
|
1594 getter = lambda: target
|
jpayne@68
|
1595 return _patch(
|
jpayne@68
|
1596 getter, attribute, new, spec, create,
|
jpayne@68
|
1597 spec_set, autospec, new_callable, kwargs
|
jpayne@68
|
1598 )
|
jpayne@68
|
1599
|
jpayne@68
|
1600
|
jpayne@68
|
1601 def _patch_multiple(target, spec=None, create=False, spec_set=None,
|
jpayne@68
|
1602 autospec=None, new_callable=None, **kwargs):
|
jpayne@68
|
1603 """Perform multiple patches in a single call. It takes the object to be
|
jpayne@68
|
1604 patched (either as an object or a string to fetch the object by importing)
|
jpayne@68
|
1605 and keyword arguments for the patches::
|
jpayne@68
|
1606
|
jpayne@68
|
1607 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
|
jpayne@68
|
1608 ...
|
jpayne@68
|
1609
|
jpayne@68
|
1610 Use `DEFAULT` as the value if you want `patch.multiple` to create
|
jpayne@68
|
1611 mocks for you. In this case the created mocks are passed into a decorated
|
jpayne@68
|
1612 function by keyword, and a dictionary is returned when `patch.multiple` is
|
jpayne@68
|
1613 used as a context manager.
|
jpayne@68
|
1614
|
jpayne@68
|
1615 `patch.multiple` can be used as a decorator, class decorator or a context
|
jpayne@68
|
1616 manager. The arguments `spec`, `spec_set`, `create`,
|
jpayne@68
|
1617 `autospec` and `new_callable` have the same meaning as for `patch`. These
|
jpayne@68
|
1618 arguments will be applied to *all* patches done by `patch.multiple`.
|
jpayne@68
|
1619
|
jpayne@68
|
1620 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
|
jpayne@68
|
1621 for choosing which methods to wrap.
|
jpayne@68
|
1622 """
|
jpayne@68
|
1623 if type(target) is str:
|
jpayne@68
|
1624 getter = lambda: _importer(target)
|
jpayne@68
|
1625 else:
|
jpayne@68
|
1626 getter = lambda: target
|
jpayne@68
|
1627
|
jpayne@68
|
1628 if not kwargs:
|
jpayne@68
|
1629 raise ValueError(
|
jpayne@68
|
1630 'Must supply at least one keyword argument with patch.multiple'
|
jpayne@68
|
1631 )
|
jpayne@68
|
1632 # need to wrap in a list for python 3, where items is a view
|
jpayne@68
|
1633 items = list(kwargs.items())
|
jpayne@68
|
1634 attribute, new = items[0]
|
jpayne@68
|
1635 patcher = _patch(
|
jpayne@68
|
1636 getter, attribute, new, spec, create, spec_set,
|
jpayne@68
|
1637 autospec, new_callable, {}
|
jpayne@68
|
1638 )
|
jpayne@68
|
1639 patcher.attribute_name = attribute
|
jpayne@68
|
1640 for attribute, new in items[1:]:
|
jpayne@68
|
1641 this_patcher = _patch(
|
jpayne@68
|
1642 getter, attribute, new, spec, create, spec_set,
|
jpayne@68
|
1643 autospec, new_callable, {}
|
jpayne@68
|
1644 )
|
jpayne@68
|
1645 this_patcher.attribute_name = attribute
|
jpayne@68
|
1646 patcher.additional_patchers.append(this_patcher)
|
jpayne@68
|
1647 return patcher
|
jpayne@68
|
1648
|
jpayne@68
|
1649
|
jpayne@68
|
1650 def patch(
|
jpayne@68
|
1651 target, new=DEFAULT, spec=None, create=False,
|
jpayne@68
|
1652 spec_set=None, autospec=None, new_callable=None, **kwargs
|
jpayne@68
|
1653 ):
|
jpayne@68
|
1654 """
|
jpayne@68
|
1655 `patch` acts as a function decorator, class decorator or a context
|
jpayne@68
|
1656 manager. Inside the body of the function or with statement, the `target`
|
jpayne@68
|
1657 is patched with a `new` object. When the function/with statement exits
|
jpayne@68
|
1658 the patch is undone.
|
jpayne@68
|
1659
|
jpayne@68
|
1660 If `new` is omitted, then the target is replaced with an
|
jpayne@68
|
1661 `AsyncMock if the patched object is an async function or a
|
jpayne@68
|
1662 `MagicMock` otherwise. If `patch` is used as a decorator and `new` is
|
jpayne@68
|
1663 omitted, the created mock is passed in as an extra argument to the
|
jpayne@68
|
1664 decorated function. If `patch` is used as a context manager the created
|
jpayne@68
|
1665 mock is returned by the context manager.
|
jpayne@68
|
1666
|
jpayne@68
|
1667 `target` should be a string in the form `'package.module.ClassName'`. The
|
jpayne@68
|
1668 `target` is imported and the specified object replaced with the `new`
|
jpayne@68
|
1669 object, so the `target` must be importable from the environment you are
|
jpayne@68
|
1670 calling `patch` from. The target is imported when the decorated function
|
jpayne@68
|
1671 is executed, not at decoration time.
|
jpayne@68
|
1672
|
jpayne@68
|
1673 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
|
jpayne@68
|
1674 if patch is creating one for you.
|
jpayne@68
|
1675
|
jpayne@68
|
1676 In addition you can pass `spec=True` or `spec_set=True`, which causes
|
jpayne@68
|
1677 patch to pass in the object being mocked as the spec/spec_set object.
|
jpayne@68
|
1678
|
jpayne@68
|
1679 `new_callable` allows you to specify a different class, or callable object,
|
jpayne@68
|
1680 that will be called to create the `new` object. By default `AsyncMock` is
|
jpayne@68
|
1681 used for async functions and `MagicMock` for the rest.
|
jpayne@68
|
1682
|
jpayne@68
|
1683 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
|
jpayne@68
|
1684 then the mock will be created with a spec from the object being replaced.
|
jpayne@68
|
1685 All attributes of the mock will also have the spec of the corresponding
|
jpayne@68
|
1686 attribute of the object being replaced. Methods and functions being
|
jpayne@68
|
1687 mocked will have their arguments checked and will raise a `TypeError` if
|
jpayne@68
|
1688 they are called with the wrong signature. For mocks replacing a class,
|
jpayne@68
|
1689 their return value (the 'instance') will have the same spec as the class.
|
jpayne@68
|
1690
|
jpayne@68
|
1691 Instead of `autospec=True` you can pass `autospec=some_object` to use an
|
jpayne@68
|
1692 arbitrary object as the spec instead of the one being replaced.
|
jpayne@68
|
1693
|
jpayne@68
|
1694 By default `patch` will fail to replace attributes that don't exist. If
|
jpayne@68
|
1695 you pass in `create=True`, and the attribute doesn't exist, patch will
|
jpayne@68
|
1696 create the attribute for you when the patched function is called, and
|
jpayne@68
|
1697 delete it again afterwards. This is useful for writing tests against
|
jpayne@68
|
1698 attributes that your production code creates at runtime. It is off by
|
jpayne@68
|
1699 default because it can be dangerous. With it switched on you can write
|
jpayne@68
|
1700 passing tests against APIs that don't actually exist!
|
jpayne@68
|
1701
|
jpayne@68
|
1702 Patch can be used as a `TestCase` class decorator. It works by
|
jpayne@68
|
1703 decorating each test method in the class. This reduces the boilerplate
|
jpayne@68
|
1704 code when your test methods share a common patchings set. `patch` finds
|
jpayne@68
|
1705 tests by looking for method names that start with `patch.TEST_PREFIX`.
|
jpayne@68
|
1706 By default this is `test`, which matches the way `unittest` finds tests.
|
jpayne@68
|
1707 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
|
jpayne@68
|
1708
|
jpayne@68
|
1709 Patch can be used as a context manager, with the with statement. Here the
|
jpayne@68
|
1710 patching applies to the indented block after the with statement. If you
|
jpayne@68
|
1711 use "as" then the patched object will be bound to the name after the
|
jpayne@68
|
1712 "as"; very useful if `patch` is creating a mock object for you.
|
jpayne@68
|
1713
|
jpayne@68
|
1714 `patch` takes arbitrary keyword arguments. These will be passed to
|
jpayne@68
|
1715 the `Mock` (or `new_callable`) on construction.
|
jpayne@68
|
1716
|
jpayne@68
|
1717 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
|
jpayne@68
|
1718 available for alternate use-cases.
|
jpayne@68
|
1719 """
|
jpayne@68
|
1720 getter, attribute = _get_target(target)
|
jpayne@68
|
1721 return _patch(
|
jpayne@68
|
1722 getter, attribute, new, spec, create,
|
jpayne@68
|
1723 spec_set, autospec, new_callable, kwargs
|
jpayne@68
|
1724 )
|
jpayne@68
|
1725
|
jpayne@68
|
1726
|
jpayne@68
|
1727 class _patch_dict(object):
|
jpayne@68
|
1728 """
|
jpayne@68
|
1729 Patch a dictionary, or dictionary like object, and restore the dictionary
|
jpayne@68
|
1730 to its original state after the test.
|
jpayne@68
|
1731
|
jpayne@68
|
1732 `in_dict` can be a dictionary or a mapping like container. If it is a
|
jpayne@68
|
1733 mapping then it must at least support getting, setting and deleting items
|
jpayne@68
|
1734 plus iterating over keys.
|
jpayne@68
|
1735
|
jpayne@68
|
1736 `in_dict` can also be a string specifying the name of the dictionary, which
|
jpayne@68
|
1737 will then be fetched by importing it.
|
jpayne@68
|
1738
|
jpayne@68
|
1739 `values` can be a dictionary of values to set in the dictionary. `values`
|
jpayne@68
|
1740 can also be an iterable of `(key, value)` pairs.
|
jpayne@68
|
1741
|
jpayne@68
|
1742 If `clear` is True then the dictionary will be cleared before the new
|
jpayne@68
|
1743 values are set.
|
jpayne@68
|
1744
|
jpayne@68
|
1745 `patch.dict` can also be called with arbitrary keyword arguments to set
|
jpayne@68
|
1746 values in the dictionary::
|
jpayne@68
|
1747
|
jpayne@68
|
1748 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
|
jpayne@68
|
1749 ...
|
jpayne@68
|
1750
|
jpayne@68
|
1751 `patch.dict` can be used as a context manager, decorator or class
|
jpayne@68
|
1752 decorator. When used as a class decorator `patch.dict` honours
|
jpayne@68
|
1753 `patch.TEST_PREFIX` for choosing which methods to wrap.
|
jpayne@68
|
1754 """
|
jpayne@68
|
1755
|
jpayne@68
|
1756 def __init__(self, in_dict, values=(), clear=False, **kwargs):
|
jpayne@68
|
1757 self.in_dict = in_dict
|
jpayne@68
|
1758 # support any argument supported by dict(...) constructor
|
jpayne@68
|
1759 self.values = dict(values)
|
jpayne@68
|
1760 self.values.update(kwargs)
|
jpayne@68
|
1761 self.clear = clear
|
jpayne@68
|
1762 self._original = None
|
jpayne@68
|
1763
|
jpayne@68
|
1764
|
jpayne@68
|
1765 def __call__(self, f):
|
jpayne@68
|
1766 if isinstance(f, type):
|
jpayne@68
|
1767 return self.decorate_class(f)
|
jpayne@68
|
1768 @wraps(f)
|
jpayne@68
|
1769 def _inner(*args, **kw):
|
jpayne@68
|
1770 self._patch_dict()
|
jpayne@68
|
1771 try:
|
jpayne@68
|
1772 return f(*args, **kw)
|
jpayne@68
|
1773 finally:
|
jpayne@68
|
1774 self._unpatch_dict()
|
jpayne@68
|
1775
|
jpayne@68
|
1776 return _inner
|
jpayne@68
|
1777
|
jpayne@68
|
1778
|
jpayne@68
|
1779 def decorate_class(self, klass):
|
jpayne@68
|
1780 for attr in dir(klass):
|
jpayne@68
|
1781 attr_value = getattr(klass, attr)
|
jpayne@68
|
1782 if (attr.startswith(patch.TEST_PREFIX) and
|
jpayne@68
|
1783 hasattr(attr_value, "__call__")):
|
jpayne@68
|
1784 decorator = _patch_dict(self.in_dict, self.values, self.clear)
|
jpayne@68
|
1785 decorated = decorator(attr_value)
|
jpayne@68
|
1786 setattr(klass, attr, decorated)
|
jpayne@68
|
1787 return klass
|
jpayne@68
|
1788
|
jpayne@68
|
1789
|
jpayne@68
|
1790 def __enter__(self):
|
jpayne@68
|
1791 """Patch the dict."""
|
jpayne@68
|
1792 self._patch_dict()
|
jpayne@68
|
1793 return self.in_dict
|
jpayne@68
|
1794
|
jpayne@68
|
1795
|
jpayne@68
|
1796 def _patch_dict(self):
|
jpayne@68
|
1797 values = self.values
|
jpayne@68
|
1798 if isinstance(self.in_dict, str):
|
jpayne@68
|
1799 self.in_dict = _importer(self.in_dict)
|
jpayne@68
|
1800 in_dict = self.in_dict
|
jpayne@68
|
1801 clear = self.clear
|
jpayne@68
|
1802
|
jpayne@68
|
1803 try:
|
jpayne@68
|
1804 original = in_dict.copy()
|
jpayne@68
|
1805 except AttributeError:
|
jpayne@68
|
1806 # dict like object with no copy method
|
jpayne@68
|
1807 # must support iteration over keys
|
jpayne@68
|
1808 original = {}
|
jpayne@68
|
1809 for key in in_dict:
|
jpayne@68
|
1810 original[key] = in_dict[key]
|
jpayne@68
|
1811 self._original = original
|
jpayne@68
|
1812
|
jpayne@68
|
1813 if clear:
|
jpayne@68
|
1814 _clear_dict(in_dict)
|
jpayne@68
|
1815
|
jpayne@68
|
1816 try:
|
jpayne@68
|
1817 in_dict.update(values)
|
jpayne@68
|
1818 except AttributeError:
|
jpayne@68
|
1819 # dict like object with no update method
|
jpayne@68
|
1820 for key in values:
|
jpayne@68
|
1821 in_dict[key] = values[key]
|
jpayne@68
|
1822
|
jpayne@68
|
1823
|
jpayne@68
|
1824 def _unpatch_dict(self):
|
jpayne@68
|
1825 in_dict = self.in_dict
|
jpayne@68
|
1826 original = self._original
|
jpayne@68
|
1827
|
jpayne@68
|
1828 _clear_dict(in_dict)
|
jpayne@68
|
1829
|
jpayne@68
|
1830 try:
|
jpayne@68
|
1831 in_dict.update(original)
|
jpayne@68
|
1832 except AttributeError:
|
jpayne@68
|
1833 for key in original:
|
jpayne@68
|
1834 in_dict[key] = original[key]
|
jpayne@68
|
1835
|
jpayne@68
|
1836
|
jpayne@68
|
1837 def __exit__(self, *args):
|
jpayne@68
|
1838 """Unpatch the dict."""
|
jpayne@68
|
1839 self._unpatch_dict()
|
jpayne@68
|
1840 return False
|
jpayne@68
|
1841
|
jpayne@68
|
1842 start = __enter__
|
jpayne@68
|
1843 stop = __exit__
|
jpayne@68
|
1844
|
jpayne@68
|
1845
|
jpayne@68
|
1846 def _clear_dict(in_dict):
|
jpayne@68
|
1847 try:
|
jpayne@68
|
1848 in_dict.clear()
|
jpayne@68
|
1849 except AttributeError:
|
jpayne@68
|
1850 keys = list(in_dict)
|
jpayne@68
|
1851 for key in keys:
|
jpayne@68
|
1852 del in_dict[key]
|
jpayne@68
|
1853
|
jpayne@68
|
1854
|
jpayne@68
|
1855 def _patch_stopall():
|
jpayne@68
|
1856 """Stop all active patches. LIFO to unroll nested patches."""
|
jpayne@68
|
1857 for patch in reversed(_patch._active_patches):
|
jpayne@68
|
1858 patch.stop()
|
jpayne@68
|
1859
|
jpayne@68
|
1860
|
jpayne@68
|
1861 patch.object = _patch_object
|
jpayne@68
|
1862 patch.dict = _patch_dict
|
jpayne@68
|
1863 patch.multiple = _patch_multiple
|
jpayne@68
|
1864 patch.stopall = _patch_stopall
|
jpayne@68
|
1865 patch.TEST_PREFIX = 'test'
|
jpayne@68
|
1866
|
jpayne@68
|
1867 magic_methods = (
|
jpayne@68
|
1868 "lt le gt ge eq ne "
|
jpayne@68
|
1869 "getitem setitem delitem "
|
jpayne@68
|
1870 "len contains iter "
|
jpayne@68
|
1871 "hash str sizeof "
|
jpayne@68
|
1872 "enter exit "
|
jpayne@68
|
1873 # we added divmod and rdivmod here instead of numerics
|
jpayne@68
|
1874 # because there is no idivmod
|
jpayne@68
|
1875 "divmod rdivmod neg pos abs invert "
|
jpayne@68
|
1876 "complex int float index "
|
jpayne@68
|
1877 "round trunc floor ceil "
|
jpayne@68
|
1878 "bool next "
|
jpayne@68
|
1879 "fspath "
|
jpayne@68
|
1880 "aiter "
|
jpayne@68
|
1881 )
|
jpayne@68
|
1882
|
jpayne@68
|
1883 numerics = (
|
jpayne@68
|
1884 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
|
jpayne@68
|
1885 )
|
jpayne@68
|
1886 inplace = ' '.join('i%s' % n for n in numerics.split())
|
jpayne@68
|
1887 right = ' '.join('r%s' % n for n in numerics.split())
|
jpayne@68
|
1888
|
jpayne@68
|
1889 # not including __prepare__, __instancecheck__, __subclasscheck__
|
jpayne@68
|
1890 # (as they are metaclass methods)
|
jpayne@68
|
1891 # __del__ is not supported at all as it causes problems if it exists
|
jpayne@68
|
1892
|
jpayne@68
|
1893 _non_defaults = {
|
jpayne@68
|
1894 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
|
jpayne@68
|
1895 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
|
jpayne@68
|
1896 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
|
jpayne@68
|
1897 '__repr__', '__dir__', '__subclasses__', '__format__',
|
jpayne@68
|
1898 '__getnewargs_ex__',
|
jpayne@68
|
1899 }
|
jpayne@68
|
1900
|
jpayne@68
|
1901
|
jpayne@68
|
1902 def _get_method(name, func):
|
jpayne@68
|
1903 "Turns a callable object (like a mock) into a real function"
|
jpayne@68
|
1904 def method(self, /, *args, **kw):
|
jpayne@68
|
1905 return func(self, *args, **kw)
|
jpayne@68
|
1906 method.__name__ = name
|
jpayne@68
|
1907 return method
|
jpayne@68
|
1908
|
jpayne@68
|
1909
|
jpayne@68
|
1910 _magics = {
|
jpayne@68
|
1911 '__%s__' % method for method in
|
jpayne@68
|
1912 ' '.join([magic_methods, numerics, inplace, right]).split()
|
jpayne@68
|
1913 }
|
jpayne@68
|
1914
|
jpayne@68
|
1915 # Magic methods used for async `with` statements
|
jpayne@68
|
1916 _async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
|
jpayne@68
|
1917 # Magic methods that are only used with async calls but are synchronous functions themselves
|
jpayne@68
|
1918 _sync_async_magics = {"__aiter__"}
|
jpayne@68
|
1919 _async_magics = _async_method_magics | _sync_async_magics
|
jpayne@68
|
1920
|
jpayne@68
|
1921 _all_sync_magics = _magics | _non_defaults
|
jpayne@68
|
1922 _all_magics = _all_sync_magics | _async_magics
|
jpayne@68
|
1923
|
jpayne@68
|
1924 _unsupported_magics = {
|
jpayne@68
|
1925 '__getattr__', '__setattr__',
|
jpayne@68
|
1926 '__init__', '__new__', '__prepare__',
|
jpayne@68
|
1927 '__instancecheck__', '__subclasscheck__',
|
jpayne@68
|
1928 '__del__'
|
jpayne@68
|
1929 }
|
jpayne@68
|
1930
|
jpayne@68
|
1931 _calculate_return_value = {
|
jpayne@68
|
1932 '__hash__': lambda self: object.__hash__(self),
|
jpayne@68
|
1933 '__str__': lambda self: object.__str__(self),
|
jpayne@68
|
1934 '__sizeof__': lambda self: object.__sizeof__(self),
|
jpayne@68
|
1935 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
|
jpayne@68
|
1936 }
|
jpayne@68
|
1937
|
jpayne@68
|
1938 _return_values = {
|
jpayne@68
|
1939 '__lt__': NotImplemented,
|
jpayne@68
|
1940 '__gt__': NotImplemented,
|
jpayne@68
|
1941 '__le__': NotImplemented,
|
jpayne@68
|
1942 '__ge__': NotImplemented,
|
jpayne@68
|
1943 '__int__': 1,
|
jpayne@68
|
1944 '__contains__': False,
|
jpayne@68
|
1945 '__len__': 0,
|
jpayne@68
|
1946 '__exit__': False,
|
jpayne@68
|
1947 '__complex__': 1j,
|
jpayne@68
|
1948 '__float__': 1.0,
|
jpayne@68
|
1949 '__bool__': True,
|
jpayne@68
|
1950 '__index__': 1,
|
jpayne@68
|
1951 '__aexit__': False,
|
jpayne@68
|
1952 }
|
jpayne@68
|
1953
|
jpayne@68
|
1954
|
jpayne@68
|
1955 def _get_eq(self):
|
jpayne@68
|
1956 def __eq__(other):
|
jpayne@68
|
1957 ret_val = self.__eq__._mock_return_value
|
jpayne@68
|
1958 if ret_val is not DEFAULT:
|
jpayne@68
|
1959 return ret_val
|
jpayne@68
|
1960 if self is other:
|
jpayne@68
|
1961 return True
|
jpayne@68
|
1962 return NotImplemented
|
jpayne@68
|
1963 return __eq__
|
jpayne@68
|
1964
|
jpayne@68
|
1965 def _get_ne(self):
|
jpayne@68
|
1966 def __ne__(other):
|
jpayne@68
|
1967 if self.__ne__._mock_return_value is not DEFAULT:
|
jpayne@68
|
1968 return DEFAULT
|
jpayne@68
|
1969 if self is other:
|
jpayne@68
|
1970 return False
|
jpayne@68
|
1971 return NotImplemented
|
jpayne@68
|
1972 return __ne__
|
jpayne@68
|
1973
|
jpayne@68
|
1974 def _get_iter(self):
|
jpayne@68
|
1975 def __iter__():
|
jpayne@68
|
1976 ret_val = self.__iter__._mock_return_value
|
jpayne@68
|
1977 if ret_val is DEFAULT:
|
jpayne@68
|
1978 return iter([])
|
jpayne@68
|
1979 # if ret_val was already an iterator, then calling iter on it should
|
jpayne@68
|
1980 # return the iterator unchanged
|
jpayne@68
|
1981 return iter(ret_val)
|
jpayne@68
|
1982 return __iter__
|
jpayne@68
|
1983
|
jpayne@68
|
1984 def _get_async_iter(self):
|
jpayne@68
|
1985 def __aiter__():
|
jpayne@68
|
1986 ret_val = self.__aiter__._mock_return_value
|
jpayne@68
|
1987 if ret_val is DEFAULT:
|
jpayne@68
|
1988 return _AsyncIterator(iter([]))
|
jpayne@68
|
1989 return _AsyncIterator(iter(ret_val))
|
jpayne@68
|
1990 return __aiter__
|
jpayne@68
|
1991
|
jpayne@68
|
1992 _side_effect_methods = {
|
jpayne@68
|
1993 '__eq__': _get_eq,
|
jpayne@68
|
1994 '__ne__': _get_ne,
|
jpayne@68
|
1995 '__iter__': _get_iter,
|
jpayne@68
|
1996 '__aiter__': _get_async_iter
|
jpayne@68
|
1997 }
|
jpayne@68
|
1998
|
jpayne@68
|
1999
|
jpayne@68
|
2000
|
jpayne@68
|
2001 def _set_return_value(mock, method, name):
|
jpayne@68
|
2002 fixed = _return_values.get(name, DEFAULT)
|
jpayne@68
|
2003 if fixed is not DEFAULT:
|
jpayne@68
|
2004 method.return_value = fixed
|
jpayne@68
|
2005 return
|
jpayne@68
|
2006
|
jpayne@68
|
2007 return_calculator = _calculate_return_value.get(name)
|
jpayne@68
|
2008 if return_calculator is not None:
|
jpayne@68
|
2009 return_value = return_calculator(mock)
|
jpayne@68
|
2010 method.return_value = return_value
|
jpayne@68
|
2011 return
|
jpayne@68
|
2012
|
jpayne@68
|
2013 side_effector = _side_effect_methods.get(name)
|
jpayne@68
|
2014 if side_effector is not None:
|
jpayne@68
|
2015 method.side_effect = side_effector(mock)
|
jpayne@68
|
2016
|
jpayne@68
|
2017
|
jpayne@68
|
2018
|
jpayne@68
|
2019 class MagicMixin(Base):
|
jpayne@68
|
2020 def __init__(self, /, *args, **kw):
|
jpayne@68
|
2021 self._mock_set_magics() # make magic work for kwargs in init
|
jpayne@68
|
2022 _safe_super(MagicMixin, self).__init__(*args, **kw)
|
jpayne@68
|
2023 self._mock_set_magics() # fix magic broken by upper level init
|
jpayne@68
|
2024
|
jpayne@68
|
2025
|
jpayne@68
|
2026 def _mock_set_magics(self):
|
jpayne@68
|
2027 orig_magics = _magics | _async_method_magics
|
jpayne@68
|
2028 these_magics = orig_magics
|
jpayne@68
|
2029
|
jpayne@68
|
2030 if getattr(self, "_mock_methods", None) is not None:
|
jpayne@68
|
2031 these_magics = orig_magics.intersection(self._mock_methods)
|
jpayne@68
|
2032
|
jpayne@68
|
2033 remove_magics = set()
|
jpayne@68
|
2034 remove_magics = orig_magics - these_magics
|
jpayne@68
|
2035
|
jpayne@68
|
2036 for entry in remove_magics:
|
jpayne@68
|
2037 if entry in type(self).__dict__:
|
jpayne@68
|
2038 # remove unneeded magic methods
|
jpayne@68
|
2039 delattr(self, entry)
|
jpayne@68
|
2040
|
jpayne@68
|
2041 # don't overwrite existing attributes if called a second time
|
jpayne@68
|
2042 these_magics = these_magics - set(type(self).__dict__)
|
jpayne@68
|
2043
|
jpayne@68
|
2044 _type = type(self)
|
jpayne@68
|
2045 for entry in these_magics:
|
jpayne@68
|
2046 setattr(_type, entry, MagicProxy(entry, self))
|
jpayne@68
|
2047
|
jpayne@68
|
2048
|
jpayne@68
|
2049
|
jpayne@68
|
2050 class NonCallableMagicMock(MagicMixin, NonCallableMock):
|
jpayne@68
|
2051 """A version of `MagicMock` that isn't callable."""
|
jpayne@68
|
2052 def mock_add_spec(self, spec, spec_set=False):
|
jpayne@68
|
2053 """Add a spec to a mock. `spec` can either be an object or a
|
jpayne@68
|
2054 list of strings. Only attributes on the `spec` can be fetched as
|
jpayne@68
|
2055 attributes from the mock.
|
jpayne@68
|
2056
|
jpayne@68
|
2057 If `spec_set` is True then only attributes on the spec can be set."""
|
jpayne@68
|
2058 self._mock_add_spec(spec, spec_set)
|
jpayne@68
|
2059 self._mock_set_magics()
|
jpayne@68
|
2060
|
jpayne@68
|
2061
|
jpayne@68
|
2062 class AsyncMagicMixin(MagicMixin):
|
jpayne@68
|
2063 def __init__(self, /, *args, **kw):
|
jpayne@68
|
2064 self._mock_set_magics() # make magic work for kwargs in init
|
jpayne@68
|
2065 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)
|
jpayne@68
|
2066 self._mock_set_magics() # fix magic broken by upper level init
|
jpayne@68
|
2067
|
jpayne@68
|
2068 class MagicMock(MagicMixin, Mock):
|
jpayne@68
|
2069 """
|
jpayne@68
|
2070 MagicMock is a subclass of Mock with default implementations
|
jpayne@68
|
2071 of most of the magic methods. You can use MagicMock without having to
|
jpayne@68
|
2072 configure the magic methods yourself.
|
jpayne@68
|
2073
|
jpayne@68
|
2074 If you use the `spec` or `spec_set` arguments then *only* magic
|
jpayne@68
|
2075 methods that exist in the spec will be created.
|
jpayne@68
|
2076
|
jpayne@68
|
2077 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
|
jpayne@68
|
2078 """
|
jpayne@68
|
2079 def mock_add_spec(self, spec, spec_set=False):
|
jpayne@68
|
2080 """Add a spec to a mock. `spec` can either be an object or a
|
jpayne@68
|
2081 list of strings. Only attributes on the `spec` can be fetched as
|
jpayne@68
|
2082 attributes from the mock.
|
jpayne@68
|
2083
|
jpayne@68
|
2084 If `spec_set` is True then only attributes on the spec can be set."""
|
jpayne@68
|
2085 self._mock_add_spec(spec, spec_set)
|
jpayne@68
|
2086 self._mock_set_magics()
|
jpayne@68
|
2087
|
jpayne@68
|
2088
|
jpayne@68
|
2089
|
jpayne@68
|
2090 class MagicProxy(Base):
|
jpayne@68
|
2091 def __init__(self, name, parent):
|
jpayne@68
|
2092 self.name = name
|
jpayne@68
|
2093 self.parent = parent
|
jpayne@68
|
2094
|
jpayne@68
|
2095 def create_mock(self):
|
jpayne@68
|
2096 entry = self.name
|
jpayne@68
|
2097 parent = self.parent
|
jpayne@68
|
2098 m = parent._get_child_mock(name=entry, _new_name=entry,
|
jpayne@68
|
2099 _new_parent=parent)
|
jpayne@68
|
2100 setattr(parent, entry, m)
|
jpayne@68
|
2101 _set_return_value(parent, m, entry)
|
jpayne@68
|
2102 return m
|
jpayne@68
|
2103
|
jpayne@68
|
2104 def __get__(self, obj, _type=None):
|
jpayne@68
|
2105 return self.create_mock()
|
jpayne@68
|
2106
|
jpayne@68
|
2107
|
jpayne@68
|
2108 class AsyncMockMixin(Base):
|
jpayne@68
|
2109 await_count = _delegating_property('await_count')
|
jpayne@68
|
2110 await_args = _delegating_property('await_args')
|
jpayne@68
|
2111 await_args_list = _delegating_property('await_args_list')
|
jpayne@68
|
2112
|
jpayne@68
|
2113 def __init__(self, /, *args, **kwargs):
|
jpayne@68
|
2114 super().__init__(*args, **kwargs)
|
jpayne@68
|
2115 # asyncio.iscoroutinefunction() checks _is_coroutine property to say if an
|
jpayne@68
|
2116 # object is a coroutine. Without this check it looks to see if it is a
|
jpayne@68
|
2117 # function/method, which in this case it is not (since it is an
|
jpayne@68
|
2118 # AsyncMock).
|
jpayne@68
|
2119 # It is set through __dict__ because when spec_set is True, this
|
jpayne@68
|
2120 # attribute is likely undefined.
|
jpayne@68
|
2121 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
|
jpayne@68
|
2122 self.__dict__['_mock_await_count'] = 0
|
jpayne@68
|
2123 self.__dict__['_mock_await_args'] = None
|
jpayne@68
|
2124 self.__dict__['_mock_await_args_list'] = _CallList()
|
jpayne@68
|
2125 code_mock = NonCallableMock(spec_set=CodeType)
|
jpayne@68
|
2126 code_mock.co_flags = inspect.CO_COROUTINE
|
jpayne@68
|
2127 self.__dict__['__code__'] = code_mock
|
jpayne@68
|
2128
|
jpayne@68
|
2129 async def _execute_mock_call(self, /, *args, **kwargs):
|
jpayne@68
|
2130 # This is nearly just like super(), except for sepcial handling
|
jpayne@68
|
2131 # of coroutines
|
jpayne@68
|
2132
|
jpayne@68
|
2133 _call = self.call_args
|
jpayne@68
|
2134 self.await_count += 1
|
jpayne@68
|
2135 self.await_args = _call
|
jpayne@68
|
2136 self.await_args_list.append(_call)
|
jpayne@68
|
2137
|
jpayne@68
|
2138 effect = self.side_effect
|
jpayne@68
|
2139 if effect is not None:
|
jpayne@68
|
2140 if _is_exception(effect):
|
jpayne@68
|
2141 raise effect
|
jpayne@68
|
2142 elif not _callable(effect):
|
jpayne@68
|
2143 try:
|
jpayne@68
|
2144 result = next(effect)
|
jpayne@68
|
2145 except StopIteration:
|
jpayne@68
|
2146 # It is impossible to propogate a StopIteration
|
jpayne@68
|
2147 # through coroutines because of PEP 479
|
jpayne@68
|
2148 raise StopAsyncIteration
|
jpayne@68
|
2149 if _is_exception(result):
|
jpayne@68
|
2150 raise result
|
jpayne@68
|
2151 elif asyncio.iscoroutinefunction(effect):
|
jpayne@68
|
2152 result = await effect(*args, **kwargs)
|
jpayne@68
|
2153 else:
|
jpayne@68
|
2154 result = effect(*args, **kwargs)
|
jpayne@68
|
2155
|
jpayne@68
|
2156 if result is not DEFAULT:
|
jpayne@68
|
2157 return result
|
jpayne@68
|
2158
|
jpayne@68
|
2159 if self._mock_return_value is not DEFAULT:
|
jpayne@68
|
2160 return self.return_value
|
jpayne@68
|
2161
|
jpayne@68
|
2162 if self._mock_wraps is not None:
|
jpayne@68
|
2163 if asyncio.iscoroutinefunction(self._mock_wraps):
|
jpayne@68
|
2164 return await self._mock_wraps(*args, **kwargs)
|
jpayne@68
|
2165 return self._mock_wraps(*args, **kwargs)
|
jpayne@68
|
2166
|
jpayne@68
|
2167 return self.return_value
|
jpayne@68
|
2168
|
jpayne@68
|
2169 def assert_awaited(self):
|
jpayne@68
|
2170 """
|
jpayne@68
|
2171 Assert that the mock was awaited at least once.
|
jpayne@68
|
2172 """
|
jpayne@68
|
2173 if self.await_count == 0:
|
jpayne@68
|
2174 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
|
jpayne@68
|
2175 raise AssertionError(msg)
|
jpayne@68
|
2176
|
jpayne@68
|
2177 def assert_awaited_once(self):
|
jpayne@68
|
2178 """
|
jpayne@68
|
2179 Assert that the mock was awaited exactly once.
|
jpayne@68
|
2180 """
|
jpayne@68
|
2181 if not self.await_count == 1:
|
jpayne@68
|
2182 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
|
jpayne@68
|
2183 f" Awaited {self.await_count} times.")
|
jpayne@68
|
2184 raise AssertionError(msg)
|
jpayne@68
|
2185
|
jpayne@68
|
2186 def assert_awaited_with(self, /, *args, **kwargs):
|
jpayne@68
|
2187 """
|
jpayne@68
|
2188 Assert that the last await was with the specified arguments.
|
jpayne@68
|
2189 """
|
jpayne@68
|
2190 if self.await_args is None:
|
jpayne@68
|
2191 expected = self._format_mock_call_signature(args, kwargs)
|
jpayne@68
|
2192 raise AssertionError(f'Expected await: {expected}\nNot awaited')
|
jpayne@68
|
2193
|
jpayne@68
|
2194 def _error_message():
|
jpayne@68
|
2195 msg = self._format_mock_failure_message(args, kwargs, action='await')
|
jpayne@68
|
2196 return msg
|
jpayne@68
|
2197
|
jpayne@68
|
2198 expected = self._call_matcher((args, kwargs))
|
jpayne@68
|
2199 actual = self._call_matcher(self.await_args)
|
jpayne@68
|
2200 if expected != actual:
|
jpayne@68
|
2201 cause = expected if isinstance(expected, Exception) else None
|
jpayne@68
|
2202 raise AssertionError(_error_message()) from cause
|
jpayne@68
|
2203
|
jpayne@68
|
2204 def assert_awaited_once_with(self, /, *args, **kwargs):
|
jpayne@68
|
2205 """
|
jpayne@68
|
2206 Assert that the mock was awaited exactly once and with the specified
|
jpayne@68
|
2207 arguments.
|
jpayne@68
|
2208 """
|
jpayne@68
|
2209 if not self.await_count == 1:
|
jpayne@68
|
2210 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
|
jpayne@68
|
2211 f" Awaited {self.await_count} times.")
|
jpayne@68
|
2212 raise AssertionError(msg)
|
jpayne@68
|
2213 return self.assert_awaited_with(*args, **kwargs)
|
jpayne@68
|
2214
|
jpayne@68
|
2215 def assert_any_await(self, /, *args, **kwargs):
|
jpayne@68
|
2216 """
|
jpayne@68
|
2217 Assert the mock has ever been awaited with the specified arguments.
|
jpayne@68
|
2218 """
|
jpayne@68
|
2219 expected = self._call_matcher((args, kwargs))
|
jpayne@68
|
2220 actual = [self._call_matcher(c) for c in self.await_args_list]
|
jpayne@68
|
2221 if expected not in actual:
|
jpayne@68
|
2222 cause = expected if isinstance(expected, Exception) else None
|
jpayne@68
|
2223 expected_string = self._format_mock_call_signature(args, kwargs)
|
jpayne@68
|
2224 raise AssertionError(
|
jpayne@68
|
2225 '%s await not found' % expected_string
|
jpayne@68
|
2226 ) from cause
|
jpayne@68
|
2227
|
jpayne@68
|
2228 def assert_has_awaits(self, calls, any_order=False):
|
jpayne@68
|
2229 """
|
jpayne@68
|
2230 Assert the mock has been awaited with the specified calls.
|
jpayne@68
|
2231 The :attr:`await_args_list` list is checked for the awaits.
|
jpayne@68
|
2232
|
jpayne@68
|
2233 If `any_order` is False (the default) then the awaits must be
|
jpayne@68
|
2234 sequential. There can be extra calls before or after the
|
jpayne@68
|
2235 specified awaits.
|
jpayne@68
|
2236
|
jpayne@68
|
2237 If `any_order` is True then the awaits can be in any order, but
|
jpayne@68
|
2238 they must all appear in :attr:`await_args_list`.
|
jpayne@68
|
2239 """
|
jpayne@68
|
2240 expected = [self._call_matcher(c) for c in calls]
|
jpayne@68
|
2241 cause = next((e for e in expected if isinstance(e, Exception)), None)
|
jpayne@68
|
2242 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
|
jpayne@68
|
2243 if not any_order:
|
jpayne@68
|
2244 if expected not in all_awaits:
|
jpayne@68
|
2245 if cause is None:
|
jpayne@68
|
2246 problem = 'Awaits not found.'
|
jpayne@68
|
2247 else:
|
jpayne@68
|
2248 problem = ('Error processing expected awaits.\n'
|
jpayne@68
|
2249 'Errors: {}').format(
|
jpayne@68
|
2250 [e if isinstance(e, Exception) else None
|
jpayne@68
|
2251 for e in expected])
|
jpayne@68
|
2252 raise AssertionError(
|
jpayne@68
|
2253 f'{problem}\n'
|
jpayne@68
|
2254 f'Expected: {_CallList(calls)}\n'
|
jpayne@68
|
2255 f'Actual: {self.await_args_list}'
|
jpayne@68
|
2256 ) from cause
|
jpayne@68
|
2257 return
|
jpayne@68
|
2258
|
jpayne@68
|
2259 all_awaits = list(all_awaits)
|
jpayne@68
|
2260
|
jpayne@68
|
2261 not_found = []
|
jpayne@68
|
2262 for kall in expected:
|
jpayne@68
|
2263 try:
|
jpayne@68
|
2264 all_awaits.remove(kall)
|
jpayne@68
|
2265 except ValueError:
|
jpayne@68
|
2266 not_found.append(kall)
|
jpayne@68
|
2267 if not_found:
|
jpayne@68
|
2268 raise AssertionError(
|
jpayne@68
|
2269 '%r not all found in await list' % (tuple(not_found),)
|
jpayne@68
|
2270 ) from cause
|
jpayne@68
|
2271
|
jpayne@68
|
2272 def assert_not_awaited(self):
|
jpayne@68
|
2273 """
|
jpayne@68
|
2274 Assert that the mock was never awaited.
|
jpayne@68
|
2275 """
|
jpayne@68
|
2276 if self.await_count != 0:
|
jpayne@68
|
2277 msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
|
jpayne@68
|
2278 f" Awaited {self.await_count} times.")
|
jpayne@68
|
2279 raise AssertionError(msg)
|
jpayne@68
|
2280
|
jpayne@68
|
2281 def reset_mock(self, /, *args, **kwargs):
|
jpayne@68
|
2282 """
|
jpayne@68
|
2283 See :func:`.Mock.reset_mock()`
|
jpayne@68
|
2284 """
|
jpayne@68
|
2285 super().reset_mock(*args, **kwargs)
|
jpayne@68
|
2286 self.await_count = 0
|
jpayne@68
|
2287 self.await_args = None
|
jpayne@68
|
2288 self.await_args_list = _CallList()
|
jpayne@68
|
2289
|
jpayne@68
|
2290
|
jpayne@68
|
2291 class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
|
jpayne@68
|
2292 """
|
jpayne@68
|
2293 Enhance :class:`Mock` with features allowing to mock
|
jpayne@68
|
2294 an async function.
|
jpayne@68
|
2295
|
jpayne@68
|
2296 The :class:`AsyncMock` object will behave so the object is
|
jpayne@68
|
2297 recognized as an async function, and the result of a call is an awaitable:
|
jpayne@68
|
2298
|
jpayne@68
|
2299 >>> mock = AsyncMock()
|
jpayne@68
|
2300 >>> asyncio.iscoroutinefunction(mock)
|
jpayne@68
|
2301 True
|
jpayne@68
|
2302 >>> inspect.isawaitable(mock())
|
jpayne@68
|
2303 True
|
jpayne@68
|
2304
|
jpayne@68
|
2305
|
jpayne@68
|
2306 The result of ``mock()`` is an async function which will have the outcome
|
jpayne@68
|
2307 of ``side_effect`` or ``return_value``:
|
jpayne@68
|
2308
|
jpayne@68
|
2309 - if ``side_effect`` is a function, the async function will return the
|
jpayne@68
|
2310 result of that function,
|
jpayne@68
|
2311 - if ``side_effect`` is an exception, the async function will raise the
|
jpayne@68
|
2312 exception,
|
jpayne@68
|
2313 - if ``side_effect`` is an iterable, the async function will return the
|
jpayne@68
|
2314 next value of the iterable, however, if the sequence of result is
|
jpayne@68
|
2315 exhausted, ``StopIteration`` is raised immediately,
|
jpayne@68
|
2316 - if ``side_effect`` is not defined, the async function will return the
|
jpayne@68
|
2317 value defined by ``return_value``, hence, by default, the async function
|
jpayne@68
|
2318 returns a new :class:`AsyncMock` object.
|
jpayne@68
|
2319
|
jpayne@68
|
2320 If the outcome of ``side_effect`` or ``return_value`` is an async function,
|
jpayne@68
|
2321 the mock async function obtained when the mock object is called will be this
|
jpayne@68
|
2322 async function itself (and not an async function returning an async
|
jpayne@68
|
2323 function).
|
jpayne@68
|
2324
|
jpayne@68
|
2325 The test author can also specify a wrapped object with ``wraps``. In this
|
jpayne@68
|
2326 case, the :class:`Mock` object behavior is the same as with an
|
jpayne@68
|
2327 :class:`.Mock` object: the wrapped object may have methods
|
jpayne@68
|
2328 defined as async function functions.
|
jpayne@68
|
2329
|
jpayne@68
|
2330 Based on Martin Richard's asynctest project.
|
jpayne@68
|
2331 """
|
jpayne@68
|
2332
|
jpayne@68
|
2333
|
jpayne@68
|
2334 class _ANY(object):
|
jpayne@68
|
2335 "A helper object that compares equal to everything."
|
jpayne@68
|
2336
|
jpayne@68
|
2337 def __eq__(self, other):
|
jpayne@68
|
2338 return True
|
jpayne@68
|
2339
|
jpayne@68
|
2340 def __ne__(self, other):
|
jpayne@68
|
2341 return False
|
jpayne@68
|
2342
|
jpayne@68
|
2343 def __repr__(self):
|
jpayne@68
|
2344 return '<ANY>'
|
jpayne@68
|
2345
|
jpayne@68
|
2346 ANY = _ANY()
|
jpayne@68
|
2347
|
jpayne@68
|
2348
|
jpayne@68
|
2349
|
jpayne@68
|
2350 def _format_call_signature(name, args, kwargs):
|
jpayne@68
|
2351 message = '%s(%%s)' % name
|
jpayne@68
|
2352 formatted_args = ''
|
jpayne@68
|
2353 args_string = ', '.join([repr(arg) for arg in args])
|
jpayne@68
|
2354 kwargs_string = ', '.join([
|
jpayne@68
|
2355 '%s=%r' % (key, value) for key, value in kwargs.items()
|
jpayne@68
|
2356 ])
|
jpayne@68
|
2357 if args_string:
|
jpayne@68
|
2358 formatted_args = args_string
|
jpayne@68
|
2359 if kwargs_string:
|
jpayne@68
|
2360 if formatted_args:
|
jpayne@68
|
2361 formatted_args += ', '
|
jpayne@68
|
2362 formatted_args += kwargs_string
|
jpayne@68
|
2363
|
jpayne@68
|
2364 return message % formatted_args
|
jpayne@68
|
2365
|
jpayne@68
|
2366
|
jpayne@68
|
2367
|
jpayne@68
|
2368 class _Call(tuple):
|
jpayne@68
|
2369 """
|
jpayne@68
|
2370 A tuple for holding the results of a call to a mock, either in the form
|
jpayne@68
|
2371 `(args, kwargs)` or `(name, args, kwargs)`.
|
jpayne@68
|
2372
|
jpayne@68
|
2373 If args or kwargs are empty then a call tuple will compare equal to
|
jpayne@68
|
2374 a tuple without those values. This makes comparisons less verbose::
|
jpayne@68
|
2375
|
jpayne@68
|
2376 _Call(('name', (), {})) == ('name',)
|
jpayne@68
|
2377 _Call(('name', (1,), {})) == ('name', (1,))
|
jpayne@68
|
2378 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
|
jpayne@68
|
2379
|
jpayne@68
|
2380 The `_Call` object provides a useful shortcut for comparing with call::
|
jpayne@68
|
2381
|
jpayne@68
|
2382 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
|
jpayne@68
|
2383 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
|
jpayne@68
|
2384
|
jpayne@68
|
2385 If the _Call has no name then it will match any name.
|
jpayne@68
|
2386 """
|
jpayne@68
|
2387 def __new__(cls, value=(), name='', parent=None, two=False,
|
jpayne@68
|
2388 from_kall=True):
|
jpayne@68
|
2389 args = ()
|
jpayne@68
|
2390 kwargs = {}
|
jpayne@68
|
2391 _len = len(value)
|
jpayne@68
|
2392 if _len == 3:
|
jpayne@68
|
2393 name, args, kwargs = value
|
jpayne@68
|
2394 elif _len == 2:
|
jpayne@68
|
2395 first, second = value
|
jpayne@68
|
2396 if isinstance(first, str):
|
jpayne@68
|
2397 name = first
|
jpayne@68
|
2398 if isinstance(second, tuple):
|
jpayne@68
|
2399 args = second
|
jpayne@68
|
2400 else:
|
jpayne@68
|
2401 kwargs = second
|
jpayne@68
|
2402 else:
|
jpayne@68
|
2403 args, kwargs = first, second
|
jpayne@68
|
2404 elif _len == 1:
|
jpayne@68
|
2405 value, = value
|
jpayne@68
|
2406 if isinstance(value, str):
|
jpayne@68
|
2407 name = value
|
jpayne@68
|
2408 elif isinstance(value, tuple):
|
jpayne@68
|
2409 args = value
|
jpayne@68
|
2410 else:
|
jpayne@68
|
2411 kwargs = value
|
jpayne@68
|
2412
|
jpayne@68
|
2413 if two:
|
jpayne@68
|
2414 return tuple.__new__(cls, (args, kwargs))
|
jpayne@68
|
2415
|
jpayne@68
|
2416 return tuple.__new__(cls, (name, args, kwargs))
|
jpayne@68
|
2417
|
jpayne@68
|
2418
|
jpayne@68
|
2419 def __init__(self, value=(), name=None, parent=None, two=False,
|
jpayne@68
|
2420 from_kall=True):
|
jpayne@68
|
2421 self._mock_name = name
|
jpayne@68
|
2422 self._mock_parent = parent
|
jpayne@68
|
2423 self._mock_from_kall = from_kall
|
jpayne@68
|
2424
|
jpayne@68
|
2425
|
jpayne@68
|
2426 def __eq__(self, other):
|
jpayne@68
|
2427 if other is ANY:
|
jpayne@68
|
2428 return True
|
jpayne@68
|
2429 try:
|
jpayne@68
|
2430 len_other = len(other)
|
jpayne@68
|
2431 except TypeError:
|
jpayne@68
|
2432 return False
|
jpayne@68
|
2433
|
jpayne@68
|
2434 self_name = ''
|
jpayne@68
|
2435 if len(self) == 2:
|
jpayne@68
|
2436 self_args, self_kwargs = self
|
jpayne@68
|
2437 else:
|
jpayne@68
|
2438 self_name, self_args, self_kwargs = self
|
jpayne@68
|
2439
|
jpayne@68
|
2440 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
|
jpayne@68
|
2441 and self._mock_parent != other._mock_parent):
|
jpayne@68
|
2442 return False
|
jpayne@68
|
2443
|
jpayne@68
|
2444 other_name = ''
|
jpayne@68
|
2445 if len_other == 0:
|
jpayne@68
|
2446 other_args, other_kwargs = (), {}
|
jpayne@68
|
2447 elif len_other == 3:
|
jpayne@68
|
2448 other_name, other_args, other_kwargs = other
|
jpayne@68
|
2449 elif len_other == 1:
|
jpayne@68
|
2450 value, = other
|
jpayne@68
|
2451 if isinstance(value, tuple):
|
jpayne@68
|
2452 other_args = value
|
jpayne@68
|
2453 other_kwargs = {}
|
jpayne@68
|
2454 elif isinstance(value, str):
|
jpayne@68
|
2455 other_name = value
|
jpayne@68
|
2456 other_args, other_kwargs = (), {}
|
jpayne@68
|
2457 else:
|
jpayne@68
|
2458 other_args = ()
|
jpayne@68
|
2459 other_kwargs = value
|
jpayne@68
|
2460 elif len_other == 2:
|
jpayne@68
|
2461 # could be (name, args) or (name, kwargs) or (args, kwargs)
|
jpayne@68
|
2462 first, second = other
|
jpayne@68
|
2463 if isinstance(first, str):
|
jpayne@68
|
2464 other_name = first
|
jpayne@68
|
2465 if isinstance(second, tuple):
|
jpayne@68
|
2466 other_args, other_kwargs = second, {}
|
jpayne@68
|
2467 else:
|
jpayne@68
|
2468 other_args, other_kwargs = (), second
|
jpayne@68
|
2469 else:
|
jpayne@68
|
2470 other_args, other_kwargs = first, second
|
jpayne@68
|
2471 else:
|
jpayne@68
|
2472 return False
|
jpayne@68
|
2473
|
jpayne@68
|
2474 if self_name and other_name != self_name:
|
jpayne@68
|
2475 return False
|
jpayne@68
|
2476
|
jpayne@68
|
2477 # this order is important for ANY to work!
|
jpayne@68
|
2478 return (other_args, other_kwargs) == (self_args, self_kwargs)
|
jpayne@68
|
2479
|
jpayne@68
|
2480
|
jpayne@68
|
2481 __ne__ = object.__ne__
|
jpayne@68
|
2482
|
jpayne@68
|
2483
|
jpayne@68
|
2484 def __call__(self, /, *args, **kwargs):
|
jpayne@68
|
2485 if self._mock_name is None:
|
jpayne@68
|
2486 return _Call(('', args, kwargs), name='()')
|
jpayne@68
|
2487
|
jpayne@68
|
2488 name = self._mock_name + '()'
|
jpayne@68
|
2489 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
|
jpayne@68
|
2490
|
jpayne@68
|
2491
|
jpayne@68
|
2492 def __getattr__(self, attr):
|
jpayne@68
|
2493 if self._mock_name is None:
|
jpayne@68
|
2494 return _Call(name=attr, from_kall=False)
|
jpayne@68
|
2495 name = '%s.%s' % (self._mock_name, attr)
|
jpayne@68
|
2496 return _Call(name=name, parent=self, from_kall=False)
|
jpayne@68
|
2497
|
jpayne@68
|
2498
|
jpayne@68
|
2499 def __getattribute__(self, attr):
|
jpayne@68
|
2500 if attr in tuple.__dict__:
|
jpayne@68
|
2501 raise AttributeError
|
jpayne@68
|
2502 return tuple.__getattribute__(self, attr)
|
jpayne@68
|
2503
|
jpayne@68
|
2504
|
jpayne@68
|
2505 def count(self, /, *args, **kwargs):
|
jpayne@68
|
2506 return self.__getattr__('count')(*args, **kwargs)
|
jpayne@68
|
2507
|
jpayne@68
|
2508 def index(self, /, *args, **kwargs):
|
jpayne@68
|
2509 return self.__getattr__('index')(*args, **kwargs)
|
jpayne@68
|
2510
|
jpayne@68
|
2511 def _get_call_arguments(self):
|
jpayne@68
|
2512 if len(self) == 2:
|
jpayne@68
|
2513 args, kwargs = self
|
jpayne@68
|
2514 else:
|
jpayne@68
|
2515 name, args, kwargs = self
|
jpayne@68
|
2516
|
jpayne@68
|
2517 return args, kwargs
|
jpayne@68
|
2518
|
jpayne@68
|
2519 @property
|
jpayne@68
|
2520 def args(self):
|
jpayne@68
|
2521 return self._get_call_arguments()[0]
|
jpayne@68
|
2522
|
jpayne@68
|
2523 @property
|
jpayne@68
|
2524 def kwargs(self):
|
jpayne@68
|
2525 return self._get_call_arguments()[1]
|
jpayne@68
|
2526
|
jpayne@68
|
2527 def __repr__(self):
|
jpayne@68
|
2528 if not self._mock_from_kall:
|
jpayne@68
|
2529 name = self._mock_name or 'call'
|
jpayne@68
|
2530 if name.startswith('()'):
|
jpayne@68
|
2531 name = 'call%s' % name
|
jpayne@68
|
2532 return name
|
jpayne@68
|
2533
|
jpayne@68
|
2534 if len(self) == 2:
|
jpayne@68
|
2535 name = 'call'
|
jpayne@68
|
2536 args, kwargs = self
|
jpayne@68
|
2537 else:
|
jpayne@68
|
2538 name, args, kwargs = self
|
jpayne@68
|
2539 if not name:
|
jpayne@68
|
2540 name = 'call'
|
jpayne@68
|
2541 elif not name.startswith('()'):
|
jpayne@68
|
2542 name = 'call.%s' % name
|
jpayne@68
|
2543 else:
|
jpayne@68
|
2544 name = 'call%s' % name
|
jpayne@68
|
2545 return _format_call_signature(name, args, kwargs)
|
jpayne@68
|
2546
|
jpayne@68
|
2547
|
jpayne@68
|
2548 def call_list(self):
|
jpayne@68
|
2549 """For a call object that represents multiple calls, `call_list`
|
jpayne@68
|
2550 returns a list of all the intermediate calls as well as the
|
jpayne@68
|
2551 final call."""
|
jpayne@68
|
2552 vals = []
|
jpayne@68
|
2553 thing = self
|
jpayne@68
|
2554 while thing is not None:
|
jpayne@68
|
2555 if thing._mock_from_kall:
|
jpayne@68
|
2556 vals.append(thing)
|
jpayne@68
|
2557 thing = thing._mock_parent
|
jpayne@68
|
2558 return _CallList(reversed(vals))
|
jpayne@68
|
2559
|
jpayne@68
|
2560
|
jpayne@68
|
2561 call = _Call(from_kall=False)
|
jpayne@68
|
2562
|
jpayne@68
|
2563
|
jpayne@68
|
2564 def create_autospec(spec, spec_set=False, instance=False, _parent=None,
|
jpayne@68
|
2565 _name=None, **kwargs):
|
jpayne@68
|
2566 """Create a mock object using another object as a spec. Attributes on the
|
jpayne@68
|
2567 mock will use the corresponding attribute on the `spec` object as their
|
jpayne@68
|
2568 spec.
|
jpayne@68
|
2569
|
jpayne@68
|
2570 Functions or methods being mocked will have their arguments checked
|
jpayne@68
|
2571 to check that they are called with the correct signature.
|
jpayne@68
|
2572
|
jpayne@68
|
2573 If `spec_set` is True then attempting to set attributes that don't exist
|
jpayne@68
|
2574 on the spec object will raise an `AttributeError`.
|
jpayne@68
|
2575
|
jpayne@68
|
2576 If a class is used as a spec then the return value of the mock (the
|
jpayne@68
|
2577 instance of the class) will have the same spec. You can use a class as the
|
jpayne@68
|
2578 spec for an instance object by passing `instance=True`. The returned mock
|
jpayne@68
|
2579 will only be callable if instances of the mock are callable.
|
jpayne@68
|
2580
|
jpayne@68
|
2581 `create_autospec` also takes arbitrary keyword arguments that are passed to
|
jpayne@68
|
2582 the constructor of the created mock."""
|
jpayne@68
|
2583 if _is_list(spec):
|
jpayne@68
|
2584 # can't pass a list instance to the mock constructor as it will be
|
jpayne@68
|
2585 # interpreted as a list of strings
|
jpayne@68
|
2586 spec = type(spec)
|
jpayne@68
|
2587
|
jpayne@68
|
2588 is_type = isinstance(spec, type)
|
jpayne@68
|
2589 is_async_func = _is_async_func(spec)
|
jpayne@68
|
2590 _kwargs = {'spec': spec}
|
jpayne@68
|
2591 if spec_set:
|
jpayne@68
|
2592 _kwargs = {'spec_set': spec}
|
jpayne@68
|
2593 elif spec is None:
|
jpayne@68
|
2594 # None we mock with a normal mock without a spec
|
jpayne@68
|
2595 _kwargs = {}
|
jpayne@68
|
2596 if _kwargs and instance:
|
jpayne@68
|
2597 _kwargs['_spec_as_instance'] = True
|
jpayne@68
|
2598
|
jpayne@68
|
2599 _kwargs.update(kwargs)
|
jpayne@68
|
2600
|
jpayne@68
|
2601 Klass = MagicMock
|
jpayne@68
|
2602 if inspect.isdatadescriptor(spec):
|
jpayne@68
|
2603 # descriptors don't have a spec
|
jpayne@68
|
2604 # because we don't know what type they return
|
jpayne@68
|
2605 _kwargs = {}
|
jpayne@68
|
2606 elif is_async_func:
|
jpayne@68
|
2607 if instance:
|
jpayne@68
|
2608 raise RuntimeError("Instance can not be True when create_autospec "
|
jpayne@68
|
2609 "is mocking an async function")
|
jpayne@68
|
2610 Klass = AsyncMock
|
jpayne@68
|
2611 elif not _callable(spec):
|
jpayne@68
|
2612 Klass = NonCallableMagicMock
|
jpayne@68
|
2613 elif is_type and instance and not _instance_callable(spec):
|
jpayne@68
|
2614 Klass = NonCallableMagicMock
|
jpayne@68
|
2615
|
jpayne@68
|
2616 _name = _kwargs.pop('name', _name)
|
jpayne@68
|
2617
|
jpayne@68
|
2618 _new_name = _name
|
jpayne@68
|
2619 if _parent is None:
|
jpayne@68
|
2620 # for a top level object no _new_name should be set
|
jpayne@68
|
2621 _new_name = ''
|
jpayne@68
|
2622
|
jpayne@68
|
2623 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
|
jpayne@68
|
2624 name=_name, **_kwargs)
|
jpayne@68
|
2625
|
jpayne@68
|
2626 if isinstance(spec, FunctionTypes):
|
jpayne@68
|
2627 # should only happen at the top level because we don't
|
jpayne@68
|
2628 # recurse for functions
|
jpayne@68
|
2629 mock = _set_signature(mock, spec)
|
jpayne@68
|
2630 if is_async_func:
|
jpayne@68
|
2631 _setup_async_mock(mock)
|
jpayne@68
|
2632 else:
|
jpayne@68
|
2633 _check_signature(spec, mock, is_type, instance)
|
jpayne@68
|
2634
|
jpayne@68
|
2635 if _parent is not None and not instance:
|
jpayne@68
|
2636 _parent._mock_children[_name] = mock
|
jpayne@68
|
2637
|
jpayne@68
|
2638 if is_type and not instance and 'return_value' not in kwargs:
|
jpayne@68
|
2639 mock.return_value = create_autospec(spec, spec_set, instance=True,
|
jpayne@68
|
2640 _name='()', _parent=mock)
|
jpayne@68
|
2641
|
jpayne@68
|
2642 for entry in dir(spec):
|
jpayne@68
|
2643 if _is_magic(entry):
|
jpayne@68
|
2644 # MagicMock already does the useful magic methods for us
|
jpayne@68
|
2645 continue
|
jpayne@68
|
2646
|
jpayne@68
|
2647 # XXXX do we need a better way of getting attributes without
|
jpayne@68
|
2648 # triggering code execution (?) Probably not - we need the actual
|
jpayne@68
|
2649 # object to mock it so we would rather trigger a property than mock
|
jpayne@68
|
2650 # the property descriptor. Likewise we want to mock out dynamically
|
jpayne@68
|
2651 # provided attributes.
|
jpayne@68
|
2652 # XXXX what about attributes that raise exceptions other than
|
jpayne@68
|
2653 # AttributeError on being fetched?
|
jpayne@68
|
2654 # we could be resilient against it, or catch and propagate the
|
jpayne@68
|
2655 # exception when the attribute is fetched from the mock
|
jpayne@68
|
2656 try:
|
jpayne@68
|
2657 original = getattr(spec, entry)
|
jpayne@68
|
2658 except AttributeError:
|
jpayne@68
|
2659 continue
|
jpayne@68
|
2660
|
jpayne@68
|
2661 kwargs = {'spec': original}
|
jpayne@68
|
2662 if spec_set:
|
jpayne@68
|
2663 kwargs = {'spec_set': original}
|
jpayne@68
|
2664
|
jpayne@68
|
2665 if not isinstance(original, FunctionTypes):
|
jpayne@68
|
2666 new = _SpecState(original, spec_set, mock, entry, instance)
|
jpayne@68
|
2667 mock._mock_children[entry] = new
|
jpayne@68
|
2668 else:
|
jpayne@68
|
2669 parent = mock
|
jpayne@68
|
2670 if isinstance(spec, FunctionTypes):
|
jpayne@68
|
2671 parent = mock.mock
|
jpayne@68
|
2672
|
jpayne@68
|
2673 skipfirst = _must_skip(spec, entry, is_type)
|
jpayne@68
|
2674 kwargs['_eat_self'] = skipfirst
|
jpayne@68
|
2675 if asyncio.iscoroutinefunction(original):
|
jpayne@68
|
2676 child_klass = AsyncMock
|
jpayne@68
|
2677 else:
|
jpayne@68
|
2678 child_klass = MagicMock
|
jpayne@68
|
2679 new = child_klass(parent=parent, name=entry, _new_name=entry,
|
jpayne@68
|
2680 _new_parent=parent,
|
jpayne@68
|
2681 **kwargs)
|
jpayne@68
|
2682 mock._mock_children[entry] = new
|
jpayne@68
|
2683 _check_signature(original, new, skipfirst=skipfirst)
|
jpayne@68
|
2684
|
jpayne@68
|
2685 # so functions created with _set_signature become instance attributes,
|
jpayne@68
|
2686 # *plus* their underlying mock exists in _mock_children of the parent
|
jpayne@68
|
2687 # mock. Adding to _mock_children may be unnecessary where we are also
|
jpayne@68
|
2688 # setting as an instance attribute?
|
jpayne@68
|
2689 if isinstance(new, FunctionTypes):
|
jpayne@68
|
2690 setattr(mock, entry, new)
|
jpayne@68
|
2691
|
jpayne@68
|
2692 return mock
|
jpayne@68
|
2693
|
jpayne@68
|
2694
|
jpayne@68
|
2695 def _must_skip(spec, entry, is_type):
|
jpayne@68
|
2696 """
|
jpayne@68
|
2697 Return whether we should skip the first argument on spec's `entry`
|
jpayne@68
|
2698 attribute.
|
jpayne@68
|
2699 """
|
jpayne@68
|
2700 if not isinstance(spec, type):
|
jpayne@68
|
2701 if entry in getattr(spec, '__dict__', {}):
|
jpayne@68
|
2702 # instance attribute - shouldn't skip
|
jpayne@68
|
2703 return False
|
jpayne@68
|
2704 spec = spec.__class__
|
jpayne@68
|
2705
|
jpayne@68
|
2706 for klass in spec.__mro__:
|
jpayne@68
|
2707 result = klass.__dict__.get(entry, DEFAULT)
|
jpayne@68
|
2708 if result is DEFAULT:
|
jpayne@68
|
2709 continue
|
jpayne@68
|
2710 if isinstance(result, (staticmethod, classmethod)):
|
jpayne@68
|
2711 return False
|
jpayne@68
|
2712 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
|
jpayne@68
|
2713 # Normal method => skip if looked up on type
|
jpayne@68
|
2714 # (if looked up on instance, self is already skipped)
|
jpayne@68
|
2715 return is_type
|
jpayne@68
|
2716 else:
|
jpayne@68
|
2717 return False
|
jpayne@68
|
2718
|
jpayne@68
|
2719 # function is a dynamically provided attribute
|
jpayne@68
|
2720 return is_type
|
jpayne@68
|
2721
|
jpayne@68
|
2722
|
jpayne@68
|
2723 class _SpecState(object):
|
jpayne@68
|
2724
|
jpayne@68
|
2725 def __init__(self, spec, spec_set=False, parent=None,
|
jpayne@68
|
2726 name=None, ids=None, instance=False):
|
jpayne@68
|
2727 self.spec = spec
|
jpayne@68
|
2728 self.ids = ids
|
jpayne@68
|
2729 self.spec_set = spec_set
|
jpayne@68
|
2730 self.parent = parent
|
jpayne@68
|
2731 self.instance = instance
|
jpayne@68
|
2732 self.name = name
|
jpayne@68
|
2733
|
jpayne@68
|
2734
|
jpayne@68
|
2735 FunctionTypes = (
|
jpayne@68
|
2736 # python function
|
jpayne@68
|
2737 type(create_autospec),
|
jpayne@68
|
2738 # instance method
|
jpayne@68
|
2739 type(ANY.__eq__),
|
jpayne@68
|
2740 )
|
jpayne@68
|
2741
|
jpayne@68
|
2742 MethodWrapperTypes = (
|
jpayne@68
|
2743 type(ANY.__eq__.__get__),
|
jpayne@68
|
2744 )
|
jpayne@68
|
2745
|
jpayne@68
|
2746
|
jpayne@68
|
2747 file_spec = None
|
jpayne@68
|
2748
|
jpayne@68
|
2749
|
jpayne@68
|
2750 def _to_stream(read_data):
|
jpayne@68
|
2751 if isinstance(read_data, bytes):
|
jpayne@68
|
2752 return io.BytesIO(read_data)
|
jpayne@68
|
2753 else:
|
jpayne@68
|
2754 return io.StringIO(read_data)
|
jpayne@68
|
2755
|
jpayne@68
|
2756
|
jpayne@68
|
2757 def mock_open(mock=None, read_data=''):
|
jpayne@68
|
2758 """
|
jpayne@68
|
2759 A helper function to create a mock to replace the use of `open`. It works
|
jpayne@68
|
2760 for `open` called directly or used as a context manager.
|
jpayne@68
|
2761
|
jpayne@68
|
2762 The `mock` argument is the mock object to configure. If `None` (the
|
jpayne@68
|
2763 default) then a `MagicMock` will be created for you, with the API limited
|
jpayne@68
|
2764 to methods or attributes available on standard file handles.
|
jpayne@68
|
2765
|
jpayne@68
|
2766 `read_data` is a string for the `read`, `readline` and `readlines` of the
|
jpayne@68
|
2767 file handle to return. This is an empty string by default.
|
jpayne@68
|
2768 """
|
jpayne@68
|
2769 _read_data = _to_stream(read_data)
|
jpayne@68
|
2770 _state = [_read_data, None]
|
jpayne@68
|
2771
|
jpayne@68
|
2772 def _readlines_side_effect(*args, **kwargs):
|
jpayne@68
|
2773 if handle.readlines.return_value is not None:
|
jpayne@68
|
2774 return handle.readlines.return_value
|
jpayne@68
|
2775 return _state[0].readlines(*args, **kwargs)
|
jpayne@68
|
2776
|
jpayne@68
|
2777 def _read_side_effect(*args, **kwargs):
|
jpayne@68
|
2778 if handle.read.return_value is not None:
|
jpayne@68
|
2779 return handle.read.return_value
|
jpayne@68
|
2780 return _state[0].read(*args, **kwargs)
|
jpayne@68
|
2781
|
jpayne@68
|
2782 def _readline_side_effect(*args, **kwargs):
|
jpayne@68
|
2783 yield from _iter_side_effect()
|
jpayne@68
|
2784 while True:
|
jpayne@68
|
2785 yield _state[0].readline(*args, **kwargs)
|
jpayne@68
|
2786
|
jpayne@68
|
2787 def _iter_side_effect():
|
jpayne@68
|
2788 if handle.readline.return_value is not None:
|
jpayne@68
|
2789 while True:
|
jpayne@68
|
2790 yield handle.readline.return_value
|
jpayne@68
|
2791 for line in _state[0]:
|
jpayne@68
|
2792 yield line
|
jpayne@68
|
2793
|
jpayne@68
|
2794 def _next_side_effect():
|
jpayne@68
|
2795 if handle.readline.return_value is not None:
|
jpayne@68
|
2796 return handle.readline.return_value
|
jpayne@68
|
2797 return next(_state[0])
|
jpayne@68
|
2798
|
jpayne@68
|
2799 global file_spec
|
jpayne@68
|
2800 if file_spec is None:
|
jpayne@68
|
2801 import _io
|
jpayne@68
|
2802 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
|
jpayne@68
|
2803
|
jpayne@68
|
2804 if mock is None:
|
jpayne@68
|
2805 mock = MagicMock(name='open', spec=open)
|
jpayne@68
|
2806
|
jpayne@68
|
2807 handle = MagicMock(spec=file_spec)
|
jpayne@68
|
2808 handle.__enter__.return_value = handle
|
jpayne@68
|
2809
|
jpayne@68
|
2810 handle.write.return_value = None
|
jpayne@68
|
2811 handle.read.return_value = None
|
jpayne@68
|
2812 handle.readline.return_value = None
|
jpayne@68
|
2813 handle.readlines.return_value = None
|
jpayne@68
|
2814
|
jpayne@68
|
2815 handle.read.side_effect = _read_side_effect
|
jpayne@68
|
2816 _state[1] = _readline_side_effect()
|
jpayne@68
|
2817 handle.readline.side_effect = _state[1]
|
jpayne@68
|
2818 handle.readlines.side_effect = _readlines_side_effect
|
jpayne@68
|
2819 handle.__iter__.side_effect = _iter_side_effect
|
jpayne@68
|
2820 handle.__next__.side_effect = _next_side_effect
|
jpayne@68
|
2821
|
jpayne@68
|
2822 def reset_data(*args, **kwargs):
|
jpayne@68
|
2823 _state[0] = _to_stream(read_data)
|
jpayne@68
|
2824 if handle.readline.side_effect == _state[1]:
|
jpayne@68
|
2825 # Only reset the side effect if the user hasn't overridden it.
|
jpayne@68
|
2826 _state[1] = _readline_side_effect()
|
jpayne@68
|
2827 handle.readline.side_effect = _state[1]
|
jpayne@68
|
2828 return DEFAULT
|
jpayne@68
|
2829
|
jpayne@68
|
2830 mock.side_effect = reset_data
|
jpayne@68
|
2831 mock.return_value = handle
|
jpayne@68
|
2832 return mock
|
jpayne@68
|
2833
|
jpayne@68
|
2834
|
jpayne@68
|
2835 class PropertyMock(Mock):
|
jpayne@68
|
2836 """
|
jpayne@68
|
2837 A mock intended to be used as a property, or other descriptor, on a class.
|
jpayne@68
|
2838 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
|
jpayne@68
|
2839 a return value when it is fetched.
|
jpayne@68
|
2840
|
jpayne@68
|
2841 Fetching a `PropertyMock` instance from an object calls the mock, with
|
jpayne@68
|
2842 no args. Setting it calls the mock with the value being set.
|
jpayne@68
|
2843 """
|
jpayne@68
|
2844 def _get_child_mock(self, /, **kwargs):
|
jpayne@68
|
2845 return MagicMock(**kwargs)
|
jpayne@68
|
2846
|
jpayne@68
|
2847 def __get__(self, obj, obj_type=None):
|
jpayne@68
|
2848 return self()
|
jpayne@68
|
2849 def __set__(self, obj, val):
|
jpayne@68
|
2850 self(val)
|
jpayne@68
|
2851
|
jpayne@68
|
2852
|
jpayne@68
|
2853 def seal(mock):
|
jpayne@68
|
2854 """Disable the automatic generation of child mocks.
|
jpayne@68
|
2855
|
jpayne@68
|
2856 Given an input Mock, seals it to ensure no further mocks will be generated
|
jpayne@68
|
2857 when accessing an attribute that was not already defined.
|
jpayne@68
|
2858
|
jpayne@68
|
2859 The operation recursively seals the mock passed in, meaning that
|
jpayne@68
|
2860 the mock itself, any mocks generated by accessing one of its attributes,
|
jpayne@68
|
2861 and all assigned mocks without a name or spec will be sealed.
|
jpayne@68
|
2862 """
|
jpayne@68
|
2863 mock._mock_sealed = True
|
jpayne@68
|
2864 for attr in dir(mock):
|
jpayne@68
|
2865 try:
|
jpayne@68
|
2866 m = getattr(mock, attr)
|
jpayne@68
|
2867 except AttributeError:
|
jpayne@68
|
2868 continue
|
jpayne@68
|
2869 if not isinstance(m, NonCallableMock):
|
jpayne@68
|
2870 continue
|
jpayne@68
|
2871 if m._mock_new_parent is mock:
|
jpayne@68
|
2872 seal(m)
|
jpayne@68
|
2873
|
jpayne@68
|
2874
|
jpayne@68
|
2875 class _AsyncIterator:
|
jpayne@68
|
2876 """
|
jpayne@68
|
2877 Wraps an iterator in an asynchronous iterator.
|
jpayne@68
|
2878 """
|
jpayne@68
|
2879 def __init__(self, iterator):
|
jpayne@68
|
2880 self.iterator = iterator
|
jpayne@68
|
2881 code_mock = NonCallableMock(spec_set=CodeType)
|
jpayne@68
|
2882 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
|
jpayne@68
|
2883 self.__dict__['__code__'] = code_mock
|
jpayne@68
|
2884
|
jpayne@68
|
2885 def __aiter__(self):
|
jpayne@68
|
2886 return self
|
jpayne@68
|
2887
|
jpayne@68
|
2888 async def __anext__(self):
|
jpayne@68
|
2889 try:
|
jpayne@68
|
2890 return next(self.iterator)
|
jpayne@68
|
2891 except StopIteration:
|
jpayne@68
|
2892 pass
|
jpayne@68
|
2893 raise StopAsyncIteration
|