blob: b06e29cf01c95b355ffd22f178e7c5b7ee0bad64 [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):
Lisa Roachf1a297a2019-09-10 12:18:40 +010049 if _is_instance_mock(obj) and not isinstance(obj, AsyncMock):
Lisa Roach77b3b772019-05-20 09:19:53 -070050 return False
Lisa Roachf1a297a2019-09-10 12:18:40 +010051 return asyncio.iscoroutinefunction(obj) or inspect.isawaitable(obj)
Lisa Roach77b3b772019-05-20 09:19:53 -070052
53
Xtreakff6b2e62019-05-27 18:26:23 +053054def _is_async_func(func):
55 if getattr(func, '__code__', None):
56 return asyncio.iscoroutinefunction(func)
57 else:
58 return False
59
60
Michael Foord345266a2012-03-14 12:24:34 -070061def _is_instance_mock(obj):
62 # can't use isinstance on Mock objects because they override __class__
63 # The base class for all mocks is NonCallableMock
64 return issubclass(type(obj), NonCallableMock)
65
66
67def _is_exception(obj):
68 return (
Chris Withers49e27f02019-05-01 08:48:44 +010069 isinstance(obj, BaseException) or
70 isinstance(obj, type) and issubclass(obj, BaseException)
Michael Foord345266a2012-03-14 12:24:34 -070071 )
72
73
Xtreak7397cda2019-07-22 13:08:22 +053074def _extract_mock(obj):
75 # Autospecced functions will return a FunctionType with "mock" attribute
76 # which is the actual mock object that needs to be used.
77 if isinstance(obj, FunctionTypes) and hasattr(obj, 'mock'):
78 return obj.mock
79 else:
80 return obj
81
82
Antoine Pitrou5c64df72013-02-03 00:23:58 +010083def _get_signature_object(func, as_instance, eat_self):
84 """
85 Given an arbitrary, possibly callable object, try to create a suitable
86 signature object.
87 Return a (reduced func, signature) tuple, or None.
88 """
89 if isinstance(func, type) and not as_instance:
90 # If it's a type and should be modelled as a type, use __init__.
Chris Withersadbf1782019-05-01 23:04:04 +010091 func = func.__init__
Antoine Pitrou5c64df72013-02-03 00:23:58 +010092 # Skip the `self` argument in __init__
93 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070094 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010095 # If we really want to model an instance of the passed type,
96 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070097 try:
98 func = func.__call__
99 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100100 return None
101 if eat_self:
102 sig_func = partial(func, None)
103 else:
104 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -0700105 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100106 return func, inspect.signature(sig_func)
107 except ValueError:
108 # Certain callable types are not supported by inspect.signature()
109 return None
Michael Foord345266a2012-03-14 12:24:34 -0700110
111
112def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100113 sig = _get_signature_object(func, instance, skipfirst)
114 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -0700115 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100116 func, sig = sig
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300117 def checksig(self, /, *args, **kwargs):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100118 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700119 _copy_func_details(func, checksig)
120 type(mock)._mock_check_sig = checksig
Xtreakf7fa62e2018-12-12 13:24:54 +0530121 type(mock).__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700122
123
124def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700125 # we explicitly don't copy func.__dict__ into this copy as it would
126 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300127 for attribute in (
128 '__name__', '__doc__', '__text_signature__',
129 '__module__', '__defaults__', '__kwdefaults__',
130 ):
131 try:
132 setattr(funcopy, attribute, getattr(func, attribute))
133 except AttributeError:
134 pass
Michael Foord345266a2012-03-14 12:24:34 -0700135
136
137def _callable(obj):
138 if isinstance(obj, type):
139 return True
Xtreak9b218562019-04-22 08:00:23 +0530140 if isinstance(obj, (staticmethod, classmethod, MethodType)):
141 return _callable(obj.__func__)
Michael Foord345266a2012-03-14 12:24:34 -0700142 if getattr(obj, '__call__', None) is not None:
143 return True
144 return False
145
146
147def _is_list(obj):
148 # checks for list or tuples
149 # XXXX badly named!
150 return type(obj) in (list, tuple)
151
152
153def _instance_callable(obj):
154 """Given an object, return True if the object is callable.
155 For classes, return True if instances would be callable."""
156 if not isinstance(obj, type):
157 # already an instance
158 return getattr(obj, '__call__', None) is not None
159
Michael Foorda74b3aa2012-03-14 14:40:22 -0700160 # *could* be broken by a class overriding __mro__ or __dict__ via
161 # a metaclass
162 for base in (obj,) + obj.__mro__:
163 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700164 return True
165 return False
166
167
168def _set_signature(mock, original, instance=False):
169 # creates a function with signature (*args, **kwargs) that delegates to a
170 # mock. It still does signature checking by calling a lambda with the same
171 # signature as the original.
Michael Foord345266a2012-03-14 12:24:34 -0700172
173 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100174 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700175 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700176 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100177 func, sig = result
178 def checksig(*args, **kwargs):
179 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700180 _copy_func_details(func, checksig)
181
182 name = original.__name__
183 if not name.isidentifier():
184 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100185 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700186 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100187 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700188 return mock(*args, **kwargs)""" % name
189 exec (src, context)
190 funcopy = context[name]
Xtreakf7fa62e2018-12-12 13:24:54 +0530191 _setup_func(funcopy, mock, sig)
Michael Foord345266a2012-03-14 12:24:34 -0700192 return funcopy
193
194
Xtreakf7fa62e2018-12-12 13:24:54 +0530195def _setup_func(funcopy, mock, sig):
Michael Foord345266a2012-03-14 12:24:34 -0700196 funcopy.mock = mock
197
Michael Foord345266a2012-03-14 12:24:34 -0700198 def assert_called_with(*args, **kwargs):
199 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700200 def assert_called(*args, **kwargs):
201 return mock.assert_called(*args, **kwargs)
202 def assert_not_called(*args, **kwargs):
203 return mock.assert_not_called(*args, **kwargs)
204 def assert_called_once(*args, **kwargs):
205 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700206 def assert_called_once_with(*args, **kwargs):
207 return mock.assert_called_once_with(*args, **kwargs)
208 def assert_has_calls(*args, **kwargs):
209 return mock.assert_has_calls(*args, **kwargs)
210 def assert_any_call(*args, **kwargs):
211 return mock.assert_any_call(*args, **kwargs)
212 def reset_mock():
213 funcopy.method_calls = _CallList()
214 funcopy.mock_calls = _CallList()
215 mock.reset_mock()
216 ret = funcopy.return_value
217 if _is_instance_mock(ret) and not ret is mock:
218 ret.reset_mock()
219
220 funcopy.called = False
221 funcopy.call_count = 0
222 funcopy.call_args = None
223 funcopy.call_args_list = _CallList()
224 funcopy.method_calls = _CallList()
225 funcopy.mock_calls = _CallList()
226
227 funcopy.return_value = mock.return_value
228 funcopy.side_effect = mock.side_effect
229 funcopy._mock_children = mock._mock_children
230
231 funcopy.assert_called_with = assert_called_with
232 funcopy.assert_called_once_with = assert_called_once_with
233 funcopy.assert_has_calls = assert_has_calls
234 funcopy.assert_any_call = assert_any_call
235 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700236 funcopy.assert_called = assert_called
237 funcopy.assert_not_called = assert_not_called
238 funcopy.assert_called_once = assert_called_once
Xtreakf7fa62e2018-12-12 13:24:54 +0530239 funcopy.__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700240
241 mock._mock_delegate = funcopy
242
243
Xtreakff6b2e62019-05-27 18:26:23 +0530244def _setup_async_mock(mock):
245 mock._is_coroutine = asyncio.coroutines._is_coroutine
246 mock.await_count = 0
247 mock.await_args = None
248 mock.await_args_list = _CallList()
Xtreakff6b2e62019-05-27 18:26:23 +0530249
250 # Mock is not configured yet so the attributes are set
251 # to a function and then the corresponding mock helper function
252 # is called when the helper is accessed similar to _setup_func.
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300253 def wrapper(attr, /, *args, **kwargs):
Xtreakff6b2e62019-05-27 18:26:23 +0530254 return getattr(mock.mock, attr)(*args, **kwargs)
255
256 for attribute in ('assert_awaited',
257 'assert_awaited_once',
258 'assert_awaited_with',
259 'assert_awaited_once_with',
260 'assert_any_await',
261 'assert_has_awaits',
262 'assert_not_awaited'):
263
264 # setattr(mock, attribute, wrapper) causes late binding
265 # hence attribute will always be the last value in the loop
266 # Use partial(wrapper, attribute) to ensure the attribute is bound
267 # correctly.
268 setattr(mock, attribute, partial(wrapper, attribute))
269
270
Michael Foord345266a2012-03-14 12:24:34 -0700271def _is_magic(name):
272 return '__%s__' % name[2:-2] == name
273
274
275class _SentinelObject(object):
276 "A unique, named, sentinel object."
277 def __init__(self, name):
278 self.name = name
279
280 def __repr__(self):
281 return 'sentinel.%s' % self.name
282
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200283 def __reduce__(self):
284 return 'sentinel.%s' % self.name
285
Michael Foord345266a2012-03-14 12:24:34 -0700286
287class _Sentinel(object):
288 """Access attributes to return a named object, usable as a sentinel."""
289 def __init__(self):
290 self._sentinels = {}
291
292 def __getattr__(self, name):
293 if name == '__bases__':
294 # Without this help(unittest.mock) raises an exception
295 raise AttributeError
296 return self._sentinels.setdefault(name, _SentinelObject(name))
297
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200298 def __reduce__(self):
299 return 'sentinel'
300
Michael Foord345266a2012-03-14 12:24:34 -0700301
302sentinel = _Sentinel()
303
304DEFAULT = sentinel.DEFAULT
305_missing = sentinel.MISSING
306_deleted = sentinel.DELETED
307
308
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200309_allowed_names = {
310 'return_value', '_mock_return_value', 'side_effect',
311 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
312 '_mock_name', '_mock_new_name'
313}
Michael Foord345266a2012-03-14 12:24:34 -0700314
315
316def _delegating_property(name):
317 _allowed_names.add(name)
318 _the_name = '_mock_' + name
319 def _get(self, name=name, _the_name=_the_name):
320 sig = self._mock_delegate
321 if sig is None:
322 return getattr(self, _the_name)
323 return getattr(sig, name)
324 def _set(self, value, name=name, _the_name=_the_name):
325 sig = self._mock_delegate
326 if sig is None:
327 self.__dict__[_the_name] = value
328 else:
329 setattr(sig, name, value)
330
331 return property(_get, _set)
332
333
334
335class _CallList(list):
336
337 def __contains__(self, value):
338 if not isinstance(value, list):
339 return list.__contains__(self, value)
340 len_value = len(value)
341 len_self = len(self)
342 if len_value > len_self:
343 return False
344
345 for i in range(0, len_self - len_value + 1):
346 sub_list = self[i:i+len_value]
347 if sub_list == value:
348 return True
349 return False
350
351 def __repr__(self):
352 return pprint.pformat(list(self))
353
354
355def _check_and_set_parent(parent, value, name, new_name):
Xtreak7397cda2019-07-22 13:08:22 +0530356 value = _extract_mock(value)
Xtreak9c3f2842019-02-26 03:16:34 +0530357
Michael Foord345266a2012-03-14 12:24:34 -0700358 if not _is_instance_mock(value):
359 return False
360 if ((value._mock_name or value._mock_new_name) or
361 (value._mock_parent is not None) or
362 (value._mock_new_parent is not None)):
363 return False
364
365 _parent = parent
366 while _parent is not None:
367 # setting a mock (value) as a child or return value of itself
368 # should not modify the mock
369 if _parent is value:
370 return False
371 _parent = _parent._mock_new_parent
372
373 if new_name:
374 value._mock_new_parent = parent
375 value._mock_new_name = new_name
376 if name:
377 value._mock_parent = parent
378 value._mock_name = name
379 return True
380
Michael Foord01bafdc2014-04-14 16:09:42 -0400381# Internal class to identify if we wrapped an iterator object or not.
382class _MockIter(object):
383 def __init__(self, obj):
384 self.obj = iter(obj)
Michael Foord01bafdc2014-04-14 16:09:42 -0400385 def __next__(self):
386 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700387
388class Base(object):
389 _mock_return_value = DEFAULT
390 _mock_side_effect = None
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300391 def __init__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700392 pass
393
394
395
396class NonCallableMock(Base):
397 """A non-callable version of `Mock`"""
398
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300399 def __new__(cls, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700400 # every instance has its own class
401 # so we can create magic methods on the
402 # class without stomping on other mocks
Lisa Roach77b3b772019-05-20 09:19:53 -0700403 bases = (cls,)
Michael Foord14fd9252019-09-13 18:40:56 +0200404 if not issubclass(cls, AsyncMockMixin):
Lisa Roach77b3b772019-05-20 09:19:53 -0700405 # Check if spec is an async object or function
Michael Foord14fd9252019-09-13 18:40:56 +0200406 bound_args = _MOCK_SIG.bind_partial(cls, *args, **kw).arguments
407 spec_arg = bound_args.get('spec_set', bound_args.get('spec'))
408 if spec_arg and _is_async_obj(spec_arg):
409 bases = (AsyncMockMixin, cls)
Lisa Roach77b3b772019-05-20 09:19:53 -0700410 new = type(cls.__name__, bases, {'__doc__': cls.__doc__})
Lisa Roach9a7d9512019-09-28 18:42:44 -0700411 instance = _safe_super(NonCallableMock, cls).__new__(new)
Michael Foord345266a2012-03-14 12:24:34 -0700412 return instance
413
414
415 def __init__(
416 self, spec=None, wraps=None, name=None, spec_set=None,
417 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530418 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700419 ):
420 if _new_parent is None:
421 _new_parent = parent
422
423 __dict__ = self.__dict__
424 __dict__['_mock_parent'] = parent
425 __dict__['_mock_name'] = name
426 __dict__['_mock_new_name'] = _new_name
427 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100428 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700429
430 if spec_set is not None:
431 spec = spec_set
432 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100433 if _eat_self is None:
434 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700435
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100436 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700437
438 __dict__['_mock_children'] = {}
439 __dict__['_mock_wraps'] = wraps
440 __dict__['_mock_delegate'] = None
441
442 __dict__['_mock_called'] = False
443 __dict__['_mock_call_args'] = None
444 __dict__['_mock_call_count'] = 0
445 __dict__['_mock_call_args_list'] = _CallList()
446 __dict__['_mock_mock_calls'] = _CallList()
447
448 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530449 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700450
451 if kwargs:
452 self.configure_mock(**kwargs)
453
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000454 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700455 spec, wraps, name, spec_set, parent,
456 _spec_state
457 )
458
459
460 def attach_mock(self, mock, attribute):
461 """
462 Attach a mock as an attribute of this one, replacing its name and
463 parent. Calls to the attached mock will be recorded in the
464 `method_calls` and `mock_calls` attributes of this one."""
Xtreak7397cda2019-07-22 13:08:22 +0530465 inner_mock = _extract_mock(mock)
466
467 inner_mock._mock_parent = None
468 inner_mock._mock_new_parent = None
469 inner_mock._mock_name = ''
470 inner_mock._mock_new_name = None
Michael Foord345266a2012-03-14 12:24:34 -0700471
472 setattr(self, attribute, mock)
473
474
475 def mock_add_spec(self, spec, spec_set=False):
476 """Add a spec to a mock. `spec` can either be an object or a
477 list of strings. Only attributes on the `spec` can be fetched as
478 attributes from the mock.
479
480 If `spec_set` is True then only attributes on the spec can be set."""
481 self._mock_add_spec(spec, spec_set)
482
483
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100484 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
485 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700486 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100487 _spec_signature = None
Lisa Roach77b3b772019-05-20 09:19:53 -0700488 _spec_asyncs = []
489
490 for attr in dir(spec):
491 if asyncio.iscoroutinefunction(getattr(spec, attr, None)):
492 _spec_asyncs.append(attr)
Michael Foord345266a2012-03-14 12:24:34 -0700493
494 if spec is not None and not _is_list(spec):
495 if isinstance(spec, type):
496 _spec_class = spec
497 else:
Chris Withersadbf1782019-05-01 23:04:04 +0100498 _spec_class = type(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100499 res = _get_signature_object(spec,
500 _spec_as_instance, _eat_self)
501 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700502
503 spec = dir(spec)
504
505 __dict__ = self.__dict__
506 __dict__['_spec_class'] = _spec_class
507 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100508 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700509 __dict__['_mock_methods'] = spec
Lisa Roach77b3b772019-05-20 09:19:53 -0700510 __dict__['_spec_asyncs'] = _spec_asyncs
Michael Foord345266a2012-03-14 12:24:34 -0700511
512 def __get_return_value(self):
513 ret = self._mock_return_value
514 if self._mock_delegate is not None:
515 ret = self._mock_delegate.return_value
516
517 if ret is DEFAULT:
518 ret = self._get_child_mock(
519 _new_parent=self, _new_name='()'
520 )
521 self.return_value = ret
522 return ret
523
524
525 def __set_return_value(self, value):
526 if self._mock_delegate is not None:
527 self._mock_delegate.return_value = value
528 else:
529 self._mock_return_value = value
530 _check_and_set_parent(self, value, None, '()')
531
532 __return_value_doc = "The value to be returned when the mock is called."
533 return_value = property(__get_return_value, __set_return_value,
534 __return_value_doc)
535
536
537 @property
538 def __class__(self):
539 if self._spec_class is None:
540 return type(self)
541 return self._spec_class
542
543 called = _delegating_property('called')
544 call_count = _delegating_property('call_count')
545 call_args = _delegating_property('call_args')
546 call_args_list = _delegating_property('call_args_list')
547 mock_calls = _delegating_property('mock_calls')
548
549
550 def __get_side_effect(self):
551 delegated = self._mock_delegate
552 if delegated is None:
553 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400554 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200555 if (sf is not None and not callable(sf)
556 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400557 sf = _MockIter(sf)
558 delegated.side_effect = sf
559 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700560
561 def __set_side_effect(self, value):
562 value = _try_iter(value)
563 delegated = self._mock_delegate
564 if delegated is None:
565 self._mock_side_effect = value
566 else:
567 delegated.side_effect = value
568
569 side_effect = property(__get_side_effect, __set_side_effect)
570
571
Kushal Das9cd39a12016-06-02 10:20:16 -0700572 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700573 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200574 if visited is None:
575 visited = []
576 if id(self) in visited:
577 return
578 visited.append(id(self))
579
Michael Foord345266a2012-03-14 12:24:34 -0700580 self.called = False
581 self.call_args = None
582 self.call_count = 0
583 self.mock_calls = _CallList()
584 self.call_args_list = _CallList()
585 self.method_calls = _CallList()
586
Kushal Das9cd39a12016-06-02 10:20:16 -0700587 if return_value:
588 self._mock_return_value = DEFAULT
589 if side_effect:
590 self._mock_side_effect = None
591
Michael Foord345266a2012-03-14 12:24:34 -0700592 for child in self._mock_children.values():
Xtreakedeca922018-12-01 15:33:54 +0530593 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100594 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200595 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700596
597 ret = self._mock_return_value
598 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200599 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700600
601
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300602 def configure_mock(self, /, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700603 """Set attributes on the mock through keyword arguments.
604
605 Attributes plus return values and side effects can be set on child
606 mocks using standard dot notation and unpacking a dictionary in the
607 method call:
608
609 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
610 >>> mock.configure_mock(**attrs)"""
611 for arg, val in sorted(kwargs.items(),
612 # we sort on the number of dots so that
613 # attributes are set before we set attributes on
614 # attributes
615 key=lambda entry: entry[0].count('.')):
616 args = arg.split('.')
617 final = args.pop()
618 obj = self
619 for entry in args:
620 obj = getattr(obj, entry)
621 setattr(obj, final, val)
622
623
624 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530625 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700626 raise AttributeError(name)
627 elif self._mock_methods is not None:
628 if name not in self._mock_methods or name in _all_magics:
629 raise AttributeError("Mock object has no attribute %r" % name)
630 elif _is_magic(name):
631 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530632 if not self._mock_unsafe:
633 if name.startswith(('assert', 'assret')):
Zackery Spytzb9b08cd2019-05-08 11:32:24 -0600634 raise AttributeError("Attributes cannot start with 'assert' "
635 "or 'assret'")
Michael Foord345266a2012-03-14 12:24:34 -0700636
637 result = self._mock_children.get(name)
638 if result is _deleted:
639 raise AttributeError(name)
640 elif result is None:
641 wraps = None
642 if self._mock_wraps is not None:
643 # XXXX should we get the attribute without triggering code
644 # execution?
645 wraps = getattr(self._mock_wraps, name)
646
647 result = self._get_child_mock(
648 parent=self, name=name, wraps=wraps, _new_name=name,
649 _new_parent=self
650 )
651 self._mock_children[name] = result
652
653 elif isinstance(result, _SpecState):
654 result = create_autospec(
655 result.spec, result.spec_set, result.instance,
656 result.parent, result.name
657 )
658 self._mock_children[name] = result
659
660 return result
661
662
Mario Corchero552be9d2017-10-17 12:35:11 +0100663 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700664 _name_list = [self._mock_new_name]
665 _parent = self._mock_new_parent
666 last = self
667
668 dot = '.'
669 if _name_list == ['()']:
670 dot = ''
Chris Withersadbf1782019-05-01 23:04:04 +0100671
Michael Foord345266a2012-03-14 12:24:34 -0700672 while _parent is not None:
673 last = _parent
674
675 _name_list.append(_parent._mock_new_name + dot)
676 dot = '.'
677 if _parent._mock_new_name == '()':
678 dot = ''
679
680 _parent = _parent._mock_new_parent
681
Michael Foord345266a2012-03-14 12:24:34 -0700682 _name_list = list(reversed(_name_list))
683 _first = last._mock_name or 'mock'
684 if len(_name_list) > 1:
685 if _name_list[1] not in ('()', '().'):
686 _first += '.'
687 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100688 return ''.join(_name_list)
689
690 def __repr__(self):
691 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700692
693 name_string = ''
694 if name not in ('mock', 'mock.'):
695 name_string = ' name=%r' % name
696
697 spec_string = ''
698 if self._spec_class is not None:
699 spec_string = ' spec=%r'
700 if self._spec_set:
701 spec_string = ' spec_set=%r'
702 spec_string = spec_string % self._spec_class.__name__
703 return "<%s%s%s id='%s'>" % (
704 type(self).__name__,
705 name_string,
706 spec_string,
707 id(self)
708 )
709
710
711 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700712 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100713 if not FILTER_DIR:
714 return object.__dir__(self)
715
Michael Foord345266a2012-03-14 12:24:34 -0700716 extras = self._mock_methods or []
717 from_type = dir(type(self))
718 from_dict = list(self.__dict__)
Mario Corchero0df635c2019-04-30 19:56:36 +0100719 from_child_mocks = [
720 m_name for m_name, m_value in self._mock_children.items()
721 if m_value is not _deleted]
Michael Foord345266a2012-03-14 12:24:34 -0700722
Michael Foord313f85f2012-03-25 18:16:07 +0100723 from_type = [e for e in from_type if not e.startswith('_')]
724 from_dict = [e for e in from_dict if not e.startswith('_') or
725 _is_magic(e)]
Mario Corchero0df635c2019-04-30 19:56:36 +0100726 return sorted(set(extras + from_type + from_dict + from_child_mocks))
Michael Foord345266a2012-03-14 12:24:34 -0700727
728
729 def __setattr__(self, name, value):
730 if name in _allowed_names:
731 # property setters go through here
732 return object.__setattr__(self, name, value)
733 elif (self._spec_set and self._mock_methods is not None and
734 name not in self._mock_methods and
735 name not in self.__dict__):
736 raise AttributeError("Mock object has no attribute '%s'" % name)
737 elif name in _unsupported_magics:
738 msg = 'Attempting to set unsupported magic method %r.' % name
739 raise AttributeError(msg)
740 elif name in _all_magics:
741 if self._mock_methods is not None and name not in self._mock_methods:
742 raise AttributeError("Mock object has no attribute '%s'" % name)
743
744 if not _is_instance_mock(value):
745 setattr(type(self), name, _get_method(name, value))
746 original = value
747 value = lambda *args, **kw: original(self, *args, **kw)
748 else:
749 # only set _new_name and not name so that mock_calls is tracked
750 # but not method calls
751 _check_and_set_parent(self, value, None, name)
752 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100753 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700754 elif name == '__class__':
755 self._spec_class = value
756 return
757 else:
758 if _check_and_set_parent(self, value, name, name):
759 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100760
761 if self._mock_sealed and not hasattr(self, name):
762 mock_name = f'{self._extract_mock_name()}.{name}'
763 raise AttributeError(f'Cannot set {mock_name}')
764
Michael Foord345266a2012-03-14 12:24:34 -0700765 return object.__setattr__(self, name, value)
766
767
768 def __delattr__(self, name):
769 if name in _all_magics and name in type(self).__dict__:
770 delattr(type(self), name)
771 if name not in self.__dict__:
772 # for magic methods that are still MagicProxy objects and
773 # not set on the instance itself
774 return
775
Michael Foord345266a2012-03-14 12:24:34 -0700776 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000777 if name in self.__dict__:
Xtreak830b43d2019-04-14 00:42:33 +0530778 _safe_super(NonCallableMock, self).__delattr__(name)
Pablo Galindo222d3032019-01-21 08:57:46 +0000779 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700780 raise AttributeError(name)
781 if obj is not _missing:
782 del self._mock_children[name]
783 self._mock_children[name] = _deleted
784
785
Michael Foord345266a2012-03-14 12:24:34 -0700786 def _format_mock_call_signature(self, args, kwargs):
787 name = self._mock_name or 'mock'
788 return _format_call_signature(name, args, kwargs)
789
790
Xtreak0ae022c2019-05-29 12:32:26 +0530791 def _format_mock_failure_message(self, args, kwargs, action='call'):
792 message = 'expected %s not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700793 expected_string = self._format_mock_call_signature(args, kwargs)
794 call_args = self.call_args
Michael Foord345266a2012-03-14 12:24:34 -0700795 actual_string = self._format_mock_call_signature(*call_args)
Xtreak0ae022c2019-05-29 12:32:26 +0530796 return message % (action, expected_string, actual_string)
Michael Foord345266a2012-03-14 12:24:34 -0700797
798
Xtreakc9612782019-08-29 11:39:01 +0530799 def _get_call_signature_from_name(self, name):
800 """
801 * If call objects are asserted against a method/function like obj.meth1
802 then there could be no name for the call object to lookup. Hence just
803 return the spec_signature of the method/function being asserted against.
804 * If the name is not empty then remove () and split by '.' to get
805 list of names to iterate through the children until a potential
806 match is found. A child mock is created only during attribute access
807 so if we get a _SpecState then no attributes of the spec were accessed
808 and can be safely exited.
809 """
810 if not name:
811 return self._spec_signature
812
813 sig = None
814 names = name.replace('()', '').split('.')
815 children = self._mock_children
816
817 for name in names:
818 child = children.get(name)
819 if child is None or isinstance(child, _SpecState):
820 break
821 else:
822 children = child._mock_children
823 sig = child._spec_signature
824
825 return sig
826
827
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100828 def _call_matcher(self, _call):
829 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000830 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100831 comparison key suitable for matching with other calls.
832 This is a best effort method which relies on the spec's signature,
833 if available, or falls back on the arguments themselves.
834 """
Xtreakc9612782019-08-29 11:39:01 +0530835
836 if isinstance(_call, tuple) and len(_call) > 2:
837 sig = self._get_call_signature_from_name(_call[0])
838 else:
839 sig = self._spec_signature
840
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100841 if sig is not None:
842 if len(_call) == 2:
843 name = ''
844 args, kwargs = _call
845 else:
846 name, args, kwargs = _call
847 try:
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700848 bound_call = sig.bind(*args, **kwargs)
849 return call(name, bound_call.args, bound_call.kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100850 except TypeError as e:
851 return e.with_traceback(None)
852 else:
853 return _call
854
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300855 def assert_not_called(self):
Kushal Das8af9db32014-04-17 01:36:14 +0530856 """assert that the mock was never called.
857 """
Kushal Das8af9db32014-04-17 01:36:14 +0530858 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100859 msg = ("Expected '%s' to not have been called. Called %s times.%s"
860 % (self._mock_name or 'mock',
861 self.call_count,
862 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530863 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100864
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300865 def assert_called(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100866 """assert that the mock was called at least once
867 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100868 if self.call_count == 0:
869 msg = ("Expected '%s' to have been called." %
Abraham Toriz Cruz5f5f11f2019-09-17 06:16:08 -0500870 (self._mock_name or 'mock'))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100871 raise AssertionError(msg)
872
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300873 def assert_called_once(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100874 """assert that the mock was called only once.
875 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100876 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100877 msg = ("Expected '%s' to have been called once. Called %s times.%s"
878 % (self._mock_name or 'mock',
879 self.call_count,
880 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100881 raise AssertionError(msg)
882
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300883 def assert_called_with(self, /, *args, **kwargs):
Rémi Lapeyref5896a02019-08-29 08:15:53 +0200884 """assert that the last call was made with the specified arguments.
Michael Foord345266a2012-03-14 12:24:34 -0700885
886 Raises an AssertionError if the args and keyword args passed in are
887 different to the last call to the mock."""
Michael Foord345266a2012-03-14 12:24:34 -0700888 if self.call_args is None:
889 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800890 actual = 'not called.'
891 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
892 % (expected, actual))
893 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700894
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100895 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700896 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100897 return msg
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700898 expected = self._call_matcher(_Call((args, kwargs), two=True))
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100899 actual = self._call_matcher(self.call_args)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700900 if actual != expected:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100901 cause = expected if isinstance(expected, Exception) else None
902 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700903
904
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300905 def assert_called_once_with(self, /, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100906 """assert that the mock was called exactly once and that that call was
907 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700908 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100909 msg = ("Expected '%s' to be called once. Called %s times.%s"
910 % (self._mock_name or 'mock',
911 self.call_count,
912 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700913 raise AssertionError(msg)
914 return self.assert_called_with(*args, **kwargs)
915
916
917 def assert_has_calls(self, calls, any_order=False):
918 """assert the mock has been called with the specified calls.
919 The `mock_calls` list is checked for the calls.
920
921 If `any_order` is False (the default) then the calls must be
922 sequential. There can be extra calls before or after the
923 specified calls.
924
925 If `any_order` is True then the calls can be in any order, but
926 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100927 expected = [self._call_matcher(c) for c in calls]
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400928 cause = next((e for e in expected if isinstance(e, Exception)), None)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100929 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700930 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100931 if expected not in all_calls:
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400932 if cause is None:
933 problem = 'Calls not found.'
934 else:
935 problem = ('Error processing expected calls.\n'
936 'Errors: {}').format(
937 [e if isinstance(e, Exception) else None
938 for e in expected])
Michael Foord345266a2012-03-14 12:24:34 -0700939 raise AssertionError(
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400940 f'{problem}\n'
Samuel Freilich2180f6b2019-09-24 18:04:29 -0400941 f'Expected: {_CallList(calls)}'
942 f'{self._calls_repr(prefix="Actual").rstrip(".")}'
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100943 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700944 return
945
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100946 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700947
948 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100949 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700950 try:
951 all_calls.remove(kall)
952 except ValueError:
953 not_found.append(kall)
954 if not_found:
955 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400956 '%r does not contain all of %r in its call list, '
957 'found %r instead' % (self._mock_name or 'mock',
958 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100959 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700960
961
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300962 def assert_any_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700963 """assert the mock has been called with the specified arguments.
964
965 The assert passes if the mock has *ever* been called, unlike
966 `assert_called_with` and `assert_called_once_with` that only pass if
967 the call is the most recent one."""
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700968 expected = self._call_matcher(_Call((args, kwargs), two=True))
969 cause = expected if isinstance(expected, Exception) else None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100970 actual = [self._call_matcher(c) for c in self.call_args_list]
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700971 if cause or expected not in _AnyComparer(actual):
Michael Foord345266a2012-03-14 12:24:34 -0700972 expected_string = self._format_mock_call_signature(args, kwargs)
973 raise AssertionError(
974 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100975 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700976
977
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300978 def _get_child_mock(self, /, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700979 """Create the child mocks for attributes and return value.
980 By default child mocks will be the same type as the parent.
981 Subclasses of Mock may want to override this to customize the way
982 child mocks are made.
983
984 For non-callable mocks the callable variant will be used (rather than
985 any custom subclass)."""
Lisa Roach77b3b772019-05-20 09:19:53 -0700986 _new_name = kw.get("_new_name")
987 if _new_name in self.__dict__['_spec_asyncs']:
988 return AsyncMock(**kw)
989
Michael Foord345266a2012-03-14 12:24:34 -0700990 _type = type(self)
Lisa Roach77b3b772019-05-20 09:19:53 -0700991 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
Lisa Roach9a7d9512019-09-28 18:42:44 -0700992 # Any asynchronous magic becomes an AsyncMock
Lisa Roach77b3b772019-05-20 09:19:53 -0700993 klass = AsyncMock
Lisa Roach8b03f942019-09-19 21:04:18 -0700994 elif issubclass(_type, AsyncMockMixin):
Lisa Roach3667e1e2019-09-29 21:56:47 -0700995 if (_new_name in _all_sync_magics or
996 self._mock_methods and _new_name in self._mock_methods):
997 # Any synchronous method on AsyncMock becomes a MagicMock
Lisa Roach9a7d9512019-09-28 18:42:44 -0700998 klass = MagicMock
999 else:
1000 klass = AsyncMock
Lisa Roach8b03f942019-09-19 21:04:18 -07001001 elif not issubclass(_type, CallableMixin):
Michael Foord345266a2012-03-14 12:24:34 -07001002 if issubclass(_type, NonCallableMagicMock):
1003 klass = MagicMock
Lisa Roach9a7d9512019-09-28 18:42:44 -07001004 elif issubclass(_type, NonCallableMock):
Michael Foord345266a2012-03-14 12:24:34 -07001005 klass = Mock
1006 else:
1007 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +01001008
1009 if self._mock_sealed:
1010 attribute = "." + kw["name"] if "name" in kw else "()"
1011 mock_name = self._extract_mock_name() + attribute
1012 raise AttributeError(mock_name)
1013
Michael Foord345266a2012-03-14 12:24:34 -07001014 return klass(**kw)
1015
1016
Petter Strandmark47d94242018-10-28 21:37:10 +01001017 def _calls_repr(self, prefix="Calls"):
1018 """Renders self.mock_calls as a string.
1019
1020 Example: "\nCalls: [call(1), call(2)]."
1021
1022 If self.mock_calls is empty, an empty string is returned. The
1023 output will be truncated if very long.
1024 """
1025 if not self.mock_calls:
1026 return ""
1027 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
1028
1029
Michael Foord14fd9252019-09-13 18:40:56 +02001030_MOCK_SIG = inspect.signature(NonCallableMock.__init__)
1031
1032
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07001033class _AnyComparer(list):
1034 """A list which checks if it contains a call which may have an
1035 argument of ANY, flipping the components of item and self from
1036 their traditional locations so that ANY is guaranteed to be on
1037 the left."""
1038 def __contains__(self, item):
1039 for _call in self:
1040 if len(item) != len(_call):
1041 continue
1042 if all([
1043 expected == actual
1044 for expected, actual in zip(item, _call)
1045 ]):
1046 return True
1047 return False
1048
Michael Foord345266a2012-03-14 12:24:34 -07001049
1050def _try_iter(obj):
1051 if obj is None:
1052 return obj
1053 if _is_exception(obj):
1054 return obj
1055 if _callable(obj):
1056 return obj
1057 try:
1058 return iter(obj)
1059 except TypeError:
1060 # XXXX backwards compatibility
1061 # but this will blow up on first call - so maybe we should fail early?
1062 return obj
1063
1064
Michael Foord345266a2012-03-14 12:24:34 -07001065class CallableMixin(Base):
1066
1067 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
1068 wraps=None, name=None, spec_set=None, parent=None,
1069 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
1070 self.__dict__['_mock_return_value'] = return_value
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001071 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -07001072 spec, wraps, name, spec_set, parent,
1073 _spec_state, _new_name, _new_parent, **kwargs
1074 )
1075
1076 self.side_effect = side_effect
1077
1078
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001079 def _mock_check_sig(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001080 # stub method that can be replaced with one with a specific signature
1081 pass
1082
1083
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001084 def __call__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001085 # can't use self in-case a function / method we are mocking uses self
1086 # in the signature
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001087 self._mock_check_sig(*args, **kwargs)
Lisa Roachef048512019-09-23 20:49:40 -07001088 self._increment_mock_call(*args, **kwargs)
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001089 return self._mock_call(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001090
1091
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001092 def _mock_call(self, /, *args, **kwargs):
Lisa Roachef048512019-09-23 20:49:40 -07001093 return self._execute_mock_call(*args, **kwargs)
1094
1095 def _increment_mock_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001096 self.called = True
1097 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001098
Chris Withers8ca0fa92018-12-03 21:31:37 +00001099 # handle call_args
Lisa Roachef048512019-09-23 20:49:40 -07001100 # needs to be set here so assertions on call arguments pass before
1101 # execution in the case of awaited calls
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001102 _call = _Call((args, kwargs), two=True)
1103 self.call_args = _call
1104 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -07001105
Chris Withers8ca0fa92018-12-03 21:31:37 +00001106 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001107 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +00001108 method_call_name = self._mock_name
1109
1110 # initial stuff for mock_calls:
1111 mock_call_name = self._mock_new_name
1112 is_a_call = mock_call_name == '()'
1113 self.mock_calls.append(_Call(('', args, kwargs)))
1114
1115 # follow up the chain of mocks:
1116 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001117 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001118
Chris Withers8ca0fa92018-12-03 21:31:37 +00001119 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001120 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001121 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001122 do_method_calls = _new_parent._mock_parent is not None
1123 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001124 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001125
Chris Withers8ca0fa92018-12-03 21:31:37 +00001126 # handle mock_calls:
1127 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001128 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001129
1130 if _new_parent._mock_new_name:
1131 if is_a_call:
1132 dot = ''
1133 else:
1134 dot = '.'
1135 is_a_call = _new_parent._mock_new_name == '()'
1136 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1137
1138 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001139 _new_parent = _new_parent._mock_new_parent
1140
Lisa Roachef048512019-09-23 20:49:40 -07001141 def _execute_mock_call(self, /, *args, **kwargs):
Jason Fried046442d2019-11-20 16:27:51 -08001142 # separate from _increment_mock_call so that awaited functions are
1143 # executed separately from their call, also AsyncMock overrides this method
Lisa Roachef048512019-09-23 20:49:40 -07001144
Michael Foord345266a2012-03-14 12:24:34 -07001145 effect = self.side_effect
1146 if effect is not None:
1147 if _is_exception(effect):
1148 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001149 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001150 result = next(effect)
1151 if _is_exception(result):
1152 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001153 else:
1154 result = effect(*args, **kwargs)
1155
1156 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001157 return result
Michael Foord345266a2012-03-14 12:24:34 -07001158
Mario Corcherof05df0a2018-12-08 11:25:02 +00001159 if self._mock_return_value is not DEFAULT:
1160 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001161
Mario Corcherof05df0a2018-12-08 11:25:02 +00001162 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001163 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001164
1165 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001166
1167
1168
1169class Mock(CallableMixin, NonCallableMock):
1170 """
1171 Create a new `Mock` object. `Mock` takes several optional arguments
1172 that specify the behaviour of the Mock object:
1173
1174 * `spec`: This can be either a list of strings or an existing object (a
1175 class or instance) that acts as the specification for the mock object. If
1176 you pass in an object then a list of strings is formed by calling dir on
1177 the object (excluding unsupported magic attributes and methods). Accessing
1178 any attribute not in this list will raise an `AttributeError`.
1179
1180 If `spec` is an object (rather than a list of strings) then
1181 `mock.__class__` returns the class of the spec object. This allows mocks
1182 to pass `isinstance` tests.
1183
1184 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1185 or get an attribute on the mock that isn't on the object passed as
1186 `spec_set` will raise an `AttributeError`.
1187
1188 * `side_effect`: A function to be called whenever the Mock is called. See
1189 the `side_effect` attribute. Useful for raising exceptions or
1190 dynamically changing return values. The function is called with the same
1191 arguments as the mock, and unless it returns `DEFAULT`, the return
1192 value of this function is used as the return value.
1193
Michael Foord2cd48732012-04-21 15:52:11 +01001194 If `side_effect` is an iterable then each call to the mock will return
1195 the next value from the iterable. If any of the members of the iterable
1196 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001197
Michael Foord345266a2012-03-14 12:24:34 -07001198 * `return_value`: The value returned when the mock is called. By default
1199 this is a new Mock (created on first access). See the
1200 `return_value` attribute.
1201
Michael Foord0682a0c2012-04-13 20:51:20 +01001202 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1203 calling the Mock will pass the call through to the wrapped object
1204 (returning the real result). Attribute access on the mock will return a
1205 Mock object that wraps the corresponding attribute of the wrapped object
1206 (so attempting to access an attribute that doesn't exist will raise an
1207 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001208
1209 If the mock has an explicit `return_value` set then calls are not passed
1210 to the wrapped object and the `return_value` is returned instead.
1211
1212 * `name`: If the mock has a name then it will be used in the repr of the
1213 mock. This can be useful for debugging. The name is propagated to child
1214 mocks.
1215
1216 Mocks can also be called with arbitrary keyword arguments. These will be
1217 used to set attributes on the mock after it is created.
1218 """
1219
1220
Michael Foord345266a2012-03-14 12:24:34 -07001221def _dot_lookup(thing, comp, import_path):
1222 try:
1223 return getattr(thing, comp)
1224 except AttributeError:
1225 __import__(import_path)
1226 return getattr(thing, comp)
1227
1228
1229def _importer(target):
1230 components = target.split('.')
1231 import_path = components.pop(0)
1232 thing = __import__(import_path)
1233
1234 for comp in components:
1235 import_path += ".%s" % comp
1236 thing = _dot_lookup(thing, comp, import_path)
1237 return thing
1238
1239
1240def _is_started(patcher):
1241 # XXXX horrible
1242 return hasattr(patcher, 'is_local')
1243
1244
1245class _patch(object):
1246
1247 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001248 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001249
1250 def __init__(
1251 self, getter, attribute, new, spec, create,
1252 spec_set, autospec, new_callable, kwargs
1253 ):
1254 if new_callable is not None:
1255 if new is not DEFAULT:
1256 raise ValueError(
1257 "Cannot use 'new' and 'new_callable' together"
1258 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001259 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001260 raise ValueError(
1261 "Cannot use 'autospec' and 'new_callable' together"
1262 )
1263
1264 self.getter = getter
1265 self.attribute = attribute
1266 self.new = new
1267 self.new_callable = new_callable
1268 self.spec = spec
1269 self.create = create
1270 self.has_local = False
1271 self.spec_set = spec_set
1272 self.autospec = autospec
1273 self.kwargs = kwargs
1274 self.additional_patchers = []
1275
1276
1277 def copy(self):
1278 patcher = _patch(
1279 self.getter, self.attribute, self.new, self.spec,
1280 self.create, self.spec_set,
1281 self.autospec, self.new_callable, self.kwargs
1282 )
1283 patcher.attribute_name = self.attribute_name
1284 patcher.additional_patchers = [
1285 p.copy() for p in self.additional_patchers
1286 ]
1287 return patcher
1288
1289
1290 def __call__(self, func):
1291 if isinstance(func, type):
1292 return self.decorate_class(func)
Xtreak436c2b02019-05-28 12:37:39 +05301293 if inspect.iscoroutinefunction(func):
1294 return self.decorate_async_callable(func)
Michael Foord345266a2012-03-14 12:24:34 -07001295 return self.decorate_callable(func)
1296
1297
1298 def decorate_class(self, klass):
1299 for attr in dir(klass):
1300 if not attr.startswith(patch.TEST_PREFIX):
1301 continue
1302
1303 attr_value = getattr(klass, attr)
1304 if not hasattr(attr_value, "__call__"):
1305 continue
1306
1307 patcher = self.copy()
1308 setattr(klass, attr, patcher(attr_value))
1309 return klass
1310
1311
Xtreak436c2b02019-05-28 12:37:39 +05301312 @contextlib.contextmanager
1313 def decoration_helper(self, patched, args, keywargs):
1314 extra_args = []
1315 entered_patchers = []
1316 patching = None
1317
1318 exc_info = tuple()
1319 try:
1320 for patching in patched.patchings:
1321 arg = patching.__enter__()
1322 entered_patchers.append(patching)
1323 if patching.attribute_name is not None:
1324 keywargs.update(arg)
1325 elif patching.new is DEFAULT:
1326 extra_args.append(arg)
1327
1328 args += tuple(extra_args)
1329 yield (args, keywargs)
1330 except:
1331 if (patching not in entered_patchers and
1332 _is_started(patching)):
1333 # the patcher may have been started, but an exception
1334 # raised whilst entering one of its additional_patchers
1335 entered_patchers.append(patching)
1336 # Pass the exception to __exit__
1337 exc_info = sys.exc_info()
1338 # re-raise the exception
1339 raise
1340 finally:
1341 for patching in reversed(entered_patchers):
1342 patching.__exit__(*exc_info)
1343
1344
Michael Foord345266a2012-03-14 12:24:34 -07001345 def decorate_callable(self, func):
Xtreak436c2b02019-05-28 12:37:39 +05301346 # NB. Keep the method in sync with decorate_async_callable()
Michael Foord345266a2012-03-14 12:24:34 -07001347 if hasattr(func, 'patchings'):
1348 func.patchings.append(self)
1349 return func
1350
1351 @wraps(func)
1352 def patched(*args, **keywargs):
Xtreak436c2b02019-05-28 12:37:39 +05301353 with self.decoration_helper(patched,
1354 args,
1355 keywargs) as (newargs, newkeywargs):
1356 return func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001357
Xtreak436c2b02019-05-28 12:37:39 +05301358 patched.patchings = [self]
1359 return patched
Michael Foord345266a2012-03-14 12:24:34 -07001360
Xtreak436c2b02019-05-28 12:37:39 +05301361
1362 def decorate_async_callable(self, func):
1363 # NB. Keep the method in sync with decorate_callable()
1364 if hasattr(func, 'patchings'):
1365 func.patchings.append(self)
1366 return func
1367
1368 @wraps(func)
1369 async def patched(*args, **keywargs):
1370 with self.decoration_helper(patched,
1371 args,
1372 keywargs) as (newargs, newkeywargs):
1373 return await func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001374
1375 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001376 return patched
1377
1378
1379 def get_original(self):
1380 target = self.getter()
1381 name = self.attribute
1382
1383 original = DEFAULT
1384 local = False
1385
1386 try:
1387 original = target.__dict__[name]
1388 except (AttributeError, KeyError):
1389 original = getattr(target, name, DEFAULT)
1390 else:
1391 local = True
1392
Michael Foordfddcfa22014-04-14 16:25:20 -04001393 if name in _builtins and isinstance(target, ModuleType):
1394 self.create = True
1395
Michael Foord345266a2012-03-14 12:24:34 -07001396 if not self.create and original is DEFAULT:
1397 raise AttributeError(
1398 "%s does not have the attribute %r" % (target, name)
1399 )
1400 return original, local
1401
1402
1403 def __enter__(self):
1404 """Perform the patch."""
1405 new, spec, spec_set = self.new, self.spec, self.spec_set
1406 autospec, kwargs = self.autospec, self.kwargs
1407 new_callable = self.new_callable
1408 self.target = self.getter()
1409
Michael Foord50a8c0e2012-03-25 18:57:58 +01001410 # normalise False to None
1411 if spec is False:
1412 spec = None
1413 if spec_set is False:
1414 spec_set = None
1415 if autospec is False:
1416 autospec = None
1417
1418 if spec is not None and autospec is not None:
1419 raise TypeError("Can't specify spec and autospec")
1420 if ((spec is not None or autospec is not None) and
1421 spec_set not in (True, None)):
1422 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1423
Michael Foord345266a2012-03-14 12:24:34 -07001424 original, local = self.get_original()
1425
Michael Foord50a8c0e2012-03-25 18:57:58 +01001426 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001427 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001428 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001429 # set spec to the object we are replacing
1430 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001431 if spec_set is True:
1432 spec_set = original
1433 spec = None
1434 elif spec is not None:
1435 if spec_set is True:
1436 spec_set = spec
1437 spec = None
1438 elif spec_set is True:
1439 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001440
Michael Foord50a8c0e2012-03-25 18:57:58 +01001441 if spec is not None or spec_set is not None:
1442 if original is DEFAULT:
1443 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001444 if isinstance(original, type):
1445 # If we're patching out a class and there is a spec
1446 inherit = True
Lisa Roach77b3b772019-05-20 09:19:53 -07001447 if spec is None and _is_async_obj(original):
1448 Klass = AsyncMock
1449 else:
1450 Klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -07001451 _kwargs = {}
1452 if new_callable is not None:
1453 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001454 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001455 this_spec = spec
1456 if spec_set is not None:
1457 this_spec = spec_set
1458 if _is_list(this_spec):
1459 not_callable = '__call__' not in this_spec
1460 else:
1461 not_callable = not callable(this_spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07001462 if _is_async_obj(this_spec):
1463 Klass = AsyncMock
1464 elif not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001465 Klass = NonCallableMagicMock
1466
1467 if spec is not None:
1468 _kwargs['spec'] = spec
1469 if spec_set is not None:
1470 _kwargs['spec_set'] = spec_set
1471
1472 # add a name to mocks
1473 if (isinstance(Klass, type) and
1474 issubclass(Klass, NonCallableMock) and self.attribute):
1475 _kwargs['name'] = self.attribute
1476
1477 _kwargs.update(kwargs)
1478 new = Klass(**_kwargs)
1479
1480 if inherit and _is_instance_mock(new):
1481 # we can only tell if the instance should be callable if the
1482 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001483 this_spec = spec
1484 if spec_set is not None:
1485 this_spec = spec_set
1486 if (not _is_list(this_spec) and not
1487 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001488 Klass = NonCallableMagicMock
1489
1490 _kwargs.pop('name')
1491 new.return_value = Klass(_new_parent=new, _new_name='()',
1492 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001493 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001494 # spec is ignored, new *must* be default, spec_set is treated
1495 # as a boolean. Should we check spec is not None and that spec_set
1496 # is a bool?
1497 if new is not DEFAULT:
1498 raise TypeError(
1499 "autospec creates the mock for you. Can't specify "
1500 "autospec and new."
1501 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001502 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001503 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001504 spec_set = bool(spec_set)
1505 if autospec is True:
1506 autospec = original
1507
1508 new = create_autospec(autospec, spec_set=spec_set,
1509 _name=self.attribute, **kwargs)
1510 elif kwargs:
1511 # can't set keyword args when we aren't creating the mock
1512 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1513 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1514
1515 new_attr = new
1516
1517 self.temp_original = original
1518 self.is_local = local
1519 setattr(self.target, self.attribute, new_attr)
1520 if self.attribute_name is not None:
1521 extra_args = {}
1522 if self.new is DEFAULT:
1523 extra_args[self.attribute_name] = new
1524 for patching in self.additional_patchers:
1525 arg = patching.__enter__()
1526 if patching.new is DEFAULT:
1527 extra_args.update(arg)
1528 return extra_args
1529
1530 return new
1531
1532
Michael Foord50a8c0e2012-03-25 18:57:58 +01001533 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001534 """Undo the patch."""
1535 if not _is_started(self):
Xtreak02b84cb2019-03-29 02:38:43 +05301536 return
Michael Foord345266a2012-03-14 12:24:34 -07001537
1538 if self.is_local and self.temp_original is not DEFAULT:
1539 setattr(self.target, self.attribute, self.temp_original)
1540 else:
1541 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001542 if not self.create and (not hasattr(self.target, self.attribute) or
1543 self.attribute in ('__doc__', '__module__',
1544 '__defaults__', '__annotations__',
1545 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001546 # needed for proxy objects like django settings
1547 setattr(self.target, self.attribute, self.temp_original)
1548
1549 del self.temp_original
1550 del self.is_local
1551 del self.target
1552 for patcher in reversed(self.additional_patchers):
1553 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001554 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001555
Michael Foordf7c41582012-06-10 20:36:32 +01001556
1557 def start(self):
1558 """Activate a patch, returning any created mock."""
1559 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001560 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001561 return result
1562
1563
1564 def stop(self):
1565 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001566 try:
1567 self._active_patches.remove(self)
1568 except ValueError:
1569 # If the patch hasn't been started this will fail
1570 pass
1571
Michael Foordf7c41582012-06-10 20:36:32 +01001572 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001573
1574
1575
1576def _get_target(target):
1577 try:
1578 target, attribute = target.rsplit('.', 1)
1579 except (TypeError, ValueError):
1580 raise TypeError("Need a valid target to patch. You supplied: %r" %
1581 (target,))
1582 getter = lambda: _importer(target)
1583 return getter, attribute
1584
1585
1586def _patch_object(
1587 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001588 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001589 new_callable=None, **kwargs
1590 ):
1591 """
Michael Foord345266a2012-03-14 12:24:34 -07001592 patch the named member (`attribute`) on an object (`target`) with a mock
1593 object.
1594
1595 `patch.object` can be used as a decorator, class decorator or a context
1596 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1597 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1598 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1599 the mock object it creates.
1600
1601 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1602 for choosing which methods to wrap.
1603 """
1604 getter = lambda: target
1605 return _patch(
1606 getter, attribute, new, spec, create,
1607 spec_set, autospec, new_callable, kwargs
1608 )
1609
1610
Michael Foord50a8c0e2012-03-25 18:57:58 +01001611def _patch_multiple(target, spec=None, create=False, spec_set=None,
1612 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001613 """Perform multiple patches in a single call. It takes the object to be
1614 patched (either as an object or a string to fetch the object by importing)
1615 and keyword arguments for the patches::
1616
1617 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1618 ...
1619
1620 Use `DEFAULT` as the value if you want `patch.multiple` to create
1621 mocks for you. In this case the created mocks are passed into a decorated
1622 function by keyword, and a dictionary is returned when `patch.multiple` is
1623 used as a context manager.
1624
1625 `patch.multiple` can be used as a decorator, class decorator or a context
1626 manager. The arguments `spec`, `spec_set`, `create`,
1627 `autospec` and `new_callable` have the same meaning as for `patch`. These
1628 arguments will be applied to *all* patches done by `patch.multiple`.
1629
1630 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1631 for choosing which methods to wrap.
1632 """
1633 if type(target) is str:
1634 getter = lambda: _importer(target)
1635 else:
1636 getter = lambda: target
1637
1638 if not kwargs:
1639 raise ValueError(
1640 'Must supply at least one keyword argument with patch.multiple'
1641 )
1642 # need to wrap in a list for python 3, where items is a view
1643 items = list(kwargs.items())
1644 attribute, new = items[0]
1645 patcher = _patch(
1646 getter, attribute, new, spec, create, spec_set,
1647 autospec, new_callable, {}
1648 )
1649 patcher.attribute_name = attribute
1650 for attribute, new in items[1:]:
1651 this_patcher = _patch(
1652 getter, attribute, new, spec, create, spec_set,
1653 autospec, new_callable, {}
1654 )
1655 this_patcher.attribute_name = attribute
1656 patcher.additional_patchers.append(this_patcher)
1657 return patcher
1658
1659
1660def patch(
1661 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001662 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001663 ):
1664 """
1665 `patch` acts as a function decorator, class decorator or a context
1666 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001667 is patched with a `new` object. When the function/with statement exits
1668 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001669
Mario Corcherof5e7f392019-09-09 15:18:06 +01001670 If `new` is omitted, then the target is replaced with an
1671 `AsyncMock if the patched object is an async function or a
1672 `MagicMock` otherwise. If `patch` is used as a decorator and `new` is
Michael Foord54b3db82012-03-28 15:08:08 +01001673 omitted, the created mock is passed in as an extra argument to the
1674 decorated function. If `patch` is used as a context manager the created
1675 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001676
Michael Foord54b3db82012-03-28 15:08:08 +01001677 `target` should be a string in the form `'package.module.ClassName'`. The
1678 `target` is imported and the specified object replaced with the `new`
1679 object, so the `target` must be importable from the environment you are
1680 calling `patch` from. The target is imported when the decorated function
1681 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001682
1683 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1684 if patch is creating one for you.
1685
1686 In addition you can pass `spec=True` or `spec_set=True`, which causes
1687 patch to pass in the object being mocked as the spec/spec_set object.
1688
1689 `new_callable` allows you to specify a different class, or callable object,
Mario Corcherof5e7f392019-09-09 15:18:06 +01001690 that will be called to create the `new` object. By default `AsyncMock` is
1691 used for async functions and `MagicMock` for the rest.
Michael Foord345266a2012-03-14 12:24:34 -07001692
1693 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001694 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001695 All attributes of the mock will also have the spec of the corresponding
1696 attribute of the object being replaced. Methods and functions being
1697 mocked will have their arguments checked and will raise a `TypeError` if
1698 they are called with the wrong signature. For mocks replacing a class,
1699 their return value (the 'instance') will have the same spec as the class.
1700
1701 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1702 arbitrary object as the spec instead of the one being replaced.
1703
1704 By default `patch` will fail to replace attributes that don't exist. If
1705 you pass in `create=True`, and the attribute doesn't exist, patch will
1706 create the attribute for you when the patched function is called, and
1707 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001708 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001709 default because it can be dangerous. With it switched on you can write
1710 passing tests against APIs that don't actually exist!
1711
1712 Patch can be used as a `TestCase` class decorator. It works by
1713 decorating each test method in the class. This reduces the boilerplate
1714 code when your test methods share a common patchings set. `patch` finds
1715 tests by looking for method names that start with `patch.TEST_PREFIX`.
1716 By default this is `test`, which matches the way `unittest` finds tests.
1717 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1718
1719 Patch can be used as a context manager, with the with statement. Here the
1720 patching applies to the indented block after the with statement. If you
1721 use "as" then the patched object will be bound to the name after the
1722 "as"; very useful if `patch` is creating a mock object for you.
1723
1724 `patch` takes arbitrary keyword arguments. These will be passed to
1725 the `Mock` (or `new_callable`) on construction.
1726
1727 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1728 available for alternate use-cases.
1729 """
1730 getter, attribute = _get_target(target)
1731 return _patch(
1732 getter, attribute, new, spec, create,
1733 spec_set, autospec, new_callable, kwargs
1734 )
1735
1736
1737class _patch_dict(object):
1738 """
1739 Patch a dictionary, or dictionary like object, and restore the dictionary
1740 to its original state after the test.
1741
1742 `in_dict` can be a dictionary or a mapping like container. If it is a
1743 mapping then it must at least support getting, setting and deleting items
1744 plus iterating over keys.
1745
1746 `in_dict` can also be a string specifying the name of the dictionary, which
1747 will then be fetched by importing it.
1748
1749 `values` can be a dictionary of values to set in the dictionary. `values`
1750 can also be an iterable of `(key, value)` pairs.
1751
1752 If `clear` is True then the dictionary will be cleared before the new
1753 values are set.
1754
1755 `patch.dict` can also be called with arbitrary keyword arguments to set
1756 values in the dictionary::
1757
1758 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1759 ...
1760
1761 `patch.dict` can be used as a context manager, decorator or class
1762 decorator. When used as a class decorator `patch.dict` honours
1763 `patch.TEST_PREFIX` for choosing which methods to wrap.
1764 """
1765
1766 def __init__(self, in_dict, values=(), clear=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001767 self.in_dict = in_dict
1768 # support any argument supported by dict(...) constructor
1769 self.values = dict(values)
1770 self.values.update(kwargs)
1771 self.clear = clear
1772 self._original = None
1773
1774
1775 def __call__(self, f):
1776 if isinstance(f, type):
1777 return self.decorate_class(f)
1778 @wraps(f)
1779 def _inner(*args, **kw):
1780 self._patch_dict()
1781 try:
1782 return f(*args, **kw)
1783 finally:
1784 self._unpatch_dict()
1785
1786 return _inner
1787
1788
1789 def decorate_class(self, klass):
1790 for attr in dir(klass):
1791 attr_value = getattr(klass, attr)
1792 if (attr.startswith(patch.TEST_PREFIX) and
1793 hasattr(attr_value, "__call__")):
1794 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1795 decorated = decorator(attr_value)
1796 setattr(klass, attr, decorated)
1797 return klass
1798
1799
1800 def __enter__(self):
1801 """Patch the dict."""
1802 self._patch_dict()
Mario Corchero04530812019-05-28 13:53:31 +01001803 return self.in_dict
Michael Foord345266a2012-03-14 12:24:34 -07001804
1805
1806 def _patch_dict(self):
1807 values = self.values
Xtreaka875ea52019-02-25 00:24:49 +05301808 if isinstance(self.in_dict, str):
1809 self.in_dict = _importer(self.in_dict)
Michael Foord345266a2012-03-14 12:24:34 -07001810 in_dict = self.in_dict
1811 clear = self.clear
1812
1813 try:
1814 original = in_dict.copy()
1815 except AttributeError:
1816 # dict like object with no copy method
1817 # must support iteration over keys
1818 original = {}
1819 for key in in_dict:
1820 original[key] = in_dict[key]
1821 self._original = original
1822
1823 if clear:
1824 _clear_dict(in_dict)
1825
1826 try:
1827 in_dict.update(values)
1828 except AttributeError:
1829 # dict like object with no update method
1830 for key in values:
1831 in_dict[key] = values[key]
1832
1833
1834 def _unpatch_dict(self):
1835 in_dict = self.in_dict
1836 original = self._original
1837
1838 _clear_dict(in_dict)
1839
1840 try:
1841 in_dict.update(original)
1842 except AttributeError:
1843 for key in original:
1844 in_dict[key] = original[key]
1845
1846
1847 def __exit__(self, *args):
1848 """Unpatch the dict."""
1849 self._unpatch_dict()
1850 return False
1851
1852 start = __enter__
1853 stop = __exit__
1854
1855
1856def _clear_dict(in_dict):
1857 try:
1858 in_dict.clear()
1859 except AttributeError:
1860 keys = list(in_dict)
1861 for key in keys:
1862 del in_dict[key]
1863
1864
Michael Foordf7c41582012-06-10 20:36:32 +01001865def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001866 """Stop all active patches. LIFO to unroll nested patches."""
1867 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001868 patch.stop()
1869
1870
Michael Foord345266a2012-03-14 12:24:34 -07001871patch.object = _patch_object
1872patch.dict = _patch_dict
1873patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001874patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001875patch.TEST_PREFIX = 'test'
1876
1877magic_methods = (
1878 "lt le gt ge eq ne "
1879 "getitem setitem delitem "
1880 "len contains iter "
1881 "hash str sizeof "
1882 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001883 # we added divmod and rdivmod here instead of numerics
1884 # because there is no idivmod
1885 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001886 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001887 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001888 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001889 "fspath "
Lisa Roach9a7d9512019-09-28 18:42:44 -07001890 "aiter "
Michael Foord345266a2012-03-14 12:24:34 -07001891)
1892
Michael Foordd2623d72014-04-14 11:23:48 -04001893numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001894 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001895)
Michael Foord345266a2012-03-14 12:24:34 -07001896inplace = ' '.join('i%s' % n for n in numerics.split())
1897right = ' '.join('r%s' % n for n in numerics.split())
1898
1899# not including __prepare__, __instancecheck__, __subclasscheck__
1900# (as they are metaclass methods)
1901# __del__ is not supported at all as it causes problems if it exists
1902
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001903_non_defaults = {
1904 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1905 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1906 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1907 '__repr__', '__dir__', '__subclasses__', '__format__',
Lisa Roach8b03f942019-09-19 21:04:18 -07001908 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001909}
Michael Foord345266a2012-03-14 12:24:34 -07001910
1911
1912def _get_method(name, func):
1913 "Turns a callable object (like a mock) into a real function"
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001914 def method(self, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -07001915 return func(self, *args, **kw)
1916 method.__name__ = name
1917 return method
1918
1919
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001920_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001921 '__%s__' % method for method in
1922 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001923}
Michael Foord345266a2012-03-14 12:24:34 -07001924
Lisa Roach77b3b772019-05-20 09:19:53 -07001925# Magic methods used for async `with` statements
1926_async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
Lisa Roach8b03f942019-09-19 21:04:18 -07001927# Magic methods that are only used with async calls but are synchronous functions themselves
1928_sync_async_magics = {"__aiter__"}
1929_async_magics = _async_method_magics | _sync_async_magics
Lisa Roach77b3b772019-05-20 09:19:53 -07001930
Lisa Roach8b03f942019-09-19 21:04:18 -07001931_all_sync_magics = _magics | _non_defaults
1932_all_magics = _all_sync_magics | _async_magics
Michael Foord345266a2012-03-14 12:24:34 -07001933
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001934_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001935 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001936 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001937 '__instancecheck__', '__subclasscheck__',
1938 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001939}
Michael Foord345266a2012-03-14 12:24:34 -07001940
1941_calculate_return_value = {
1942 '__hash__': lambda self: object.__hash__(self),
1943 '__str__': lambda self: object.__str__(self),
1944 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001945 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001946}
1947
1948_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001949 '__lt__': NotImplemented,
1950 '__gt__': NotImplemented,
1951 '__le__': NotImplemented,
1952 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001953 '__int__': 1,
1954 '__contains__': False,
1955 '__len__': 0,
1956 '__exit__': False,
1957 '__complex__': 1j,
1958 '__float__': 1.0,
1959 '__bool__': True,
1960 '__index__': 1,
Lisa Roach77b3b772019-05-20 09:19:53 -07001961 '__aexit__': False,
Michael Foord345266a2012-03-14 12:24:34 -07001962}
1963
1964
1965def _get_eq(self):
1966 def __eq__(other):
1967 ret_val = self.__eq__._mock_return_value
1968 if ret_val is not DEFAULT:
1969 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001970 if self is other:
1971 return True
1972 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001973 return __eq__
1974
1975def _get_ne(self):
1976 def __ne__(other):
1977 if self.__ne__._mock_return_value is not DEFAULT:
1978 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001979 if self is other:
1980 return False
1981 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001982 return __ne__
1983
1984def _get_iter(self):
1985 def __iter__():
1986 ret_val = self.__iter__._mock_return_value
1987 if ret_val is DEFAULT:
1988 return iter([])
1989 # if ret_val was already an iterator, then calling iter on it should
1990 # return the iterator unchanged
1991 return iter(ret_val)
1992 return __iter__
1993
Lisa Roach77b3b772019-05-20 09:19:53 -07001994def _get_async_iter(self):
1995 def __aiter__():
1996 ret_val = self.__aiter__._mock_return_value
1997 if ret_val is DEFAULT:
1998 return _AsyncIterator(iter([]))
1999 return _AsyncIterator(iter(ret_val))
2000 return __aiter__
2001
Michael Foord345266a2012-03-14 12:24:34 -07002002_side_effect_methods = {
2003 '__eq__': _get_eq,
2004 '__ne__': _get_ne,
2005 '__iter__': _get_iter,
Lisa Roach77b3b772019-05-20 09:19:53 -07002006 '__aiter__': _get_async_iter
Michael Foord345266a2012-03-14 12:24:34 -07002007}
2008
2009
2010
2011def _set_return_value(mock, method, name):
2012 fixed = _return_values.get(name, DEFAULT)
2013 if fixed is not DEFAULT:
2014 method.return_value = fixed
2015 return
2016
marcoramirezmxa9187c32019-09-16 11:34:46 -05002017 return_calculator = _calculate_return_value.get(name)
2018 if return_calculator is not None:
2019 return_value = return_calculator(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002020 method.return_value = return_value
2021 return
2022
2023 side_effector = _side_effect_methods.get(name)
2024 if side_effector is not None:
2025 method.side_effect = side_effector(mock)
2026
2027
2028
Lisa Roach9a7d9512019-09-28 18:42:44 -07002029class MagicMixin(Base):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002030 def __init__(self, /, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07002031 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10002032 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07002033 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002034
2035
2036 def _mock_set_magics(self):
Lisa Roach9a7d9512019-09-28 18:42:44 -07002037 orig_magics = _magics | _async_method_magics
2038 these_magics = orig_magics
Michael Foord345266a2012-03-14 12:24:34 -07002039
Łukasz Langaa468db92015-04-13 23:12:42 -07002040 if getattr(self, "_mock_methods", None) is not None:
Lisa Roach9a7d9512019-09-28 18:42:44 -07002041 these_magics = orig_magics.intersection(self._mock_methods)
Michael Foord345266a2012-03-14 12:24:34 -07002042
2043 remove_magics = set()
Lisa Roach9a7d9512019-09-28 18:42:44 -07002044 remove_magics = orig_magics - these_magics
Michael Foord345266a2012-03-14 12:24:34 -07002045
2046 for entry in remove_magics:
2047 if entry in type(self).__dict__:
2048 # remove unneeded magic methods
2049 delattr(self, entry)
2050
2051 # don't overwrite existing attributes if called a second time
2052 these_magics = these_magics - set(type(self).__dict__)
2053
2054 _type = type(self)
2055 for entry in these_magics:
2056 setattr(_type, entry, MagicProxy(entry, self))
2057
2058
2059
2060class NonCallableMagicMock(MagicMixin, NonCallableMock):
2061 """A version of `MagicMock` that isn't callable."""
2062 def mock_add_spec(self, spec, spec_set=False):
2063 """Add a spec to a mock. `spec` can either be an object or a
2064 list of strings. Only attributes on the `spec` can be fetched as
2065 attributes from the mock.
2066
2067 If `spec_set` is True then only attributes on the spec can be set."""
2068 self._mock_add_spec(spec, spec_set)
2069 self._mock_set_magics()
2070
2071
Lisa Roach9a7d9512019-09-28 18:42:44 -07002072class AsyncMagicMixin(MagicMixin):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002073 def __init__(self, /, *args, **kw):
Lisa Roach9a7d9512019-09-28 18:42:44 -07002074 self._mock_set_magics() # make magic work for kwargs in init
Lisa Roach77b3b772019-05-20 09:19:53 -07002075 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)
Lisa Roach9a7d9512019-09-28 18:42:44 -07002076 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002077
Lisa Roach9a7d9512019-09-28 18:42:44 -07002078class MagicMock(MagicMixin, Mock):
Michael Foord345266a2012-03-14 12:24:34 -07002079 """
2080 MagicMock is a subclass of Mock with default implementations
2081 of most of the magic methods. You can use MagicMock without having to
2082 configure the magic methods yourself.
2083
2084 If you use the `spec` or `spec_set` arguments then *only* magic
2085 methods that exist in the spec will be created.
2086
2087 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
2088 """
2089 def mock_add_spec(self, spec, spec_set=False):
2090 """Add a spec to a mock. `spec` can either be an object or a
2091 list of strings. Only attributes on the `spec` can be fetched as
2092 attributes from the mock.
2093
2094 If `spec_set` is True then only attributes on the spec can be set."""
2095 self._mock_add_spec(spec, spec_set)
2096 self._mock_set_magics()
2097
2098
2099
Lisa Roach9a7d9512019-09-28 18:42:44 -07002100class MagicProxy(Base):
Michael Foord345266a2012-03-14 12:24:34 -07002101 def __init__(self, name, parent):
2102 self.name = name
2103 self.parent = parent
2104
Michael Foord345266a2012-03-14 12:24:34 -07002105 def create_mock(self):
2106 entry = self.name
2107 parent = self.parent
2108 m = parent._get_child_mock(name=entry, _new_name=entry,
2109 _new_parent=parent)
2110 setattr(parent, entry, m)
2111 _set_return_value(parent, m, entry)
2112 return m
2113
2114 def __get__(self, obj, _type=None):
2115 return self.create_mock()
2116
2117
Lisa Roach77b3b772019-05-20 09:19:53 -07002118class AsyncMockMixin(Base):
Lisa Roach77b3b772019-05-20 09:19:53 -07002119 await_count = _delegating_property('await_count')
2120 await_args = _delegating_property('await_args')
2121 await_args_list = _delegating_property('await_args_list')
2122
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002123 def __init__(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002124 super().__init__(*args, **kwargs)
2125 # asyncio.iscoroutinefunction() checks _is_coroutine property to say if an
2126 # object is a coroutine. Without this check it looks to see if it is a
2127 # function/method, which in this case it is not (since it is an
2128 # AsyncMock).
2129 # It is set through __dict__ because when spec_set is True, this
2130 # attribute is likely undefined.
2131 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
Lisa Roach77b3b772019-05-20 09:19:53 -07002132 self.__dict__['_mock_await_count'] = 0
2133 self.__dict__['_mock_await_args'] = None
2134 self.__dict__['_mock_await_args_list'] = _CallList()
2135 code_mock = NonCallableMock(spec_set=CodeType)
2136 code_mock.co_flags = inspect.CO_COROUTINE
2137 self.__dict__['__code__'] = code_mock
2138
Jason Fried046442d2019-11-20 16:27:51 -08002139 async def _execute_mock_call(self, /, *args, **kwargs):
2140 # This is nearly just like super(), except for sepcial handling
2141 # of coroutines
Lisa Roach77b3b772019-05-20 09:19:53 -07002142
2143 _call = self.call_args
Jason Fried046442d2019-11-20 16:27:51 -08002144 self.await_count += 1
2145 self.await_args = _call
2146 self.await_args_list.append(_call)
Lisa Roach77b3b772019-05-20 09:19:53 -07002147
Jason Fried046442d2019-11-20 16:27:51 -08002148 effect = self.side_effect
2149 if effect is not None:
2150 if _is_exception(effect):
2151 raise effect
2152 elif not _callable(effect):
2153 try:
2154 result = next(effect)
2155 except StopIteration:
2156 # It is impossible to propogate a StopIteration
2157 # through coroutines because of PEP 479
2158 raise StopAsyncIteration
2159 if _is_exception(result):
2160 raise result
2161 elif asyncio.iscoroutinefunction(effect):
2162 result = await effect(*args, **kwargs)
2163 else:
2164 result = effect(*args, **kwargs)
Lisa Roach77b3b772019-05-20 09:19:53 -07002165
Jason Fried046442d2019-11-20 16:27:51 -08002166 if result is not DEFAULT:
2167 return result
2168
2169 if self._mock_return_value is not DEFAULT:
2170 return self.return_value
2171
2172 if self._mock_wraps is not None:
2173 if asyncio.iscoroutinefunction(self._mock_wraps):
2174 return await self._mock_wraps(*args, **kwargs)
2175 return self._mock_wraps(*args, **kwargs)
2176
2177 return self.return_value
Lisa Roach77b3b772019-05-20 09:19:53 -07002178
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002179 def assert_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002180 """
2181 Assert that the mock was awaited at least once.
2182 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002183 if self.await_count == 0:
2184 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2185 raise AssertionError(msg)
2186
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002187 def assert_awaited_once(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002188 """
2189 Assert that the mock was awaited exactly once.
2190 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002191 if not self.await_count == 1:
2192 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2193 f" Awaited {self.await_count} times.")
2194 raise AssertionError(msg)
2195
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002196 def assert_awaited_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002197 """
2198 Assert that the last await was with the specified arguments.
2199 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002200 if self.await_args is None:
2201 expected = self._format_mock_call_signature(args, kwargs)
2202 raise AssertionError(f'Expected await: {expected}\nNot awaited')
2203
2204 def _error_message():
Xtreak0ae022c2019-05-29 12:32:26 +05302205 msg = self._format_mock_failure_message(args, kwargs, action='await')
Lisa Roach77b3b772019-05-20 09:19:53 -07002206 return msg
2207
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002208 expected = self._call_matcher(_Call((args, kwargs), two=True))
Lisa Roach77b3b772019-05-20 09:19:53 -07002209 actual = self._call_matcher(self.await_args)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002210 if actual != expected:
Lisa Roach77b3b772019-05-20 09:19:53 -07002211 cause = expected if isinstance(expected, Exception) else None
2212 raise AssertionError(_error_message()) from cause
2213
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002214 def assert_awaited_once_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002215 """
2216 Assert that the mock was awaited exactly once and with the specified
2217 arguments.
2218 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002219 if not self.await_count == 1:
2220 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2221 f" Awaited {self.await_count} times.")
2222 raise AssertionError(msg)
2223 return self.assert_awaited_with(*args, **kwargs)
2224
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002225 def assert_any_await(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002226 """
2227 Assert the mock has ever been awaited with the specified arguments.
2228 """
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002229 expected = self._call_matcher(_Call((args, kwargs), two=True))
2230 cause = expected if isinstance(expected, Exception) else None
Lisa Roach77b3b772019-05-20 09:19:53 -07002231 actual = [self._call_matcher(c) for c in self.await_args_list]
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002232 if cause or expected not in _AnyComparer(actual):
Lisa Roach77b3b772019-05-20 09:19:53 -07002233 expected_string = self._format_mock_call_signature(args, kwargs)
2234 raise AssertionError(
2235 '%s await not found' % expected_string
2236 ) from cause
2237
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002238 def assert_has_awaits(self, calls, any_order=False):
Lisa Roach77b3b772019-05-20 09:19:53 -07002239 """
2240 Assert the mock has been awaited with the specified calls.
2241 The :attr:`await_args_list` list is checked for the awaits.
2242
2243 If `any_order` is False (the default) then the awaits must be
2244 sequential. There can be extra calls before or after the
2245 specified awaits.
2246
2247 If `any_order` is True then the awaits can be in any order, but
2248 they must all appear in :attr:`await_args_list`.
2249 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002250 expected = [self._call_matcher(c) for c in calls]
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002251 cause = next((e for e in expected if isinstance(e, Exception)), None)
Lisa Roach77b3b772019-05-20 09:19:53 -07002252 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2253 if not any_order:
2254 if expected not in all_awaits:
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002255 if cause is None:
2256 problem = 'Awaits not found.'
2257 else:
2258 problem = ('Error processing expected awaits.\n'
2259 'Errors: {}').format(
2260 [e if isinstance(e, Exception) else None
2261 for e in expected])
Lisa Roach77b3b772019-05-20 09:19:53 -07002262 raise AssertionError(
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002263 f'{problem}\n'
2264 f'Expected: {_CallList(calls)}\n'
Lisa Roach77b3b772019-05-20 09:19:53 -07002265 f'Actual: {self.await_args_list}'
2266 ) from cause
2267 return
2268
2269 all_awaits = list(all_awaits)
2270
2271 not_found = []
2272 for kall in expected:
2273 try:
2274 all_awaits.remove(kall)
2275 except ValueError:
2276 not_found.append(kall)
2277 if not_found:
2278 raise AssertionError(
2279 '%r not all found in await list' % (tuple(not_found),)
2280 ) from cause
2281
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002282 def assert_not_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002283 """
2284 Assert that the mock was never awaited.
2285 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002286 if self.await_count != 0:
Xtreakff6b2e62019-05-27 18:26:23 +05302287 msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
Lisa Roach77b3b772019-05-20 09:19:53 -07002288 f" Awaited {self.await_count} times.")
2289 raise AssertionError(msg)
2290
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002291 def reset_mock(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002292 """
2293 See :func:`.Mock.reset_mock()`
2294 """
2295 super().reset_mock(*args, **kwargs)
2296 self.await_count = 0
2297 self.await_args = None
2298 self.await_args_list = _CallList()
2299
2300
2301class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2302 """
2303 Enhance :class:`Mock` with features allowing to mock
2304 an async function.
2305
2306 The :class:`AsyncMock` object will behave so the object is
2307 recognized as an async function, and the result of a call is an awaitable:
2308
2309 >>> mock = AsyncMock()
2310 >>> asyncio.iscoroutinefunction(mock)
2311 True
2312 >>> inspect.isawaitable(mock())
2313 True
2314
2315
2316 The result of ``mock()`` is an async function which will have the outcome
2317 of ``side_effect`` or ``return_value``:
2318
2319 - if ``side_effect`` is a function, the async function will return the
2320 result of that function,
2321 - if ``side_effect`` is an exception, the async function will raise the
2322 exception,
2323 - if ``side_effect`` is an iterable, the async function will return the
2324 next value of the iterable, however, if the sequence of result is
2325 exhausted, ``StopIteration`` is raised immediately,
2326 - if ``side_effect`` is not defined, the async function will return the
2327 value defined by ``return_value``, hence, by default, the async function
2328 returns a new :class:`AsyncMock` object.
2329
2330 If the outcome of ``side_effect`` or ``return_value`` is an async function,
2331 the mock async function obtained when the mock object is called will be this
2332 async function itself (and not an async function returning an async
2333 function).
2334
2335 The test author can also specify a wrapped object with ``wraps``. In this
2336 case, the :class:`Mock` object behavior is the same as with an
2337 :class:`.Mock` object: the wrapped object may have methods
2338 defined as async function functions.
2339
Xtreake7cb23b2019-05-21 14:17:17 +05302340 Based on Martin Richard's asynctest project.
Lisa Roach77b3b772019-05-20 09:19:53 -07002341 """
2342
Michael Foord345266a2012-03-14 12:24:34 -07002343
2344class _ANY(object):
2345 "A helper object that compares equal to everything."
2346
2347 def __eq__(self, other):
2348 return True
2349
2350 def __ne__(self, other):
2351 return False
2352
2353 def __repr__(self):
2354 return '<ANY>'
2355
2356ANY = _ANY()
2357
2358
2359
2360def _format_call_signature(name, args, kwargs):
2361 message = '%s(%%s)' % name
2362 formatted_args = ''
2363 args_string = ', '.join([repr(arg) for arg in args])
2364 kwargs_string = ', '.join([
Xtreak9d607062019-09-09 16:25:22 +05302365 '%s=%r' % (key, value) for key, value in kwargs.items()
Michael Foord345266a2012-03-14 12:24:34 -07002366 ])
2367 if args_string:
2368 formatted_args = args_string
2369 if kwargs_string:
2370 if formatted_args:
2371 formatted_args += ', '
2372 formatted_args += kwargs_string
2373
2374 return message % formatted_args
2375
2376
2377
2378class _Call(tuple):
2379 """
2380 A tuple for holding the results of a call to a mock, either in the form
2381 `(args, kwargs)` or `(name, args, kwargs)`.
2382
2383 If args or kwargs are empty then a call tuple will compare equal to
2384 a tuple without those values. This makes comparisons less verbose::
2385
2386 _Call(('name', (), {})) == ('name',)
2387 _Call(('name', (1,), {})) == ('name', (1,))
2388 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2389
2390 The `_Call` object provides a useful shortcut for comparing with call::
2391
2392 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2393 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2394
2395 If the _Call has no name then it will match any name.
2396 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002397 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002398 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002399 args = ()
2400 kwargs = {}
2401 _len = len(value)
2402 if _len == 3:
2403 name, args, kwargs = value
2404 elif _len == 2:
2405 first, second = value
2406 if isinstance(first, str):
2407 name = first
2408 if isinstance(second, tuple):
2409 args = second
2410 else:
2411 kwargs = second
2412 else:
2413 args, kwargs = first, second
2414 elif _len == 1:
2415 value, = value
2416 if isinstance(value, str):
2417 name = value
2418 elif isinstance(value, tuple):
2419 args = value
2420 else:
2421 kwargs = value
2422
2423 if two:
2424 return tuple.__new__(cls, (args, kwargs))
2425
2426 return tuple.__new__(cls, (name, args, kwargs))
2427
2428
2429 def __init__(self, value=(), name=None, parent=None, two=False,
2430 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002431 self._mock_name = name
2432 self._mock_parent = parent
2433 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002434
2435
2436 def __eq__(self, other):
Michael Foord345266a2012-03-14 12:24:34 -07002437 try:
2438 len_other = len(other)
2439 except TypeError:
Serhiy Storchaka662db122019-08-08 08:42:54 +03002440 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07002441
2442 self_name = ''
2443 if len(self) == 2:
2444 self_args, self_kwargs = self
2445 else:
2446 self_name, self_args, self_kwargs = self
2447
Andrew Dunaie63e6172018-12-04 11:08:45 +02002448 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2449 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002450 return False
2451
Michael Foord345266a2012-03-14 12:24:34 -07002452 other_name = ''
2453 if len_other == 0:
2454 other_args, other_kwargs = (), {}
2455 elif len_other == 3:
2456 other_name, other_args, other_kwargs = other
2457 elif len_other == 1:
2458 value, = other
2459 if isinstance(value, tuple):
2460 other_args = value
2461 other_kwargs = {}
2462 elif isinstance(value, str):
2463 other_name = value
2464 other_args, other_kwargs = (), {}
2465 else:
2466 other_args = ()
2467 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002468 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002469 # could be (name, args) or (name, kwargs) or (args, kwargs)
2470 first, second = other
2471 if isinstance(first, str):
2472 other_name = first
2473 if isinstance(second, tuple):
2474 other_args, other_kwargs = second, {}
2475 else:
2476 other_args, other_kwargs = (), second
2477 else:
2478 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002479 else:
2480 return False
Michael Foord345266a2012-03-14 12:24:34 -07002481
2482 if self_name and other_name != self_name:
2483 return False
2484
2485 # this order is important for ANY to work!
2486 return (other_args, other_kwargs) == (self_args, self_kwargs)
2487
2488
Berker Peksagce913872016-03-28 00:30:02 +03002489 __ne__ = object.__ne__
2490
2491
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002492 def __call__(self, /, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002493 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002494 return _Call(('', args, kwargs), name='()')
2495
Andrew Dunaie63e6172018-12-04 11:08:45 +02002496 name = self._mock_name + '()'
2497 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002498
2499
2500 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002501 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002502 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002503 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002504 return _Call(name=name, parent=self, from_kall=False)
2505
2506
blhsing72c35992019-09-11 07:28:06 -07002507 def __getattribute__(self, attr):
2508 if attr in tuple.__dict__:
2509 raise AttributeError
2510 return tuple.__getattribute__(self, attr)
2511
2512
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002513 def count(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302514 return self.__getattr__('count')(*args, **kwargs)
2515
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002516 def index(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302517 return self.__getattr__('index')(*args, **kwargs)
2518
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302519 def _get_call_arguments(self):
2520 if len(self) == 2:
2521 args, kwargs = self
2522 else:
2523 name, args, kwargs = self
2524
2525 return args, kwargs
2526
2527 @property
2528 def args(self):
2529 return self._get_call_arguments()[0]
2530
2531 @property
2532 def kwargs(self):
2533 return self._get_call_arguments()[1]
2534
Michael Foord345266a2012-03-14 12:24:34 -07002535 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002536 if not self._mock_from_kall:
2537 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002538 if name.startswith('()'):
2539 name = 'call%s' % name
2540 return name
2541
2542 if len(self) == 2:
2543 name = 'call'
2544 args, kwargs = self
2545 else:
2546 name, args, kwargs = self
2547 if not name:
2548 name = 'call'
2549 elif not name.startswith('()'):
2550 name = 'call.%s' % name
2551 else:
2552 name = 'call%s' % name
2553 return _format_call_signature(name, args, kwargs)
2554
2555
2556 def call_list(self):
2557 """For a call object that represents multiple calls, `call_list`
2558 returns a list of all the intermediate calls as well as the
2559 final call."""
2560 vals = []
2561 thing = self
2562 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002563 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002564 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002565 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002566 return _CallList(reversed(vals))
2567
2568
2569call = _Call(from_kall=False)
2570
2571
Michael Foord345266a2012-03-14 12:24:34 -07002572def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2573 _name=None, **kwargs):
2574 """Create a mock object using another object as a spec. Attributes on the
2575 mock will use the corresponding attribute on the `spec` object as their
2576 spec.
2577
2578 Functions or methods being mocked will have their arguments checked
2579 to check that they are called with the correct signature.
2580
2581 If `spec_set` is True then attempting to set attributes that don't exist
2582 on the spec object will raise an `AttributeError`.
2583
2584 If a class is used as a spec then the return value of the mock (the
2585 instance of the class) will have the same spec. You can use a class as the
2586 spec for an instance object by passing `instance=True`. The returned mock
2587 will only be callable if instances of the mock are callable.
2588
2589 `create_autospec` also takes arbitrary keyword arguments that are passed to
2590 the constructor of the created mock."""
2591 if _is_list(spec):
2592 # can't pass a list instance to the mock constructor as it will be
2593 # interpreted as a list of strings
2594 spec = type(spec)
2595
2596 is_type = isinstance(spec, type)
Xtreakff6b2e62019-05-27 18:26:23 +05302597 is_async_func = _is_async_func(spec)
Michael Foord345266a2012-03-14 12:24:34 -07002598 _kwargs = {'spec': spec}
2599 if spec_set:
2600 _kwargs = {'spec_set': spec}
2601 elif spec is None:
2602 # None we mock with a normal mock without a spec
2603 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002604 if _kwargs and instance:
2605 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002606
2607 _kwargs.update(kwargs)
2608
2609 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002610 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002611 # descriptors don't have a spec
2612 # because we don't know what type they return
2613 _kwargs = {}
Lisa Roach77b3b772019-05-20 09:19:53 -07002614 elif is_async_func:
2615 if instance:
2616 raise RuntimeError("Instance can not be True when create_autospec "
2617 "is mocking an async function")
2618 Klass = AsyncMock
Michael Foord345266a2012-03-14 12:24:34 -07002619 elif not _callable(spec):
2620 Klass = NonCallableMagicMock
2621 elif is_type and instance and not _instance_callable(spec):
2622 Klass = NonCallableMagicMock
2623
Kushal Das484f8a82014-04-16 01:05:50 +05302624 _name = _kwargs.pop('name', _name)
2625
Michael Foord345266a2012-03-14 12:24:34 -07002626 _new_name = _name
2627 if _parent is None:
2628 # for a top level object no _new_name should be set
2629 _new_name = ''
2630
2631 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2632 name=_name, **_kwargs)
2633
2634 if isinstance(spec, FunctionTypes):
2635 # should only happen at the top level because we don't
2636 # recurse for functions
2637 mock = _set_signature(mock, spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07002638 if is_async_func:
Xtreakff6b2e62019-05-27 18:26:23 +05302639 _setup_async_mock(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002640 else:
2641 _check_signature(spec, mock, is_type, instance)
2642
2643 if _parent is not None and not instance:
2644 _parent._mock_children[_name] = mock
2645
2646 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002647 mock.return_value = create_autospec(spec, spec_set, instance=True,
2648 _name='()', _parent=mock)
2649
2650 for entry in dir(spec):
2651 if _is_magic(entry):
2652 # MagicMock already does the useful magic methods for us
2653 continue
2654
Michael Foord345266a2012-03-14 12:24:34 -07002655 # XXXX do we need a better way of getting attributes without
2656 # triggering code execution (?) Probably not - we need the actual
2657 # object to mock it so we would rather trigger a property than mock
2658 # the property descriptor. Likewise we want to mock out dynamically
2659 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002660 # XXXX what about attributes that raise exceptions other than
2661 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002662 # we could be resilient against it, or catch and propagate the
2663 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002664 try:
2665 original = getattr(spec, entry)
2666 except AttributeError:
2667 continue
Michael Foord345266a2012-03-14 12:24:34 -07002668
2669 kwargs = {'spec': original}
2670 if spec_set:
2671 kwargs = {'spec_set': original}
2672
2673 if not isinstance(original, FunctionTypes):
2674 new = _SpecState(original, spec_set, mock, entry, instance)
2675 mock._mock_children[entry] = new
2676 else:
2677 parent = mock
2678 if isinstance(spec, FunctionTypes):
2679 parent = mock.mock
2680
Michael Foord345266a2012-03-14 12:24:34 -07002681 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002682 kwargs['_eat_self'] = skipfirst
Lisa Roach77b3b772019-05-20 09:19:53 -07002683 if asyncio.iscoroutinefunction(original):
2684 child_klass = AsyncMock
2685 else:
2686 child_klass = MagicMock
2687 new = child_klass(parent=parent, name=entry, _new_name=entry,
2688 _new_parent=parent,
2689 **kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002690 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002691 _check_signature(original, new, skipfirst=skipfirst)
2692
2693 # so functions created with _set_signature become instance attributes,
2694 # *plus* their underlying mock exists in _mock_children of the parent
2695 # mock. Adding to _mock_children may be unnecessary where we are also
2696 # setting as an instance attribute?
2697 if isinstance(new, FunctionTypes):
2698 setattr(mock, entry, new)
2699
2700 return mock
2701
2702
2703def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002704 """
2705 Return whether we should skip the first argument on spec's `entry`
2706 attribute.
2707 """
Michael Foord345266a2012-03-14 12:24:34 -07002708 if not isinstance(spec, type):
2709 if entry in getattr(spec, '__dict__', {}):
2710 # instance attribute - shouldn't skip
2711 return False
Michael Foord345266a2012-03-14 12:24:34 -07002712 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002713
2714 for klass in spec.__mro__:
2715 result = klass.__dict__.get(entry, DEFAULT)
2716 if result is DEFAULT:
2717 continue
2718 if isinstance(result, (staticmethod, classmethod)):
2719 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002720 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2721 # Normal method => skip if looked up on type
2722 # (if looked up on instance, self is already skipped)
2723 return is_type
2724 else:
2725 return False
Michael Foord345266a2012-03-14 12:24:34 -07002726
Chris Withersadbf1782019-05-01 23:04:04 +01002727 # function is a dynamically provided attribute
Michael Foord345266a2012-03-14 12:24:34 -07002728 return is_type
2729
2730
Michael Foord345266a2012-03-14 12:24:34 -07002731class _SpecState(object):
2732
2733 def __init__(self, spec, spec_set=False, parent=None,
2734 name=None, ids=None, instance=False):
2735 self.spec = spec
2736 self.ids = ids
2737 self.spec_set = spec_set
2738 self.parent = parent
2739 self.instance = instance
2740 self.name = name
2741
2742
2743FunctionTypes = (
2744 # python function
2745 type(create_autospec),
2746 # instance method
2747 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002748)
2749
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002750MethodWrapperTypes = (
2751 type(ANY.__eq__.__get__),
2752)
2753
Michael Foord345266a2012-03-14 12:24:34 -07002754
Michael Foorda74561a2012-03-25 19:03:13 +01002755file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002756
Michael Foord04cbe0c2013-03-19 17:22:51 -07002757
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002758def _to_stream(read_data):
2759 if isinstance(read_data, bytes):
2760 return io.BytesIO(read_data)
Michael Foord04cbe0c2013-03-19 17:22:51 -07002761 else:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002762 return io.StringIO(read_data)
Michael Foord0dccf652012-03-25 19:11:50 +01002763
Robert Collins5329aaa2015-07-17 20:08:45 +12002764
Michael Foord0dccf652012-03-25 19:11:50 +01002765def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002766 """
2767 A helper function to create a mock to replace the use of `open`. It works
2768 for `open` called directly or used as a context manager.
2769
2770 The `mock` argument is the mock object to configure. If `None` (the
2771 default) then a `MagicMock` will be created for you, with the API limited
2772 to methods or attributes available on standard file handles.
2773
Xtreak71f82a22018-12-20 21:30:21 +05302774 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002775 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002776 """
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002777 _read_data = _to_stream(read_data)
2778 _state = [_read_data, None]
2779
Robert Collinsca647ef2015-07-24 03:48:20 +12002780 def _readlines_side_effect(*args, **kwargs):
2781 if handle.readlines.return_value is not None:
2782 return handle.readlines.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002783 return _state[0].readlines(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002784
2785 def _read_side_effect(*args, **kwargs):
2786 if handle.read.return_value is not None:
2787 return handle.read.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002788 return _state[0].read(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002789
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002790 def _readline_side_effect(*args, **kwargs):
Tony Flury20870232018-09-12 23:21:16 +01002791 yield from _iter_side_effect()
2792 while True:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002793 yield _state[0].readline(*args, **kwargs)
Tony Flury20870232018-09-12 23:21:16 +01002794
2795 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002796 if handle.readline.return_value is not None:
2797 while True:
2798 yield handle.readline.return_value
2799 for line in _state[0]:
2800 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002801
Damien Nadé394119a2019-05-23 12:03:25 +02002802 def _next_side_effect():
2803 if handle.readline.return_value is not None:
2804 return handle.readline.return_value
2805 return next(_state[0])
2806
Michael Foorda74561a2012-03-25 19:03:13 +01002807 global file_spec
2808 if file_spec is None:
2809 import _io
2810 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2811
Michael Foord345266a2012-03-14 12:24:34 -07002812 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002813 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002814
Robert Collinsca647ef2015-07-24 03:48:20 +12002815 handle = MagicMock(spec=file_spec)
2816 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002817
Robert Collinsca647ef2015-07-24 03:48:20 +12002818 handle.write.return_value = None
2819 handle.read.return_value = None
2820 handle.readline.return_value = None
2821 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002822
Robert Collinsca647ef2015-07-24 03:48:20 +12002823 handle.read.side_effect = _read_side_effect
2824 _state[1] = _readline_side_effect()
2825 handle.readline.side_effect = _state[1]
2826 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002827 handle.__iter__.side_effect = _iter_side_effect
Damien Nadé394119a2019-05-23 12:03:25 +02002828 handle.__next__.side_effect = _next_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002829
Robert Collinsca647ef2015-07-24 03:48:20 +12002830 def reset_data(*args, **kwargs):
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002831 _state[0] = _to_stream(read_data)
Robert Collinsca647ef2015-07-24 03:48:20 +12002832 if handle.readline.side_effect == _state[1]:
2833 # Only reset the side effect if the user hasn't overridden it.
2834 _state[1] = _readline_side_effect()
2835 handle.readline.side_effect = _state[1]
2836 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002837
Robert Collinsca647ef2015-07-24 03:48:20 +12002838 mock.side_effect = reset_data
2839 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002840 return mock
2841
2842
2843class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002844 """
2845 A mock intended to be used as a property, or other descriptor, on a class.
2846 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2847 a return value when it is fetched.
2848
2849 Fetching a `PropertyMock` instance from an object calls the mock, with
2850 no args. Setting it calls the mock with the value being set.
2851 """
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002852 def _get_child_mock(self, /, **kwargs):
Michael Foordc2870622012-04-13 16:57:22 +01002853 return MagicMock(**kwargs)
2854
Raymond Hettinger0dac68f2019-08-29 01:27:42 -07002855 def __get__(self, obj, obj_type=None):
Michael Foord345266a2012-03-14 12:24:34 -07002856 return self()
2857 def __set__(self, obj, val):
2858 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002859
2860
2861def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002862 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002863
2864 Given an input Mock, seals it to ensure no further mocks will be generated
2865 when accessing an attribute that was not already defined.
2866
Mario Corchero96200eb2018-10-19 22:57:37 +01002867 The operation recursively seals the mock passed in, meaning that
2868 the mock itself, any mocks generated by accessing one of its attributes,
2869 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002870 """
2871 mock._mock_sealed = True
2872 for attr in dir(mock):
2873 try:
2874 m = getattr(mock, attr)
2875 except AttributeError:
2876 continue
2877 if not isinstance(m, NonCallableMock):
2878 continue
2879 if m._mock_new_parent is mock:
2880 seal(m)
Lisa Roach77b3b772019-05-20 09:19:53 -07002881
2882
Lisa Roach77b3b772019-05-20 09:19:53 -07002883class _AsyncIterator:
2884 """
2885 Wraps an iterator in an asynchronous iterator.
2886 """
2887 def __init__(self, iterator):
2888 self.iterator = iterator
2889 code_mock = NonCallableMock(spec_set=CodeType)
2890 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
2891 self.__dict__['__code__'] = code_mock
2892
2893 def __aiter__(self):
2894 return self
2895
2896 async def __anext__(self):
2897 try:
2898 return next(self.iterator)
2899 except StopIteration:
2900 pass
2901 raise StopAsyncIteration