blob: 1acafc51df1d649257efd3fde9f469556cf70971 [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):
Karthikeyan Singaravelan72b10042020-01-27 12:18:15 +05302036 # If _mock_wraps is present then attach it so that wrapped object
2037 # is used for return value is used when called.
2038 if mock._mock_wraps is not None:
2039 method._mock_wraps = getattr(mock._mock_wraps, name)
2040 return
2041
Michael Foord345266a2012-03-14 12:24:34 -07002042 fixed = _return_values.get(name, DEFAULT)
2043 if fixed is not DEFAULT:
2044 method.return_value = fixed
2045 return
2046
marcoramirezmxa9187c32019-09-16 11:34:46 -05002047 return_calculator = _calculate_return_value.get(name)
2048 if return_calculator is not None:
2049 return_value = return_calculator(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002050 method.return_value = return_value
2051 return
2052
2053 side_effector = _side_effect_methods.get(name)
2054 if side_effector is not None:
2055 method.side_effect = side_effector(mock)
2056
2057
2058
Lisa Roach9a7d9512019-09-28 18:42:44 -07002059class MagicMixin(Base):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002060 def __init__(self, /, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07002061 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10002062 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07002063 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002064
2065
2066 def _mock_set_magics(self):
Lisa Roach9a7d9512019-09-28 18:42:44 -07002067 orig_magics = _magics | _async_method_magics
2068 these_magics = orig_magics
Michael Foord345266a2012-03-14 12:24:34 -07002069
Łukasz Langaa468db92015-04-13 23:12:42 -07002070 if getattr(self, "_mock_methods", None) is not None:
Lisa Roach9a7d9512019-09-28 18:42:44 -07002071 these_magics = orig_magics.intersection(self._mock_methods)
Michael Foord345266a2012-03-14 12:24:34 -07002072
2073 remove_magics = set()
Lisa Roach9a7d9512019-09-28 18:42:44 -07002074 remove_magics = orig_magics - these_magics
Michael Foord345266a2012-03-14 12:24:34 -07002075
2076 for entry in remove_magics:
2077 if entry in type(self).__dict__:
2078 # remove unneeded magic methods
2079 delattr(self, entry)
2080
2081 # don't overwrite existing attributes if called a second time
2082 these_magics = these_magics - set(type(self).__dict__)
2083
2084 _type = type(self)
2085 for entry in these_magics:
2086 setattr(_type, entry, MagicProxy(entry, self))
2087
2088
2089
2090class NonCallableMagicMock(MagicMixin, NonCallableMock):
2091 """A version of `MagicMock` that isn't callable."""
2092 def mock_add_spec(self, spec, spec_set=False):
2093 """Add a spec to a mock. `spec` can either be an object or a
2094 list of strings. Only attributes on the `spec` can be fetched as
2095 attributes from the mock.
2096
2097 If `spec_set` is True then only attributes on the spec can be set."""
2098 self._mock_add_spec(spec, spec_set)
2099 self._mock_set_magics()
2100
2101
Lisa Roach9a7d9512019-09-28 18:42:44 -07002102class AsyncMagicMixin(MagicMixin):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002103 def __init__(self, /, *args, **kw):
Lisa Roach9a7d9512019-09-28 18:42:44 -07002104 self._mock_set_magics() # make magic work for kwargs in init
Lisa Roach77b3b772019-05-20 09:19:53 -07002105 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)
Lisa Roach9a7d9512019-09-28 18:42:44 -07002106 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002107
Lisa Roach9a7d9512019-09-28 18:42:44 -07002108class MagicMock(MagicMixin, Mock):
Michael Foord345266a2012-03-14 12:24:34 -07002109 """
2110 MagicMock is a subclass of Mock with default implementations
2111 of most of the magic methods. You can use MagicMock without having to
2112 configure the magic methods yourself.
2113
2114 If you use the `spec` or `spec_set` arguments then *only* magic
2115 methods that exist in the spec will be created.
2116
2117 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
2118 """
2119 def mock_add_spec(self, spec, spec_set=False):
2120 """Add a spec to a mock. `spec` can either be an object or a
2121 list of strings. Only attributes on the `spec` can be fetched as
2122 attributes from the mock.
2123
2124 If `spec_set` is True then only attributes on the spec can be set."""
2125 self._mock_add_spec(spec, spec_set)
2126 self._mock_set_magics()
2127
2128
2129
Lisa Roach9a7d9512019-09-28 18:42:44 -07002130class MagicProxy(Base):
Michael Foord345266a2012-03-14 12:24:34 -07002131 def __init__(self, name, parent):
2132 self.name = name
2133 self.parent = parent
2134
Michael Foord345266a2012-03-14 12:24:34 -07002135 def create_mock(self):
2136 entry = self.name
2137 parent = self.parent
2138 m = parent._get_child_mock(name=entry, _new_name=entry,
2139 _new_parent=parent)
2140 setattr(parent, entry, m)
2141 _set_return_value(parent, m, entry)
2142 return m
2143
2144 def __get__(self, obj, _type=None):
2145 return self.create_mock()
2146
2147
Lisa Roach77b3b772019-05-20 09:19:53 -07002148class AsyncMockMixin(Base):
Lisa Roach77b3b772019-05-20 09:19:53 -07002149 await_count = _delegating_property('await_count')
2150 await_args = _delegating_property('await_args')
2151 await_args_list = _delegating_property('await_args_list')
2152
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002153 def __init__(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002154 super().__init__(*args, **kwargs)
2155 # asyncio.iscoroutinefunction() checks _is_coroutine property to say if an
2156 # object is a coroutine. Without this check it looks to see if it is a
2157 # function/method, which in this case it is not (since it is an
2158 # AsyncMock).
2159 # It is set through __dict__ because when spec_set is True, this
2160 # attribute is likely undefined.
2161 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
Lisa Roach77b3b772019-05-20 09:19:53 -07002162 self.__dict__['_mock_await_count'] = 0
2163 self.__dict__['_mock_await_args'] = None
2164 self.__dict__['_mock_await_args_list'] = _CallList()
2165 code_mock = NonCallableMock(spec_set=CodeType)
2166 code_mock.co_flags = inspect.CO_COROUTINE
2167 self.__dict__['__code__'] = code_mock
2168
Jason Fried046442d2019-11-20 16:27:51 -08002169 async def _execute_mock_call(self, /, *args, **kwargs):
2170 # This is nearly just like super(), except for sepcial handling
2171 # of coroutines
Lisa Roach77b3b772019-05-20 09:19:53 -07002172
2173 _call = self.call_args
Jason Fried046442d2019-11-20 16:27:51 -08002174 self.await_count += 1
2175 self.await_args = _call
2176 self.await_args_list.append(_call)
Lisa Roach77b3b772019-05-20 09:19:53 -07002177
Jason Fried046442d2019-11-20 16:27:51 -08002178 effect = self.side_effect
2179 if effect is not None:
2180 if _is_exception(effect):
2181 raise effect
2182 elif not _callable(effect):
2183 try:
2184 result = next(effect)
2185 except StopIteration:
2186 # It is impossible to propogate a StopIteration
2187 # through coroutines because of PEP 479
2188 raise StopAsyncIteration
2189 if _is_exception(result):
2190 raise result
2191 elif asyncio.iscoroutinefunction(effect):
2192 result = await effect(*args, **kwargs)
2193 else:
2194 result = effect(*args, **kwargs)
Lisa Roach77b3b772019-05-20 09:19:53 -07002195
Jason Fried046442d2019-11-20 16:27:51 -08002196 if result is not DEFAULT:
2197 return result
2198
2199 if self._mock_return_value is not DEFAULT:
2200 return self.return_value
2201
2202 if self._mock_wraps is not None:
2203 if asyncio.iscoroutinefunction(self._mock_wraps):
2204 return await self._mock_wraps(*args, **kwargs)
2205 return self._mock_wraps(*args, **kwargs)
2206
2207 return self.return_value
Lisa Roach77b3b772019-05-20 09:19:53 -07002208
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002209 def assert_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002210 """
2211 Assert that the mock was awaited at least once.
2212 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002213 if self.await_count == 0:
2214 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2215 raise AssertionError(msg)
2216
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002217 def assert_awaited_once(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002218 """
2219 Assert that the mock was awaited exactly once.
2220 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002221 if not self.await_count == 1:
2222 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2223 f" Awaited {self.await_count} times.")
2224 raise AssertionError(msg)
2225
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002226 def assert_awaited_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002227 """
2228 Assert that the last await was with the specified arguments.
2229 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002230 if self.await_args is None:
2231 expected = self._format_mock_call_signature(args, kwargs)
2232 raise AssertionError(f'Expected await: {expected}\nNot awaited')
2233
2234 def _error_message():
Xtreak0ae022c2019-05-29 12:32:26 +05302235 msg = self._format_mock_failure_message(args, kwargs, action='await')
Lisa Roach77b3b772019-05-20 09:19:53 -07002236 return msg
2237
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002238 expected = self._call_matcher(_Call((args, kwargs), two=True))
Lisa Roach77b3b772019-05-20 09:19:53 -07002239 actual = self._call_matcher(self.await_args)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002240 if actual != expected:
Lisa Roach77b3b772019-05-20 09:19:53 -07002241 cause = expected if isinstance(expected, Exception) else None
2242 raise AssertionError(_error_message()) from cause
2243
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002244 def assert_awaited_once_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002245 """
2246 Assert that the mock was awaited exactly once and with the specified
2247 arguments.
2248 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002249 if not self.await_count == 1:
2250 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2251 f" Awaited {self.await_count} times.")
2252 raise AssertionError(msg)
2253 return self.assert_awaited_with(*args, **kwargs)
2254
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002255 def assert_any_await(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002256 """
2257 Assert the mock has ever been awaited with the specified arguments.
2258 """
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002259 expected = self._call_matcher(_Call((args, kwargs), two=True))
2260 cause = expected if isinstance(expected, Exception) else None
Lisa Roach77b3b772019-05-20 09:19:53 -07002261 actual = [self._call_matcher(c) for c in self.await_args_list]
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002262 if cause or expected not in _AnyComparer(actual):
Lisa Roach77b3b772019-05-20 09:19:53 -07002263 expected_string = self._format_mock_call_signature(args, kwargs)
2264 raise AssertionError(
2265 '%s await not found' % expected_string
2266 ) from cause
2267
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002268 def assert_has_awaits(self, calls, any_order=False):
Lisa Roach77b3b772019-05-20 09:19:53 -07002269 """
2270 Assert the mock has been awaited with the specified calls.
2271 The :attr:`await_args_list` list is checked for the awaits.
2272
2273 If `any_order` is False (the default) then the awaits must be
2274 sequential. There can be extra calls before or after the
2275 specified awaits.
2276
2277 If `any_order` is True then the awaits can be in any order, but
2278 they must all appear in :attr:`await_args_list`.
2279 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002280 expected = [self._call_matcher(c) for c in calls]
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002281 cause = next((e for e in expected if isinstance(e, Exception)), None)
Lisa Roach77b3b772019-05-20 09:19:53 -07002282 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2283 if not any_order:
2284 if expected not in all_awaits:
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002285 if cause is None:
2286 problem = 'Awaits not found.'
2287 else:
2288 problem = ('Error processing expected awaits.\n'
2289 'Errors: {}').format(
2290 [e if isinstance(e, Exception) else None
2291 for e in expected])
Lisa Roach77b3b772019-05-20 09:19:53 -07002292 raise AssertionError(
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002293 f'{problem}\n'
2294 f'Expected: {_CallList(calls)}\n'
Lisa Roach77b3b772019-05-20 09:19:53 -07002295 f'Actual: {self.await_args_list}'
2296 ) from cause
2297 return
2298
2299 all_awaits = list(all_awaits)
2300
2301 not_found = []
2302 for kall in expected:
2303 try:
2304 all_awaits.remove(kall)
2305 except ValueError:
2306 not_found.append(kall)
2307 if not_found:
2308 raise AssertionError(
2309 '%r not all found in await list' % (tuple(not_found),)
2310 ) from cause
2311
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002312 def assert_not_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002313 """
2314 Assert that the mock was never awaited.
2315 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002316 if self.await_count != 0:
Xtreakff6b2e62019-05-27 18:26:23 +05302317 msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
Lisa Roach77b3b772019-05-20 09:19:53 -07002318 f" Awaited {self.await_count} times.")
2319 raise AssertionError(msg)
2320
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002321 def reset_mock(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002322 """
2323 See :func:`.Mock.reset_mock()`
2324 """
2325 super().reset_mock(*args, **kwargs)
2326 self.await_count = 0
2327 self.await_args = None
2328 self.await_args_list = _CallList()
2329
2330
2331class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2332 """
2333 Enhance :class:`Mock` with features allowing to mock
2334 an async function.
2335
2336 The :class:`AsyncMock` object will behave so the object is
2337 recognized as an async function, and the result of a call is an awaitable:
2338
2339 >>> mock = AsyncMock()
2340 >>> asyncio.iscoroutinefunction(mock)
2341 True
2342 >>> inspect.isawaitable(mock())
2343 True
2344
2345
2346 The result of ``mock()`` is an async function which will have the outcome
2347 of ``side_effect`` or ``return_value``:
2348
2349 - if ``side_effect`` is a function, the async function will return the
2350 result of that function,
2351 - if ``side_effect`` is an exception, the async function will raise the
2352 exception,
2353 - if ``side_effect`` is an iterable, the async function will return the
2354 next value of the iterable, however, if the sequence of result is
2355 exhausted, ``StopIteration`` is raised immediately,
2356 - if ``side_effect`` is not defined, the async function will return the
2357 value defined by ``return_value``, hence, by default, the async function
2358 returns a new :class:`AsyncMock` object.
2359
2360 If the outcome of ``side_effect`` or ``return_value`` is an async function,
2361 the mock async function obtained when the mock object is called will be this
2362 async function itself (and not an async function returning an async
2363 function).
2364
2365 The test author can also specify a wrapped object with ``wraps``. In this
2366 case, the :class:`Mock` object behavior is the same as with an
2367 :class:`.Mock` object: the wrapped object may have methods
2368 defined as async function functions.
2369
Xtreake7cb23b2019-05-21 14:17:17 +05302370 Based on Martin Richard's asynctest project.
Lisa Roach77b3b772019-05-20 09:19:53 -07002371 """
2372
Michael Foord345266a2012-03-14 12:24:34 -07002373
2374class _ANY(object):
2375 "A helper object that compares equal to everything."
2376
2377 def __eq__(self, other):
2378 return True
2379
2380 def __ne__(self, other):
2381 return False
2382
2383 def __repr__(self):
2384 return '<ANY>'
2385
2386ANY = _ANY()
2387
2388
2389
2390def _format_call_signature(name, args, kwargs):
2391 message = '%s(%%s)' % name
2392 formatted_args = ''
2393 args_string = ', '.join([repr(arg) for arg in args])
2394 kwargs_string = ', '.join([
Xtreak9d607062019-09-09 16:25:22 +05302395 '%s=%r' % (key, value) for key, value in kwargs.items()
Michael Foord345266a2012-03-14 12:24:34 -07002396 ])
2397 if args_string:
2398 formatted_args = args_string
2399 if kwargs_string:
2400 if formatted_args:
2401 formatted_args += ', '
2402 formatted_args += kwargs_string
2403
2404 return message % formatted_args
2405
2406
2407
2408class _Call(tuple):
2409 """
2410 A tuple for holding the results of a call to a mock, either in the form
2411 `(args, kwargs)` or `(name, args, kwargs)`.
2412
2413 If args or kwargs are empty then a call tuple will compare equal to
2414 a tuple without those values. This makes comparisons less verbose::
2415
2416 _Call(('name', (), {})) == ('name',)
2417 _Call(('name', (1,), {})) == ('name', (1,))
2418 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2419
2420 The `_Call` object provides a useful shortcut for comparing with call::
2421
2422 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2423 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2424
2425 If the _Call has no name then it will match any name.
2426 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002427 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002428 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002429 args = ()
2430 kwargs = {}
2431 _len = len(value)
2432 if _len == 3:
2433 name, args, kwargs = value
2434 elif _len == 2:
2435 first, second = value
2436 if isinstance(first, str):
2437 name = first
2438 if isinstance(second, tuple):
2439 args = second
2440 else:
2441 kwargs = second
2442 else:
2443 args, kwargs = first, second
2444 elif _len == 1:
2445 value, = value
2446 if isinstance(value, str):
2447 name = value
2448 elif isinstance(value, tuple):
2449 args = value
2450 else:
2451 kwargs = value
2452
2453 if two:
2454 return tuple.__new__(cls, (args, kwargs))
2455
2456 return tuple.__new__(cls, (name, args, kwargs))
2457
2458
2459 def __init__(self, value=(), name=None, parent=None, two=False,
2460 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002461 self._mock_name = name
2462 self._mock_parent = parent
2463 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002464
2465
2466 def __eq__(self, other):
Michael Foord345266a2012-03-14 12:24:34 -07002467 try:
2468 len_other = len(other)
2469 except TypeError:
Serhiy Storchaka662db122019-08-08 08:42:54 +03002470 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07002471
2472 self_name = ''
2473 if len(self) == 2:
2474 self_args, self_kwargs = self
2475 else:
2476 self_name, self_args, self_kwargs = self
2477
Andrew Dunaie63e6172018-12-04 11:08:45 +02002478 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2479 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002480 return False
2481
Michael Foord345266a2012-03-14 12:24:34 -07002482 other_name = ''
2483 if len_other == 0:
2484 other_args, other_kwargs = (), {}
2485 elif len_other == 3:
2486 other_name, other_args, other_kwargs = other
2487 elif len_other == 1:
2488 value, = other
2489 if isinstance(value, tuple):
2490 other_args = value
2491 other_kwargs = {}
2492 elif isinstance(value, str):
2493 other_name = value
2494 other_args, other_kwargs = (), {}
2495 else:
2496 other_args = ()
2497 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002498 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002499 # could be (name, args) or (name, kwargs) or (args, kwargs)
2500 first, second = other
2501 if isinstance(first, str):
2502 other_name = first
2503 if isinstance(second, tuple):
2504 other_args, other_kwargs = second, {}
2505 else:
2506 other_args, other_kwargs = (), second
2507 else:
2508 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002509 else:
2510 return False
Michael Foord345266a2012-03-14 12:24:34 -07002511
2512 if self_name and other_name != self_name:
2513 return False
2514
2515 # this order is important for ANY to work!
2516 return (other_args, other_kwargs) == (self_args, self_kwargs)
2517
2518
Berker Peksagce913872016-03-28 00:30:02 +03002519 __ne__ = object.__ne__
2520
2521
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002522 def __call__(self, /, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002523 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002524 return _Call(('', args, kwargs), name='()')
2525
Andrew Dunaie63e6172018-12-04 11:08:45 +02002526 name = self._mock_name + '()'
2527 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002528
2529
2530 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002531 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002532 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002533 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002534 return _Call(name=name, parent=self, from_kall=False)
2535
2536
blhsing72c35992019-09-11 07:28:06 -07002537 def __getattribute__(self, attr):
2538 if attr in tuple.__dict__:
2539 raise AttributeError
2540 return tuple.__getattribute__(self, attr)
2541
2542
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002543 def count(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302544 return self.__getattr__('count')(*args, **kwargs)
2545
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002546 def index(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302547 return self.__getattr__('index')(*args, **kwargs)
2548
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302549 def _get_call_arguments(self):
2550 if len(self) == 2:
2551 args, kwargs = self
2552 else:
2553 name, args, kwargs = self
2554
2555 return args, kwargs
2556
2557 @property
2558 def args(self):
2559 return self._get_call_arguments()[0]
2560
2561 @property
2562 def kwargs(self):
2563 return self._get_call_arguments()[1]
2564
Michael Foord345266a2012-03-14 12:24:34 -07002565 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002566 if not self._mock_from_kall:
2567 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002568 if name.startswith('()'):
2569 name = 'call%s' % name
2570 return name
2571
2572 if len(self) == 2:
2573 name = 'call'
2574 args, kwargs = self
2575 else:
2576 name, args, kwargs = self
2577 if not name:
2578 name = 'call'
2579 elif not name.startswith('()'):
2580 name = 'call.%s' % name
2581 else:
2582 name = 'call%s' % name
2583 return _format_call_signature(name, args, kwargs)
2584
2585
2586 def call_list(self):
2587 """For a call object that represents multiple calls, `call_list`
2588 returns a list of all the intermediate calls as well as the
2589 final call."""
2590 vals = []
2591 thing = self
2592 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002593 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002594 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002595 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002596 return _CallList(reversed(vals))
2597
2598
2599call = _Call(from_kall=False)
2600
2601
Michael Foord345266a2012-03-14 12:24:34 -07002602def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2603 _name=None, **kwargs):
2604 """Create a mock object using another object as a spec. Attributes on the
2605 mock will use the corresponding attribute on the `spec` object as their
2606 spec.
2607
2608 Functions or methods being mocked will have their arguments checked
2609 to check that they are called with the correct signature.
2610
2611 If `spec_set` is True then attempting to set attributes that don't exist
2612 on the spec object will raise an `AttributeError`.
2613
2614 If a class is used as a spec then the return value of the mock (the
2615 instance of the class) will have the same spec. You can use a class as the
2616 spec for an instance object by passing `instance=True`. The returned mock
2617 will only be callable if instances of the mock are callable.
2618
2619 `create_autospec` also takes arbitrary keyword arguments that are passed to
2620 the constructor of the created mock."""
2621 if _is_list(spec):
2622 # can't pass a list instance to the mock constructor as it will be
2623 # interpreted as a list of strings
2624 spec = type(spec)
2625
2626 is_type = isinstance(spec, type)
Xtreakff6b2e62019-05-27 18:26:23 +05302627 is_async_func = _is_async_func(spec)
Michael Foord345266a2012-03-14 12:24:34 -07002628 _kwargs = {'spec': spec}
2629 if spec_set:
2630 _kwargs = {'spec_set': spec}
2631 elif spec is None:
2632 # None we mock with a normal mock without a spec
2633 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002634 if _kwargs and instance:
2635 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002636
2637 _kwargs.update(kwargs)
2638
2639 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002640 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002641 # descriptors don't have a spec
2642 # because we don't know what type they return
2643 _kwargs = {}
Lisa Roach77b3b772019-05-20 09:19:53 -07002644 elif is_async_func:
2645 if instance:
2646 raise RuntimeError("Instance can not be True when create_autospec "
2647 "is mocking an async function")
2648 Klass = AsyncMock
Michael Foord345266a2012-03-14 12:24:34 -07002649 elif not _callable(spec):
2650 Klass = NonCallableMagicMock
2651 elif is_type and instance and not _instance_callable(spec):
2652 Klass = NonCallableMagicMock
2653
Kushal Das484f8a82014-04-16 01:05:50 +05302654 _name = _kwargs.pop('name', _name)
2655
Michael Foord345266a2012-03-14 12:24:34 -07002656 _new_name = _name
2657 if _parent is None:
2658 # for a top level object no _new_name should be set
2659 _new_name = ''
2660
2661 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2662 name=_name, **_kwargs)
2663
2664 if isinstance(spec, FunctionTypes):
2665 # should only happen at the top level because we don't
2666 # recurse for functions
2667 mock = _set_signature(mock, spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07002668 if is_async_func:
Xtreakff6b2e62019-05-27 18:26:23 +05302669 _setup_async_mock(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002670 else:
2671 _check_signature(spec, mock, is_type, instance)
2672
2673 if _parent is not None and not instance:
2674 _parent._mock_children[_name] = mock
2675
2676 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002677 mock.return_value = create_autospec(spec, spec_set, instance=True,
2678 _name='()', _parent=mock)
2679
2680 for entry in dir(spec):
2681 if _is_magic(entry):
2682 # MagicMock already does the useful magic methods for us
2683 continue
2684
Michael Foord345266a2012-03-14 12:24:34 -07002685 # XXXX do we need a better way of getting attributes without
2686 # triggering code execution (?) Probably not - we need the actual
2687 # object to mock it so we would rather trigger a property than mock
2688 # the property descriptor. Likewise we want to mock out dynamically
2689 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002690 # XXXX what about attributes that raise exceptions other than
2691 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002692 # we could be resilient against it, or catch and propagate the
2693 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002694 try:
2695 original = getattr(spec, entry)
2696 except AttributeError:
2697 continue
Michael Foord345266a2012-03-14 12:24:34 -07002698
2699 kwargs = {'spec': original}
2700 if spec_set:
2701 kwargs = {'spec_set': original}
2702
2703 if not isinstance(original, FunctionTypes):
2704 new = _SpecState(original, spec_set, mock, entry, instance)
2705 mock._mock_children[entry] = new
2706 else:
2707 parent = mock
2708 if isinstance(spec, FunctionTypes):
2709 parent = mock.mock
2710
Michael Foord345266a2012-03-14 12:24:34 -07002711 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002712 kwargs['_eat_self'] = skipfirst
Lisa Roach77b3b772019-05-20 09:19:53 -07002713 if asyncio.iscoroutinefunction(original):
2714 child_klass = AsyncMock
2715 else:
2716 child_klass = MagicMock
2717 new = child_klass(parent=parent, name=entry, _new_name=entry,
2718 _new_parent=parent,
2719 **kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002720 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002721 _check_signature(original, new, skipfirst=skipfirst)
2722
2723 # so functions created with _set_signature become instance attributes,
2724 # *plus* their underlying mock exists in _mock_children of the parent
2725 # mock. Adding to _mock_children may be unnecessary where we are also
2726 # setting as an instance attribute?
2727 if isinstance(new, FunctionTypes):
2728 setattr(mock, entry, new)
2729
2730 return mock
2731
2732
2733def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002734 """
2735 Return whether we should skip the first argument on spec's `entry`
2736 attribute.
2737 """
Michael Foord345266a2012-03-14 12:24:34 -07002738 if not isinstance(spec, type):
2739 if entry in getattr(spec, '__dict__', {}):
2740 # instance attribute - shouldn't skip
2741 return False
Michael Foord345266a2012-03-14 12:24:34 -07002742 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002743
2744 for klass in spec.__mro__:
2745 result = klass.__dict__.get(entry, DEFAULT)
2746 if result is DEFAULT:
2747 continue
2748 if isinstance(result, (staticmethod, classmethod)):
2749 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002750 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2751 # Normal method => skip if looked up on type
2752 # (if looked up on instance, self is already skipped)
2753 return is_type
2754 else:
2755 return False
Michael Foord345266a2012-03-14 12:24:34 -07002756
Chris Withersadbf1782019-05-01 23:04:04 +01002757 # function is a dynamically provided attribute
Michael Foord345266a2012-03-14 12:24:34 -07002758 return is_type
2759
2760
Michael Foord345266a2012-03-14 12:24:34 -07002761class _SpecState(object):
2762
2763 def __init__(self, spec, spec_set=False, parent=None,
2764 name=None, ids=None, instance=False):
2765 self.spec = spec
2766 self.ids = ids
2767 self.spec_set = spec_set
2768 self.parent = parent
2769 self.instance = instance
2770 self.name = name
2771
2772
2773FunctionTypes = (
2774 # python function
2775 type(create_autospec),
2776 # instance method
2777 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002778)
2779
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002780MethodWrapperTypes = (
2781 type(ANY.__eq__.__get__),
2782)
2783
Michael Foord345266a2012-03-14 12:24:34 -07002784
Michael Foorda74561a2012-03-25 19:03:13 +01002785file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002786
Michael Foord04cbe0c2013-03-19 17:22:51 -07002787
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002788def _to_stream(read_data):
2789 if isinstance(read_data, bytes):
2790 return io.BytesIO(read_data)
Michael Foord04cbe0c2013-03-19 17:22:51 -07002791 else:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002792 return io.StringIO(read_data)
Michael Foord0dccf652012-03-25 19:11:50 +01002793
Robert Collins5329aaa2015-07-17 20:08:45 +12002794
Michael Foord0dccf652012-03-25 19:11:50 +01002795def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002796 """
2797 A helper function to create a mock to replace the use of `open`. It works
2798 for `open` called directly or used as a context manager.
2799
2800 The `mock` argument is the mock object to configure. If `None` (the
2801 default) then a `MagicMock` will be created for you, with the API limited
2802 to methods or attributes available on standard file handles.
2803
Xtreak71f82a22018-12-20 21:30:21 +05302804 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002805 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002806 """
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002807 _read_data = _to_stream(read_data)
2808 _state = [_read_data, None]
2809
Robert Collinsca647ef2015-07-24 03:48:20 +12002810 def _readlines_side_effect(*args, **kwargs):
2811 if handle.readlines.return_value is not None:
2812 return handle.readlines.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002813 return _state[0].readlines(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002814
2815 def _read_side_effect(*args, **kwargs):
2816 if handle.read.return_value is not None:
2817 return handle.read.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002818 return _state[0].read(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002819
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002820 def _readline_side_effect(*args, **kwargs):
Tony Flury20870232018-09-12 23:21:16 +01002821 yield from _iter_side_effect()
2822 while True:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002823 yield _state[0].readline(*args, **kwargs)
Tony Flury20870232018-09-12 23:21:16 +01002824
2825 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002826 if handle.readline.return_value is not None:
2827 while True:
2828 yield handle.readline.return_value
2829 for line in _state[0]:
2830 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002831
Damien Nadé394119a2019-05-23 12:03:25 +02002832 def _next_side_effect():
2833 if handle.readline.return_value is not None:
2834 return handle.readline.return_value
2835 return next(_state[0])
2836
Michael Foorda74561a2012-03-25 19:03:13 +01002837 global file_spec
2838 if file_spec is None:
2839 import _io
2840 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2841
Michael Foord345266a2012-03-14 12:24:34 -07002842 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002843 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002844
Robert Collinsca647ef2015-07-24 03:48:20 +12002845 handle = MagicMock(spec=file_spec)
2846 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002847
Robert Collinsca647ef2015-07-24 03:48:20 +12002848 handle.write.return_value = None
2849 handle.read.return_value = None
2850 handle.readline.return_value = None
2851 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002852
Robert Collinsca647ef2015-07-24 03:48:20 +12002853 handle.read.side_effect = _read_side_effect
2854 _state[1] = _readline_side_effect()
2855 handle.readline.side_effect = _state[1]
2856 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002857 handle.__iter__.side_effect = _iter_side_effect
Damien Nadé394119a2019-05-23 12:03:25 +02002858 handle.__next__.side_effect = _next_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002859
Robert Collinsca647ef2015-07-24 03:48:20 +12002860 def reset_data(*args, **kwargs):
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002861 _state[0] = _to_stream(read_data)
Robert Collinsca647ef2015-07-24 03:48:20 +12002862 if handle.readline.side_effect == _state[1]:
2863 # Only reset the side effect if the user hasn't overridden it.
2864 _state[1] = _readline_side_effect()
2865 handle.readline.side_effect = _state[1]
2866 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002867
Robert Collinsca647ef2015-07-24 03:48:20 +12002868 mock.side_effect = reset_data
2869 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002870 return mock
2871
2872
2873class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002874 """
2875 A mock intended to be used as a property, or other descriptor, on a class.
2876 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2877 a return value when it is fetched.
2878
2879 Fetching a `PropertyMock` instance from an object calls the mock, with
2880 no args. Setting it calls the mock with the value being set.
2881 """
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002882 def _get_child_mock(self, /, **kwargs):
Michael Foordc2870622012-04-13 16:57:22 +01002883 return MagicMock(**kwargs)
2884
Raymond Hettinger0dac68f2019-08-29 01:27:42 -07002885 def __get__(self, obj, obj_type=None):
Michael Foord345266a2012-03-14 12:24:34 -07002886 return self()
2887 def __set__(self, obj, val):
2888 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002889
2890
2891def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002892 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002893
2894 Given an input Mock, seals it to ensure no further mocks will be generated
2895 when accessing an attribute that was not already defined.
2896
Mario Corchero96200eb2018-10-19 22:57:37 +01002897 The operation recursively seals the mock passed in, meaning that
2898 the mock itself, any mocks generated by accessing one of its attributes,
2899 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002900 """
2901 mock._mock_sealed = True
2902 for attr in dir(mock):
2903 try:
2904 m = getattr(mock, attr)
2905 except AttributeError:
2906 continue
2907 if not isinstance(m, NonCallableMock):
2908 continue
2909 if m._mock_new_parent is mock:
2910 seal(m)
Lisa Roach77b3b772019-05-20 09:19:53 -07002911
2912
Lisa Roach77b3b772019-05-20 09:19:53 -07002913class _AsyncIterator:
2914 """
2915 Wraps an iterator in an asynchronous iterator.
2916 """
2917 def __init__(self, iterator):
2918 self.iterator = iterator
2919 code_mock = NonCallableMock(spec_set=CodeType)
2920 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
2921 self.__dict__['__code__'] = code_mock
2922
2923 def __aiter__(self):
2924 return self
2925
2926 async def __anext__(self):
2927 try:
2928 return next(self.iterator)
2929 except StopIteration:
2930 pass
2931 raise StopAsyncIteration