blob: 720f682efbb54cf96d1249afe7622cb49d361541 [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'))
idanw206c598a042020-12-06 11:59:36 +0200409 if spec_arg is not None and _is_async_obj(spec_arg):
Michael Foord14fd9252019-09-13 18:40:56 +0200410 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:
vabr-g4662fa92020-11-05 18:04:38 +0100634 if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')):
vabr-g9fc57132020-12-10 19:35:28 +0100635 raise AttributeError(
vabr-gfdb9efc2020-12-14 19:30:09 +0100636 f"{name!r} is not a valid assertion. Use a spec "
637 f"for the mock if {name!r} is meant to be an attribute.")
Michael Foord345266a2012-03-14 12:24:34 -0700638
639 result = self._mock_children.get(name)
640 if result is _deleted:
641 raise AttributeError(name)
642 elif result is None:
643 wraps = None
644 if self._mock_wraps is not None:
645 # XXXX should we get the attribute without triggering code
646 # execution?
647 wraps = getattr(self._mock_wraps, name)
648
649 result = self._get_child_mock(
650 parent=self, name=name, wraps=wraps, _new_name=name,
651 _new_parent=self
652 )
653 self._mock_children[name] = result
654
655 elif isinstance(result, _SpecState):
656 result = create_autospec(
657 result.spec, result.spec_set, result.instance,
658 result.parent, result.name
659 )
660 self._mock_children[name] = result
661
662 return result
663
664
Mario Corchero552be9d2017-10-17 12:35:11 +0100665 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700666 _name_list = [self._mock_new_name]
667 _parent = self._mock_new_parent
668 last = self
669
670 dot = '.'
671 if _name_list == ['()']:
672 dot = ''
Chris Withersadbf1782019-05-01 23:04:04 +0100673
Michael Foord345266a2012-03-14 12:24:34 -0700674 while _parent is not None:
675 last = _parent
676
677 _name_list.append(_parent._mock_new_name + dot)
678 dot = '.'
679 if _parent._mock_new_name == '()':
680 dot = ''
681
682 _parent = _parent._mock_new_parent
683
Michael Foord345266a2012-03-14 12:24:34 -0700684 _name_list = list(reversed(_name_list))
685 _first = last._mock_name or 'mock'
686 if len(_name_list) > 1:
687 if _name_list[1] not in ('()', '().'):
688 _first += '.'
689 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100690 return ''.join(_name_list)
691
692 def __repr__(self):
693 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700694
695 name_string = ''
696 if name not in ('mock', 'mock.'):
697 name_string = ' name=%r' % name
698
699 spec_string = ''
700 if self._spec_class is not None:
701 spec_string = ' spec=%r'
702 if self._spec_set:
703 spec_string = ' spec_set=%r'
704 spec_string = spec_string % self._spec_class.__name__
705 return "<%s%s%s id='%s'>" % (
706 type(self).__name__,
707 name_string,
708 spec_string,
709 id(self)
710 )
711
712
713 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700714 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100715 if not FILTER_DIR:
716 return object.__dir__(self)
717
Michael Foord345266a2012-03-14 12:24:34 -0700718 extras = self._mock_methods or []
719 from_type = dir(type(self))
720 from_dict = list(self.__dict__)
Mario Corchero0df635c2019-04-30 19:56:36 +0100721 from_child_mocks = [
722 m_name for m_name, m_value in self._mock_children.items()
723 if m_value is not _deleted]
Michael Foord345266a2012-03-14 12:24:34 -0700724
Michael Foord313f85f2012-03-25 18:16:07 +0100725 from_type = [e for e in from_type if not e.startswith('_')]
726 from_dict = [e for e in from_dict if not e.startswith('_') or
727 _is_magic(e)]
Mario Corchero0df635c2019-04-30 19:56:36 +0100728 return sorted(set(extras + from_type + from_dict + from_child_mocks))
Michael Foord345266a2012-03-14 12:24:34 -0700729
730
731 def __setattr__(self, name, value):
732 if name in _allowed_names:
733 # property setters go through here
734 return object.__setattr__(self, name, value)
735 elif (self._spec_set and self._mock_methods is not None and
736 name not in self._mock_methods and
737 name not in self.__dict__):
738 raise AttributeError("Mock object has no attribute '%s'" % name)
739 elif name in _unsupported_magics:
740 msg = 'Attempting to set unsupported magic method %r.' % name
741 raise AttributeError(msg)
742 elif name in _all_magics:
743 if self._mock_methods is not None and name not in self._mock_methods:
744 raise AttributeError("Mock object has no attribute '%s'" % name)
745
746 if not _is_instance_mock(value):
747 setattr(type(self), name, _get_method(name, value))
748 original = value
749 value = lambda *args, **kw: original(self, *args, **kw)
750 else:
751 # only set _new_name and not name so that mock_calls is tracked
752 # but not method calls
753 _check_and_set_parent(self, value, None, name)
754 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100755 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700756 elif name == '__class__':
757 self._spec_class = value
758 return
759 else:
760 if _check_and_set_parent(self, value, name, name):
761 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100762
763 if self._mock_sealed and not hasattr(self, name):
764 mock_name = f'{self._extract_mock_name()}.{name}'
765 raise AttributeError(f'Cannot set {mock_name}')
766
Michael Foord345266a2012-03-14 12:24:34 -0700767 return object.__setattr__(self, name, value)
768
769
770 def __delattr__(self, name):
771 if name in _all_magics and name in type(self).__dict__:
772 delattr(type(self), name)
773 if name not in self.__dict__:
774 # for magic methods that are still MagicProxy objects and
775 # not set on the instance itself
776 return
777
Michael Foord345266a2012-03-14 12:24:34 -0700778 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000779 if name in self.__dict__:
Xtreak830b43d2019-04-14 00:42:33 +0530780 _safe_super(NonCallableMock, self).__delattr__(name)
Pablo Galindo222d3032019-01-21 08:57:46 +0000781 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700782 raise AttributeError(name)
783 if obj is not _missing:
784 del self._mock_children[name]
785 self._mock_children[name] = _deleted
786
787
Michael Foord345266a2012-03-14 12:24:34 -0700788 def _format_mock_call_signature(self, args, kwargs):
789 name = self._mock_name or 'mock'
790 return _format_call_signature(name, args, kwargs)
791
792
Xtreak0ae022c2019-05-29 12:32:26 +0530793 def _format_mock_failure_message(self, args, kwargs, action='call'):
794 message = 'expected %s not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700795 expected_string = self._format_mock_call_signature(args, kwargs)
796 call_args = self.call_args
Michael Foord345266a2012-03-14 12:24:34 -0700797 actual_string = self._format_mock_call_signature(*call_args)
Xtreak0ae022c2019-05-29 12:32:26 +0530798 return message % (action, expected_string, actual_string)
Michael Foord345266a2012-03-14 12:24:34 -0700799
800
Xtreakc9612782019-08-29 11:39:01 +0530801 def _get_call_signature_from_name(self, name):
802 """
803 * If call objects are asserted against a method/function like obj.meth1
804 then there could be no name for the call object to lookup. Hence just
805 return the spec_signature of the method/function being asserted against.
806 * If the name is not empty then remove () and split by '.' to get
807 list of names to iterate through the children until a potential
808 match is found. A child mock is created only during attribute access
809 so if we get a _SpecState then no attributes of the spec were accessed
810 and can be safely exited.
811 """
812 if not name:
813 return self._spec_signature
814
815 sig = None
816 names = name.replace('()', '').split('.')
817 children = self._mock_children
818
819 for name in names:
820 child = children.get(name)
821 if child is None or isinstance(child, _SpecState):
822 break
823 else:
Karthikeyan Singaravelan66b00a92020-01-24 18:44:29 +0530824 # If an autospecced object is attached using attach_mock the
825 # child would be a function with mock object as attribute from
826 # which signature has to be derived.
827 child = _extract_mock(child)
Xtreakc9612782019-08-29 11:39:01 +0530828 children = child._mock_children
829 sig = child._spec_signature
830
831 return sig
832
833
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100834 def _call_matcher(self, _call):
835 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000836 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100837 comparison key suitable for matching with other calls.
838 This is a best effort method which relies on the spec's signature,
839 if available, or falls back on the arguments themselves.
840 """
Xtreakc9612782019-08-29 11:39:01 +0530841
842 if isinstance(_call, tuple) and len(_call) > 2:
843 sig = self._get_call_signature_from_name(_call[0])
844 else:
845 sig = self._spec_signature
846
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100847 if sig is not None:
848 if len(_call) == 2:
849 name = ''
850 args, kwargs = _call
851 else:
852 name, args, kwargs = _call
853 try:
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700854 bound_call = sig.bind(*args, **kwargs)
855 return call(name, bound_call.args, bound_call.kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100856 except TypeError as e:
857 return e.with_traceback(None)
858 else:
859 return _call
860
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300861 def assert_not_called(self):
Kushal Das8af9db32014-04-17 01:36:14 +0530862 """assert that the mock was never called.
863 """
Kushal Das8af9db32014-04-17 01:36:14 +0530864 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100865 msg = ("Expected '%s' to not have been called. Called %s times.%s"
866 % (self._mock_name or 'mock',
867 self.call_count,
868 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530869 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100870
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300871 def assert_called(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100872 """assert that the mock was called at least once
873 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100874 if self.call_count == 0:
875 msg = ("Expected '%s' to have been called." %
Abraham Toriz Cruz5f5f11f2019-09-17 06:16:08 -0500876 (self._mock_name or 'mock'))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100877 raise AssertionError(msg)
878
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300879 def assert_called_once(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100880 """assert that the mock was called only once.
881 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100882 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100883 msg = ("Expected '%s' to have been called once. Called %s times.%s"
884 % (self._mock_name or 'mock',
885 self.call_count,
886 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100887 raise AssertionError(msg)
888
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300889 def assert_called_with(self, /, *args, **kwargs):
Rémi Lapeyref5896a02019-08-29 08:15:53 +0200890 """assert that the last call was made with the specified arguments.
Michael Foord345266a2012-03-14 12:24:34 -0700891
892 Raises an AssertionError if the args and keyword args passed in are
893 different to the last call to the mock."""
Michael Foord345266a2012-03-14 12:24:34 -0700894 if self.call_args is None:
895 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800896 actual = 'not called.'
897 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
898 % (expected, actual))
899 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700900
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100901 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700902 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100903 return msg
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700904 expected = self._call_matcher(_Call((args, kwargs), two=True))
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100905 actual = self._call_matcher(self.call_args)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700906 if actual != expected:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100907 cause = expected if isinstance(expected, Exception) else None
908 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700909
910
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300911 def assert_called_once_with(self, /, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100912 """assert that the mock was called exactly once and that that call was
913 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700914 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100915 msg = ("Expected '%s' to be called once. Called %s times.%s"
916 % (self._mock_name or 'mock',
917 self.call_count,
918 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700919 raise AssertionError(msg)
920 return self.assert_called_with(*args, **kwargs)
921
922
923 def assert_has_calls(self, calls, any_order=False):
924 """assert the mock has been called with the specified calls.
925 The `mock_calls` list is checked for the calls.
926
927 If `any_order` is False (the default) then the calls must be
928 sequential. There can be extra calls before or after the
929 specified calls.
930
931 If `any_order` is True then the calls can be in any order, but
932 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100933 expected = [self._call_matcher(c) for c in calls]
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400934 cause = next((e for e in expected if isinstance(e, Exception)), None)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100935 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700936 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100937 if expected not in all_calls:
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400938 if cause is None:
939 problem = 'Calls not found.'
940 else:
941 problem = ('Error processing expected calls.\n'
942 'Errors: {}').format(
943 [e if isinstance(e, Exception) else None
944 for e in expected])
Michael Foord345266a2012-03-14 12:24:34 -0700945 raise AssertionError(
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400946 f'{problem}\n'
Samuel Freilich2180f6b2019-09-24 18:04:29 -0400947 f'Expected: {_CallList(calls)}'
948 f'{self._calls_repr(prefix="Actual").rstrip(".")}'
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100949 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700950 return
951
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100952 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700953
954 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100955 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700956 try:
957 all_calls.remove(kall)
958 except ValueError:
959 not_found.append(kall)
960 if not_found:
961 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400962 '%r does not contain all of %r in its call list, '
963 'found %r instead' % (self._mock_name or 'mock',
964 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100965 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700966
967
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300968 def assert_any_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700969 """assert the mock has been called with the specified arguments.
970
971 The assert passes if the mock has *ever* been called, unlike
972 `assert_called_with` and `assert_called_once_with` that only pass if
973 the call is the most recent one."""
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700974 expected = self._call_matcher(_Call((args, kwargs), two=True))
975 cause = expected if isinstance(expected, Exception) else None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100976 actual = [self._call_matcher(c) for c in self.call_args_list]
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700977 if cause or expected not in _AnyComparer(actual):
Michael Foord345266a2012-03-14 12:24:34 -0700978 expected_string = self._format_mock_call_signature(args, kwargs)
979 raise AssertionError(
980 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100981 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700982
983
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300984 def _get_child_mock(self, /, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700985 """Create the child mocks for attributes and return value.
986 By default child mocks will be the same type as the parent.
987 Subclasses of Mock may want to override this to customize the way
988 child mocks are made.
989
990 For non-callable mocks the callable variant will be used (rather than
991 any custom subclass)."""
Lisa Roach77b3b772019-05-20 09:19:53 -0700992 _new_name = kw.get("_new_name")
993 if _new_name in self.__dict__['_spec_asyncs']:
994 return AsyncMock(**kw)
995
Michael Foord345266a2012-03-14 12:24:34 -0700996 _type = type(self)
Lisa Roach77b3b772019-05-20 09:19:53 -0700997 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
Lisa Roach9a7d9512019-09-28 18:42:44 -0700998 # Any asynchronous magic becomes an AsyncMock
Lisa Roach77b3b772019-05-20 09:19:53 -0700999 klass = AsyncMock
Lisa Roach8b03f942019-09-19 21:04:18 -07001000 elif issubclass(_type, AsyncMockMixin):
Lisa Roach3667e1e2019-09-29 21:56:47 -07001001 if (_new_name in _all_sync_magics or
1002 self._mock_methods and _new_name in self._mock_methods):
1003 # Any synchronous method on AsyncMock becomes a MagicMock
Lisa Roach9a7d9512019-09-28 18:42:44 -07001004 klass = MagicMock
1005 else:
1006 klass = AsyncMock
Lisa Roach8b03f942019-09-19 21:04:18 -07001007 elif not issubclass(_type, CallableMixin):
Michael Foord345266a2012-03-14 12:24:34 -07001008 if issubclass(_type, NonCallableMagicMock):
1009 klass = MagicMock
Lisa Roach9a7d9512019-09-28 18:42:44 -07001010 elif issubclass(_type, NonCallableMock):
Michael Foord345266a2012-03-14 12:24:34 -07001011 klass = Mock
1012 else:
1013 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +01001014
1015 if self._mock_sealed:
1016 attribute = "." + kw["name"] if "name" in kw else "()"
1017 mock_name = self._extract_mock_name() + attribute
1018 raise AttributeError(mock_name)
1019
Michael Foord345266a2012-03-14 12:24:34 -07001020 return klass(**kw)
1021
1022
Petter Strandmark47d94242018-10-28 21:37:10 +01001023 def _calls_repr(self, prefix="Calls"):
1024 """Renders self.mock_calls as a string.
1025
1026 Example: "\nCalls: [call(1), call(2)]."
1027
1028 If self.mock_calls is empty, an empty string is returned. The
1029 output will be truncated if very long.
1030 """
1031 if not self.mock_calls:
1032 return ""
1033 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
1034
1035
Michael Foord14fd9252019-09-13 18:40:56 +02001036_MOCK_SIG = inspect.signature(NonCallableMock.__init__)
1037
1038
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07001039class _AnyComparer(list):
1040 """A list which checks if it contains a call which may have an
1041 argument of ANY, flipping the components of item and self from
1042 their traditional locations so that ANY is guaranteed to be on
1043 the left."""
1044 def __contains__(self, item):
1045 for _call in self:
Chris Withersdb5e86a2020-01-29 16:24:54 +00001046 assert len(item) == len(_call)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07001047 if all([
1048 expected == actual
1049 for expected, actual in zip(item, _call)
1050 ]):
1051 return True
1052 return False
1053
Michael Foord345266a2012-03-14 12:24:34 -07001054
1055def _try_iter(obj):
1056 if obj is None:
1057 return obj
1058 if _is_exception(obj):
1059 return obj
1060 if _callable(obj):
1061 return obj
1062 try:
1063 return iter(obj)
1064 except TypeError:
1065 # XXXX backwards compatibility
1066 # but this will blow up on first call - so maybe we should fail early?
1067 return obj
1068
1069
Michael Foord345266a2012-03-14 12:24:34 -07001070class CallableMixin(Base):
1071
1072 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
1073 wraps=None, name=None, spec_set=None, parent=None,
1074 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
1075 self.__dict__['_mock_return_value'] = return_value
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001076 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -07001077 spec, wraps, name, spec_set, parent,
1078 _spec_state, _new_name, _new_parent, **kwargs
1079 )
1080
1081 self.side_effect = side_effect
1082
1083
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001084 def _mock_check_sig(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001085 # stub method that can be replaced with one with a specific signature
1086 pass
1087
1088
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001089 def __call__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001090 # can't use self in-case a function / method we are mocking uses self
1091 # in the signature
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001092 self._mock_check_sig(*args, **kwargs)
Lisa Roachef048512019-09-23 20:49:40 -07001093 self._increment_mock_call(*args, **kwargs)
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001094 return self._mock_call(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001095
1096
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001097 def _mock_call(self, /, *args, **kwargs):
Lisa Roachef048512019-09-23 20:49:40 -07001098 return self._execute_mock_call(*args, **kwargs)
1099
1100 def _increment_mock_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001101 self.called = True
1102 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001103
Chris Withers8ca0fa92018-12-03 21:31:37 +00001104 # handle call_args
Lisa Roachef048512019-09-23 20:49:40 -07001105 # needs to be set here so assertions on call arguments pass before
1106 # execution in the case of awaited calls
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001107 _call = _Call((args, kwargs), two=True)
1108 self.call_args = _call
1109 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -07001110
Chris Withers8ca0fa92018-12-03 21:31:37 +00001111 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001112 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +00001113 method_call_name = self._mock_name
1114
1115 # initial stuff for mock_calls:
1116 mock_call_name = self._mock_new_name
1117 is_a_call = mock_call_name == '()'
1118 self.mock_calls.append(_Call(('', args, kwargs)))
1119
1120 # follow up the chain of mocks:
1121 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001122 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001123
Chris Withers8ca0fa92018-12-03 21:31:37 +00001124 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001125 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001126 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001127 do_method_calls = _new_parent._mock_parent is not None
1128 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001129 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001130
Chris Withers8ca0fa92018-12-03 21:31:37 +00001131 # handle mock_calls:
1132 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001133 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001134
1135 if _new_parent._mock_new_name:
1136 if is_a_call:
1137 dot = ''
1138 else:
1139 dot = '.'
1140 is_a_call = _new_parent._mock_new_name == '()'
1141 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1142
1143 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001144 _new_parent = _new_parent._mock_new_parent
1145
Lisa Roachef048512019-09-23 20:49:40 -07001146 def _execute_mock_call(self, /, *args, **kwargs):
Jason Fried046442d2019-11-20 16:27:51 -08001147 # separate from _increment_mock_call so that awaited functions are
1148 # executed separately from their call, also AsyncMock overrides this method
Lisa Roachef048512019-09-23 20:49:40 -07001149
Michael Foord345266a2012-03-14 12:24:34 -07001150 effect = self.side_effect
1151 if effect is not None:
1152 if _is_exception(effect):
1153 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001154 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001155 result = next(effect)
1156 if _is_exception(result):
1157 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001158 else:
1159 result = effect(*args, **kwargs)
1160
1161 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001162 return result
Michael Foord345266a2012-03-14 12:24:34 -07001163
Mario Corcherof05df0a2018-12-08 11:25:02 +00001164 if self._mock_return_value is not DEFAULT:
1165 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001166
Mario Corcherof05df0a2018-12-08 11:25:02 +00001167 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001168 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001169
1170 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001171
1172
1173
1174class Mock(CallableMixin, NonCallableMock):
1175 """
1176 Create a new `Mock` object. `Mock` takes several optional arguments
1177 that specify the behaviour of the Mock object:
1178
1179 * `spec`: This can be either a list of strings or an existing object (a
1180 class or instance) that acts as the specification for the mock object. If
1181 you pass in an object then a list of strings is formed by calling dir on
1182 the object (excluding unsupported magic attributes and methods). Accessing
1183 any attribute not in this list will raise an `AttributeError`.
1184
1185 If `spec` is an object (rather than a list of strings) then
1186 `mock.__class__` returns the class of the spec object. This allows mocks
1187 to pass `isinstance` tests.
1188
1189 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1190 or get an attribute on the mock that isn't on the object passed as
1191 `spec_set` will raise an `AttributeError`.
1192
1193 * `side_effect`: A function to be called whenever the Mock is called. See
1194 the `side_effect` attribute. Useful for raising exceptions or
1195 dynamically changing return values. The function is called with the same
1196 arguments as the mock, and unless it returns `DEFAULT`, the return
1197 value of this function is used as the return value.
1198
Michael Foord2cd48732012-04-21 15:52:11 +01001199 If `side_effect` is an iterable then each call to the mock will return
1200 the next value from the iterable. If any of the members of the iterable
1201 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001202
Michael Foord345266a2012-03-14 12:24:34 -07001203 * `return_value`: The value returned when the mock is called. By default
1204 this is a new Mock (created on first access). See the
1205 `return_value` attribute.
1206
Michael Foord0682a0c2012-04-13 20:51:20 +01001207 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1208 calling the Mock will pass the call through to the wrapped object
1209 (returning the real result). Attribute access on the mock will return a
1210 Mock object that wraps the corresponding attribute of the wrapped object
1211 (so attempting to access an attribute that doesn't exist will raise an
1212 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001213
1214 If the mock has an explicit `return_value` set then calls are not passed
1215 to the wrapped object and the `return_value` is returned instead.
1216
1217 * `name`: If the mock has a name then it will be used in the repr of the
1218 mock. This can be useful for debugging. The name is propagated to child
1219 mocks.
1220
1221 Mocks can also be called with arbitrary keyword arguments. These will be
1222 used to set attributes on the mock after it is created.
1223 """
1224
1225
Michael Foord345266a2012-03-14 12:24:34 -07001226def _dot_lookup(thing, comp, import_path):
1227 try:
1228 return getattr(thing, comp)
1229 except AttributeError:
1230 __import__(import_path)
1231 return getattr(thing, comp)
1232
1233
1234def _importer(target):
1235 components = target.split('.')
1236 import_path = components.pop(0)
1237 thing = __import__(import_path)
1238
1239 for comp in components:
1240 import_path += ".%s" % comp
1241 thing = _dot_lookup(thing, comp, import_path)
1242 return thing
1243
1244
vabr-gfdb9efc2020-12-14 19:30:09 +01001245# _check_spec_arg_typos takes kwargs from commands like patch and checks that
1246# they don't contain common misspellings of arguments related to autospeccing.
1247def _check_spec_arg_typos(kwargs_to_check):
1248 typos = ("autospect", "auto_spec", "set_spec")
1249 for typo in typos:
1250 if typo in kwargs_to_check:
1251 raise RuntimeError(
1252 f"{typo!r} might be a typo; use unsafe=True if this is intended"
1253 )
1254
1255
Michael Foord345266a2012-03-14 12:24:34 -07001256class _patch(object):
1257
1258 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001259 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001260
1261 def __init__(
1262 self, getter, attribute, new, spec, create,
vabr-gfdb9efc2020-12-14 19:30:09 +01001263 spec_set, autospec, new_callable, kwargs, *, unsafe=False
Michael Foord345266a2012-03-14 12:24:34 -07001264 ):
1265 if new_callable is not None:
1266 if new is not DEFAULT:
1267 raise ValueError(
1268 "Cannot use 'new' and 'new_callable' together"
1269 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001270 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001271 raise ValueError(
1272 "Cannot use 'autospec' and 'new_callable' together"
1273 )
vabr-gfdb9efc2020-12-14 19:30:09 +01001274 if not unsafe:
1275 _check_spec_arg_typos(kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001276
1277 self.getter = getter
1278 self.attribute = attribute
1279 self.new = new
1280 self.new_callable = new_callable
1281 self.spec = spec
1282 self.create = create
1283 self.has_local = False
1284 self.spec_set = spec_set
1285 self.autospec = autospec
1286 self.kwargs = kwargs
1287 self.additional_patchers = []
1288
1289
1290 def copy(self):
1291 patcher = _patch(
1292 self.getter, self.attribute, self.new, self.spec,
1293 self.create, self.spec_set,
1294 self.autospec, self.new_callable, self.kwargs
1295 )
1296 patcher.attribute_name = self.attribute_name
1297 patcher.additional_patchers = [
1298 p.copy() for p in self.additional_patchers
1299 ]
1300 return patcher
1301
1302
1303 def __call__(self, func):
1304 if isinstance(func, type):
1305 return self.decorate_class(func)
Xtreak436c2b02019-05-28 12:37:39 +05301306 if inspect.iscoroutinefunction(func):
1307 return self.decorate_async_callable(func)
Michael Foord345266a2012-03-14 12:24:34 -07001308 return self.decorate_callable(func)
1309
1310
1311 def decorate_class(self, klass):
1312 for attr in dir(klass):
1313 if not attr.startswith(patch.TEST_PREFIX):
1314 continue
1315
1316 attr_value = getattr(klass, attr)
1317 if not hasattr(attr_value, "__call__"):
1318 continue
1319
1320 patcher = self.copy()
1321 setattr(klass, attr, patcher(attr_value))
1322 return klass
1323
1324
Xtreak436c2b02019-05-28 12:37:39 +05301325 @contextlib.contextmanager
1326 def decoration_helper(self, patched, args, keywargs):
1327 extra_args = []
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001328 with contextlib.ExitStack() as exit_stack:
Xtreak436c2b02019-05-28 12:37:39 +05301329 for patching in patched.patchings:
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001330 arg = exit_stack.enter_context(patching)
Xtreak436c2b02019-05-28 12:37:39 +05301331 if patching.attribute_name is not None:
1332 keywargs.update(arg)
1333 elif patching.new is DEFAULT:
1334 extra_args.append(arg)
1335
1336 args += tuple(extra_args)
1337 yield (args, keywargs)
Xtreak436c2b02019-05-28 12:37:39 +05301338
1339
Michael Foord345266a2012-03-14 12:24:34 -07001340 def decorate_callable(self, func):
Xtreak436c2b02019-05-28 12:37:39 +05301341 # NB. Keep the method in sync with decorate_async_callable()
Michael Foord345266a2012-03-14 12:24:34 -07001342 if hasattr(func, 'patchings'):
1343 func.patchings.append(self)
1344 return func
1345
1346 @wraps(func)
1347 def patched(*args, **keywargs):
Xtreak436c2b02019-05-28 12:37:39 +05301348 with self.decoration_helper(patched,
1349 args,
1350 keywargs) as (newargs, newkeywargs):
1351 return func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001352
Xtreak436c2b02019-05-28 12:37:39 +05301353 patched.patchings = [self]
1354 return patched
Michael Foord345266a2012-03-14 12:24:34 -07001355
Xtreak436c2b02019-05-28 12:37:39 +05301356
1357 def decorate_async_callable(self, func):
1358 # NB. Keep the method in sync with decorate_callable()
1359 if hasattr(func, 'patchings'):
1360 func.patchings.append(self)
1361 return func
1362
1363 @wraps(func)
1364 async def patched(*args, **keywargs):
1365 with self.decoration_helper(patched,
1366 args,
1367 keywargs) as (newargs, newkeywargs):
1368 return await func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001369
1370 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001371 return patched
1372
1373
1374 def get_original(self):
1375 target = self.getter()
1376 name = self.attribute
1377
1378 original = DEFAULT
1379 local = False
1380
1381 try:
1382 original = target.__dict__[name]
1383 except (AttributeError, KeyError):
1384 original = getattr(target, name, DEFAULT)
1385 else:
1386 local = True
1387
Michael Foordfddcfa22014-04-14 16:25:20 -04001388 if name in _builtins and isinstance(target, ModuleType):
1389 self.create = True
1390
Michael Foord345266a2012-03-14 12:24:34 -07001391 if not self.create and original is DEFAULT:
1392 raise AttributeError(
1393 "%s does not have the attribute %r" % (target, name)
1394 )
1395 return original, local
1396
1397
1398 def __enter__(self):
1399 """Perform the patch."""
1400 new, spec, spec_set = self.new, self.spec, self.spec_set
1401 autospec, kwargs = self.autospec, self.kwargs
1402 new_callable = self.new_callable
1403 self.target = self.getter()
1404
Michael Foord50a8c0e2012-03-25 18:57:58 +01001405 # normalise False to None
1406 if spec is False:
1407 spec = None
1408 if spec_set is False:
1409 spec_set = None
1410 if autospec is False:
1411 autospec = None
1412
1413 if spec is not None and autospec is not None:
1414 raise TypeError("Can't specify spec and autospec")
1415 if ((spec is not None or autospec is not None) and
1416 spec_set not in (True, None)):
1417 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1418
Michael Foord345266a2012-03-14 12:24:34 -07001419 original, local = self.get_original()
1420
Michael Foord50a8c0e2012-03-25 18:57:58 +01001421 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001422 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001423 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001424 # set spec to the object we are replacing
1425 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001426 if spec_set is True:
1427 spec_set = original
1428 spec = None
1429 elif spec is not None:
1430 if spec_set is True:
1431 spec_set = spec
1432 spec = None
1433 elif spec_set is True:
1434 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001435
Michael Foord50a8c0e2012-03-25 18:57:58 +01001436 if spec is not None or spec_set is not None:
1437 if original is DEFAULT:
1438 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001439 if isinstance(original, type):
1440 # If we're patching out a class and there is a spec
1441 inherit = True
Lisa Roach77b3b772019-05-20 09:19:53 -07001442 if spec is None and _is_async_obj(original):
1443 Klass = AsyncMock
1444 else:
1445 Klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -07001446 _kwargs = {}
1447 if new_callable is not None:
1448 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001449 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001450 this_spec = spec
1451 if spec_set is not None:
1452 this_spec = spec_set
1453 if _is_list(this_spec):
1454 not_callable = '__call__' not in this_spec
1455 else:
1456 not_callable = not callable(this_spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07001457 if _is_async_obj(this_spec):
1458 Klass = AsyncMock
1459 elif not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001460 Klass = NonCallableMagicMock
1461
1462 if spec is not None:
1463 _kwargs['spec'] = spec
1464 if spec_set is not None:
1465 _kwargs['spec_set'] = spec_set
1466
1467 # add a name to mocks
1468 if (isinstance(Klass, type) and
1469 issubclass(Klass, NonCallableMock) and self.attribute):
1470 _kwargs['name'] = self.attribute
1471
1472 _kwargs.update(kwargs)
1473 new = Klass(**_kwargs)
1474
1475 if inherit and _is_instance_mock(new):
1476 # we can only tell if the instance should be callable if the
1477 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001478 this_spec = spec
1479 if spec_set is not None:
1480 this_spec = spec_set
1481 if (not _is_list(this_spec) and not
1482 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001483 Klass = NonCallableMagicMock
1484
1485 _kwargs.pop('name')
1486 new.return_value = Klass(_new_parent=new, _new_name='()',
1487 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001488 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001489 # spec is ignored, new *must* be default, spec_set is treated
1490 # as a boolean. Should we check spec is not None and that spec_set
1491 # is a bool?
1492 if new is not DEFAULT:
1493 raise TypeError(
1494 "autospec creates the mock for you. Can't specify "
1495 "autospec and new."
1496 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001497 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001498 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001499 spec_set = bool(spec_set)
1500 if autospec is True:
1501 autospec = original
1502
1503 new = create_autospec(autospec, spec_set=spec_set,
1504 _name=self.attribute, **kwargs)
1505 elif kwargs:
1506 # can't set keyword args when we aren't creating the mock
1507 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1508 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1509
1510 new_attr = new
1511
1512 self.temp_original = original
1513 self.is_local = local
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001514 self._exit_stack = contextlib.ExitStack()
1515 try:
1516 setattr(self.target, self.attribute, new_attr)
1517 if self.attribute_name is not None:
1518 extra_args = {}
1519 if self.new is DEFAULT:
1520 extra_args[self.attribute_name] = new
1521 for patching in self.additional_patchers:
1522 arg = self._exit_stack.enter_context(patching)
1523 if patching.new is DEFAULT:
1524 extra_args.update(arg)
1525 return extra_args
Michael Foord345266a2012-03-14 12:24:34 -07001526
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001527 return new
1528 except:
1529 if not self.__exit__(*sys.exc_info()):
1530 raise
Michael Foord345266a2012-03-14 12:24:34 -07001531
Michael Foord50a8c0e2012-03-25 18:57:58 +01001532 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001533 """Undo the patch."""
Michael Foord345266a2012-03-14 12:24:34 -07001534 if self.is_local and self.temp_original is not DEFAULT:
1535 setattr(self.target, self.attribute, self.temp_original)
1536 else:
1537 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001538 if not self.create and (not hasattr(self.target, self.attribute) or
1539 self.attribute in ('__doc__', '__module__',
1540 '__defaults__', '__annotations__',
1541 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001542 # needed for proxy objects like django settings
1543 setattr(self.target, self.attribute, self.temp_original)
1544
1545 del self.temp_original
1546 del self.is_local
1547 del self.target
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001548 exit_stack = self._exit_stack
1549 del self._exit_stack
1550 return exit_stack.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001551
Michael Foordf7c41582012-06-10 20:36:32 +01001552
1553 def start(self):
1554 """Activate a patch, returning any created mock."""
1555 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001556 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001557 return result
1558
1559
1560 def stop(self):
1561 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001562 try:
1563 self._active_patches.remove(self)
1564 except ValueError:
1565 # If the patch hasn't been started this will fail
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001566 return None
Michael Foordebc1a302014-04-15 17:21:08 -04001567
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001568 return self.__exit__(None, None, None)
Michael Foord345266a2012-03-14 12:24:34 -07001569
1570
1571
1572def _get_target(target):
1573 try:
1574 target, attribute = target.rsplit('.', 1)
1575 except (TypeError, ValueError):
1576 raise TypeError("Need a valid target to patch. You supplied: %r" %
1577 (target,))
1578 getter = lambda: _importer(target)
1579 return getter, attribute
1580
1581
1582def _patch_object(
1583 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001584 create=False, spec_set=None, autospec=None,
vabr-gfdb9efc2020-12-14 19:30:09 +01001585 new_callable=None, *, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001586 ):
1587 """
Michael Foord345266a2012-03-14 12:24:34 -07001588 patch the named member (`attribute`) on an object (`target`) with a mock
1589 object.
1590
1591 `patch.object` can be used as a decorator, class decorator or a context
1592 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1593 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1594 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1595 the mock object it creates.
1596
1597 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1598 for choosing which methods to wrap.
1599 """
Elena Oatcd90a522019-12-08 12:14:38 -08001600 if type(target) is str:
1601 raise TypeError(
1602 f"{target!r} must be the actual object to be patched, not a str"
1603 )
Michael Foord345266a2012-03-14 12:24:34 -07001604 getter = lambda: target
1605 return _patch(
1606 getter, attribute, new, spec, create,
vabr-gfdb9efc2020-12-14 19:30:09 +01001607 spec_set, autospec, new_callable, kwargs, unsafe=unsafe
Michael Foord345266a2012-03-14 12:24:34 -07001608 )
1609
1610
Michael Foord50a8c0e2012-03-25 18:57:58 +01001611def _patch_multiple(target, spec=None, create=False, spec_set=None,
1612 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001613 """Perform multiple patches in a single call. It takes the object to be
1614 patched (either as an object or a string to fetch the object by importing)
1615 and keyword arguments for the patches::
1616
1617 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1618 ...
1619
1620 Use `DEFAULT` as the value if you want `patch.multiple` to create
1621 mocks for you. In this case the created mocks are passed into a decorated
1622 function by keyword, and a dictionary is returned when `patch.multiple` is
1623 used as a context manager.
1624
1625 `patch.multiple` can be used as a decorator, class decorator or a context
1626 manager. The arguments `spec`, `spec_set`, `create`,
1627 `autospec` and `new_callable` have the same meaning as for `patch`. These
1628 arguments will be applied to *all* patches done by `patch.multiple`.
1629
1630 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1631 for choosing which methods to wrap.
1632 """
1633 if type(target) is str:
1634 getter = lambda: _importer(target)
1635 else:
1636 getter = lambda: target
1637
1638 if not kwargs:
1639 raise ValueError(
1640 'Must supply at least one keyword argument with patch.multiple'
1641 )
1642 # need to wrap in a list for python 3, where items is a view
1643 items = list(kwargs.items())
1644 attribute, new = items[0]
1645 patcher = _patch(
1646 getter, attribute, new, spec, create, spec_set,
1647 autospec, new_callable, {}
1648 )
1649 patcher.attribute_name = attribute
1650 for attribute, new in items[1:]:
1651 this_patcher = _patch(
1652 getter, attribute, new, spec, create, spec_set,
1653 autospec, new_callable, {}
1654 )
1655 this_patcher.attribute_name = attribute
1656 patcher.additional_patchers.append(this_patcher)
1657 return patcher
1658
1659
1660def patch(
1661 target, new=DEFAULT, spec=None, create=False,
vabr-gfdb9efc2020-12-14 19:30:09 +01001662 spec_set=None, autospec=None, new_callable=None, *, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001663 ):
1664 """
1665 `patch` acts as a function decorator, class decorator or a context
1666 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001667 is patched with a `new` object. When the function/with statement exits
1668 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001669
Mario Corcherof5e7f392019-09-09 15:18:06 +01001670 If `new` is omitted, then the target is replaced with an
1671 `AsyncMock if the patched object is an async function or a
1672 `MagicMock` otherwise. If `patch` is used as a decorator and `new` is
Michael Foord54b3db82012-03-28 15:08:08 +01001673 omitted, the created mock is passed in as an extra argument to the
1674 decorated function. If `patch` is used as a context manager the created
1675 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001676
Michael Foord54b3db82012-03-28 15:08:08 +01001677 `target` should be a string in the form `'package.module.ClassName'`. The
1678 `target` is imported and the specified object replaced with the `new`
1679 object, so the `target` must be importable from the environment you are
1680 calling `patch` from. The target is imported when the decorated function
1681 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001682
1683 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1684 if patch is creating one for you.
1685
1686 In addition you can pass `spec=True` or `spec_set=True`, which causes
1687 patch to pass in the object being mocked as the spec/spec_set object.
1688
1689 `new_callable` allows you to specify a different class, or callable object,
Mario Corcherof5e7f392019-09-09 15:18:06 +01001690 that will be called to create the `new` object. By default `AsyncMock` is
1691 used for async functions and `MagicMock` for the rest.
Michael Foord345266a2012-03-14 12:24:34 -07001692
1693 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001694 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001695 All attributes of the mock will also have the spec of the corresponding
1696 attribute of the object being replaced. Methods and functions being
1697 mocked will have their arguments checked and will raise a `TypeError` if
1698 they are called with the wrong signature. For mocks replacing a class,
1699 their return value (the 'instance') will have the same spec as the class.
1700
1701 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1702 arbitrary object as the spec instead of the one being replaced.
1703
1704 By default `patch` will fail to replace attributes that don't exist. If
1705 you pass in `create=True`, and the attribute doesn't exist, patch will
1706 create the attribute for you when the patched function is called, and
1707 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001708 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001709 default because it can be dangerous. With it switched on you can write
1710 passing tests against APIs that don't actually exist!
1711
1712 Patch can be used as a `TestCase` class decorator. It works by
1713 decorating each test method in the class. This reduces the boilerplate
1714 code when your test methods share a common patchings set. `patch` finds
1715 tests by looking for method names that start with `patch.TEST_PREFIX`.
1716 By default this is `test`, which matches the way `unittest` finds tests.
1717 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1718
1719 Patch can be used as a context manager, with the with statement. Here the
1720 patching applies to the indented block after the with statement. If you
1721 use "as" then the patched object will be bound to the name after the
1722 "as"; very useful if `patch` is creating a mock object for you.
1723
vabr-gfdb9efc2020-12-14 19:30:09 +01001724 Patch will raise a `RuntimeError` if passed some common misspellings of
1725 the arguments autospec and spec_set. Pass the argument `unsafe` with the
1726 value True to disable that check.
1727
Michael Foord345266a2012-03-14 12:24:34 -07001728 `patch` takes arbitrary keyword arguments. These will be passed to
Paulo Henrique Silva40c08092020-01-25 07:53:54 -03001729 `AsyncMock` if the patched object is asynchronous, to `MagicMock`
1730 otherwise or to `new_callable` if specified.
Michael Foord345266a2012-03-14 12:24:34 -07001731
1732 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1733 available for alternate use-cases.
1734 """
1735 getter, attribute = _get_target(target)
1736 return _patch(
1737 getter, attribute, new, spec, create,
vabr-gfdb9efc2020-12-14 19:30:09 +01001738 spec_set, autospec, new_callable, kwargs, unsafe=unsafe
Michael Foord345266a2012-03-14 12:24:34 -07001739 )
1740
1741
1742class _patch_dict(object):
1743 """
1744 Patch a dictionary, or dictionary like object, and restore the dictionary
1745 to its original state after the test.
1746
1747 `in_dict` can be a dictionary or a mapping like container. If it is a
1748 mapping then it must at least support getting, setting and deleting items
1749 plus iterating over keys.
1750
1751 `in_dict` can also be a string specifying the name of the dictionary, which
1752 will then be fetched by importing it.
1753
1754 `values` can be a dictionary of values to set in the dictionary. `values`
1755 can also be an iterable of `(key, value)` pairs.
1756
1757 If `clear` is True then the dictionary will be cleared before the new
1758 values are set.
1759
1760 `patch.dict` can also be called with arbitrary keyword arguments to set
1761 values in the dictionary::
1762
1763 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1764 ...
1765
1766 `patch.dict` can be used as a context manager, decorator or class
1767 decorator. When used as a class decorator `patch.dict` honours
1768 `patch.TEST_PREFIX` for choosing which methods to wrap.
1769 """
1770
1771 def __init__(self, in_dict, values=(), clear=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001772 self.in_dict = in_dict
1773 # support any argument supported by dict(...) constructor
1774 self.values = dict(values)
1775 self.values.update(kwargs)
1776 self.clear = clear
1777 self._original = None
1778
1779
1780 def __call__(self, f):
1781 if isinstance(f, type):
1782 return self.decorate_class(f)
1783 @wraps(f)
1784 def _inner(*args, **kw):
1785 self._patch_dict()
1786 try:
1787 return f(*args, **kw)
1788 finally:
1789 self._unpatch_dict()
1790
1791 return _inner
1792
1793
1794 def decorate_class(self, klass):
1795 for attr in dir(klass):
1796 attr_value = getattr(klass, attr)
1797 if (attr.startswith(patch.TEST_PREFIX) and
1798 hasattr(attr_value, "__call__")):
1799 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1800 decorated = decorator(attr_value)
1801 setattr(klass, attr, decorated)
1802 return klass
1803
1804
1805 def __enter__(self):
1806 """Patch the dict."""
1807 self._patch_dict()
Mario Corchero04530812019-05-28 13:53:31 +01001808 return self.in_dict
Michael Foord345266a2012-03-14 12:24:34 -07001809
1810
1811 def _patch_dict(self):
1812 values = self.values
Xtreaka875ea52019-02-25 00:24:49 +05301813 if isinstance(self.in_dict, str):
1814 self.in_dict = _importer(self.in_dict)
Michael Foord345266a2012-03-14 12:24:34 -07001815 in_dict = self.in_dict
1816 clear = self.clear
1817
1818 try:
1819 original = in_dict.copy()
1820 except AttributeError:
1821 # dict like object with no copy method
1822 # must support iteration over keys
1823 original = {}
1824 for key in in_dict:
1825 original[key] = in_dict[key]
1826 self._original = original
1827
1828 if clear:
1829 _clear_dict(in_dict)
1830
1831 try:
1832 in_dict.update(values)
1833 except AttributeError:
1834 # dict like object with no update method
1835 for key in values:
1836 in_dict[key] = values[key]
1837
1838
1839 def _unpatch_dict(self):
1840 in_dict = self.in_dict
1841 original = self._original
1842
1843 _clear_dict(in_dict)
1844
1845 try:
1846 in_dict.update(original)
1847 except AttributeError:
1848 for key in original:
1849 in_dict[key] = original[key]
1850
1851
1852 def __exit__(self, *args):
1853 """Unpatch the dict."""
Chris Withersdb5e86a2020-01-29 16:24:54 +00001854 if self._original is not None:
1855 self._unpatch_dict()
Michael Foord345266a2012-03-14 12:24:34 -07001856 return False
1857
Mario Corcheroe131c972020-01-24 08:38:33 +00001858
1859 def start(self):
1860 """Activate a patch, returning any created mock."""
1861 result = self.__enter__()
1862 _patch._active_patches.append(self)
1863 return result
1864
1865
1866 def stop(self):
1867 """Stop an active patch."""
1868 try:
1869 _patch._active_patches.remove(self)
1870 except ValueError:
1871 # If the patch hasn't been started this will fail
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001872 return None
Mario Corcheroe131c972020-01-24 08:38:33 +00001873
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001874 return self.__exit__(None, None, None)
Michael Foord345266a2012-03-14 12:24:34 -07001875
1876
1877def _clear_dict(in_dict):
1878 try:
1879 in_dict.clear()
1880 except AttributeError:
1881 keys = list(in_dict)
1882 for key in keys:
1883 del in_dict[key]
1884
1885
Michael Foordf7c41582012-06-10 20:36:32 +01001886def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001887 """Stop all active patches. LIFO to unroll nested patches."""
1888 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001889 patch.stop()
1890
1891
Michael Foord345266a2012-03-14 12:24:34 -07001892patch.object = _patch_object
1893patch.dict = _patch_dict
1894patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001895patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001896patch.TEST_PREFIX = 'test'
1897
1898magic_methods = (
1899 "lt le gt ge eq ne "
1900 "getitem setitem delitem "
1901 "len contains iter "
1902 "hash str sizeof "
1903 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001904 # we added divmod and rdivmod here instead of numerics
1905 # because there is no idivmod
1906 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001907 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001908 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001909 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001910 "fspath "
Lisa Roach9a7d9512019-09-28 18:42:44 -07001911 "aiter "
Michael Foord345266a2012-03-14 12:24:34 -07001912)
1913
Michael Foordd2623d72014-04-14 11:23:48 -04001914numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001915 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001916)
Michael Foord345266a2012-03-14 12:24:34 -07001917inplace = ' '.join('i%s' % n for n in numerics.split())
1918right = ' '.join('r%s' % n for n in numerics.split())
1919
1920# not including __prepare__, __instancecheck__, __subclasscheck__
1921# (as they are metaclass methods)
1922# __del__ is not supported at all as it causes problems if it exists
1923
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001924_non_defaults = {
1925 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1926 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1927 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1928 '__repr__', '__dir__', '__subclasses__', '__format__',
Lisa Roach8b03f942019-09-19 21:04:18 -07001929 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001930}
Michael Foord345266a2012-03-14 12:24:34 -07001931
1932
1933def _get_method(name, func):
1934 "Turns a callable object (like a mock) into a real function"
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001935 def method(self, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -07001936 return func(self, *args, **kw)
1937 method.__name__ = name
1938 return method
1939
1940
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001941_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001942 '__%s__' % method for method in
1943 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001944}
Michael Foord345266a2012-03-14 12:24:34 -07001945
Lisa Roach77b3b772019-05-20 09:19:53 -07001946# Magic methods used for async `with` statements
1947_async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
Lisa Roach8b03f942019-09-19 21:04:18 -07001948# Magic methods that are only used with async calls but are synchronous functions themselves
1949_sync_async_magics = {"__aiter__"}
1950_async_magics = _async_method_magics | _sync_async_magics
Lisa Roach77b3b772019-05-20 09:19:53 -07001951
Lisa Roach8b03f942019-09-19 21:04:18 -07001952_all_sync_magics = _magics | _non_defaults
1953_all_magics = _all_sync_magics | _async_magics
Michael Foord345266a2012-03-14 12:24:34 -07001954
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001955_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001956 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001957 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001958 '__instancecheck__', '__subclasscheck__',
1959 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001960}
Michael Foord345266a2012-03-14 12:24:34 -07001961
1962_calculate_return_value = {
1963 '__hash__': lambda self: object.__hash__(self),
1964 '__str__': lambda self: object.__str__(self),
1965 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001966 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001967}
1968
1969_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001970 '__lt__': NotImplemented,
1971 '__gt__': NotImplemented,
1972 '__le__': NotImplemented,
1973 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001974 '__int__': 1,
1975 '__contains__': False,
1976 '__len__': 0,
1977 '__exit__': False,
1978 '__complex__': 1j,
1979 '__float__': 1.0,
1980 '__bool__': True,
1981 '__index__': 1,
Lisa Roach77b3b772019-05-20 09:19:53 -07001982 '__aexit__': False,
Michael Foord345266a2012-03-14 12:24:34 -07001983}
1984
1985
1986def _get_eq(self):
1987 def __eq__(other):
1988 ret_val = self.__eq__._mock_return_value
1989 if ret_val is not DEFAULT:
1990 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001991 if self is other:
1992 return True
1993 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001994 return __eq__
1995
1996def _get_ne(self):
1997 def __ne__(other):
1998 if self.__ne__._mock_return_value is not DEFAULT:
1999 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02002000 if self is other:
2001 return False
2002 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07002003 return __ne__
2004
2005def _get_iter(self):
2006 def __iter__():
2007 ret_val = self.__iter__._mock_return_value
2008 if ret_val is DEFAULT:
2009 return iter([])
2010 # if ret_val was already an iterator, then calling iter on it should
2011 # return the iterator unchanged
2012 return iter(ret_val)
2013 return __iter__
2014
Lisa Roach77b3b772019-05-20 09:19:53 -07002015def _get_async_iter(self):
2016 def __aiter__():
2017 ret_val = self.__aiter__._mock_return_value
2018 if ret_val is DEFAULT:
2019 return _AsyncIterator(iter([]))
2020 return _AsyncIterator(iter(ret_val))
2021 return __aiter__
2022
Michael Foord345266a2012-03-14 12:24:34 -07002023_side_effect_methods = {
2024 '__eq__': _get_eq,
2025 '__ne__': _get_ne,
2026 '__iter__': _get_iter,
Lisa Roach77b3b772019-05-20 09:19:53 -07002027 '__aiter__': _get_async_iter
Michael Foord345266a2012-03-14 12:24:34 -07002028}
2029
2030
2031
2032def _set_return_value(mock, method, name):
2033 fixed = _return_values.get(name, DEFAULT)
2034 if fixed is not DEFAULT:
2035 method.return_value = fixed
2036 return
2037
marcoramirezmxa9187c32019-09-16 11:34:46 -05002038 return_calculator = _calculate_return_value.get(name)
2039 if return_calculator is not None:
2040 return_value = return_calculator(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002041 method.return_value = return_value
2042 return
2043
2044 side_effector = _side_effect_methods.get(name)
2045 if side_effector is not None:
2046 method.side_effect = side_effector(mock)
2047
2048
2049
Lisa Roach9a7d9512019-09-28 18:42:44 -07002050class MagicMixin(Base):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002051 def __init__(self, /, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07002052 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10002053 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07002054 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002055
2056
2057 def _mock_set_magics(self):
Lisa Roach9a7d9512019-09-28 18:42:44 -07002058 orig_magics = _magics | _async_method_magics
2059 these_magics = orig_magics
Michael Foord345266a2012-03-14 12:24:34 -07002060
Łukasz Langaa468db92015-04-13 23:12:42 -07002061 if getattr(self, "_mock_methods", None) is not None:
Lisa Roach9a7d9512019-09-28 18:42:44 -07002062 these_magics = orig_magics.intersection(self._mock_methods)
Michael Foord345266a2012-03-14 12:24:34 -07002063
2064 remove_magics = set()
Lisa Roach9a7d9512019-09-28 18:42:44 -07002065 remove_magics = orig_magics - these_magics
Michael Foord345266a2012-03-14 12:24:34 -07002066
2067 for entry in remove_magics:
2068 if entry in type(self).__dict__:
2069 # remove unneeded magic methods
2070 delattr(self, entry)
2071
2072 # don't overwrite existing attributes if called a second time
2073 these_magics = these_magics - set(type(self).__dict__)
2074
2075 _type = type(self)
2076 for entry in these_magics:
2077 setattr(_type, entry, MagicProxy(entry, self))
2078
2079
2080
2081class NonCallableMagicMock(MagicMixin, NonCallableMock):
2082 """A version of `MagicMock` that isn't callable."""
2083 def mock_add_spec(self, spec, spec_set=False):
2084 """Add a spec to a mock. `spec` can either be an object or a
2085 list of strings. Only attributes on the `spec` can be fetched as
2086 attributes from the mock.
2087
2088 If `spec_set` is True then only attributes on the spec can be set."""
2089 self._mock_add_spec(spec, spec_set)
2090 self._mock_set_magics()
2091
2092
Lisa Roach9a7d9512019-09-28 18:42:44 -07002093class AsyncMagicMixin(MagicMixin):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002094 def __init__(self, /, *args, **kw):
Lisa Roach9a7d9512019-09-28 18:42:44 -07002095 self._mock_set_magics() # make magic work for kwargs in init
Lisa Roach77b3b772019-05-20 09:19:53 -07002096 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)
Lisa Roach9a7d9512019-09-28 18:42:44 -07002097 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002098
Lisa Roach9a7d9512019-09-28 18:42:44 -07002099class MagicMock(MagicMixin, Mock):
Michael Foord345266a2012-03-14 12:24:34 -07002100 """
2101 MagicMock is a subclass of Mock with default implementations
2102 of most of the magic methods. You can use MagicMock without having to
2103 configure the magic methods yourself.
2104
2105 If you use the `spec` or `spec_set` arguments then *only* magic
2106 methods that exist in the spec will be created.
2107
2108 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
2109 """
2110 def mock_add_spec(self, spec, spec_set=False):
2111 """Add a spec to a mock. `spec` can either be an object or a
2112 list of strings. Only attributes on the `spec` can be fetched as
2113 attributes from the mock.
2114
2115 If `spec_set` is True then only attributes on the spec can be set."""
2116 self._mock_add_spec(spec, spec_set)
2117 self._mock_set_magics()
2118
2119
2120
Lisa Roach9a7d9512019-09-28 18:42:44 -07002121class MagicProxy(Base):
Michael Foord345266a2012-03-14 12:24:34 -07002122 def __init__(self, name, parent):
2123 self.name = name
2124 self.parent = parent
2125
Michael Foord345266a2012-03-14 12:24:34 -07002126 def create_mock(self):
2127 entry = self.name
2128 parent = self.parent
2129 m = parent._get_child_mock(name=entry, _new_name=entry,
2130 _new_parent=parent)
2131 setattr(parent, entry, m)
2132 _set_return_value(parent, m, entry)
2133 return m
2134
2135 def __get__(self, obj, _type=None):
2136 return self.create_mock()
2137
2138
Lisa Roach77b3b772019-05-20 09:19:53 -07002139class AsyncMockMixin(Base):
Lisa Roach77b3b772019-05-20 09:19:53 -07002140 await_count = _delegating_property('await_count')
2141 await_args = _delegating_property('await_args')
2142 await_args_list = _delegating_property('await_args_list')
2143
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002144 def __init__(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002145 super().__init__(*args, **kwargs)
Chris Withersc7dd3c72020-01-27 14:11:19 +00002146 # iscoroutinefunction() checks _is_coroutine property to say if an
Lisa Roach77b3b772019-05-20 09:19:53 -07002147 # object is a coroutine. Without this check it looks to see if it is a
2148 # function/method, which in this case it is not (since it is an
2149 # AsyncMock).
2150 # It is set through __dict__ because when spec_set is True, this
2151 # attribute is likely undefined.
2152 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
Lisa Roach77b3b772019-05-20 09:19:53 -07002153 self.__dict__['_mock_await_count'] = 0
2154 self.__dict__['_mock_await_args'] = None
2155 self.__dict__['_mock_await_args_list'] = _CallList()
2156 code_mock = NonCallableMock(spec_set=CodeType)
2157 code_mock.co_flags = inspect.CO_COROUTINE
2158 self.__dict__['__code__'] = code_mock
2159
Jason Fried046442d2019-11-20 16:27:51 -08002160 async def _execute_mock_call(self, /, *args, **kwargs):
Chris Withersdb5e86a2020-01-29 16:24:54 +00002161 # This is nearly just like super(), except for special handling
Jason Fried046442d2019-11-20 16:27:51 -08002162 # of coroutines
Lisa Roach77b3b772019-05-20 09:19:53 -07002163
Karthikeyan Singaravelane553f202020-03-11 20:36:12 +05302164 _call = _Call((args, kwargs), two=True)
Jason Fried046442d2019-11-20 16:27:51 -08002165 self.await_count += 1
2166 self.await_args = _call
2167 self.await_args_list.append(_call)
Lisa Roach77b3b772019-05-20 09:19:53 -07002168
Jason Fried046442d2019-11-20 16:27:51 -08002169 effect = self.side_effect
2170 if effect is not None:
2171 if _is_exception(effect):
2172 raise effect
2173 elif not _callable(effect):
2174 try:
2175 result = next(effect)
2176 except StopIteration:
2177 # It is impossible to propogate a StopIteration
2178 # through coroutines because of PEP 479
2179 raise StopAsyncIteration
2180 if _is_exception(result):
2181 raise result
Chris Withersc7dd3c72020-01-27 14:11:19 +00002182 elif iscoroutinefunction(effect):
Jason Fried046442d2019-11-20 16:27:51 -08002183 result = await effect(*args, **kwargs)
2184 else:
2185 result = effect(*args, **kwargs)
Lisa Roach77b3b772019-05-20 09:19:53 -07002186
Jason Fried046442d2019-11-20 16:27:51 -08002187 if result is not DEFAULT:
2188 return result
2189
2190 if self._mock_return_value is not DEFAULT:
2191 return self.return_value
2192
2193 if self._mock_wraps is not None:
Chris Withersc7dd3c72020-01-27 14:11:19 +00002194 if iscoroutinefunction(self._mock_wraps):
Jason Fried046442d2019-11-20 16:27:51 -08002195 return await self._mock_wraps(*args, **kwargs)
2196 return self._mock_wraps(*args, **kwargs)
2197
2198 return self.return_value
Lisa Roach77b3b772019-05-20 09:19:53 -07002199
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002200 def assert_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002201 """
2202 Assert that the mock was awaited at least once.
2203 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002204 if self.await_count == 0:
2205 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2206 raise AssertionError(msg)
2207
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002208 def assert_awaited_once(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002209 """
2210 Assert that the mock was awaited exactly once.
2211 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002212 if not self.await_count == 1:
2213 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2214 f" Awaited {self.await_count} times.")
2215 raise AssertionError(msg)
2216
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002217 def assert_awaited_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002218 """
2219 Assert that the last await was with the specified arguments.
2220 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002221 if self.await_args is None:
2222 expected = self._format_mock_call_signature(args, kwargs)
2223 raise AssertionError(f'Expected await: {expected}\nNot awaited')
2224
2225 def _error_message():
Xtreak0ae022c2019-05-29 12:32:26 +05302226 msg = self._format_mock_failure_message(args, kwargs, action='await')
Lisa Roach77b3b772019-05-20 09:19:53 -07002227 return msg
2228
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002229 expected = self._call_matcher(_Call((args, kwargs), two=True))
Lisa Roach77b3b772019-05-20 09:19:53 -07002230 actual = self._call_matcher(self.await_args)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002231 if actual != expected:
Lisa Roach77b3b772019-05-20 09:19:53 -07002232 cause = expected if isinstance(expected, Exception) else None
2233 raise AssertionError(_error_message()) from cause
2234
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002235 def assert_awaited_once_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002236 """
2237 Assert that the mock was awaited exactly once and with the specified
2238 arguments.
2239 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002240 if not self.await_count == 1:
2241 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2242 f" Awaited {self.await_count} times.")
2243 raise AssertionError(msg)
2244 return self.assert_awaited_with(*args, **kwargs)
2245
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002246 def assert_any_await(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002247 """
2248 Assert the mock has ever been awaited with the specified arguments.
2249 """
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002250 expected = self._call_matcher(_Call((args, kwargs), two=True))
2251 cause = expected if isinstance(expected, Exception) else None
Lisa Roach77b3b772019-05-20 09:19:53 -07002252 actual = [self._call_matcher(c) for c in self.await_args_list]
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002253 if cause or expected not in _AnyComparer(actual):
Lisa Roach77b3b772019-05-20 09:19:53 -07002254 expected_string = self._format_mock_call_signature(args, kwargs)
2255 raise AssertionError(
2256 '%s await not found' % expected_string
2257 ) from cause
2258
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002259 def assert_has_awaits(self, calls, any_order=False):
Lisa Roach77b3b772019-05-20 09:19:53 -07002260 """
2261 Assert the mock has been awaited with the specified calls.
2262 The :attr:`await_args_list` list is checked for the awaits.
2263
2264 If `any_order` is False (the default) then the awaits must be
2265 sequential. There can be extra calls before or after the
2266 specified awaits.
2267
2268 If `any_order` is True then the awaits can be in any order, but
2269 they must all appear in :attr:`await_args_list`.
2270 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002271 expected = [self._call_matcher(c) for c in calls]
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002272 cause = next((e for e in expected if isinstance(e, Exception)), None)
Lisa Roach77b3b772019-05-20 09:19:53 -07002273 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2274 if not any_order:
2275 if expected not in all_awaits:
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002276 if cause is None:
2277 problem = 'Awaits not found.'
2278 else:
2279 problem = ('Error processing expected awaits.\n'
2280 'Errors: {}').format(
2281 [e if isinstance(e, Exception) else None
2282 for e in expected])
Lisa Roach77b3b772019-05-20 09:19:53 -07002283 raise AssertionError(
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002284 f'{problem}\n'
2285 f'Expected: {_CallList(calls)}\n'
Lisa Roach77b3b772019-05-20 09:19:53 -07002286 f'Actual: {self.await_args_list}'
2287 ) from cause
2288 return
2289
2290 all_awaits = list(all_awaits)
2291
2292 not_found = []
2293 for kall in expected:
2294 try:
2295 all_awaits.remove(kall)
2296 except ValueError:
2297 not_found.append(kall)
2298 if not_found:
2299 raise AssertionError(
2300 '%r not all found in await list' % (tuple(not_found),)
2301 ) from cause
2302
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002303 def assert_not_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002304 """
2305 Assert that the mock was never awaited.
2306 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002307 if self.await_count != 0:
Xtreakff6b2e62019-05-27 18:26:23 +05302308 msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
Lisa Roach77b3b772019-05-20 09:19:53 -07002309 f" Awaited {self.await_count} times.")
2310 raise AssertionError(msg)
2311
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002312 def reset_mock(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002313 """
2314 See :func:`.Mock.reset_mock()`
2315 """
2316 super().reset_mock(*args, **kwargs)
2317 self.await_count = 0
2318 self.await_args = None
2319 self.await_args_list = _CallList()
2320
2321
2322class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2323 """
2324 Enhance :class:`Mock` with features allowing to mock
2325 an async function.
2326
2327 The :class:`AsyncMock` object will behave so the object is
2328 recognized as an async function, and the result of a call is an awaitable:
2329
2330 >>> mock = AsyncMock()
Chris Withersc7dd3c72020-01-27 14:11:19 +00002331 >>> iscoroutinefunction(mock)
Lisa Roach77b3b772019-05-20 09:19:53 -07002332 True
2333 >>> inspect.isawaitable(mock())
2334 True
2335
2336
2337 The result of ``mock()`` is an async function which will have the outcome
2338 of ``side_effect`` or ``return_value``:
2339
2340 - if ``side_effect`` is a function, the async function will return the
2341 result of that function,
2342 - if ``side_effect`` is an exception, the async function will raise the
2343 exception,
2344 - if ``side_effect`` is an iterable, the async function will return the
2345 next value of the iterable, however, if the sequence of result is
2346 exhausted, ``StopIteration`` is raised immediately,
2347 - if ``side_effect`` is not defined, the async function will return the
2348 value defined by ``return_value``, hence, by default, the async function
2349 returns a new :class:`AsyncMock` object.
2350
2351 If the outcome of ``side_effect`` or ``return_value`` is an async function,
2352 the mock async function obtained when the mock object is called will be this
2353 async function itself (and not an async function returning an async
2354 function).
2355
2356 The test author can also specify a wrapped object with ``wraps``. In this
2357 case, the :class:`Mock` object behavior is the same as with an
2358 :class:`.Mock` object: the wrapped object may have methods
2359 defined as async function functions.
2360
Xtreake7cb23b2019-05-21 14:17:17 +05302361 Based on Martin Richard's asynctest project.
Lisa Roach77b3b772019-05-20 09:19:53 -07002362 """
2363
Michael Foord345266a2012-03-14 12:24:34 -07002364
2365class _ANY(object):
2366 "A helper object that compares equal to everything."
2367
2368 def __eq__(self, other):
2369 return True
2370
2371 def __ne__(self, other):
2372 return False
2373
2374 def __repr__(self):
2375 return '<ANY>'
2376
2377ANY = _ANY()
2378
2379
2380
2381def _format_call_signature(name, args, kwargs):
2382 message = '%s(%%s)' % name
2383 formatted_args = ''
2384 args_string = ', '.join([repr(arg) for arg in args])
2385 kwargs_string = ', '.join([
Xtreak9d607062019-09-09 16:25:22 +05302386 '%s=%r' % (key, value) for key, value in kwargs.items()
Michael Foord345266a2012-03-14 12:24:34 -07002387 ])
2388 if args_string:
2389 formatted_args = args_string
2390 if kwargs_string:
2391 if formatted_args:
2392 formatted_args += ', '
2393 formatted_args += kwargs_string
2394
2395 return message % formatted_args
2396
2397
2398
2399class _Call(tuple):
2400 """
2401 A tuple for holding the results of a call to a mock, either in the form
2402 `(args, kwargs)` or `(name, args, kwargs)`.
2403
2404 If args or kwargs are empty then a call tuple will compare equal to
2405 a tuple without those values. This makes comparisons less verbose::
2406
2407 _Call(('name', (), {})) == ('name',)
2408 _Call(('name', (1,), {})) == ('name', (1,))
2409 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2410
2411 The `_Call` object provides a useful shortcut for comparing with call::
2412
2413 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2414 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2415
2416 If the _Call has no name then it will match any name.
2417 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002418 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002419 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002420 args = ()
2421 kwargs = {}
2422 _len = len(value)
2423 if _len == 3:
2424 name, args, kwargs = value
2425 elif _len == 2:
2426 first, second = value
2427 if isinstance(first, str):
2428 name = first
2429 if isinstance(second, tuple):
2430 args = second
2431 else:
2432 kwargs = second
2433 else:
2434 args, kwargs = first, second
2435 elif _len == 1:
2436 value, = value
2437 if isinstance(value, str):
2438 name = value
2439 elif isinstance(value, tuple):
2440 args = value
2441 else:
2442 kwargs = value
2443
2444 if two:
2445 return tuple.__new__(cls, (args, kwargs))
2446
2447 return tuple.__new__(cls, (name, args, kwargs))
2448
2449
2450 def __init__(self, value=(), name=None, parent=None, two=False,
2451 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002452 self._mock_name = name
2453 self._mock_parent = parent
2454 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002455
2456
2457 def __eq__(self, other):
Michael Foord345266a2012-03-14 12:24:34 -07002458 try:
2459 len_other = len(other)
2460 except TypeError:
Serhiy Storchaka662db122019-08-08 08:42:54 +03002461 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07002462
2463 self_name = ''
2464 if len(self) == 2:
2465 self_args, self_kwargs = self
2466 else:
2467 self_name, self_args, self_kwargs = self
2468
Andrew Dunaie63e6172018-12-04 11:08:45 +02002469 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2470 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002471 return False
2472
Michael Foord345266a2012-03-14 12:24:34 -07002473 other_name = ''
2474 if len_other == 0:
2475 other_args, other_kwargs = (), {}
2476 elif len_other == 3:
2477 other_name, other_args, other_kwargs = other
2478 elif len_other == 1:
2479 value, = other
2480 if isinstance(value, tuple):
2481 other_args = value
2482 other_kwargs = {}
2483 elif isinstance(value, str):
2484 other_name = value
2485 other_args, other_kwargs = (), {}
2486 else:
2487 other_args = ()
2488 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002489 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002490 # could be (name, args) or (name, kwargs) or (args, kwargs)
2491 first, second = other
2492 if isinstance(first, str):
2493 other_name = first
2494 if isinstance(second, tuple):
2495 other_args, other_kwargs = second, {}
2496 else:
2497 other_args, other_kwargs = (), second
2498 else:
2499 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002500 else:
2501 return False
Michael Foord345266a2012-03-14 12:24:34 -07002502
2503 if self_name and other_name != self_name:
2504 return False
2505
2506 # this order is important for ANY to work!
2507 return (other_args, other_kwargs) == (self_args, self_kwargs)
2508
2509
Berker Peksagce913872016-03-28 00:30:02 +03002510 __ne__ = object.__ne__
2511
2512
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002513 def __call__(self, /, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002514 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002515 return _Call(('', args, kwargs), name='()')
2516
Andrew Dunaie63e6172018-12-04 11:08:45 +02002517 name = self._mock_name + '()'
2518 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002519
2520
2521 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002522 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002523 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002524 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002525 return _Call(name=name, parent=self, from_kall=False)
2526
2527
blhsing72c35992019-09-11 07:28:06 -07002528 def __getattribute__(self, attr):
2529 if attr in tuple.__dict__:
2530 raise AttributeError
2531 return tuple.__getattribute__(self, attr)
2532
2533
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302534 def _get_call_arguments(self):
2535 if len(self) == 2:
2536 args, kwargs = self
2537 else:
2538 name, args, kwargs = self
2539
2540 return args, kwargs
2541
2542 @property
2543 def args(self):
2544 return self._get_call_arguments()[0]
2545
2546 @property
2547 def kwargs(self):
2548 return self._get_call_arguments()[1]
2549
Michael Foord345266a2012-03-14 12:24:34 -07002550 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002551 if not self._mock_from_kall:
2552 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002553 if name.startswith('()'):
2554 name = 'call%s' % name
2555 return name
2556
2557 if len(self) == 2:
2558 name = 'call'
2559 args, kwargs = self
2560 else:
2561 name, args, kwargs = self
2562 if not name:
2563 name = 'call'
2564 elif not name.startswith('()'):
2565 name = 'call.%s' % name
2566 else:
2567 name = 'call%s' % name
2568 return _format_call_signature(name, args, kwargs)
2569
2570
2571 def call_list(self):
2572 """For a call object that represents multiple calls, `call_list`
2573 returns a list of all the intermediate calls as well as the
2574 final call."""
2575 vals = []
2576 thing = self
2577 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002578 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002579 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002580 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002581 return _CallList(reversed(vals))
2582
2583
2584call = _Call(from_kall=False)
2585
2586
Michael Foord345266a2012-03-14 12:24:34 -07002587def create_autospec(spec, spec_set=False, instance=False, _parent=None,
vabr-gfdb9efc2020-12-14 19:30:09 +01002588 _name=None, *, unsafe=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07002589 """Create a mock object using another object as a spec. Attributes on the
2590 mock will use the corresponding attribute on the `spec` object as their
2591 spec.
2592
2593 Functions or methods being mocked will have their arguments checked
2594 to check that they are called with the correct signature.
2595
2596 If `spec_set` is True then attempting to set attributes that don't exist
2597 on the spec object will raise an `AttributeError`.
2598
2599 If a class is used as a spec then the return value of the mock (the
2600 instance of the class) will have the same spec. You can use a class as the
2601 spec for an instance object by passing `instance=True`. The returned mock
2602 will only be callable if instances of the mock are callable.
2603
vabr-gfdb9efc2020-12-14 19:30:09 +01002604 `create_autospec` will raise a `RuntimeError` if passed some common
2605 misspellings of the arguments autospec and spec_set. Pass the argument
2606 `unsafe` with the value True to disable that check.
2607
Michael Foord345266a2012-03-14 12:24:34 -07002608 `create_autospec` also takes arbitrary keyword arguments that are passed to
2609 the constructor of the created mock."""
2610 if _is_list(spec):
2611 # can't pass a list instance to the mock constructor as it will be
2612 # interpreted as a list of strings
2613 spec = type(spec)
2614
2615 is_type = isinstance(spec, type)
Xtreakff6b2e62019-05-27 18:26:23 +05302616 is_async_func = _is_async_func(spec)
Michael Foord345266a2012-03-14 12:24:34 -07002617 _kwargs = {'spec': spec}
2618 if spec_set:
2619 _kwargs = {'spec_set': spec}
2620 elif spec is None:
2621 # None we mock with a normal mock without a spec
2622 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002623 if _kwargs and instance:
2624 _kwargs['_spec_as_instance'] = True
vabr-gfdb9efc2020-12-14 19:30:09 +01002625 if not unsafe:
2626 _check_spec_arg_typos(kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07002627
2628 _kwargs.update(kwargs)
2629
2630 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002631 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002632 # descriptors don't have a spec
2633 # because we don't know what type they return
2634 _kwargs = {}
Lisa Roach77b3b772019-05-20 09:19:53 -07002635 elif is_async_func:
2636 if instance:
2637 raise RuntimeError("Instance can not be True when create_autospec "
2638 "is mocking an async function")
2639 Klass = AsyncMock
Michael Foord345266a2012-03-14 12:24:34 -07002640 elif not _callable(spec):
2641 Klass = NonCallableMagicMock
2642 elif is_type and instance and not _instance_callable(spec):
2643 Klass = NonCallableMagicMock
2644
Kushal Das484f8a82014-04-16 01:05:50 +05302645 _name = _kwargs.pop('name', _name)
2646
Michael Foord345266a2012-03-14 12:24:34 -07002647 _new_name = _name
2648 if _parent is None:
2649 # for a top level object no _new_name should be set
2650 _new_name = ''
2651
2652 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2653 name=_name, **_kwargs)
2654
2655 if isinstance(spec, FunctionTypes):
2656 # should only happen at the top level because we don't
2657 # recurse for functions
2658 mock = _set_signature(mock, spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07002659 if is_async_func:
Xtreakff6b2e62019-05-27 18:26:23 +05302660 _setup_async_mock(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002661 else:
2662 _check_signature(spec, mock, is_type, instance)
2663
2664 if _parent is not None and not instance:
2665 _parent._mock_children[_name] = mock
2666
2667 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002668 mock.return_value = create_autospec(spec, spec_set, instance=True,
2669 _name='()', _parent=mock)
2670
2671 for entry in dir(spec):
2672 if _is_magic(entry):
2673 # MagicMock already does the useful magic methods for us
2674 continue
2675
Michael Foord345266a2012-03-14 12:24:34 -07002676 # XXXX do we need a better way of getting attributes without
2677 # triggering code execution (?) Probably not - we need the actual
2678 # object to mock it so we would rather trigger a property than mock
2679 # the property descriptor. Likewise we want to mock out dynamically
2680 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002681 # XXXX what about attributes that raise exceptions other than
2682 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002683 # we could be resilient against it, or catch and propagate the
2684 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002685 try:
2686 original = getattr(spec, entry)
2687 except AttributeError:
2688 continue
Michael Foord345266a2012-03-14 12:24:34 -07002689
2690 kwargs = {'spec': original}
2691 if spec_set:
2692 kwargs = {'spec_set': original}
2693
2694 if not isinstance(original, FunctionTypes):
2695 new = _SpecState(original, spec_set, mock, entry, instance)
2696 mock._mock_children[entry] = new
2697 else:
2698 parent = mock
2699 if isinstance(spec, FunctionTypes):
2700 parent = mock.mock
2701
Michael Foord345266a2012-03-14 12:24:34 -07002702 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002703 kwargs['_eat_self'] = skipfirst
Chris Withersc7dd3c72020-01-27 14:11:19 +00002704 if iscoroutinefunction(original):
Lisa Roach77b3b772019-05-20 09:19:53 -07002705 child_klass = AsyncMock
2706 else:
2707 child_klass = MagicMock
2708 new = child_klass(parent=parent, name=entry, _new_name=entry,
2709 _new_parent=parent,
2710 **kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002711 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002712 _check_signature(original, new, skipfirst=skipfirst)
2713
2714 # so functions created with _set_signature become instance attributes,
2715 # *plus* their underlying mock exists in _mock_children of the parent
2716 # mock. Adding to _mock_children may be unnecessary where we are also
2717 # setting as an instance attribute?
2718 if isinstance(new, FunctionTypes):
2719 setattr(mock, entry, new)
2720
2721 return mock
2722
2723
2724def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002725 """
2726 Return whether we should skip the first argument on spec's `entry`
2727 attribute.
2728 """
Michael Foord345266a2012-03-14 12:24:34 -07002729 if not isinstance(spec, type):
2730 if entry in getattr(spec, '__dict__', {}):
2731 # instance attribute - shouldn't skip
2732 return False
Michael Foord345266a2012-03-14 12:24:34 -07002733 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002734
2735 for klass in spec.__mro__:
2736 result = klass.__dict__.get(entry, DEFAULT)
2737 if result is DEFAULT:
2738 continue
2739 if isinstance(result, (staticmethod, classmethod)):
2740 return False
Carl Friedrich Bolz-Tereicka3276772020-01-29 16:43:37 +01002741 elif isinstance(result, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002742 # Normal method => skip if looked up on type
2743 # (if looked up on instance, self is already skipped)
2744 return is_type
2745 else:
2746 return False
Michael Foord345266a2012-03-14 12:24:34 -07002747
Chris Withersadbf1782019-05-01 23:04:04 +01002748 # function is a dynamically provided attribute
Michael Foord345266a2012-03-14 12:24:34 -07002749 return is_type
2750
2751
Michael Foord345266a2012-03-14 12:24:34 -07002752class _SpecState(object):
2753
2754 def __init__(self, spec, spec_set=False, parent=None,
2755 name=None, ids=None, instance=False):
2756 self.spec = spec
2757 self.ids = ids
2758 self.spec_set = spec_set
2759 self.parent = parent
2760 self.instance = instance
2761 self.name = name
2762
2763
2764FunctionTypes = (
2765 # python function
2766 type(create_autospec),
2767 # instance method
2768 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002769)
2770
Michael Foord345266a2012-03-14 12:24:34 -07002771
Michael Foorda74561a2012-03-25 19:03:13 +01002772file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002773
Michael Foord04cbe0c2013-03-19 17:22:51 -07002774
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002775def _to_stream(read_data):
2776 if isinstance(read_data, bytes):
2777 return io.BytesIO(read_data)
Michael Foord04cbe0c2013-03-19 17:22:51 -07002778 else:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002779 return io.StringIO(read_data)
Michael Foord0dccf652012-03-25 19:11:50 +01002780
Robert Collins5329aaa2015-07-17 20:08:45 +12002781
Michael Foord0dccf652012-03-25 19:11:50 +01002782def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002783 """
2784 A helper function to create a mock to replace the use of `open`. It works
2785 for `open` called directly or used as a context manager.
2786
2787 The `mock` argument is the mock object to configure. If `None` (the
2788 default) then a `MagicMock` will be created for you, with the API limited
2789 to methods or attributes available on standard file handles.
2790
Xtreak71f82a22018-12-20 21:30:21 +05302791 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002792 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002793 """
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002794 _read_data = _to_stream(read_data)
2795 _state = [_read_data, None]
2796
Robert Collinsca647ef2015-07-24 03:48:20 +12002797 def _readlines_side_effect(*args, **kwargs):
2798 if handle.readlines.return_value is not None:
2799 return handle.readlines.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002800 return _state[0].readlines(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002801
2802 def _read_side_effect(*args, **kwargs):
2803 if handle.read.return_value is not None:
2804 return handle.read.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002805 return _state[0].read(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002806
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002807 def _readline_side_effect(*args, **kwargs):
Tony Flury20870232018-09-12 23:21:16 +01002808 yield from _iter_side_effect()
2809 while True:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002810 yield _state[0].readline(*args, **kwargs)
Tony Flury20870232018-09-12 23:21:16 +01002811
2812 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002813 if handle.readline.return_value is not None:
2814 while True:
2815 yield handle.readline.return_value
2816 for line in _state[0]:
2817 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002818
Damien Nadé394119a2019-05-23 12:03:25 +02002819 def _next_side_effect():
2820 if handle.readline.return_value is not None:
2821 return handle.readline.return_value
2822 return next(_state[0])
2823
Michael Foorda74561a2012-03-25 19:03:13 +01002824 global file_spec
2825 if file_spec is None:
2826 import _io
2827 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2828
Michael Foord345266a2012-03-14 12:24:34 -07002829 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002830 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002831
Robert Collinsca647ef2015-07-24 03:48:20 +12002832 handle = MagicMock(spec=file_spec)
2833 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002834
Robert Collinsca647ef2015-07-24 03:48:20 +12002835 handle.write.return_value = None
2836 handle.read.return_value = None
2837 handle.readline.return_value = None
2838 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002839
Robert Collinsca647ef2015-07-24 03:48:20 +12002840 handle.read.side_effect = _read_side_effect
2841 _state[1] = _readline_side_effect()
2842 handle.readline.side_effect = _state[1]
2843 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002844 handle.__iter__.side_effect = _iter_side_effect
Damien Nadé394119a2019-05-23 12:03:25 +02002845 handle.__next__.side_effect = _next_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002846
Robert Collinsca647ef2015-07-24 03:48:20 +12002847 def reset_data(*args, **kwargs):
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002848 _state[0] = _to_stream(read_data)
Robert Collinsca647ef2015-07-24 03:48:20 +12002849 if handle.readline.side_effect == _state[1]:
2850 # Only reset the side effect if the user hasn't overridden it.
2851 _state[1] = _readline_side_effect()
2852 handle.readline.side_effect = _state[1]
2853 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002854
Robert Collinsca647ef2015-07-24 03:48:20 +12002855 mock.side_effect = reset_data
2856 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002857 return mock
2858
2859
2860class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002861 """
2862 A mock intended to be used as a property, or other descriptor, on a class.
2863 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2864 a return value when it is fetched.
2865
2866 Fetching a `PropertyMock` instance from an object calls the mock, with
2867 no args. Setting it calls the mock with the value being set.
2868 """
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002869 def _get_child_mock(self, /, **kwargs):
Michael Foordc2870622012-04-13 16:57:22 +01002870 return MagicMock(**kwargs)
2871
Raymond Hettinger0dac68f2019-08-29 01:27:42 -07002872 def __get__(self, obj, obj_type=None):
Michael Foord345266a2012-03-14 12:24:34 -07002873 return self()
2874 def __set__(self, obj, val):
2875 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002876
2877
2878def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002879 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002880
2881 Given an input Mock, seals it to ensure no further mocks will be generated
2882 when accessing an attribute that was not already defined.
2883
Mario Corchero96200eb2018-10-19 22:57:37 +01002884 The operation recursively seals the mock passed in, meaning that
2885 the mock itself, any mocks generated by accessing one of its attributes,
2886 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002887 """
2888 mock._mock_sealed = True
2889 for attr in dir(mock):
2890 try:
2891 m = getattr(mock, attr)
2892 except AttributeError:
2893 continue
2894 if not isinstance(m, NonCallableMock):
2895 continue
2896 if m._mock_new_parent is mock:
2897 seal(m)
Lisa Roach77b3b772019-05-20 09:19:53 -07002898
2899
Lisa Roach77b3b772019-05-20 09:19:53 -07002900class _AsyncIterator:
2901 """
2902 Wraps an iterator in an asynchronous iterator.
2903 """
2904 def __init__(self, iterator):
2905 self.iterator = iterator
2906 code_mock = NonCallableMock(spec_set=CodeType)
2907 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
2908 self.__dict__['__code__'] = code_mock
2909
Lisa Roach77b3b772019-05-20 09:19:53 -07002910 async def __anext__(self):
2911 try:
2912 return next(self.iterator)
2913 except StopIteration:
2914 pass
2915 raise StopAsyncIteration