blob: beed717522bba3da0a14fe8ecf0591488b12df07 [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
Lisa Roach77b3b772019-05-20 09:19:53 -070033from types import CodeType, ModuleType, MethodType
Petter Strandmark47d94242018-10-28 21:37:10 +010034from unittest.util import safe_repr
Antoine Pitrou5c64df72013-02-03 00:23:58 +010035from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070036
37
Michael Foordfddcfa22014-04-14 16:25:20 -040038_builtins = {name for name in dir(builtins) if not name.startswith('_')}
39
Michael Foord345266a2012-03-14 12:24:34 -070040FILTER_DIR = True
41
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100042# Workaround for issue #12370
43# Without this, the __class__ properties wouldn't be set correctly
44_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070045
Lisa Roach77b3b772019-05-20 09:19:53 -070046def _is_async_obj(obj):
Lisa Roachf1a297a2019-09-10 12:18:40 +010047 if _is_instance_mock(obj) and not isinstance(obj, AsyncMock):
Lisa Roach77b3b772019-05-20 09:19:53 -070048 return False
Matthew Kokotovich62865f42020-01-25 04:17:47 -060049 if hasattr(obj, '__func__'):
50 obj = getattr(obj, '__func__')
Lisa Roachf1a297a2019-09-10 12:18:40 +010051 return asyncio.iscoroutinefunction(obj) or inspect.isawaitable(obj)
Lisa Roach77b3b772019-05-20 09:19:53 -070052
53
Xtreakff6b2e62019-05-27 18:26:23 +053054def _is_async_func(func):
55 if getattr(func, '__code__', None):
56 return asyncio.iscoroutinefunction(func)
57 else:
58 return False
59
60
Michael Foord345266a2012-03-14 12:24:34 -070061def _is_instance_mock(obj):
62 # can't use isinstance on Mock objects because they override __class__
63 # The base class for all mocks is NonCallableMock
64 return issubclass(type(obj), NonCallableMock)
65
66
67def _is_exception(obj):
68 return (
Chris Withers49e27f02019-05-01 08:48:44 +010069 isinstance(obj, BaseException) or
70 isinstance(obj, type) and issubclass(obj, BaseException)
Michael Foord345266a2012-03-14 12:24:34 -070071 )
72
73
Xtreak7397cda2019-07-22 13:08:22 +053074def _extract_mock(obj):
75 # Autospecced functions will return a FunctionType with "mock" attribute
76 # which is the actual mock object that needs to be used.
77 if isinstance(obj, FunctionTypes) and hasattr(obj, 'mock'):
78 return obj.mock
79 else:
80 return obj
81
82
Antoine Pitrou5c64df72013-02-03 00:23:58 +010083def _get_signature_object(func, as_instance, eat_self):
84 """
85 Given an arbitrary, possibly callable object, try to create a suitable
86 signature object.
87 Return a (reduced func, signature) tuple, or None.
88 """
89 if isinstance(func, type) and not as_instance:
90 # If it's a type and should be modelled as a type, use __init__.
Chris Withersadbf1782019-05-01 23:04:04 +010091 func = func.__init__
Antoine Pitrou5c64df72013-02-03 00:23:58 +010092 # Skip the `self` argument in __init__
93 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070094 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010095 # If we really want to model an instance of the passed type,
96 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070097 try:
98 func = func.__call__
99 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100100 return None
101 if eat_self:
102 sig_func = partial(func, None)
103 else:
104 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -0700105 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100106 return func, inspect.signature(sig_func)
107 except ValueError:
108 # Certain callable types are not supported by inspect.signature()
109 return None
Michael Foord345266a2012-03-14 12:24:34 -0700110
111
112def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100113 sig = _get_signature_object(func, instance, skipfirst)
114 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -0700115 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100116 func, sig = sig
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300117 def checksig(self, /, *args, **kwargs):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100118 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700119 _copy_func_details(func, checksig)
120 type(mock)._mock_check_sig = checksig
Xtreakf7fa62e2018-12-12 13:24:54 +0530121 type(mock).__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700122
123
124def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700125 # we explicitly don't copy func.__dict__ into this copy as it would
126 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300127 for attribute in (
128 '__name__', '__doc__', '__text_signature__',
129 '__module__', '__defaults__', '__kwdefaults__',
130 ):
131 try:
132 setattr(funcopy, attribute, getattr(func, attribute))
133 except AttributeError:
134 pass
Michael Foord345266a2012-03-14 12:24:34 -0700135
136
137def _callable(obj):
138 if isinstance(obj, type):
139 return True
Xtreak9b218562019-04-22 08:00:23 +0530140 if isinstance(obj, (staticmethod, classmethod, MethodType)):
141 return _callable(obj.__func__)
Michael Foord345266a2012-03-14 12:24:34 -0700142 if getattr(obj, '__call__', None) is not None:
143 return True
144 return False
145
146
147def _is_list(obj):
148 # checks for list or tuples
149 # XXXX badly named!
150 return type(obj) in (list, tuple)
151
152
153def _instance_callable(obj):
154 """Given an object, return True if the object is callable.
155 For classes, return True if instances would be callable."""
156 if not isinstance(obj, type):
157 # already an instance
158 return getattr(obj, '__call__', None) is not None
159
Michael Foorda74b3aa2012-03-14 14:40:22 -0700160 # *could* be broken by a class overriding __mro__ or __dict__ via
161 # a metaclass
162 for base in (obj,) + obj.__mro__:
163 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700164 return True
165 return False
166
167
168def _set_signature(mock, original, instance=False):
169 # creates a function with signature (*args, **kwargs) that delegates to a
170 # mock. It still does signature checking by calling a lambda with the same
171 # signature as the original.
Michael Foord345266a2012-03-14 12:24:34 -0700172
173 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100174 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700175 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700176 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100177 func, sig = result
178 def checksig(*args, **kwargs):
179 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700180 _copy_func_details(func, checksig)
181
182 name = original.__name__
183 if not name.isidentifier():
184 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100185 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700186 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100187 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700188 return mock(*args, **kwargs)""" % name
189 exec (src, context)
190 funcopy = context[name]
Xtreakf7fa62e2018-12-12 13:24:54 +0530191 _setup_func(funcopy, mock, sig)
Michael Foord345266a2012-03-14 12:24:34 -0700192 return funcopy
193
194
Xtreakf7fa62e2018-12-12 13:24:54 +0530195def _setup_func(funcopy, mock, sig):
Michael Foord345266a2012-03-14 12:24:34 -0700196 funcopy.mock = mock
197
Michael Foord345266a2012-03-14 12:24:34 -0700198 def assert_called_with(*args, **kwargs):
199 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700200 def assert_called(*args, **kwargs):
201 return mock.assert_called(*args, **kwargs)
202 def assert_not_called(*args, **kwargs):
203 return mock.assert_not_called(*args, **kwargs)
204 def assert_called_once(*args, **kwargs):
205 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700206 def assert_called_once_with(*args, **kwargs):
207 return mock.assert_called_once_with(*args, **kwargs)
208 def assert_has_calls(*args, **kwargs):
209 return mock.assert_has_calls(*args, **kwargs)
210 def assert_any_call(*args, **kwargs):
211 return mock.assert_any_call(*args, **kwargs)
212 def reset_mock():
213 funcopy.method_calls = _CallList()
214 funcopy.mock_calls = _CallList()
215 mock.reset_mock()
216 ret = funcopy.return_value
217 if _is_instance_mock(ret) and not ret is mock:
218 ret.reset_mock()
219
220 funcopy.called = False
221 funcopy.call_count = 0
222 funcopy.call_args = None
223 funcopy.call_args_list = _CallList()
224 funcopy.method_calls = _CallList()
225 funcopy.mock_calls = _CallList()
226
227 funcopy.return_value = mock.return_value
228 funcopy.side_effect = mock.side_effect
229 funcopy._mock_children = mock._mock_children
230
231 funcopy.assert_called_with = assert_called_with
232 funcopy.assert_called_once_with = assert_called_once_with
233 funcopy.assert_has_calls = assert_has_calls
234 funcopy.assert_any_call = assert_any_call
235 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700236 funcopy.assert_called = assert_called
237 funcopy.assert_not_called = assert_not_called
238 funcopy.assert_called_once = assert_called_once
Xtreakf7fa62e2018-12-12 13:24:54 +0530239 funcopy.__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700240
241 mock._mock_delegate = funcopy
242
243
Xtreakff6b2e62019-05-27 18:26:23 +0530244def _setup_async_mock(mock):
245 mock._is_coroutine = asyncio.coroutines._is_coroutine
246 mock.await_count = 0
247 mock.await_args = None
248 mock.await_args_list = _CallList()
Xtreakff6b2e62019-05-27 18:26:23 +0530249
250 # Mock is not configured yet so the attributes are set
251 # to a function and then the corresponding mock helper function
252 # is called when the helper is accessed similar to _setup_func.
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300253 def wrapper(attr, /, *args, **kwargs):
Xtreakff6b2e62019-05-27 18:26:23 +0530254 return getattr(mock.mock, attr)(*args, **kwargs)
255
256 for attribute in ('assert_awaited',
257 'assert_awaited_once',
258 'assert_awaited_with',
259 'assert_awaited_once_with',
260 'assert_any_await',
261 'assert_has_awaits',
262 'assert_not_awaited'):
263
264 # setattr(mock, attribute, wrapper) causes late binding
265 # hence attribute will always be the last value in the loop
266 # Use partial(wrapper, attribute) to ensure the attribute is bound
267 # correctly.
268 setattr(mock, attribute, partial(wrapper, attribute))
269
270
Michael Foord345266a2012-03-14 12:24:34 -0700271def _is_magic(name):
272 return '__%s__' % name[2:-2] == name
273
274
275class _SentinelObject(object):
276 "A unique, named, sentinel object."
277 def __init__(self, name):
278 self.name = name
279
280 def __repr__(self):
281 return 'sentinel.%s' % self.name
282
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200283 def __reduce__(self):
284 return 'sentinel.%s' % self.name
285
Michael Foord345266a2012-03-14 12:24:34 -0700286
287class _Sentinel(object):
288 """Access attributes to return a named object, usable as a sentinel."""
289 def __init__(self):
290 self._sentinels = {}
291
292 def __getattr__(self, name):
293 if name == '__bases__':
294 # Without this help(unittest.mock) raises an exception
295 raise AttributeError
296 return self._sentinels.setdefault(name, _SentinelObject(name))
297
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200298 def __reduce__(self):
299 return 'sentinel'
300
Michael Foord345266a2012-03-14 12:24:34 -0700301
302sentinel = _Sentinel()
303
304DEFAULT = sentinel.DEFAULT
305_missing = sentinel.MISSING
306_deleted = sentinel.DELETED
307
308
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200309_allowed_names = {
310 'return_value', '_mock_return_value', 'side_effect',
311 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
312 '_mock_name', '_mock_new_name'
313}
Michael Foord345266a2012-03-14 12:24:34 -0700314
315
316def _delegating_property(name):
317 _allowed_names.add(name)
318 _the_name = '_mock_' + name
319 def _get(self, name=name, _the_name=_the_name):
320 sig = self._mock_delegate
321 if sig is None:
322 return getattr(self, _the_name)
323 return getattr(sig, name)
324 def _set(self, value, name=name, _the_name=_the_name):
325 sig = self._mock_delegate
326 if sig is None:
327 self.__dict__[_the_name] = value
328 else:
329 setattr(sig, name, value)
330
331 return property(_get, _set)
332
333
334
335class _CallList(list):
336
337 def __contains__(self, value):
338 if not isinstance(value, list):
339 return list.__contains__(self, value)
340 len_value = len(value)
341 len_self = len(self)
342 if len_value > len_self:
343 return False
344
345 for i in range(0, len_self - len_value + 1):
346 sub_list = self[i:i+len_value]
347 if sub_list == value:
348 return True
349 return False
350
351 def __repr__(self):
352 return pprint.pformat(list(self))
353
354
355def _check_and_set_parent(parent, value, name, new_name):
Xtreak7397cda2019-07-22 13:08:22 +0530356 value = _extract_mock(value)
Xtreak9c3f2842019-02-26 03:16:34 +0530357
Michael Foord345266a2012-03-14 12:24:34 -0700358 if not _is_instance_mock(value):
359 return False
360 if ((value._mock_name or value._mock_new_name) or
361 (value._mock_parent is not None) or
362 (value._mock_new_parent is not None)):
363 return False
364
365 _parent = parent
366 while _parent is not None:
367 # setting a mock (value) as a child or return value of itself
368 # should not modify the mock
369 if _parent is value:
370 return False
371 _parent = _parent._mock_new_parent
372
373 if new_name:
374 value._mock_new_parent = parent
375 value._mock_new_name = new_name
376 if name:
377 value._mock_parent = parent
378 value._mock_name = name
379 return True
380
Michael Foord01bafdc2014-04-14 16:09:42 -0400381# Internal class to identify if we wrapped an iterator object or not.
382class _MockIter(object):
383 def __init__(self, obj):
384 self.obj = iter(obj)
Michael Foord01bafdc2014-04-14 16:09:42 -0400385 def __next__(self):
386 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700387
388class Base(object):
389 _mock_return_value = DEFAULT
390 _mock_side_effect = None
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300391 def __init__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700392 pass
393
394
395
396class NonCallableMock(Base):
397 """A non-callable version of `Mock`"""
398
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300399 def __new__(cls, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700400 # every instance has its own class
401 # so we can create magic methods on the
402 # class without stomping on other mocks
Lisa Roach77b3b772019-05-20 09:19:53 -0700403 bases = (cls,)
Michael Foord14fd9252019-09-13 18:40:56 +0200404 if not issubclass(cls, AsyncMockMixin):
Lisa Roach77b3b772019-05-20 09:19:53 -0700405 # Check if spec is an async object or function
Michael Foord14fd9252019-09-13 18:40:56 +0200406 bound_args = _MOCK_SIG.bind_partial(cls, *args, **kw).arguments
407 spec_arg = bound_args.get('spec_set', bound_args.get('spec'))
408 if spec_arg and _is_async_obj(spec_arg):
409 bases = (AsyncMockMixin, cls)
Lisa Roach77b3b772019-05-20 09:19:53 -0700410 new = type(cls.__name__, bases, {'__doc__': cls.__doc__})
Lisa Roach9a7d9512019-09-28 18:42:44 -0700411 instance = _safe_super(NonCallableMock, cls).__new__(new)
Michael Foord345266a2012-03-14 12:24:34 -0700412 return instance
413
414
415 def __init__(
416 self, spec=None, wraps=None, name=None, spec_set=None,
417 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530418 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700419 ):
420 if _new_parent is None:
421 _new_parent = parent
422
423 __dict__ = self.__dict__
424 __dict__['_mock_parent'] = parent
425 __dict__['_mock_name'] = name
426 __dict__['_mock_new_name'] = _new_name
427 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100428 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700429
430 if spec_set is not None:
431 spec = spec_set
432 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100433 if _eat_self is None:
434 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700435
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100436 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700437
438 __dict__['_mock_children'] = {}
439 __dict__['_mock_wraps'] = wraps
440 __dict__['_mock_delegate'] = None
441
442 __dict__['_mock_called'] = False
443 __dict__['_mock_call_args'] = None
444 __dict__['_mock_call_count'] = 0
445 __dict__['_mock_call_args_list'] = _CallList()
446 __dict__['_mock_mock_calls'] = _CallList()
447
448 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530449 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700450
451 if kwargs:
452 self.configure_mock(**kwargs)
453
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000454 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700455 spec, wraps, name, spec_set, parent,
456 _spec_state
457 )
458
459
460 def attach_mock(self, mock, attribute):
461 """
462 Attach a mock as an attribute of this one, replacing its name and
463 parent. Calls to the attached mock will be recorded in the
464 `method_calls` and `mock_calls` attributes of this one."""
Xtreak7397cda2019-07-22 13:08:22 +0530465 inner_mock = _extract_mock(mock)
466
467 inner_mock._mock_parent = None
468 inner_mock._mock_new_parent = None
469 inner_mock._mock_name = ''
470 inner_mock._mock_new_name = None
Michael Foord345266a2012-03-14 12:24:34 -0700471
472 setattr(self, attribute, mock)
473
474
475 def mock_add_spec(self, spec, spec_set=False):
476 """Add a spec to a mock. `spec` can either be an object or a
477 list of strings. Only attributes on the `spec` can be fetched as
478 attributes from the mock.
479
480 If `spec_set` is True then only attributes on the spec can be set."""
481 self._mock_add_spec(spec, spec_set)
482
483
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100484 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
485 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700486 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100487 _spec_signature = None
Lisa Roach77b3b772019-05-20 09:19:53 -0700488 _spec_asyncs = []
489
490 for attr in dir(spec):
491 if asyncio.iscoroutinefunction(getattr(spec, attr, None)):
492 _spec_asyncs.append(attr)
Michael Foord345266a2012-03-14 12:24:34 -0700493
494 if spec is not None and not _is_list(spec):
495 if isinstance(spec, type):
496 _spec_class = spec
497 else:
Chris Withersadbf1782019-05-01 23:04:04 +0100498 _spec_class = type(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100499 res = _get_signature_object(spec,
500 _spec_as_instance, _eat_self)
501 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700502
503 spec = dir(spec)
504
505 __dict__ = self.__dict__
506 __dict__['_spec_class'] = _spec_class
507 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100508 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700509 __dict__['_mock_methods'] = spec
Lisa Roach77b3b772019-05-20 09:19:53 -0700510 __dict__['_spec_asyncs'] = _spec_asyncs
Michael Foord345266a2012-03-14 12:24:34 -0700511
512 def __get_return_value(self):
513 ret = self._mock_return_value
514 if self._mock_delegate is not None:
515 ret = self._mock_delegate.return_value
516
517 if ret is DEFAULT:
518 ret = self._get_child_mock(
519 _new_parent=self, _new_name='()'
520 )
521 self.return_value = ret
522 return ret
523
524
525 def __set_return_value(self, value):
526 if self._mock_delegate is not None:
527 self._mock_delegate.return_value = value
528 else:
529 self._mock_return_value = value
530 _check_and_set_parent(self, value, None, '()')
531
532 __return_value_doc = "The value to be returned when the mock is called."
533 return_value = property(__get_return_value, __set_return_value,
534 __return_value_doc)
535
536
537 @property
538 def __class__(self):
539 if self._spec_class is None:
540 return type(self)
541 return self._spec_class
542
543 called = _delegating_property('called')
544 call_count = _delegating_property('call_count')
545 call_args = _delegating_property('call_args')
546 call_args_list = _delegating_property('call_args_list')
547 mock_calls = _delegating_property('mock_calls')
548
549
550 def __get_side_effect(self):
551 delegated = self._mock_delegate
552 if delegated is None:
553 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400554 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200555 if (sf is not None and not callable(sf)
556 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400557 sf = _MockIter(sf)
558 delegated.side_effect = sf
559 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700560
561 def __set_side_effect(self, value):
562 value = _try_iter(value)
563 delegated = self._mock_delegate
564 if delegated is None:
565 self._mock_side_effect = value
566 else:
567 delegated.side_effect = value
568
569 side_effect = property(__get_side_effect, __set_side_effect)
570
571
Kushal Das9cd39a12016-06-02 10:20:16 -0700572 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700573 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200574 if visited is None:
575 visited = []
576 if id(self) in visited:
577 return
578 visited.append(id(self))
579
Michael Foord345266a2012-03-14 12:24:34 -0700580 self.called = False
581 self.call_args = None
582 self.call_count = 0
583 self.mock_calls = _CallList()
584 self.call_args_list = _CallList()
585 self.method_calls = _CallList()
586
Kushal Das9cd39a12016-06-02 10:20:16 -0700587 if return_value:
588 self._mock_return_value = DEFAULT
589 if side_effect:
590 self._mock_side_effect = None
591
Michael Foord345266a2012-03-14 12:24:34 -0700592 for child in self._mock_children.values():
Xtreakedeca922018-12-01 15:33:54 +0530593 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100594 continue
Vegard Stikbakkeaef7dc82020-01-25 16:44:46 +0100595 child.reset_mock(visited, return_value=return_value, side_effect=side_effect)
Michael Foord345266a2012-03-14 12:24:34 -0700596
597 ret = self._mock_return_value
598 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200599 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700600
601
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300602 def configure_mock(self, /, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700603 """Set attributes on the mock through keyword arguments.
604
605 Attributes plus return values and side effects can be set on child
606 mocks using standard dot notation and unpacking a dictionary in the
607 method call:
608
609 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
610 >>> mock.configure_mock(**attrs)"""
611 for arg, val in sorted(kwargs.items(),
612 # we sort on the number of dots so that
613 # attributes are set before we set attributes on
614 # attributes
615 key=lambda entry: entry[0].count('.')):
616 args = arg.split('.')
617 final = args.pop()
618 obj = self
619 for entry in args:
620 obj = getattr(obj, entry)
621 setattr(obj, final, val)
622
623
624 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530625 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700626 raise AttributeError(name)
627 elif self._mock_methods is not None:
628 if name not in self._mock_methods or name in _all_magics:
629 raise AttributeError("Mock object has no attribute %r" % name)
630 elif _is_magic(name):
631 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530632 if not self._mock_unsafe:
633 if name.startswith(('assert', 'assret')):
Zackery Spytzb9b08cd2019-05-08 11:32:24 -0600634 raise AttributeError("Attributes cannot start with 'assert' "
635 "or 'assret'")
Michael Foord345266a2012-03-14 12:24:34 -0700636
637 result = self._mock_children.get(name)
638 if result is _deleted:
639 raise AttributeError(name)
640 elif result is None:
641 wraps = None
642 if self._mock_wraps is not None:
643 # XXXX should we get the attribute without triggering code
644 # execution?
645 wraps = getattr(self._mock_wraps, name)
646
647 result = self._get_child_mock(
648 parent=self, name=name, wraps=wraps, _new_name=name,
649 _new_parent=self
650 )
651 self._mock_children[name] = result
652
653 elif isinstance(result, _SpecState):
654 result = create_autospec(
655 result.spec, result.spec_set, result.instance,
656 result.parent, result.name
657 )
658 self._mock_children[name] = result
659
660 return result
661
662
Mario Corchero552be9d2017-10-17 12:35:11 +0100663 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700664 _name_list = [self._mock_new_name]
665 _parent = self._mock_new_parent
666 last = self
667
668 dot = '.'
669 if _name_list == ['()']:
670 dot = ''
Chris Withersadbf1782019-05-01 23:04:04 +0100671
Michael Foord345266a2012-03-14 12:24:34 -0700672 while _parent is not None:
673 last = _parent
674
675 _name_list.append(_parent._mock_new_name + dot)
676 dot = '.'
677 if _parent._mock_new_name == '()':
678 dot = ''
679
680 _parent = _parent._mock_new_parent
681
Michael Foord345266a2012-03-14 12:24:34 -0700682 _name_list = list(reversed(_name_list))
683 _first = last._mock_name or 'mock'
684 if len(_name_list) > 1:
685 if _name_list[1] not in ('()', '().'):
686 _first += '.'
687 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100688 return ''.join(_name_list)
689
690 def __repr__(self):
691 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700692
693 name_string = ''
694 if name not in ('mock', 'mock.'):
695 name_string = ' name=%r' % name
696
697 spec_string = ''
698 if self._spec_class is not None:
699 spec_string = ' spec=%r'
700 if self._spec_set:
701 spec_string = ' spec_set=%r'
702 spec_string = spec_string % self._spec_class.__name__
703 return "<%s%s%s id='%s'>" % (
704 type(self).__name__,
705 name_string,
706 spec_string,
707 id(self)
708 )
709
710
711 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700712 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100713 if not FILTER_DIR:
714 return object.__dir__(self)
715
Michael Foord345266a2012-03-14 12:24:34 -0700716 extras = self._mock_methods or []
717 from_type = dir(type(self))
718 from_dict = list(self.__dict__)
Mario Corchero0df635c2019-04-30 19:56:36 +0100719 from_child_mocks = [
720 m_name for m_name, m_value in self._mock_children.items()
721 if m_value is not _deleted]
Michael Foord345266a2012-03-14 12:24:34 -0700722
Michael Foord313f85f2012-03-25 18:16:07 +0100723 from_type = [e for e in from_type if not e.startswith('_')]
724 from_dict = [e for e in from_dict if not e.startswith('_') or
725 _is_magic(e)]
Mario Corchero0df635c2019-04-30 19:56:36 +0100726 return sorted(set(extras + from_type + from_dict + from_child_mocks))
Michael Foord345266a2012-03-14 12:24:34 -0700727
728
729 def __setattr__(self, name, value):
730 if name in _allowed_names:
731 # property setters go through here
732 return object.__setattr__(self, name, value)
733 elif (self._spec_set and self._mock_methods is not None and
734 name not in self._mock_methods and
735 name not in self.__dict__):
736 raise AttributeError("Mock object has no attribute '%s'" % name)
737 elif name in _unsupported_magics:
738 msg = 'Attempting to set unsupported magic method %r.' % name
739 raise AttributeError(msg)
740 elif name in _all_magics:
741 if self._mock_methods is not None and name not in self._mock_methods:
742 raise AttributeError("Mock object has no attribute '%s'" % name)
743
744 if not _is_instance_mock(value):
745 setattr(type(self), name, _get_method(name, value))
746 original = value
747 value = lambda *args, **kw: original(self, *args, **kw)
748 else:
749 # only set _new_name and not name so that mock_calls is tracked
750 # but not method calls
751 _check_and_set_parent(self, value, None, name)
752 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100753 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700754 elif name == '__class__':
755 self._spec_class = value
756 return
757 else:
758 if _check_and_set_parent(self, value, name, name):
759 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100760
761 if self._mock_sealed and not hasattr(self, name):
762 mock_name = f'{self._extract_mock_name()}.{name}'
763 raise AttributeError(f'Cannot set {mock_name}')
764
Michael Foord345266a2012-03-14 12:24:34 -0700765 return object.__setattr__(self, name, value)
766
767
768 def __delattr__(self, name):
769 if name in _all_magics and name in type(self).__dict__:
770 delattr(type(self), name)
771 if name not in self.__dict__:
772 # for magic methods that are still MagicProxy objects and
773 # not set on the instance itself
774 return
775
Michael Foord345266a2012-03-14 12:24:34 -0700776 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000777 if name in self.__dict__:
Xtreak830b43d2019-04-14 00:42:33 +0530778 _safe_super(NonCallableMock, self).__delattr__(name)
Pablo Galindo222d3032019-01-21 08:57:46 +0000779 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700780 raise AttributeError(name)
781 if obj is not _missing:
782 del self._mock_children[name]
783 self._mock_children[name] = _deleted
784
785
Michael Foord345266a2012-03-14 12:24:34 -0700786 def _format_mock_call_signature(self, args, kwargs):
787 name = self._mock_name or 'mock'
788 return _format_call_signature(name, args, kwargs)
789
790
Xtreak0ae022c2019-05-29 12:32:26 +0530791 def _format_mock_failure_message(self, args, kwargs, action='call'):
792 message = 'expected %s not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700793 expected_string = self._format_mock_call_signature(args, kwargs)
794 call_args = self.call_args
Michael Foord345266a2012-03-14 12:24:34 -0700795 actual_string = self._format_mock_call_signature(*call_args)
Xtreak0ae022c2019-05-29 12:32:26 +0530796 return message % (action, expected_string, actual_string)
Michael Foord345266a2012-03-14 12:24:34 -0700797
798
Xtreakc9612782019-08-29 11:39:01 +0530799 def _get_call_signature_from_name(self, name):
800 """
801 * If call objects are asserted against a method/function like obj.meth1
802 then there could be no name for the call object to lookup. Hence just
803 return the spec_signature of the method/function being asserted against.
804 * If the name is not empty then remove () and split by '.' to get
805 list of names to iterate through the children until a potential
806 match is found. A child mock is created only during attribute access
807 so if we get a _SpecState then no attributes of the spec were accessed
808 and can be safely exited.
809 """
810 if not name:
811 return self._spec_signature
812
813 sig = None
814 names = name.replace('()', '').split('.')
815 children = self._mock_children
816
817 for name in names:
818 child = children.get(name)
819 if child is None or isinstance(child, _SpecState):
820 break
821 else:
Karthikeyan Singaravelan66b00a92020-01-24 18:44:29 +0530822 # If an autospecced object is attached using attach_mock the
823 # child would be a function with mock object as attribute from
824 # which signature has to be derived.
825 child = _extract_mock(child)
Xtreakc9612782019-08-29 11:39:01 +0530826 children = child._mock_children
827 sig = child._spec_signature
828
829 return sig
830
831
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100832 def _call_matcher(self, _call):
833 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000834 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100835 comparison key suitable for matching with other calls.
836 This is a best effort method which relies on the spec's signature,
837 if available, or falls back on the arguments themselves.
838 """
Xtreakc9612782019-08-29 11:39:01 +0530839
840 if isinstance(_call, tuple) and len(_call) > 2:
841 sig = self._get_call_signature_from_name(_call[0])
842 else:
843 sig = self._spec_signature
844
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100845 if sig is not None:
846 if len(_call) == 2:
847 name = ''
848 args, kwargs = _call
849 else:
850 name, args, kwargs = _call
851 try:
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700852 bound_call = sig.bind(*args, **kwargs)
853 return call(name, bound_call.args, bound_call.kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100854 except TypeError as e:
855 return e.with_traceback(None)
856 else:
857 return _call
858
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300859 def assert_not_called(self):
Kushal Das8af9db32014-04-17 01:36:14 +0530860 """assert that the mock was never called.
861 """
Kushal Das8af9db32014-04-17 01:36:14 +0530862 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100863 msg = ("Expected '%s' to not have been called. Called %s times.%s"
864 % (self._mock_name or 'mock',
865 self.call_count,
866 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530867 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100868
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300869 def assert_called(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100870 """assert that the mock was called at least once
871 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100872 if self.call_count == 0:
873 msg = ("Expected '%s' to have been called." %
Abraham Toriz Cruz5f5f11f2019-09-17 06:16:08 -0500874 (self._mock_name or 'mock'))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100875 raise AssertionError(msg)
876
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300877 def assert_called_once(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100878 """assert that the mock was called only once.
879 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100880 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100881 msg = ("Expected '%s' to have been called once. Called %s times.%s"
882 % (self._mock_name or 'mock',
883 self.call_count,
884 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100885 raise AssertionError(msg)
886
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300887 def assert_called_with(self, /, *args, **kwargs):
Rémi Lapeyref5896a02019-08-29 08:15:53 +0200888 """assert that the last call was made with the specified arguments.
Michael Foord345266a2012-03-14 12:24:34 -0700889
890 Raises an AssertionError if the args and keyword args passed in are
891 different to the last call to the mock."""
Michael Foord345266a2012-03-14 12:24:34 -0700892 if self.call_args is None:
893 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800894 actual = 'not called.'
895 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
896 % (expected, actual))
897 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700898
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100899 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700900 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100901 return msg
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700902 expected = self._call_matcher(_Call((args, kwargs), two=True))
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100903 actual = self._call_matcher(self.call_args)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700904 if actual != expected:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100905 cause = expected if isinstance(expected, Exception) else None
906 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700907
908
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300909 def assert_called_once_with(self, /, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100910 """assert that the mock was called exactly once and that that call was
911 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700912 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100913 msg = ("Expected '%s' to be called once. Called %s times.%s"
914 % (self._mock_name or 'mock',
915 self.call_count,
916 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700917 raise AssertionError(msg)
918 return self.assert_called_with(*args, **kwargs)
919
920
921 def assert_has_calls(self, calls, any_order=False):
922 """assert the mock has been called with the specified calls.
923 The `mock_calls` list is checked for the calls.
924
925 If `any_order` is False (the default) then the calls must be
926 sequential. There can be extra calls before or after the
927 specified calls.
928
929 If `any_order` is True then the calls can be in any order, but
930 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100931 expected = [self._call_matcher(c) for c in calls]
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400932 cause = next((e for e in expected if isinstance(e, Exception)), None)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100933 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700934 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100935 if expected not in all_calls:
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400936 if cause is None:
937 problem = 'Calls not found.'
938 else:
939 problem = ('Error processing expected calls.\n'
940 'Errors: {}').format(
941 [e if isinstance(e, Exception) else None
942 for e in expected])
Michael Foord345266a2012-03-14 12:24:34 -0700943 raise AssertionError(
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400944 f'{problem}\n'
Samuel Freilich2180f6b2019-09-24 18:04:29 -0400945 f'Expected: {_CallList(calls)}'
946 f'{self._calls_repr(prefix="Actual").rstrip(".")}'
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100947 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700948 return
949
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100950 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700951
952 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100953 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700954 try:
955 all_calls.remove(kall)
956 except ValueError:
957 not_found.append(kall)
958 if not_found:
959 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400960 '%r does not contain all of %r in its call list, '
961 'found %r instead' % (self._mock_name or 'mock',
962 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100963 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700964
965
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300966 def assert_any_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700967 """assert the mock has been called with the specified arguments.
968
969 The assert passes if the mock has *ever* been called, unlike
970 `assert_called_with` and `assert_called_once_with` that only pass if
971 the call is the most recent one."""
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700972 expected = self._call_matcher(_Call((args, kwargs), two=True))
973 cause = expected if isinstance(expected, Exception) else None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100974 actual = [self._call_matcher(c) for c in self.call_args_list]
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700975 if cause or expected not in _AnyComparer(actual):
Michael Foord345266a2012-03-14 12:24:34 -0700976 expected_string = self._format_mock_call_signature(args, kwargs)
977 raise AssertionError(
978 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100979 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700980
981
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300982 def _get_child_mock(self, /, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700983 """Create the child mocks for attributes and return value.
984 By default child mocks will be the same type as the parent.
985 Subclasses of Mock may want to override this to customize the way
986 child mocks are made.
987
988 For non-callable mocks the callable variant will be used (rather than
989 any custom subclass)."""
Lisa Roach77b3b772019-05-20 09:19:53 -0700990 _new_name = kw.get("_new_name")
991 if _new_name in self.__dict__['_spec_asyncs']:
992 return AsyncMock(**kw)
993
Michael Foord345266a2012-03-14 12:24:34 -0700994 _type = type(self)
Lisa Roach77b3b772019-05-20 09:19:53 -0700995 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
Lisa Roach9a7d9512019-09-28 18:42:44 -0700996 # Any asynchronous magic becomes an AsyncMock
Lisa Roach77b3b772019-05-20 09:19:53 -0700997 klass = AsyncMock
Lisa Roach8b03f942019-09-19 21:04:18 -0700998 elif issubclass(_type, AsyncMockMixin):
Lisa Roach3667e1e2019-09-29 21:56:47 -0700999 if (_new_name in _all_sync_magics or
1000 self._mock_methods and _new_name in self._mock_methods):
1001 # Any synchronous method on AsyncMock becomes a MagicMock
Lisa Roach9a7d9512019-09-28 18:42:44 -07001002 klass = MagicMock
1003 else:
1004 klass = AsyncMock
Lisa Roach8b03f942019-09-19 21:04:18 -07001005 elif not issubclass(_type, CallableMixin):
Michael Foord345266a2012-03-14 12:24:34 -07001006 if issubclass(_type, NonCallableMagicMock):
1007 klass = MagicMock
Lisa Roach9a7d9512019-09-28 18:42:44 -07001008 elif issubclass(_type, NonCallableMock):
Michael Foord345266a2012-03-14 12:24:34 -07001009 klass = Mock
1010 else:
1011 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +01001012
1013 if self._mock_sealed:
1014 attribute = "." + kw["name"] if "name" in kw else "()"
1015 mock_name = self._extract_mock_name() + attribute
1016 raise AttributeError(mock_name)
1017
Michael Foord345266a2012-03-14 12:24:34 -07001018 return klass(**kw)
1019
1020
Petter Strandmark47d94242018-10-28 21:37:10 +01001021 def _calls_repr(self, prefix="Calls"):
1022 """Renders self.mock_calls as a string.
1023
1024 Example: "\nCalls: [call(1), call(2)]."
1025
1026 If self.mock_calls is empty, an empty string is returned. The
1027 output will be truncated if very long.
1028 """
1029 if not self.mock_calls:
1030 return ""
1031 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
1032
1033
Michael Foord14fd9252019-09-13 18:40:56 +02001034_MOCK_SIG = inspect.signature(NonCallableMock.__init__)
1035
1036
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07001037class _AnyComparer(list):
1038 """A list which checks if it contains a call which may have an
1039 argument of ANY, flipping the components of item and self from
1040 their traditional locations so that ANY is guaranteed to be on
1041 the left."""
1042 def __contains__(self, item):
1043 for _call in self:
1044 if len(item) != len(_call):
1045 continue
1046 if all([
1047 expected == actual
1048 for expected, actual in zip(item, _call)
1049 ]):
1050 return True
1051 return False
1052
Michael Foord345266a2012-03-14 12:24:34 -07001053
1054def _try_iter(obj):
1055 if obj is None:
1056 return obj
1057 if _is_exception(obj):
1058 return obj
1059 if _callable(obj):
1060 return obj
1061 try:
1062 return iter(obj)
1063 except TypeError:
1064 # XXXX backwards compatibility
1065 # but this will blow up on first call - so maybe we should fail early?
1066 return obj
1067
1068
Michael Foord345266a2012-03-14 12:24:34 -07001069class CallableMixin(Base):
1070
1071 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
1072 wraps=None, name=None, spec_set=None, parent=None,
1073 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
1074 self.__dict__['_mock_return_value'] = return_value
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001075 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -07001076 spec, wraps, name, spec_set, parent,
1077 _spec_state, _new_name, _new_parent, **kwargs
1078 )
1079
1080 self.side_effect = side_effect
1081
1082
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001083 def _mock_check_sig(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001084 # stub method that can be replaced with one with a specific signature
1085 pass
1086
1087
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001088 def __call__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001089 # can't use self in-case a function / method we are mocking uses self
1090 # in the signature
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001091 self._mock_check_sig(*args, **kwargs)
Lisa Roachef048512019-09-23 20:49:40 -07001092 self._increment_mock_call(*args, **kwargs)
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001093 return self._mock_call(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001094
1095
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001096 def _mock_call(self, /, *args, **kwargs):
Lisa Roachef048512019-09-23 20:49:40 -07001097 return self._execute_mock_call(*args, **kwargs)
1098
1099 def _increment_mock_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001100 self.called = True
1101 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001102
Chris Withers8ca0fa92018-12-03 21:31:37 +00001103 # handle call_args
Lisa Roachef048512019-09-23 20:49:40 -07001104 # needs to be set here so assertions on call arguments pass before
1105 # execution in the case of awaited calls
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001106 _call = _Call((args, kwargs), two=True)
1107 self.call_args = _call
1108 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -07001109
Chris Withers8ca0fa92018-12-03 21:31:37 +00001110 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001111 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +00001112 method_call_name = self._mock_name
1113
1114 # initial stuff for mock_calls:
1115 mock_call_name = self._mock_new_name
1116 is_a_call = mock_call_name == '()'
1117 self.mock_calls.append(_Call(('', args, kwargs)))
1118
1119 # follow up the chain of mocks:
1120 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001121 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001122
Chris Withers8ca0fa92018-12-03 21:31:37 +00001123 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001124 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001125 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001126 do_method_calls = _new_parent._mock_parent is not None
1127 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001128 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001129
Chris Withers8ca0fa92018-12-03 21:31:37 +00001130 # handle mock_calls:
1131 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001132 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001133
1134 if _new_parent._mock_new_name:
1135 if is_a_call:
1136 dot = ''
1137 else:
1138 dot = '.'
1139 is_a_call = _new_parent._mock_new_name == '()'
1140 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1141
1142 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001143 _new_parent = _new_parent._mock_new_parent
1144
Lisa Roachef048512019-09-23 20:49:40 -07001145 def _execute_mock_call(self, /, *args, **kwargs):
Jason Fried046442d2019-11-20 16:27:51 -08001146 # separate from _increment_mock_call so that awaited functions are
1147 # executed separately from their call, also AsyncMock overrides this method
Lisa Roachef048512019-09-23 20:49:40 -07001148
Michael Foord345266a2012-03-14 12:24:34 -07001149 effect = self.side_effect
1150 if effect is not None:
1151 if _is_exception(effect):
1152 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001153 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001154 result = next(effect)
1155 if _is_exception(result):
1156 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001157 else:
1158 result = effect(*args, **kwargs)
1159
1160 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001161 return result
Michael Foord345266a2012-03-14 12:24:34 -07001162
Mario Corcherof05df0a2018-12-08 11:25:02 +00001163 if self._mock_return_value is not DEFAULT:
1164 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001165
Mario Corcherof05df0a2018-12-08 11:25:02 +00001166 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001167 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001168
1169 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001170
1171
1172
1173class Mock(CallableMixin, NonCallableMock):
1174 """
1175 Create a new `Mock` object. `Mock` takes several optional arguments
1176 that specify the behaviour of the Mock object:
1177
1178 * `spec`: This can be either a list of strings or an existing object (a
1179 class or instance) that acts as the specification for the mock object. If
1180 you pass in an object then a list of strings is formed by calling dir on
1181 the object (excluding unsupported magic attributes and methods). Accessing
1182 any attribute not in this list will raise an `AttributeError`.
1183
1184 If `spec` is an object (rather than a list of strings) then
1185 `mock.__class__` returns the class of the spec object. This allows mocks
1186 to pass `isinstance` tests.
1187
1188 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1189 or get an attribute on the mock that isn't on the object passed as
1190 `spec_set` will raise an `AttributeError`.
1191
1192 * `side_effect`: A function to be called whenever the Mock is called. See
1193 the `side_effect` attribute. Useful for raising exceptions or
1194 dynamically changing return values. The function is called with the same
1195 arguments as the mock, and unless it returns `DEFAULT`, the return
1196 value of this function is used as the return value.
1197
Michael Foord2cd48732012-04-21 15:52:11 +01001198 If `side_effect` is an iterable then each call to the mock will return
1199 the next value from the iterable. If any of the members of the iterable
1200 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001201
Michael Foord345266a2012-03-14 12:24:34 -07001202 * `return_value`: The value returned when the mock is called. By default
1203 this is a new Mock (created on first access). See the
1204 `return_value` attribute.
1205
Michael Foord0682a0c2012-04-13 20:51:20 +01001206 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1207 calling the Mock will pass the call through to the wrapped object
1208 (returning the real result). Attribute access on the mock will return a
1209 Mock object that wraps the corresponding attribute of the wrapped object
1210 (so attempting to access an attribute that doesn't exist will raise an
1211 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001212
1213 If the mock has an explicit `return_value` set then calls are not passed
1214 to the wrapped object and the `return_value` is returned instead.
1215
1216 * `name`: If the mock has a name then it will be used in the repr of the
1217 mock. This can be useful for debugging. The name is propagated to child
1218 mocks.
1219
1220 Mocks can also be called with arbitrary keyword arguments. These will be
1221 used to set attributes on the mock after it is created.
1222 """
1223
1224
Michael Foord345266a2012-03-14 12:24:34 -07001225def _dot_lookup(thing, comp, import_path):
1226 try:
1227 return getattr(thing, comp)
1228 except AttributeError:
1229 __import__(import_path)
1230 return getattr(thing, comp)
1231
1232
1233def _importer(target):
1234 components = target.split('.')
1235 import_path = components.pop(0)
1236 thing = __import__(import_path)
1237
1238 for comp in components:
1239 import_path += ".%s" % comp
1240 thing = _dot_lookup(thing, comp, import_path)
1241 return thing
1242
1243
1244def _is_started(patcher):
1245 # XXXX horrible
1246 return hasattr(patcher, 'is_local')
1247
1248
1249class _patch(object):
1250
1251 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001252 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001253
1254 def __init__(
1255 self, getter, attribute, new, spec, create,
1256 spec_set, autospec, new_callable, kwargs
1257 ):
1258 if new_callable is not None:
1259 if new is not DEFAULT:
1260 raise ValueError(
1261 "Cannot use 'new' and 'new_callable' together"
1262 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001263 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001264 raise ValueError(
1265 "Cannot use 'autospec' and 'new_callable' together"
1266 )
1267
1268 self.getter = getter
1269 self.attribute = attribute
1270 self.new = new
1271 self.new_callable = new_callable
1272 self.spec = spec
1273 self.create = create
1274 self.has_local = False
1275 self.spec_set = spec_set
1276 self.autospec = autospec
1277 self.kwargs = kwargs
1278 self.additional_patchers = []
1279
1280
1281 def copy(self):
1282 patcher = _patch(
1283 self.getter, self.attribute, self.new, self.spec,
1284 self.create, self.spec_set,
1285 self.autospec, self.new_callable, self.kwargs
1286 )
1287 patcher.attribute_name = self.attribute_name
1288 patcher.additional_patchers = [
1289 p.copy() for p in self.additional_patchers
1290 ]
1291 return patcher
1292
1293
1294 def __call__(self, func):
1295 if isinstance(func, type):
1296 return self.decorate_class(func)
Xtreak436c2b02019-05-28 12:37:39 +05301297 if inspect.iscoroutinefunction(func):
1298 return self.decorate_async_callable(func)
Michael Foord345266a2012-03-14 12:24:34 -07001299 return self.decorate_callable(func)
1300
1301
1302 def decorate_class(self, klass):
1303 for attr in dir(klass):
1304 if not attr.startswith(patch.TEST_PREFIX):
1305 continue
1306
1307 attr_value = getattr(klass, attr)
1308 if not hasattr(attr_value, "__call__"):
1309 continue
1310
1311 patcher = self.copy()
1312 setattr(klass, attr, patcher(attr_value))
1313 return klass
1314
1315
Xtreak436c2b02019-05-28 12:37:39 +05301316 @contextlib.contextmanager
1317 def decoration_helper(self, patched, args, keywargs):
1318 extra_args = []
1319 entered_patchers = []
1320 patching = None
1321
1322 exc_info = tuple()
1323 try:
1324 for patching in patched.patchings:
1325 arg = patching.__enter__()
1326 entered_patchers.append(patching)
1327 if patching.attribute_name is not None:
1328 keywargs.update(arg)
1329 elif patching.new is DEFAULT:
1330 extra_args.append(arg)
1331
1332 args += tuple(extra_args)
1333 yield (args, keywargs)
1334 except:
1335 if (patching not in entered_patchers and
1336 _is_started(patching)):
1337 # the patcher may have been started, but an exception
1338 # raised whilst entering one of its additional_patchers
1339 entered_patchers.append(patching)
1340 # Pass the exception to __exit__
1341 exc_info = sys.exc_info()
1342 # re-raise the exception
1343 raise
1344 finally:
1345 for patching in reversed(entered_patchers):
1346 patching.__exit__(*exc_info)
1347
1348
Michael Foord345266a2012-03-14 12:24:34 -07001349 def decorate_callable(self, func):
Xtreak436c2b02019-05-28 12:37:39 +05301350 # NB. Keep the method in sync with decorate_async_callable()
Michael Foord345266a2012-03-14 12:24:34 -07001351 if hasattr(func, 'patchings'):
1352 func.patchings.append(self)
1353 return func
1354
1355 @wraps(func)
1356 def patched(*args, **keywargs):
Xtreak436c2b02019-05-28 12:37:39 +05301357 with self.decoration_helper(patched,
1358 args,
1359 keywargs) as (newargs, newkeywargs):
1360 return func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001361
Xtreak436c2b02019-05-28 12:37:39 +05301362 patched.patchings = [self]
1363 return patched
Michael Foord345266a2012-03-14 12:24:34 -07001364
Xtreak436c2b02019-05-28 12:37:39 +05301365
1366 def decorate_async_callable(self, func):
1367 # NB. Keep the method in sync with decorate_callable()
1368 if hasattr(func, 'patchings'):
1369 func.patchings.append(self)
1370 return func
1371
1372 @wraps(func)
1373 async def patched(*args, **keywargs):
1374 with self.decoration_helper(patched,
1375 args,
1376 keywargs) as (newargs, newkeywargs):
1377 return await func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001378
1379 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001380 return patched
1381
1382
1383 def get_original(self):
1384 target = self.getter()
1385 name = self.attribute
1386
1387 original = DEFAULT
1388 local = False
1389
1390 try:
1391 original = target.__dict__[name]
1392 except (AttributeError, KeyError):
1393 original = getattr(target, name, DEFAULT)
1394 else:
1395 local = True
1396
Michael Foordfddcfa22014-04-14 16:25:20 -04001397 if name in _builtins and isinstance(target, ModuleType):
1398 self.create = True
1399
Michael Foord345266a2012-03-14 12:24:34 -07001400 if not self.create and original is DEFAULT:
1401 raise AttributeError(
1402 "%s does not have the attribute %r" % (target, name)
1403 )
1404 return original, local
1405
1406
1407 def __enter__(self):
1408 """Perform the patch."""
1409 new, spec, spec_set = self.new, self.spec, self.spec_set
1410 autospec, kwargs = self.autospec, self.kwargs
1411 new_callable = self.new_callable
1412 self.target = self.getter()
1413
Michael Foord50a8c0e2012-03-25 18:57:58 +01001414 # normalise False to None
1415 if spec is False:
1416 spec = None
1417 if spec_set is False:
1418 spec_set = None
1419 if autospec is False:
1420 autospec = None
1421
1422 if spec is not None and autospec is not None:
1423 raise TypeError("Can't specify spec and autospec")
1424 if ((spec is not None or autospec is not None) and
1425 spec_set not in (True, None)):
1426 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1427
Michael Foord345266a2012-03-14 12:24:34 -07001428 original, local = self.get_original()
1429
Michael Foord50a8c0e2012-03-25 18:57:58 +01001430 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001431 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001432 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001433 # set spec to the object we are replacing
1434 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001435 if spec_set is True:
1436 spec_set = original
1437 spec = None
1438 elif spec is not None:
1439 if spec_set is True:
1440 spec_set = spec
1441 spec = None
1442 elif spec_set is True:
1443 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001444
Michael Foord50a8c0e2012-03-25 18:57:58 +01001445 if spec is not None or spec_set is not None:
1446 if original is DEFAULT:
1447 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001448 if isinstance(original, type):
1449 # If we're patching out a class and there is a spec
1450 inherit = True
Lisa Roach77b3b772019-05-20 09:19:53 -07001451 if spec is None and _is_async_obj(original):
1452 Klass = AsyncMock
1453 else:
1454 Klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -07001455 _kwargs = {}
1456 if new_callable is not None:
1457 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001458 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001459 this_spec = spec
1460 if spec_set is not None:
1461 this_spec = spec_set
1462 if _is_list(this_spec):
1463 not_callable = '__call__' not in this_spec
1464 else:
1465 not_callable = not callable(this_spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07001466 if _is_async_obj(this_spec):
1467 Klass = AsyncMock
1468 elif not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001469 Klass = NonCallableMagicMock
1470
1471 if spec is not None:
1472 _kwargs['spec'] = spec
1473 if spec_set is not None:
1474 _kwargs['spec_set'] = spec_set
1475
1476 # add a name to mocks
1477 if (isinstance(Klass, type) and
1478 issubclass(Klass, NonCallableMock) and self.attribute):
1479 _kwargs['name'] = self.attribute
1480
1481 _kwargs.update(kwargs)
1482 new = Klass(**_kwargs)
1483
1484 if inherit and _is_instance_mock(new):
1485 # we can only tell if the instance should be callable if the
1486 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001487 this_spec = spec
1488 if spec_set is not None:
1489 this_spec = spec_set
1490 if (not _is_list(this_spec) and not
1491 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001492 Klass = NonCallableMagicMock
1493
1494 _kwargs.pop('name')
1495 new.return_value = Klass(_new_parent=new, _new_name='()',
1496 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001497 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001498 # spec is ignored, new *must* be default, spec_set is treated
1499 # as a boolean. Should we check spec is not None and that spec_set
1500 # is a bool?
1501 if new is not DEFAULT:
1502 raise TypeError(
1503 "autospec creates the mock for you. Can't specify "
1504 "autospec and new."
1505 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001506 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001507 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001508 spec_set = bool(spec_set)
1509 if autospec is True:
1510 autospec = original
1511
1512 new = create_autospec(autospec, spec_set=spec_set,
1513 _name=self.attribute, **kwargs)
1514 elif kwargs:
1515 # can't set keyword args when we aren't creating the mock
1516 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1517 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1518
1519 new_attr = new
1520
1521 self.temp_original = original
1522 self.is_local = local
1523 setattr(self.target, self.attribute, new_attr)
1524 if self.attribute_name is not None:
1525 extra_args = {}
1526 if self.new is DEFAULT:
1527 extra_args[self.attribute_name] = new
1528 for patching in self.additional_patchers:
1529 arg = patching.__enter__()
1530 if patching.new is DEFAULT:
1531 extra_args.update(arg)
1532 return extra_args
1533
1534 return new
1535
1536
Michael Foord50a8c0e2012-03-25 18:57:58 +01001537 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001538 """Undo the patch."""
1539 if not _is_started(self):
Xtreak02b84cb2019-03-29 02:38:43 +05301540 return
Michael Foord345266a2012-03-14 12:24:34 -07001541
1542 if self.is_local and self.temp_original is not DEFAULT:
1543 setattr(self.target, self.attribute, self.temp_original)
1544 else:
1545 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001546 if not self.create and (not hasattr(self.target, self.attribute) or
1547 self.attribute in ('__doc__', '__module__',
1548 '__defaults__', '__annotations__',
1549 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001550 # needed for proxy objects like django settings
1551 setattr(self.target, self.attribute, self.temp_original)
1552
1553 del self.temp_original
1554 del self.is_local
1555 del self.target
1556 for patcher in reversed(self.additional_patchers):
1557 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001558 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001559
Michael Foordf7c41582012-06-10 20:36:32 +01001560
1561 def start(self):
1562 """Activate a patch, returning any created mock."""
1563 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001564 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001565 return result
1566
1567
1568 def stop(self):
1569 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001570 try:
1571 self._active_patches.remove(self)
1572 except ValueError:
1573 # If the patch hasn't been started this will fail
1574 pass
1575
Michael Foordf7c41582012-06-10 20:36:32 +01001576 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001577
1578
1579
1580def _get_target(target):
1581 try:
1582 target, attribute = target.rsplit('.', 1)
1583 except (TypeError, ValueError):
1584 raise TypeError("Need a valid target to patch. You supplied: %r" %
1585 (target,))
1586 getter = lambda: _importer(target)
1587 return getter, attribute
1588
1589
1590def _patch_object(
1591 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001592 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001593 new_callable=None, **kwargs
1594 ):
1595 """
Michael Foord345266a2012-03-14 12:24:34 -07001596 patch the named member (`attribute`) on an object (`target`) with a mock
1597 object.
1598
1599 `patch.object` can be used as a decorator, class decorator or a context
1600 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1601 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1602 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1603 the mock object it creates.
1604
1605 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1606 for choosing which methods to wrap.
1607 """
Elena Oatcd90a522019-12-08 12:14:38 -08001608 if type(target) is str:
1609 raise TypeError(
1610 f"{target!r} must be the actual object to be patched, not a str"
1611 )
Michael Foord345266a2012-03-14 12:24:34 -07001612 getter = lambda: target
1613 return _patch(
1614 getter, attribute, new, spec, create,
1615 spec_set, autospec, new_callable, kwargs
1616 )
1617
1618
Michael Foord50a8c0e2012-03-25 18:57:58 +01001619def _patch_multiple(target, spec=None, create=False, spec_set=None,
1620 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001621 """Perform multiple patches in a single call. It takes the object to be
1622 patched (either as an object or a string to fetch the object by importing)
1623 and keyword arguments for the patches::
1624
1625 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1626 ...
1627
1628 Use `DEFAULT` as the value if you want `patch.multiple` to create
1629 mocks for you. In this case the created mocks are passed into a decorated
1630 function by keyword, and a dictionary is returned when `patch.multiple` is
1631 used as a context manager.
1632
1633 `patch.multiple` can be used as a decorator, class decorator or a context
1634 manager. The arguments `spec`, `spec_set`, `create`,
1635 `autospec` and `new_callable` have the same meaning as for `patch`. These
1636 arguments will be applied to *all* patches done by `patch.multiple`.
1637
1638 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1639 for choosing which methods to wrap.
1640 """
1641 if type(target) is str:
1642 getter = lambda: _importer(target)
1643 else:
1644 getter = lambda: target
1645
1646 if not kwargs:
1647 raise ValueError(
1648 'Must supply at least one keyword argument with patch.multiple'
1649 )
1650 # need to wrap in a list for python 3, where items is a view
1651 items = list(kwargs.items())
1652 attribute, new = items[0]
1653 patcher = _patch(
1654 getter, attribute, new, spec, create, spec_set,
1655 autospec, new_callable, {}
1656 )
1657 patcher.attribute_name = attribute
1658 for attribute, new in items[1:]:
1659 this_patcher = _patch(
1660 getter, attribute, new, spec, create, spec_set,
1661 autospec, new_callable, {}
1662 )
1663 this_patcher.attribute_name = attribute
1664 patcher.additional_patchers.append(this_patcher)
1665 return patcher
1666
1667
1668def patch(
1669 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001670 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001671 ):
1672 """
1673 `patch` acts as a function decorator, class decorator or a context
1674 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001675 is patched with a `new` object. When the function/with statement exits
1676 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001677
Mario Corcherof5e7f392019-09-09 15:18:06 +01001678 If `new` is omitted, then the target is replaced with an
1679 `AsyncMock if the patched object is an async function or a
1680 `MagicMock` otherwise. If `patch` is used as a decorator and `new` is
Michael Foord54b3db82012-03-28 15:08:08 +01001681 omitted, the created mock is passed in as an extra argument to the
1682 decorated function. If `patch` is used as a context manager the created
1683 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001684
Michael Foord54b3db82012-03-28 15:08:08 +01001685 `target` should be a string in the form `'package.module.ClassName'`. The
1686 `target` is imported and the specified object replaced with the `new`
1687 object, so the `target` must be importable from the environment you are
1688 calling `patch` from. The target is imported when the decorated function
1689 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001690
1691 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1692 if patch is creating one for you.
1693
1694 In addition you can pass `spec=True` or `spec_set=True`, which causes
1695 patch to pass in the object being mocked as the spec/spec_set object.
1696
1697 `new_callable` allows you to specify a different class, or callable object,
Mario Corcherof5e7f392019-09-09 15:18:06 +01001698 that will be called to create the `new` object. By default `AsyncMock` is
1699 used for async functions and `MagicMock` for the rest.
Michael Foord345266a2012-03-14 12:24:34 -07001700
1701 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001702 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001703 All attributes of the mock will also have the spec of the corresponding
1704 attribute of the object being replaced. Methods and functions being
1705 mocked will have their arguments checked and will raise a `TypeError` if
1706 they are called with the wrong signature. For mocks replacing a class,
1707 their return value (the 'instance') will have the same spec as the class.
1708
1709 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1710 arbitrary object as the spec instead of the one being replaced.
1711
1712 By default `patch` will fail to replace attributes that don't exist. If
1713 you pass in `create=True`, and the attribute doesn't exist, patch will
1714 create the attribute for you when the patched function is called, and
1715 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001716 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001717 default because it can be dangerous. With it switched on you can write
1718 passing tests against APIs that don't actually exist!
1719
1720 Patch can be used as a `TestCase` class decorator. It works by
1721 decorating each test method in the class. This reduces the boilerplate
1722 code when your test methods share a common patchings set. `patch` finds
1723 tests by looking for method names that start with `patch.TEST_PREFIX`.
1724 By default this is `test`, which matches the way `unittest` finds tests.
1725 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1726
1727 Patch can be used as a context manager, with the with statement. Here the
1728 patching applies to the indented block after the with statement. If you
1729 use "as" then the patched object will be bound to the name after the
1730 "as"; very useful if `patch` is creating a mock object for you.
1731
1732 `patch` takes arbitrary keyword arguments. These will be passed to
Paulo Henrique Silva40c08092020-01-25 07:53:54 -03001733 `AsyncMock` if the patched object is asynchronous, to `MagicMock`
1734 otherwise or to `new_callable` if specified.
Michael Foord345266a2012-03-14 12:24:34 -07001735
1736 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1737 available for alternate use-cases.
1738 """
1739 getter, attribute = _get_target(target)
1740 return _patch(
1741 getter, attribute, new, spec, create,
1742 spec_set, autospec, new_callable, kwargs
1743 )
1744
1745
1746class _patch_dict(object):
1747 """
1748 Patch a dictionary, or dictionary like object, and restore the dictionary
1749 to its original state after the test.
1750
1751 `in_dict` can be a dictionary or a mapping like container. If it is a
1752 mapping then it must at least support getting, setting and deleting items
1753 plus iterating over keys.
1754
1755 `in_dict` can also be a string specifying the name of the dictionary, which
1756 will then be fetched by importing it.
1757
1758 `values` can be a dictionary of values to set in the dictionary. `values`
1759 can also be an iterable of `(key, value)` pairs.
1760
1761 If `clear` is True then the dictionary will be cleared before the new
1762 values are set.
1763
1764 `patch.dict` can also be called with arbitrary keyword arguments to set
1765 values in the dictionary::
1766
1767 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1768 ...
1769
1770 `patch.dict` can be used as a context manager, decorator or class
1771 decorator. When used as a class decorator `patch.dict` honours
1772 `patch.TEST_PREFIX` for choosing which methods to wrap.
1773 """
1774
1775 def __init__(self, in_dict, values=(), clear=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001776 self.in_dict = in_dict
1777 # support any argument supported by dict(...) constructor
1778 self.values = dict(values)
1779 self.values.update(kwargs)
1780 self.clear = clear
1781 self._original = None
1782
1783
1784 def __call__(self, f):
1785 if isinstance(f, type):
1786 return self.decorate_class(f)
1787 @wraps(f)
1788 def _inner(*args, **kw):
1789 self._patch_dict()
1790 try:
1791 return f(*args, **kw)
1792 finally:
1793 self._unpatch_dict()
1794
1795 return _inner
1796
1797
1798 def decorate_class(self, klass):
1799 for attr in dir(klass):
1800 attr_value = getattr(klass, attr)
1801 if (attr.startswith(patch.TEST_PREFIX) and
1802 hasattr(attr_value, "__call__")):
1803 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1804 decorated = decorator(attr_value)
1805 setattr(klass, attr, decorated)
1806 return klass
1807
1808
1809 def __enter__(self):
1810 """Patch the dict."""
1811 self._patch_dict()
Mario Corchero04530812019-05-28 13:53:31 +01001812 return self.in_dict
Michael Foord345266a2012-03-14 12:24:34 -07001813
1814
1815 def _patch_dict(self):
1816 values = self.values
Xtreaka875ea52019-02-25 00:24:49 +05301817 if isinstance(self.in_dict, str):
1818 self.in_dict = _importer(self.in_dict)
Michael Foord345266a2012-03-14 12:24:34 -07001819 in_dict = self.in_dict
1820 clear = self.clear
1821
1822 try:
1823 original = in_dict.copy()
1824 except AttributeError:
1825 # dict like object with no copy method
1826 # must support iteration over keys
1827 original = {}
1828 for key in in_dict:
1829 original[key] = in_dict[key]
1830 self._original = original
1831
1832 if clear:
1833 _clear_dict(in_dict)
1834
1835 try:
1836 in_dict.update(values)
1837 except AttributeError:
1838 # dict like object with no update method
1839 for key in values:
1840 in_dict[key] = values[key]
1841
1842
1843 def _unpatch_dict(self):
1844 in_dict = self.in_dict
1845 original = self._original
1846
1847 _clear_dict(in_dict)
1848
1849 try:
1850 in_dict.update(original)
1851 except AttributeError:
1852 for key in original:
1853 in_dict[key] = original[key]
1854
1855
1856 def __exit__(self, *args):
1857 """Unpatch the dict."""
1858 self._unpatch_dict()
1859 return False
1860
Mario Corcheroe131c972020-01-24 08:38:33 +00001861
1862 def start(self):
1863 """Activate a patch, returning any created mock."""
1864 result = self.__enter__()
1865 _patch._active_patches.append(self)
1866 return result
1867
1868
1869 def stop(self):
1870 """Stop an active patch."""
1871 try:
1872 _patch._active_patches.remove(self)
1873 except ValueError:
1874 # If the patch hasn't been started this will fail
1875 pass
1876
1877 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001878
1879
1880def _clear_dict(in_dict):
1881 try:
1882 in_dict.clear()
1883 except AttributeError:
1884 keys = list(in_dict)
1885 for key in keys:
1886 del in_dict[key]
1887
1888
Michael Foordf7c41582012-06-10 20:36:32 +01001889def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001890 """Stop all active patches. LIFO to unroll nested patches."""
1891 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001892 patch.stop()
1893
1894
Michael Foord345266a2012-03-14 12:24:34 -07001895patch.object = _patch_object
1896patch.dict = _patch_dict
1897patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001898patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001899patch.TEST_PREFIX = 'test'
1900
1901magic_methods = (
1902 "lt le gt ge eq ne "
1903 "getitem setitem delitem "
1904 "len contains iter "
1905 "hash str sizeof "
1906 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001907 # we added divmod and rdivmod here instead of numerics
1908 # because there is no idivmod
1909 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001910 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001911 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001912 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001913 "fspath "
Lisa Roach9a7d9512019-09-28 18:42:44 -07001914 "aiter "
Michael Foord345266a2012-03-14 12:24:34 -07001915)
1916
Michael Foordd2623d72014-04-14 11:23:48 -04001917numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001918 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001919)
Michael Foord345266a2012-03-14 12:24:34 -07001920inplace = ' '.join('i%s' % n for n in numerics.split())
1921right = ' '.join('r%s' % n for n in numerics.split())
1922
1923# not including __prepare__, __instancecheck__, __subclasscheck__
1924# (as they are metaclass methods)
1925# __del__ is not supported at all as it causes problems if it exists
1926
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001927_non_defaults = {
1928 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1929 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1930 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1931 '__repr__', '__dir__', '__subclasses__', '__format__',
Lisa Roach8b03f942019-09-19 21:04:18 -07001932 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001933}
Michael Foord345266a2012-03-14 12:24:34 -07001934
1935
1936def _get_method(name, func):
1937 "Turns a callable object (like a mock) into a real function"
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001938 def method(self, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -07001939 return func(self, *args, **kw)
1940 method.__name__ = name
1941 return method
1942
1943
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001944_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001945 '__%s__' % method for method in
1946 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001947}
Michael Foord345266a2012-03-14 12:24:34 -07001948
Lisa Roach77b3b772019-05-20 09:19:53 -07001949# Magic methods used for async `with` statements
1950_async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
Lisa Roach8b03f942019-09-19 21:04:18 -07001951# Magic methods that are only used with async calls but are synchronous functions themselves
1952_sync_async_magics = {"__aiter__"}
1953_async_magics = _async_method_magics | _sync_async_magics
Lisa Roach77b3b772019-05-20 09:19:53 -07001954
Lisa Roach8b03f942019-09-19 21:04:18 -07001955_all_sync_magics = _magics | _non_defaults
1956_all_magics = _all_sync_magics | _async_magics
Michael Foord345266a2012-03-14 12:24:34 -07001957
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001958_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001959 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001960 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001961 '__instancecheck__', '__subclasscheck__',
1962 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001963}
Michael Foord345266a2012-03-14 12:24:34 -07001964
1965_calculate_return_value = {
1966 '__hash__': lambda self: object.__hash__(self),
1967 '__str__': lambda self: object.__str__(self),
1968 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001969 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001970}
1971
1972_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001973 '__lt__': NotImplemented,
1974 '__gt__': NotImplemented,
1975 '__le__': NotImplemented,
1976 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001977 '__int__': 1,
1978 '__contains__': False,
1979 '__len__': 0,
1980 '__exit__': False,
1981 '__complex__': 1j,
1982 '__float__': 1.0,
1983 '__bool__': True,
1984 '__index__': 1,
Lisa Roach77b3b772019-05-20 09:19:53 -07001985 '__aexit__': False,
Michael Foord345266a2012-03-14 12:24:34 -07001986}
1987
1988
1989def _get_eq(self):
1990 def __eq__(other):
1991 ret_val = self.__eq__._mock_return_value
1992 if ret_val is not DEFAULT:
1993 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001994 if self is other:
1995 return True
1996 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001997 return __eq__
1998
1999def _get_ne(self):
2000 def __ne__(other):
2001 if self.__ne__._mock_return_value is not DEFAULT:
2002 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02002003 if self is other:
2004 return False
2005 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07002006 return __ne__
2007
2008def _get_iter(self):
2009 def __iter__():
2010 ret_val = self.__iter__._mock_return_value
2011 if ret_val is DEFAULT:
2012 return iter([])
2013 # if ret_val was already an iterator, then calling iter on it should
2014 # return the iterator unchanged
2015 return iter(ret_val)
2016 return __iter__
2017
Lisa Roach77b3b772019-05-20 09:19:53 -07002018def _get_async_iter(self):
2019 def __aiter__():
2020 ret_val = self.__aiter__._mock_return_value
2021 if ret_val is DEFAULT:
2022 return _AsyncIterator(iter([]))
2023 return _AsyncIterator(iter(ret_val))
2024 return __aiter__
2025
Michael Foord345266a2012-03-14 12:24:34 -07002026_side_effect_methods = {
2027 '__eq__': _get_eq,
2028 '__ne__': _get_ne,
2029 '__iter__': _get_iter,
Lisa Roach77b3b772019-05-20 09:19:53 -07002030 '__aiter__': _get_async_iter
Michael Foord345266a2012-03-14 12:24:34 -07002031}
2032
2033
2034
2035def _set_return_value(mock, method, name):
2036 fixed = _return_values.get(name, DEFAULT)
2037 if fixed is not DEFAULT:
2038 method.return_value = fixed
2039 return
2040
marcoramirezmxa9187c32019-09-16 11:34:46 -05002041 return_calculator = _calculate_return_value.get(name)
2042 if return_calculator is not None:
2043 return_value = return_calculator(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002044 method.return_value = return_value
2045 return
2046
2047 side_effector = _side_effect_methods.get(name)
2048 if side_effector is not None:
2049 method.side_effect = side_effector(mock)
2050
2051
2052
Lisa Roach9a7d9512019-09-28 18:42:44 -07002053class MagicMixin(Base):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002054 def __init__(self, /, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07002055 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10002056 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07002057 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002058
2059
2060 def _mock_set_magics(self):
Lisa Roach9a7d9512019-09-28 18:42:44 -07002061 orig_magics = _magics | _async_method_magics
2062 these_magics = orig_magics
Michael Foord345266a2012-03-14 12:24:34 -07002063
Łukasz Langaa468db92015-04-13 23:12:42 -07002064 if getattr(self, "_mock_methods", None) is not None:
Lisa Roach9a7d9512019-09-28 18:42:44 -07002065 these_magics = orig_magics.intersection(self._mock_methods)
Michael Foord345266a2012-03-14 12:24:34 -07002066
2067 remove_magics = set()
Lisa Roach9a7d9512019-09-28 18:42:44 -07002068 remove_magics = orig_magics - these_magics
Michael Foord345266a2012-03-14 12:24:34 -07002069
2070 for entry in remove_magics:
2071 if entry in type(self).__dict__:
2072 # remove unneeded magic methods
2073 delattr(self, entry)
2074
2075 # don't overwrite existing attributes if called a second time
2076 these_magics = these_magics - set(type(self).__dict__)
2077
2078 _type = type(self)
2079 for entry in these_magics:
2080 setattr(_type, entry, MagicProxy(entry, self))
2081
2082
2083
2084class NonCallableMagicMock(MagicMixin, NonCallableMock):
2085 """A version of `MagicMock` that isn't callable."""
2086 def mock_add_spec(self, spec, spec_set=False):
2087 """Add a spec to a mock. `spec` can either be an object or a
2088 list of strings. Only attributes on the `spec` can be fetched as
2089 attributes from the mock.
2090
2091 If `spec_set` is True then only attributes on the spec can be set."""
2092 self._mock_add_spec(spec, spec_set)
2093 self._mock_set_magics()
2094
2095
Lisa Roach9a7d9512019-09-28 18:42:44 -07002096class AsyncMagicMixin(MagicMixin):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002097 def __init__(self, /, *args, **kw):
Lisa Roach9a7d9512019-09-28 18:42:44 -07002098 self._mock_set_magics() # make magic work for kwargs in init
Lisa Roach77b3b772019-05-20 09:19:53 -07002099 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)
Lisa Roach9a7d9512019-09-28 18:42:44 -07002100 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002101
Lisa Roach9a7d9512019-09-28 18:42:44 -07002102class MagicMock(MagicMixin, Mock):
Michael Foord345266a2012-03-14 12:24:34 -07002103 """
2104 MagicMock is a subclass of Mock with default implementations
2105 of most of the magic methods. You can use MagicMock without having to
2106 configure the magic methods yourself.
2107
2108 If you use the `spec` or `spec_set` arguments then *only* magic
2109 methods that exist in the spec will be created.
2110
2111 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
2112 """
2113 def mock_add_spec(self, spec, spec_set=False):
2114 """Add a spec to a mock. `spec` can either be an object or a
2115 list of strings. Only attributes on the `spec` can be fetched as
2116 attributes from the mock.
2117
2118 If `spec_set` is True then only attributes on the spec can be set."""
2119 self._mock_add_spec(spec, spec_set)
2120 self._mock_set_magics()
2121
2122
2123
Lisa Roach9a7d9512019-09-28 18:42:44 -07002124class MagicProxy(Base):
Michael Foord345266a2012-03-14 12:24:34 -07002125 def __init__(self, name, parent):
2126 self.name = name
2127 self.parent = parent
2128
Michael Foord345266a2012-03-14 12:24:34 -07002129 def create_mock(self):
2130 entry = self.name
2131 parent = self.parent
2132 m = parent._get_child_mock(name=entry, _new_name=entry,
2133 _new_parent=parent)
2134 setattr(parent, entry, m)
2135 _set_return_value(parent, m, entry)
2136 return m
2137
2138 def __get__(self, obj, _type=None):
2139 return self.create_mock()
2140
2141
Lisa Roach77b3b772019-05-20 09:19:53 -07002142class AsyncMockMixin(Base):
Lisa Roach77b3b772019-05-20 09:19:53 -07002143 await_count = _delegating_property('await_count')
2144 await_args = _delegating_property('await_args')
2145 await_args_list = _delegating_property('await_args_list')
2146
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002147 def __init__(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002148 super().__init__(*args, **kwargs)
2149 # asyncio.iscoroutinefunction() checks _is_coroutine property to say if an
2150 # object is a coroutine. Without this check it looks to see if it is a
2151 # function/method, which in this case it is not (since it is an
2152 # AsyncMock).
2153 # It is set through __dict__ because when spec_set is True, this
2154 # attribute is likely undefined.
2155 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
Lisa Roach77b3b772019-05-20 09:19:53 -07002156 self.__dict__['_mock_await_count'] = 0
2157 self.__dict__['_mock_await_args'] = None
2158 self.__dict__['_mock_await_args_list'] = _CallList()
2159 code_mock = NonCallableMock(spec_set=CodeType)
2160 code_mock.co_flags = inspect.CO_COROUTINE
2161 self.__dict__['__code__'] = code_mock
2162
Jason Fried046442d2019-11-20 16:27:51 -08002163 async def _execute_mock_call(self, /, *args, **kwargs):
2164 # This is nearly just like super(), except for sepcial handling
2165 # of coroutines
Lisa Roach77b3b772019-05-20 09:19:53 -07002166
2167 _call = self.call_args
Jason Fried046442d2019-11-20 16:27:51 -08002168 self.await_count += 1
2169 self.await_args = _call
2170 self.await_args_list.append(_call)
Lisa Roach77b3b772019-05-20 09:19:53 -07002171
Jason Fried046442d2019-11-20 16:27:51 -08002172 effect = self.side_effect
2173 if effect is not None:
2174 if _is_exception(effect):
2175 raise effect
2176 elif not _callable(effect):
2177 try:
2178 result = next(effect)
2179 except StopIteration:
2180 # It is impossible to propogate a StopIteration
2181 # through coroutines because of PEP 479
2182 raise StopAsyncIteration
2183 if _is_exception(result):
2184 raise result
2185 elif asyncio.iscoroutinefunction(effect):
2186 result = await effect(*args, **kwargs)
2187 else:
2188 result = effect(*args, **kwargs)
Lisa Roach77b3b772019-05-20 09:19:53 -07002189
Jason Fried046442d2019-11-20 16:27:51 -08002190 if result is not DEFAULT:
2191 return result
2192
2193 if self._mock_return_value is not DEFAULT:
2194 return self.return_value
2195
2196 if self._mock_wraps is not None:
2197 if asyncio.iscoroutinefunction(self._mock_wraps):
2198 return await self._mock_wraps(*args, **kwargs)
2199 return self._mock_wraps(*args, **kwargs)
2200
2201 return self.return_value
Lisa Roach77b3b772019-05-20 09:19:53 -07002202
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002203 def assert_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002204 """
2205 Assert that the mock was awaited at least once.
2206 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002207 if self.await_count == 0:
2208 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2209 raise AssertionError(msg)
2210
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002211 def assert_awaited_once(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002212 """
2213 Assert that the mock was awaited exactly once.
2214 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002215 if not self.await_count == 1:
2216 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2217 f" Awaited {self.await_count} times.")
2218 raise AssertionError(msg)
2219
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002220 def assert_awaited_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002221 """
2222 Assert that the last await was with the specified arguments.
2223 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002224 if self.await_args is None:
2225 expected = self._format_mock_call_signature(args, kwargs)
2226 raise AssertionError(f'Expected await: {expected}\nNot awaited')
2227
2228 def _error_message():
Xtreak0ae022c2019-05-29 12:32:26 +05302229 msg = self._format_mock_failure_message(args, kwargs, action='await')
Lisa Roach77b3b772019-05-20 09:19:53 -07002230 return msg
2231
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002232 expected = self._call_matcher(_Call((args, kwargs), two=True))
Lisa Roach77b3b772019-05-20 09:19:53 -07002233 actual = self._call_matcher(self.await_args)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002234 if actual != expected:
Lisa Roach77b3b772019-05-20 09:19:53 -07002235 cause = expected if isinstance(expected, Exception) else None
2236 raise AssertionError(_error_message()) from cause
2237
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002238 def assert_awaited_once_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002239 """
2240 Assert that the mock was awaited exactly once and with the specified
2241 arguments.
2242 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002243 if not self.await_count == 1:
2244 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2245 f" Awaited {self.await_count} times.")
2246 raise AssertionError(msg)
2247 return self.assert_awaited_with(*args, **kwargs)
2248
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002249 def assert_any_await(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002250 """
2251 Assert the mock has ever been awaited with the specified arguments.
2252 """
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002253 expected = self._call_matcher(_Call((args, kwargs), two=True))
2254 cause = expected if isinstance(expected, Exception) else None
Lisa Roach77b3b772019-05-20 09:19:53 -07002255 actual = [self._call_matcher(c) for c in self.await_args_list]
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002256 if cause or expected not in _AnyComparer(actual):
Lisa Roach77b3b772019-05-20 09:19:53 -07002257 expected_string = self._format_mock_call_signature(args, kwargs)
2258 raise AssertionError(
2259 '%s await not found' % expected_string
2260 ) from cause
2261
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002262 def assert_has_awaits(self, calls, any_order=False):
Lisa Roach77b3b772019-05-20 09:19:53 -07002263 """
2264 Assert the mock has been awaited with the specified calls.
2265 The :attr:`await_args_list` list is checked for the awaits.
2266
2267 If `any_order` is False (the default) then the awaits must be
2268 sequential. There can be extra calls before or after the
2269 specified awaits.
2270
2271 If `any_order` is True then the awaits can be in any order, but
2272 they must all appear in :attr:`await_args_list`.
2273 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002274 expected = [self._call_matcher(c) for c in calls]
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002275 cause = next((e for e in expected if isinstance(e, Exception)), None)
Lisa Roach77b3b772019-05-20 09:19:53 -07002276 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2277 if not any_order:
2278 if expected not in all_awaits:
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002279 if cause is None:
2280 problem = 'Awaits not found.'
2281 else:
2282 problem = ('Error processing expected awaits.\n'
2283 'Errors: {}').format(
2284 [e if isinstance(e, Exception) else None
2285 for e in expected])
Lisa Roach77b3b772019-05-20 09:19:53 -07002286 raise AssertionError(
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002287 f'{problem}\n'
2288 f'Expected: {_CallList(calls)}\n'
Lisa Roach77b3b772019-05-20 09:19:53 -07002289 f'Actual: {self.await_args_list}'
2290 ) from cause
2291 return
2292
2293 all_awaits = list(all_awaits)
2294
2295 not_found = []
2296 for kall in expected:
2297 try:
2298 all_awaits.remove(kall)
2299 except ValueError:
2300 not_found.append(kall)
2301 if not_found:
2302 raise AssertionError(
2303 '%r not all found in await list' % (tuple(not_found),)
2304 ) from cause
2305
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002306 def assert_not_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002307 """
2308 Assert that the mock was never awaited.
2309 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002310 if self.await_count != 0:
Xtreakff6b2e62019-05-27 18:26:23 +05302311 msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
Lisa Roach77b3b772019-05-20 09:19:53 -07002312 f" Awaited {self.await_count} times.")
2313 raise AssertionError(msg)
2314
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002315 def reset_mock(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002316 """
2317 See :func:`.Mock.reset_mock()`
2318 """
2319 super().reset_mock(*args, **kwargs)
2320 self.await_count = 0
2321 self.await_args = None
2322 self.await_args_list = _CallList()
2323
2324
2325class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2326 """
2327 Enhance :class:`Mock` with features allowing to mock
2328 an async function.
2329
2330 The :class:`AsyncMock` object will behave so the object is
2331 recognized as an async function, and the result of a call is an awaitable:
2332
2333 >>> mock = AsyncMock()
2334 >>> asyncio.iscoroutinefunction(mock)
2335 True
2336 >>> inspect.isawaitable(mock())
2337 True
2338
2339
2340 The result of ``mock()`` is an async function which will have the outcome
2341 of ``side_effect`` or ``return_value``:
2342
2343 - if ``side_effect`` is a function, the async function will return the
2344 result of that function,
2345 - if ``side_effect`` is an exception, the async function will raise the
2346 exception,
2347 - if ``side_effect`` is an iterable, the async function will return the
2348 next value of the iterable, however, if the sequence of result is
2349 exhausted, ``StopIteration`` is raised immediately,
2350 - if ``side_effect`` is not defined, the async function will return the
2351 value defined by ``return_value``, hence, by default, the async function
2352 returns a new :class:`AsyncMock` object.
2353
2354 If the outcome of ``side_effect`` or ``return_value`` is an async function,
2355 the mock async function obtained when the mock object is called will be this
2356 async function itself (and not an async function returning an async
2357 function).
2358
2359 The test author can also specify a wrapped object with ``wraps``. In this
2360 case, the :class:`Mock` object behavior is the same as with an
2361 :class:`.Mock` object: the wrapped object may have methods
2362 defined as async function functions.
2363
Xtreake7cb23b2019-05-21 14:17:17 +05302364 Based on Martin Richard's asynctest project.
Lisa Roach77b3b772019-05-20 09:19:53 -07002365 """
2366
Michael Foord345266a2012-03-14 12:24:34 -07002367
2368class _ANY(object):
2369 "A helper object that compares equal to everything."
2370
2371 def __eq__(self, other):
2372 return True
2373
2374 def __ne__(self, other):
2375 return False
2376
2377 def __repr__(self):
2378 return '<ANY>'
2379
2380ANY = _ANY()
2381
2382
2383
2384def _format_call_signature(name, args, kwargs):
2385 message = '%s(%%s)' % name
2386 formatted_args = ''
2387 args_string = ', '.join([repr(arg) for arg in args])
2388 kwargs_string = ', '.join([
Xtreak9d607062019-09-09 16:25:22 +05302389 '%s=%r' % (key, value) for key, value in kwargs.items()
Michael Foord345266a2012-03-14 12:24:34 -07002390 ])
2391 if args_string:
2392 formatted_args = args_string
2393 if kwargs_string:
2394 if formatted_args:
2395 formatted_args += ', '
2396 formatted_args += kwargs_string
2397
2398 return message % formatted_args
2399
2400
2401
2402class _Call(tuple):
2403 """
2404 A tuple for holding the results of a call to a mock, either in the form
2405 `(args, kwargs)` or `(name, args, kwargs)`.
2406
2407 If args or kwargs are empty then a call tuple will compare equal to
2408 a tuple without those values. This makes comparisons less verbose::
2409
2410 _Call(('name', (), {})) == ('name',)
2411 _Call(('name', (1,), {})) == ('name', (1,))
2412 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2413
2414 The `_Call` object provides a useful shortcut for comparing with call::
2415
2416 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2417 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2418
2419 If the _Call has no name then it will match any name.
2420 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002421 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002422 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002423 args = ()
2424 kwargs = {}
2425 _len = len(value)
2426 if _len == 3:
2427 name, args, kwargs = value
2428 elif _len == 2:
2429 first, second = value
2430 if isinstance(first, str):
2431 name = first
2432 if isinstance(second, tuple):
2433 args = second
2434 else:
2435 kwargs = second
2436 else:
2437 args, kwargs = first, second
2438 elif _len == 1:
2439 value, = value
2440 if isinstance(value, str):
2441 name = value
2442 elif isinstance(value, tuple):
2443 args = value
2444 else:
2445 kwargs = value
2446
2447 if two:
2448 return tuple.__new__(cls, (args, kwargs))
2449
2450 return tuple.__new__(cls, (name, args, kwargs))
2451
2452
2453 def __init__(self, value=(), name=None, parent=None, two=False,
2454 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002455 self._mock_name = name
2456 self._mock_parent = parent
2457 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002458
2459
2460 def __eq__(self, other):
Michael Foord345266a2012-03-14 12:24:34 -07002461 try:
2462 len_other = len(other)
2463 except TypeError:
Serhiy Storchaka662db122019-08-08 08:42:54 +03002464 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07002465
2466 self_name = ''
2467 if len(self) == 2:
2468 self_args, self_kwargs = self
2469 else:
2470 self_name, self_args, self_kwargs = self
2471
Andrew Dunaie63e6172018-12-04 11:08:45 +02002472 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2473 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002474 return False
2475
Michael Foord345266a2012-03-14 12:24:34 -07002476 other_name = ''
2477 if len_other == 0:
2478 other_args, other_kwargs = (), {}
2479 elif len_other == 3:
2480 other_name, other_args, other_kwargs = other
2481 elif len_other == 1:
2482 value, = other
2483 if isinstance(value, tuple):
2484 other_args = value
2485 other_kwargs = {}
2486 elif isinstance(value, str):
2487 other_name = value
2488 other_args, other_kwargs = (), {}
2489 else:
2490 other_args = ()
2491 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002492 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002493 # could be (name, args) or (name, kwargs) or (args, kwargs)
2494 first, second = other
2495 if isinstance(first, str):
2496 other_name = first
2497 if isinstance(second, tuple):
2498 other_args, other_kwargs = second, {}
2499 else:
2500 other_args, other_kwargs = (), second
2501 else:
2502 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002503 else:
2504 return False
Michael Foord345266a2012-03-14 12:24:34 -07002505
2506 if self_name and other_name != self_name:
2507 return False
2508
2509 # this order is important for ANY to work!
2510 return (other_args, other_kwargs) == (self_args, self_kwargs)
2511
2512
Berker Peksagce913872016-03-28 00:30:02 +03002513 __ne__ = object.__ne__
2514
2515
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002516 def __call__(self, /, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002517 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002518 return _Call(('', args, kwargs), name='()')
2519
Andrew Dunaie63e6172018-12-04 11:08:45 +02002520 name = self._mock_name + '()'
2521 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002522
2523
2524 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002525 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002526 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002527 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002528 return _Call(name=name, parent=self, from_kall=False)
2529
2530
blhsing72c35992019-09-11 07:28:06 -07002531 def __getattribute__(self, attr):
2532 if attr in tuple.__dict__:
2533 raise AttributeError
2534 return tuple.__getattribute__(self, attr)
2535
2536
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002537 def count(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302538 return self.__getattr__('count')(*args, **kwargs)
2539
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002540 def index(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302541 return self.__getattr__('index')(*args, **kwargs)
2542
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302543 def _get_call_arguments(self):
2544 if len(self) == 2:
2545 args, kwargs = self
2546 else:
2547 name, args, kwargs = self
2548
2549 return args, kwargs
2550
2551 @property
2552 def args(self):
2553 return self._get_call_arguments()[0]
2554
2555 @property
2556 def kwargs(self):
2557 return self._get_call_arguments()[1]
2558
Michael Foord345266a2012-03-14 12:24:34 -07002559 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002560 if not self._mock_from_kall:
2561 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002562 if name.startswith('()'):
2563 name = 'call%s' % name
2564 return name
2565
2566 if len(self) == 2:
2567 name = 'call'
2568 args, kwargs = self
2569 else:
2570 name, args, kwargs = self
2571 if not name:
2572 name = 'call'
2573 elif not name.startswith('()'):
2574 name = 'call.%s' % name
2575 else:
2576 name = 'call%s' % name
2577 return _format_call_signature(name, args, kwargs)
2578
2579
2580 def call_list(self):
2581 """For a call object that represents multiple calls, `call_list`
2582 returns a list of all the intermediate calls as well as the
2583 final call."""
2584 vals = []
2585 thing = self
2586 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002587 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002588 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002589 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002590 return _CallList(reversed(vals))
2591
2592
2593call = _Call(from_kall=False)
2594
2595
Michael Foord345266a2012-03-14 12:24:34 -07002596def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2597 _name=None, **kwargs):
2598 """Create a mock object using another object as a spec. Attributes on the
2599 mock will use the corresponding attribute on the `spec` object as their
2600 spec.
2601
2602 Functions or methods being mocked will have their arguments checked
2603 to check that they are called with the correct signature.
2604
2605 If `spec_set` is True then attempting to set attributes that don't exist
2606 on the spec object will raise an `AttributeError`.
2607
2608 If a class is used as a spec then the return value of the mock (the
2609 instance of the class) will have the same spec. You can use a class as the
2610 spec for an instance object by passing `instance=True`. The returned mock
2611 will only be callable if instances of the mock are callable.
2612
2613 `create_autospec` also takes arbitrary keyword arguments that are passed to
2614 the constructor of the created mock."""
2615 if _is_list(spec):
2616 # can't pass a list instance to the mock constructor as it will be
2617 # interpreted as a list of strings
2618 spec = type(spec)
2619
2620 is_type = isinstance(spec, type)
Xtreakff6b2e62019-05-27 18:26:23 +05302621 is_async_func = _is_async_func(spec)
Michael Foord345266a2012-03-14 12:24:34 -07002622 _kwargs = {'spec': spec}
2623 if spec_set:
2624 _kwargs = {'spec_set': spec}
2625 elif spec is None:
2626 # None we mock with a normal mock without a spec
2627 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002628 if _kwargs and instance:
2629 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002630
2631 _kwargs.update(kwargs)
2632
2633 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002634 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002635 # descriptors don't have a spec
2636 # because we don't know what type they return
2637 _kwargs = {}
Lisa Roach77b3b772019-05-20 09:19:53 -07002638 elif is_async_func:
2639 if instance:
2640 raise RuntimeError("Instance can not be True when create_autospec "
2641 "is mocking an async function")
2642 Klass = AsyncMock
Michael Foord345266a2012-03-14 12:24:34 -07002643 elif not _callable(spec):
2644 Klass = NonCallableMagicMock
2645 elif is_type and instance and not _instance_callable(spec):
2646 Klass = NonCallableMagicMock
2647
Kushal Das484f8a82014-04-16 01:05:50 +05302648 _name = _kwargs.pop('name', _name)
2649
Michael Foord345266a2012-03-14 12:24:34 -07002650 _new_name = _name
2651 if _parent is None:
2652 # for a top level object no _new_name should be set
2653 _new_name = ''
2654
2655 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2656 name=_name, **_kwargs)
2657
2658 if isinstance(spec, FunctionTypes):
2659 # should only happen at the top level because we don't
2660 # recurse for functions
2661 mock = _set_signature(mock, spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07002662 if is_async_func:
Xtreakff6b2e62019-05-27 18:26:23 +05302663 _setup_async_mock(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002664 else:
2665 _check_signature(spec, mock, is_type, instance)
2666
2667 if _parent is not None and not instance:
2668 _parent._mock_children[_name] = mock
2669
2670 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002671 mock.return_value = create_autospec(spec, spec_set, instance=True,
2672 _name='()', _parent=mock)
2673
2674 for entry in dir(spec):
2675 if _is_magic(entry):
2676 # MagicMock already does the useful magic methods for us
2677 continue
2678
Michael Foord345266a2012-03-14 12:24:34 -07002679 # XXXX do we need a better way of getting attributes without
2680 # triggering code execution (?) Probably not - we need the actual
2681 # object to mock it so we would rather trigger a property than mock
2682 # the property descriptor. Likewise we want to mock out dynamically
2683 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002684 # XXXX what about attributes that raise exceptions other than
2685 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002686 # we could be resilient against it, or catch and propagate the
2687 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002688 try:
2689 original = getattr(spec, entry)
2690 except AttributeError:
2691 continue
Michael Foord345266a2012-03-14 12:24:34 -07002692
2693 kwargs = {'spec': original}
2694 if spec_set:
2695 kwargs = {'spec_set': original}
2696
2697 if not isinstance(original, FunctionTypes):
2698 new = _SpecState(original, spec_set, mock, entry, instance)
2699 mock._mock_children[entry] = new
2700 else:
2701 parent = mock
2702 if isinstance(spec, FunctionTypes):
2703 parent = mock.mock
2704
Michael Foord345266a2012-03-14 12:24:34 -07002705 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002706 kwargs['_eat_self'] = skipfirst
Lisa Roach77b3b772019-05-20 09:19:53 -07002707 if asyncio.iscoroutinefunction(original):
2708 child_klass = AsyncMock
2709 else:
2710 child_klass = MagicMock
2711 new = child_klass(parent=parent, name=entry, _new_name=entry,
2712 _new_parent=parent,
2713 **kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002714 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002715 _check_signature(original, new, skipfirst=skipfirst)
2716
2717 # so functions created with _set_signature become instance attributes,
2718 # *plus* their underlying mock exists in _mock_children of the parent
2719 # mock. Adding to _mock_children may be unnecessary where we are also
2720 # setting as an instance attribute?
2721 if isinstance(new, FunctionTypes):
2722 setattr(mock, entry, new)
2723
2724 return mock
2725
2726
2727def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002728 """
2729 Return whether we should skip the first argument on spec's `entry`
2730 attribute.
2731 """
Michael Foord345266a2012-03-14 12:24:34 -07002732 if not isinstance(spec, type):
2733 if entry in getattr(spec, '__dict__', {}):
2734 # instance attribute - shouldn't skip
2735 return False
Michael Foord345266a2012-03-14 12:24:34 -07002736 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002737
2738 for klass in spec.__mro__:
2739 result = klass.__dict__.get(entry, DEFAULT)
2740 if result is DEFAULT:
2741 continue
2742 if isinstance(result, (staticmethod, classmethod)):
2743 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002744 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2745 # Normal method => skip if looked up on type
2746 # (if looked up on instance, self is already skipped)
2747 return is_type
2748 else:
2749 return False
Michael Foord345266a2012-03-14 12:24:34 -07002750
Chris Withersadbf1782019-05-01 23:04:04 +01002751 # function is a dynamically provided attribute
Michael Foord345266a2012-03-14 12:24:34 -07002752 return is_type
2753
2754
Michael Foord345266a2012-03-14 12:24:34 -07002755class _SpecState(object):
2756
2757 def __init__(self, spec, spec_set=False, parent=None,
2758 name=None, ids=None, instance=False):
2759 self.spec = spec
2760 self.ids = ids
2761 self.spec_set = spec_set
2762 self.parent = parent
2763 self.instance = instance
2764 self.name = name
2765
2766
2767FunctionTypes = (
2768 # python function
2769 type(create_autospec),
2770 # instance method
2771 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002772)
2773
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002774MethodWrapperTypes = (
2775 type(ANY.__eq__.__get__),
2776)
2777
Michael Foord345266a2012-03-14 12:24:34 -07002778
Michael Foorda74561a2012-03-25 19:03:13 +01002779file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002780
Michael Foord04cbe0c2013-03-19 17:22:51 -07002781
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002782def _to_stream(read_data):
2783 if isinstance(read_data, bytes):
2784 return io.BytesIO(read_data)
Michael Foord04cbe0c2013-03-19 17:22:51 -07002785 else:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002786 return io.StringIO(read_data)
Michael Foord0dccf652012-03-25 19:11:50 +01002787
Robert Collins5329aaa2015-07-17 20:08:45 +12002788
Michael Foord0dccf652012-03-25 19:11:50 +01002789def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002790 """
2791 A helper function to create a mock to replace the use of `open`. It works
2792 for `open` called directly or used as a context manager.
2793
2794 The `mock` argument is the mock object to configure. If `None` (the
2795 default) then a `MagicMock` will be created for you, with the API limited
2796 to methods or attributes available on standard file handles.
2797
Xtreak71f82a22018-12-20 21:30:21 +05302798 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002799 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002800 """
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002801 _read_data = _to_stream(read_data)
2802 _state = [_read_data, None]
2803
Robert Collinsca647ef2015-07-24 03:48:20 +12002804 def _readlines_side_effect(*args, **kwargs):
2805 if handle.readlines.return_value is not None:
2806 return handle.readlines.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002807 return _state[0].readlines(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002808
2809 def _read_side_effect(*args, **kwargs):
2810 if handle.read.return_value is not None:
2811 return handle.read.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002812 return _state[0].read(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002813
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002814 def _readline_side_effect(*args, **kwargs):
Tony Flury20870232018-09-12 23:21:16 +01002815 yield from _iter_side_effect()
2816 while True:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002817 yield _state[0].readline(*args, **kwargs)
Tony Flury20870232018-09-12 23:21:16 +01002818
2819 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002820 if handle.readline.return_value is not None:
2821 while True:
2822 yield handle.readline.return_value
2823 for line in _state[0]:
2824 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002825
Damien Nadé394119a2019-05-23 12:03:25 +02002826 def _next_side_effect():
2827 if handle.readline.return_value is not None:
2828 return handle.readline.return_value
2829 return next(_state[0])
2830
Michael Foorda74561a2012-03-25 19:03:13 +01002831 global file_spec
2832 if file_spec is None:
2833 import _io
2834 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2835
Michael Foord345266a2012-03-14 12:24:34 -07002836 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002837 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002838
Robert Collinsca647ef2015-07-24 03:48:20 +12002839 handle = MagicMock(spec=file_spec)
2840 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002841
Robert Collinsca647ef2015-07-24 03:48:20 +12002842 handle.write.return_value = None
2843 handle.read.return_value = None
2844 handle.readline.return_value = None
2845 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002846
Robert Collinsca647ef2015-07-24 03:48:20 +12002847 handle.read.side_effect = _read_side_effect
2848 _state[1] = _readline_side_effect()
2849 handle.readline.side_effect = _state[1]
2850 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002851 handle.__iter__.side_effect = _iter_side_effect
Damien Nadé394119a2019-05-23 12:03:25 +02002852 handle.__next__.side_effect = _next_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002853
Robert Collinsca647ef2015-07-24 03:48:20 +12002854 def reset_data(*args, **kwargs):
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002855 _state[0] = _to_stream(read_data)
Robert Collinsca647ef2015-07-24 03:48:20 +12002856 if handle.readline.side_effect == _state[1]:
2857 # Only reset the side effect if the user hasn't overridden it.
2858 _state[1] = _readline_side_effect()
2859 handle.readline.side_effect = _state[1]
2860 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002861
Robert Collinsca647ef2015-07-24 03:48:20 +12002862 mock.side_effect = reset_data
2863 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002864 return mock
2865
2866
2867class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002868 """
2869 A mock intended to be used as a property, or other descriptor, on a class.
2870 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2871 a return value when it is fetched.
2872
2873 Fetching a `PropertyMock` instance from an object calls the mock, with
2874 no args. Setting it calls the mock with the value being set.
2875 """
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002876 def _get_child_mock(self, /, **kwargs):
Michael Foordc2870622012-04-13 16:57:22 +01002877 return MagicMock(**kwargs)
2878
Raymond Hettinger0dac68f2019-08-29 01:27:42 -07002879 def __get__(self, obj, obj_type=None):
Michael Foord345266a2012-03-14 12:24:34 -07002880 return self()
2881 def __set__(self, obj, val):
2882 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002883
2884
2885def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002886 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002887
2888 Given an input Mock, seals it to ensure no further mocks will be generated
2889 when accessing an attribute that was not already defined.
2890
Mario Corchero96200eb2018-10-19 22:57:37 +01002891 The operation recursively seals the mock passed in, meaning that
2892 the mock itself, any mocks generated by accessing one of its attributes,
2893 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002894 """
2895 mock._mock_sealed = True
2896 for attr in dir(mock):
2897 try:
2898 m = getattr(mock, attr)
2899 except AttributeError:
2900 continue
2901 if not isinstance(m, NonCallableMock):
2902 continue
2903 if m._mock_new_parent is mock:
2904 seal(m)
Lisa Roach77b3b772019-05-20 09:19:53 -07002905
2906
Lisa Roach77b3b772019-05-20 09:19:53 -07002907class _AsyncIterator:
2908 """
2909 Wraps an iterator in an asynchronous iterator.
2910 """
2911 def __init__(self, iterator):
2912 self.iterator = iterator
2913 code_mock = NonCallableMock(spec_set=CodeType)
2914 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
2915 self.__dict__['__code__'] = code_mock
2916
2917 def __aiter__(self):
2918 return self
2919
2920 async def __anext__(self):
2921 try:
2922 return next(self.iterator)
2923 except StopIteration:
2924 pass
2925 raise StopAsyncIteration