blob: 5ea562428a1249a8cc67e24f7c86237e29a077b7 [file] [log] [blame]
Michael Foord345266a2012-03-14 12:24:34 -07001# mock.py
2# Test tools for mocking and patching.
Michael Foordc17adf42012-03-14 13:30:29 -07003# Maintained by Michael Foord
4# Backport for other versions of Python available from
Ned Deily9d6d06e2018-06-11 00:45:50 -04005# https://pypi.org/project/mock
Michael Foord345266a2012-03-14 12:24:34 -07006
7__all__ = (
8 'Mock',
9 'MagicMock',
10 'patch',
11 'sentinel',
12 'DEFAULT',
13 'ANY',
14 'call',
15 'create_autospec',
Lisa Roach77b3b772019-05-20 09:19:53 -070016 'AsyncMock',
Michael Foord345266a2012-03-14 12:24:34 -070017 'FILTER_DIR',
18 'NonCallableMock',
19 'NonCallableMagicMock',
20 'mock_open',
21 'PropertyMock',
Mario Corchero552be9d2017-10-17 12:35:11 +010022 'seal',
Michael Foord345266a2012-03-14 12:24:34 -070023)
24
25
26__version__ = '1.0'
27
Lisa Roach77b3b772019-05-20 09:19:53 -070028import asyncio
Xtreak436c2b02019-05-28 12:37:39 +053029import contextlib
Rémi Lapeyre11a88322019-05-07 12:48:36 +020030import io
Michael Foord345266a2012-03-14 12:24:34 -070031import inspect
32import pprint
33import sys
Michael Foordfddcfa22014-04-14 16:25:20 -040034import builtins
Lisa Roach77b3b772019-05-20 09:19:53 -070035from types import CodeType, ModuleType, MethodType
Petter Strandmark47d94242018-10-28 21:37:10 +010036from unittest.util import safe_repr
Antoine Pitrou5c64df72013-02-03 00:23:58 +010037from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070038
39
Michael Foordfddcfa22014-04-14 16:25:20 -040040_builtins = {name for name in dir(builtins) if not name.startswith('_')}
41
Michael Foord345266a2012-03-14 12:24:34 -070042FILTER_DIR = True
43
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100044# Workaround for issue #12370
45# Without this, the __class__ properties wouldn't be set correctly
46_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070047
Lisa Roach77b3b772019-05-20 09:19:53 -070048def _is_async_obj(obj):
Miss Islington (bot)c3008dd2019-09-10 06:16:00 -070049 if _is_instance_mock(obj) and not isinstance(obj, AsyncMock):
Lisa Roach77b3b772019-05-20 09:19:53 -070050 return False
Miss Islington (bot)c3008dd2019-09-10 06:16:00 -070051 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
Miss Islington (bot)22fd6792019-07-22 00:59:00 -070074def _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()
249 mock.awaited = _AwaitEvent(mock)
250
251 # Mock is not configured yet so the attributes are set
252 # to a function and then the corresponding mock helper function
253 # is called when the helper is accessed similar to _setup_func.
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300254 def wrapper(attr, /, *args, **kwargs):
Xtreakff6b2e62019-05-27 18:26:23 +0530255 return getattr(mock.mock, attr)(*args, **kwargs)
256
257 for attribute in ('assert_awaited',
258 'assert_awaited_once',
259 'assert_awaited_with',
260 'assert_awaited_once_with',
261 'assert_any_await',
262 'assert_has_awaits',
263 'assert_not_awaited'):
264
265 # setattr(mock, attribute, wrapper) causes late binding
266 # hence attribute will always be the last value in the loop
267 # Use partial(wrapper, attribute) to ensure the attribute is bound
268 # correctly.
269 setattr(mock, attribute, partial(wrapper, attribute))
270
271
Michael Foord345266a2012-03-14 12:24:34 -0700272def _is_magic(name):
273 return '__%s__' % name[2:-2] == name
274
275
276class _SentinelObject(object):
277 "A unique, named, sentinel object."
278 def __init__(self, name):
279 self.name = name
280
281 def __repr__(self):
282 return 'sentinel.%s' % self.name
283
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200284 def __reduce__(self):
285 return 'sentinel.%s' % self.name
286
Michael Foord345266a2012-03-14 12:24:34 -0700287
288class _Sentinel(object):
289 """Access attributes to return a named object, usable as a sentinel."""
290 def __init__(self):
291 self._sentinels = {}
292
293 def __getattr__(self, name):
294 if name == '__bases__':
295 # Without this help(unittest.mock) raises an exception
296 raise AttributeError
297 return self._sentinels.setdefault(name, _SentinelObject(name))
298
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200299 def __reduce__(self):
300 return 'sentinel'
301
Michael Foord345266a2012-03-14 12:24:34 -0700302
303sentinel = _Sentinel()
304
305DEFAULT = sentinel.DEFAULT
306_missing = sentinel.MISSING
307_deleted = sentinel.DELETED
308
309
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200310_allowed_names = {
311 'return_value', '_mock_return_value', 'side_effect',
312 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
313 '_mock_name', '_mock_new_name'
314}
Michael Foord345266a2012-03-14 12:24:34 -0700315
316
317def _delegating_property(name):
318 _allowed_names.add(name)
319 _the_name = '_mock_' + name
320 def _get(self, name=name, _the_name=_the_name):
321 sig = self._mock_delegate
322 if sig is None:
323 return getattr(self, _the_name)
324 return getattr(sig, name)
325 def _set(self, value, name=name, _the_name=_the_name):
326 sig = self._mock_delegate
327 if sig is None:
328 self.__dict__[_the_name] = value
329 else:
330 setattr(sig, name, value)
331
332 return property(_get, _set)
333
334
335
336class _CallList(list):
337
338 def __contains__(self, value):
339 if not isinstance(value, list):
340 return list.__contains__(self, value)
341 len_value = len(value)
342 len_self = len(self)
343 if len_value > len_self:
344 return False
345
346 for i in range(0, len_self - len_value + 1):
347 sub_list = self[i:i+len_value]
348 if sub_list == value:
349 return True
350 return False
351
352 def __repr__(self):
353 return pprint.pformat(list(self))
354
355
356def _check_and_set_parent(parent, value, name, new_name):
Miss Islington (bot)22fd6792019-07-22 00:59:00 -0700357 value = _extract_mock(value)
Xtreak9c3f2842019-02-26 03:16:34 +0530358
Michael Foord345266a2012-03-14 12:24:34 -0700359 if not _is_instance_mock(value):
360 return False
361 if ((value._mock_name or value._mock_new_name) or
362 (value._mock_parent is not None) or
363 (value._mock_new_parent is not None)):
364 return False
365
366 _parent = parent
367 while _parent is not None:
368 # setting a mock (value) as a child or return value of itself
369 # should not modify the mock
370 if _parent is value:
371 return False
372 _parent = _parent._mock_new_parent
373
374 if new_name:
375 value._mock_new_parent = parent
376 value._mock_new_name = new_name
377 if name:
378 value._mock_parent = parent
379 value._mock_name = name
380 return True
381
Michael Foord01bafdc2014-04-14 16:09:42 -0400382# Internal class to identify if we wrapped an iterator object or not.
383class _MockIter(object):
384 def __init__(self, obj):
385 self.obj = iter(obj)
Michael Foord01bafdc2014-04-14 16:09:42 -0400386 def __next__(self):
387 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700388
389class Base(object):
390 _mock_return_value = DEFAULT
391 _mock_side_effect = None
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300392 def __init__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700393 pass
394
395
396
397class NonCallableMock(Base):
398 """A non-callable version of `Mock`"""
399
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300400 def __new__(cls, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700401 # every instance has its own class
402 # so we can create magic methods on the
403 # class without stomping on other mocks
Lisa Roach77b3b772019-05-20 09:19:53 -0700404 bases = (cls,)
405 if not issubclass(cls, AsyncMock):
406 # Check if spec is an async object or function
407 sig = inspect.signature(NonCallableMock.__init__)
408 bound_args = sig.bind_partial(cls, *args, **kw).arguments
409 spec_arg = [
410 arg for arg in bound_args.keys()
411 if arg.startswith('spec')
412 ]
413 if spec_arg:
414 # what if spec_set is different than spec?
415 if _is_async_obj(bound_args[spec_arg[0]]):
416 bases = (AsyncMockMixin, cls,)
417 new = type(cls.__name__, bases, {'__doc__': cls.__doc__})
Michael Foord345266a2012-03-14 12:24:34 -0700418 instance = object.__new__(new)
419 return instance
420
421
422 def __init__(
423 self, spec=None, wraps=None, name=None, spec_set=None,
424 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530425 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700426 ):
427 if _new_parent is None:
428 _new_parent = parent
429
430 __dict__ = self.__dict__
431 __dict__['_mock_parent'] = parent
432 __dict__['_mock_name'] = name
433 __dict__['_mock_new_name'] = _new_name
434 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100435 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700436
437 if spec_set is not None:
438 spec = spec_set
439 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100440 if _eat_self is None:
441 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700442
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100443 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700444
445 __dict__['_mock_children'] = {}
446 __dict__['_mock_wraps'] = wraps
447 __dict__['_mock_delegate'] = None
448
449 __dict__['_mock_called'] = False
450 __dict__['_mock_call_args'] = None
451 __dict__['_mock_call_count'] = 0
452 __dict__['_mock_call_args_list'] = _CallList()
453 __dict__['_mock_mock_calls'] = _CallList()
454
455 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530456 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700457
458 if kwargs:
459 self.configure_mock(**kwargs)
460
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000461 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700462 spec, wraps, name, spec_set, parent,
463 _spec_state
464 )
465
466
467 def attach_mock(self, mock, attribute):
468 """
469 Attach a mock as an attribute of this one, replacing its name and
470 parent. Calls to the attached mock will be recorded in the
471 `method_calls` and `mock_calls` attributes of this one."""
Miss Islington (bot)22fd6792019-07-22 00:59:00 -0700472 inner_mock = _extract_mock(mock)
473
474 inner_mock._mock_parent = None
475 inner_mock._mock_new_parent = None
476 inner_mock._mock_name = ''
477 inner_mock._mock_new_name = None
Michael Foord345266a2012-03-14 12:24:34 -0700478
479 setattr(self, attribute, mock)
480
481
482 def mock_add_spec(self, spec, spec_set=False):
483 """Add a spec to a mock. `spec` can either be an object or a
484 list of strings. Only attributes on the `spec` can be fetched as
485 attributes from the mock.
486
487 If `spec_set` is True then only attributes on the spec can be set."""
488 self._mock_add_spec(spec, spec_set)
489
490
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100491 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
492 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700493 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100494 _spec_signature = None
Lisa Roach77b3b772019-05-20 09:19:53 -0700495 _spec_asyncs = []
496
497 for attr in dir(spec):
498 if asyncio.iscoroutinefunction(getattr(spec, attr, None)):
499 _spec_asyncs.append(attr)
Michael Foord345266a2012-03-14 12:24:34 -0700500
501 if spec is not None and not _is_list(spec):
502 if isinstance(spec, type):
503 _spec_class = spec
504 else:
Chris Withersadbf1782019-05-01 23:04:04 +0100505 _spec_class = type(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100506 res = _get_signature_object(spec,
507 _spec_as_instance, _eat_self)
508 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700509
510 spec = dir(spec)
511
512 __dict__ = self.__dict__
513 __dict__['_spec_class'] = _spec_class
514 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100515 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700516 __dict__['_mock_methods'] = spec
Lisa Roach77b3b772019-05-20 09:19:53 -0700517 __dict__['_spec_asyncs'] = _spec_asyncs
Michael Foord345266a2012-03-14 12:24:34 -0700518
519 def __get_return_value(self):
520 ret = self._mock_return_value
521 if self._mock_delegate is not None:
522 ret = self._mock_delegate.return_value
523
524 if ret is DEFAULT:
525 ret = self._get_child_mock(
526 _new_parent=self, _new_name='()'
527 )
528 self.return_value = ret
529 return ret
530
531
532 def __set_return_value(self, value):
533 if self._mock_delegate is not None:
534 self._mock_delegate.return_value = value
535 else:
536 self._mock_return_value = value
537 _check_and_set_parent(self, value, None, '()')
538
539 __return_value_doc = "The value to be returned when the mock is called."
540 return_value = property(__get_return_value, __set_return_value,
541 __return_value_doc)
542
543
544 @property
545 def __class__(self):
546 if self._spec_class is None:
547 return type(self)
548 return self._spec_class
549
550 called = _delegating_property('called')
551 call_count = _delegating_property('call_count')
552 call_args = _delegating_property('call_args')
553 call_args_list = _delegating_property('call_args_list')
554 mock_calls = _delegating_property('mock_calls')
555
556
557 def __get_side_effect(self):
558 delegated = self._mock_delegate
559 if delegated is None:
560 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400561 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200562 if (sf is not None and not callable(sf)
563 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400564 sf = _MockIter(sf)
565 delegated.side_effect = sf
566 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700567
568 def __set_side_effect(self, value):
569 value = _try_iter(value)
570 delegated = self._mock_delegate
571 if delegated is None:
572 self._mock_side_effect = value
573 else:
574 delegated.side_effect = value
575
576 side_effect = property(__get_side_effect, __set_side_effect)
577
578
Kushal Das9cd39a12016-06-02 10:20:16 -0700579 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700580 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200581 if visited is None:
582 visited = []
583 if id(self) in visited:
584 return
585 visited.append(id(self))
586
Michael Foord345266a2012-03-14 12:24:34 -0700587 self.called = False
588 self.call_args = None
589 self.call_count = 0
590 self.mock_calls = _CallList()
591 self.call_args_list = _CallList()
592 self.method_calls = _CallList()
593
Kushal Das9cd39a12016-06-02 10:20:16 -0700594 if return_value:
595 self._mock_return_value = DEFAULT
596 if side_effect:
597 self._mock_side_effect = None
598
Michael Foord345266a2012-03-14 12:24:34 -0700599 for child in self._mock_children.values():
Xtreakedeca922018-12-01 15:33:54 +0530600 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100601 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200602 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700603
604 ret = self._mock_return_value
605 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200606 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700607
608
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300609 def configure_mock(self, /, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700610 """Set attributes on the mock through keyword arguments.
611
612 Attributes plus return values and side effects can be set on child
613 mocks using standard dot notation and unpacking a dictionary in the
614 method call:
615
616 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
617 >>> mock.configure_mock(**attrs)"""
618 for arg, val in sorted(kwargs.items(),
619 # we sort on the number of dots so that
620 # attributes are set before we set attributes on
621 # attributes
622 key=lambda entry: entry[0].count('.')):
623 args = arg.split('.')
624 final = args.pop()
625 obj = self
626 for entry in args:
627 obj = getattr(obj, entry)
628 setattr(obj, final, val)
629
630
631 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530632 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700633 raise AttributeError(name)
634 elif self._mock_methods is not None:
635 if name not in self._mock_methods or name in _all_magics:
636 raise AttributeError("Mock object has no attribute %r" % name)
637 elif _is_magic(name):
638 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530639 if not self._mock_unsafe:
640 if name.startswith(('assert', 'assret')):
Zackery Spytzb9b08cd2019-05-08 11:32:24 -0600641 raise AttributeError("Attributes cannot start with 'assert' "
642 "or 'assret'")
Michael Foord345266a2012-03-14 12:24:34 -0700643
644 result = self._mock_children.get(name)
645 if result is _deleted:
646 raise AttributeError(name)
647 elif result is None:
648 wraps = None
649 if self._mock_wraps is not None:
650 # XXXX should we get the attribute without triggering code
651 # execution?
652 wraps = getattr(self._mock_wraps, name)
653
654 result = self._get_child_mock(
655 parent=self, name=name, wraps=wraps, _new_name=name,
656 _new_parent=self
657 )
658 self._mock_children[name] = result
659
660 elif isinstance(result, _SpecState):
661 result = create_autospec(
662 result.spec, result.spec_set, result.instance,
663 result.parent, result.name
664 )
665 self._mock_children[name] = result
666
667 return result
668
669
Mario Corchero552be9d2017-10-17 12:35:11 +0100670 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700671 _name_list = [self._mock_new_name]
672 _parent = self._mock_new_parent
673 last = self
674
675 dot = '.'
676 if _name_list == ['()']:
677 dot = ''
Chris Withersadbf1782019-05-01 23:04:04 +0100678
Michael Foord345266a2012-03-14 12:24:34 -0700679 while _parent is not None:
680 last = _parent
681
682 _name_list.append(_parent._mock_new_name + dot)
683 dot = '.'
684 if _parent._mock_new_name == '()':
685 dot = ''
686
687 _parent = _parent._mock_new_parent
688
Michael Foord345266a2012-03-14 12:24:34 -0700689 _name_list = list(reversed(_name_list))
690 _first = last._mock_name or 'mock'
691 if len(_name_list) > 1:
692 if _name_list[1] not in ('()', '().'):
693 _first += '.'
694 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100695 return ''.join(_name_list)
696
697 def __repr__(self):
698 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700699
700 name_string = ''
701 if name not in ('mock', 'mock.'):
702 name_string = ' name=%r' % name
703
704 spec_string = ''
705 if self._spec_class is not None:
706 spec_string = ' spec=%r'
707 if self._spec_set:
708 spec_string = ' spec_set=%r'
709 spec_string = spec_string % self._spec_class.__name__
710 return "<%s%s%s id='%s'>" % (
711 type(self).__name__,
712 name_string,
713 spec_string,
714 id(self)
715 )
716
717
718 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700719 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100720 if not FILTER_DIR:
721 return object.__dir__(self)
722
Michael Foord345266a2012-03-14 12:24:34 -0700723 extras = self._mock_methods or []
724 from_type = dir(type(self))
725 from_dict = list(self.__dict__)
Mario Corchero0df635c2019-04-30 19:56:36 +0100726 from_child_mocks = [
727 m_name for m_name, m_value in self._mock_children.items()
728 if m_value is not _deleted]
Michael Foord345266a2012-03-14 12:24:34 -0700729
Michael Foord313f85f2012-03-25 18:16:07 +0100730 from_type = [e for e in from_type if not e.startswith('_')]
731 from_dict = [e for e in from_dict if not e.startswith('_') or
732 _is_magic(e)]
Mario Corchero0df635c2019-04-30 19:56:36 +0100733 return sorted(set(extras + from_type + from_dict + from_child_mocks))
Michael Foord345266a2012-03-14 12:24:34 -0700734
735
736 def __setattr__(self, name, value):
737 if name in _allowed_names:
738 # property setters go through here
739 return object.__setattr__(self, name, value)
740 elif (self._spec_set and self._mock_methods is not None and
741 name not in self._mock_methods and
742 name not in self.__dict__):
743 raise AttributeError("Mock object has no attribute '%s'" % name)
744 elif name in _unsupported_magics:
745 msg = 'Attempting to set unsupported magic method %r.' % name
746 raise AttributeError(msg)
747 elif name in _all_magics:
748 if self._mock_methods is not None and name not in self._mock_methods:
749 raise AttributeError("Mock object has no attribute '%s'" % name)
750
751 if not _is_instance_mock(value):
752 setattr(type(self), name, _get_method(name, value))
753 original = value
754 value = lambda *args, **kw: original(self, *args, **kw)
755 else:
756 # only set _new_name and not name so that mock_calls is tracked
757 # but not method calls
758 _check_and_set_parent(self, value, None, name)
759 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100760 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700761 elif name == '__class__':
762 self._spec_class = value
763 return
764 else:
765 if _check_and_set_parent(self, value, name, name):
766 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100767
768 if self._mock_sealed and not hasattr(self, name):
769 mock_name = f'{self._extract_mock_name()}.{name}'
770 raise AttributeError(f'Cannot set {mock_name}')
771
Michael Foord345266a2012-03-14 12:24:34 -0700772 return object.__setattr__(self, name, value)
773
774
775 def __delattr__(self, name):
776 if name in _all_magics and name in type(self).__dict__:
777 delattr(type(self), name)
778 if name not in self.__dict__:
779 # for magic methods that are still MagicProxy objects and
780 # not set on the instance itself
781 return
782
Michael Foord345266a2012-03-14 12:24:34 -0700783 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000784 if name in self.__dict__:
Xtreak830b43d2019-04-14 00:42:33 +0530785 _safe_super(NonCallableMock, self).__delattr__(name)
Pablo Galindo222d3032019-01-21 08:57:46 +0000786 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700787 raise AttributeError(name)
788 if obj is not _missing:
789 del self._mock_children[name]
790 self._mock_children[name] = _deleted
791
792
Michael Foord345266a2012-03-14 12:24:34 -0700793 def _format_mock_call_signature(self, args, kwargs):
794 name = self._mock_name or 'mock'
795 return _format_call_signature(name, args, kwargs)
796
797
Xtreak0ae022c2019-05-29 12:32:26 +0530798 def _format_mock_failure_message(self, args, kwargs, action='call'):
799 message = 'expected %s not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700800 expected_string = self._format_mock_call_signature(args, kwargs)
801 call_args = self.call_args
Michael Foord345266a2012-03-14 12:24:34 -0700802 actual_string = self._format_mock_call_signature(*call_args)
Xtreak0ae022c2019-05-29 12:32:26 +0530803 return message % (action, expected_string, actual_string)
Michael Foord345266a2012-03-14 12:24:34 -0700804
805
Miss Islington (bot)38d311d2019-08-28 23:58:27 -0700806 def _get_call_signature_from_name(self, name):
807 """
808 * If call objects are asserted against a method/function like obj.meth1
809 then there could be no name for the call object to lookup. Hence just
810 return the spec_signature of the method/function being asserted against.
811 * If the name is not empty then remove () and split by '.' to get
812 list of names to iterate through the children until a potential
813 match is found. A child mock is created only during attribute access
814 so if we get a _SpecState then no attributes of the spec were accessed
815 and can be safely exited.
816 """
817 if not name:
818 return self._spec_signature
819
820 sig = None
821 names = name.replace('()', '').split('.')
822 children = self._mock_children
823
824 for name in names:
825 child = children.get(name)
826 if child is None or isinstance(child, _SpecState):
827 break
828 else:
829 children = child._mock_children
830 sig = child._spec_signature
831
832 return sig
833
834
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100835 def _call_matcher(self, _call):
836 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000837 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100838 comparison key suitable for matching with other calls.
839 This is a best effort method which relies on the spec's signature,
840 if available, or falls back on the arguments themselves.
841 """
Miss Islington (bot)38d311d2019-08-28 23:58:27 -0700842
843 if isinstance(_call, tuple) and len(_call) > 2:
844 sig = self._get_call_signature_from_name(_call[0])
845 else:
846 sig = self._spec_signature
847
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100848 if sig is not None:
849 if len(_call) == 2:
850 name = ''
851 args, kwargs = _call
852 else:
853 name, args, kwargs = _call
854 try:
855 return name, sig.bind(*args, **kwargs)
856 except TypeError as e:
857 return e.with_traceback(None)
858 else:
859 return _call
860
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300861 def assert_not_called(self):
Kushal Das8af9db32014-04-17 01:36:14 +0530862 """assert that the mock was never called.
863 """
Kushal Das8af9db32014-04-17 01:36:14 +0530864 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100865 msg = ("Expected '%s' to not have been called. Called %s times.%s"
866 % (self._mock_name or 'mock',
867 self.call_count,
868 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530869 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100870
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300871 def assert_called(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100872 """assert that the mock was called at least once
873 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100874 if self.call_count == 0:
875 msg = ("Expected '%s' to have been called." %
Miss Islington (bot)f668d2b2019-09-17 04:35:56 -0700876 (self._mock_name or 'mock'))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100877 raise AssertionError(msg)
878
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300879 def assert_called_once(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100880 """assert that the mock was called only once.
881 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100882 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100883 msg = ("Expected '%s' to have been called once. Called %s times.%s"
884 % (self._mock_name or 'mock',
885 self.call_count,
886 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100887 raise AssertionError(msg)
888
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300889 def assert_called_with(self, /, *args, **kwargs):
Miss Islington (bot)612d3932019-08-28 23:39:47 -0700890 """assert that the last call was made with the specified arguments.
Michael Foord345266a2012-03-14 12:24:34 -0700891
892 Raises an AssertionError if the args and keyword args passed in are
893 different to the last call to the mock."""
Michael Foord345266a2012-03-14 12:24:34 -0700894 if self.call_args is None:
895 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800896 actual = 'not called.'
897 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
898 % (expected, actual))
899 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700900
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100901 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700902 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100903 return msg
904 expected = self._call_matcher((args, kwargs))
905 actual = self._call_matcher(self.call_args)
906 if expected != actual:
907 cause = expected if isinstance(expected, Exception) else None
908 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700909
910
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300911 def assert_called_once_with(self, /, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100912 """assert that the mock was called exactly once and that that call was
913 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700914 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100915 msg = ("Expected '%s' to be called once. Called %s times.%s"
916 % (self._mock_name or 'mock',
917 self.call_count,
918 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700919 raise AssertionError(msg)
920 return self.assert_called_with(*args, **kwargs)
921
922
923 def assert_has_calls(self, calls, any_order=False):
924 """assert the mock has been called with the specified calls.
925 The `mock_calls` list is checked for the calls.
926
927 If `any_order` is False (the default) then the calls must be
928 sequential. There can be extra calls before or after the
929 specified calls.
930
931 If `any_order` is True then the calls can be in any order, but
932 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100933 expected = [self._call_matcher(c) for c in calls]
Miss Islington (bot)1a17a052019-09-24 17:29:17 -0700934 cause = next((e for e in expected if isinstance(e, Exception)), None)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100935 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700936 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100937 if expected not in all_calls:
Miss Islington (bot)1a17a052019-09-24 17:29:17 -0700938 if cause is None:
939 problem = 'Calls not found.'
940 else:
941 problem = ('Error processing expected calls.\n'
942 'Errors: {}').format(
943 [e if isinstance(e, Exception) else None
944 for e in expected])
Michael Foord345266a2012-03-14 12:24:34 -0700945 raise AssertionError(
Miss Islington (bot)1a17a052019-09-24 17:29:17 -0700946 f'{problem}\n'
947 f'Expected: {_CallList(calls)}'
948 f'{self._calls_repr(prefix="Actual").rstrip(".")}'
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100949 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700950 return
951
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100952 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700953
954 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100955 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700956 try:
957 all_calls.remove(kall)
958 except ValueError:
959 not_found.append(kall)
960 if not_found:
961 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400962 '%r does not contain all of %r in its call list, '
963 'found %r instead' % (self._mock_name or 'mock',
964 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100965 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700966
967
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300968 def assert_any_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700969 """assert the mock has been called with the specified arguments.
970
971 The assert passes if the mock has *ever* been called, unlike
972 `assert_called_with` and `assert_called_once_with` that only pass if
973 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100974 expected = self._call_matcher((args, kwargs))
975 actual = [self._call_matcher(c) for c in self.call_args_list]
976 if expected not in actual:
977 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700978 expected_string = self._format_mock_call_signature(args, kwargs)
979 raise AssertionError(
980 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100981 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700982
983
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300984 def _get_child_mock(self, /, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700985 """Create the child mocks for attributes and return value.
986 By default child mocks will be the same type as the parent.
987 Subclasses of Mock may want to override this to customize the way
988 child mocks are made.
989
990 For non-callable mocks the callable variant will be used (rather than
991 any custom subclass)."""
Lisa Roach77b3b772019-05-20 09:19:53 -0700992 _new_name = kw.get("_new_name")
993 if _new_name in self.__dict__['_spec_asyncs']:
994 return AsyncMock(**kw)
995
Michael Foord345266a2012-03-14 12:24:34 -0700996 _type = type(self)
Lisa Roach77b3b772019-05-20 09:19:53 -0700997 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
998 klass = AsyncMock
Lisa Roach865bb682019-09-20 23:00:04 -0700999 elif _new_name in _sync_async_magics:
1000 # Special case these ones b/c users will assume they are async,
1001 # but they are actually sync (ie. __aiter__)
Lisa Roach77b3b772019-05-20 09:19:53 -07001002 klass = MagicMock
Lisa Roach865bb682019-09-20 23:00:04 -07001003 elif issubclass(_type, AsyncMockMixin):
1004 klass = AsyncMock
1005 elif not issubclass(_type, CallableMixin):
Michael Foord345266a2012-03-14 12:24:34 -07001006 if issubclass(_type, NonCallableMagicMock):
1007 klass = MagicMock
1008 elif issubclass(_type, NonCallableMock) :
1009 klass = Mock
1010 else:
1011 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +01001012
1013 if self._mock_sealed:
1014 attribute = "." + kw["name"] if "name" in kw else "()"
1015 mock_name = self._extract_mock_name() + attribute
1016 raise AttributeError(mock_name)
1017
Michael Foord345266a2012-03-14 12:24:34 -07001018 return klass(**kw)
1019
1020
Petter Strandmark47d94242018-10-28 21:37:10 +01001021 def _calls_repr(self, prefix="Calls"):
1022 """Renders self.mock_calls as a string.
1023
1024 Example: "\nCalls: [call(1), call(2)]."
1025
1026 If self.mock_calls is empty, an empty string is returned. The
1027 output will be truncated if very long.
1028 """
1029 if not self.mock_calls:
1030 return ""
1031 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
1032
1033
Michael Foord345266a2012-03-14 12:24:34 -07001034
1035def _try_iter(obj):
1036 if obj is None:
1037 return obj
1038 if _is_exception(obj):
1039 return obj
1040 if _callable(obj):
1041 return obj
1042 try:
1043 return iter(obj)
1044 except TypeError:
1045 # XXXX backwards compatibility
1046 # but this will blow up on first call - so maybe we should fail early?
1047 return obj
1048
1049
Michael Foord345266a2012-03-14 12:24:34 -07001050class CallableMixin(Base):
1051
1052 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
1053 wraps=None, name=None, spec_set=None, parent=None,
1054 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
1055 self.__dict__['_mock_return_value'] = return_value
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001056 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -07001057 spec, wraps, name, spec_set, parent,
1058 _spec_state, _new_name, _new_parent, **kwargs
1059 )
1060
1061 self.side_effect = side_effect
1062
1063
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001064 def _mock_check_sig(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001065 # stub method that can be replaced with one with a specific signature
1066 pass
1067
1068
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001069 def __call__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001070 # can't use self in-case a function / method we are mocking uses self
1071 # in the signature
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001072 self._mock_check_sig(*args, **kwargs)
Lisa Roach52bdd412019-09-27 15:44:34 -07001073 self._increment_mock_call(*args, **kwargs)
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001074 return self._mock_call(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001075
1076
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001077 def _mock_call(self, /, *args, **kwargs):
Lisa Roach52bdd412019-09-27 15:44:34 -07001078 return self._execute_mock_call(*args, **kwargs)
1079
1080 def _increment_mock_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001081 self.called = True
1082 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001083
Chris Withers8ca0fa92018-12-03 21:31:37 +00001084 # handle call_args
Lisa Roach52bdd412019-09-27 15:44:34 -07001085 # needs to be set here so assertions on call arguments pass before
1086 # execution in the case of awaited calls
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001087 _call = _Call((args, kwargs), two=True)
1088 self.call_args = _call
1089 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -07001090
Chris Withers8ca0fa92018-12-03 21:31:37 +00001091 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001092 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +00001093 method_call_name = self._mock_name
1094
1095 # initial stuff for mock_calls:
1096 mock_call_name = self._mock_new_name
1097 is_a_call = mock_call_name == '()'
1098 self.mock_calls.append(_Call(('', args, kwargs)))
1099
1100 # follow up the chain of mocks:
1101 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001102 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001103
Chris Withers8ca0fa92018-12-03 21:31:37 +00001104 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001105 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001106 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001107 do_method_calls = _new_parent._mock_parent is not None
1108 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001109 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001110
Chris Withers8ca0fa92018-12-03 21:31:37 +00001111 # handle mock_calls:
1112 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001113 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001114
1115 if _new_parent._mock_new_name:
1116 if is_a_call:
1117 dot = ''
1118 else:
1119 dot = '.'
1120 is_a_call = _new_parent._mock_new_name == '()'
1121 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1122
1123 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001124 _new_parent = _new_parent._mock_new_parent
1125
Lisa Roach52bdd412019-09-27 15:44:34 -07001126 def _execute_mock_call(self, /, *args, **kwargs):
1127 # seperate from _increment_mock_call so that awaited functions are
1128 # executed seperately from their call
1129
Michael Foord345266a2012-03-14 12:24:34 -07001130 effect = self.side_effect
1131 if effect is not None:
1132 if _is_exception(effect):
1133 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001134 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001135 result = next(effect)
1136 if _is_exception(result):
1137 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001138 else:
1139 result = effect(*args, **kwargs)
1140
1141 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001142 return result
Michael Foord345266a2012-03-14 12:24:34 -07001143
Mario Corcherof05df0a2018-12-08 11:25:02 +00001144 if self._mock_return_value is not DEFAULT:
1145 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001146
Mario Corcherof05df0a2018-12-08 11:25:02 +00001147 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001148 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001149
1150 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001151
1152
1153
1154class Mock(CallableMixin, NonCallableMock):
1155 """
1156 Create a new `Mock` object. `Mock` takes several optional arguments
1157 that specify the behaviour of the Mock object:
1158
1159 * `spec`: This can be either a list of strings or an existing object (a
1160 class or instance) that acts as the specification for the mock object. If
1161 you pass in an object then a list of strings is formed by calling dir on
1162 the object (excluding unsupported magic attributes and methods). Accessing
1163 any attribute not in this list will raise an `AttributeError`.
1164
1165 If `spec` is an object (rather than a list of strings) then
1166 `mock.__class__` returns the class of the spec object. This allows mocks
1167 to pass `isinstance` tests.
1168
1169 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1170 or get an attribute on the mock that isn't on the object passed as
1171 `spec_set` will raise an `AttributeError`.
1172
1173 * `side_effect`: A function to be called whenever the Mock is called. See
1174 the `side_effect` attribute. Useful for raising exceptions or
1175 dynamically changing return values. The function is called with the same
1176 arguments as the mock, and unless it returns `DEFAULT`, the return
1177 value of this function is used as the return value.
1178
Michael Foord2cd48732012-04-21 15:52:11 +01001179 If `side_effect` is an iterable then each call to the mock will return
1180 the next value from the iterable. If any of the members of the iterable
1181 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001182
Michael Foord345266a2012-03-14 12:24:34 -07001183 * `return_value`: The value returned when the mock is called. By default
1184 this is a new Mock (created on first access). See the
1185 `return_value` attribute.
1186
Michael Foord0682a0c2012-04-13 20:51:20 +01001187 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1188 calling the Mock will pass the call through to the wrapped object
1189 (returning the real result). Attribute access on the mock will return a
1190 Mock object that wraps the corresponding attribute of the wrapped object
1191 (so attempting to access an attribute that doesn't exist will raise an
1192 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001193
1194 If the mock has an explicit `return_value` set then calls are not passed
1195 to the wrapped object and the `return_value` is returned instead.
1196
1197 * `name`: If the mock has a name then it will be used in the repr of the
1198 mock. This can be useful for debugging. The name is propagated to child
1199 mocks.
1200
1201 Mocks can also be called with arbitrary keyword arguments. These will be
1202 used to set attributes on the mock after it is created.
1203 """
1204
1205
Michael Foord345266a2012-03-14 12:24:34 -07001206def _dot_lookup(thing, comp, import_path):
1207 try:
1208 return getattr(thing, comp)
1209 except AttributeError:
1210 __import__(import_path)
1211 return getattr(thing, comp)
1212
1213
1214def _importer(target):
1215 components = target.split('.')
1216 import_path = components.pop(0)
1217 thing = __import__(import_path)
1218
1219 for comp in components:
1220 import_path += ".%s" % comp
1221 thing = _dot_lookup(thing, comp, import_path)
1222 return thing
1223
1224
1225def _is_started(patcher):
1226 # XXXX horrible
1227 return hasattr(patcher, 'is_local')
1228
1229
1230class _patch(object):
1231
1232 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001233 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001234
1235 def __init__(
1236 self, getter, attribute, new, spec, create,
1237 spec_set, autospec, new_callable, kwargs
1238 ):
1239 if new_callable is not None:
1240 if new is not DEFAULT:
1241 raise ValueError(
1242 "Cannot use 'new' and 'new_callable' together"
1243 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001244 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001245 raise ValueError(
1246 "Cannot use 'autospec' and 'new_callable' together"
1247 )
1248
1249 self.getter = getter
1250 self.attribute = attribute
1251 self.new = new
1252 self.new_callable = new_callable
1253 self.spec = spec
1254 self.create = create
1255 self.has_local = False
1256 self.spec_set = spec_set
1257 self.autospec = autospec
1258 self.kwargs = kwargs
1259 self.additional_patchers = []
1260
1261
1262 def copy(self):
1263 patcher = _patch(
1264 self.getter, self.attribute, self.new, self.spec,
1265 self.create, self.spec_set,
1266 self.autospec, self.new_callable, self.kwargs
1267 )
1268 patcher.attribute_name = self.attribute_name
1269 patcher.additional_patchers = [
1270 p.copy() for p in self.additional_patchers
1271 ]
1272 return patcher
1273
1274
1275 def __call__(self, func):
1276 if isinstance(func, type):
1277 return self.decorate_class(func)
Xtreak436c2b02019-05-28 12:37:39 +05301278 if inspect.iscoroutinefunction(func):
1279 return self.decorate_async_callable(func)
Michael Foord345266a2012-03-14 12:24:34 -07001280 return self.decorate_callable(func)
1281
1282
1283 def decorate_class(self, klass):
1284 for attr in dir(klass):
1285 if not attr.startswith(patch.TEST_PREFIX):
1286 continue
1287
1288 attr_value = getattr(klass, attr)
1289 if not hasattr(attr_value, "__call__"):
1290 continue
1291
1292 patcher = self.copy()
1293 setattr(klass, attr, patcher(attr_value))
1294 return klass
1295
1296
Xtreak436c2b02019-05-28 12:37:39 +05301297 @contextlib.contextmanager
1298 def decoration_helper(self, patched, args, keywargs):
1299 extra_args = []
1300 entered_patchers = []
1301 patching = None
1302
1303 exc_info = tuple()
1304 try:
1305 for patching in patched.patchings:
1306 arg = patching.__enter__()
1307 entered_patchers.append(patching)
1308 if patching.attribute_name is not None:
1309 keywargs.update(arg)
1310 elif patching.new is DEFAULT:
1311 extra_args.append(arg)
1312
1313 args += tuple(extra_args)
1314 yield (args, keywargs)
1315 except:
1316 if (patching not in entered_patchers and
1317 _is_started(patching)):
1318 # the patcher may have been started, but an exception
1319 # raised whilst entering one of its additional_patchers
1320 entered_patchers.append(patching)
1321 # Pass the exception to __exit__
1322 exc_info = sys.exc_info()
1323 # re-raise the exception
1324 raise
1325 finally:
1326 for patching in reversed(entered_patchers):
1327 patching.__exit__(*exc_info)
1328
1329
Michael Foord345266a2012-03-14 12:24:34 -07001330 def decorate_callable(self, func):
Xtreak436c2b02019-05-28 12:37:39 +05301331 # NB. Keep the method in sync with decorate_async_callable()
Michael Foord345266a2012-03-14 12:24:34 -07001332 if hasattr(func, 'patchings'):
1333 func.patchings.append(self)
1334 return func
1335
1336 @wraps(func)
1337 def patched(*args, **keywargs):
Xtreak436c2b02019-05-28 12:37:39 +05301338 with self.decoration_helper(patched,
1339 args,
1340 keywargs) as (newargs, newkeywargs):
1341 return func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001342
Xtreak436c2b02019-05-28 12:37:39 +05301343 patched.patchings = [self]
1344 return patched
Michael Foord345266a2012-03-14 12:24:34 -07001345
Xtreak436c2b02019-05-28 12:37:39 +05301346
1347 def decorate_async_callable(self, func):
1348 # NB. Keep the method in sync with decorate_callable()
1349 if hasattr(func, 'patchings'):
1350 func.patchings.append(self)
1351 return func
1352
1353 @wraps(func)
1354 async def patched(*args, **keywargs):
1355 with self.decoration_helper(patched,
1356 args,
1357 keywargs) as (newargs, newkeywargs):
1358 return await func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001359
1360 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001361 return patched
1362
1363
1364 def get_original(self):
1365 target = self.getter()
1366 name = self.attribute
1367
1368 original = DEFAULT
1369 local = False
1370
1371 try:
1372 original = target.__dict__[name]
1373 except (AttributeError, KeyError):
1374 original = getattr(target, name, DEFAULT)
1375 else:
1376 local = True
1377
Michael Foordfddcfa22014-04-14 16:25:20 -04001378 if name in _builtins and isinstance(target, ModuleType):
1379 self.create = True
1380
Michael Foord345266a2012-03-14 12:24:34 -07001381 if not self.create and original is DEFAULT:
1382 raise AttributeError(
1383 "%s does not have the attribute %r" % (target, name)
1384 )
1385 return original, local
1386
1387
1388 def __enter__(self):
1389 """Perform the patch."""
1390 new, spec, spec_set = self.new, self.spec, self.spec_set
1391 autospec, kwargs = self.autospec, self.kwargs
1392 new_callable = self.new_callable
1393 self.target = self.getter()
1394
Michael Foord50a8c0e2012-03-25 18:57:58 +01001395 # normalise False to None
1396 if spec is False:
1397 spec = None
1398 if spec_set is False:
1399 spec_set = None
1400 if autospec is False:
1401 autospec = None
1402
1403 if spec is not None and autospec is not None:
1404 raise TypeError("Can't specify spec and autospec")
1405 if ((spec is not None or autospec is not None) and
1406 spec_set not in (True, None)):
1407 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1408
Michael Foord345266a2012-03-14 12:24:34 -07001409 original, local = self.get_original()
1410
Michael Foord50a8c0e2012-03-25 18:57:58 +01001411 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001412 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001413 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001414 # set spec to the object we are replacing
1415 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001416 if spec_set is True:
1417 spec_set = original
1418 spec = None
1419 elif spec is not None:
1420 if spec_set is True:
1421 spec_set = spec
1422 spec = None
1423 elif spec_set is True:
1424 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001425
Michael Foord50a8c0e2012-03-25 18:57:58 +01001426 if spec is not None or spec_set is not None:
1427 if original is DEFAULT:
1428 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001429 if isinstance(original, type):
1430 # If we're patching out a class and there is a spec
1431 inherit = True
Lisa Roach77b3b772019-05-20 09:19:53 -07001432 if spec is None and _is_async_obj(original):
1433 Klass = AsyncMock
1434 else:
1435 Klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -07001436 _kwargs = {}
1437 if new_callable is not None:
1438 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001439 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001440 this_spec = spec
1441 if spec_set is not None:
1442 this_spec = spec_set
1443 if _is_list(this_spec):
1444 not_callable = '__call__' not in this_spec
1445 else:
1446 not_callable = not callable(this_spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07001447 if _is_async_obj(this_spec):
1448 Klass = AsyncMock
1449 elif not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001450 Klass = NonCallableMagicMock
1451
1452 if spec is not None:
1453 _kwargs['spec'] = spec
1454 if spec_set is not None:
1455 _kwargs['spec_set'] = spec_set
1456
1457 # add a name to mocks
1458 if (isinstance(Klass, type) and
1459 issubclass(Klass, NonCallableMock) and self.attribute):
1460 _kwargs['name'] = self.attribute
1461
1462 _kwargs.update(kwargs)
1463 new = Klass(**_kwargs)
1464
1465 if inherit and _is_instance_mock(new):
1466 # we can only tell if the instance should be callable if the
1467 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001468 this_spec = spec
1469 if spec_set is not None:
1470 this_spec = spec_set
1471 if (not _is_list(this_spec) and not
1472 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001473 Klass = NonCallableMagicMock
1474
1475 _kwargs.pop('name')
1476 new.return_value = Klass(_new_parent=new, _new_name='()',
1477 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001478 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001479 # spec is ignored, new *must* be default, spec_set is treated
1480 # as a boolean. Should we check spec is not None and that spec_set
1481 # is a bool?
1482 if new is not DEFAULT:
1483 raise TypeError(
1484 "autospec creates the mock for you. Can't specify "
1485 "autospec and new."
1486 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001487 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001488 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001489 spec_set = bool(spec_set)
1490 if autospec is True:
1491 autospec = original
1492
1493 new = create_autospec(autospec, spec_set=spec_set,
1494 _name=self.attribute, **kwargs)
1495 elif kwargs:
1496 # can't set keyword args when we aren't creating the mock
1497 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1498 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1499
1500 new_attr = new
1501
1502 self.temp_original = original
1503 self.is_local = local
1504 setattr(self.target, self.attribute, new_attr)
1505 if self.attribute_name is not None:
1506 extra_args = {}
1507 if self.new is DEFAULT:
1508 extra_args[self.attribute_name] = new
1509 for patching in self.additional_patchers:
1510 arg = patching.__enter__()
1511 if patching.new is DEFAULT:
1512 extra_args.update(arg)
1513 return extra_args
1514
1515 return new
1516
1517
Michael Foord50a8c0e2012-03-25 18:57:58 +01001518 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001519 """Undo the patch."""
1520 if not _is_started(self):
Xtreak02b84cb2019-03-29 02:38:43 +05301521 return
Michael Foord345266a2012-03-14 12:24:34 -07001522
1523 if self.is_local and self.temp_original is not DEFAULT:
1524 setattr(self.target, self.attribute, self.temp_original)
1525 else:
1526 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001527 if not self.create and (not hasattr(self.target, self.attribute) or
1528 self.attribute in ('__doc__', '__module__',
1529 '__defaults__', '__annotations__',
1530 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001531 # needed for proxy objects like django settings
1532 setattr(self.target, self.attribute, self.temp_original)
1533
1534 del self.temp_original
1535 del self.is_local
1536 del self.target
1537 for patcher in reversed(self.additional_patchers):
1538 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001539 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001540
Michael Foordf7c41582012-06-10 20:36:32 +01001541
1542 def start(self):
1543 """Activate a patch, returning any created mock."""
1544 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001545 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001546 return result
1547
1548
1549 def stop(self):
1550 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001551 try:
1552 self._active_patches.remove(self)
1553 except ValueError:
1554 # If the patch hasn't been started this will fail
1555 pass
1556
Michael Foordf7c41582012-06-10 20:36:32 +01001557 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001558
1559
1560
1561def _get_target(target):
1562 try:
1563 target, attribute = target.rsplit('.', 1)
1564 except (TypeError, ValueError):
1565 raise TypeError("Need a valid target to patch. You supplied: %r" %
1566 (target,))
1567 getter = lambda: _importer(target)
1568 return getter, attribute
1569
1570
1571def _patch_object(
1572 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001573 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001574 new_callable=None, **kwargs
1575 ):
1576 """
Michael Foord345266a2012-03-14 12:24:34 -07001577 patch the named member (`attribute`) on an object (`target`) with a mock
1578 object.
1579
1580 `patch.object` can be used as a decorator, class decorator or a context
1581 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1582 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1583 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1584 the mock object it creates.
1585
1586 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1587 for choosing which methods to wrap.
1588 """
1589 getter = lambda: target
1590 return _patch(
1591 getter, attribute, new, spec, create,
1592 spec_set, autospec, new_callable, kwargs
1593 )
1594
1595
Michael Foord50a8c0e2012-03-25 18:57:58 +01001596def _patch_multiple(target, spec=None, create=False, spec_set=None,
1597 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001598 """Perform multiple patches in a single call. It takes the object to be
1599 patched (either as an object or a string to fetch the object by importing)
1600 and keyword arguments for the patches::
1601
1602 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1603 ...
1604
1605 Use `DEFAULT` as the value if you want `patch.multiple` to create
1606 mocks for you. In this case the created mocks are passed into a decorated
1607 function by keyword, and a dictionary is returned when `patch.multiple` is
1608 used as a context manager.
1609
1610 `patch.multiple` can be used as a decorator, class decorator or a context
1611 manager. The arguments `spec`, `spec_set`, `create`,
1612 `autospec` and `new_callable` have the same meaning as for `patch`. These
1613 arguments will be applied to *all* patches done by `patch.multiple`.
1614
1615 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1616 for choosing which methods to wrap.
1617 """
1618 if type(target) is str:
1619 getter = lambda: _importer(target)
1620 else:
1621 getter = lambda: target
1622
1623 if not kwargs:
1624 raise ValueError(
1625 'Must supply at least one keyword argument with patch.multiple'
1626 )
1627 # need to wrap in a list for python 3, where items is a view
1628 items = list(kwargs.items())
1629 attribute, new = items[0]
1630 patcher = _patch(
1631 getter, attribute, new, spec, create, spec_set,
1632 autospec, new_callable, {}
1633 )
1634 patcher.attribute_name = attribute
1635 for attribute, new in items[1:]:
1636 this_patcher = _patch(
1637 getter, attribute, new, spec, create, spec_set,
1638 autospec, new_callable, {}
1639 )
1640 this_patcher.attribute_name = attribute
1641 patcher.additional_patchers.append(this_patcher)
1642 return patcher
1643
1644
1645def patch(
1646 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001647 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001648 ):
1649 """
1650 `patch` acts as a function decorator, class decorator or a context
1651 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001652 is patched with a `new` object. When the function/with statement exits
1653 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001654
Miss Islington (bot)eaa1b092019-09-10 06:15:19 -07001655 If `new` is omitted, then the target is replaced with an
1656 `AsyncMock if the patched object is an async function or a
1657 `MagicMock` otherwise. If `patch` is used as a decorator and `new` is
Michael Foord54b3db82012-03-28 15:08:08 +01001658 omitted, the created mock is passed in as an extra argument to the
1659 decorated function. If `patch` is used as a context manager the created
1660 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001661
Michael Foord54b3db82012-03-28 15:08:08 +01001662 `target` should be a string in the form `'package.module.ClassName'`. The
1663 `target` is imported and the specified object replaced with the `new`
1664 object, so the `target` must be importable from the environment you are
1665 calling `patch` from. The target is imported when the decorated function
1666 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001667
1668 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1669 if patch is creating one for you.
1670
1671 In addition you can pass `spec=True` or `spec_set=True`, which causes
1672 patch to pass in the object being mocked as the spec/spec_set object.
1673
1674 `new_callable` allows you to specify a different class, or callable object,
Miss Islington (bot)eaa1b092019-09-10 06:15:19 -07001675 that will be called to create the `new` object. By default `AsyncMock` is
1676 used for async functions and `MagicMock` for the rest.
Michael Foord345266a2012-03-14 12:24:34 -07001677
1678 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001679 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001680 All attributes of the mock will also have the spec of the corresponding
1681 attribute of the object being replaced. Methods and functions being
1682 mocked will have their arguments checked and will raise a `TypeError` if
1683 they are called with the wrong signature. For mocks replacing a class,
1684 their return value (the 'instance') will have the same spec as the class.
1685
1686 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1687 arbitrary object as the spec instead of the one being replaced.
1688
1689 By default `patch` will fail to replace attributes that don't exist. If
1690 you pass in `create=True`, and the attribute doesn't exist, patch will
1691 create the attribute for you when the patched function is called, and
1692 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001693 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001694 default because it can be dangerous. With it switched on you can write
1695 passing tests against APIs that don't actually exist!
1696
1697 Patch can be used as a `TestCase` class decorator. It works by
1698 decorating each test method in the class. This reduces the boilerplate
1699 code when your test methods share a common patchings set. `patch` finds
1700 tests by looking for method names that start with `patch.TEST_PREFIX`.
1701 By default this is `test`, which matches the way `unittest` finds tests.
1702 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1703
1704 Patch can be used as a context manager, with the with statement. Here the
1705 patching applies to the indented block after the with statement. If you
1706 use "as" then the patched object will be bound to the name after the
1707 "as"; very useful if `patch` is creating a mock object for you.
1708
1709 `patch` takes arbitrary keyword arguments. These will be passed to
1710 the `Mock` (or `new_callable`) on construction.
1711
1712 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1713 available for alternate use-cases.
1714 """
1715 getter, attribute = _get_target(target)
1716 return _patch(
1717 getter, attribute, new, spec, create,
1718 spec_set, autospec, new_callable, kwargs
1719 )
1720
1721
1722class _patch_dict(object):
1723 """
1724 Patch a dictionary, or dictionary like object, and restore the dictionary
1725 to its original state after the test.
1726
1727 `in_dict` can be a dictionary or a mapping like container. If it is a
1728 mapping then it must at least support getting, setting and deleting items
1729 plus iterating over keys.
1730
1731 `in_dict` can also be a string specifying the name of the dictionary, which
1732 will then be fetched by importing it.
1733
1734 `values` can be a dictionary of values to set in the dictionary. `values`
1735 can also be an iterable of `(key, value)` pairs.
1736
1737 If `clear` is True then the dictionary will be cleared before the new
1738 values are set.
1739
1740 `patch.dict` can also be called with arbitrary keyword arguments to set
1741 values in the dictionary::
1742
1743 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1744 ...
1745
1746 `patch.dict` can be used as a context manager, decorator or class
1747 decorator. When used as a class decorator `patch.dict` honours
1748 `patch.TEST_PREFIX` for choosing which methods to wrap.
1749 """
1750
1751 def __init__(self, in_dict, values=(), clear=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001752 self.in_dict = in_dict
1753 # support any argument supported by dict(...) constructor
1754 self.values = dict(values)
1755 self.values.update(kwargs)
1756 self.clear = clear
1757 self._original = None
1758
1759
1760 def __call__(self, f):
1761 if isinstance(f, type):
1762 return self.decorate_class(f)
1763 @wraps(f)
1764 def _inner(*args, **kw):
1765 self._patch_dict()
1766 try:
1767 return f(*args, **kw)
1768 finally:
1769 self._unpatch_dict()
1770
1771 return _inner
1772
1773
1774 def decorate_class(self, klass):
1775 for attr in dir(klass):
1776 attr_value = getattr(klass, attr)
1777 if (attr.startswith(patch.TEST_PREFIX) and
1778 hasattr(attr_value, "__call__")):
1779 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1780 decorated = decorator(attr_value)
1781 setattr(klass, attr, decorated)
1782 return klass
1783
1784
1785 def __enter__(self):
1786 """Patch the dict."""
1787 self._patch_dict()
Mario Corchero04530812019-05-28 13:53:31 +01001788 return self.in_dict
Michael Foord345266a2012-03-14 12:24:34 -07001789
1790
1791 def _patch_dict(self):
1792 values = self.values
Xtreaka875ea52019-02-25 00:24:49 +05301793 if isinstance(self.in_dict, str):
1794 self.in_dict = _importer(self.in_dict)
Michael Foord345266a2012-03-14 12:24:34 -07001795 in_dict = self.in_dict
1796 clear = self.clear
1797
1798 try:
1799 original = in_dict.copy()
1800 except AttributeError:
1801 # dict like object with no copy method
1802 # must support iteration over keys
1803 original = {}
1804 for key in in_dict:
1805 original[key] = in_dict[key]
1806 self._original = original
1807
1808 if clear:
1809 _clear_dict(in_dict)
1810
1811 try:
1812 in_dict.update(values)
1813 except AttributeError:
1814 # dict like object with no update method
1815 for key in values:
1816 in_dict[key] = values[key]
1817
1818
1819 def _unpatch_dict(self):
1820 in_dict = self.in_dict
1821 original = self._original
1822
1823 _clear_dict(in_dict)
1824
1825 try:
1826 in_dict.update(original)
1827 except AttributeError:
1828 for key in original:
1829 in_dict[key] = original[key]
1830
1831
1832 def __exit__(self, *args):
1833 """Unpatch the dict."""
1834 self._unpatch_dict()
1835 return False
1836
1837 start = __enter__
1838 stop = __exit__
1839
1840
1841def _clear_dict(in_dict):
1842 try:
1843 in_dict.clear()
1844 except AttributeError:
1845 keys = list(in_dict)
1846 for key in keys:
1847 del in_dict[key]
1848
1849
Michael Foordf7c41582012-06-10 20:36:32 +01001850def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001851 """Stop all active patches. LIFO to unroll nested patches."""
1852 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001853 patch.stop()
1854
1855
Michael Foord345266a2012-03-14 12:24:34 -07001856patch.object = _patch_object
1857patch.dict = _patch_dict
1858patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001859patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001860patch.TEST_PREFIX = 'test'
1861
1862magic_methods = (
1863 "lt le gt ge eq ne "
1864 "getitem setitem delitem "
1865 "len contains iter "
1866 "hash str sizeof "
1867 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001868 # we added divmod and rdivmod here instead of numerics
1869 # because there is no idivmod
1870 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001871 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001872 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001873 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001874 "fspath "
Michael Foord345266a2012-03-14 12:24:34 -07001875)
1876
Michael Foordd2623d72014-04-14 11:23:48 -04001877numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001878 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001879)
Michael Foord345266a2012-03-14 12:24:34 -07001880inplace = ' '.join('i%s' % n for n in numerics.split())
1881right = ' '.join('r%s' % n for n in numerics.split())
1882
1883# not including __prepare__, __instancecheck__, __subclasscheck__
1884# (as they are metaclass methods)
1885# __del__ is not supported at all as it causes problems if it exists
1886
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001887_non_defaults = {
1888 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1889 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1890 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1891 '__repr__', '__dir__', '__subclasses__', '__format__',
Lisa Roach865bb682019-09-20 23:00:04 -07001892 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001893}
Michael Foord345266a2012-03-14 12:24:34 -07001894
1895
1896def _get_method(name, func):
1897 "Turns a callable object (like a mock) into a real function"
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001898 def method(self, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -07001899 return func(self, *args, **kw)
1900 method.__name__ = name
1901 return method
1902
1903
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001904_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001905 '__%s__' % method for method in
1906 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001907}
Michael Foord345266a2012-03-14 12:24:34 -07001908
Lisa Roach77b3b772019-05-20 09:19:53 -07001909# Magic methods used for async `with` statements
1910_async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
Lisa Roach865bb682019-09-20 23:00:04 -07001911# Magic methods that are only used with async calls but are synchronous functions themselves
1912_sync_async_magics = {"__aiter__"}
1913_async_magics = _async_method_magics | _sync_async_magics
Lisa Roach77b3b772019-05-20 09:19:53 -07001914
Lisa Roach865bb682019-09-20 23:00:04 -07001915_all_sync_magics = _magics | _non_defaults
1916_all_magics = _all_sync_magics | _async_magics
Michael Foord345266a2012-03-14 12:24:34 -07001917
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001918_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001919 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001920 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001921 '__instancecheck__', '__subclasscheck__',
1922 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001923}
Michael Foord345266a2012-03-14 12:24:34 -07001924
1925_calculate_return_value = {
1926 '__hash__': lambda self: object.__hash__(self),
1927 '__str__': lambda self: object.__str__(self),
1928 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001929 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001930}
1931
1932_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001933 '__lt__': NotImplemented,
1934 '__gt__': NotImplemented,
1935 '__le__': NotImplemented,
1936 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001937 '__int__': 1,
1938 '__contains__': False,
1939 '__len__': 0,
1940 '__exit__': False,
1941 '__complex__': 1j,
1942 '__float__': 1.0,
1943 '__bool__': True,
1944 '__index__': 1,
Lisa Roach77b3b772019-05-20 09:19:53 -07001945 '__aexit__': False,
Michael Foord345266a2012-03-14 12:24:34 -07001946}
1947
1948
1949def _get_eq(self):
1950 def __eq__(other):
1951 ret_val = self.__eq__._mock_return_value
1952 if ret_val is not DEFAULT:
1953 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001954 if self is other:
1955 return True
1956 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001957 return __eq__
1958
1959def _get_ne(self):
1960 def __ne__(other):
1961 if self.__ne__._mock_return_value is not DEFAULT:
1962 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001963 if self is other:
1964 return False
1965 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001966 return __ne__
1967
1968def _get_iter(self):
1969 def __iter__():
1970 ret_val = self.__iter__._mock_return_value
1971 if ret_val is DEFAULT:
1972 return iter([])
1973 # if ret_val was already an iterator, then calling iter on it should
1974 # return the iterator unchanged
1975 return iter(ret_val)
1976 return __iter__
1977
Lisa Roach77b3b772019-05-20 09:19:53 -07001978def _get_async_iter(self):
1979 def __aiter__():
1980 ret_val = self.__aiter__._mock_return_value
1981 if ret_val is DEFAULT:
1982 return _AsyncIterator(iter([]))
1983 return _AsyncIterator(iter(ret_val))
1984 return __aiter__
1985
Michael Foord345266a2012-03-14 12:24:34 -07001986_side_effect_methods = {
1987 '__eq__': _get_eq,
1988 '__ne__': _get_ne,
1989 '__iter__': _get_iter,
Lisa Roach77b3b772019-05-20 09:19:53 -07001990 '__aiter__': _get_async_iter
Michael Foord345266a2012-03-14 12:24:34 -07001991}
1992
1993
1994
1995def _set_return_value(mock, method, name):
1996 fixed = _return_values.get(name, DEFAULT)
1997 if fixed is not DEFAULT:
1998 method.return_value = fixed
1999 return
2000
Miss Islington (bot)cc8edfb2019-09-16 09:52:45 -07002001 return_calculator = _calculate_return_value.get(name)
2002 if return_calculator is not None:
2003 return_value = return_calculator(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002004 method.return_value = return_value
2005 return
2006
2007 side_effector = _side_effect_methods.get(name)
2008 if side_effector is not None:
2009 method.side_effect = side_effector(mock)
2010
2011
2012
2013class MagicMixin(object):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002014 def __init__(self, /, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07002015 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10002016 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07002017 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002018
2019
2020 def _mock_set_magics(self):
2021 these_magics = _magics
2022
Łukasz Langaa468db92015-04-13 23:12:42 -07002023 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07002024 these_magics = _magics.intersection(self._mock_methods)
2025
2026 remove_magics = set()
2027 remove_magics = _magics - these_magics
2028
2029 for entry in remove_magics:
2030 if entry in type(self).__dict__:
2031 # remove unneeded magic methods
2032 delattr(self, entry)
2033
2034 # don't overwrite existing attributes if called a second time
2035 these_magics = these_magics - set(type(self).__dict__)
2036
2037 _type = type(self)
2038 for entry in these_magics:
2039 setattr(_type, entry, MagicProxy(entry, self))
2040
2041
2042
2043class NonCallableMagicMock(MagicMixin, NonCallableMock):
2044 """A version of `MagicMock` that isn't callable."""
2045 def mock_add_spec(self, spec, spec_set=False):
2046 """Add a spec to a mock. `spec` can either be an object or a
2047 list of strings. Only attributes on the `spec` can be fetched as
2048 attributes from the mock.
2049
2050 If `spec_set` is True then only attributes on the spec can be set."""
2051 self._mock_add_spec(spec, spec_set)
2052 self._mock_set_magics()
2053
2054
Lisa Roach77b3b772019-05-20 09:19:53 -07002055class AsyncMagicMixin:
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002056 def __init__(self, /, *args, **kw):
Lisa Roach77b3b772019-05-20 09:19:53 -07002057 self._mock_set_async_magics() # make magic work for kwargs in init
2058 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)
2059 self._mock_set_async_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002060
Lisa Roach77b3b772019-05-20 09:19:53 -07002061 def _mock_set_async_magics(self):
2062 these_magics = _async_magics
2063
2064 if getattr(self, "_mock_methods", None) is not None:
2065 these_magics = _async_magics.intersection(self._mock_methods)
2066 remove_magics = _async_magics - these_magics
2067
2068 for entry in remove_magics:
2069 if entry in type(self).__dict__:
2070 # remove unneeded magic methods
2071 delattr(self, entry)
2072
2073 # don't overwrite existing attributes if called a second time
2074 these_magics = these_magics - set(type(self).__dict__)
2075
2076 _type = type(self)
2077 for entry in these_magics:
2078 setattr(_type, entry, MagicProxy(entry, self))
2079
2080
2081class MagicMock(MagicMixin, AsyncMagicMixin, Mock):
Michael Foord345266a2012-03-14 12:24:34 -07002082 """
2083 MagicMock is a subclass of Mock with default implementations
2084 of most of the magic methods. You can use MagicMock without having to
2085 configure the magic methods yourself.
2086
2087 If you use the `spec` or `spec_set` arguments then *only* magic
2088 methods that exist in the spec will be created.
2089
2090 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
2091 """
2092 def mock_add_spec(self, spec, spec_set=False):
2093 """Add a spec to a mock. `spec` can either be an object or a
2094 list of strings. Only attributes on the `spec` can be fetched as
2095 attributes from the mock.
2096
2097 If `spec_set` is True then only attributes on the spec can be set."""
2098 self._mock_add_spec(spec, spec_set)
2099 self._mock_set_magics()
2100
2101
2102
2103class MagicProxy(object):
2104 def __init__(self, name, parent):
2105 self.name = name
2106 self.parent = parent
2107
Michael Foord345266a2012-03-14 12:24:34 -07002108 def create_mock(self):
2109 entry = self.name
2110 parent = self.parent
2111 m = parent._get_child_mock(name=entry, _new_name=entry,
2112 _new_parent=parent)
2113 setattr(parent, entry, m)
2114 _set_return_value(parent, m, entry)
2115 return m
2116
2117 def __get__(self, obj, _type=None):
2118 return self.create_mock()
2119
2120
Lisa Roach77b3b772019-05-20 09:19:53 -07002121class AsyncMockMixin(Base):
2122 awaited = _delegating_property('awaited')
2123 await_count = _delegating_property('await_count')
2124 await_args = _delegating_property('await_args')
2125 await_args_list = _delegating_property('await_args_list')
2126
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002127 def __init__(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002128 super().__init__(*args, **kwargs)
2129 # asyncio.iscoroutinefunction() checks _is_coroutine property to say if an
2130 # object is a coroutine. Without this check it looks to see if it is a
2131 # function/method, which in this case it is not (since it is an
2132 # AsyncMock).
2133 # It is set through __dict__ because when spec_set is True, this
2134 # attribute is likely undefined.
2135 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
2136 self.__dict__['_mock_awaited'] = _AwaitEvent(self)
2137 self.__dict__['_mock_await_count'] = 0
2138 self.__dict__['_mock_await_args'] = None
2139 self.__dict__['_mock_await_args_list'] = _CallList()
2140 code_mock = NonCallableMock(spec_set=CodeType)
2141 code_mock.co_flags = inspect.CO_COROUTINE
2142 self.__dict__['__code__'] = code_mock
2143
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002144 async def _mock_call(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002145 try:
2146 result = super()._mock_call(*args, **kwargs)
2147 except (BaseException, StopIteration) as e:
2148 side_effect = self.side_effect
2149 if side_effect is not None and not callable(side_effect):
2150 raise
2151 return await _raise(e)
2152
2153 _call = self.call_args
2154
2155 async def proxy():
2156 try:
2157 if inspect.isawaitable(result):
2158 return await result
2159 else:
2160 return result
2161 finally:
2162 self.await_count += 1
2163 self.await_args = _call
2164 self.await_args_list.append(_call)
2165 await self.awaited._notify()
2166
2167 return await proxy()
2168
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002169 def assert_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002170 """
2171 Assert that the mock was awaited at least once.
2172 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002173 if self.await_count == 0:
2174 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2175 raise AssertionError(msg)
2176
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002177 def assert_awaited_once(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002178 """
2179 Assert that the mock was awaited exactly once.
2180 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002181 if not self.await_count == 1:
2182 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2183 f" Awaited {self.await_count} times.")
2184 raise AssertionError(msg)
2185
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002186 def assert_awaited_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002187 """
2188 Assert that the last await was with the specified arguments.
2189 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002190 if self.await_args is None:
2191 expected = self._format_mock_call_signature(args, kwargs)
2192 raise AssertionError(f'Expected await: {expected}\nNot awaited')
2193
2194 def _error_message():
Xtreak0ae022c2019-05-29 12:32:26 +05302195 msg = self._format_mock_failure_message(args, kwargs, action='await')
Lisa Roach77b3b772019-05-20 09:19:53 -07002196 return msg
2197
2198 expected = self._call_matcher((args, kwargs))
2199 actual = self._call_matcher(self.await_args)
2200 if expected != actual:
2201 cause = expected if isinstance(expected, Exception) else None
2202 raise AssertionError(_error_message()) from cause
2203
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002204 def assert_awaited_once_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002205 """
2206 Assert that the mock was awaited exactly once and with the specified
2207 arguments.
2208 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002209 if not self.await_count == 1:
2210 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2211 f" Awaited {self.await_count} times.")
2212 raise AssertionError(msg)
2213 return self.assert_awaited_with(*args, **kwargs)
2214
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002215 def assert_any_await(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002216 """
2217 Assert the mock has ever been awaited with the specified arguments.
2218 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002219 expected = self._call_matcher((args, kwargs))
2220 actual = [self._call_matcher(c) for c in self.await_args_list]
2221 if expected not in actual:
2222 cause = expected if isinstance(expected, Exception) else None
2223 expected_string = self._format_mock_call_signature(args, kwargs)
2224 raise AssertionError(
2225 '%s await not found' % expected_string
2226 ) from cause
2227
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002228 def assert_has_awaits(self, calls, any_order=False):
Lisa Roach77b3b772019-05-20 09:19:53 -07002229 """
2230 Assert the mock has been awaited with the specified calls.
2231 The :attr:`await_args_list` list is checked for the awaits.
2232
2233 If `any_order` is False (the default) then the awaits must be
2234 sequential. There can be extra calls before or after the
2235 specified awaits.
2236
2237 If `any_order` is True then the awaits can be in any order, but
2238 they must all appear in :attr:`await_args_list`.
2239 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002240 expected = [self._call_matcher(c) for c in calls]
Miss Islington (bot)1a17a052019-09-24 17:29:17 -07002241 cause = next((e for e in expected if isinstance(e, Exception)), None)
Lisa Roach77b3b772019-05-20 09:19:53 -07002242 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2243 if not any_order:
2244 if expected not in all_awaits:
Miss Islington (bot)1a17a052019-09-24 17:29:17 -07002245 if cause is None:
2246 problem = 'Awaits not found.'
2247 else:
2248 problem = ('Error processing expected awaits.\n'
2249 'Errors: {}').format(
2250 [e if isinstance(e, Exception) else None
2251 for e in expected])
Lisa Roach77b3b772019-05-20 09:19:53 -07002252 raise AssertionError(
Miss Islington (bot)1a17a052019-09-24 17:29:17 -07002253 f'{problem}\n'
2254 f'Expected: {_CallList(calls)}\n'
Lisa Roach77b3b772019-05-20 09:19:53 -07002255 f'Actual: {self.await_args_list}'
2256 ) from cause
2257 return
2258
2259 all_awaits = list(all_awaits)
2260
2261 not_found = []
2262 for kall in expected:
2263 try:
2264 all_awaits.remove(kall)
2265 except ValueError:
2266 not_found.append(kall)
2267 if not_found:
2268 raise AssertionError(
2269 '%r not all found in await list' % (tuple(not_found),)
2270 ) from cause
2271
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002272 def assert_not_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002273 """
2274 Assert that the mock was never awaited.
2275 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002276 if self.await_count != 0:
Xtreakff6b2e62019-05-27 18:26:23 +05302277 msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
Lisa Roach77b3b772019-05-20 09:19:53 -07002278 f" Awaited {self.await_count} times.")
2279 raise AssertionError(msg)
2280
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002281 def reset_mock(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002282 """
2283 See :func:`.Mock.reset_mock()`
2284 """
2285 super().reset_mock(*args, **kwargs)
2286 self.await_count = 0
2287 self.await_args = None
2288 self.await_args_list = _CallList()
2289
2290
2291class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2292 """
2293 Enhance :class:`Mock` with features allowing to mock
2294 an async function.
2295
2296 The :class:`AsyncMock` object will behave so the object is
2297 recognized as an async function, and the result of a call is an awaitable:
2298
2299 >>> mock = AsyncMock()
2300 >>> asyncio.iscoroutinefunction(mock)
2301 True
2302 >>> inspect.isawaitable(mock())
2303 True
2304
2305
2306 The result of ``mock()`` is an async function which will have the outcome
2307 of ``side_effect`` or ``return_value``:
2308
2309 - if ``side_effect`` is a function, the async function will return the
2310 result of that function,
2311 - if ``side_effect`` is an exception, the async function will raise the
2312 exception,
2313 - if ``side_effect`` is an iterable, the async function will return the
2314 next value of the iterable, however, if the sequence of result is
2315 exhausted, ``StopIteration`` is raised immediately,
2316 - if ``side_effect`` is not defined, the async function will return the
2317 value defined by ``return_value``, hence, by default, the async function
2318 returns a new :class:`AsyncMock` object.
2319
2320 If the outcome of ``side_effect`` or ``return_value`` is an async function,
2321 the mock async function obtained when the mock object is called will be this
2322 async function itself (and not an async function returning an async
2323 function).
2324
2325 The test author can also specify a wrapped object with ``wraps``. In this
2326 case, the :class:`Mock` object behavior is the same as with an
2327 :class:`.Mock` object: the wrapped object may have methods
2328 defined as async function functions.
2329
Xtreake7cb23b2019-05-21 14:17:17 +05302330 Based on Martin Richard's asynctest project.
Lisa Roach77b3b772019-05-20 09:19:53 -07002331 """
2332
Michael Foord345266a2012-03-14 12:24:34 -07002333
2334class _ANY(object):
2335 "A helper object that compares equal to everything."
2336
2337 def __eq__(self, other):
2338 return True
2339
2340 def __ne__(self, other):
2341 return False
2342
2343 def __repr__(self):
2344 return '<ANY>'
2345
2346ANY = _ANY()
2347
2348
2349
2350def _format_call_signature(name, args, kwargs):
2351 message = '%s(%%s)' % name
2352 formatted_args = ''
2353 args_string = ', '.join([repr(arg) for arg in args])
2354 kwargs_string = ', '.join([
Miss Islington (bot)bee8bfe2019-09-09 04:42:43 -07002355 '%s=%r' % (key, value) for key, value in kwargs.items()
Michael Foord345266a2012-03-14 12:24:34 -07002356 ])
2357 if args_string:
2358 formatted_args = args_string
2359 if kwargs_string:
2360 if formatted_args:
2361 formatted_args += ', '
2362 formatted_args += kwargs_string
2363
2364 return message % formatted_args
2365
2366
2367
2368class _Call(tuple):
2369 """
2370 A tuple for holding the results of a call to a mock, either in the form
2371 `(args, kwargs)` or `(name, args, kwargs)`.
2372
2373 If args or kwargs are empty then a call tuple will compare equal to
2374 a tuple without those values. This makes comparisons less verbose::
2375
2376 _Call(('name', (), {})) == ('name',)
2377 _Call(('name', (1,), {})) == ('name', (1,))
2378 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2379
2380 The `_Call` object provides a useful shortcut for comparing with call::
2381
2382 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2383 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2384
2385 If the _Call has no name then it will match any name.
2386 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002387 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002388 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002389 args = ()
2390 kwargs = {}
2391 _len = len(value)
2392 if _len == 3:
2393 name, args, kwargs = value
2394 elif _len == 2:
2395 first, second = value
2396 if isinstance(first, str):
2397 name = first
2398 if isinstance(second, tuple):
2399 args = second
2400 else:
2401 kwargs = second
2402 else:
2403 args, kwargs = first, second
2404 elif _len == 1:
2405 value, = value
2406 if isinstance(value, str):
2407 name = value
2408 elif isinstance(value, tuple):
2409 args = value
2410 else:
2411 kwargs = value
2412
2413 if two:
2414 return tuple.__new__(cls, (args, kwargs))
2415
2416 return tuple.__new__(cls, (name, args, kwargs))
2417
2418
2419 def __init__(self, value=(), name=None, parent=None, two=False,
2420 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002421 self._mock_name = name
2422 self._mock_parent = parent
2423 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002424
2425
2426 def __eq__(self, other):
2427 if other is ANY:
2428 return True
2429 try:
2430 len_other = len(other)
2431 except TypeError:
2432 return False
2433
2434 self_name = ''
2435 if len(self) == 2:
2436 self_args, self_kwargs = self
2437 else:
2438 self_name, self_args, self_kwargs = self
2439
Andrew Dunaie63e6172018-12-04 11:08:45 +02002440 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2441 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002442 return False
2443
Michael Foord345266a2012-03-14 12:24:34 -07002444 other_name = ''
2445 if len_other == 0:
2446 other_args, other_kwargs = (), {}
2447 elif len_other == 3:
2448 other_name, other_args, other_kwargs = other
2449 elif len_other == 1:
2450 value, = other
2451 if isinstance(value, tuple):
2452 other_args = value
2453 other_kwargs = {}
2454 elif isinstance(value, str):
2455 other_name = value
2456 other_args, other_kwargs = (), {}
2457 else:
2458 other_args = ()
2459 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002460 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002461 # could be (name, args) or (name, kwargs) or (args, kwargs)
2462 first, second = other
2463 if isinstance(first, str):
2464 other_name = first
2465 if isinstance(second, tuple):
2466 other_args, other_kwargs = second, {}
2467 else:
2468 other_args, other_kwargs = (), second
2469 else:
2470 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002471 else:
2472 return False
Michael Foord345266a2012-03-14 12:24:34 -07002473
2474 if self_name and other_name != self_name:
2475 return False
2476
2477 # this order is important for ANY to work!
2478 return (other_args, other_kwargs) == (self_args, self_kwargs)
2479
2480
Berker Peksagce913872016-03-28 00:30:02 +03002481 __ne__ = object.__ne__
2482
2483
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002484 def __call__(self, /, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002485 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002486 return _Call(('', args, kwargs), name='()')
2487
Andrew Dunaie63e6172018-12-04 11:08:45 +02002488 name = self._mock_name + '()'
2489 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002490
2491
2492 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002493 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002494 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002495 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002496 return _Call(name=name, parent=self, from_kall=False)
2497
2498
Miss Islington (bot)db0d8a52019-09-12 03:52:49 -07002499 def __getattribute__(self, attr):
2500 if attr in tuple.__dict__:
2501 raise AttributeError
2502 return tuple.__getattribute__(self, attr)
2503
2504
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002505 def count(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302506 return self.__getattr__('count')(*args, **kwargs)
2507
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002508 def index(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302509 return self.__getattr__('index')(*args, **kwargs)
2510
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302511 def _get_call_arguments(self):
2512 if len(self) == 2:
2513 args, kwargs = self
2514 else:
2515 name, args, kwargs = self
2516
2517 return args, kwargs
2518
2519 @property
2520 def args(self):
2521 return self._get_call_arguments()[0]
2522
2523 @property
2524 def kwargs(self):
2525 return self._get_call_arguments()[1]
2526
Michael Foord345266a2012-03-14 12:24:34 -07002527 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002528 if not self._mock_from_kall:
2529 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002530 if name.startswith('()'):
2531 name = 'call%s' % name
2532 return name
2533
2534 if len(self) == 2:
2535 name = 'call'
2536 args, kwargs = self
2537 else:
2538 name, args, kwargs = self
2539 if not name:
2540 name = 'call'
2541 elif not name.startswith('()'):
2542 name = 'call.%s' % name
2543 else:
2544 name = 'call%s' % name
2545 return _format_call_signature(name, args, kwargs)
2546
2547
2548 def call_list(self):
2549 """For a call object that represents multiple calls, `call_list`
2550 returns a list of all the intermediate calls as well as the
2551 final call."""
2552 vals = []
2553 thing = self
2554 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002555 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002556 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002557 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002558 return _CallList(reversed(vals))
2559
2560
2561call = _Call(from_kall=False)
2562
2563
Michael Foord345266a2012-03-14 12:24:34 -07002564def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2565 _name=None, **kwargs):
2566 """Create a mock object using another object as a spec. Attributes on the
2567 mock will use the corresponding attribute on the `spec` object as their
2568 spec.
2569
2570 Functions or methods being mocked will have their arguments checked
2571 to check that they are called with the correct signature.
2572
2573 If `spec_set` is True then attempting to set attributes that don't exist
2574 on the spec object will raise an `AttributeError`.
2575
2576 If a class is used as a spec then the return value of the mock (the
2577 instance of the class) will have the same spec. You can use a class as the
2578 spec for an instance object by passing `instance=True`. The returned mock
2579 will only be callable if instances of the mock are callable.
2580
2581 `create_autospec` also takes arbitrary keyword arguments that are passed to
2582 the constructor of the created mock."""
2583 if _is_list(spec):
2584 # can't pass a list instance to the mock constructor as it will be
2585 # interpreted as a list of strings
2586 spec = type(spec)
2587
2588 is_type = isinstance(spec, type)
Xtreakff6b2e62019-05-27 18:26:23 +05302589 is_async_func = _is_async_func(spec)
Michael Foord345266a2012-03-14 12:24:34 -07002590 _kwargs = {'spec': spec}
2591 if spec_set:
2592 _kwargs = {'spec_set': spec}
2593 elif spec is None:
2594 # None we mock with a normal mock without a spec
2595 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002596 if _kwargs and instance:
2597 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002598
2599 _kwargs.update(kwargs)
2600
2601 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002602 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002603 # descriptors don't have a spec
2604 # because we don't know what type they return
2605 _kwargs = {}
Lisa Roach77b3b772019-05-20 09:19:53 -07002606 elif is_async_func:
2607 if instance:
2608 raise RuntimeError("Instance can not be True when create_autospec "
2609 "is mocking an async function")
2610 Klass = AsyncMock
Michael Foord345266a2012-03-14 12:24:34 -07002611 elif not _callable(spec):
2612 Klass = NonCallableMagicMock
2613 elif is_type and instance and not _instance_callable(spec):
2614 Klass = NonCallableMagicMock
2615
Kushal Das484f8a82014-04-16 01:05:50 +05302616 _name = _kwargs.pop('name', _name)
2617
Michael Foord345266a2012-03-14 12:24:34 -07002618 _new_name = _name
2619 if _parent is None:
2620 # for a top level object no _new_name should be set
2621 _new_name = ''
2622
2623 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2624 name=_name, **_kwargs)
2625
2626 if isinstance(spec, FunctionTypes):
2627 # should only happen at the top level because we don't
2628 # recurse for functions
2629 mock = _set_signature(mock, spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07002630 if is_async_func:
Xtreakff6b2e62019-05-27 18:26:23 +05302631 _setup_async_mock(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002632 else:
2633 _check_signature(spec, mock, is_type, instance)
2634
2635 if _parent is not None and not instance:
2636 _parent._mock_children[_name] = mock
2637
2638 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002639 mock.return_value = create_autospec(spec, spec_set, instance=True,
2640 _name='()', _parent=mock)
2641
2642 for entry in dir(spec):
2643 if _is_magic(entry):
2644 # MagicMock already does the useful magic methods for us
2645 continue
2646
Michael Foord345266a2012-03-14 12:24:34 -07002647 # XXXX do we need a better way of getting attributes without
2648 # triggering code execution (?) Probably not - we need the actual
2649 # object to mock it so we would rather trigger a property than mock
2650 # the property descriptor. Likewise we want to mock out dynamically
2651 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002652 # XXXX what about attributes that raise exceptions other than
2653 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002654 # we could be resilient against it, or catch and propagate the
2655 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002656 try:
2657 original = getattr(spec, entry)
2658 except AttributeError:
2659 continue
Michael Foord345266a2012-03-14 12:24:34 -07002660
2661 kwargs = {'spec': original}
2662 if spec_set:
2663 kwargs = {'spec_set': original}
2664
2665 if not isinstance(original, FunctionTypes):
2666 new = _SpecState(original, spec_set, mock, entry, instance)
2667 mock._mock_children[entry] = new
2668 else:
2669 parent = mock
2670 if isinstance(spec, FunctionTypes):
2671 parent = mock.mock
2672
Michael Foord345266a2012-03-14 12:24:34 -07002673 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002674 kwargs['_eat_self'] = skipfirst
Lisa Roach77b3b772019-05-20 09:19:53 -07002675 if asyncio.iscoroutinefunction(original):
2676 child_klass = AsyncMock
2677 else:
2678 child_klass = MagicMock
2679 new = child_klass(parent=parent, name=entry, _new_name=entry,
2680 _new_parent=parent,
2681 **kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002682 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002683 _check_signature(original, new, skipfirst=skipfirst)
2684
2685 # so functions created with _set_signature become instance attributes,
2686 # *plus* their underlying mock exists in _mock_children of the parent
2687 # mock. Adding to _mock_children may be unnecessary where we are also
2688 # setting as an instance attribute?
2689 if isinstance(new, FunctionTypes):
2690 setattr(mock, entry, new)
2691
2692 return mock
2693
2694
2695def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002696 """
2697 Return whether we should skip the first argument on spec's `entry`
2698 attribute.
2699 """
Michael Foord345266a2012-03-14 12:24:34 -07002700 if not isinstance(spec, type):
2701 if entry in getattr(spec, '__dict__', {}):
2702 # instance attribute - shouldn't skip
2703 return False
Michael Foord345266a2012-03-14 12:24:34 -07002704 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002705
2706 for klass in spec.__mro__:
2707 result = klass.__dict__.get(entry, DEFAULT)
2708 if result is DEFAULT:
2709 continue
2710 if isinstance(result, (staticmethod, classmethod)):
2711 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002712 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2713 # Normal method => skip if looked up on type
2714 # (if looked up on instance, self is already skipped)
2715 return is_type
2716 else:
2717 return False
Michael Foord345266a2012-03-14 12:24:34 -07002718
Chris Withersadbf1782019-05-01 23:04:04 +01002719 # function is a dynamically provided attribute
Michael Foord345266a2012-03-14 12:24:34 -07002720 return is_type
2721
2722
Michael Foord345266a2012-03-14 12:24:34 -07002723class _SpecState(object):
2724
2725 def __init__(self, spec, spec_set=False, parent=None,
2726 name=None, ids=None, instance=False):
2727 self.spec = spec
2728 self.ids = ids
2729 self.spec_set = spec_set
2730 self.parent = parent
2731 self.instance = instance
2732 self.name = name
2733
2734
2735FunctionTypes = (
2736 # python function
2737 type(create_autospec),
2738 # instance method
2739 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002740)
2741
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002742MethodWrapperTypes = (
2743 type(ANY.__eq__.__get__),
2744)
2745
Michael Foord345266a2012-03-14 12:24:34 -07002746
Michael Foorda74561a2012-03-25 19:03:13 +01002747file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002748
Michael Foord04cbe0c2013-03-19 17:22:51 -07002749
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002750def _to_stream(read_data):
2751 if isinstance(read_data, bytes):
2752 return io.BytesIO(read_data)
Michael Foord04cbe0c2013-03-19 17:22:51 -07002753 else:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002754 return io.StringIO(read_data)
Michael Foord0dccf652012-03-25 19:11:50 +01002755
Robert Collins5329aaa2015-07-17 20:08:45 +12002756
Michael Foord0dccf652012-03-25 19:11:50 +01002757def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002758 """
2759 A helper function to create a mock to replace the use of `open`. It works
2760 for `open` called directly or used as a context manager.
2761
2762 The `mock` argument is the mock object to configure. If `None` (the
2763 default) then a `MagicMock` will be created for you, with the API limited
2764 to methods or attributes available on standard file handles.
2765
Xtreak71f82a22018-12-20 21:30:21 +05302766 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002767 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002768 """
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002769 _read_data = _to_stream(read_data)
2770 _state = [_read_data, None]
2771
Robert Collinsca647ef2015-07-24 03:48:20 +12002772 def _readlines_side_effect(*args, **kwargs):
2773 if handle.readlines.return_value is not None:
2774 return handle.readlines.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002775 return _state[0].readlines(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002776
2777 def _read_side_effect(*args, **kwargs):
2778 if handle.read.return_value is not None:
2779 return handle.read.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002780 return _state[0].read(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002781
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002782 def _readline_side_effect(*args, **kwargs):
Tony Flury20870232018-09-12 23:21:16 +01002783 yield from _iter_side_effect()
2784 while True:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002785 yield _state[0].readline(*args, **kwargs)
Tony Flury20870232018-09-12 23:21:16 +01002786
2787 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002788 if handle.readline.return_value is not None:
2789 while True:
2790 yield handle.readline.return_value
2791 for line in _state[0]:
2792 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002793
Damien Nadé394119a2019-05-23 12:03:25 +02002794 def _next_side_effect():
2795 if handle.readline.return_value is not None:
2796 return handle.readline.return_value
2797 return next(_state[0])
2798
Michael Foorda74561a2012-03-25 19:03:13 +01002799 global file_spec
2800 if file_spec is None:
2801 import _io
2802 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2803
Michael Foord345266a2012-03-14 12:24:34 -07002804 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002805 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002806
Robert Collinsca647ef2015-07-24 03:48:20 +12002807 handle = MagicMock(spec=file_spec)
2808 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002809
Robert Collinsca647ef2015-07-24 03:48:20 +12002810 handle.write.return_value = None
2811 handle.read.return_value = None
2812 handle.readline.return_value = None
2813 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002814
Robert Collinsca647ef2015-07-24 03:48:20 +12002815 handle.read.side_effect = _read_side_effect
2816 _state[1] = _readline_side_effect()
2817 handle.readline.side_effect = _state[1]
2818 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002819 handle.__iter__.side_effect = _iter_side_effect
Damien Nadé394119a2019-05-23 12:03:25 +02002820 handle.__next__.side_effect = _next_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002821
Robert Collinsca647ef2015-07-24 03:48:20 +12002822 def reset_data(*args, **kwargs):
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002823 _state[0] = _to_stream(read_data)
Robert Collinsca647ef2015-07-24 03:48:20 +12002824 if handle.readline.side_effect == _state[1]:
2825 # Only reset the side effect if the user hasn't overridden it.
2826 _state[1] = _readline_side_effect()
2827 handle.readline.side_effect = _state[1]
2828 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002829
Robert Collinsca647ef2015-07-24 03:48:20 +12002830 mock.side_effect = reset_data
2831 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002832 return mock
2833
2834
2835class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002836 """
2837 A mock intended to be used as a property, or other descriptor, on a class.
2838 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2839 a return value when it is fetched.
2840
2841 Fetching a `PropertyMock` instance from an object calls the mock, with
2842 no args. Setting it calls the mock with the value being set.
2843 """
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002844 def _get_child_mock(self, /, **kwargs):
Michael Foordc2870622012-04-13 16:57:22 +01002845 return MagicMock(**kwargs)
2846
Miss Islington (bot)c71ae1a2019-08-29 02:02:51 -07002847 def __get__(self, obj, obj_type=None):
Michael Foord345266a2012-03-14 12:24:34 -07002848 return self()
2849 def __set__(self, obj, val):
2850 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002851
2852
2853def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002854 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002855
2856 Given an input Mock, seals it to ensure no further mocks will be generated
2857 when accessing an attribute that was not already defined.
2858
Mario Corchero96200eb2018-10-19 22:57:37 +01002859 The operation recursively seals the mock passed in, meaning that
2860 the mock itself, any mocks generated by accessing one of its attributes,
2861 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002862 """
2863 mock._mock_sealed = True
2864 for attr in dir(mock):
2865 try:
2866 m = getattr(mock, attr)
2867 except AttributeError:
2868 continue
2869 if not isinstance(m, NonCallableMock):
2870 continue
2871 if m._mock_new_parent is mock:
2872 seal(m)
Lisa Roach77b3b772019-05-20 09:19:53 -07002873
2874
2875async def _raise(exception):
2876 raise exception
2877
2878
2879class _AsyncIterator:
2880 """
2881 Wraps an iterator in an asynchronous iterator.
2882 """
2883 def __init__(self, iterator):
2884 self.iterator = iterator
2885 code_mock = NonCallableMock(spec_set=CodeType)
2886 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
2887 self.__dict__['__code__'] = code_mock
2888
2889 def __aiter__(self):
2890 return self
2891
2892 async def __anext__(self):
2893 try:
2894 return next(self.iterator)
2895 except StopIteration:
2896 pass
2897 raise StopAsyncIteration
2898
2899
2900class _AwaitEvent:
2901 def __init__(self, mock):
2902 self._mock = mock
2903 self._condition = None
2904
2905 async def _notify(self):
2906 condition = self._get_condition()
2907 try:
2908 await condition.acquire()
2909 condition.notify_all()
2910 finally:
2911 condition.release()
2912
2913 def _get_condition(self):
2914 """
2915 Creation of condition is delayed, to minimize the chance of using the
2916 wrong loop.
2917 A user may create a mock with _AwaitEvent before selecting the
2918 execution loop. Requiring a user to delay creation is error-prone and
2919 inflexible. Instead, condition is created when user actually starts to
2920 use the mock.
2921 """
2922 # No synchronization is needed:
2923 # - asyncio is thread unsafe
2924 # - there are no awaits here, method will be executed without
2925 # switching asyncio context.
2926 if self._condition is None:
2927 self._condition = asyncio.Condition()
2928
2929 return self._condition