blob: a8f74a95791c1f881c98d026406887231f443b14 [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
26__version__ = '1.0'
27
Lisa Roach77b3b772019-05-20 09:19:53 -070028import asyncio
Xtreak436c2b02019-05-28 12:37:39 +053029import contextlib
Rémi Lapeyre11a88322019-05-07 12:48:36 +020030import io
Michael Foord345266a2012-03-14 12:24:34 -070031import inspect
32import pprint
33import sys
Michael Foordfddcfa22014-04-14 16:25:20 -040034import builtins
Lisa Roach77b3b772019-05-20 09:19:53 -070035from types import CodeType, ModuleType, MethodType
Petter Strandmark47d94242018-10-28 21:37:10 +010036from unittest.util import safe_repr
Antoine Pitrou5c64df72013-02-03 00:23:58 +010037from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070038
39
Michael Foordfddcfa22014-04-14 16:25:20 -040040_builtins = {name for name in dir(builtins) if not name.startswith('_')}
41
Michael Foord345266a2012-03-14 12:24:34 -070042FILTER_DIR = True
43
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100044# Workaround for issue #12370
45# Without this, the __class__ properties wouldn't be set correctly
46_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070047
Lisa Roach77b3b772019-05-20 09:19:53 -070048def _is_async_obj(obj):
Miss Islington (bot)c3008dd2019-09-10 06:16:00 -070049 if _is_instance_mock(obj) and not isinstance(obj, AsyncMock):
Lisa Roach77b3b772019-05-20 09:19:53 -070050 return False
Matthew Kokotovich19be85c2020-01-26 09:30:27 -060051 if hasattr(obj, '__func__'):
52 obj = getattr(obj, '__func__')
Miss Islington (bot)c3008dd2019-09-10 06:16:00 -070053 return asyncio.iscoroutinefunction(obj) or inspect.isawaitable(obj)
Lisa Roach77b3b772019-05-20 09:19:53 -070054
55
Xtreakff6b2e62019-05-27 18:26:23 +053056def _is_async_func(func):
57 if getattr(func, '__code__', None):
58 return asyncio.iscoroutinefunction(func)
59 else:
60 return False
61
62
Michael Foord345266a2012-03-14 12:24:34 -070063def _is_instance_mock(obj):
64 # can't use isinstance on Mock objects because they override __class__
65 # The base class for all mocks is NonCallableMock
66 return issubclass(type(obj), NonCallableMock)
67
68
69def _is_exception(obj):
70 return (
Chris Withers49e27f02019-05-01 08:48:44 +010071 isinstance(obj, BaseException) or
72 isinstance(obj, type) and issubclass(obj, BaseException)
Michael Foord345266a2012-03-14 12:24:34 -070073 )
74
75
Miss Islington (bot)22fd6792019-07-22 00:59:00 -070076def _extract_mock(obj):
77 # Autospecced functions will return a FunctionType with "mock" attribute
78 # which is the actual mock object that needs to be used.
79 if isinstance(obj, FunctionTypes) and hasattr(obj, 'mock'):
80 return obj.mock
81 else:
82 return obj
83
84
Antoine Pitrou5c64df72013-02-03 00:23:58 +010085def _get_signature_object(func, as_instance, eat_self):
86 """
87 Given an arbitrary, possibly callable object, try to create a suitable
88 signature object.
89 Return a (reduced func, signature) tuple, or None.
90 """
91 if isinstance(func, type) and not as_instance:
92 # If it's a type and should be modelled as a type, use __init__.
Chris Withersadbf1782019-05-01 23:04:04 +010093 func = func.__init__
Antoine Pitrou5c64df72013-02-03 00:23:58 +010094 # Skip the `self` argument in __init__
95 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070096 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010097 # If we really want to model an instance of the passed type,
98 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070099 try:
100 func = func.__call__
101 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100102 return None
103 if eat_self:
104 sig_func = partial(func, None)
105 else:
106 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -0700107 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100108 return func, inspect.signature(sig_func)
109 except ValueError:
110 # Certain callable types are not supported by inspect.signature()
111 return None
Michael Foord345266a2012-03-14 12:24:34 -0700112
113
114def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100115 sig = _get_signature_object(func, instance, skipfirst)
116 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -0700117 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100118 func, sig = sig
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300119 def checksig(self, /, *args, **kwargs):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100120 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700121 _copy_func_details(func, checksig)
122 type(mock)._mock_check_sig = checksig
Xtreakf7fa62e2018-12-12 13:24:54 +0530123 type(mock).__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700124
125
126def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700127 # we explicitly don't copy func.__dict__ into this copy as it would
128 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300129 for attribute in (
130 '__name__', '__doc__', '__text_signature__',
131 '__module__', '__defaults__', '__kwdefaults__',
132 ):
133 try:
134 setattr(funcopy, attribute, getattr(func, attribute))
135 except AttributeError:
136 pass
Michael Foord345266a2012-03-14 12:24:34 -0700137
138
139def _callable(obj):
140 if isinstance(obj, type):
141 return True
Xtreak9b218562019-04-22 08:00:23 +0530142 if isinstance(obj, (staticmethod, classmethod, MethodType)):
143 return _callable(obj.__func__)
Michael Foord345266a2012-03-14 12:24:34 -0700144 if getattr(obj, '__call__', None) is not None:
145 return True
146 return False
147
148
149def _is_list(obj):
150 # checks for list or tuples
151 # XXXX badly named!
152 return type(obj) in (list, tuple)
153
154
155def _instance_callable(obj):
156 """Given an object, return True if the object is callable.
157 For classes, return True if instances would be callable."""
158 if not isinstance(obj, type):
159 # already an instance
160 return getattr(obj, '__call__', None) is not None
161
Michael Foorda74b3aa2012-03-14 14:40:22 -0700162 # *could* be broken by a class overriding __mro__ or __dict__ via
163 # a metaclass
164 for base in (obj,) + obj.__mro__:
165 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700166 return True
167 return False
168
169
170def _set_signature(mock, original, instance=False):
171 # creates a function with signature (*args, **kwargs) that delegates to a
172 # mock. It still does signature checking by calling a lambda with the same
173 # signature as the original.
Michael Foord345266a2012-03-14 12:24:34 -0700174
175 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100176 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700177 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700178 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100179 func, sig = result
180 def checksig(*args, **kwargs):
181 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700182 _copy_func_details(func, checksig)
183
184 name = original.__name__
185 if not name.isidentifier():
186 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100187 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700188 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100189 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700190 return mock(*args, **kwargs)""" % name
191 exec (src, context)
192 funcopy = context[name]
Xtreakf7fa62e2018-12-12 13:24:54 +0530193 _setup_func(funcopy, mock, sig)
Michael Foord345266a2012-03-14 12:24:34 -0700194 return funcopy
195
196
Xtreakf7fa62e2018-12-12 13:24:54 +0530197def _setup_func(funcopy, mock, sig):
Michael Foord345266a2012-03-14 12:24:34 -0700198 funcopy.mock = mock
199
Michael Foord345266a2012-03-14 12:24:34 -0700200 def assert_called_with(*args, **kwargs):
201 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700202 def assert_called(*args, **kwargs):
203 return mock.assert_called(*args, **kwargs)
204 def assert_not_called(*args, **kwargs):
205 return mock.assert_not_called(*args, **kwargs)
206 def assert_called_once(*args, **kwargs):
207 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700208 def assert_called_once_with(*args, **kwargs):
209 return mock.assert_called_once_with(*args, **kwargs)
210 def assert_has_calls(*args, **kwargs):
211 return mock.assert_has_calls(*args, **kwargs)
212 def assert_any_call(*args, **kwargs):
213 return mock.assert_any_call(*args, **kwargs)
214 def reset_mock():
215 funcopy.method_calls = _CallList()
216 funcopy.mock_calls = _CallList()
217 mock.reset_mock()
218 ret = funcopy.return_value
219 if _is_instance_mock(ret) and not ret is mock:
220 ret.reset_mock()
221
222 funcopy.called = False
223 funcopy.call_count = 0
224 funcopy.call_args = None
225 funcopy.call_args_list = _CallList()
226 funcopy.method_calls = _CallList()
227 funcopy.mock_calls = _CallList()
228
229 funcopy.return_value = mock.return_value
230 funcopy.side_effect = mock.side_effect
231 funcopy._mock_children = mock._mock_children
232
233 funcopy.assert_called_with = assert_called_with
234 funcopy.assert_called_once_with = assert_called_once_with
235 funcopy.assert_has_calls = assert_has_calls
236 funcopy.assert_any_call = assert_any_call
237 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700238 funcopy.assert_called = assert_called
239 funcopy.assert_not_called = assert_not_called
240 funcopy.assert_called_once = assert_called_once
Xtreakf7fa62e2018-12-12 13:24:54 +0530241 funcopy.__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700242
243 mock._mock_delegate = funcopy
244
245
Xtreakff6b2e62019-05-27 18:26:23 +0530246def _setup_async_mock(mock):
247 mock._is_coroutine = asyncio.coroutines._is_coroutine
248 mock.await_count = 0
249 mock.await_args = None
250 mock.await_args_list = _CallList()
Xtreakff6b2e62019-05-27 18:26:23 +0530251
252 # Mock is not configured yet so the attributes are set
253 # to a function and then the corresponding mock helper function
254 # is called when the helper is accessed similar to _setup_func.
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300255 def wrapper(attr, /, *args, **kwargs):
Xtreakff6b2e62019-05-27 18:26:23 +0530256 return getattr(mock.mock, attr)(*args, **kwargs)
257
258 for attribute in ('assert_awaited',
259 'assert_awaited_once',
260 'assert_awaited_with',
261 'assert_awaited_once_with',
262 'assert_any_await',
263 'assert_has_awaits',
264 'assert_not_awaited'):
265
266 # setattr(mock, attribute, wrapper) causes late binding
267 # hence attribute will always be the last value in the loop
268 # Use partial(wrapper, attribute) to ensure the attribute is bound
269 # correctly.
270 setattr(mock, attribute, partial(wrapper, attribute))
271
272
Michael Foord345266a2012-03-14 12:24:34 -0700273def _is_magic(name):
274 return '__%s__' % name[2:-2] == name
275
276
277class _SentinelObject(object):
278 "A unique, named, sentinel object."
279 def __init__(self, name):
280 self.name = name
281
282 def __repr__(self):
283 return 'sentinel.%s' % self.name
284
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200285 def __reduce__(self):
286 return 'sentinel.%s' % self.name
287
Michael Foord345266a2012-03-14 12:24:34 -0700288
289class _Sentinel(object):
290 """Access attributes to return a named object, usable as a sentinel."""
291 def __init__(self):
292 self._sentinels = {}
293
294 def __getattr__(self, name):
295 if name == '__bases__':
296 # Without this help(unittest.mock) raises an exception
297 raise AttributeError
298 return self._sentinels.setdefault(name, _SentinelObject(name))
299
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200300 def __reduce__(self):
301 return 'sentinel'
302
Michael Foord345266a2012-03-14 12:24:34 -0700303
304sentinel = _Sentinel()
305
306DEFAULT = sentinel.DEFAULT
307_missing = sentinel.MISSING
308_deleted = sentinel.DELETED
309
310
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200311_allowed_names = {
312 'return_value', '_mock_return_value', 'side_effect',
313 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
314 '_mock_name', '_mock_new_name'
315}
Michael Foord345266a2012-03-14 12:24:34 -0700316
317
318def _delegating_property(name):
319 _allowed_names.add(name)
320 _the_name = '_mock_' + name
321 def _get(self, name=name, _the_name=_the_name):
322 sig = self._mock_delegate
323 if sig is None:
324 return getattr(self, _the_name)
325 return getattr(sig, name)
326 def _set(self, value, name=name, _the_name=_the_name):
327 sig = self._mock_delegate
328 if sig is None:
329 self.__dict__[_the_name] = value
330 else:
331 setattr(sig, name, value)
332
333 return property(_get, _set)
334
335
336
337class _CallList(list):
338
339 def __contains__(self, value):
340 if not isinstance(value, list):
341 return list.__contains__(self, value)
342 len_value = len(value)
343 len_self = len(self)
344 if len_value > len_self:
345 return False
346
347 for i in range(0, len_self - len_value + 1):
348 sub_list = self[i:i+len_value]
349 if sub_list == value:
350 return True
351 return False
352
353 def __repr__(self):
354 return pprint.pformat(list(self))
355
356
357def _check_and_set_parent(parent, value, name, new_name):
Miss Islington (bot)22fd6792019-07-22 00:59:00 -0700358 value = _extract_mock(value)
Xtreak9c3f2842019-02-26 03:16:34 +0530359
Michael Foord345266a2012-03-14 12:24:34 -0700360 if not _is_instance_mock(value):
361 return False
362 if ((value._mock_name or value._mock_new_name) or
363 (value._mock_parent is not None) or
364 (value._mock_new_parent is not None)):
365 return False
366
367 _parent = parent
368 while _parent is not None:
369 # setting a mock (value) as a child or return value of itself
370 # should not modify the mock
371 if _parent is value:
372 return False
373 _parent = _parent._mock_new_parent
374
375 if new_name:
376 value._mock_new_parent = parent
377 value._mock_new_name = new_name
378 if name:
379 value._mock_parent = parent
380 value._mock_name = name
381 return True
382
Michael Foord01bafdc2014-04-14 16:09:42 -0400383# Internal class to identify if we wrapped an iterator object or not.
384class _MockIter(object):
385 def __init__(self, obj):
386 self.obj = iter(obj)
Michael Foord01bafdc2014-04-14 16:09:42 -0400387 def __next__(self):
388 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700389
390class Base(object):
391 _mock_return_value = DEFAULT
392 _mock_side_effect = None
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300393 def __init__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700394 pass
395
396
397
398class NonCallableMock(Base):
399 """A non-callable version of `Mock`"""
400
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300401 def __new__(cls, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700402 # every instance has its own class
403 # so we can create magic methods on the
404 # class without stomping on other mocks
Lisa Roach77b3b772019-05-20 09:19:53 -0700405 bases = (cls,)
406 if not issubclass(cls, AsyncMock):
407 # Check if spec is an async object or function
408 sig = inspect.signature(NonCallableMock.__init__)
409 bound_args = sig.bind_partial(cls, *args, **kw).arguments
410 spec_arg = [
411 arg for arg in bound_args.keys()
412 if arg.startswith('spec')
413 ]
414 if spec_arg:
415 # what if spec_set is different than spec?
416 if _is_async_obj(bound_args[spec_arg[0]]):
417 bases = (AsyncMockMixin, cls,)
418 new = type(cls.__name__, bases, {'__doc__': cls.__doc__})
Miss Islington (bot)b76ab352019-09-29 21:02:46 -0700419 instance = _safe_super(NonCallableMock, cls).__new__(new)
Michael Foord345266a2012-03-14 12:24:34 -0700420 return instance
421
422
423 def __init__(
424 self, spec=None, wraps=None, name=None, spec_set=None,
425 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530426 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700427 ):
428 if _new_parent is None:
429 _new_parent = parent
430
431 __dict__ = self.__dict__
432 __dict__['_mock_parent'] = parent
433 __dict__['_mock_name'] = name
434 __dict__['_mock_new_name'] = _new_name
435 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100436 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700437
438 if spec_set is not None:
439 spec = spec_set
440 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100441 if _eat_self is None:
442 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700443
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100444 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700445
446 __dict__['_mock_children'] = {}
447 __dict__['_mock_wraps'] = wraps
448 __dict__['_mock_delegate'] = None
449
450 __dict__['_mock_called'] = False
451 __dict__['_mock_call_args'] = None
452 __dict__['_mock_call_count'] = 0
453 __dict__['_mock_call_args_list'] = _CallList()
454 __dict__['_mock_mock_calls'] = _CallList()
455
456 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530457 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700458
459 if kwargs:
460 self.configure_mock(**kwargs)
461
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000462 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700463 spec, wraps, name, spec_set, parent,
464 _spec_state
465 )
466
467
468 def attach_mock(self, mock, attribute):
469 """
470 Attach a mock as an attribute of this one, replacing its name and
471 parent. Calls to the attached mock will be recorded in the
472 `method_calls` and `mock_calls` attributes of this one."""
Miss Islington (bot)22fd6792019-07-22 00:59:00 -0700473 inner_mock = _extract_mock(mock)
474
475 inner_mock._mock_parent = None
476 inner_mock._mock_new_parent = None
477 inner_mock._mock_name = ''
478 inner_mock._mock_new_name = None
Michael Foord345266a2012-03-14 12:24:34 -0700479
480 setattr(self, attribute, mock)
481
482
483 def mock_add_spec(self, spec, spec_set=False):
484 """Add a spec to a mock. `spec` can either be an object or a
485 list of strings. Only attributes on the `spec` can be fetched as
486 attributes from the mock.
487
488 If `spec_set` is True then only attributes on the spec can be set."""
489 self._mock_add_spec(spec, spec_set)
490
491
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100492 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
493 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700494 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100495 _spec_signature = None
Lisa Roach77b3b772019-05-20 09:19:53 -0700496 _spec_asyncs = []
497
498 for attr in dir(spec):
499 if asyncio.iscoroutinefunction(getattr(spec, attr, None)):
500 _spec_asyncs.append(attr)
Michael Foord345266a2012-03-14 12:24:34 -0700501
502 if spec is not None and not _is_list(spec):
503 if isinstance(spec, type):
504 _spec_class = spec
505 else:
Chris Withersadbf1782019-05-01 23:04:04 +0100506 _spec_class = type(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100507 res = _get_signature_object(spec,
508 _spec_as_instance, _eat_self)
509 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700510
511 spec = dir(spec)
512
513 __dict__ = self.__dict__
514 __dict__['_spec_class'] = _spec_class
515 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100516 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700517 __dict__['_mock_methods'] = spec
Lisa Roach77b3b772019-05-20 09:19:53 -0700518 __dict__['_spec_asyncs'] = _spec_asyncs
Michael Foord345266a2012-03-14 12:24:34 -0700519
520 def __get_return_value(self):
521 ret = self._mock_return_value
522 if self._mock_delegate is not None:
523 ret = self._mock_delegate.return_value
524
525 if ret is DEFAULT:
526 ret = self._get_child_mock(
527 _new_parent=self, _new_name='()'
528 )
529 self.return_value = ret
530 return ret
531
532
533 def __set_return_value(self, value):
534 if self._mock_delegate is not None:
535 self._mock_delegate.return_value = value
536 else:
537 self._mock_return_value = value
538 _check_and_set_parent(self, value, None, '()')
539
540 __return_value_doc = "The value to be returned when the mock is called."
541 return_value = property(__get_return_value, __set_return_value,
542 __return_value_doc)
543
544
545 @property
546 def __class__(self):
547 if self._spec_class is None:
548 return type(self)
549 return self._spec_class
550
551 called = _delegating_property('called')
552 call_count = _delegating_property('call_count')
553 call_args = _delegating_property('call_args')
554 call_args_list = _delegating_property('call_args_list')
555 mock_calls = _delegating_property('mock_calls')
556
557
558 def __get_side_effect(self):
559 delegated = self._mock_delegate
560 if delegated is None:
561 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400562 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200563 if (sf is not None and not callable(sf)
564 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400565 sf = _MockIter(sf)
566 delegated.side_effect = sf
567 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700568
569 def __set_side_effect(self, value):
570 value = _try_iter(value)
571 delegated = self._mock_delegate
572 if delegated is None:
573 self._mock_side_effect = value
574 else:
575 delegated.side_effect = value
576
577 side_effect = property(__get_side_effect, __set_side_effect)
578
579
Kushal Das9cd39a12016-06-02 10:20:16 -0700580 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700581 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200582 if visited is None:
583 visited = []
584 if id(self) in visited:
585 return
586 visited.append(id(self))
587
Michael Foord345266a2012-03-14 12:24:34 -0700588 self.called = False
589 self.call_args = None
590 self.call_count = 0
591 self.mock_calls = _CallList()
592 self.call_args_list = _CallList()
593 self.method_calls = _CallList()
594
Kushal Das9cd39a12016-06-02 10:20:16 -0700595 if return_value:
596 self._mock_return_value = DEFAULT
597 if side_effect:
598 self._mock_side_effect = None
599
Michael Foord345266a2012-03-14 12:24:34 -0700600 for child in self._mock_children.values():
Xtreakedeca922018-12-01 15:33:54 +0530601 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100602 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200603 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700604
605 ret = self._mock_return_value
606 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200607 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700608
609
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300610 def configure_mock(self, /, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700611 """Set attributes on the mock through keyword arguments.
612
613 Attributes plus return values and side effects can be set on child
614 mocks using standard dot notation and unpacking a dictionary in the
615 method call:
616
617 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
618 >>> mock.configure_mock(**attrs)"""
619 for arg, val in sorted(kwargs.items(),
620 # we sort on the number of dots so that
621 # attributes are set before we set attributes on
622 # attributes
623 key=lambda entry: entry[0].count('.')):
624 args = arg.split('.')
625 final = args.pop()
626 obj = self
627 for entry in args:
628 obj = getattr(obj, entry)
629 setattr(obj, final, val)
630
631
632 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530633 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700634 raise AttributeError(name)
635 elif self._mock_methods is not None:
636 if name not in self._mock_methods or name in _all_magics:
637 raise AttributeError("Mock object has no attribute %r" % name)
638 elif _is_magic(name):
639 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530640 if not self._mock_unsafe:
641 if name.startswith(('assert', 'assret')):
Zackery Spytzb9b08cd2019-05-08 11:32:24 -0600642 raise AttributeError("Attributes cannot start with 'assert' "
643 "or 'assret'")
Michael Foord345266a2012-03-14 12:24:34 -0700644
645 result = self._mock_children.get(name)
646 if result is _deleted:
647 raise AttributeError(name)
648 elif result is None:
649 wraps = None
650 if self._mock_wraps is not None:
651 # XXXX should we get the attribute without triggering code
652 # execution?
653 wraps = getattr(self._mock_wraps, name)
654
655 result = self._get_child_mock(
656 parent=self, name=name, wraps=wraps, _new_name=name,
657 _new_parent=self
658 )
659 self._mock_children[name] = result
660
661 elif isinstance(result, _SpecState):
662 result = create_autospec(
663 result.spec, result.spec_set, result.instance,
664 result.parent, result.name
665 )
666 self._mock_children[name] = result
667
668 return result
669
670
Mario Corchero552be9d2017-10-17 12:35:11 +0100671 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700672 _name_list = [self._mock_new_name]
673 _parent = self._mock_new_parent
674 last = self
675
676 dot = '.'
677 if _name_list == ['()']:
678 dot = ''
Chris Withersadbf1782019-05-01 23:04:04 +0100679
Michael Foord345266a2012-03-14 12:24:34 -0700680 while _parent is not None:
681 last = _parent
682
683 _name_list.append(_parent._mock_new_name + dot)
684 dot = '.'
685 if _parent._mock_new_name == '()':
686 dot = ''
687
688 _parent = _parent._mock_new_parent
689
Michael Foord345266a2012-03-14 12:24:34 -0700690 _name_list = list(reversed(_name_list))
691 _first = last._mock_name or 'mock'
692 if len(_name_list) > 1:
693 if _name_list[1] not in ('()', '().'):
694 _first += '.'
695 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100696 return ''.join(_name_list)
697
698 def __repr__(self):
699 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700700
701 name_string = ''
702 if name not in ('mock', 'mock.'):
703 name_string = ' name=%r' % name
704
705 spec_string = ''
706 if self._spec_class is not None:
707 spec_string = ' spec=%r'
708 if self._spec_set:
709 spec_string = ' spec_set=%r'
710 spec_string = spec_string % self._spec_class.__name__
711 return "<%s%s%s id='%s'>" % (
712 type(self).__name__,
713 name_string,
714 spec_string,
715 id(self)
716 )
717
718
719 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700720 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100721 if not FILTER_DIR:
722 return object.__dir__(self)
723
Michael Foord345266a2012-03-14 12:24:34 -0700724 extras = self._mock_methods or []
725 from_type = dir(type(self))
726 from_dict = list(self.__dict__)
Mario Corchero0df635c2019-04-30 19:56:36 +0100727 from_child_mocks = [
728 m_name for m_name, m_value in self._mock_children.items()
729 if m_value is not _deleted]
Michael Foord345266a2012-03-14 12:24:34 -0700730
Michael Foord313f85f2012-03-25 18:16:07 +0100731 from_type = [e for e in from_type if not e.startswith('_')]
732 from_dict = [e for e in from_dict if not e.startswith('_') or
733 _is_magic(e)]
Mario Corchero0df635c2019-04-30 19:56:36 +0100734 return sorted(set(extras + from_type + from_dict + from_child_mocks))
Michael Foord345266a2012-03-14 12:24:34 -0700735
736
737 def __setattr__(self, name, value):
738 if name in _allowed_names:
739 # property setters go through here
740 return object.__setattr__(self, name, value)
741 elif (self._spec_set and self._mock_methods is not None and
742 name not in self._mock_methods and
743 name not in self.__dict__):
744 raise AttributeError("Mock object has no attribute '%s'" % name)
745 elif name in _unsupported_magics:
746 msg = 'Attempting to set unsupported magic method %r.' % name
747 raise AttributeError(msg)
748 elif name in _all_magics:
749 if self._mock_methods is not None and name not in self._mock_methods:
750 raise AttributeError("Mock object has no attribute '%s'" % name)
751
752 if not _is_instance_mock(value):
753 setattr(type(self), name, _get_method(name, value))
754 original = value
755 value = lambda *args, **kw: original(self, *args, **kw)
756 else:
757 # only set _new_name and not name so that mock_calls is tracked
758 # but not method calls
759 _check_and_set_parent(self, value, None, name)
760 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100761 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700762 elif name == '__class__':
763 self._spec_class = value
764 return
765 else:
766 if _check_and_set_parent(self, value, name, name):
767 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100768
769 if self._mock_sealed and not hasattr(self, name):
770 mock_name = f'{self._extract_mock_name()}.{name}'
771 raise AttributeError(f'Cannot set {mock_name}')
772
Michael Foord345266a2012-03-14 12:24:34 -0700773 return object.__setattr__(self, name, value)
774
775
776 def __delattr__(self, name):
777 if name in _all_magics and name in type(self).__dict__:
778 delattr(type(self), name)
779 if name not in self.__dict__:
780 # for magic methods that are still MagicProxy objects and
781 # not set on the instance itself
782 return
783
Michael Foord345266a2012-03-14 12:24:34 -0700784 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000785 if name in self.__dict__:
Xtreak830b43d2019-04-14 00:42:33 +0530786 _safe_super(NonCallableMock, self).__delattr__(name)
Pablo Galindo222d3032019-01-21 08:57:46 +0000787 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700788 raise AttributeError(name)
789 if obj is not _missing:
790 del self._mock_children[name]
791 self._mock_children[name] = _deleted
792
793
Michael Foord345266a2012-03-14 12:24:34 -0700794 def _format_mock_call_signature(self, args, kwargs):
795 name = self._mock_name or 'mock'
796 return _format_call_signature(name, args, kwargs)
797
798
Xtreak0ae022c2019-05-29 12:32:26 +0530799 def _format_mock_failure_message(self, args, kwargs, action='call'):
800 message = 'expected %s not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700801 expected_string = self._format_mock_call_signature(args, kwargs)
802 call_args = self.call_args
Michael Foord345266a2012-03-14 12:24:34 -0700803 actual_string = self._format_mock_call_signature(*call_args)
Xtreak0ae022c2019-05-29 12:32:26 +0530804 return message % (action, expected_string, actual_string)
Michael Foord345266a2012-03-14 12:24:34 -0700805
806
Miss Islington (bot)38d311d2019-08-28 23:58:27 -0700807 def _get_call_signature_from_name(self, name):
808 """
809 * If call objects are asserted against a method/function like obj.meth1
810 then there could be no name for the call object to lookup. Hence just
811 return the spec_signature of the method/function being asserted against.
812 * If the name is not empty then remove () and split by '.' to get
813 list of names to iterate through the children until a potential
814 match is found. A child mock is created only during attribute access
815 so if we get a _SpecState then no attributes of the spec were accessed
816 and can be safely exited.
817 """
818 if not name:
819 return self._spec_signature
820
821 sig = None
822 names = name.replace('()', '').split('.')
823 children = self._mock_children
824
825 for name in names:
826 child = children.get(name)
827 if child is None or isinstance(child, _SpecState):
828 break
829 else:
Miss Islington (bot)a5906b22020-01-25 06:53:08 -0800830 # If an autospecced object is attached using attach_mock the
831 # child would be a function with mock object as attribute from
832 # which signature has to be derived.
833 child = _extract_mock(child)
Miss Islington (bot)38d311d2019-08-28 23:58:27 -0700834 children = child._mock_children
835 sig = child._spec_signature
836
837 return sig
838
839
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100840 def _call_matcher(self, _call):
841 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000842 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100843 comparison key suitable for matching with other calls.
844 This is a best effort method which relies on the spec's signature,
845 if available, or falls back on the arguments themselves.
846 """
Miss Islington (bot)38d311d2019-08-28 23:58:27 -0700847
848 if isinstance(_call, tuple) and len(_call) > 2:
849 sig = self._get_call_signature_from_name(_call[0])
850 else:
851 sig = self._spec_signature
852
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100853 if sig is not None:
854 if len(_call) == 2:
855 name = ''
856 args, kwargs = _call
857 else:
858 name, args, kwargs = _call
859 try:
860 return name, sig.bind(*args, **kwargs)
861 except TypeError as e:
862 return e.with_traceback(None)
863 else:
864 return _call
865
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300866 def assert_not_called(self):
Kushal Das8af9db32014-04-17 01:36:14 +0530867 """assert that the mock was never called.
868 """
Kushal Das8af9db32014-04-17 01:36:14 +0530869 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100870 msg = ("Expected '%s' to not have been called. Called %s times.%s"
871 % (self._mock_name or 'mock',
872 self.call_count,
873 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530874 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100875
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300876 def assert_called(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100877 """assert that the mock was called at least once
878 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100879 if self.call_count == 0:
880 msg = ("Expected '%s' to have been called." %
Miss Islington (bot)f668d2b2019-09-17 04:35:56 -0700881 (self._mock_name or 'mock'))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100882 raise AssertionError(msg)
883
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300884 def assert_called_once(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100885 """assert that the mock was called only once.
886 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100887 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100888 msg = ("Expected '%s' to have been called once. Called %s times.%s"
889 % (self._mock_name or 'mock',
890 self.call_count,
891 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100892 raise AssertionError(msg)
893
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300894 def assert_called_with(self, /, *args, **kwargs):
Miss Islington (bot)612d3932019-08-28 23:39:47 -0700895 """assert that the last call was made with the specified arguments.
Michael Foord345266a2012-03-14 12:24:34 -0700896
897 Raises an AssertionError if the args and keyword args passed in are
898 different to the last call to the mock."""
Michael Foord345266a2012-03-14 12:24:34 -0700899 if self.call_args is None:
900 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800901 actual = 'not called.'
902 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
903 % (expected, actual))
904 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700905
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100906 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700907 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100908 return msg
909 expected = self._call_matcher((args, kwargs))
910 actual = self._call_matcher(self.call_args)
911 if expected != actual:
912 cause = expected if isinstance(expected, Exception) else None
913 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700914
915
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300916 def assert_called_once_with(self, /, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100917 """assert that the mock was called exactly once and that that call was
918 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700919 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100920 msg = ("Expected '%s' to be called once. Called %s times.%s"
921 % (self._mock_name or 'mock',
922 self.call_count,
923 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700924 raise AssertionError(msg)
925 return self.assert_called_with(*args, **kwargs)
926
927
928 def assert_has_calls(self, calls, any_order=False):
929 """assert the mock has been called with the specified calls.
930 The `mock_calls` list is checked for the calls.
931
932 If `any_order` is False (the default) then the calls must be
933 sequential. There can be extra calls before or after the
934 specified calls.
935
936 If `any_order` is True then the calls can be in any order, but
937 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100938 expected = [self._call_matcher(c) for c in calls]
Miss Islington (bot)1a17a052019-09-24 17:29:17 -0700939 cause = next((e for e in expected if isinstance(e, Exception)), None)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100940 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700941 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100942 if expected not in all_calls:
Miss Islington (bot)1a17a052019-09-24 17:29:17 -0700943 if cause is None:
944 problem = 'Calls not found.'
945 else:
946 problem = ('Error processing expected calls.\n'
947 'Errors: {}').format(
948 [e if isinstance(e, Exception) else None
949 for e in expected])
Michael Foord345266a2012-03-14 12:24:34 -0700950 raise AssertionError(
Miss Islington (bot)1a17a052019-09-24 17:29:17 -0700951 f'{problem}\n'
952 f'Expected: {_CallList(calls)}'
953 f'{self._calls_repr(prefix="Actual").rstrip(".")}'
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100954 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700955 return
956
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100957 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700958
959 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100960 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700961 try:
962 all_calls.remove(kall)
963 except ValueError:
964 not_found.append(kall)
965 if not_found:
966 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400967 '%r does not contain all of %r in its call list, '
968 'found %r instead' % (self._mock_name or 'mock',
969 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100970 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700971
972
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300973 def assert_any_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700974 """assert the mock has been called with the specified arguments.
975
976 The assert passes if the mock has *ever* been called, unlike
977 `assert_called_with` and `assert_called_once_with` that only pass if
978 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100979 expected = self._call_matcher((args, kwargs))
980 actual = [self._call_matcher(c) for c in self.call_args_list]
981 if expected not in actual:
982 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700983 expected_string = self._format_mock_call_signature(args, kwargs)
984 raise AssertionError(
985 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100986 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700987
988
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300989 def _get_child_mock(self, /, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700990 """Create the child mocks for attributes and return value.
991 By default child mocks will be the same type as the parent.
992 Subclasses of Mock may want to override this to customize the way
993 child mocks are made.
994
995 For non-callable mocks the callable variant will be used (rather than
996 any custom subclass)."""
Lisa Roach77b3b772019-05-20 09:19:53 -0700997 _new_name = kw.get("_new_name")
998 if _new_name in self.__dict__['_spec_asyncs']:
999 return AsyncMock(**kw)
1000
Michael Foord345266a2012-03-14 12:24:34 -07001001 _type = type(self)
Lisa Roach77b3b772019-05-20 09:19:53 -07001002 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07001003 # Any asynchronous magic becomes an AsyncMock
Lisa Roach77b3b772019-05-20 09:19:53 -07001004 klass = AsyncMock
Lisa Roach865bb682019-09-20 23:00:04 -07001005 elif issubclass(_type, AsyncMockMixin):
Lisa Roach21f24ea2019-09-29 22:22:44 -07001006 if (_new_name in _all_sync_magics or
1007 self._mock_methods and _new_name in self._mock_methods):
1008 # Any synchronous method on AsyncMock becomes a MagicMock
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07001009 klass = MagicMock
1010 else:
1011 klass = AsyncMock
Lisa Roach865bb682019-09-20 23:00:04 -07001012 elif not issubclass(_type, CallableMixin):
Michael Foord345266a2012-03-14 12:24:34 -07001013 if issubclass(_type, NonCallableMagicMock):
1014 klass = MagicMock
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07001015 elif issubclass(_type, NonCallableMock):
Michael Foord345266a2012-03-14 12:24:34 -07001016 klass = Mock
1017 else:
1018 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +01001019
1020 if self._mock_sealed:
1021 attribute = "." + kw["name"] if "name" in kw else "()"
1022 mock_name = self._extract_mock_name() + attribute
1023 raise AttributeError(mock_name)
1024
Michael Foord345266a2012-03-14 12:24:34 -07001025 return klass(**kw)
1026
1027
Petter Strandmark47d94242018-10-28 21:37:10 +01001028 def _calls_repr(self, prefix="Calls"):
1029 """Renders self.mock_calls as a string.
1030
1031 Example: "\nCalls: [call(1), call(2)]."
1032
1033 If self.mock_calls is empty, an empty string is returned. The
1034 output will be truncated if very long.
1035 """
1036 if not self.mock_calls:
1037 return ""
1038 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
1039
1040
Michael Foord345266a2012-03-14 12:24:34 -07001041
1042def _try_iter(obj):
1043 if obj is None:
1044 return obj
1045 if _is_exception(obj):
1046 return obj
1047 if _callable(obj):
1048 return obj
1049 try:
1050 return iter(obj)
1051 except TypeError:
1052 # XXXX backwards compatibility
1053 # but this will blow up on first call - so maybe we should fail early?
1054 return obj
1055
1056
Michael Foord345266a2012-03-14 12:24:34 -07001057class CallableMixin(Base):
1058
1059 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
1060 wraps=None, name=None, spec_set=None, parent=None,
1061 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
1062 self.__dict__['_mock_return_value'] = return_value
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001063 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -07001064 spec, wraps, name, spec_set, parent,
1065 _spec_state, _new_name, _new_parent, **kwargs
1066 )
1067
1068 self.side_effect = side_effect
1069
1070
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001071 def _mock_check_sig(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001072 # stub method that can be replaced with one with a specific signature
1073 pass
1074
1075
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001076 def __call__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001077 # can't use self in-case a function / method we are mocking uses self
1078 # in the signature
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001079 self._mock_check_sig(*args, **kwargs)
Lisa Roach52bdd412019-09-27 15:44:34 -07001080 self._increment_mock_call(*args, **kwargs)
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001081 return self._mock_call(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001082
1083
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001084 def _mock_call(self, /, *args, **kwargs):
Lisa Roach52bdd412019-09-27 15:44:34 -07001085 return self._execute_mock_call(*args, **kwargs)
1086
1087 def _increment_mock_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001088 self.called = True
1089 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001090
Chris Withers8ca0fa92018-12-03 21:31:37 +00001091 # handle call_args
Lisa Roach52bdd412019-09-27 15:44:34 -07001092 # needs to be set here so assertions on call arguments pass before
1093 # execution in the case of awaited calls
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001094 _call = _Call((args, kwargs), two=True)
1095 self.call_args = _call
1096 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -07001097
Chris Withers8ca0fa92018-12-03 21:31:37 +00001098 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001099 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +00001100 method_call_name = self._mock_name
1101
1102 # initial stuff for mock_calls:
1103 mock_call_name = self._mock_new_name
1104 is_a_call = mock_call_name == '()'
1105 self.mock_calls.append(_Call(('', args, kwargs)))
1106
1107 # follow up the chain of mocks:
1108 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001109 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001110
Chris Withers8ca0fa92018-12-03 21:31:37 +00001111 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001112 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001113 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001114 do_method_calls = _new_parent._mock_parent is not None
1115 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001116 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001117
Chris Withers8ca0fa92018-12-03 21:31:37 +00001118 # handle mock_calls:
1119 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001120 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001121
1122 if _new_parent._mock_new_name:
1123 if is_a_call:
1124 dot = ''
1125 else:
1126 dot = '.'
1127 is_a_call = _new_parent._mock_new_name == '()'
1128 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1129
1130 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001131 _new_parent = _new_parent._mock_new_parent
1132
Lisa Roach52bdd412019-09-27 15:44:34 -07001133 def _execute_mock_call(self, /, *args, **kwargs):
Lisa Roachb2744c12019-11-21 10:14:32 -08001134 # separate from _increment_mock_call so that awaited functions are
1135 # executed separately from their call, also AsyncMock overrides this method
Lisa Roach52bdd412019-09-27 15:44:34 -07001136
Michael Foord345266a2012-03-14 12:24:34 -07001137 effect = self.side_effect
1138 if effect is not None:
1139 if _is_exception(effect):
1140 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001141 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001142 result = next(effect)
1143 if _is_exception(result):
1144 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001145 else:
1146 result = effect(*args, **kwargs)
1147
1148 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001149 return result
Michael Foord345266a2012-03-14 12:24:34 -07001150
Mario Corcherof05df0a2018-12-08 11:25:02 +00001151 if self._mock_return_value is not DEFAULT:
1152 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001153
Mario Corcherof05df0a2018-12-08 11:25:02 +00001154 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001155 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001156
1157 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001158
1159
1160
1161class Mock(CallableMixin, NonCallableMock):
1162 """
1163 Create a new `Mock` object. `Mock` takes several optional arguments
1164 that specify the behaviour of the Mock object:
1165
1166 * `spec`: This can be either a list of strings or an existing object (a
1167 class or instance) that acts as the specification for the mock object. If
1168 you pass in an object then a list of strings is formed by calling dir on
1169 the object (excluding unsupported magic attributes and methods). Accessing
1170 any attribute not in this list will raise an `AttributeError`.
1171
1172 If `spec` is an object (rather than a list of strings) then
1173 `mock.__class__` returns the class of the spec object. This allows mocks
1174 to pass `isinstance` tests.
1175
1176 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1177 or get an attribute on the mock that isn't on the object passed as
1178 `spec_set` will raise an `AttributeError`.
1179
1180 * `side_effect`: A function to be called whenever the Mock is called. See
1181 the `side_effect` attribute. Useful for raising exceptions or
1182 dynamically changing return values. The function is called with the same
1183 arguments as the mock, and unless it returns `DEFAULT`, the return
1184 value of this function is used as the return value.
1185
Michael Foord2cd48732012-04-21 15:52:11 +01001186 If `side_effect` is an iterable then each call to the mock will return
1187 the next value from the iterable. If any of the members of the iterable
1188 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001189
Michael Foord345266a2012-03-14 12:24:34 -07001190 * `return_value`: The value returned when the mock is called. By default
1191 this is a new Mock (created on first access). See the
1192 `return_value` attribute.
1193
Michael Foord0682a0c2012-04-13 20:51:20 +01001194 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1195 calling the Mock will pass the call through to the wrapped object
1196 (returning the real result). Attribute access on the mock will return a
1197 Mock object that wraps the corresponding attribute of the wrapped object
1198 (so attempting to access an attribute that doesn't exist will raise an
1199 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001200
1201 If the mock has an explicit `return_value` set then calls are not passed
1202 to the wrapped object and the `return_value` is returned instead.
1203
1204 * `name`: If the mock has a name then it will be used in the repr of the
1205 mock. This can be useful for debugging. The name is propagated to child
1206 mocks.
1207
1208 Mocks can also be called with arbitrary keyword arguments. These will be
1209 used to set attributes on the mock after it is created.
1210 """
1211
1212
Michael Foord345266a2012-03-14 12:24:34 -07001213def _dot_lookup(thing, comp, import_path):
1214 try:
1215 return getattr(thing, comp)
1216 except AttributeError:
1217 __import__(import_path)
1218 return getattr(thing, comp)
1219
1220
1221def _importer(target):
1222 components = target.split('.')
1223 import_path = components.pop(0)
1224 thing = __import__(import_path)
1225
1226 for comp in components:
1227 import_path += ".%s" % comp
1228 thing = _dot_lookup(thing, comp, import_path)
1229 return thing
1230
1231
1232def _is_started(patcher):
1233 # XXXX horrible
1234 return hasattr(patcher, 'is_local')
1235
1236
1237class _patch(object):
1238
1239 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001240 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001241
1242 def __init__(
1243 self, getter, attribute, new, spec, create,
1244 spec_set, autospec, new_callable, kwargs
1245 ):
1246 if new_callable is not None:
1247 if new is not DEFAULT:
1248 raise ValueError(
1249 "Cannot use 'new' and 'new_callable' together"
1250 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001251 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001252 raise ValueError(
1253 "Cannot use 'autospec' and 'new_callable' together"
1254 )
1255
1256 self.getter = getter
1257 self.attribute = attribute
1258 self.new = new
1259 self.new_callable = new_callable
1260 self.spec = spec
1261 self.create = create
1262 self.has_local = False
1263 self.spec_set = spec_set
1264 self.autospec = autospec
1265 self.kwargs = kwargs
1266 self.additional_patchers = []
1267
1268
1269 def copy(self):
1270 patcher = _patch(
1271 self.getter, self.attribute, self.new, self.spec,
1272 self.create, self.spec_set,
1273 self.autospec, self.new_callable, self.kwargs
1274 )
1275 patcher.attribute_name = self.attribute_name
1276 patcher.additional_patchers = [
1277 p.copy() for p in self.additional_patchers
1278 ]
1279 return patcher
1280
1281
1282 def __call__(self, func):
1283 if isinstance(func, type):
1284 return self.decorate_class(func)
Xtreak436c2b02019-05-28 12:37:39 +05301285 if inspect.iscoroutinefunction(func):
1286 return self.decorate_async_callable(func)
Michael Foord345266a2012-03-14 12:24:34 -07001287 return self.decorate_callable(func)
1288
1289
1290 def decorate_class(self, klass):
1291 for attr in dir(klass):
1292 if not attr.startswith(patch.TEST_PREFIX):
1293 continue
1294
1295 attr_value = getattr(klass, attr)
1296 if not hasattr(attr_value, "__call__"):
1297 continue
1298
1299 patcher = self.copy()
1300 setattr(klass, attr, patcher(attr_value))
1301 return klass
1302
1303
Xtreak436c2b02019-05-28 12:37:39 +05301304 @contextlib.contextmanager
1305 def decoration_helper(self, patched, args, keywargs):
1306 extra_args = []
1307 entered_patchers = []
1308 patching = None
1309
1310 exc_info = tuple()
1311 try:
1312 for patching in patched.patchings:
1313 arg = patching.__enter__()
1314 entered_patchers.append(patching)
1315 if patching.attribute_name is not None:
1316 keywargs.update(arg)
1317 elif patching.new is DEFAULT:
1318 extra_args.append(arg)
1319
1320 args += tuple(extra_args)
1321 yield (args, keywargs)
1322 except:
1323 if (patching not in entered_patchers and
1324 _is_started(patching)):
1325 # the patcher may have been started, but an exception
1326 # raised whilst entering one of its additional_patchers
1327 entered_patchers.append(patching)
1328 # Pass the exception to __exit__
1329 exc_info = sys.exc_info()
1330 # re-raise the exception
1331 raise
1332 finally:
1333 for patching in reversed(entered_patchers):
1334 patching.__exit__(*exc_info)
1335
1336
Michael Foord345266a2012-03-14 12:24:34 -07001337 def decorate_callable(self, func):
Xtreak436c2b02019-05-28 12:37:39 +05301338 # NB. Keep the method in sync with decorate_async_callable()
Michael Foord345266a2012-03-14 12:24:34 -07001339 if hasattr(func, 'patchings'):
1340 func.patchings.append(self)
1341 return func
1342
1343 @wraps(func)
1344 def patched(*args, **keywargs):
Xtreak436c2b02019-05-28 12:37:39 +05301345 with self.decoration_helper(patched,
1346 args,
1347 keywargs) as (newargs, newkeywargs):
1348 return func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001349
Xtreak436c2b02019-05-28 12:37:39 +05301350 patched.patchings = [self]
1351 return patched
Michael Foord345266a2012-03-14 12:24:34 -07001352
Xtreak436c2b02019-05-28 12:37:39 +05301353
1354 def decorate_async_callable(self, func):
1355 # NB. Keep the method in sync with decorate_callable()
1356 if hasattr(func, 'patchings'):
1357 func.patchings.append(self)
1358 return func
1359
1360 @wraps(func)
1361 async def patched(*args, **keywargs):
1362 with self.decoration_helper(patched,
1363 args,
1364 keywargs) as (newargs, newkeywargs):
1365 return await func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001366
1367 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001368 return patched
1369
1370
1371 def get_original(self):
1372 target = self.getter()
1373 name = self.attribute
1374
1375 original = DEFAULT
1376 local = False
1377
1378 try:
1379 original = target.__dict__[name]
1380 except (AttributeError, KeyError):
1381 original = getattr(target, name, DEFAULT)
1382 else:
1383 local = True
1384
Michael Foordfddcfa22014-04-14 16:25:20 -04001385 if name in _builtins and isinstance(target, ModuleType):
1386 self.create = True
1387
Michael Foord345266a2012-03-14 12:24:34 -07001388 if not self.create and original is DEFAULT:
1389 raise AttributeError(
1390 "%s does not have the attribute %r" % (target, name)
1391 )
1392 return original, local
1393
1394
1395 def __enter__(self):
1396 """Perform the patch."""
1397 new, spec, spec_set = self.new, self.spec, self.spec_set
1398 autospec, kwargs = self.autospec, self.kwargs
1399 new_callable = self.new_callable
1400 self.target = self.getter()
1401
Michael Foord50a8c0e2012-03-25 18:57:58 +01001402 # normalise False to None
1403 if spec is False:
1404 spec = None
1405 if spec_set is False:
1406 spec_set = None
1407 if autospec is False:
1408 autospec = None
1409
1410 if spec is not None and autospec is not None:
1411 raise TypeError("Can't specify spec and autospec")
1412 if ((spec is not None or autospec is not None) and
1413 spec_set not in (True, None)):
1414 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1415
Michael Foord345266a2012-03-14 12:24:34 -07001416 original, local = self.get_original()
1417
Michael Foord50a8c0e2012-03-25 18:57:58 +01001418 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001419 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001420 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001421 # set spec to the object we are replacing
1422 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001423 if spec_set is True:
1424 spec_set = original
1425 spec = None
1426 elif spec is not None:
1427 if spec_set is True:
1428 spec_set = spec
1429 spec = None
1430 elif spec_set is True:
1431 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001432
Michael Foord50a8c0e2012-03-25 18:57:58 +01001433 if spec is not None or spec_set is not None:
1434 if original is DEFAULT:
1435 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001436 if isinstance(original, type):
1437 # If we're patching out a class and there is a spec
1438 inherit = True
Lisa Roach77b3b772019-05-20 09:19:53 -07001439 if spec is None and _is_async_obj(original):
1440 Klass = AsyncMock
1441 else:
1442 Klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -07001443 _kwargs = {}
1444 if new_callable is not None:
1445 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001446 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001447 this_spec = spec
1448 if spec_set is not None:
1449 this_spec = spec_set
1450 if _is_list(this_spec):
1451 not_callable = '__call__' not in this_spec
1452 else:
1453 not_callable = not callable(this_spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07001454 if _is_async_obj(this_spec):
1455 Klass = AsyncMock
1456 elif not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001457 Klass = NonCallableMagicMock
1458
1459 if spec is not None:
1460 _kwargs['spec'] = spec
1461 if spec_set is not None:
1462 _kwargs['spec_set'] = spec_set
1463
1464 # add a name to mocks
1465 if (isinstance(Klass, type) and
1466 issubclass(Klass, NonCallableMock) and self.attribute):
1467 _kwargs['name'] = self.attribute
1468
1469 _kwargs.update(kwargs)
1470 new = Klass(**_kwargs)
1471
1472 if inherit and _is_instance_mock(new):
1473 # we can only tell if the instance should be callable if the
1474 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001475 this_spec = spec
1476 if spec_set is not None:
1477 this_spec = spec_set
1478 if (not _is_list(this_spec) and not
1479 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001480 Klass = NonCallableMagicMock
1481
1482 _kwargs.pop('name')
1483 new.return_value = Klass(_new_parent=new, _new_name='()',
1484 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001485 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001486 # spec is ignored, new *must* be default, spec_set is treated
1487 # as a boolean. Should we check spec is not None and that spec_set
1488 # is a bool?
1489 if new is not DEFAULT:
1490 raise TypeError(
1491 "autospec creates the mock for you. Can't specify "
1492 "autospec and new."
1493 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001494 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001495 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001496 spec_set = bool(spec_set)
1497 if autospec is True:
1498 autospec = original
1499
1500 new = create_autospec(autospec, spec_set=spec_set,
1501 _name=self.attribute, **kwargs)
1502 elif kwargs:
1503 # can't set keyword args when we aren't creating the mock
1504 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1505 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1506
1507 new_attr = new
1508
1509 self.temp_original = original
1510 self.is_local = local
1511 setattr(self.target, self.attribute, new_attr)
1512 if self.attribute_name is not None:
1513 extra_args = {}
1514 if self.new is DEFAULT:
1515 extra_args[self.attribute_name] = new
1516 for patching in self.additional_patchers:
1517 arg = patching.__enter__()
1518 if patching.new is DEFAULT:
1519 extra_args.update(arg)
1520 return extra_args
1521
1522 return new
1523
1524
Michael Foord50a8c0e2012-03-25 18:57:58 +01001525 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001526 """Undo the patch."""
1527 if not _is_started(self):
Xtreak02b84cb2019-03-29 02:38:43 +05301528 return
Michael Foord345266a2012-03-14 12:24:34 -07001529
1530 if self.is_local and self.temp_original is not DEFAULT:
1531 setattr(self.target, self.attribute, self.temp_original)
1532 else:
1533 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001534 if not self.create and (not hasattr(self.target, self.attribute) or
1535 self.attribute in ('__doc__', '__module__',
1536 '__defaults__', '__annotations__',
1537 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001538 # needed for proxy objects like django settings
1539 setattr(self.target, self.attribute, self.temp_original)
1540
1541 del self.temp_original
1542 del self.is_local
1543 del self.target
1544 for patcher in reversed(self.additional_patchers):
1545 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001546 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001547
Michael Foordf7c41582012-06-10 20:36:32 +01001548
1549 def start(self):
1550 """Activate a patch, returning any created mock."""
1551 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001552 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001553 return result
1554
1555
1556 def stop(self):
1557 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001558 try:
1559 self._active_patches.remove(self)
1560 except ValueError:
1561 # If the patch hasn't been started this will fail
1562 pass
1563
Michael Foordf7c41582012-06-10 20:36:32 +01001564 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001565
1566
1567
1568def _get_target(target):
1569 try:
1570 target, attribute = target.rsplit('.', 1)
1571 except (TypeError, ValueError):
1572 raise TypeError("Need a valid target to patch. You supplied: %r" %
1573 (target,))
1574 getter = lambda: _importer(target)
1575 return getter, attribute
1576
1577
1578def _patch_object(
1579 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001580 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001581 new_callable=None, **kwargs
1582 ):
1583 """
Michael Foord345266a2012-03-14 12:24:34 -07001584 patch the named member (`attribute`) on an object (`target`) with a mock
1585 object.
1586
1587 `patch.object` can be used as a decorator, class decorator or a context
1588 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1589 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1590 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1591 the mock object it creates.
1592
1593 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1594 for choosing which methods to wrap.
1595 """
Miss Islington (bot)45945652019-12-08 22:59:04 -08001596 if type(target) is str:
1597 raise TypeError(
1598 f"{target!r} must be the actual object to be patched, not a str"
1599 )
Michael Foord345266a2012-03-14 12:24:34 -07001600 getter = lambda: target
1601 return _patch(
1602 getter, attribute, new, spec, create,
1603 spec_set, autospec, new_callable, kwargs
1604 )
1605
1606
Michael Foord50a8c0e2012-03-25 18:57:58 +01001607def _patch_multiple(target, spec=None, create=False, spec_set=None,
1608 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001609 """Perform multiple patches in a single call. It takes the object to be
1610 patched (either as an object or a string to fetch the object by importing)
1611 and keyword arguments for the patches::
1612
1613 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1614 ...
1615
1616 Use `DEFAULT` as the value if you want `patch.multiple` to create
1617 mocks for you. In this case the created mocks are passed into a decorated
1618 function by keyword, and a dictionary is returned when `patch.multiple` is
1619 used as a context manager.
1620
1621 `patch.multiple` can be used as a decorator, class decorator or a context
1622 manager. The arguments `spec`, `spec_set`, `create`,
1623 `autospec` and `new_callable` have the same meaning as for `patch`. These
1624 arguments will be applied to *all* patches done by `patch.multiple`.
1625
1626 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1627 for choosing which methods to wrap.
1628 """
1629 if type(target) is str:
1630 getter = lambda: _importer(target)
1631 else:
1632 getter = lambda: target
1633
1634 if not kwargs:
1635 raise ValueError(
1636 'Must supply at least one keyword argument with patch.multiple'
1637 )
1638 # need to wrap in a list for python 3, where items is a view
1639 items = list(kwargs.items())
1640 attribute, new = items[0]
1641 patcher = _patch(
1642 getter, attribute, new, spec, create, spec_set,
1643 autospec, new_callable, {}
1644 )
1645 patcher.attribute_name = attribute
1646 for attribute, new in items[1:]:
1647 this_patcher = _patch(
1648 getter, attribute, new, spec, create, spec_set,
1649 autospec, new_callable, {}
1650 )
1651 this_patcher.attribute_name = attribute
1652 patcher.additional_patchers.append(this_patcher)
1653 return patcher
1654
1655
1656def patch(
1657 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001658 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001659 ):
1660 """
1661 `patch` acts as a function decorator, class decorator or a context
1662 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001663 is patched with a `new` object. When the function/with statement exits
1664 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001665
Miss Islington (bot)eaa1b092019-09-10 06:15:19 -07001666 If `new` is omitted, then the target is replaced with an
1667 `AsyncMock if the patched object is an async function or a
1668 `MagicMock` otherwise. If `patch` is used as a decorator and `new` is
Michael Foord54b3db82012-03-28 15:08:08 +01001669 omitted, the created mock is passed in as an extra argument to the
1670 decorated function. If `patch` is used as a context manager the created
1671 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001672
Michael Foord54b3db82012-03-28 15:08:08 +01001673 `target` should be a string in the form `'package.module.ClassName'`. The
1674 `target` is imported and the specified object replaced with the `new`
1675 object, so the `target` must be importable from the environment you are
1676 calling `patch` from. The target is imported when the decorated function
1677 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001678
1679 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1680 if patch is creating one for you.
1681
1682 In addition you can pass `spec=True` or `spec_set=True`, which causes
1683 patch to pass in the object being mocked as the spec/spec_set object.
1684
1685 `new_callable` allows you to specify a different class, or callable object,
Miss Islington (bot)eaa1b092019-09-10 06:15:19 -07001686 that will be called to create the `new` object. By default `AsyncMock` is
1687 used for async functions and `MagicMock` for the rest.
Michael Foord345266a2012-03-14 12:24:34 -07001688
1689 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001690 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001691 All attributes of the mock will also have the spec of the corresponding
1692 attribute of the object being replaced. Methods and functions being
1693 mocked will have their arguments checked and will raise a `TypeError` if
1694 they are called with the wrong signature. For mocks replacing a class,
1695 their return value (the 'instance') will have the same spec as the class.
1696
1697 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1698 arbitrary object as the spec instead of the one being replaced.
1699
1700 By default `patch` will fail to replace attributes that don't exist. If
1701 you pass in `create=True`, and the attribute doesn't exist, patch will
1702 create the attribute for you when the patched function is called, and
1703 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001704 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001705 default because it can be dangerous. With it switched on you can write
1706 passing tests against APIs that don't actually exist!
1707
1708 Patch can be used as a `TestCase` class decorator. It works by
1709 decorating each test method in the class. This reduces the boilerplate
1710 code when your test methods share a common patchings set. `patch` finds
1711 tests by looking for method names that start with `patch.TEST_PREFIX`.
1712 By default this is `test`, which matches the way `unittest` finds tests.
1713 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1714
1715 Patch can be used as a context manager, with the with statement. Here the
1716 patching applies to the indented block after the with statement. If you
1717 use "as" then the patched object will be bound to the name after the
1718 "as"; very useful if `patch` is creating a mock object for you.
1719
1720 `patch` takes arbitrary keyword arguments. These will be passed to
1721 the `Mock` (or `new_callable`) on construction.
1722
1723 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1724 available for alternate use-cases.
1725 """
1726 getter, attribute = _get_target(target)
1727 return _patch(
1728 getter, attribute, new, spec, create,
1729 spec_set, autospec, new_callable, kwargs
1730 )
1731
1732
1733class _patch_dict(object):
1734 """
1735 Patch a dictionary, or dictionary like object, and restore the dictionary
1736 to its original state after the test.
1737
1738 `in_dict` can be a dictionary or a mapping like container. If it is a
1739 mapping then it must at least support getting, setting and deleting items
1740 plus iterating over keys.
1741
1742 `in_dict` can also be a string specifying the name of the dictionary, which
1743 will then be fetched by importing it.
1744
1745 `values` can be a dictionary of values to set in the dictionary. `values`
1746 can also be an iterable of `(key, value)` pairs.
1747
1748 If `clear` is True then the dictionary will be cleared before the new
1749 values are set.
1750
1751 `patch.dict` can also be called with arbitrary keyword arguments to set
1752 values in the dictionary::
1753
1754 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1755 ...
1756
1757 `patch.dict` can be used as a context manager, decorator or class
1758 decorator. When used as a class decorator `patch.dict` honours
1759 `patch.TEST_PREFIX` for choosing which methods to wrap.
1760 """
1761
1762 def __init__(self, in_dict, values=(), clear=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001763 self.in_dict = in_dict
1764 # support any argument supported by dict(...) constructor
1765 self.values = dict(values)
1766 self.values.update(kwargs)
1767 self.clear = clear
1768 self._original = None
1769
1770
1771 def __call__(self, f):
1772 if isinstance(f, type):
1773 return self.decorate_class(f)
1774 @wraps(f)
1775 def _inner(*args, **kw):
1776 self._patch_dict()
1777 try:
1778 return f(*args, **kw)
1779 finally:
1780 self._unpatch_dict()
1781
1782 return _inner
1783
1784
1785 def decorate_class(self, klass):
1786 for attr in dir(klass):
1787 attr_value = getattr(klass, attr)
1788 if (attr.startswith(patch.TEST_PREFIX) and
1789 hasattr(attr_value, "__call__")):
1790 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1791 decorated = decorator(attr_value)
1792 setattr(klass, attr, decorated)
1793 return klass
1794
1795
1796 def __enter__(self):
1797 """Patch the dict."""
1798 self._patch_dict()
Mario Corchero04530812019-05-28 13:53:31 +01001799 return self.in_dict
Michael Foord345266a2012-03-14 12:24:34 -07001800
1801
1802 def _patch_dict(self):
1803 values = self.values
Xtreaka875ea52019-02-25 00:24:49 +05301804 if isinstance(self.in_dict, str):
1805 self.in_dict = _importer(self.in_dict)
Michael Foord345266a2012-03-14 12:24:34 -07001806 in_dict = self.in_dict
1807 clear = self.clear
1808
1809 try:
1810 original = in_dict.copy()
1811 except AttributeError:
1812 # dict like object with no copy method
1813 # must support iteration over keys
1814 original = {}
1815 for key in in_dict:
1816 original[key] = in_dict[key]
1817 self._original = original
1818
1819 if clear:
1820 _clear_dict(in_dict)
1821
1822 try:
1823 in_dict.update(values)
1824 except AttributeError:
1825 # dict like object with no update method
1826 for key in values:
1827 in_dict[key] = values[key]
1828
1829
1830 def _unpatch_dict(self):
1831 in_dict = self.in_dict
1832 original = self._original
1833
1834 _clear_dict(in_dict)
1835
1836 try:
1837 in_dict.update(original)
1838 except AttributeError:
1839 for key in original:
1840 in_dict[key] = original[key]
1841
1842
1843 def __exit__(self, *args):
1844 """Unpatch the dict."""
1845 self._unpatch_dict()
1846 return False
1847
1848 start = __enter__
1849 stop = __exit__
1850
1851
1852def _clear_dict(in_dict):
1853 try:
1854 in_dict.clear()
1855 except AttributeError:
1856 keys = list(in_dict)
1857 for key in keys:
1858 del in_dict[key]
1859
1860
Michael Foordf7c41582012-06-10 20:36:32 +01001861def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001862 """Stop all active patches. LIFO to unroll nested patches."""
1863 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001864 patch.stop()
1865
1866
Michael Foord345266a2012-03-14 12:24:34 -07001867patch.object = _patch_object
1868patch.dict = _patch_dict
1869patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001870patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001871patch.TEST_PREFIX = 'test'
1872
1873magic_methods = (
1874 "lt le gt ge eq ne "
1875 "getitem setitem delitem "
1876 "len contains iter "
1877 "hash str sizeof "
1878 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001879 # we added divmod and rdivmod here instead of numerics
1880 # because there is no idivmod
1881 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001882 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001883 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001884 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001885 "fspath "
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07001886 "aiter "
Michael Foord345266a2012-03-14 12:24:34 -07001887)
1888
Michael Foordd2623d72014-04-14 11:23:48 -04001889numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001890 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001891)
Michael Foord345266a2012-03-14 12:24:34 -07001892inplace = ' '.join('i%s' % n for n in numerics.split())
1893right = ' '.join('r%s' % n for n in numerics.split())
1894
1895# not including __prepare__, __instancecheck__, __subclasscheck__
1896# (as they are metaclass methods)
1897# __del__ is not supported at all as it causes problems if it exists
1898
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001899_non_defaults = {
1900 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1901 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1902 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1903 '__repr__', '__dir__', '__subclasses__', '__format__',
Lisa Roach865bb682019-09-20 23:00:04 -07001904 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001905}
Michael Foord345266a2012-03-14 12:24:34 -07001906
1907
1908def _get_method(name, func):
1909 "Turns a callable object (like a mock) into a real function"
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001910 def method(self, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -07001911 return func(self, *args, **kw)
1912 method.__name__ = name
1913 return method
1914
1915
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001916_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001917 '__%s__' % method for method in
1918 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001919}
Michael Foord345266a2012-03-14 12:24:34 -07001920
Lisa Roach77b3b772019-05-20 09:19:53 -07001921# Magic methods used for async `with` statements
1922_async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
Lisa Roach865bb682019-09-20 23:00:04 -07001923# Magic methods that are only used with async calls but are synchronous functions themselves
1924_sync_async_magics = {"__aiter__"}
1925_async_magics = _async_method_magics | _sync_async_magics
Lisa Roach77b3b772019-05-20 09:19:53 -07001926
Lisa Roach865bb682019-09-20 23:00:04 -07001927_all_sync_magics = _magics | _non_defaults
1928_all_magics = _all_sync_magics | _async_magics
Michael Foord345266a2012-03-14 12:24:34 -07001929
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001930_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001931 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001932 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001933 '__instancecheck__', '__subclasscheck__',
1934 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001935}
Michael Foord345266a2012-03-14 12:24:34 -07001936
1937_calculate_return_value = {
1938 '__hash__': lambda self: object.__hash__(self),
1939 '__str__': lambda self: object.__str__(self),
1940 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001941 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001942}
1943
1944_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001945 '__lt__': NotImplemented,
1946 '__gt__': NotImplemented,
1947 '__le__': NotImplemented,
1948 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001949 '__int__': 1,
1950 '__contains__': False,
1951 '__len__': 0,
1952 '__exit__': False,
1953 '__complex__': 1j,
1954 '__float__': 1.0,
1955 '__bool__': True,
1956 '__index__': 1,
Lisa Roach77b3b772019-05-20 09:19:53 -07001957 '__aexit__': False,
Michael Foord345266a2012-03-14 12:24:34 -07001958}
1959
1960
1961def _get_eq(self):
1962 def __eq__(other):
1963 ret_val = self.__eq__._mock_return_value
1964 if ret_val is not DEFAULT:
1965 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001966 if self is other:
1967 return True
1968 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001969 return __eq__
1970
1971def _get_ne(self):
1972 def __ne__(other):
1973 if self.__ne__._mock_return_value is not DEFAULT:
1974 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001975 if self is other:
1976 return False
1977 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001978 return __ne__
1979
1980def _get_iter(self):
1981 def __iter__():
1982 ret_val = self.__iter__._mock_return_value
1983 if ret_val is DEFAULT:
1984 return iter([])
1985 # if ret_val was already an iterator, then calling iter on it should
1986 # return the iterator unchanged
1987 return iter(ret_val)
1988 return __iter__
1989
Lisa Roach77b3b772019-05-20 09:19:53 -07001990def _get_async_iter(self):
1991 def __aiter__():
1992 ret_val = self.__aiter__._mock_return_value
1993 if ret_val is DEFAULT:
1994 return _AsyncIterator(iter([]))
1995 return _AsyncIterator(iter(ret_val))
1996 return __aiter__
1997
Michael Foord345266a2012-03-14 12:24:34 -07001998_side_effect_methods = {
1999 '__eq__': _get_eq,
2000 '__ne__': _get_ne,
2001 '__iter__': _get_iter,
Lisa Roach77b3b772019-05-20 09:19:53 -07002002 '__aiter__': _get_async_iter
Michael Foord345266a2012-03-14 12:24:34 -07002003}
2004
2005
2006
2007def _set_return_value(mock, method, name):
2008 fixed = _return_values.get(name, DEFAULT)
2009 if fixed is not DEFAULT:
2010 method.return_value = fixed
2011 return
2012
Miss Islington (bot)cc8edfb2019-09-16 09:52:45 -07002013 return_calculator = _calculate_return_value.get(name)
2014 if return_calculator is not None:
2015 return_value = return_calculator(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002016 method.return_value = return_value
2017 return
2018
2019 side_effector = _side_effect_methods.get(name)
2020 if side_effector is not None:
2021 method.side_effect = side_effector(mock)
2022
2023
2024
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002025class MagicMixin(Base):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002026 def __init__(self, /, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07002027 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10002028 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07002029 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002030
2031
2032 def _mock_set_magics(self):
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002033 orig_magics = _magics | _async_method_magics
2034 these_magics = orig_magics
Michael Foord345266a2012-03-14 12:24:34 -07002035
Łukasz Langaa468db92015-04-13 23:12:42 -07002036 if getattr(self, "_mock_methods", None) is not None:
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002037 these_magics = orig_magics.intersection(self._mock_methods)
Michael Foord345266a2012-03-14 12:24:34 -07002038
2039 remove_magics = set()
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002040 remove_magics = orig_magics - these_magics
Michael Foord345266a2012-03-14 12:24:34 -07002041
2042 for entry in remove_magics:
2043 if entry in type(self).__dict__:
2044 # remove unneeded magic methods
2045 delattr(self, entry)
2046
2047 # don't overwrite existing attributes if called a second time
2048 these_magics = these_magics - set(type(self).__dict__)
2049
2050 _type = type(self)
2051 for entry in these_magics:
2052 setattr(_type, entry, MagicProxy(entry, self))
2053
2054
2055
2056class NonCallableMagicMock(MagicMixin, NonCallableMock):
2057 """A version of `MagicMock` that isn't callable."""
2058 def mock_add_spec(self, spec, spec_set=False):
2059 """Add a spec to a mock. `spec` can either be an object or a
2060 list of strings. Only attributes on the `spec` can be fetched as
2061 attributes from the mock.
2062
2063 If `spec_set` is True then only attributes on the spec can be set."""
2064 self._mock_add_spec(spec, spec_set)
2065 self._mock_set_magics()
2066
2067
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002068class AsyncMagicMixin(MagicMixin):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002069 def __init__(self, /, *args, **kw):
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002070 self._mock_set_magics() # make magic work for kwargs in init
Lisa Roach77b3b772019-05-20 09:19:53 -07002071 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002072 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002073
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002074class MagicMock(MagicMixin, Mock):
Michael Foord345266a2012-03-14 12:24:34 -07002075 """
2076 MagicMock is a subclass of Mock with default implementations
2077 of most of the magic methods. You can use MagicMock without having to
2078 configure the magic methods yourself.
2079
2080 If you use the `spec` or `spec_set` arguments then *only* magic
2081 methods that exist in the spec will be created.
2082
2083 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
2084 """
2085 def mock_add_spec(self, spec, spec_set=False):
2086 """Add a spec to a mock. `spec` can either be an object or a
2087 list of strings. Only attributes on the `spec` can be fetched as
2088 attributes from the mock.
2089
2090 If `spec_set` is True then only attributes on the spec can be set."""
2091 self._mock_add_spec(spec, spec_set)
2092 self._mock_set_magics()
2093
2094
2095
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002096class MagicProxy(Base):
Michael Foord345266a2012-03-14 12:24:34 -07002097 def __init__(self, name, parent):
2098 self.name = name
2099 self.parent = parent
2100
Michael Foord345266a2012-03-14 12:24:34 -07002101 def create_mock(self):
2102 entry = self.name
2103 parent = self.parent
2104 m = parent._get_child_mock(name=entry, _new_name=entry,
2105 _new_parent=parent)
2106 setattr(parent, entry, m)
2107 _set_return_value(parent, m, entry)
2108 return m
2109
2110 def __get__(self, obj, _type=None):
2111 return self.create_mock()
2112
2113
Lisa Roach77b3b772019-05-20 09:19:53 -07002114class AsyncMockMixin(Base):
Lisa Roach77b3b772019-05-20 09:19:53 -07002115 await_count = _delegating_property('await_count')
2116 await_args = _delegating_property('await_args')
2117 await_args_list = _delegating_property('await_args_list')
2118
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002119 def __init__(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002120 super().__init__(*args, **kwargs)
2121 # asyncio.iscoroutinefunction() checks _is_coroutine property to say if an
2122 # object is a coroutine. Without this check it looks to see if it is a
2123 # function/method, which in this case it is not (since it is an
2124 # AsyncMock).
2125 # It is set through __dict__ because when spec_set is True, this
2126 # attribute is likely undefined.
2127 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
Lisa Roach77b3b772019-05-20 09:19:53 -07002128 self.__dict__['_mock_await_count'] = 0
2129 self.__dict__['_mock_await_args'] = None
2130 self.__dict__['_mock_await_args_list'] = _CallList()
2131 code_mock = NonCallableMock(spec_set=CodeType)
2132 code_mock.co_flags = inspect.CO_COROUTINE
2133 self.__dict__['__code__'] = code_mock
2134
Lisa Roachb2744c12019-11-21 10:14:32 -08002135 async def _execute_mock_call(self, /, *args, **kwargs):
2136 # This is nearly just like super(), except for sepcial handling
2137 # of coroutines
Lisa Roach77b3b772019-05-20 09:19:53 -07002138
Miss Islington (bot)f6bdac12020-03-14 00:12:57 -07002139 _call = _Call((args, kwargs), two=True)
Lisa Roachb2744c12019-11-21 10:14:32 -08002140 self.await_count += 1
2141 self.await_args = _call
2142 self.await_args_list.append(_call)
Lisa Roach77b3b772019-05-20 09:19:53 -07002143
Lisa Roachb2744c12019-11-21 10:14:32 -08002144 effect = self.side_effect
2145 if effect is not None:
2146 if _is_exception(effect):
2147 raise effect
2148 elif not _callable(effect):
2149 try:
2150 result = next(effect)
2151 except StopIteration:
2152 # It is impossible to propogate a StopIteration
2153 # through coroutines because of PEP 479
2154 raise StopAsyncIteration
2155 if _is_exception(result):
2156 raise result
2157 elif asyncio.iscoroutinefunction(effect):
2158 result = await effect(*args, **kwargs)
2159 else:
2160 result = effect(*args, **kwargs)
Lisa Roach77b3b772019-05-20 09:19:53 -07002161
Lisa Roachb2744c12019-11-21 10:14:32 -08002162 if result is not DEFAULT:
2163 return result
2164
2165 if self._mock_return_value is not DEFAULT:
2166 return self.return_value
2167
2168 if self._mock_wraps is not None:
2169 if asyncio.iscoroutinefunction(self._mock_wraps):
2170 return await self._mock_wraps(*args, **kwargs)
2171 return self._mock_wraps(*args, **kwargs)
2172
2173 return self.return_value
Lisa Roach77b3b772019-05-20 09:19:53 -07002174
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002175 def assert_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002176 """
2177 Assert that the mock was awaited at least once.
2178 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002179 if self.await_count == 0:
2180 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2181 raise AssertionError(msg)
2182
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002183 def assert_awaited_once(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002184 """
2185 Assert that the mock was awaited exactly once.
2186 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002187 if not self.await_count == 1:
2188 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2189 f" Awaited {self.await_count} times.")
2190 raise AssertionError(msg)
2191
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002192 def assert_awaited_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002193 """
2194 Assert that the last await was with the specified arguments.
2195 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002196 if self.await_args is None:
2197 expected = self._format_mock_call_signature(args, kwargs)
2198 raise AssertionError(f'Expected await: {expected}\nNot awaited')
2199
2200 def _error_message():
Xtreak0ae022c2019-05-29 12:32:26 +05302201 msg = self._format_mock_failure_message(args, kwargs, action='await')
Lisa Roach77b3b772019-05-20 09:19:53 -07002202 return msg
2203
2204 expected = self._call_matcher((args, kwargs))
2205 actual = self._call_matcher(self.await_args)
2206 if expected != actual:
2207 cause = expected if isinstance(expected, Exception) else None
2208 raise AssertionError(_error_message()) from cause
2209
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002210 def assert_awaited_once_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002211 """
2212 Assert that the mock was awaited exactly once and with the specified
2213 arguments.
2214 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002215 if not self.await_count == 1:
2216 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2217 f" Awaited {self.await_count} times.")
2218 raise AssertionError(msg)
2219 return self.assert_awaited_with(*args, **kwargs)
2220
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002221 def assert_any_await(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002222 """
2223 Assert the mock has ever been awaited with the specified arguments.
2224 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002225 expected = self._call_matcher((args, kwargs))
2226 actual = [self._call_matcher(c) for c in self.await_args_list]
2227 if expected not in actual:
2228 cause = expected if isinstance(expected, Exception) else None
2229 expected_string = self._format_mock_call_signature(args, kwargs)
2230 raise AssertionError(
2231 '%s await not found' % expected_string
2232 ) from cause
2233
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002234 def assert_has_awaits(self, calls, any_order=False):
Lisa Roach77b3b772019-05-20 09:19:53 -07002235 """
2236 Assert the mock has been awaited with the specified calls.
2237 The :attr:`await_args_list` list is checked for the awaits.
2238
2239 If `any_order` is False (the default) then the awaits must be
2240 sequential. There can be extra calls before or after the
2241 specified awaits.
2242
2243 If `any_order` is True then the awaits can be in any order, but
2244 they must all appear in :attr:`await_args_list`.
2245 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002246 expected = [self._call_matcher(c) for c in calls]
Miss Islington (bot)1a17a052019-09-24 17:29:17 -07002247 cause = next((e for e in expected if isinstance(e, Exception)), None)
Lisa Roach77b3b772019-05-20 09:19:53 -07002248 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2249 if not any_order:
2250 if expected not in all_awaits:
Miss Islington (bot)1a17a052019-09-24 17:29:17 -07002251 if cause is None:
2252 problem = 'Awaits not found.'
2253 else:
2254 problem = ('Error processing expected awaits.\n'
2255 'Errors: {}').format(
2256 [e if isinstance(e, Exception) else None
2257 for e in expected])
Lisa Roach77b3b772019-05-20 09:19:53 -07002258 raise AssertionError(
Miss Islington (bot)1a17a052019-09-24 17:29:17 -07002259 f'{problem}\n'
2260 f'Expected: {_CallList(calls)}\n'
Lisa Roach77b3b772019-05-20 09:19:53 -07002261 f'Actual: {self.await_args_list}'
2262 ) from cause
2263 return
2264
2265 all_awaits = list(all_awaits)
2266
2267 not_found = []
2268 for kall in expected:
2269 try:
2270 all_awaits.remove(kall)
2271 except ValueError:
2272 not_found.append(kall)
2273 if not_found:
2274 raise AssertionError(
2275 '%r not all found in await list' % (tuple(not_found),)
2276 ) from cause
2277
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002278 def assert_not_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002279 """
2280 Assert that the mock was never awaited.
2281 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002282 if self.await_count != 0:
Xtreakff6b2e62019-05-27 18:26:23 +05302283 msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
Lisa Roach77b3b772019-05-20 09:19:53 -07002284 f" Awaited {self.await_count} times.")
2285 raise AssertionError(msg)
2286
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002287 def reset_mock(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002288 """
2289 See :func:`.Mock.reset_mock()`
2290 """
2291 super().reset_mock(*args, **kwargs)
2292 self.await_count = 0
2293 self.await_args = None
2294 self.await_args_list = _CallList()
2295
2296
2297class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2298 """
2299 Enhance :class:`Mock` with features allowing to mock
2300 an async function.
2301
2302 The :class:`AsyncMock` object will behave so the object is
2303 recognized as an async function, and the result of a call is an awaitable:
2304
2305 >>> mock = AsyncMock()
2306 >>> asyncio.iscoroutinefunction(mock)
2307 True
2308 >>> inspect.isawaitable(mock())
2309 True
2310
2311
2312 The result of ``mock()`` is an async function which will have the outcome
2313 of ``side_effect`` or ``return_value``:
2314
2315 - if ``side_effect`` is a function, the async function will return the
2316 result of that function,
2317 - if ``side_effect`` is an exception, the async function will raise the
2318 exception,
2319 - if ``side_effect`` is an iterable, the async function will return the
2320 next value of the iterable, however, if the sequence of result is
2321 exhausted, ``StopIteration`` is raised immediately,
2322 - if ``side_effect`` is not defined, the async function will return the
2323 value defined by ``return_value``, hence, by default, the async function
2324 returns a new :class:`AsyncMock` object.
2325
2326 If the outcome of ``side_effect`` or ``return_value`` is an async function,
2327 the mock async function obtained when the mock object is called will be this
2328 async function itself (and not an async function returning an async
2329 function).
2330
2331 The test author can also specify a wrapped object with ``wraps``. In this
2332 case, the :class:`Mock` object behavior is the same as with an
2333 :class:`.Mock` object: the wrapped object may have methods
2334 defined as async function functions.
2335
Xtreake7cb23b2019-05-21 14:17:17 +05302336 Based on Martin Richard's asynctest project.
Lisa Roach77b3b772019-05-20 09:19:53 -07002337 """
2338
Michael Foord345266a2012-03-14 12:24:34 -07002339
2340class _ANY(object):
2341 "A helper object that compares equal to everything."
2342
2343 def __eq__(self, other):
2344 return True
2345
2346 def __ne__(self, other):
2347 return False
2348
2349 def __repr__(self):
2350 return '<ANY>'
2351
2352ANY = _ANY()
2353
2354
2355
2356def _format_call_signature(name, args, kwargs):
2357 message = '%s(%%s)' % name
2358 formatted_args = ''
2359 args_string = ', '.join([repr(arg) for arg in args])
2360 kwargs_string = ', '.join([
Miss Islington (bot)bee8bfe2019-09-09 04:42:43 -07002361 '%s=%r' % (key, value) for key, value in kwargs.items()
Michael Foord345266a2012-03-14 12:24:34 -07002362 ])
2363 if args_string:
2364 formatted_args = args_string
2365 if kwargs_string:
2366 if formatted_args:
2367 formatted_args += ', '
2368 formatted_args += kwargs_string
2369
2370 return message % formatted_args
2371
2372
2373
2374class _Call(tuple):
2375 """
2376 A tuple for holding the results of a call to a mock, either in the form
2377 `(args, kwargs)` or `(name, args, kwargs)`.
2378
2379 If args or kwargs are empty then a call tuple will compare equal to
2380 a tuple without those values. This makes comparisons less verbose::
2381
2382 _Call(('name', (), {})) == ('name',)
2383 _Call(('name', (1,), {})) == ('name', (1,))
2384 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2385
2386 The `_Call` object provides a useful shortcut for comparing with call::
2387
2388 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2389 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2390
2391 If the _Call has no name then it will match any name.
2392 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002393 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002394 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002395 args = ()
2396 kwargs = {}
2397 _len = len(value)
2398 if _len == 3:
2399 name, args, kwargs = value
2400 elif _len == 2:
2401 first, second = value
2402 if isinstance(first, str):
2403 name = first
2404 if isinstance(second, tuple):
2405 args = second
2406 else:
2407 kwargs = second
2408 else:
2409 args, kwargs = first, second
2410 elif _len == 1:
2411 value, = value
2412 if isinstance(value, str):
2413 name = value
2414 elif isinstance(value, tuple):
2415 args = value
2416 else:
2417 kwargs = value
2418
2419 if two:
2420 return tuple.__new__(cls, (args, kwargs))
2421
2422 return tuple.__new__(cls, (name, args, kwargs))
2423
2424
2425 def __init__(self, value=(), name=None, parent=None, two=False,
2426 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002427 self._mock_name = name
2428 self._mock_parent = parent
2429 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002430
2431
2432 def __eq__(self, other):
2433 if other is ANY:
2434 return True
2435 try:
2436 len_other = len(other)
2437 except TypeError:
2438 return False
2439
2440 self_name = ''
2441 if len(self) == 2:
2442 self_args, self_kwargs = self
2443 else:
2444 self_name, self_args, self_kwargs = self
2445
Andrew Dunaie63e6172018-12-04 11:08:45 +02002446 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2447 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002448 return False
2449
Michael Foord345266a2012-03-14 12:24:34 -07002450 other_name = ''
2451 if len_other == 0:
2452 other_args, other_kwargs = (), {}
2453 elif len_other == 3:
2454 other_name, other_args, other_kwargs = other
2455 elif len_other == 1:
2456 value, = other
2457 if isinstance(value, tuple):
2458 other_args = value
2459 other_kwargs = {}
2460 elif isinstance(value, str):
2461 other_name = value
2462 other_args, other_kwargs = (), {}
2463 else:
2464 other_args = ()
2465 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002466 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002467 # could be (name, args) or (name, kwargs) or (args, kwargs)
2468 first, second = other
2469 if isinstance(first, str):
2470 other_name = first
2471 if isinstance(second, tuple):
2472 other_args, other_kwargs = second, {}
2473 else:
2474 other_args, other_kwargs = (), second
2475 else:
2476 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002477 else:
2478 return False
Michael Foord345266a2012-03-14 12:24:34 -07002479
2480 if self_name and other_name != self_name:
2481 return False
2482
2483 # this order is important for ANY to work!
2484 return (other_args, other_kwargs) == (self_args, self_kwargs)
2485
2486
Berker Peksagce913872016-03-28 00:30:02 +03002487 __ne__ = object.__ne__
2488
2489
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002490 def __call__(self, /, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002491 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002492 return _Call(('', args, kwargs), name='()')
2493
Andrew Dunaie63e6172018-12-04 11:08:45 +02002494 name = self._mock_name + '()'
2495 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002496
2497
2498 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002499 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002500 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002501 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002502 return _Call(name=name, parent=self, from_kall=False)
2503
2504
Miss Islington (bot)db0d8a52019-09-12 03:52:49 -07002505 def __getattribute__(self, attr):
2506 if attr in tuple.__dict__:
2507 raise AttributeError
2508 return tuple.__getattribute__(self, attr)
2509
2510
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002511 def count(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302512 return self.__getattr__('count')(*args, **kwargs)
2513
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002514 def index(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302515 return self.__getattr__('index')(*args, **kwargs)
2516
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302517 def _get_call_arguments(self):
2518 if len(self) == 2:
2519 args, kwargs = self
2520 else:
2521 name, args, kwargs = self
2522
2523 return args, kwargs
2524
2525 @property
2526 def args(self):
2527 return self._get_call_arguments()[0]
2528
2529 @property
2530 def kwargs(self):
2531 return self._get_call_arguments()[1]
2532
Michael Foord345266a2012-03-14 12:24:34 -07002533 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002534 if not self._mock_from_kall:
2535 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002536 if name.startswith('()'):
2537 name = 'call%s' % name
2538 return name
2539
2540 if len(self) == 2:
2541 name = 'call'
2542 args, kwargs = self
2543 else:
2544 name, args, kwargs = self
2545 if not name:
2546 name = 'call'
2547 elif not name.startswith('()'):
2548 name = 'call.%s' % name
2549 else:
2550 name = 'call%s' % name
2551 return _format_call_signature(name, args, kwargs)
2552
2553
2554 def call_list(self):
2555 """For a call object that represents multiple calls, `call_list`
2556 returns a list of all the intermediate calls as well as the
2557 final call."""
2558 vals = []
2559 thing = self
2560 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002561 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002562 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002563 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002564 return _CallList(reversed(vals))
2565
2566
2567call = _Call(from_kall=False)
2568
2569
Michael Foord345266a2012-03-14 12:24:34 -07002570def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2571 _name=None, **kwargs):
2572 """Create a mock object using another object as a spec. Attributes on the
2573 mock will use the corresponding attribute on the `spec` object as their
2574 spec.
2575
2576 Functions or methods being mocked will have their arguments checked
2577 to check that they are called with the correct signature.
2578
2579 If `spec_set` is True then attempting to set attributes that don't exist
2580 on the spec object will raise an `AttributeError`.
2581
2582 If a class is used as a spec then the return value of the mock (the
2583 instance of the class) will have the same spec. You can use a class as the
2584 spec for an instance object by passing `instance=True`. The returned mock
2585 will only be callable if instances of the mock are callable.
2586
2587 `create_autospec` also takes arbitrary keyword arguments that are passed to
2588 the constructor of the created mock."""
2589 if _is_list(spec):
2590 # can't pass a list instance to the mock constructor as it will be
2591 # interpreted as a list of strings
2592 spec = type(spec)
2593
2594 is_type = isinstance(spec, type)
Xtreakff6b2e62019-05-27 18:26:23 +05302595 is_async_func = _is_async_func(spec)
Michael Foord345266a2012-03-14 12:24:34 -07002596 _kwargs = {'spec': spec}
2597 if spec_set:
2598 _kwargs = {'spec_set': spec}
2599 elif spec is None:
2600 # None we mock with a normal mock without a spec
2601 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002602 if _kwargs and instance:
2603 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002604
2605 _kwargs.update(kwargs)
2606
2607 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002608 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002609 # descriptors don't have a spec
2610 # because we don't know what type they return
2611 _kwargs = {}
Lisa Roach77b3b772019-05-20 09:19:53 -07002612 elif is_async_func:
2613 if instance:
2614 raise RuntimeError("Instance can not be True when create_autospec "
2615 "is mocking an async function")
2616 Klass = AsyncMock
Michael Foord345266a2012-03-14 12:24:34 -07002617 elif not _callable(spec):
2618 Klass = NonCallableMagicMock
2619 elif is_type and instance and not _instance_callable(spec):
2620 Klass = NonCallableMagicMock
2621
Kushal Das484f8a82014-04-16 01:05:50 +05302622 _name = _kwargs.pop('name', _name)
2623
Michael Foord345266a2012-03-14 12:24:34 -07002624 _new_name = _name
2625 if _parent is None:
2626 # for a top level object no _new_name should be set
2627 _new_name = ''
2628
2629 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2630 name=_name, **_kwargs)
2631
2632 if isinstance(spec, FunctionTypes):
2633 # should only happen at the top level because we don't
2634 # recurse for functions
2635 mock = _set_signature(mock, spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07002636 if is_async_func:
Xtreakff6b2e62019-05-27 18:26:23 +05302637 _setup_async_mock(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002638 else:
2639 _check_signature(spec, mock, is_type, instance)
2640
2641 if _parent is not None and not instance:
2642 _parent._mock_children[_name] = mock
2643
2644 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002645 mock.return_value = create_autospec(spec, spec_set, instance=True,
2646 _name='()', _parent=mock)
2647
2648 for entry in dir(spec):
2649 if _is_magic(entry):
2650 # MagicMock already does the useful magic methods for us
2651 continue
2652
Michael Foord345266a2012-03-14 12:24:34 -07002653 # XXXX do we need a better way of getting attributes without
2654 # triggering code execution (?) Probably not - we need the actual
2655 # object to mock it so we would rather trigger a property than mock
2656 # the property descriptor. Likewise we want to mock out dynamically
2657 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002658 # XXXX what about attributes that raise exceptions other than
2659 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002660 # we could be resilient against it, or catch and propagate the
2661 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002662 try:
2663 original = getattr(spec, entry)
2664 except AttributeError:
2665 continue
Michael Foord345266a2012-03-14 12:24:34 -07002666
2667 kwargs = {'spec': original}
2668 if spec_set:
2669 kwargs = {'spec_set': original}
2670
2671 if not isinstance(original, FunctionTypes):
2672 new = _SpecState(original, spec_set, mock, entry, instance)
2673 mock._mock_children[entry] = new
2674 else:
2675 parent = mock
2676 if isinstance(spec, FunctionTypes):
2677 parent = mock.mock
2678
Michael Foord345266a2012-03-14 12:24:34 -07002679 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002680 kwargs['_eat_self'] = skipfirst
Lisa Roach77b3b772019-05-20 09:19:53 -07002681 if asyncio.iscoroutinefunction(original):
2682 child_klass = AsyncMock
2683 else:
2684 child_klass = MagicMock
2685 new = child_klass(parent=parent, name=entry, _new_name=entry,
2686 _new_parent=parent,
2687 **kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002688 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002689 _check_signature(original, new, skipfirst=skipfirst)
2690
2691 # so functions created with _set_signature become instance attributes,
2692 # *plus* their underlying mock exists in _mock_children of the parent
2693 # mock. Adding to _mock_children may be unnecessary where we are also
2694 # setting as an instance attribute?
2695 if isinstance(new, FunctionTypes):
2696 setattr(mock, entry, new)
2697
2698 return mock
2699
2700
2701def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002702 """
2703 Return whether we should skip the first argument on spec's `entry`
2704 attribute.
2705 """
Michael Foord345266a2012-03-14 12:24:34 -07002706 if not isinstance(spec, type):
2707 if entry in getattr(spec, '__dict__', {}):
2708 # instance attribute - shouldn't skip
2709 return False
Michael Foord345266a2012-03-14 12:24:34 -07002710 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002711
2712 for klass in spec.__mro__:
2713 result = klass.__dict__.get(entry, DEFAULT)
2714 if result is DEFAULT:
2715 continue
2716 if isinstance(result, (staticmethod, classmethod)):
2717 return False
Miss Islington (bot)696d2322020-01-29 08:15:36 -08002718 elif isinstance(result, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002719 # Normal method => skip if looked up on type
2720 # (if looked up on instance, self is already skipped)
2721 return is_type
2722 else:
2723 return False
Michael Foord345266a2012-03-14 12:24:34 -07002724
Chris Withersadbf1782019-05-01 23:04:04 +01002725 # function is a dynamically provided attribute
Michael Foord345266a2012-03-14 12:24:34 -07002726 return is_type
2727
2728
Michael Foord345266a2012-03-14 12:24:34 -07002729class _SpecState(object):
2730
2731 def __init__(self, spec, spec_set=False, parent=None,
2732 name=None, ids=None, instance=False):
2733 self.spec = spec
2734 self.ids = ids
2735 self.spec_set = spec_set
2736 self.parent = parent
2737 self.instance = instance
2738 self.name = name
2739
2740
2741FunctionTypes = (
2742 # python function
2743 type(create_autospec),
2744 # instance method
2745 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002746)
2747
Michael Foord345266a2012-03-14 12:24:34 -07002748
Michael Foorda74561a2012-03-25 19:03:13 +01002749file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002750
Michael Foord04cbe0c2013-03-19 17:22:51 -07002751
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002752def _to_stream(read_data):
2753 if isinstance(read_data, bytes):
2754 return io.BytesIO(read_data)
Michael Foord04cbe0c2013-03-19 17:22:51 -07002755 else:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002756 return io.StringIO(read_data)
Michael Foord0dccf652012-03-25 19:11:50 +01002757
Robert Collins5329aaa2015-07-17 20:08:45 +12002758
Michael Foord0dccf652012-03-25 19:11:50 +01002759def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002760 """
2761 A helper function to create a mock to replace the use of `open`. It works
2762 for `open` called directly or used as a context manager.
2763
2764 The `mock` argument is the mock object to configure. If `None` (the
2765 default) then a `MagicMock` will be created for you, with the API limited
2766 to methods or attributes available on standard file handles.
2767
Xtreak71f82a22018-12-20 21:30:21 +05302768 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002769 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002770 """
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002771 _read_data = _to_stream(read_data)
2772 _state = [_read_data, None]
2773
Robert Collinsca647ef2015-07-24 03:48:20 +12002774 def _readlines_side_effect(*args, **kwargs):
2775 if handle.readlines.return_value is not None:
2776 return handle.readlines.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002777 return _state[0].readlines(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002778
2779 def _read_side_effect(*args, **kwargs):
2780 if handle.read.return_value is not None:
2781 return handle.read.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002782 return _state[0].read(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002783
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002784 def _readline_side_effect(*args, **kwargs):
Tony Flury20870232018-09-12 23:21:16 +01002785 yield from _iter_side_effect()
2786 while True:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002787 yield _state[0].readline(*args, **kwargs)
Tony Flury20870232018-09-12 23:21:16 +01002788
2789 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002790 if handle.readline.return_value is not None:
2791 while True:
2792 yield handle.readline.return_value
2793 for line in _state[0]:
2794 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002795
Damien Nadé394119a2019-05-23 12:03:25 +02002796 def _next_side_effect():
2797 if handle.readline.return_value is not None:
2798 return handle.readline.return_value
2799 return next(_state[0])
2800
Michael Foorda74561a2012-03-25 19:03:13 +01002801 global file_spec
2802 if file_spec is None:
2803 import _io
2804 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2805
Michael Foord345266a2012-03-14 12:24:34 -07002806 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002807 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002808
Robert Collinsca647ef2015-07-24 03:48:20 +12002809 handle = MagicMock(spec=file_spec)
2810 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002811
Robert Collinsca647ef2015-07-24 03:48:20 +12002812 handle.write.return_value = None
2813 handle.read.return_value = None
2814 handle.readline.return_value = None
2815 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002816
Robert Collinsca647ef2015-07-24 03:48:20 +12002817 handle.read.side_effect = _read_side_effect
2818 _state[1] = _readline_side_effect()
2819 handle.readline.side_effect = _state[1]
2820 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002821 handle.__iter__.side_effect = _iter_side_effect
Damien Nadé394119a2019-05-23 12:03:25 +02002822 handle.__next__.side_effect = _next_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002823
Robert Collinsca647ef2015-07-24 03:48:20 +12002824 def reset_data(*args, **kwargs):
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002825 _state[0] = _to_stream(read_data)
Robert Collinsca647ef2015-07-24 03:48:20 +12002826 if handle.readline.side_effect == _state[1]:
2827 # Only reset the side effect if the user hasn't overridden it.
2828 _state[1] = _readline_side_effect()
2829 handle.readline.side_effect = _state[1]
2830 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002831
Robert Collinsca647ef2015-07-24 03:48:20 +12002832 mock.side_effect = reset_data
2833 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002834 return mock
2835
2836
2837class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002838 """
2839 A mock intended to be used as a property, or other descriptor, on a class.
2840 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2841 a return value when it is fetched.
2842
2843 Fetching a `PropertyMock` instance from an object calls the mock, with
2844 no args. Setting it calls the mock with the value being set.
2845 """
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002846 def _get_child_mock(self, /, **kwargs):
Michael Foordc2870622012-04-13 16:57:22 +01002847 return MagicMock(**kwargs)
2848
Miss Islington (bot)c71ae1a2019-08-29 02:02:51 -07002849 def __get__(self, obj, obj_type=None):
Michael Foord345266a2012-03-14 12:24:34 -07002850 return self()
2851 def __set__(self, obj, val):
2852 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002853
2854
2855def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002856 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002857
2858 Given an input Mock, seals it to ensure no further mocks will be generated
2859 when accessing an attribute that was not already defined.
2860
Mario Corchero96200eb2018-10-19 22:57:37 +01002861 The operation recursively seals the mock passed in, meaning that
2862 the mock itself, any mocks generated by accessing one of its attributes,
2863 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002864 """
2865 mock._mock_sealed = True
2866 for attr in dir(mock):
2867 try:
2868 m = getattr(mock, attr)
2869 except AttributeError:
2870 continue
2871 if not isinstance(m, NonCallableMock):
2872 continue
2873 if m._mock_new_parent is mock:
2874 seal(m)
Lisa Roach77b3b772019-05-20 09:19:53 -07002875
2876
Lisa Roach77b3b772019-05-20 09:19:53 -07002877class _AsyncIterator:
2878 """
2879 Wraps an iterator in an asynchronous iterator.
2880 """
2881 def __init__(self, iterator):
2882 self.iterator = iterator
2883 code_mock = NonCallableMock(spec_set=CodeType)
2884 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
2885 self.__dict__['__code__'] = code_mock
2886
2887 def __aiter__(self):
2888 return self
2889
2890 async def __anext__(self):
2891 try:
2892 return next(self.iterator)
2893 except StopIteration:
2894 pass
2895 raise StopAsyncIteration