blob: 9e692981a229bb52b7b21ecfc01dc70cc9e5f64e [file] [log] [blame]
Michael Foord345266a2012-03-14 12:24:34 -07001# mock.py
2# Test tools for mocking and patching.
Michael Foordc17adf42012-03-14 13:30:29 -07003# Maintained by Michael Foord
4# Backport for other versions of Python available from
Ned Deily9d6d06e2018-06-11 00:45:50 -04005# https://pypi.org/project/mock
Michael Foord345266a2012-03-14 12:24:34 -07006
7__all__ = (
8 'Mock',
9 'MagicMock',
10 'patch',
11 'sentinel',
12 'DEFAULT',
13 'ANY',
14 'call',
15 'create_autospec',
Lisa Roach77b3b772019-05-20 09:19:53 -070016 'AsyncMock',
Michael Foord345266a2012-03-14 12:24:34 -070017 'FILTER_DIR',
18 'NonCallableMock',
19 'NonCallableMagicMock',
20 'mock_open',
21 'PropertyMock',
Mario Corchero552be9d2017-10-17 12:35:11 +010022 'seal',
Michael Foord345266a2012-03-14 12:24:34 -070023)
24
25
Lisa Roach77b3b772019-05-20 09:19:53 -070026import asyncio
Xtreak436c2b02019-05-28 12:37:39 +053027import contextlib
Rémi Lapeyre11a88322019-05-07 12:48:36 +020028import io
Michael Foord345266a2012-03-14 12:24:34 -070029import inspect
30import pprint
31import sys
Michael Foordfddcfa22014-04-14 16:25:20 -040032import builtins
Chris Withersc7dd3c72020-01-27 14:11:19 +000033from asyncio import iscoroutinefunction
Lisa Roach77b3b772019-05-20 09:19:53 -070034from types import CodeType, ModuleType, MethodType
Petter Strandmark47d94242018-10-28 21:37:10 +010035from unittest.util import safe_repr
Antoine Pitrou5c64df72013-02-03 00:23:58 +010036from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070037
38
Michael Foordfddcfa22014-04-14 16:25:20 -040039_builtins = {name for name in dir(builtins) if not name.startswith('_')}
40
Michael Foord345266a2012-03-14 12:24:34 -070041FILTER_DIR = True
42
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100043# Workaround for issue #12370
44# Without this, the __class__ properties wouldn't be set correctly
45_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070046
Lisa Roach77b3b772019-05-20 09:19:53 -070047def _is_async_obj(obj):
Lisa Roachf1a297a2019-09-10 12:18:40 +010048 if _is_instance_mock(obj) and not isinstance(obj, AsyncMock):
Lisa Roach77b3b772019-05-20 09:19:53 -070049 return False
Matthew Kokotovich62865f42020-01-25 04:17:47 -060050 if hasattr(obj, '__func__'):
51 obj = getattr(obj, '__func__')
Chris Withersc7dd3c72020-01-27 14:11:19 +000052 return iscoroutinefunction(obj) or inspect.isawaitable(obj)
Lisa Roach77b3b772019-05-20 09:19:53 -070053
54
Xtreakff6b2e62019-05-27 18:26:23 +053055def _is_async_func(func):
56 if getattr(func, '__code__', None):
Chris Withersc7dd3c72020-01-27 14:11:19 +000057 return iscoroutinefunction(func)
Xtreakff6b2e62019-05-27 18:26:23 +053058 else:
59 return False
60
61
Michael Foord345266a2012-03-14 12:24:34 -070062def _is_instance_mock(obj):
63 # can't use isinstance on Mock objects because they override __class__
64 # The base class for all mocks is NonCallableMock
65 return issubclass(type(obj), NonCallableMock)
66
67
68def _is_exception(obj):
69 return (
Chris Withers49e27f02019-05-01 08:48:44 +010070 isinstance(obj, BaseException) or
71 isinstance(obj, type) and issubclass(obj, BaseException)
Michael Foord345266a2012-03-14 12:24:34 -070072 )
73
74
Xtreak7397cda2019-07-22 13:08:22 +053075def _extract_mock(obj):
76 # Autospecced functions will return a FunctionType with "mock" attribute
77 # which is the actual mock object that needs to be used.
78 if isinstance(obj, FunctionTypes) and hasattr(obj, 'mock'):
79 return obj.mock
80 else:
81 return obj
82
83
Antoine Pitrou5c64df72013-02-03 00:23:58 +010084def _get_signature_object(func, as_instance, eat_self):
85 """
86 Given an arbitrary, possibly callable object, try to create a suitable
87 signature object.
88 Return a (reduced func, signature) tuple, or None.
89 """
90 if isinstance(func, type) and not as_instance:
91 # If it's a type and should be modelled as a type, use __init__.
Chris Withersadbf1782019-05-01 23:04:04 +010092 func = func.__init__
Antoine Pitrou5c64df72013-02-03 00:23:58 +010093 # Skip the `self` argument in __init__
94 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070095 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010096 # If we really want to model an instance of the passed type,
97 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070098 try:
99 func = func.__call__
100 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100101 return None
102 if eat_self:
103 sig_func = partial(func, None)
104 else:
105 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -0700106 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100107 return func, inspect.signature(sig_func)
108 except ValueError:
109 # Certain callable types are not supported by inspect.signature()
110 return None
Michael Foord345266a2012-03-14 12:24:34 -0700111
112
113def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100114 sig = _get_signature_object(func, instance, skipfirst)
115 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -0700116 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100117 func, sig = sig
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300118 def checksig(self, /, *args, **kwargs):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100119 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700120 _copy_func_details(func, checksig)
121 type(mock)._mock_check_sig = checksig
Xtreakf7fa62e2018-12-12 13:24:54 +0530122 type(mock).__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700123
124
125def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700126 # we explicitly don't copy func.__dict__ into this copy as it would
127 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300128 for attribute in (
129 '__name__', '__doc__', '__text_signature__',
130 '__module__', '__defaults__', '__kwdefaults__',
131 ):
132 try:
133 setattr(funcopy, attribute, getattr(func, attribute))
134 except AttributeError:
135 pass
Michael Foord345266a2012-03-14 12:24:34 -0700136
137
138def _callable(obj):
139 if isinstance(obj, type):
140 return True
Xtreak9b218562019-04-22 08:00:23 +0530141 if isinstance(obj, (staticmethod, classmethod, MethodType)):
142 return _callable(obj.__func__)
Michael Foord345266a2012-03-14 12:24:34 -0700143 if getattr(obj, '__call__', None) is not None:
144 return True
145 return False
146
147
148def _is_list(obj):
149 # checks for list or tuples
150 # XXXX badly named!
151 return type(obj) in (list, tuple)
152
153
154def _instance_callable(obj):
155 """Given an object, return True if the object is callable.
156 For classes, return True if instances would be callable."""
157 if not isinstance(obj, type):
158 # already an instance
159 return getattr(obj, '__call__', None) is not None
160
Michael Foorda74b3aa2012-03-14 14:40:22 -0700161 # *could* be broken by a class overriding __mro__ or __dict__ via
162 # a metaclass
163 for base in (obj,) + obj.__mro__:
164 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700165 return True
166 return False
167
168
169def _set_signature(mock, original, instance=False):
170 # creates a function with signature (*args, **kwargs) that delegates to a
171 # mock. It still does signature checking by calling a lambda with the same
172 # signature as the original.
Michael Foord345266a2012-03-14 12:24:34 -0700173
174 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100175 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700176 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700177 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100178 func, sig = result
179 def checksig(*args, **kwargs):
180 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700181 _copy_func_details(func, checksig)
182
183 name = original.__name__
184 if not name.isidentifier():
185 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100186 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700187 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100188 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700189 return mock(*args, **kwargs)""" % name
190 exec (src, context)
191 funcopy = context[name]
Xtreakf7fa62e2018-12-12 13:24:54 +0530192 _setup_func(funcopy, mock, sig)
Michael Foord345266a2012-03-14 12:24:34 -0700193 return funcopy
194
195
Xtreakf7fa62e2018-12-12 13:24:54 +0530196def _setup_func(funcopy, mock, sig):
Michael Foord345266a2012-03-14 12:24:34 -0700197 funcopy.mock = mock
198
Michael Foord345266a2012-03-14 12:24:34 -0700199 def assert_called_with(*args, **kwargs):
200 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700201 def assert_called(*args, **kwargs):
202 return mock.assert_called(*args, **kwargs)
203 def assert_not_called(*args, **kwargs):
204 return mock.assert_not_called(*args, **kwargs)
205 def assert_called_once(*args, **kwargs):
206 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700207 def assert_called_once_with(*args, **kwargs):
208 return mock.assert_called_once_with(*args, **kwargs)
209 def assert_has_calls(*args, **kwargs):
210 return mock.assert_has_calls(*args, **kwargs)
211 def assert_any_call(*args, **kwargs):
212 return mock.assert_any_call(*args, **kwargs)
213 def reset_mock():
214 funcopy.method_calls = _CallList()
215 funcopy.mock_calls = _CallList()
216 mock.reset_mock()
217 ret = funcopy.return_value
218 if _is_instance_mock(ret) and not ret is mock:
219 ret.reset_mock()
220
221 funcopy.called = False
222 funcopy.call_count = 0
223 funcopy.call_args = None
224 funcopy.call_args_list = _CallList()
225 funcopy.method_calls = _CallList()
226 funcopy.mock_calls = _CallList()
227
228 funcopy.return_value = mock.return_value
229 funcopy.side_effect = mock.side_effect
230 funcopy._mock_children = mock._mock_children
231
232 funcopy.assert_called_with = assert_called_with
233 funcopy.assert_called_once_with = assert_called_once_with
234 funcopy.assert_has_calls = assert_has_calls
235 funcopy.assert_any_call = assert_any_call
236 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700237 funcopy.assert_called = assert_called
238 funcopy.assert_not_called = assert_not_called
239 funcopy.assert_called_once = assert_called_once
Xtreakf7fa62e2018-12-12 13:24:54 +0530240 funcopy.__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700241
242 mock._mock_delegate = funcopy
243
244
Xtreakff6b2e62019-05-27 18:26:23 +0530245def _setup_async_mock(mock):
246 mock._is_coroutine = asyncio.coroutines._is_coroutine
247 mock.await_count = 0
248 mock.await_args = None
249 mock.await_args_list = _CallList()
Xtreakff6b2e62019-05-27 18:26:23 +0530250
251 # Mock is not configured yet so the attributes are set
252 # to a function and then the corresponding mock helper function
253 # is called when the helper is accessed similar to _setup_func.
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300254 def wrapper(attr, /, *args, **kwargs):
Xtreakff6b2e62019-05-27 18:26:23 +0530255 return getattr(mock.mock, attr)(*args, **kwargs)
256
257 for attribute in ('assert_awaited',
258 'assert_awaited_once',
259 'assert_awaited_with',
260 'assert_awaited_once_with',
261 'assert_any_await',
262 'assert_has_awaits',
263 'assert_not_awaited'):
264
265 # setattr(mock, attribute, wrapper) causes late binding
266 # hence attribute will always be the last value in the loop
267 # Use partial(wrapper, attribute) to ensure the attribute is bound
268 # correctly.
269 setattr(mock, attribute, partial(wrapper, attribute))
270
271
Michael Foord345266a2012-03-14 12:24:34 -0700272def _is_magic(name):
273 return '__%s__' % name[2:-2] == name
274
275
276class _SentinelObject(object):
277 "A unique, named, sentinel object."
278 def __init__(self, name):
279 self.name = name
280
281 def __repr__(self):
282 return 'sentinel.%s' % self.name
283
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200284 def __reduce__(self):
285 return 'sentinel.%s' % self.name
286
Michael Foord345266a2012-03-14 12:24:34 -0700287
288class _Sentinel(object):
289 """Access attributes to return a named object, usable as a sentinel."""
290 def __init__(self):
291 self._sentinels = {}
292
293 def __getattr__(self, name):
294 if name == '__bases__':
295 # Without this help(unittest.mock) raises an exception
296 raise AttributeError
297 return self._sentinels.setdefault(name, _SentinelObject(name))
298
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200299 def __reduce__(self):
300 return 'sentinel'
301
Michael Foord345266a2012-03-14 12:24:34 -0700302
303sentinel = _Sentinel()
304
305DEFAULT = sentinel.DEFAULT
306_missing = sentinel.MISSING
307_deleted = sentinel.DELETED
308
309
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200310_allowed_names = {
311 'return_value', '_mock_return_value', 'side_effect',
312 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
313 '_mock_name', '_mock_new_name'
314}
Michael Foord345266a2012-03-14 12:24:34 -0700315
316
317def _delegating_property(name):
318 _allowed_names.add(name)
319 _the_name = '_mock_' + name
320 def _get(self, name=name, _the_name=_the_name):
321 sig = self._mock_delegate
322 if sig is None:
323 return getattr(self, _the_name)
324 return getattr(sig, name)
325 def _set(self, value, name=name, _the_name=_the_name):
326 sig = self._mock_delegate
327 if sig is None:
328 self.__dict__[_the_name] = value
329 else:
330 setattr(sig, name, value)
331
332 return property(_get, _set)
333
334
335
336class _CallList(list):
337
338 def __contains__(self, value):
339 if not isinstance(value, list):
340 return list.__contains__(self, value)
341 len_value = len(value)
342 len_self = len(self)
343 if len_value > len_self:
344 return False
345
346 for i in range(0, len_self - len_value + 1):
347 sub_list = self[i:i+len_value]
348 if sub_list == value:
349 return True
350 return False
351
352 def __repr__(self):
353 return pprint.pformat(list(self))
354
355
356def _check_and_set_parent(parent, value, name, new_name):
Xtreak7397cda2019-07-22 13:08:22 +0530357 value = _extract_mock(value)
Xtreak9c3f2842019-02-26 03:16:34 +0530358
Michael Foord345266a2012-03-14 12:24:34 -0700359 if not _is_instance_mock(value):
360 return False
361 if ((value._mock_name or value._mock_new_name) or
362 (value._mock_parent is not None) or
363 (value._mock_new_parent is not None)):
364 return False
365
366 _parent = parent
367 while _parent is not None:
368 # setting a mock (value) as a child or return value of itself
369 # should not modify the mock
370 if _parent is value:
371 return False
372 _parent = _parent._mock_new_parent
373
374 if new_name:
375 value._mock_new_parent = parent
376 value._mock_new_name = new_name
377 if name:
378 value._mock_parent = parent
379 value._mock_name = name
380 return True
381
Michael Foord01bafdc2014-04-14 16:09:42 -0400382# Internal class to identify if we wrapped an iterator object or not.
383class _MockIter(object):
384 def __init__(self, obj):
385 self.obj = iter(obj)
Michael Foord01bafdc2014-04-14 16:09:42 -0400386 def __next__(self):
387 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700388
389class Base(object):
390 _mock_return_value = DEFAULT
391 _mock_side_effect = None
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300392 def __init__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700393 pass
394
395
396
397class NonCallableMock(Base):
398 """A non-callable version of `Mock`"""
399
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300400 def __new__(cls, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700401 # every instance has its own class
402 # so we can create magic methods on the
403 # class without stomping on other mocks
Lisa Roach77b3b772019-05-20 09:19:53 -0700404 bases = (cls,)
Michael Foord14fd9252019-09-13 18:40:56 +0200405 if not issubclass(cls, AsyncMockMixin):
Lisa Roach77b3b772019-05-20 09:19:53 -0700406 # Check if spec is an async object or function
Michael Foord14fd9252019-09-13 18:40:56 +0200407 bound_args = _MOCK_SIG.bind_partial(cls, *args, **kw).arguments
408 spec_arg = bound_args.get('spec_set', bound_args.get('spec'))
409 if spec_arg and _is_async_obj(spec_arg):
410 bases = (AsyncMockMixin, cls)
Lisa Roach77b3b772019-05-20 09:19:53 -0700411 new = type(cls.__name__, bases, {'__doc__': cls.__doc__})
Lisa Roach9a7d9512019-09-28 18:42:44 -0700412 instance = _safe_super(NonCallableMock, cls).__new__(new)
Michael Foord345266a2012-03-14 12:24:34 -0700413 return instance
414
415
416 def __init__(
417 self, spec=None, wraps=None, name=None, spec_set=None,
418 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530419 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700420 ):
421 if _new_parent is None:
422 _new_parent = parent
423
424 __dict__ = self.__dict__
425 __dict__['_mock_parent'] = parent
426 __dict__['_mock_name'] = name
427 __dict__['_mock_new_name'] = _new_name
428 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100429 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700430
431 if spec_set is not None:
432 spec = spec_set
433 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100434 if _eat_self is None:
435 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700436
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100437 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700438
439 __dict__['_mock_children'] = {}
440 __dict__['_mock_wraps'] = wraps
441 __dict__['_mock_delegate'] = None
442
443 __dict__['_mock_called'] = False
444 __dict__['_mock_call_args'] = None
445 __dict__['_mock_call_count'] = 0
446 __dict__['_mock_call_args_list'] = _CallList()
447 __dict__['_mock_mock_calls'] = _CallList()
448
449 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530450 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700451
452 if kwargs:
453 self.configure_mock(**kwargs)
454
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000455 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700456 spec, wraps, name, spec_set, parent,
457 _spec_state
458 )
459
460
461 def attach_mock(self, mock, attribute):
462 """
463 Attach a mock as an attribute of this one, replacing its name and
464 parent. Calls to the attached mock will be recorded in the
465 `method_calls` and `mock_calls` attributes of this one."""
Xtreak7397cda2019-07-22 13:08:22 +0530466 inner_mock = _extract_mock(mock)
467
468 inner_mock._mock_parent = None
469 inner_mock._mock_new_parent = None
470 inner_mock._mock_name = ''
471 inner_mock._mock_new_name = None
Michael Foord345266a2012-03-14 12:24:34 -0700472
473 setattr(self, attribute, mock)
474
475
476 def mock_add_spec(self, spec, spec_set=False):
477 """Add a spec to a mock. `spec` can either be an object or a
478 list of strings. Only attributes on the `spec` can be fetched as
479 attributes from the mock.
480
481 If `spec_set` is True then only attributes on the spec can be set."""
482 self._mock_add_spec(spec, spec_set)
483
484
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100485 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
486 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700487 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100488 _spec_signature = None
Lisa Roach77b3b772019-05-20 09:19:53 -0700489 _spec_asyncs = []
490
491 for attr in dir(spec):
Chris Withersc7dd3c72020-01-27 14:11:19 +0000492 if iscoroutinefunction(getattr(spec, attr, None)):
Lisa Roach77b3b772019-05-20 09:19:53 -0700493 _spec_asyncs.append(attr)
Michael Foord345266a2012-03-14 12:24:34 -0700494
495 if spec is not None and not _is_list(spec):
496 if isinstance(spec, type):
497 _spec_class = spec
498 else:
Chris Withersadbf1782019-05-01 23:04:04 +0100499 _spec_class = type(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100500 res = _get_signature_object(spec,
501 _spec_as_instance, _eat_self)
502 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700503
504 spec = dir(spec)
505
506 __dict__ = self.__dict__
507 __dict__['_spec_class'] = _spec_class
508 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100509 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700510 __dict__['_mock_methods'] = spec
Lisa Roach77b3b772019-05-20 09:19:53 -0700511 __dict__['_spec_asyncs'] = _spec_asyncs
Michael Foord345266a2012-03-14 12:24:34 -0700512
513 def __get_return_value(self):
514 ret = self._mock_return_value
515 if self._mock_delegate is not None:
516 ret = self._mock_delegate.return_value
517
518 if ret is DEFAULT:
519 ret = self._get_child_mock(
520 _new_parent=self, _new_name='()'
521 )
522 self.return_value = ret
523 return ret
524
525
526 def __set_return_value(self, value):
527 if self._mock_delegate is not None:
528 self._mock_delegate.return_value = value
529 else:
530 self._mock_return_value = value
531 _check_and_set_parent(self, value, None, '()')
532
533 __return_value_doc = "The value to be returned when the mock is called."
534 return_value = property(__get_return_value, __set_return_value,
535 __return_value_doc)
536
537
538 @property
539 def __class__(self):
540 if self._spec_class is None:
541 return type(self)
542 return self._spec_class
543
544 called = _delegating_property('called')
545 call_count = _delegating_property('call_count')
546 call_args = _delegating_property('call_args')
547 call_args_list = _delegating_property('call_args_list')
548 mock_calls = _delegating_property('mock_calls')
549
550
551 def __get_side_effect(self):
552 delegated = self._mock_delegate
553 if delegated is None:
554 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400555 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200556 if (sf is not None and not callable(sf)
557 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400558 sf = _MockIter(sf)
559 delegated.side_effect = sf
560 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700561
562 def __set_side_effect(self, value):
563 value = _try_iter(value)
564 delegated = self._mock_delegate
565 if delegated is None:
566 self._mock_side_effect = value
567 else:
568 delegated.side_effect = value
569
570 side_effect = property(__get_side_effect, __set_side_effect)
571
572
Kushal Das9cd39a12016-06-02 10:20:16 -0700573 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700574 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200575 if visited is None:
576 visited = []
577 if id(self) in visited:
578 return
579 visited.append(id(self))
580
Michael Foord345266a2012-03-14 12:24:34 -0700581 self.called = False
582 self.call_args = None
583 self.call_count = 0
584 self.mock_calls = _CallList()
585 self.call_args_list = _CallList()
586 self.method_calls = _CallList()
587
Kushal Das9cd39a12016-06-02 10:20:16 -0700588 if return_value:
589 self._mock_return_value = DEFAULT
590 if side_effect:
591 self._mock_side_effect = None
592
Michael Foord345266a2012-03-14 12:24:34 -0700593 for child in self._mock_children.values():
Xtreakedeca922018-12-01 15:33:54 +0530594 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100595 continue
Vegard Stikbakkeaef7dc82020-01-25 16:44:46 +0100596 child.reset_mock(visited, return_value=return_value, side_effect=side_effect)
Michael Foord345266a2012-03-14 12:24:34 -0700597
598 ret = self._mock_return_value
599 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200600 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700601
602
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300603 def configure_mock(self, /, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700604 """Set attributes on the mock through keyword arguments.
605
606 Attributes plus return values and side effects can be set on child
607 mocks using standard dot notation and unpacking a dictionary in the
608 method call:
609
610 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
611 >>> mock.configure_mock(**attrs)"""
612 for arg, val in sorted(kwargs.items(),
613 # we sort on the number of dots so that
614 # attributes are set before we set attributes on
615 # attributes
616 key=lambda entry: entry[0].count('.')):
617 args = arg.split('.')
618 final = args.pop()
619 obj = self
620 for entry in args:
621 obj = getattr(obj, entry)
622 setattr(obj, final, val)
623
624
625 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530626 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700627 raise AttributeError(name)
628 elif self._mock_methods is not None:
629 if name not in self._mock_methods or name in _all_magics:
630 raise AttributeError("Mock object has no attribute %r" % name)
631 elif _is_magic(name):
632 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530633 if not self._mock_unsafe:
634 if name.startswith(('assert', 'assret')):
Zackery Spytzb9b08cd2019-05-08 11:32:24 -0600635 raise AttributeError("Attributes cannot start with 'assert' "
636 "or 'assret'")
Michael Foord345266a2012-03-14 12:24:34 -0700637
638 result = self._mock_children.get(name)
639 if result is _deleted:
640 raise AttributeError(name)
641 elif result is None:
642 wraps = None
643 if self._mock_wraps is not None:
644 # XXXX should we get the attribute without triggering code
645 # execution?
646 wraps = getattr(self._mock_wraps, name)
647
648 result = self._get_child_mock(
649 parent=self, name=name, wraps=wraps, _new_name=name,
650 _new_parent=self
651 )
652 self._mock_children[name] = result
653
654 elif isinstance(result, _SpecState):
655 result = create_autospec(
656 result.spec, result.spec_set, result.instance,
657 result.parent, result.name
658 )
659 self._mock_children[name] = result
660
661 return result
662
663
Mario Corchero552be9d2017-10-17 12:35:11 +0100664 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700665 _name_list = [self._mock_new_name]
666 _parent = self._mock_new_parent
667 last = self
668
669 dot = '.'
670 if _name_list == ['()']:
671 dot = ''
Chris Withersadbf1782019-05-01 23:04:04 +0100672
Michael Foord345266a2012-03-14 12:24:34 -0700673 while _parent is not None:
674 last = _parent
675
676 _name_list.append(_parent._mock_new_name + dot)
677 dot = '.'
678 if _parent._mock_new_name == '()':
679 dot = ''
680
681 _parent = _parent._mock_new_parent
682
Michael Foord345266a2012-03-14 12:24:34 -0700683 _name_list = list(reversed(_name_list))
684 _first = last._mock_name or 'mock'
685 if len(_name_list) > 1:
686 if _name_list[1] not in ('()', '().'):
687 _first += '.'
688 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100689 return ''.join(_name_list)
690
691 def __repr__(self):
692 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700693
694 name_string = ''
695 if name not in ('mock', 'mock.'):
696 name_string = ' name=%r' % name
697
698 spec_string = ''
699 if self._spec_class is not None:
700 spec_string = ' spec=%r'
701 if self._spec_set:
702 spec_string = ' spec_set=%r'
703 spec_string = spec_string % self._spec_class.__name__
704 return "<%s%s%s id='%s'>" % (
705 type(self).__name__,
706 name_string,
707 spec_string,
708 id(self)
709 )
710
711
712 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700713 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100714 if not FILTER_DIR:
715 return object.__dir__(self)
716
Michael Foord345266a2012-03-14 12:24:34 -0700717 extras = self._mock_methods or []
718 from_type = dir(type(self))
719 from_dict = list(self.__dict__)
Mario Corchero0df635c2019-04-30 19:56:36 +0100720 from_child_mocks = [
721 m_name for m_name, m_value in self._mock_children.items()
722 if m_value is not _deleted]
Michael Foord345266a2012-03-14 12:24:34 -0700723
Michael Foord313f85f2012-03-25 18:16:07 +0100724 from_type = [e for e in from_type if not e.startswith('_')]
725 from_dict = [e for e in from_dict if not e.startswith('_') or
726 _is_magic(e)]
Mario Corchero0df635c2019-04-30 19:56:36 +0100727 return sorted(set(extras + from_type + from_dict + from_child_mocks))
Michael Foord345266a2012-03-14 12:24:34 -0700728
729
730 def __setattr__(self, name, value):
731 if name in _allowed_names:
732 # property setters go through here
733 return object.__setattr__(self, name, value)
734 elif (self._spec_set and self._mock_methods is not None and
735 name not in self._mock_methods and
736 name not in self.__dict__):
737 raise AttributeError("Mock object has no attribute '%s'" % name)
738 elif name in _unsupported_magics:
739 msg = 'Attempting to set unsupported magic method %r.' % name
740 raise AttributeError(msg)
741 elif name in _all_magics:
742 if self._mock_methods is not None and name not in self._mock_methods:
743 raise AttributeError("Mock object has no attribute '%s'" % name)
744
745 if not _is_instance_mock(value):
746 setattr(type(self), name, _get_method(name, value))
747 original = value
748 value = lambda *args, **kw: original(self, *args, **kw)
749 else:
750 # only set _new_name and not name so that mock_calls is tracked
751 # but not method calls
752 _check_and_set_parent(self, value, None, name)
753 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100754 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700755 elif name == '__class__':
756 self._spec_class = value
757 return
758 else:
759 if _check_and_set_parent(self, value, name, name):
760 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100761
762 if self._mock_sealed and not hasattr(self, name):
763 mock_name = f'{self._extract_mock_name()}.{name}'
764 raise AttributeError(f'Cannot set {mock_name}')
765
Michael Foord345266a2012-03-14 12:24:34 -0700766 return object.__setattr__(self, name, value)
767
768
769 def __delattr__(self, name):
770 if name in _all_magics and name in type(self).__dict__:
771 delattr(type(self), name)
772 if name not in self.__dict__:
773 # for magic methods that are still MagicProxy objects and
774 # not set on the instance itself
775 return
776
Michael Foord345266a2012-03-14 12:24:34 -0700777 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000778 if name in self.__dict__:
Xtreak830b43d2019-04-14 00:42:33 +0530779 _safe_super(NonCallableMock, self).__delattr__(name)
Pablo Galindo222d3032019-01-21 08:57:46 +0000780 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700781 raise AttributeError(name)
782 if obj is not _missing:
783 del self._mock_children[name]
784 self._mock_children[name] = _deleted
785
786
Michael Foord345266a2012-03-14 12:24:34 -0700787 def _format_mock_call_signature(self, args, kwargs):
788 name = self._mock_name or 'mock'
789 return _format_call_signature(name, args, kwargs)
790
791
Xtreak0ae022c2019-05-29 12:32:26 +0530792 def _format_mock_failure_message(self, args, kwargs, action='call'):
793 message = 'expected %s not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700794 expected_string = self._format_mock_call_signature(args, kwargs)
795 call_args = self.call_args
Michael Foord345266a2012-03-14 12:24:34 -0700796 actual_string = self._format_mock_call_signature(*call_args)
Xtreak0ae022c2019-05-29 12:32:26 +0530797 return message % (action, expected_string, actual_string)
Michael Foord345266a2012-03-14 12:24:34 -0700798
799
Xtreakc9612782019-08-29 11:39:01 +0530800 def _get_call_signature_from_name(self, name):
801 """
802 * If call objects are asserted against a method/function like obj.meth1
803 then there could be no name for the call object to lookup. Hence just
804 return the spec_signature of the method/function being asserted against.
805 * If the name is not empty then remove () and split by '.' to get
806 list of names to iterate through the children until a potential
807 match is found. A child mock is created only during attribute access
808 so if we get a _SpecState then no attributes of the spec were accessed
809 and can be safely exited.
810 """
811 if not name:
812 return self._spec_signature
813
814 sig = None
815 names = name.replace('()', '').split('.')
816 children = self._mock_children
817
818 for name in names:
819 child = children.get(name)
820 if child is None or isinstance(child, _SpecState):
821 break
822 else:
Karthikeyan Singaravelan66b00a92020-01-24 18:44:29 +0530823 # If an autospecced object is attached using attach_mock the
824 # child would be a function with mock object as attribute from
825 # which signature has to be derived.
826 child = _extract_mock(child)
Xtreakc9612782019-08-29 11:39:01 +0530827 children = child._mock_children
828 sig = child._spec_signature
829
830 return sig
831
832
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100833 def _call_matcher(self, _call):
834 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000835 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100836 comparison key suitable for matching with other calls.
837 This is a best effort method which relies on the spec's signature,
838 if available, or falls back on the arguments themselves.
839 """
Xtreakc9612782019-08-29 11:39:01 +0530840
841 if isinstance(_call, tuple) and len(_call) > 2:
842 sig = self._get_call_signature_from_name(_call[0])
843 else:
844 sig = self._spec_signature
845
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100846 if sig is not None:
847 if len(_call) == 2:
848 name = ''
849 args, kwargs = _call
850 else:
851 name, args, kwargs = _call
852 try:
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700853 bound_call = sig.bind(*args, **kwargs)
854 return call(name, bound_call.args, bound_call.kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100855 except TypeError as e:
856 return e.with_traceback(None)
857 else:
858 return _call
859
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300860 def assert_not_called(self):
Kushal Das8af9db32014-04-17 01:36:14 +0530861 """assert that the mock was never called.
862 """
Kushal Das8af9db32014-04-17 01:36:14 +0530863 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100864 msg = ("Expected '%s' to not have been called. Called %s times.%s"
865 % (self._mock_name or 'mock',
866 self.call_count,
867 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530868 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100869
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300870 def assert_called(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100871 """assert that the mock was called at least once
872 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100873 if self.call_count == 0:
874 msg = ("Expected '%s' to have been called." %
Abraham Toriz Cruz5f5f11f2019-09-17 06:16:08 -0500875 (self._mock_name or 'mock'))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100876 raise AssertionError(msg)
877
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300878 def assert_called_once(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100879 """assert that the mock was called only once.
880 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100881 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100882 msg = ("Expected '%s' to have been called once. Called %s times.%s"
883 % (self._mock_name or 'mock',
884 self.call_count,
885 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100886 raise AssertionError(msg)
887
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300888 def assert_called_with(self, /, *args, **kwargs):
Rémi Lapeyref5896a02019-08-29 08:15:53 +0200889 """assert that the last call was made with the specified arguments.
Michael Foord345266a2012-03-14 12:24:34 -0700890
891 Raises an AssertionError if the args and keyword args passed in are
892 different to the last call to the mock."""
Michael Foord345266a2012-03-14 12:24:34 -0700893 if self.call_args is None:
894 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800895 actual = 'not called.'
896 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
897 % (expected, actual))
898 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700899
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100900 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700901 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100902 return msg
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700903 expected = self._call_matcher(_Call((args, kwargs), two=True))
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100904 actual = self._call_matcher(self.call_args)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700905 if actual != expected:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100906 cause = expected if isinstance(expected, Exception) else None
907 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700908
909
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300910 def assert_called_once_with(self, /, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100911 """assert that the mock was called exactly once and that that call was
912 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700913 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100914 msg = ("Expected '%s' to be called once. Called %s times.%s"
915 % (self._mock_name or 'mock',
916 self.call_count,
917 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700918 raise AssertionError(msg)
919 return self.assert_called_with(*args, **kwargs)
920
921
922 def assert_has_calls(self, calls, any_order=False):
923 """assert the mock has been called with the specified calls.
924 The `mock_calls` list is checked for the calls.
925
926 If `any_order` is False (the default) then the calls must be
927 sequential. There can be extra calls before or after the
928 specified calls.
929
930 If `any_order` is True then the calls can be in any order, but
931 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100932 expected = [self._call_matcher(c) for c in calls]
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400933 cause = next((e for e in expected if isinstance(e, Exception)), None)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100934 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700935 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100936 if expected not in all_calls:
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400937 if cause is None:
938 problem = 'Calls not found.'
939 else:
940 problem = ('Error processing expected calls.\n'
941 'Errors: {}').format(
942 [e if isinstance(e, Exception) else None
943 for e in expected])
Michael Foord345266a2012-03-14 12:24:34 -0700944 raise AssertionError(
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400945 f'{problem}\n'
Samuel Freilich2180f6b2019-09-24 18:04:29 -0400946 f'Expected: {_CallList(calls)}'
947 f'{self._calls_repr(prefix="Actual").rstrip(".")}'
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100948 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700949 return
950
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100951 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700952
953 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100954 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700955 try:
956 all_calls.remove(kall)
957 except ValueError:
958 not_found.append(kall)
959 if not_found:
960 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400961 '%r does not contain all of %r in its call list, '
962 'found %r instead' % (self._mock_name or 'mock',
963 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100964 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700965
966
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300967 def assert_any_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700968 """assert the mock has been called with the specified arguments.
969
970 The assert passes if the mock has *ever* been called, unlike
971 `assert_called_with` and `assert_called_once_with` that only pass if
972 the call is the most recent one."""
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700973 expected = self._call_matcher(_Call((args, kwargs), two=True))
974 cause = expected if isinstance(expected, Exception) else None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100975 actual = [self._call_matcher(c) for c in self.call_args_list]
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700976 if cause or expected not in _AnyComparer(actual):
Michael Foord345266a2012-03-14 12:24:34 -0700977 expected_string = self._format_mock_call_signature(args, kwargs)
978 raise AssertionError(
979 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100980 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700981
982
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300983 def _get_child_mock(self, /, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700984 """Create the child mocks for attributes and return value.
985 By default child mocks will be the same type as the parent.
986 Subclasses of Mock may want to override this to customize the way
987 child mocks are made.
988
989 For non-callable mocks the callable variant will be used (rather than
990 any custom subclass)."""
Lisa Roach77b3b772019-05-20 09:19:53 -0700991 _new_name = kw.get("_new_name")
992 if _new_name in self.__dict__['_spec_asyncs']:
993 return AsyncMock(**kw)
994
Michael Foord345266a2012-03-14 12:24:34 -0700995 _type = type(self)
Lisa Roach77b3b772019-05-20 09:19:53 -0700996 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
Lisa Roach9a7d9512019-09-28 18:42:44 -0700997 # Any asynchronous magic becomes an AsyncMock
Lisa Roach77b3b772019-05-20 09:19:53 -0700998 klass = AsyncMock
Lisa Roach8b03f942019-09-19 21:04:18 -0700999 elif issubclass(_type, AsyncMockMixin):
Lisa Roach3667e1e2019-09-29 21:56:47 -07001000 if (_new_name in _all_sync_magics or
1001 self._mock_methods and _new_name in self._mock_methods):
1002 # Any synchronous method on AsyncMock becomes a MagicMock
Lisa Roach9a7d9512019-09-28 18:42:44 -07001003 klass = MagicMock
1004 else:
1005 klass = AsyncMock
Lisa Roach8b03f942019-09-19 21:04:18 -07001006 elif not issubclass(_type, CallableMixin):
Michael Foord345266a2012-03-14 12:24:34 -07001007 if issubclass(_type, NonCallableMagicMock):
1008 klass = MagicMock
Lisa Roach9a7d9512019-09-28 18:42:44 -07001009 elif issubclass(_type, NonCallableMock):
Michael Foord345266a2012-03-14 12:24:34 -07001010 klass = Mock
1011 else:
1012 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +01001013
1014 if self._mock_sealed:
1015 attribute = "." + kw["name"] if "name" in kw else "()"
1016 mock_name = self._extract_mock_name() + attribute
1017 raise AttributeError(mock_name)
1018
Michael Foord345266a2012-03-14 12:24:34 -07001019 return klass(**kw)
1020
1021
Petter Strandmark47d94242018-10-28 21:37:10 +01001022 def _calls_repr(self, prefix="Calls"):
1023 """Renders self.mock_calls as a string.
1024
1025 Example: "\nCalls: [call(1), call(2)]."
1026
1027 If self.mock_calls is empty, an empty string is returned. The
1028 output will be truncated if very long.
1029 """
1030 if not self.mock_calls:
1031 return ""
1032 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
1033
1034
Michael Foord14fd9252019-09-13 18:40:56 +02001035_MOCK_SIG = inspect.signature(NonCallableMock.__init__)
1036
1037
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07001038class _AnyComparer(list):
1039 """A list which checks if it contains a call which may have an
1040 argument of ANY, flipping the components of item and self from
1041 their traditional locations so that ANY is guaranteed to be on
1042 the left."""
1043 def __contains__(self, item):
1044 for _call in self:
Chris Withersdb5e86a2020-01-29 16:24:54 +00001045 assert len(item) == len(_call)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07001046 if all([
1047 expected == actual
1048 for expected, actual in zip(item, _call)
1049 ]):
1050 return True
1051 return False
1052
Michael Foord345266a2012-03-14 12:24:34 -07001053
1054def _try_iter(obj):
1055 if obj is None:
1056 return obj
1057 if _is_exception(obj):
1058 return obj
1059 if _callable(obj):
1060 return obj
1061 try:
1062 return iter(obj)
1063 except TypeError:
1064 # XXXX backwards compatibility
1065 # but this will blow up on first call - so maybe we should fail early?
1066 return obj
1067
1068
Michael Foord345266a2012-03-14 12:24:34 -07001069class CallableMixin(Base):
1070
1071 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
1072 wraps=None, name=None, spec_set=None, parent=None,
1073 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
1074 self.__dict__['_mock_return_value'] = return_value
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001075 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -07001076 spec, wraps, name, spec_set, parent,
1077 _spec_state, _new_name, _new_parent, **kwargs
1078 )
1079
1080 self.side_effect = side_effect
1081
1082
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001083 def _mock_check_sig(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001084 # stub method that can be replaced with one with a specific signature
1085 pass
1086
1087
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001088 def __call__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001089 # can't use self in-case a function / method we are mocking uses self
1090 # in the signature
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001091 self._mock_check_sig(*args, **kwargs)
Lisa Roachef048512019-09-23 20:49:40 -07001092 self._increment_mock_call(*args, **kwargs)
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001093 return self._mock_call(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001094
1095
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001096 def _mock_call(self, /, *args, **kwargs):
Lisa Roachef048512019-09-23 20:49:40 -07001097 return self._execute_mock_call(*args, **kwargs)
1098
1099 def _increment_mock_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001100 self.called = True
1101 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001102
Chris Withers8ca0fa92018-12-03 21:31:37 +00001103 # handle call_args
Lisa Roachef048512019-09-23 20:49:40 -07001104 # needs to be set here so assertions on call arguments pass before
1105 # execution in the case of awaited calls
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001106 _call = _Call((args, kwargs), two=True)
1107 self.call_args = _call
1108 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -07001109
Chris Withers8ca0fa92018-12-03 21:31:37 +00001110 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001111 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +00001112 method_call_name = self._mock_name
1113
1114 # initial stuff for mock_calls:
1115 mock_call_name = self._mock_new_name
1116 is_a_call = mock_call_name == '()'
1117 self.mock_calls.append(_Call(('', args, kwargs)))
1118
1119 # follow up the chain of mocks:
1120 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001121 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001122
Chris Withers8ca0fa92018-12-03 21:31:37 +00001123 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001124 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001125 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001126 do_method_calls = _new_parent._mock_parent is not None
1127 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001128 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001129
Chris Withers8ca0fa92018-12-03 21:31:37 +00001130 # handle mock_calls:
1131 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001132 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001133
1134 if _new_parent._mock_new_name:
1135 if is_a_call:
1136 dot = ''
1137 else:
1138 dot = '.'
1139 is_a_call = _new_parent._mock_new_name == '()'
1140 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1141
1142 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001143 _new_parent = _new_parent._mock_new_parent
1144
Lisa Roachef048512019-09-23 20:49:40 -07001145 def _execute_mock_call(self, /, *args, **kwargs):
Jason Fried046442d2019-11-20 16:27:51 -08001146 # separate from _increment_mock_call so that awaited functions are
1147 # executed separately from their call, also AsyncMock overrides this method
Lisa Roachef048512019-09-23 20:49:40 -07001148
Michael Foord345266a2012-03-14 12:24:34 -07001149 effect = self.side_effect
1150 if effect is not None:
1151 if _is_exception(effect):
1152 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001153 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001154 result = next(effect)
1155 if _is_exception(result):
1156 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001157 else:
1158 result = effect(*args, **kwargs)
1159
1160 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001161 return result
Michael Foord345266a2012-03-14 12:24:34 -07001162
Mario Corcherof05df0a2018-12-08 11:25:02 +00001163 if self._mock_return_value is not DEFAULT:
1164 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001165
Mario Corcherof05df0a2018-12-08 11:25:02 +00001166 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001167 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001168
1169 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001170
1171
1172
1173class Mock(CallableMixin, NonCallableMock):
1174 """
1175 Create a new `Mock` object. `Mock` takes several optional arguments
1176 that specify the behaviour of the Mock object:
1177
1178 * `spec`: This can be either a list of strings or an existing object (a
1179 class or instance) that acts as the specification for the mock object. If
1180 you pass in an object then a list of strings is formed by calling dir on
1181 the object (excluding unsupported magic attributes and methods). Accessing
1182 any attribute not in this list will raise an `AttributeError`.
1183
1184 If `spec` is an object (rather than a list of strings) then
1185 `mock.__class__` returns the class of the spec object. This allows mocks
1186 to pass `isinstance` tests.
1187
1188 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1189 or get an attribute on the mock that isn't on the object passed as
1190 `spec_set` will raise an `AttributeError`.
1191
1192 * `side_effect`: A function to be called whenever the Mock is called. See
1193 the `side_effect` attribute. Useful for raising exceptions or
1194 dynamically changing return values. The function is called with the same
1195 arguments as the mock, and unless it returns `DEFAULT`, the return
1196 value of this function is used as the return value.
1197
Michael Foord2cd48732012-04-21 15:52:11 +01001198 If `side_effect` is an iterable then each call to the mock will return
1199 the next value from the iterable. If any of the members of the iterable
1200 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001201
Michael Foord345266a2012-03-14 12:24:34 -07001202 * `return_value`: The value returned when the mock is called. By default
1203 this is a new Mock (created on first access). See the
1204 `return_value` attribute.
1205
Michael Foord0682a0c2012-04-13 20:51:20 +01001206 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1207 calling the Mock will pass the call through to the wrapped object
1208 (returning the real result). Attribute access on the mock will return a
1209 Mock object that wraps the corresponding attribute of the wrapped object
1210 (so attempting to access an attribute that doesn't exist will raise an
1211 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001212
1213 If the mock has an explicit `return_value` set then calls are not passed
1214 to the wrapped object and the `return_value` is returned instead.
1215
1216 * `name`: If the mock has a name then it will be used in the repr of the
1217 mock. This can be useful for debugging. The name is propagated to child
1218 mocks.
1219
1220 Mocks can also be called with arbitrary keyword arguments. These will be
1221 used to set attributes on the mock after it is created.
1222 """
1223
1224
Michael Foord345266a2012-03-14 12:24:34 -07001225def _dot_lookup(thing, comp, import_path):
1226 try:
1227 return getattr(thing, comp)
1228 except AttributeError:
1229 __import__(import_path)
1230 return getattr(thing, comp)
1231
1232
1233def _importer(target):
1234 components = target.split('.')
1235 import_path = components.pop(0)
1236 thing = __import__(import_path)
1237
1238 for comp in components:
1239 import_path += ".%s" % comp
1240 thing = _dot_lookup(thing, comp, import_path)
1241 return thing
1242
1243
1244def _is_started(patcher):
1245 # XXXX horrible
1246 return hasattr(patcher, 'is_local')
1247
1248
1249class _patch(object):
1250
1251 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001252 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001253
1254 def __init__(
1255 self, getter, attribute, new, spec, create,
1256 spec_set, autospec, new_callable, kwargs
1257 ):
1258 if new_callable is not None:
1259 if new is not DEFAULT:
1260 raise ValueError(
1261 "Cannot use 'new' and 'new_callable' together"
1262 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001263 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001264 raise ValueError(
1265 "Cannot use 'autospec' and 'new_callable' together"
1266 )
1267
1268 self.getter = getter
1269 self.attribute = attribute
1270 self.new = new
1271 self.new_callable = new_callable
1272 self.spec = spec
1273 self.create = create
1274 self.has_local = False
1275 self.spec_set = spec_set
1276 self.autospec = autospec
1277 self.kwargs = kwargs
1278 self.additional_patchers = []
1279
1280
1281 def copy(self):
1282 patcher = _patch(
1283 self.getter, self.attribute, self.new, self.spec,
1284 self.create, self.spec_set,
1285 self.autospec, self.new_callable, self.kwargs
1286 )
1287 patcher.attribute_name = self.attribute_name
1288 patcher.additional_patchers = [
1289 p.copy() for p in self.additional_patchers
1290 ]
1291 return patcher
1292
1293
1294 def __call__(self, func):
1295 if isinstance(func, type):
1296 return self.decorate_class(func)
Xtreak436c2b02019-05-28 12:37:39 +05301297 if inspect.iscoroutinefunction(func):
1298 return self.decorate_async_callable(func)
Michael Foord345266a2012-03-14 12:24:34 -07001299 return self.decorate_callable(func)
1300
1301
1302 def decorate_class(self, klass):
1303 for attr in dir(klass):
1304 if not attr.startswith(patch.TEST_PREFIX):
1305 continue
1306
1307 attr_value = getattr(klass, attr)
1308 if not hasattr(attr_value, "__call__"):
1309 continue
1310
1311 patcher = self.copy()
1312 setattr(klass, attr, patcher(attr_value))
1313 return klass
1314
1315
Xtreak436c2b02019-05-28 12:37:39 +05301316 @contextlib.contextmanager
1317 def decoration_helper(self, patched, args, keywargs):
1318 extra_args = []
1319 entered_patchers = []
1320 patching = None
1321
1322 exc_info = tuple()
1323 try:
1324 for patching in patched.patchings:
1325 arg = patching.__enter__()
1326 entered_patchers.append(patching)
1327 if patching.attribute_name is not None:
1328 keywargs.update(arg)
1329 elif patching.new is DEFAULT:
1330 extra_args.append(arg)
1331
1332 args += tuple(extra_args)
1333 yield (args, keywargs)
1334 except:
1335 if (patching not in entered_patchers and
1336 _is_started(patching)):
1337 # the patcher may have been started, but an exception
1338 # raised whilst entering one of its additional_patchers
1339 entered_patchers.append(patching)
1340 # Pass the exception to __exit__
1341 exc_info = sys.exc_info()
1342 # re-raise the exception
1343 raise
1344 finally:
1345 for patching in reversed(entered_patchers):
1346 patching.__exit__(*exc_info)
1347
1348
Michael Foord345266a2012-03-14 12:24:34 -07001349 def decorate_callable(self, func):
Xtreak436c2b02019-05-28 12:37:39 +05301350 # NB. Keep the method in sync with decorate_async_callable()
Michael Foord345266a2012-03-14 12:24:34 -07001351 if hasattr(func, 'patchings'):
1352 func.patchings.append(self)
1353 return func
1354
1355 @wraps(func)
1356 def patched(*args, **keywargs):
Xtreak436c2b02019-05-28 12:37:39 +05301357 with self.decoration_helper(patched,
1358 args,
1359 keywargs) as (newargs, newkeywargs):
1360 return func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001361
Xtreak436c2b02019-05-28 12:37:39 +05301362 patched.patchings = [self]
1363 return patched
Michael Foord345266a2012-03-14 12:24:34 -07001364
Xtreak436c2b02019-05-28 12:37:39 +05301365
1366 def decorate_async_callable(self, func):
1367 # NB. Keep the method in sync with decorate_callable()
1368 if hasattr(func, 'patchings'):
1369 func.patchings.append(self)
1370 return func
1371
1372 @wraps(func)
1373 async def patched(*args, **keywargs):
1374 with self.decoration_helper(patched,
1375 args,
1376 keywargs) as (newargs, newkeywargs):
1377 return await func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001378
1379 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001380 return patched
1381
1382
1383 def get_original(self):
1384 target = self.getter()
1385 name = self.attribute
1386
1387 original = DEFAULT
1388 local = False
1389
1390 try:
1391 original = target.__dict__[name]
1392 except (AttributeError, KeyError):
1393 original = getattr(target, name, DEFAULT)
1394 else:
1395 local = True
1396
Michael Foordfddcfa22014-04-14 16:25:20 -04001397 if name in _builtins and isinstance(target, ModuleType):
1398 self.create = True
1399
Michael Foord345266a2012-03-14 12:24:34 -07001400 if not self.create and original is DEFAULT:
1401 raise AttributeError(
1402 "%s does not have the attribute %r" % (target, name)
1403 )
1404 return original, local
1405
1406
1407 def __enter__(self):
1408 """Perform the patch."""
1409 new, spec, spec_set = self.new, self.spec, self.spec_set
1410 autospec, kwargs = self.autospec, self.kwargs
1411 new_callable = self.new_callable
1412 self.target = self.getter()
1413
Michael Foord50a8c0e2012-03-25 18:57:58 +01001414 # normalise False to None
1415 if spec is False:
1416 spec = None
1417 if spec_set is False:
1418 spec_set = None
1419 if autospec is False:
1420 autospec = None
1421
1422 if spec is not None and autospec is not None:
1423 raise TypeError("Can't specify spec and autospec")
1424 if ((spec is not None or autospec is not None) and
1425 spec_set not in (True, None)):
1426 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1427
Michael Foord345266a2012-03-14 12:24:34 -07001428 original, local = self.get_original()
1429
Michael Foord50a8c0e2012-03-25 18:57:58 +01001430 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001431 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001432 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001433 # set spec to the object we are replacing
1434 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001435 if spec_set is True:
1436 spec_set = original
1437 spec = None
1438 elif spec is not None:
1439 if spec_set is True:
1440 spec_set = spec
1441 spec = None
1442 elif spec_set is True:
1443 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001444
Michael Foord50a8c0e2012-03-25 18:57:58 +01001445 if spec is not None or spec_set is not None:
1446 if original is DEFAULT:
1447 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001448 if isinstance(original, type):
1449 # If we're patching out a class and there is a spec
1450 inherit = True
Lisa Roach77b3b772019-05-20 09:19:53 -07001451 if spec is None and _is_async_obj(original):
1452 Klass = AsyncMock
1453 else:
1454 Klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -07001455 _kwargs = {}
1456 if new_callable is not None:
1457 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001458 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001459 this_spec = spec
1460 if spec_set is not None:
1461 this_spec = spec_set
1462 if _is_list(this_spec):
1463 not_callable = '__call__' not in this_spec
1464 else:
1465 not_callable = not callable(this_spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07001466 if _is_async_obj(this_spec):
1467 Klass = AsyncMock
1468 elif not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001469 Klass = NonCallableMagicMock
1470
1471 if spec is not None:
1472 _kwargs['spec'] = spec
1473 if spec_set is not None:
1474 _kwargs['spec_set'] = spec_set
1475
1476 # add a name to mocks
1477 if (isinstance(Klass, type) and
1478 issubclass(Klass, NonCallableMock) and self.attribute):
1479 _kwargs['name'] = self.attribute
1480
1481 _kwargs.update(kwargs)
1482 new = Klass(**_kwargs)
1483
1484 if inherit and _is_instance_mock(new):
1485 # we can only tell if the instance should be callable if the
1486 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001487 this_spec = spec
1488 if spec_set is not None:
1489 this_spec = spec_set
1490 if (not _is_list(this_spec) and not
1491 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001492 Klass = NonCallableMagicMock
1493
1494 _kwargs.pop('name')
1495 new.return_value = Klass(_new_parent=new, _new_name='()',
1496 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001497 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001498 # spec is ignored, new *must* be default, spec_set is treated
1499 # as a boolean. Should we check spec is not None and that spec_set
1500 # is a bool?
1501 if new is not DEFAULT:
1502 raise TypeError(
1503 "autospec creates the mock for you. Can't specify "
1504 "autospec and new."
1505 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001506 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001507 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001508 spec_set = bool(spec_set)
1509 if autospec is True:
1510 autospec = original
1511
1512 new = create_autospec(autospec, spec_set=spec_set,
1513 _name=self.attribute, **kwargs)
1514 elif kwargs:
1515 # can't set keyword args when we aren't creating the mock
1516 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1517 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1518
1519 new_attr = new
1520
1521 self.temp_original = original
1522 self.is_local = local
1523 setattr(self.target, self.attribute, new_attr)
1524 if self.attribute_name is not None:
1525 extra_args = {}
1526 if self.new is DEFAULT:
1527 extra_args[self.attribute_name] = new
1528 for patching in self.additional_patchers:
1529 arg = patching.__enter__()
1530 if patching.new is DEFAULT:
1531 extra_args.update(arg)
1532 return extra_args
1533
1534 return new
1535
1536
Michael Foord50a8c0e2012-03-25 18:57:58 +01001537 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001538 """Undo the patch."""
1539 if not _is_started(self):
Xtreak02b84cb2019-03-29 02:38:43 +05301540 return
Michael Foord345266a2012-03-14 12:24:34 -07001541
1542 if self.is_local and self.temp_original is not DEFAULT:
1543 setattr(self.target, self.attribute, self.temp_original)
1544 else:
1545 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001546 if not self.create and (not hasattr(self.target, self.attribute) or
1547 self.attribute in ('__doc__', '__module__',
1548 '__defaults__', '__annotations__',
1549 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001550 # needed for proxy objects like django settings
1551 setattr(self.target, self.attribute, self.temp_original)
1552
1553 del self.temp_original
1554 del self.is_local
1555 del self.target
1556 for patcher in reversed(self.additional_patchers):
1557 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001558 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001559
Michael Foordf7c41582012-06-10 20:36:32 +01001560
1561 def start(self):
1562 """Activate a patch, returning any created mock."""
1563 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001564 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001565 return result
1566
1567
1568 def stop(self):
1569 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001570 try:
1571 self._active_patches.remove(self)
1572 except ValueError:
1573 # If the patch hasn't been started this will fail
1574 pass
1575
Michael Foordf7c41582012-06-10 20:36:32 +01001576 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001577
1578
1579
1580def _get_target(target):
1581 try:
1582 target, attribute = target.rsplit('.', 1)
1583 except (TypeError, ValueError):
1584 raise TypeError("Need a valid target to patch. You supplied: %r" %
1585 (target,))
1586 getter = lambda: _importer(target)
1587 return getter, attribute
1588
1589
1590def _patch_object(
1591 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001592 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001593 new_callable=None, **kwargs
1594 ):
1595 """
Michael Foord345266a2012-03-14 12:24:34 -07001596 patch the named member (`attribute`) on an object (`target`) with a mock
1597 object.
1598
1599 `patch.object` can be used as a decorator, class decorator or a context
1600 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1601 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1602 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1603 the mock object it creates.
1604
1605 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1606 for choosing which methods to wrap.
1607 """
Elena Oatcd90a522019-12-08 12:14:38 -08001608 if type(target) is str:
1609 raise TypeError(
1610 f"{target!r} must be the actual object to be patched, not a str"
1611 )
Michael Foord345266a2012-03-14 12:24:34 -07001612 getter = lambda: target
1613 return _patch(
1614 getter, attribute, new, spec, create,
1615 spec_set, autospec, new_callable, kwargs
1616 )
1617
1618
Michael Foord50a8c0e2012-03-25 18:57:58 +01001619def _patch_multiple(target, spec=None, create=False, spec_set=None,
1620 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001621 """Perform multiple patches in a single call. It takes the object to be
1622 patched (either as an object or a string to fetch the object by importing)
1623 and keyword arguments for the patches::
1624
1625 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1626 ...
1627
1628 Use `DEFAULT` as the value if you want `patch.multiple` to create
1629 mocks for you. In this case the created mocks are passed into a decorated
1630 function by keyword, and a dictionary is returned when `patch.multiple` is
1631 used as a context manager.
1632
1633 `patch.multiple` can be used as a decorator, class decorator or a context
1634 manager. The arguments `spec`, `spec_set`, `create`,
1635 `autospec` and `new_callable` have the same meaning as for `patch`. These
1636 arguments will be applied to *all* patches done by `patch.multiple`.
1637
1638 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1639 for choosing which methods to wrap.
1640 """
1641 if type(target) is str:
1642 getter = lambda: _importer(target)
1643 else:
1644 getter = lambda: target
1645
1646 if not kwargs:
1647 raise ValueError(
1648 'Must supply at least one keyword argument with patch.multiple'
1649 )
1650 # need to wrap in a list for python 3, where items is a view
1651 items = list(kwargs.items())
1652 attribute, new = items[0]
1653 patcher = _patch(
1654 getter, attribute, new, spec, create, spec_set,
1655 autospec, new_callable, {}
1656 )
1657 patcher.attribute_name = attribute
1658 for attribute, new in items[1:]:
1659 this_patcher = _patch(
1660 getter, attribute, new, spec, create, spec_set,
1661 autospec, new_callable, {}
1662 )
1663 this_patcher.attribute_name = attribute
1664 patcher.additional_patchers.append(this_patcher)
1665 return patcher
1666
1667
1668def patch(
1669 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001670 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001671 ):
1672 """
1673 `patch` acts as a function decorator, class decorator or a context
1674 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001675 is patched with a `new` object. When the function/with statement exits
1676 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001677
Mario Corcherof5e7f392019-09-09 15:18:06 +01001678 If `new` is omitted, then the target is replaced with an
1679 `AsyncMock if the patched object is an async function or a
1680 `MagicMock` otherwise. If `patch` is used as a decorator and `new` is
Michael Foord54b3db82012-03-28 15:08:08 +01001681 omitted, the created mock is passed in as an extra argument to the
1682 decorated function. If `patch` is used as a context manager the created
1683 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001684
Michael Foord54b3db82012-03-28 15:08:08 +01001685 `target` should be a string in the form `'package.module.ClassName'`. The
1686 `target` is imported and the specified object replaced with the `new`
1687 object, so the `target` must be importable from the environment you are
1688 calling `patch` from. The target is imported when the decorated function
1689 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001690
1691 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1692 if patch is creating one for you.
1693
1694 In addition you can pass `spec=True` or `spec_set=True`, which causes
1695 patch to pass in the object being mocked as the spec/spec_set object.
1696
1697 `new_callable` allows you to specify a different class, or callable object,
Mario Corcherof5e7f392019-09-09 15:18:06 +01001698 that will be called to create the `new` object. By default `AsyncMock` is
1699 used for async functions and `MagicMock` for the rest.
Michael Foord345266a2012-03-14 12:24:34 -07001700
1701 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001702 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001703 All attributes of the mock will also have the spec of the corresponding
1704 attribute of the object being replaced. Methods and functions being
1705 mocked will have their arguments checked and will raise a `TypeError` if
1706 they are called with the wrong signature. For mocks replacing a class,
1707 their return value (the 'instance') will have the same spec as the class.
1708
1709 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1710 arbitrary object as the spec instead of the one being replaced.
1711
1712 By default `patch` will fail to replace attributes that don't exist. If
1713 you pass in `create=True`, and the attribute doesn't exist, patch will
1714 create the attribute for you when the patched function is called, and
1715 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001716 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001717 default because it can be dangerous. With it switched on you can write
1718 passing tests against APIs that don't actually exist!
1719
1720 Patch can be used as a `TestCase` class decorator. It works by
1721 decorating each test method in the class. This reduces the boilerplate
1722 code when your test methods share a common patchings set. `patch` finds
1723 tests by looking for method names that start with `patch.TEST_PREFIX`.
1724 By default this is `test`, which matches the way `unittest` finds tests.
1725 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1726
1727 Patch can be used as a context manager, with the with statement. Here the
1728 patching applies to the indented block after the with statement. If you
1729 use "as" then the patched object will be bound to the name after the
1730 "as"; very useful if `patch` is creating a mock object for you.
1731
1732 `patch` takes arbitrary keyword arguments. These will be passed to
Paulo Henrique Silva40c08092020-01-25 07:53:54 -03001733 `AsyncMock` if the patched object is asynchronous, to `MagicMock`
1734 otherwise or to `new_callable` if specified.
Michael Foord345266a2012-03-14 12:24:34 -07001735
1736 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1737 available for alternate use-cases.
1738 """
1739 getter, attribute = _get_target(target)
1740 return _patch(
1741 getter, attribute, new, spec, create,
1742 spec_set, autospec, new_callable, kwargs
1743 )
1744
1745
1746class _patch_dict(object):
1747 """
1748 Patch a dictionary, or dictionary like object, and restore the dictionary
1749 to its original state after the test.
1750
1751 `in_dict` can be a dictionary or a mapping like container. If it is a
1752 mapping then it must at least support getting, setting and deleting items
1753 plus iterating over keys.
1754
1755 `in_dict` can also be a string specifying the name of the dictionary, which
1756 will then be fetched by importing it.
1757
1758 `values` can be a dictionary of values to set in the dictionary. `values`
1759 can also be an iterable of `(key, value)` pairs.
1760
1761 If `clear` is True then the dictionary will be cleared before the new
1762 values are set.
1763
1764 `patch.dict` can also be called with arbitrary keyword arguments to set
1765 values in the dictionary::
1766
1767 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1768 ...
1769
1770 `patch.dict` can be used as a context manager, decorator or class
1771 decorator. When used as a class decorator `patch.dict` honours
1772 `patch.TEST_PREFIX` for choosing which methods to wrap.
1773 """
1774
1775 def __init__(self, in_dict, values=(), clear=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001776 self.in_dict = in_dict
1777 # support any argument supported by dict(...) constructor
1778 self.values = dict(values)
1779 self.values.update(kwargs)
1780 self.clear = clear
1781 self._original = None
1782
1783
1784 def __call__(self, f):
1785 if isinstance(f, type):
1786 return self.decorate_class(f)
1787 @wraps(f)
1788 def _inner(*args, **kw):
1789 self._patch_dict()
1790 try:
1791 return f(*args, **kw)
1792 finally:
1793 self._unpatch_dict()
1794
1795 return _inner
1796
1797
1798 def decorate_class(self, klass):
1799 for attr in dir(klass):
1800 attr_value = getattr(klass, attr)
1801 if (attr.startswith(patch.TEST_PREFIX) and
1802 hasattr(attr_value, "__call__")):
1803 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1804 decorated = decorator(attr_value)
1805 setattr(klass, attr, decorated)
1806 return klass
1807
1808
1809 def __enter__(self):
1810 """Patch the dict."""
1811 self._patch_dict()
Mario Corchero04530812019-05-28 13:53:31 +01001812 return self.in_dict
Michael Foord345266a2012-03-14 12:24:34 -07001813
1814
1815 def _patch_dict(self):
1816 values = self.values
Xtreaka875ea52019-02-25 00:24:49 +05301817 if isinstance(self.in_dict, str):
1818 self.in_dict = _importer(self.in_dict)
Michael Foord345266a2012-03-14 12:24:34 -07001819 in_dict = self.in_dict
1820 clear = self.clear
1821
1822 try:
1823 original = in_dict.copy()
1824 except AttributeError:
1825 # dict like object with no copy method
1826 # must support iteration over keys
1827 original = {}
1828 for key in in_dict:
1829 original[key] = in_dict[key]
1830 self._original = original
1831
1832 if clear:
1833 _clear_dict(in_dict)
1834
1835 try:
1836 in_dict.update(values)
1837 except AttributeError:
1838 # dict like object with no update method
1839 for key in values:
1840 in_dict[key] = values[key]
1841
1842
1843 def _unpatch_dict(self):
1844 in_dict = self.in_dict
1845 original = self._original
1846
1847 _clear_dict(in_dict)
1848
1849 try:
1850 in_dict.update(original)
1851 except AttributeError:
1852 for key in original:
1853 in_dict[key] = original[key]
1854
1855
1856 def __exit__(self, *args):
1857 """Unpatch the dict."""
Chris Withersdb5e86a2020-01-29 16:24:54 +00001858 if self._original is not None:
1859 self._unpatch_dict()
Michael Foord345266a2012-03-14 12:24:34 -07001860 return False
1861
Mario Corcheroe131c972020-01-24 08:38:33 +00001862
1863 def start(self):
1864 """Activate a patch, returning any created mock."""
1865 result = self.__enter__()
1866 _patch._active_patches.append(self)
1867 return result
1868
1869
1870 def stop(self):
1871 """Stop an active patch."""
1872 try:
1873 _patch._active_patches.remove(self)
1874 except ValueError:
1875 # If the patch hasn't been started this will fail
1876 pass
1877
1878 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001879
1880
1881def _clear_dict(in_dict):
1882 try:
1883 in_dict.clear()
1884 except AttributeError:
1885 keys = list(in_dict)
1886 for key in keys:
1887 del in_dict[key]
1888
1889
Michael Foordf7c41582012-06-10 20:36:32 +01001890def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001891 """Stop all active patches. LIFO to unroll nested patches."""
1892 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001893 patch.stop()
1894
1895
Michael Foord345266a2012-03-14 12:24:34 -07001896patch.object = _patch_object
1897patch.dict = _patch_dict
1898patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001899patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001900patch.TEST_PREFIX = 'test'
1901
1902magic_methods = (
1903 "lt le gt ge eq ne "
1904 "getitem setitem delitem "
1905 "len contains iter "
1906 "hash str sizeof "
1907 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001908 # we added divmod and rdivmod here instead of numerics
1909 # because there is no idivmod
1910 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001911 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001912 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001913 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001914 "fspath "
Lisa Roach9a7d9512019-09-28 18:42:44 -07001915 "aiter "
Michael Foord345266a2012-03-14 12:24:34 -07001916)
1917
Michael Foordd2623d72014-04-14 11:23:48 -04001918numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001919 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001920)
Michael Foord345266a2012-03-14 12:24:34 -07001921inplace = ' '.join('i%s' % n for n in numerics.split())
1922right = ' '.join('r%s' % n for n in numerics.split())
1923
1924# not including __prepare__, __instancecheck__, __subclasscheck__
1925# (as they are metaclass methods)
1926# __del__ is not supported at all as it causes problems if it exists
1927
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001928_non_defaults = {
1929 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1930 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1931 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1932 '__repr__', '__dir__', '__subclasses__', '__format__',
Lisa Roach8b03f942019-09-19 21:04:18 -07001933 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001934}
Michael Foord345266a2012-03-14 12:24:34 -07001935
1936
1937def _get_method(name, func):
1938 "Turns a callable object (like a mock) into a real function"
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001939 def method(self, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -07001940 return func(self, *args, **kw)
1941 method.__name__ = name
1942 return method
1943
1944
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001945_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001946 '__%s__' % method for method in
1947 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001948}
Michael Foord345266a2012-03-14 12:24:34 -07001949
Lisa Roach77b3b772019-05-20 09:19:53 -07001950# Magic methods used for async `with` statements
1951_async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
Lisa Roach8b03f942019-09-19 21:04:18 -07001952# Magic methods that are only used with async calls but are synchronous functions themselves
1953_sync_async_magics = {"__aiter__"}
1954_async_magics = _async_method_magics | _sync_async_magics
Lisa Roach77b3b772019-05-20 09:19:53 -07001955
Lisa Roach8b03f942019-09-19 21:04:18 -07001956_all_sync_magics = _magics | _non_defaults
1957_all_magics = _all_sync_magics | _async_magics
Michael Foord345266a2012-03-14 12:24:34 -07001958
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001959_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001960 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001961 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001962 '__instancecheck__', '__subclasscheck__',
1963 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001964}
Michael Foord345266a2012-03-14 12:24:34 -07001965
1966_calculate_return_value = {
1967 '__hash__': lambda self: object.__hash__(self),
1968 '__str__': lambda self: object.__str__(self),
1969 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001970 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001971}
1972
1973_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001974 '__lt__': NotImplemented,
1975 '__gt__': NotImplemented,
1976 '__le__': NotImplemented,
1977 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001978 '__int__': 1,
1979 '__contains__': False,
1980 '__len__': 0,
1981 '__exit__': False,
1982 '__complex__': 1j,
1983 '__float__': 1.0,
1984 '__bool__': True,
1985 '__index__': 1,
Lisa Roach77b3b772019-05-20 09:19:53 -07001986 '__aexit__': False,
Michael Foord345266a2012-03-14 12:24:34 -07001987}
1988
1989
1990def _get_eq(self):
1991 def __eq__(other):
1992 ret_val = self.__eq__._mock_return_value
1993 if ret_val is not DEFAULT:
1994 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001995 if self is other:
1996 return True
1997 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001998 return __eq__
1999
2000def _get_ne(self):
2001 def __ne__(other):
2002 if self.__ne__._mock_return_value is not DEFAULT:
2003 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02002004 if self is other:
2005 return False
2006 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07002007 return __ne__
2008
2009def _get_iter(self):
2010 def __iter__():
2011 ret_val = self.__iter__._mock_return_value
2012 if ret_val is DEFAULT:
2013 return iter([])
2014 # if ret_val was already an iterator, then calling iter on it should
2015 # return the iterator unchanged
2016 return iter(ret_val)
2017 return __iter__
2018
Lisa Roach77b3b772019-05-20 09:19:53 -07002019def _get_async_iter(self):
2020 def __aiter__():
2021 ret_val = self.__aiter__._mock_return_value
2022 if ret_val is DEFAULT:
2023 return _AsyncIterator(iter([]))
2024 return _AsyncIterator(iter(ret_val))
2025 return __aiter__
2026
Michael Foord345266a2012-03-14 12:24:34 -07002027_side_effect_methods = {
2028 '__eq__': _get_eq,
2029 '__ne__': _get_ne,
2030 '__iter__': _get_iter,
Lisa Roach77b3b772019-05-20 09:19:53 -07002031 '__aiter__': _get_async_iter
Michael Foord345266a2012-03-14 12:24:34 -07002032}
2033
2034
2035
2036def _set_return_value(mock, method, name):
Karthikeyan Singaravelan72b10042020-01-27 12:18:15 +05302037 # If _mock_wraps is present then attach it so that wrapped object
2038 # is used for return value is used when called.
2039 if mock._mock_wraps is not None:
2040 method._mock_wraps = getattr(mock._mock_wraps, name)
2041 return
2042
Michael Foord345266a2012-03-14 12:24:34 -07002043 fixed = _return_values.get(name, DEFAULT)
2044 if fixed is not DEFAULT:
2045 method.return_value = fixed
2046 return
2047
marcoramirezmxa9187c32019-09-16 11:34:46 -05002048 return_calculator = _calculate_return_value.get(name)
2049 if return_calculator is not None:
2050 return_value = return_calculator(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002051 method.return_value = return_value
2052 return
2053
2054 side_effector = _side_effect_methods.get(name)
2055 if side_effector is not None:
2056 method.side_effect = side_effector(mock)
2057
2058
2059
Lisa Roach9a7d9512019-09-28 18:42:44 -07002060class MagicMixin(Base):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002061 def __init__(self, /, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07002062 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10002063 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07002064 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002065
2066
2067 def _mock_set_magics(self):
Lisa Roach9a7d9512019-09-28 18:42:44 -07002068 orig_magics = _magics | _async_method_magics
2069 these_magics = orig_magics
Michael Foord345266a2012-03-14 12:24:34 -07002070
Łukasz Langaa468db92015-04-13 23:12:42 -07002071 if getattr(self, "_mock_methods", None) is not None:
Lisa Roach9a7d9512019-09-28 18:42:44 -07002072 these_magics = orig_magics.intersection(self._mock_methods)
Michael Foord345266a2012-03-14 12:24:34 -07002073
2074 remove_magics = set()
Lisa Roach9a7d9512019-09-28 18:42:44 -07002075 remove_magics = orig_magics - these_magics
Michael Foord345266a2012-03-14 12:24:34 -07002076
2077 for entry in remove_magics:
2078 if entry in type(self).__dict__:
2079 # remove unneeded magic methods
2080 delattr(self, entry)
2081
2082 # don't overwrite existing attributes if called a second time
2083 these_magics = these_magics - set(type(self).__dict__)
2084
2085 _type = type(self)
2086 for entry in these_magics:
2087 setattr(_type, entry, MagicProxy(entry, self))
2088
2089
2090
2091class NonCallableMagicMock(MagicMixin, NonCallableMock):
2092 """A version of `MagicMock` that isn't callable."""
2093 def mock_add_spec(self, spec, spec_set=False):
2094 """Add a spec to a mock. `spec` can either be an object or a
2095 list of strings. Only attributes on the `spec` can be fetched as
2096 attributes from the mock.
2097
2098 If `spec_set` is True then only attributes on the spec can be set."""
2099 self._mock_add_spec(spec, spec_set)
2100 self._mock_set_magics()
2101
2102
Lisa Roach9a7d9512019-09-28 18:42:44 -07002103class AsyncMagicMixin(MagicMixin):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002104 def __init__(self, /, *args, **kw):
Lisa Roach9a7d9512019-09-28 18:42:44 -07002105 self._mock_set_magics() # make magic work for kwargs in init
Lisa Roach77b3b772019-05-20 09:19:53 -07002106 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)
Lisa Roach9a7d9512019-09-28 18:42:44 -07002107 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002108
Lisa Roach9a7d9512019-09-28 18:42:44 -07002109class MagicMock(MagicMixin, Mock):
Michael Foord345266a2012-03-14 12:24:34 -07002110 """
2111 MagicMock is a subclass of Mock with default implementations
2112 of most of the magic methods. You can use MagicMock without having to
2113 configure the magic methods yourself.
2114
2115 If you use the `spec` or `spec_set` arguments then *only* magic
2116 methods that exist in the spec will be created.
2117
2118 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
2119 """
2120 def mock_add_spec(self, spec, spec_set=False):
2121 """Add a spec to a mock. `spec` can either be an object or a
2122 list of strings. Only attributes on the `spec` can be fetched as
2123 attributes from the mock.
2124
2125 If `spec_set` is True then only attributes on the spec can be set."""
2126 self._mock_add_spec(spec, spec_set)
2127 self._mock_set_magics()
2128
2129
2130
Lisa Roach9a7d9512019-09-28 18:42:44 -07002131class MagicProxy(Base):
Michael Foord345266a2012-03-14 12:24:34 -07002132 def __init__(self, name, parent):
2133 self.name = name
2134 self.parent = parent
2135
Michael Foord345266a2012-03-14 12:24:34 -07002136 def create_mock(self):
2137 entry = self.name
2138 parent = self.parent
2139 m = parent._get_child_mock(name=entry, _new_name=entry,
2140 _new_parent=parent)
2141 setattr(parent, entry, m)
2142 _set_return_value(parent, m, entry)
2143 return m
2144
2145 def __get__(self, obj, _type=None):
2146 return self.create_mock()
2147
2148
Lisa Roach77b3b772019-05-20 09:19:53 -07002149class AsyncMockMixin(Base):
Lisa Roach77b3b772019-05-20 09:19:53 -07002150 await_count = _delegating_property('await_count')
2151 await_args = _delegating_property('await_args')
2152 await_args_list = _delegating_property('await_args_list')
2153
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002154 def __init__(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002155 super().__init__(*args, **kwargs)
Chris Withersc7dd3c72020-01-27 14:11:19 +00002156 # iscoroutinefunction() checks _is_coroutine property to say if an
Lisa Roach77b3b772019-05-20 09:19:53 -07002157 # object is a coroutine. Without this check it looks to see if it is a
2158 # function/method, which in this case it is not (since it is an
2159 # AsyncMock).
2160 # It is set through __dict__ because when spec_set is True, this
2161 # attribute is likely undefined.
2162 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
Lisa Roach77b3b772019-05-20 09:19:53 -07002163 self.__dict__['_mock_await_count'] = 0
2164 self.__dict__['_mock_await_args'] = None
2165 self.__dict__['_mock_await_args_list'] = _CallList()
2166 code_mock = NonCallableMock(spec_set=CodeType)
2167 code_mock.co_flags = inspect.CO_COROUTINE
2168 self.__dict__['__code__'] = code_mock
2169
Jason Fried046442d2019-11-20 16:27:51 -08002170 async def _execute_mock_call(self, /, *args, **kwargs):
Chris Withersdb5e86a2020-01-29 16:24:54 +00002171 # This is nearly just like super(), except for special handling
Jason Fried046442d2019-11-20 16:27:51 -08002172 # of coroutines
Lisa Roach77b3b772019-05-20 09:19:53 -07002173
2174 _call = self.call_args
Jason Fried046442d2019-11-20 16:27:51 -08002175 self.await_count += 1
2176 self.await_args = _call
2177 self.await_args_list.append(_call)
Lisa Roach77b3b772019-05-20 09:19:53 -07002178
Jason Fried046442d2019-11-20 16:27:51 -08002179 effect = self.side_effect
2180 if effect is not None:
2181 if _is_exception(effect):
2182 raise effect
2183 elif not _callable(effect):
2184 try:
2185 result = next(effect)
2186 except StopIteration:
2187 # It is impossible to propogate a StopIteration
2188 # through coroutines because of PEP 479
2189 raise StopAsyncIteration
2190 if _is_exception(result):
2191 raise result
Chris Withersc7dd3c72020-01-27 14:11:19 +00002192 elif iscoroutinefunction(effect):
Jason Fried046442d2019-11-20 16:27:51 -08002193 result = await effect(*args, **kwargs)
2194 else:
2195 result = effect(*args, **kwargs)
Lisa Roach77b3b772019-05-20 09:19:53 -07002196
Jason Fried046442d2019-11-20 16:27:51 -08002197 if result is not DEFAULT:
2198 return result
2199
2200 if self._mock_return_value is not DEFAULT:
2201 return self.return_value
2202
2203 if self._mock_wraps is not None:
Chris Withersc7dd3c72020-01-27 14:11:19 +00002204 if iscoroutinefunction(self._mock_wraps):
Jason Fried046442d2019-11-20 16:27:51 -08002205 return await self._mock_wraps(*args, **kwargs)
2206 return self._mock_wraps(*args, **kwargs)
2207
2208 return self.return_value
Lisa Roach77b3b772019-05-20 09:19:53 -07002209
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002210 def assert_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002211 """
2212 Assert that the mock was awaited at least once.
2213 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002214 if self.await_count == 0:
2215 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2216 raise AssertionError(msg)
2217
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002218 def assert_awaited_once(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002219 """
2220 Assert that the mock was awaited exactly once.
2221 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002222 if not self.await_count == 1:
2223 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2224 f" Awaited {self.await_count} times.")
2225 raise AssertionError(msg)
2226
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002227 def assert_awaited_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002228 """
2229 Assert that the last await was with the specified arguments.
2230 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002231 if self.await_args is None:
2232 expected = self._format_mock_call_signature(args, kwargs)
2233 raise AssertionError(f'Expected await: {expected}\nNot awaited')
2234
2235 def _error_message():
Xtreak0ae022c2019-05-29 12:32:26 +05302236 msg = self._format_mock_failure_message(args, kwargs, action='await')
Lisa Roach77b3b772019-05-20 09:19:53 -07002237 return msg
2238
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002239 expected = self._call_matcher(_Call((args, kwargs), two=True))
Lisa Roach77b3b772019-05-20 09:19:53 -07002240 actual = self._call_matcher(self.await_args)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002241 if actual != expected:
Lisa Roach77b3b772019-05-20 09:19:53 -07002242 cause = expected if isinstance(expected, Exception) else None
2243 raise AssertionError(_error_message()) from cause
2244
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002245 def assert_awaited_once_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002246 """
2247 Assert that the mock was awaited exactly once and with the specified
2248 arguments.
2249 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002250 if not self.await_count == 1:
2251 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2252 f" Awaited {self.await_count} times.")
2253 raise AssertionError(msg)
2254 return self.assert_awaited_with(*args, **kwargs)
2255
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002256 def assert_any_await(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002257 """
2258 Assert the mock has ever been awaited with the specified arguments.
2259 """
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002260 expected = self._call_matcher(_Call((args, kwargs), two=True))
2261 cause = expected if isinstance(expected, Exception) else None
Lisa Roach77b3b772019-05-20 09:19:53 -07002262 actual = [self._call_matcher(c) for c in self.await_args_list]
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002263 if cause or expected not in _AnyComparer(actual):
Lisa Roach77b3b772019-05-20 09:19:53 -07002264 expected_string = self._format_mock_call_signature(args, kwargs)
2265 raise AssertionError(
2266 '%s await not found' % expected_string
2267 ) from cause
2268
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002269 def assert_has_awaits(self, calls, any_order=False):
Lisa Roach77b3b772019-05-20 09:19:53 -07002270 """
2271 Assert the mock has been awaited with the specified calls.
2272 The :attr:`await_args_list` list is checked for the awaits.
2273
2274 If `any_order` is False (the default) then the awaits must be
2275 sequential. There can be extra calls before or after the
2276 specified awaits.
2277
2278 If `any_order` is True then the awaits can be in any order, but
2279 they must all appear in :attr:`await_args_list`.
2280 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002281 expected = [self._call_matcher(c) for c in calls]
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002282 cause = next((e for e in expected if isinstance(e, Exception)), None)
Lisa Roach77b3b772019-05-20 09:19:53 -07002283 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2284 if not any_order:
2285 if expected not in all_awaits:
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002286 if cause is None:
2287 problem = 'Awaits not found.'
2288 else:
2289 problem = ('Error processing expected awaits.\n'
2290 'Errors: {}').format(
2291 [e if isinstance(e, Exception) else None
2292 for e in expected])
Lisa Roach77b3b772019-05-20 09:19:53 -07002293 raise AssertionError(
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002294 f'{problem}\n'
2295 f'Expected: {_CallList(calls)}\n'
Lisa Roach77b3b772019-05-20 09:19:53 -07002296 f'Actual: {self.await_args_list}'
2297 ) from cause
2298 return
2299
2300 all_awaits = list(all_awaits)
2301
2302 not_found = []
2303 for kall in expected:
2304 try:
2305 all_awaits.remove(kall)
2306 except ValueError:
2307 not_found.append(kall)
2308 if not_found:
2309 raise AssertionError(
2310 '%r not all found in await list' % (tuple(not_found),)
2311 ) from cause
2312
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002313 def assert_not_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002314 """
2315 Assert that the mock was never awaited.
2316 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002317 if self.await_count != 0:
Xtreakff6b2e62019-05-27 18:26:23 +05302318 msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
Lisa Roach77b3b772019-05-20 09:19:53 -07002319 f" Awaited {self.await_count} times.")
2320 raise AssertionError(msg)
2321
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002322 def reset_mock(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002323 """
2324 See :func:`.Mock.reset_mock()`
2325 """
2326 super().reset_mock(*args, **kwargs)
2327 self.await_count = 0
2328 self.await_args = None
2329 self.await_args_list = _CallList()
2330
2331
2332class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2333 """
2334 Enhance :class:`Mock` with features allowing to mock
2335 an async function.
2336
2337 The :class:`AsyncMock` object will behave so the object is
2338 recognized as an async function, and the result of a call is an awaitable:
2339
2340 >>> mock = AsyncMock()
Chris Withersc7dd3c72020-01-27 14:11:19 +00002341 >>> iscoroutinefunction(mock)
Lisa Roach77b3b772019-05-20 09:19:53 -07002342 True
2343 >>> inspect.isawaitable(mock())
2344 True
2345
2346
2347 The result of ``mock()`` is an async function which will have the outcome
2348 of ``side_effect`` or ``return_value``:
2349
2350 - if ``side_effect`` is a function, the async function will return the
2351 result of that function,
2352 - if ``side_effect`` is an exception, the async function will raise the
2353 exception,
2354 - if ``side_effect`` is an iterable, the async function will return the
2355 next value of the iterable, however, if the sequence of result is
2356 exhausted, ``StopIteration`` is raised immediately,
2357 - if ``side_effect`` is not defined, the async function will return the
2358 value defined by ``return_value``, hence, by default, the async function
2359 returns a new :class:`AsyncMock` object.
2360
2361 If the outcome of ``side_effect`` or ``return_value`` is an async function,
2362 the mock async function obtained when the mock object is called will be this
2363 async function itself (and not an async function returning an async
2364 function).
2365
2366 The test author can also specify a wrapped object with ``wraps``. In this
2367 case, the :class:`Mock` object behavior is the same as with an
2368 :class:`.Mock` object: the wrapped object may have methods
2369 defined as async function functions.
2370
Xtreake7cb23b2019-05-21 14:17:17 +05302371 Based on Martin Richard's asynctest project.
Lisa Roach77b3b772019-05-20 09:19:53 -07002372 """
2373
Michael Foord345266a2012-03-14 12:24:34 -07002374
2375class _ANY(object):
2376 "A helper object that compares equal to everything."
2377
2378 def __eq__(self, other):
2379 return True
2380
2381 def __ne__(self, other):
2382 return False
2383
2384 def __repr__(self):
2385 return '<ANY>'
2386
2387ANY = _ANY()
2388
2389
2390
2391def _format_call_signature(name, args, kwargs):
2392 message = '%s(%%s)' % name
2393 formatted_args = ''
2394 args_string = ', '.join([repr(arg) for arg in args])
2395 kwargs_string = ', '.join([
Xtreak9d607062019-09-09 16:25:22 +05302396 '%s=%r' % (key, value) for key, value in kwargs.items()
Michael Foord345266a2012-03-14 12:24:34 -07002397 ])
2398 if args_string:
2399 formatted_args = args_string
2400 if kwargs_string:
2401 if formatted_args:
2402 formatted_args += ', '
2403 formatted_args += kwargs_string
2404
2405 return message % formatted_args
2406
2407
2408
2409class _Call(tuple):
2410 """
2411 A tuple for holding the results of a call to a mock, either in the form
2412 `(args, kwargs)` or `(name, args, kwargs)`.
2413
2414 If args or kwargs are empty then a call tuple will compare equal to
2415 a tuple without those values. This makes comparisons less verbose::
2416
2417 _Call(('name', (), {})) == ('name',)
2418 _Call(('name', (1,), {})) == ('name', (1,))
2419 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2420
2421 The `_Call` object provides a useful shortcut for comparing with call::
2422
2423 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2424 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2425
2426 If the _Call has no name then it will match any name.
2427 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002428 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002429 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002430 args = ()
2431 kwargs = {}
2432 _len = len(value)
2433 if _len == 3:
2434 name, args, kwargs = value
2435 elif _len == 2:
2436 first, second = value
2437 if isinstance(first, str):
2438 name = first
2439 if isinstance(second, tuple):
2440 args = second
2441 else:
2442 kwargs = second
2443 else:
2444 args, kwargs = first, second
2445 elif _len == 1:
2446 value, = value
2447 if isinstance(value, str):
2448 name = value
2449 elif isinstance(value, tuple):
2450 args = value
2451 else:
2452 kwargs = value
2453
2454 if two:
2455 return tuple.__new__(cls, (args, kwargs))
2456
2457 return tuple.__new__(cls, (name, args, kwargs))
2458
2459
2460 def __init__(self, value=(), name=None, parent=None, two=False,
2461 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002462 self._mock_name = name
2463 self._mock_parent = parent
2464 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002465
2466
2467 def __eq__(self, other):
Michael Foord345266a2012-03-14 12:24:34 -07002468 try:
2469 len_other = len(other)
2470 except TypeError:
Serhiy Storchaka662db122019-08-08 08:42:54 +03002471 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07002472
2473 self_name = ''
2474 if len(self) == 2:
2475 self_args, self_kwargs = self
2476 else:
2477 self_name, self_args, self_kwargs = self
2478
Andrew Dunaie63e6172018-12-04 11:08:45 +02002479 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2480 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002481 return False
2482
Michael Foord345266a2012-03-14 12:24:34 -07002483 other_name = ''
2484 if len_other == 0:
2485 other_args, other_kwargs = (), {}
2486 elif len_other == 3:
2487 other_name, other_args, other_kwargs = other
2488 elif len_other == 1:
2489 value, = other
2490 if isinstance(value, tuple):
2491 other_args = value
2492 other_kwargs = {}
2493 elif isinstance(value, str):
2494 other_name = value
2495 other_args, other_kwargs = (), {}
2496 else:
2497 other_args = ()
2498 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002499 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002500 # could be (name, args) or (name, kwargs) or (args, kwargs)
2501 first, second = other
2502 if isinstance(first, str):
2503 other_name = first
2504 if isinstance(second, tuple):
2505 other_args, other_kwargs = second, {}
2506 else:
2507 other_args, other_kwargs = (), second
2508 else:
2509 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002510 else:
2511 return False
Michael Foord345266a2012-03-14 12:24:34 -07002512
2513 if self_name and other_name != self_name:
2514 return False
2515
2516 # this order is important for ANY to work!
2517 return (other_args, other_kwargs) == (self_args, self_kwargs)
2518
2519
Berker Peksagce913872016-03-28 00:30:02 +03002520 __ne__ = object.__ne__
2521
2522
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002523 def __call__(self, /, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002524 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002525 return _Call(('', args, kwargs), name='()')
2526
Andrew Dunaie63e6172018-12-04 11:08:45 +02002527 name = self._mock_name + '()'
2528 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002529
2530
2531 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002532 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002533 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002534 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002535 return _Call(name=name, parent=self, from_kall=False)
2536
2537
blhsing72c35992019-09-11 07:28:06 -07002538 def __getattribute__(self, attr):
2539 if attr in tuple.__dict__:
2540 raise AttributeError
2541 return tuple.__getattribute__(self, attr)
2542
2543
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302544 def _get_call_arguments(self):
2545 if len(self) == 2:
2546 args, kwargs = self
2547 else:
2548 name, args, kwargs = self
2549
2550 return args, kwargs
2551
2552 @property
2553 def args(self):
2554 return self._get_call_arguments()[0]
2555
2556 @property
2557 def kwargs(self):
2558 return self._get_call_arguments()[1]
2559
Michael Foord345266a2012-03-14 12:24:34 -07002560 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002561 if not self._mock_from_kall:
2562 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002563 if name.startswith('()'):
2564 name = 'call%s' % name
2565 return name
2566
2567 if len(self) == 2:
2568 name = 'call'
2569 args, kwargs = self
2570 else:
2571 name, args, kwargs = self
2572 if not name:
2573 name = 'call'
2574 elif not name.startswith('()'):
2575 name = 'call.%s' % name
2576 else:
2577 name = 'call%s' % name
2578 return _format_call_signature(name, args, kwargs)
2579
2580
2581 def call_list(self):
2582 """For a call object that represents multiple calls, `call_list`
2583 returns a list of all the intermediate calls as well as the
2584 final call."""
2585 vals = []
2586 thing = self
2587 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002588 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002589 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002590 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002591 return _CallList(reversed(vals))
2592
2593
2594call = _Call(from_kall=False)
2595
2596
Michael Foord345266a2012-03-14 12:24:34 -07002597def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2598 _name=None, **kwargs):
2599 """Create a mock object using another object as a spec. Attributes on the
2600 mock will use the corresponding attribute on the `spec` object as their
2601 spec.
2602
2603 Functions or methods being mocked will have their arguments checked
2604 to check that they are called with the correct signature.
2605
2606 If `spec_set` is True then attempting to set attributes that don't exist
2607 on the spec object will raise an `AttributeError`.
2608
2609 If a class is used as a spec then the return value of the mock (the
2610 instance of the class) will have the same spec. You can use a class as the
2611 spec for an instance object by passing `instance=True`. The returned mock
2612 will only be callable if instances of the mock are callable.
2613
2614 `create_autospec` also takes arbitrary keyword arguments that are passed to
2615 the constructor of the created mock."""
2616 if _is_list(spec):
2617 # can't pass a list instance to the mock constructor as it will be
2618 # interpreted as a list of strings
2619 spec = type(spec)
2620
2621 is_type = isinstance(spec, type)
Xtreakff6b2e62019-05-27 18:26:23 +05302622 is_async_func = _is_async_func(spec)
Michael Foord345266a2012-03-14 12:24:34 -07002623 _kwargs = {'spec': spec}
2624 if spec_set:
2625 _kwargs = {'spec_set': spec}
2626 elif spec is None:
2627 # None we mock with a normal mock without a spec
2628 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002629 if _kwargs and instance:
2630 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002631
2632 _kwargs.update(kwargs)
2633
2634 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002635 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002636 # descriptors don't have a spec
2637 # because we don't know what type they return
2638 _kwargs = {}
Lisa Roach77b3b772019-05-20 09:19:53 -07002639 elif is_async_func:
2640 if instance:
2641 raise RuntimeError("Instance can not be True when create_autospec "
2642 "is mocking an async function")
2643 Klass = AsyncMock
Michael Foord345266a2012-03-14 12:24:34 -07002644 elif not _callable(spec):
2645 Klass = NonCallableMagicMock
2646 elif is_type and instance and not _instance_callable(spec):
2647 Klass = NonCallableMagicMock
2648
Kushal Das484f8a82014-04-16 01:05:50 +05302649 _name = _kwargs.pop('name', _name)
2650
Michael Foord345266a2012-03-14 12:24:34 -07002651 _new_name = _name
2652 if _parent is None:
2653 # for a top level object no _new_name should be set
2654 _new_name = ''
2655
2656 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2657 name=_name, **_kwargs)
2658
2659 if isinstance(spec, FunctionTypes):
2660 # should only happen at the top level because we don't
2661 # recurse for functions
2662 mock = _set_signature(mock, spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07002663 if is_async_func:
Xtreakff6b2e62019-05-27 18:26:23 +05302664 _setup_async_mock(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002665 else:
2666 _check_signature(spec, mock, is_type, instance)
2667
2668 if _parent is not None and not instance:
2669 _parent._mock_children[_name] = mock
2670
2671 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002672 mock.return_value = create_autospec(spec, spec_set, instance=True,
2673 _name='()', _parent=mock)
2674
2675 for entry in dir(spec):
2676 if _is_magic(entry):
2677 # MagicMock already does the useful magic methods for us
2678 continue
2679
Michael Foord345266a2012-03-14 12:24:34 -07002680 # XXXX do we need a better way of getting attributes without
2681 # triggering code execution (?) Probably not - we need the actual
2682 # object to mock it so we would rather trigger a property than mock
2683 # the property descriptor. Likewise we want to mock out dynamically
2684 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002685 # XXXX what about attributes that raise exceptions other than
2686 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002687 # we could be resilient against it, or catch and propagate the
2688 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002689 try:
2690 original = getattr(spec, entry)
2691 except AttributeError:
2692 continue
Michael Foord345266a2012-03-14 12:24:34 -07002693
2694 kwargs = {'spec': original}
2695 if spec_set:
2696 kwargs = {'spec_set': original}
2697
2698 if not isinstance(original, FunctionTypes):
2699 new = _SpecState(original, spec_set, mock, entry, instance)
2700 mock._mock_children[entry] = new
2701 else:
2702 parent = mock
2703 if isinstance(spec, FunctionTypes):
2704 parent = mock.mock
2705
Michael Foord345266a2012-03-14 12:24:34 -07002706 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002707 kwargs['_eat_self'] = skipfirst
Chris Withersc7dd3c72020-01-27 14:11:19 +00002708 if iscoroutinefunction(original):
Lisa Roach77b3b772019-05-20 09:19:53 -07002709 child_klass = AsyncMock
2710 else:
2711 child_klass = MagicMock
2712 new = child_klass(parent=parent, name=entry, _new_name=entry,
2713 _new_parent=parent,
2714 **kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002715 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002716 _check_signature(original, new, skipfirst=skipfirst)
2717
2718 # so functions created with _set_signature become instance attributes,
2719 # *plus* their underlying mock exists in _mock_children of the parent
2720 # mock. Adding to _mock_children may be unnecessary where we are also
2721 # setting as an instance attribute?
2722 if isinstance(new, FunctionTypes):
2723 setattr(mock, entry, new)
2724
2725 return mock
2726
2727
2728def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002729 """
2730 Return whether we should skip the first argument on spec's `entry`
2731 attribute.
2732 """
Michael Foord345266a2012-03-14 12:24:34 -07002733 if not isinstance(spec, type):
2734 if entry in getattr(spec, '__dict__', {}):
2735 # instance attribute - shouldn't skip
2736 return False
Michael Foord345266a2012-03-14 12:24:34 -07002737 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002738
2739 for klass in spec.__mro__:
2740 result = klass.__dict__.get(entry, DEFAULT)
2741 if result is DEFAULT:
2742 continue
2743 if isinstance(result, (staticmethod, classmethod)):
2744 return False
Carl Friedrich Bolz-Tereicka3276772020-01-29 16:43:37 +01002745 elif isinstance(result, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002746 # Normal method => skip if looked up on type
2747 # (if looked up on instance, self is already skipped)
2748 return is_type
2749 else:
2750 return False
Michael Foord345266a2012-03-14 12:24:34 -07002751
Chris Withersadbf1782019-05-01 23:04:04 +01002752 # function is a dynamically provided attribute
Michael Foord345266a2012-03-14 12:24:34 -07002753 return is_type
2754
2755
Michael Foord345266a2012-03-14 12:24:34 -07002756class _SpecState(object):
2757
2758 def __init__(self, spec, spec_set=False, parent=None,
2759 name=None, ids=None, instance=False):
2760 self.spec = spec
2761 self.ids = ids
2762 self.spec_set = spec_set
2763 self.parent = parent
2764 self.instance = instance
2765 self.name = name
2766
2767
2768FunctionTypes = (
2769 # python function
2770 type(create_autospec),
2771 # instance method
2772 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002773)
2774
Michael Foord345266a2012-03-14 12:24:34 -07002775
Michael Foorda74561a2012-03-25 19:03:13 +01002776file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002777
Michael Foord04cbe0c2013-03-19 17:22:51 -07002778
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002779def _to_stream(read_data):
2780 if isinstance(read_data, bytes):
2781 return io.BytesIO(read_data)
Michael Foord04cbe0c2013-03-19 17:22:51 -07002782 else:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002783 return io.StringIO(read_data)
Michael Foord0dccf652012-03-25 19:11:50 +01002784
Robert Collins5329aaa2015-07-17 20:08:45 +12002785
Michael Foord0dccf652012-03-25 19:11:50 +01002786def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002787 """
2788 A helper function to create a mock to replace the use of `open`. It works
2789 for `open` called directly or used as a context manager.
2790
2791 The `mock` argument is the mock object to configure. If `None` (the
2792 default) then a `MagicMock` will be created for you, with the API limited
2793 to methods or attributes available on standard file handles.
2794
Xtreak71f82a22018-12-20 21:30:21 +05302795 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002796 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002797 """
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002798 _read_data = _to_stream(read_data)
2799 _state = [_read_data, None]
2800
Robert Collinsca647ef2015-07-24 03:48:20 +12002801 def _readlines_side_effect(*args, **kwargs):
2802 if handle.readlines.return_value is not None:
2803 return handle.readlines.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002804 return _state[0].readlines(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002805
2806 def _read_side_effect(*args, **kwargs):
2807 if handle.read.return_value is not None:
2808 return handle.read.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002809 return _state[0].read(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002810
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002811 def _readline_side_effect(*args, **kwargs):
Tony Flury20870232018-09-12 23:21:16 +01002812 yield from _iter_side_effect()
2813 while True:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002814 yield _state[0].readline(*args, **kwargs)
Tony Flury20870232018-09-12 23:21:16 +01002815
2816 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002817 if handle.readline.return_value is not None:
2818 while True:
2819 yield handle.readline.return_value
2820 for line in _state[0]:
2821 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002822
Damien Nadé394119a2019-05-23 12:03:25 +02002823 def _next_side_effect():
2824 if handle.readline.return_value is not None:
2825 return handle.readline.return_value
2826 return next(_state[0])
2827
Michael Foorda74561a2012-03-25 19:03:13 +01002828 global file_spec
2829 if file_spec is None:
2830 import _io
2831 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2832
Michael Foord345266a2012-03-14 12:24:34 -07002833 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002834 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002835
Robert Collinsca647ef2015-07-24 03:48:20 +12002836 handle = MagicMock(spec=file_spec)
2837 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002838
Robert Collinsca647ef2015-07-24 03:48:20 +12002839 handle.write.return_value = None
2840 handle.read.return_value = None
2841 handle.readline.return_value = None
2842 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002843
Robert Collinsca647ef2015-07-24 03:48:20 +12002844 handle.read.side_effect = _read_side_effect
2845 _state[1] = _readline_side_effect()
2846 handle.readline.side_effect = _state[1]
2847 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002848 handle.__iter__.side_effect = _iter_side_effect
Damien Nadé394119a2019-05-23 12:03:25 +02002849 handle.__next__.side_effect = _next_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002850
Robert Collinsca647ef2015-07-24 03:48:20 +12002851 def reset_data(*args, **kwargs):
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002852 _state[0] = _to_stream(read_data)
Robert Collinsca647ef2015-07-24 03:48:20 +12002853 if handle.readline.side_effect == _state[1]:
2854 # Only reset the side effect if the user hasn't overridden it.
2855 _state[1] = _readline_side_effect()
2856 handle.readline.side_effect = _state[1]
2857 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002858
Robert Collinsca647ef2015-07-24 03:48:20 +12002859 mock.side_effect = reset_data
2860 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002861 return mock
2862
2863
2864class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002865 """
2866 A mock intended to be used as a property, or other descriptor, on a class.
2867 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2868 a return value when it is fetched.
2869
2870 Fetching a `PropertyMock` instance from an object calls the mock, with
2871 no args. Setting it calls the mock with the value being set.
2872 """
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002873 def _get_child_mock(self, /, **kwargs):
Michael Foordc2870622012-04-13 16:57:22 +01002874 return MagicMock(**kwargs)
2875
Raymond Hettinger0dac68f2019-08-29 01:27:42 -07002876 def __get__(self, obj, obj_type=None):
Michael Foord345266a2012-03-14 12:24:34 -07002877 return self()
2878 def __set__(self, obj, val):
2879 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002880
2881
2882def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002883 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002884
2885 Given an input Mock, seals it to ensure no further mocks will be generated
2886 when accessing an attribute that was not already defined.
2887
Mario Corchero96200eb2018-10-19 22:57:37 +01002888 The operation recursively seals the mock passed in, meaning that
2889 the mock itself, any mocks generated by accessing one of its attributes,
2890 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002891 """
2892 mock._mock_sealed = True
2893 for attr in dir(mock):
2894 try:
2895 m = getattr(mock, attr)
2896 except AttributeError:
2897 continue
2898 if not isinstance(m, NonCallableMock):
2899 continue
2900 if m._mock_new_parent is mock:
2901 seal(m)
Lisa Roach77b3b772019-05-20 09:19:53 -07002902
2903
Lisa Roach77b3b772019-05-20 09:19:53 -07002904class _AsyncIterator:
2905 """
2906 Wraps an iterator in an asynchronous iterator.
2907 """
2908 def __init__(self, iterator):
2909 self.iterator = iterator
2910 code_mock = NonCallableMock(spec_set=CodeType)
2911 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
2912 self.__dict__['__code__'] = code_mock
2913
Lisa Roach77b3b772019-05-20 09:19:53 -07002914 async def __anext__(self):
2915 try:
2916 return next(self.iterator)
2917 except StopIteration:
2918 pass
2919 raise StopAsyncIteration