blob: c6067151de14fee25b7962178f3d7d88256ff24d [file] [log] [blame]
Michael Foord345266a2012-03-14 12:24:34 -07001# mock.py
2# Test tools for mocking and patching.
Michael Foordc17adf42012-03-14 13:30:29 -07003# Maintained by Michael Foord
4# Backport for other versions of Python available from
Ned Deily9d6d06e2018-06-11 00:45:50 -04005# https://pypi.org/project/mock
Michael Foord345266a2012-03-14 12:24:34 -07006
7__all__ = (
8 'Mock',
9 'MagicMock',
10 'patch',
11 'sentinel',
12 'DEFAULT',
13 'ANY',
14 'call',
15 'create_autospec',
Lisa Roach77b3b772019-05-20 09:19:53 -070016 'AsyncMock',
Michael Foord345266a2012-03-14 12:24:34 -070017 'FILTER_DIR',
18 'NonCallableMock',
19 'NonCallableMagicMock',
20 'mock_open',
21 'PropertyMock',
Mario Corchero552be9d2017-10-17 12:35:11 +010022 'seal',
Michael Foord345266a2012-03-14 12:24:34 -070023)
24
25
Lisa Roach77b3b772019-05-20 09:19:53 -070026import asyncio
Xtreak436c2b02019-05-28 12:37:39 +053027import contextlib
Rémi Lapeyre11a88322019-05-07 12:48:36 +020028import io
Michael Foord345266a2012-03-14 12:24:34 -070029import inspect
30import pprint
31import sys
Michael Foordfddcfa22014-04-14 16:25:20 -040032import builtins
Chris Withersc7dd3c72020-01-27 14:11:19 +000033from asyncio import iscoroutinefunction
Lisa Roach77b3b772019-05-20 09:19:53 -070034from types import CodeType, ModuleType, MethodType
Petter Strandmark47d94242018-10-28 21:37:10 +010035from unittest.util import safe_repr
Antoine Pitrou5c64df72013-02-03 00:23:58 +010036from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070037
38
Matthew Suozzodccdc502021-04-09 23:45:50 -040039class InvalidSpecError(Exception):
40 """Indicates that an invalid value was used as a mock spec."""
41
42
Michael Foordfddcfa22014-04-14 16:25:20 -040043_builtins = {name for name in dir(builtins) if not name.startswith('_')}
44
Michael Foord345266a2012-03-14 12:24:34 -070045FILTER_DIR = True
46
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100047# Workaround for issue #12370
48# Without this, the __class__ properties wouldn't be set correctly
49_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070050
Lisa Roach77b3b772019-05-20 09:19:53 -070051def _is_async_obj(obj):
Lisa Roachf1a297a2019-09-10 12:18:40 +010052 if _is_instance_mock(obj) and not isinstance(obj, AsyncMock):
Lisa Roach77b3b772019-05-20 09:19:53 -070053 return False
Matthew Kokotovich62865f42020-01-25 04:17:47 -060054 if hasattr(obj, '__func__'):
55 obj = getattr(obj, '__func__')
Chris Withersc7dd3c72020-01-27 14:11:19 +000056 return iscoroutinefunction(obj) or inspect.isawaitable(obj)
Lisa Roach77b3b772019-05-20 09:19:53 -070057
58
Xtreakff6b2e62019-05-27 18:26:23 +053059def _is_async_func(func):
60 if getattr(func, '__code__', None):
Chris Withersc7dd3c72020-01-27 14:11:19 +000061 return iscoroutinefunction(func)
Xtreakff6b2e62019-05-27 18:26:23 +053062 else:
63 return False
64
65
Michael Foord345266a2012-03-14 12:24:34 -070066def _is_instance_mock(obj):
67 # can't use isinstance on Mock objects because they override __class__
68 # The base class for all mocks is NonCallableMock
69 return issubclass(type(obj), NonCallableMock)
70
71
72def _is_exception(obj):
73 return (
Chris Withers49e27f02019-05-01 08:48:44 +010074 isinstance(obj, BaseException) or
75 isinstance(obj, type) and issubclass(obj, BaseException)
Michael Foord345266a2012-03-14 12:24:34 -070076 )
77
78
Xtreak7397cda2019-07-22 13:08:22 +053079def _extract_mock(obj):
80 # Autospecced functions will return a FunctionType with "mock" attribute
81 # which is the actual mock object that needs to be used.
82 if isinstance(obj, FunctionTypes) and hasattr(obj, 'mock'):
83 return obj.mock
84 else:
85 return obj
86
87
Antoine Pitrou5c64df72013-02-03 00:23:58 +010088def _get_signature_object(func, as_instance, eat_self):
89 """
90 Given an arbitrary, possibly callable object, try to create a suitable
91 signature object.
92 Return a (reduced func, signature) tuple, or None.
93 """
94 if isinstance(func, type) and not as_instance:
95 # If it's a type and should be modelled as a type, use __init__.
Chris Withersadbf1782019-05-01 23:04:04 +010096 func = func.__init__
Antoine Pitrou5c64df72013-02-03 00:23:58 +010097 # Skip the `self` argument in __init__
98 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070099 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100100 # If we really want to model an instance of the passed type,
101 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -0700102 try:
103 func = func.__call__
104 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100105 return None
106 if eat_self:
107 sig_func = partial(func, None)
108 else:
109 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -0700110 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100111 return func, inspect.signature(sig_func)
112 except ValueError:
113 # Certain callable types are not supported by inspect.signature()
114 return None
Michael Foord345266a2012-03-14 12:24:34 -0700115
116
117def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100118 sig = _get_signature_object(func, instance, skipfirst)
119 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -0700120 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100121 func, sig = sig
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300122 def checksig(self, /, *args, **kwargs):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100123 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700124 _copy_func_details(func, checksig)
125 type(mock)._mock_check_sig = checksig
Xtreakf7fa62e2018-12-12 13:24:54 +0530126 type(mock).__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700127
128
129def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700130 # we explicitly don't copy func.__dict__ into this copy as it would
131 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300132 for attribute in (
133 '__name__', '__doc__', '__text_signature__',
134 '__module__', '__defaults__', '__kwdefaults__',
135 ):
136 try:
137 setattr(funcopy, attribute, getattr(func, attribute))
138 except AttributeError:
139 pass
Michael Foord345266a2012-03-14 12:24:34 -0700140
141
142def _callable(obj):
143 if isinstance(obj, type):
144 return True
Xtreak9b218562019-04-22 08:00:23 +0530145 if isinstance(obj, (staticmethod, classmethod, MethodType)):
146 return _callable(obj.__func__)
Michael Foord345266a2012-03-14 12:24:34 -0700147 if getattr(obj, '__call__', None) is not None:
148 return True
149 return False
150
151
152def _is_list(obj):
153 # checks for list or tuples
154 # XXXX badly named!
155 return type(obj) in (list, tuple)
156
157
158def _instance_callable(obj):
159 """Given an object, return True if the object is callable.
160 For classes, return True if instances would be callable."""
161 if not isinstance(obj, type):
162 # already an instance
163 return getattr(obj, '__call__', None) is not None
164
Michael Foorda74b3aa2012-03-14 14:40:22 -0700165 # *could* be broken by a class overriding __mro__ or __dict__ via
166 # a metaclass
167 for base in (obj,) + obj.__mro__:
168 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700169 return True
170 return False
171
172
173def _set_signature(mock, original, instance=False):
174 # creates a function with signature (*args, **kwargs) that delegates to a
175 # mock. It still does signature checking by calling a lambda with the same
176 # signature as the original.
Michael Foord345266a2012-03-14 12:24:34 -0700177
178 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100179 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700180 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700181 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100182 func, sig = result
183 def checksig(*args, **kwargs):
184 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700185 _copy_func_details(func, checksig)
186
187 name = original.__name__
188 if not name.isidentifier():
189 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100190 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700191 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100192 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700193 return mock(*args, **kwargs)""" % name
194 exec (src, context)
195 funcopy = context[name]
Xtreakf7fa62e2018-12-12 13:24:54 +0530196 _setup_func(funcopy, mock, sig)
Michael Foord345266a2012-03-14 12:24:34 -0700197 return funcopy
198
199
Xtreakf7fa62e2018-12-12 13:24:54 +0530200def _setup_func(funcopy, mock, sig):
Michael Foord345266a2012-03-14 12:24:34 -0700201 funcopy.mock = mock
202
Michael Foord345266a2012-03-14 12:24:34 -0700203 def assert_called_with(*args, **kwargs):
204 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700205 def assert_called(*args, **kwargs):
206 return mock.assert_called(*args, **kwargs)
207 def assert_not_called(*args, **kwargs):
208 return mock.assert_not_called(*args, **kwargs)
209 def assert_called_once(*args, **kwargs):
210 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700211 def assert_called_once_with(*args, **kwargs):
212 return mock.assert_called_once_with(*args, **kwargs)
213 def assert_has_calls(*args, **kwargs):
214 return mock.assert_has_calls(*args, **kwargs)
215 def assert_any_call(*args, **kwargs):
216 return mock.assert_any_call(*args, **kwargs)
217 def reset_mock():
218 funcopy.method_calls = _CallList()
219 funcopy.mock_calls = _CallList()
220 mock.reset_mock()
221 ret = funcopy.return_value
222 if _is_instance_mock(ret) and not ret is mock:
223 ret.reset_mock()
224
225 funcopy.called = False
226 funcopy.call_count = 0
227 funcopy.call_args = None
228 funcopy.call_args_list = _CallList()
229 funcopy.method_calls = _CallList()
230 funcopy.mock_calls = _CallList()
231
232 funcopy.return_value = mock.return_value
233 funcopy.side_effect = mock.side_effect
234 funcopy._mock_children = mock._mock_children
235
236 funcopy.assert_called_with = assert_called_with
237 funcopy.assert_called_once_with = assert_called_once_with
238 funcopy.assert_has_calls = assert_has_calls
239 funcopy.assert_any_call = assert_any_call
240 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700241 funcopy.assert_called = assert_called
242 funcopy.assert_not_called = assert_not_called
243 funcopy.assert_called_once = assert_called_once
Xtreakf7fa62e2018-12-12 13:24:54 +0530244 funcopy.__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700245
246 mock._mock_delegate = funcopy
247
248
Xtreakff6b2e62019-05-27 18:26:23 +0530249def _setup_async_mock(mock):
250 mock._is_coroutine = asyncio.coroutines._is_coroutine
251 mock.await_count = 0
252 mock.await_args = None
253 mock.await_args_list = _CallList()
Xtreakff6b2e62019-05-27 18:26:23 +0530254
255 # Mock is not configured yet so the attributes are set
256 # to a function and then the corresponding mock helper function
257 # is called when the helper is accessed similar to _setup_func.
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300258 def wrapper(attr, /, *args, **kwargs):
Xtreakff6b2e62019-05-27 18:26:23 +0530259 return getattr(mock.mock, attr)(*args, **kwargs)
260
261 for attribute in ('assert_awaited',
262 'assert_awaited_once',
263 'assert_awaited_with',
264 'assert_awaited_once_with',
265 'assert_any_await',
266 'assert_has_awaits',
267 'assert_not_awaited'):
268
269 # setattr(mock, attribute, wrapper) causes late binding
270 # hence attribute will always be the last value in the loop
271 # Use partial(wrapper, attribute) to ensure the attribute is bound
272 # correctly.
273 setattr(mock, attribute, partial(wrapper, attribute))
274
275
Michael Foord345266a2012-03-14 12:24:34 -0700276def _is_magic(name):
277 return '__%s__' % name[2:-2] == name
278
279
280class _SentinelObject(object):
281 "A unique, named, sentinel object."
282 def __init__(self, name):
283 self.name = name
284
285 def __repr__(self):
286 return 'sentinel.%s' % self.name
287
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200288 def __reduce__(self):
289 return 'sentinel.%s' % self.name
290
Michael Foord345266a2012-03-14 12:24:34 -0700291
292class _Sentinel(object):
293 """Access attributes to return a named object, usable as a sentinel."""
294 def __init__(self):
295 self._sentinels = {}
296
297 def __getattr__(self, name):
298 if name == '__bases__':
299 # Without this help(unittest.mock) raises an exception
300 raise AttributeError
301 return self._sentinels.setdefault(name, _SentinelObject(name))
302
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200303 def __reduce__(self):
304 return 'sentinel'
305
Michael Foord345266a2012-03-14 12:24:34 -0700306
307sentinel = _Sentinel()
308
309DEFAULT = sentinel.DEFAULT
310_missing = sentinel.MISSING
311_deleted = sentinel.DELETED
312
313
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200314_allowed_names = {
315 'return_value', '_mock_return_value', 'side_effect',
316 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
317 '_mock_name', '_mock_new_name'
318}
Michael Foord345266a2012-03-14 12:24:34 -0700319
320
321def _delegating_property(name):
322 _allowed_names.add(name)
323 _the_name = '_mock_' + name
324 def _get(self, name=name, _the_name=_the_name):
325 sig = self._mock_delegate
326 if sig is None:
327 return getattr(self, _the_name)
328 return getattr(sig, name)
329 def _set(self, value, name=name, _the_name=_the_name):
330 sig = self._mock_delegate
331 if sig is None:
332 self.__dict__[_the_name] = value
333 else:
334 setattr(sig, name, value)
335
336 return property(_get, _set)
337
338
339
340class _CallList(list):
341
342 def __contains__(self, value):
343 if not isinstance(value, list):
344 return list.__contains__(self, value)
345 len_value = len(value)
346 len_self = len(self)
347 if len_value > len_self:
348 return False
349
350 for i in range(0, len_self - len_value + 1):
351 sub_list = self[i:i+len_value]
352 if sub_list == value:
353 return True
354 return False
355
356 def __repr__(self):
357 return pprint.pformat(list(self))
358
359
360def _check_and_set_parent(parent, value, name, new_name):
Xtreak7397cda2019-07-22 13:08:22 +0530361 value = _extract_mock(value)
Xtreak9c3f2842019-02-26 03:16:34 +0530362
Michael Foord345266a2012-03-14 12:24:34 -0700363 if not _is_instance_mock(value):
364 return False
365 if ((value._mock_name or value._mock_new_name) or
366 (value._mock_parent is not None) or
367 (value._mock_new_parent is not None)):
368 return False
369
370 _parent = parent
371 while _parent is not None:
372 # setting a mock (value) as a child or return value of itself
373 # should not modify the mock
374 if _parent is value:
375 return False
376 _parent = _parent._mock_new_parent
377
378 if new_name:
379 value._mock_new_parent = parent
380 value._mock_new_name = new_name
381 if name:
382 value._mock_parent = parent
383 value._mock_name = name
384 return True
385
Michael Foord01bafdc2014-04-14 16:09:42 -0400386# Internal class to identify if we wrapped an iterator object or not.
387class _MockIter(object):
388 def __init__(self, obj):
389 self.obj = iter(obj)
Michael Foord01bafdc2014-04-14 16:09:42 -0400390 def __next__(self):
391 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700392
393class Base(object):
394 _mock_return_value = DEFAULT
395 _mock_side_effect = None
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300396 def __init__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700397 pass
398
399
400
401class NonCallableMock(Base):
402 """A non-callable version of `Mock`"""
403
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300404 def __new__(cls, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700405 # every instance has its own class
406 # so we can create magic methods on the
407 # class without stomping on other mocks
Lisa Roach77b3b772019-05-20 09:19:53 -0700408 bases = (cls,)
Michael Foord14fd9252019-09-13 18:40:56 +0200409 if not issubclass(cls, AsyncMockMixin):
Lisa Roach77b3b772019-05-20 09:19:53 -0700410 # Check if spec is an async object or function
Michael Foord14fd9252019-09-13 18:40:56 +0200411 bound_args = _MOCK_SIG.bind_partial(cls, *args, **kw).arguments
412 spec_arg = bound_args.get('spec_set', bound_args.get('spec'))
idanw206c598a042020-12-06 11:59:36 +0200413 if spec_arg is not None and _is_async_obj(spec_arg):
Michael Foord14fd9252019-09-13 18:40:56 +0200414 bases = (AsyncMockMixin, cls)
Lisa Roach77b3b772019-05-20 09:19:53 -0700415 new = type(cls.__name__, bases, {'__doc__': cls.__doc__})
Lisa Roach9a7d9512019-09-28 18:42:44 -0700416 instance = _safe_super(NonCallableMock, cls).__new__(new)
Michael Foord345266a2012-03-14 12:24:34 -0700417 return instance
418
419
420 def __init__(
421 self, spec=None, wraps=None, name=None, spec_set=None,
422 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530423 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700424 ):
425 if _new_parent is None:
426 _new_parent = parent
427
428 __dict__ = self.__dict__
429 __dict__['_mock_parent'] = parent
430 __dict__['_mock_name'] = name
431 __dict__['_mock_new_name'] = _new_name
432 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100433 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700434
435 if spec_set is not None:
436 spec = spec_set
437 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100438 if _eat_self is None:
439 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700440
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100441 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700442
443 __dict__['_mock_children'] = {}
444 __dict__['_mock_wraps'] = wraps
445 __dict__['_mock_delegate'] = None
446
447 __dict__['_mock_called'] = False
448 __dict__['_mock_call_args'] = None
449 __dict__['_mock_call_count'] = 0
450 __dict__['_mock_call_args_list'] = _CallList()
451 __dict__['_mock_mock_calls'] = _CallList()
452
453 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530454 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700455
456 if kwargs:
457 self.configure_mock(**kwargs)
458
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000459 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700460 spec, wraps, name, spec_set, parent,
461 _spec_state
462 )
463
464
465 def attach_mock(self, mock, attribute):
466 """
467 Attach a mock as an attribute of this one, replacing its name and
468 parent. Calls to the attached mock will be recorded in the
469 `method_calls` and `mock_calls` attributes of this one."""
Xtreak7397cda2019-07-22 13:08:22 +0530470 inner_mock = _extract_mock(mock)
471
472 inner_mock._mock_parent = None
473 inner_mock._mock_new_parent = None
474 inner_mock._mock_name = ''
475 inner_mock._mock_new_name = None
Michael Foord345266a2012-03-14 12:24:34 -0700476
477 setattr(self, attribute, mock)
478
479
480 def mock_add_spec(self, spec, spec_set=False):
481 """Add a spec to a mock. `spec` can either be an object or a
482 list of strings. Only attributes on the `spec` can be fetched as
483 attributes from the mock.
484
485 If `spec_set` is True then only attributes on the spec can be set."""
486 self._mock_add_spec(spec, spec_set)
487
488
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100489 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
490 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700491 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100492 _spec_signature = None
Lisa Roach77b3b772019-05-20 09:19:53 -0700493 _spec_asyncs = []
494
495 for attr in dir(spec):
Chris Withersc7dd3c72020-01-27 14:11:19 +0000496 if iscoroutinefunction(getattr(spec, attr, None)):
Lisa Roach77b3b772019-05-20 09:19:53 -0700497 _spec_asyncs.append(attr)
Michael Foord345266a2012-03-14 12:24:34 -0700498
499 if spec is not None and not _is_list(spec):
500 if isinstance(spec, type):
501 _spec_class = spec
502 else:
Chris Withersadbf1782019-05-01 23:04:04 +0100503 _spec_class = type(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100504 res = _get_signature_object(spec,
505 _spec_as_instance, _eat_self)
506 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700507
508 spec = dir(spec)
509
510 __dict__ = self.__dict__
511 __dict__['_spec_class'] = _spec_class
512 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100513 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700514 __dict__['_mock_methods'] = spec
Lisa Roach77b3b772019-05-20 09:19:53 -0700515 __dict__['_spec_asyncs'] = _spec_asyncs
Michael Foord345266a2012-03-14 12:24:34 -0700516
517 def __get_return_value(self):
518 ret = self._mock_return_value
519 if self._mock_delegate is not None:
520 ret = self._mock_delegate.return_value
521
522 if ret is DEFAULT:
523 ret = self._get_child_mock(
524 _new_parent=self, _new_name='()'
525 )
526 self.return_value = ret
527 return ret
528
529
530 def __set_return_value(self, value):
531 if self._mock_delegate is not None:
532 self._mock_delegate.return_value = value
533 else:
534 self._mock_return_value = value
535 _check_and_set_parent(self, value, None, '()')
536
537 __return_value_doc = "The value to be returned when the mock is called."
538 return_value = property(__get_return_value, __set_return_value,
539 __return_value_doc)
540
541
542 @property
543 def __class__(self):
544 if self._spec_class is None:
545 return type(self)
546 return self._spec_class
547
548 called = _delegating_property('called')
549 call_count = _delegating_property('call_count')
550 call_args = _delegating_property('call_args')
551 call_args_list = _delegating_property('call_args_list')
552 mock_calls = _delegating_property('mock_calls')
553
554
555 def __get_side_effect(self):
556 delegated = self._mock_delegate
557 if delegated is None:
558 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400559 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200560 if (sf is not None and not callable(sf)
561 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400562 sf = _MockIter(sf)
563 delegated.side_effect = sf
564 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700565
566 def __set_side_effect(self, value):
567 value = _try_iter(value)
568 delegated = self._mock_delegate
569 if delegated is None:
570 self._mock_side_effect = value
571 else:
572 delegated.side_effect = value
573
574 side_effect = property(__get_side_effect, __set_side_effect)
575
576
Kushal Das9cd39a12016-06-02 10:20:16 -0700577 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700578 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200579 if visited is None:
580 visited = []
581 if id(self) in visited:
582 return
583 visited.append(id(self))
584
Michael Foord345266a2012-03-14 12:24:34 -0700585 self.called = False
586 self.call_args = None
587 self.call_count = 0
588 self.mock_calls = _CallList()
589 self.call_args_list = _CallList()
590 self.method_calls = _CallList()
591
Kushal Das9cd39a12016-06-02 10:20:16 -0700592 if return_value:
593 self._mock_return_value = DEFAULT
594 if side_effect:
595 self._mock_side_effect = None
596
Michael Foord345266a2012-03-14 12:24:34 -0700597 for child in self._mock_children.values():
Xtreakedeca922018-12-01 15:33:54 +0530598 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100599 continue
Vegard Stikbakkeaef7dc82020-01-25 16:44:46 +0100600 child.reset_mock(visited, return_value=return_value, side_effect=side_effect)
Michael Foord345266a2012-03-14 12:24:34 -0700601
602 ret = self._mock_return_value
603 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200604 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700605
606
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300607 def configure_mock(self, /, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700608 """Set attributes on the mock through keyword arguments.
609
610 Attributes plus return values and side effects can be set on child
611 mocks using standard dot notation and unpacking a dictionary in the
612 method call:
613
614 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
615 >>> mock.configure_mock(**attrs)"""
616 for arg, val in sorted(kwargs.items(),
617 # we sort on the number of dots so that
618 # attributes are set before we set attributes on
619 # attributes
620 key=lambda entry: entry[0].count('.')):
621 args = arg.split('.')
622 final = args.pop()
623 obj = self
624 for entry in args:
625 obj = getattr(obj, entry)
626 setattr(obj, final, val)
627
628
629 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530630 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700631 raise AttributeError(name)
632 elif self._mock_methods is not None:
633 if name not in self._mock_methods or name in _all_magics:
634 raise AttributeError("Mock object has no attribute %r" % name)
635 elif _is_magic(name):
636 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530637 if not self._mock_unsafe:
vabr-g4662fa92020-11-05 18:04:38 +0100638 if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')):
vabr-g9fc57132020-12-10 19:35:28 +0100639 raise AttributeError(
vabr-gfdb9efc2020-12-14 19:30:09 +0100640 f"{name!r} is not a valid assertion. Use a spec "
641 f"for the mock if {name!r} is meant to be an attribute.")
Michael Foord345266a2012-03-14 12:24:34 -0700642
643 result = self._mock_children.get(name)
644 if result is _deleted:
645 raise AttributeError(name)
646 elif result is None:
647 wraps = None
648 if self._mock_wraps is not None:
649 # XXXX should we get the attribute without triggering code
650 # execution?
651 wraps = getattr(self._mock_wraps, name)
652
653 result = self._get_child_mock(
654 parent=self, name=name, wraps=wraps, _new_name=name,
655 _new_parent=self
656 )
657 self._mock_children[name] = result
658
659 elif isinstance(result, _SpecState):
Matthew Suozzodccdc502021-04-09 23:45:50 -0400660 try:
661 result = create_autospec(
662 result.spec, result.spec_set, result.instance,
663 result.parent, result.name
664 )
665 except InvalidSpecError:
666 target_name = self.__dict__['_mock_name'] or self
667 raise InvalidSpecError(
668 f'Cannot autospec attr {name!r} from target '
669 f'{target_name!r} as it has already been mocked out. '
670 f'[target={self!r}, attr={result.spec!r}]')
Michael Foord345266a2012-03-14 12:24:34 -0700671 self._mock_children[name] = result
672
673 return result
674
675
Mario Corchero552be9d2017-10-17 12:35:11 +0100676 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700677 _name_list = [self._mock_new_name]
678 _parent = self._mock_new_parent
679 last = self
680
681 dot = '.'
682 if _name_list == ['()']:
683 dot = ''
Chris Withersadbf1782019-05-01 23:04:04 +0100684
Michael Foord345266a2012-03-14 12:24:34 -0700685 while _parent is not None:
686 last = _parent
687
688 _name_list.append(_parent._mock_new_name + dot)
689 dot = '.'
690 if _parent._mock_new_name == '()':
691 dot = ''
692
693 _parent = _parent._mock_new_parent
694
Michael Foord345266a2012-03-14 12:24:34 -0700695 _name_list = list(reversed(_name_list))
696 _first = last._mock_name or 'mock'
697 if len(_name_list) > 1:
698 if _name_list[1] not in ('()', '().'):
699 _first += '.'
700 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100701 return ''.join(_name_list)
702
703 def __repr__(self):
704 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700705
706 name_string = ''
707 if name not in ('mock', 'mock.'):
708 name_string = ' name=%r' % name
709
710 spec_string = ''
711 if self._spec_class is not None:
712 spec_string = ' spec=%r'
713 if self._spec_set:
714 spec_string = ' spec_set=%r'
715 spec_string = spec_string % self._spec_class.__name__
716 return "<%s%s%s id='%s'>" % (
717 type(self).__name__,
718 name_string,
719 spec_string,
720 id(self)
721 )
722
723
724 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700725 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100726 if not FILTER_DIR:
727 return object.__dir__(self)
728
Michael Foord345266a2012-03-14 12:24:34 -0700729 extras = self._mock_methods or []
730 from_type = dir(type(self))
731 from_dict = list(self.__dict__)
Mario Corchero0df635c2019-04-30 19:56:36 +0100732 from_child_mocks = [
733 m_name for m_name, m_value in self._mock_children.items()
734 if m_value is not _deleted]
Michael Foord345266a2012-03-14 12:24:34 -0700735
Michael Foord313f85f2012-03-25 18:16:07 +0100736 from_type = [e for e in from_type if not e.startswith('_')]
737 from_dict = [e for e in from_dict if not e.startswith('_') or
738 _is_magic(e)]
Mario Corchero0df635c2019-04-30 19:56:36 +0100739 return sorted(set(extras + from_type + from_dict + from_child_mocks))
Michael Foord345266a2012-03-14 12:24:34 -0700740
741
742 def __setattr__(self, name, value):
743 if name in _allowed_names:
744 # property setters go through here
745 return object.__setattr__(self, name, value)
746 elif (self._spec_set and self._mock_methods is not None and
747 name not in self._mock_methods and
748 name not in self.__dict__):
749 raise AttributeError("Mock object has no attribute '%s'" % name)
750 elif name in _unsupported_magics:
751 msg = 'Attempting to set unsupported magic method %r.' % name
752 raise AttributeError(msg)
753 elif name in _all_magics:
754 if self._mock_methods is not None and name not in self._mock_methods:
755 raise AttributeError("Mock object has no attribute '%s'" % name)
756
757 if not _is_instance_mock(value):
758 setattr(type(self), name, _get_method(name, value))
759 original = value
760 value = lambda *args, **kw: original(self, *args, **kw)
761 else:
762 # only set _new_name and not name so that mock_calls is tracked
763 # but not method calls
764 _check_and_set_parent(self, value, None, name)
765 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100766 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700767 elif name == '__class__':
768 self._spec_class = value
769 return
770 else:
771 if _check_and_set_parent(self, value, name, name):
772 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100773
774 if self._mock_sealed and not hasattr(self, name):
775 mock_name = f'{self._extract_mock_name()}.{name}'
776 raise AttributeError(f'Cannot set {mock_name}')
777
Michael Foord345266a2012-03-14 12:24:34 -0700778 return object.__setattr__(self, name, value)
779
780
781 def __delattr__(self, name):
782 if name in _all_magics and name in type(self).__dict__:
783 delattr(type(self), name)
784 if name not in self.__dict__:
785 # for magic methods that are still MagicProxy objects and
786 # not set on the instance itself
787 return
788
Michael Foord345266a2012-03-14 12:24:34 -0700789 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000790 if name in self.__dict__:
Xtreak830b43d2019-04-14 00:42:33 +0530791 _safe_super(NonCallableMock, self).__delattr__(name)
Pablo Galindo222d3032019-01-21 08:57:46 +0000792 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700793 raise AttributeError(name)
794 if obj is not _missing:
795 del self._mock_children[name]
796 self._mock_children[name] = _deleted
797
798
Michael Foord345266a2012-03-14 12:24:34 -0700799 def _format_mock_call_signature(self, args, kwargs):
800 name = self._mock_name or 'mock'
801 return _format_call_signature(name, args, kwargs)
802
803
Xtreak0ae022c2019-05-29 12:32:26 +0530804 def _format_mock_failure_message(self, args, kwargs, action='call'):
805 message = 'expected %s not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700806 expected_string = self._format_mock_call_signature(args, kwargs)
807 call_args = self.call_args
Michael Foord345266a2012-03-14 12:24:34 -0700808 actual_string = self._format_mock_call_signature(*call_args)
Xtreak0ae022c2019-05-29 12:32:26 +0530809 return message % (action, expected_string, actual_string)
Michael Foord345266a2012-03-14 12:24:34 -0700810
811
Xtreakc9612782019-08-29 11:39:01 +0530812 def _get_call_signature_from_name(self, name):
813 """
814 * If call objects are asserted against a method/function like obj.meth1
815 then there could be no name for the call object to lookup. Hence just
816 return the spec_signature of the method/function being asserted against.
817 * If the name is not empty then remove () and split by '.' to get
818 list of names to iterate through the children until a potential
819 match is found. A child mock is created only during attribute access
820 so if we get a _SpecState then no attributes of the spec were accessed
821 and can be safely exited.
822 """
823 if not name:
824 return self._spec_signature
825
826 sig = None
827 names = name.replace('()', '').split('.')
828 children = self._mock_children
829
830 for name in names:
831 child = children.get(name)
832 if child is None or isinstance(child, _SpecState):
833 break
834 else:
Karthikeyan Singaravelan66b00a92020-01-24 18:44:29 +0530835 # If an autospecced object is attached using attach_mock the
836 # child would be a function with mock object as attribute from
837 # which signature has to be derived.
838 child = _extract_mock(child)
Xtreakc9612782019-08-29 11:39:01 +0530839 children = child._mock_children
840 sig = child._spec_signature
841
842 return sig
843
844
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100845 def _call_matcher(self, _call):
846 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000847 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100848 comparison key suitable for matching with other calls.
849 This is a best effort method which relies on the spec's signature,
850 if available, or falls back on the arguments themselves.
851 """
Xtreakc9612782019-08-29 11:39:01 +0530852
853 if isinstance(_call, tuple) and len(_call) > 2:
854 sig = self._get_call_signature_from_name(_call[0])
855 else:
856 sig = self._spec_signature
857
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100858 if sig is not None:
859 if len(_call) == 2:
860 name = ''
861 args, kwargs = _call
862 else:
863 name, args, kwargs = _call
864 try:
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700865 bound_call = sig.bind(*args, **kwargs)
866 return call(name, bound_call.args, bound_call.kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100867 except TypeError as e:
868 return e.with_traceback(None)
869 else:
870 return _call
871
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300872 def assert_not_called(self):
Kushal Das8af9db32014-04-17 01:36:14 +0530873 """assert that the mock was never called.
874 """
Kushal Das8af9db32014-04-17 01:36:14 +0530875 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100876 msg = ("Expected '%s' to not have been called. Called %s times.%s"
877 % (self._mock_name or 'mock',
878 self.call_count,
879 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530880 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100881
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300882 def assert_called(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100883 """assert that the mock was called at least once
884 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100885 if self.call_count == 0:
886 msg = ("Expected '%s' to have been called." %
Abraham Toriz Cruz5f5f11f2019-09-17 06:16:08 -0500887 (self._mock_name or 'mock'))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100888 raise AssertionError(msg)
889
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300890 def assert_called_once(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100891 """assert that the mock was called only once.
892 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100893 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100894 msg = ("Expected '%s' to have been called once. Called %s times.%s"
895 % (self._mock_name or 'mock',
896 self.call_count,
897 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100898 raise AssertionError(msg)
899
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300900 def assert_called_with(self, /, *args, **kwargs):
Rémi Lapeyref5896a02019-08-29 08:15:53 +0200901 """assert that the last call was made with the specified arguments.
Michael Foord345266a2012-03-14 12:24:34 -0700902
903 Raises an AssertionError if the args and keyword args passed in are
904 different to the last call to the mock."""
Michael Foord345266a2012-03-14 12:24:34 -0700905 if self.call_args is None:
906 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800907 actual = 'not called.'
908 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
909 % (expected, actual))
910 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700911
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100912 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700913 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100914 return msg
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700915 expected = self._call_matcher(_Call((args, kwargs), two=True))
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100916 actual = self._call_matcher(self.call_args)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700917 if actual != expected:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100918 cause = expected if isinstance(expected, Exception) else None
919 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700920
921
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300922 def assert_called_once_with(self, /, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100923 """assert that the mock was called exactly once and that that call was
924 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700925 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100926 msg = ("Expected '%s' to be called once. Called %s times.%s"
927 % (self._mock_name or 'mock',
928 self.call_count,
929 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700930 raise AssertionError(msg)
931 return self.assert_called_with(*args, **kwargs)
932
933
934 def assert_has_calls(self, calls, any_order=False):
935 """assert the mock has been called with the specified calls.
936 The `mock_calls` list is checked for the calls.
937
938 If `any_order` is False (the default) then the calls must be
939 sequential. There can be extra calls before or after the
940 specified calls.
941
942 If `any_order` is True then the calls can be in any order, but
943 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100944 expected = [self._call_matcher(c) for c in calls]
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400945 cause = next((e for e in expected if isinstance(e, Exception)), None)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100946 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700947 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100948 if expected not in all_calls:
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400949 if cause is None:
950 problem = 'Calls not found.'
951 else:
952 problem = ('Error processing expected calls.\n'
953 'Errors: {}').format(
954 [e if isinstance(e, Exception) else None
955 for e in expected])
Michael Foord345266a2012-03-14 12:24:34 -0700956 raise AssertionError(
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400957 f'{problem}\n'
Samuel Freilich2180f6b2019-09-24 18:04:29 -0400958 f'Expected: {_CallList(calls)}'
959 f'{self._calls_repr(prefix="Actual").rstrip(".")}'
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100960 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700961 return
962
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100963 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700964
965 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100966 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700967 try:
968 all_calls.remove(kall)
969 except ValueError:
970 not_found.append(kall)
971 if not_found:
972 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400973 '%r does not contain all of %r in its call list, '
974 'found %r instead' % (self._mock_name or 'mock',
975 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100976 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700977
978
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300979 def assert_any_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700980 """assert the mock has been called with the specified arguments.
981
982 The assert passes if the mock has *ever* been called, unlike
983 `assert_called_with` and `assert_called_once_with` that only pass if
984 the call is the most recent one."""
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700985 expected = self._call_matcher(_Call((args, kwargs), two=True))
986 cause = expected if isinstance(expected, Exception) else None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100987 actual = [self._call_matcher(c) for c in self.call_args_list]
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700988 if cause or expected not in _AnyComparer(actual):
Michael Foord345266a2012-03-14 12:24:34 -0700989 expected_string = self._format_mock_call_signature(args, kwargs)
990 raise AssertionError(
991 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100992 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700993
994
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300995 def _get_child_mock(self, /, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700996 """Create the child mocks for attributes and return value.
997 By default child mocks will be the same type as the parent.
998 Subclasses of Mock may want to override this to customize the way
999 child mocks are made.
1000
1001 For non-callable mocks the callable variant will be used (rather than
1002 any custom subclass)."""
Lisa Roach77b3b772019-05-20 09:19:53 -07001003 _new_name = kw.get("_new_name")
1004 if _new_name in self.__dict__['_spec_asyncs']:
1005 return AsyncMock(**kw)
1006
Michael Foord345266a2012-03-14 12:24:34 -07001007 _type = type(self)
Lisa Roach77b3b772019-05-20 09:19:53 -07001008 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
Lisa Roach9a7d9512019-09-28 18:42:44 -07001009 # Any asynchronous magic becomes an AsyncMock
Lisa Roach77b3b772019-05-20 09:19:53 -07001010 klass = AsyncMock
Lisa Roach8b03f942019-09-19 21:04:18 -07001011 elif issubclass(_type, AsyncMockMixin):
Lisa Roach3667e1e2019-09-29 21:56:47 -07001012 if (_new_name in _all_sync_magics or
1013 self._mock_methods and _new_name in self._mock_methods):
1014 # Any synchronous method on AsyncMock becomes a MagicMock
Lisa Roach9a7d9512019-09-28 18:42:44 -07001015 klass = MagicMock
1016 else:
1017 klass = AsyncMock
Lisa Roach8b03f942019-09-19 21:04:18 -07001018 elif not issubclass(_type, CallableMixin):
Michael Foord345266a2012-03-14 12:24:34 -07001019 if issubclass(_type, NonCallableMagicMock):
1020 klass = MagicMock
Lisa Roach9a7d9512019-09-28 18:42:44 -07001021 elif issubclass(_type, NonCallableMock):
Michael Foord345266a2012-03-14 12:24:34 -07001022 klass = Mock
1023 else:
1024 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +01001025
1026 if self._mock_sealed:
1027 attribute = "." + kw["name"] if "name" in kw else "()"
1028 mock_name = self._extract_mock_name() + attribute
1029 raise AttributeError(mock_name)
1030
Michael Foord345266a2012-03-14 12:24:34 -07001031 return klass(**kw)
1032
1033
Petter Strandmark47d94242018-10-28 21:37:10 +01001034 def _calls_repr(self, prefix="Calls"):
1035 """Renders self.mock_calls as a string.
1036
1037 Example: "\nCalls: [call(1), call(2)]."
1038
1039 If self.mock_calls is empty, an empty string is returned. The
1040 output will be truncated if very long.
1041 """
1042 if not self.mock_calls:
1043 return ""
1044 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
1045
1046
Michael Foord14fd9252019-09-13 18:40:56 +02001047_MOCK_SIG = inspect.signature(NonCallableMock.__init__)
1048
1049
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07001050class _AnyComparer(list):
1051 """A list which checks if it contains a call which may have an
1052 argument of ANY, flipping the components of item and self from
1053 their traditional locations so that ANY is guaranteed to be on
1054 the left."""
1055 def __contains__(self, item):
1056 for _call in self:
Chris Withersdb5e86a2020-01-29 16:24:54 +00001057 assert len(item) == len(_call)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07001058 if all([
1059 expected == actual
1060 for expected, actual in zip(item, _call)
1061 ]):
1062 return True
1063 return False
1064
Michael Foord345266a2012-03-14 12:24:34 -07001065
1066def _try_iter(obj):
1067 if obj is None:
1068 return obj
1069 if _is_exception(obj):
1070 return obj
1071 if _callable(obj):
1072 return obj
1073 try:
1074 return iter(obj)
1075 except TypeError:
1076 # XXXX backwards compatibility
1077 # but this will blow up on first call - so maybe we should fail early?
1078 return obj
1079
1080
Michael Foord345266a2012-03-14 12:24:34 -07001081class CallableMixin(Base):
1082
1083 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
1084 wraps=None, name=None, spec_set=None, parent=None,
1085 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
1086 self.__dict__['_mock_return_value'] = return_value
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001087 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -07001088 spec, wraps, name, spec_set, parent,
1089 _spec_state, _new_name, _new_parent, **kwargs
1090 )
1091
1092 self.side_effect = side_effect
1093
1094
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001095 def _mock_check_sig(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001096 # stub method that can be replaced with one with a specific signature
1097 pass
1098
1099
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001100 def __call__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001101 # can't use self in-case a function / method we are mocking uses self
1102 # in the signature
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001103 self._mock_check_sig(*args, **kwargs)
Lisa Roachef048512019-09-23 20:49:40 -07001104 self._increment_mock_call(*args, **kwargs)
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001105 return self._mock_call(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001106
1107
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001108 def _mock_call(self, /, *args, **kwargs):
Lisa Roachef048512019-09-23 20:49:40 -07001109 return self._execute_mock_call(*args, **kwargs)
1110
1111 def _increment_mock_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001112 self.called = True
1113 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001114
Chris Withers8ca0fa92018-12-03 21:31:37 +00001115 # handle call_args
Lisa Roachef048512019-09-23 20:49:40 -07001116 # needs to be set here so assertions on call arguments pass before
1117 # execution in the case of awaited calls
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001118 _call = _Call((args, kwargs), two=True)
1119 self.call_args = _call
1120 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -07001121
Chris Withers8ca0fa92018-12-03 21:31:37 +00001122 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001123 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +00001124 method_call_name = self._mock_name
1125
1126 # initial stuff for mock_calls:
1127 mock_call_name = self._mock_new_name
1128 is_a_call = mock_call_name == '()'
1129 self.mock_calls.append(_Call(('', args, kwargs)))
1130
1131 # follow up the chain of mocks:
1132 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001133 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001134
Chris Withers8ca0fa92018-12-03 21:31:37 +00001135 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001136 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001137 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001138 do_method_calls = _new_parent._mock_parent is not None
1139 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001140 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001141
Chris Withers8ca0fa92018-12-03 21:31:37 +00001142 # handle mock_calls:
1143 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001144 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001145
1146 if _new_parent._mock_new_name:
1147 if is_a_call:
1148 dot = ''
1149 else:
1150 dot = '.'
1151 is_a_call = _new_parent._mock_new_name == '()'
1152 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1153
1154 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001155 _new_parent = _new_parent._mock_new_parent
1156
Lisa Roachef048512019-09-23 20:49:40 -07001157 def _execute_mock_call(self, /, *args, **kwargs):
Jason Fried046442d2019-11-20 16:27:51 -08001158 # separate from _increment_mock_call so that awaited functions are
1159 # executed separately from their call, also AsyncMock overrides this method
Lisa Roachef048512019-09-23 20:49:40 -07001160
Michael Foord345266a2012-03-14 12:24:34 -07001161 effect = self.side_effect
1162 if effect is not None:
1163 if _is_exception(effect):
1164 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001165 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001166 result = next(effect)
1167 if _is_exception(result):
1168 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001169 else:
1170 result = effect(*args, **kwargs)
1171
1172 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001173 return result
Michael Foord345266a2012-03-14 12:24:34 -07001174
Mario Corcherof05df0a2018-12-08 11:25:02 +00001175 if self._mock_return_value is not DEFAULT:
1176 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001177
Mario Corcherof05df0a2018-12-08 11:25:02 +00001178 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001179 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001180
1181 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001182
1183
1184
1185class Mock(CallableMixin, NonCallableMock):
1186 """
1187 Create a new `Mock` object. `Mock` takes several optional arguments
1188 that specify the behaviour of the Mock object:
1189
1190 * `spec`: This can be either a list of strings or an existing object (a
1191 class or instance) that acts as the specification for the mock object. If
1192 you pass in an object then a list of strings is formed by calling dir on
1193 the object (excluding unsupported magic attributes and methods). Accessing
1194 any attribute not in this list will raise an `AttributeError`.
1195
1196 If `spec` is an object (rather than a list of strings) then
1197 `mock.__class__` returns the class of the spec object. This allows mocks
1198 to pass `isinstance` tests.
1199
1200 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1201 or get an attribute on the mock that isn't on the object passed as
1202 `spec_set` will raise an `AttributeError`.
1203
1204 * `side_effect`: A function to be called whenever the Mock is called. See
1205 the `side_effect` attribute. Useful for raising exceptions or
1206 dynamically changing return values. The function is called with the same
1207 arguments as the mock, and unless it returns `DEFAULT`, the return
1208 value of this function is used as the return value.
1209
Michael Foord2cd48732012-04-21 15:52:11 +01001210 If `side_effect` is an iterable then each call to the mock will return
1211 the next value from the iterable. If any of the members of the iterable
1212 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001213
Michael Foord345266a2012-03-14 12:24:34 -07001214 * `return_value`: The value returned when the mock is called. By default
1215 this is a new Mock (created on first access). See the
1216 `return_value` attribute.
1217
Michael Foord0682a0c2012-04-13 20:51:20 +01001218 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1219 calling the Mock will pass the call through to the wrapped object
1220 (returning the real result). Attribute access on the mock will return a
1221 Mock object that wraps the corresponding attribute of the wrapped object
1222 (so attempting to access an attribute that doesn't exist will raise an
1223 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001224
1225 If the mock has an explicit `return_value` set then calls are not passed
1226 to the wrapped object and the `return_value` is returned instead.
1227
1228 * `name`: If the mock has a name then it will be used in the repr of the
1229 mock. This can be useful for debugging. The name is propagated to child
1230 mocks.
1231
1232 Mocks can also be called with arbitrary keyword arguments. These will be
1233 used to set attributes on the mock after it is created.
1234 """
1235
1236
Michael Foord345266a2012-03-14 12:24:34 -07001237def _dot_lookup(thing, comp, import_path):
1238 try:
1239 return getattr(thing, comp)
1240 except AttributeError:
1241 __import__(import_path)
1242 return getattr(thing, comp)
1243
1244
1245def _importer(target):
1246 components = target.split('.')
1247 import_path = components.pop(0)
1248 thing = __import__(import_path)
1249
1250 for comp in components:
1251 import_path += ".%s" % comp
1252 thing = _dot_lookup(thing, comp, import_path)
1253 return thing
1254
1255
vabr-gfdb9efc2020-12-14 19:30:09 +01001256# _check_spec_arg_typos takes kwargs from commands like patch and checks that
1257# they don't contain common misspellings of arguments related to autospeccing.
1258def _check_spec_arg_typos(kwargs_to_check):
1259 typos = ("autospect", "auto_spec", "set_spec")
1260 for typo in typos:
1261 if typo in kwargs_to_check:
1262 raise RuntimeError(
1263 f"{typo!r} might be a typo; use unsafe=True if this is intended"
1264 )
1265
1266
Michael Foord345266a2012-03-14 12:24:34 -07001267class _patch(object):
1268
1269 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001270 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001271
1272 def __init__(
1273 self, getter, attribute, new, spec, create,
vabr-gfdb9efc2020-12-14 19:30:09 +01001274 spec_set, autospec, new_callable, kwargs, *, unsafe=False
Michael Foord345266a2012-03-14 12:24:34 -07001275 ):
1276 if new_callable is not None:
1277 if new is not DEFAULT:
1278 raise ValueError(
1279 "Cannot use 'new' and 'new_callable' together"
1280 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001281 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001282 raise ValueError(
1283 "Cannot use 'autospec' and 'new_callable' together"
1284 )
vabr-gfdb9efc2020-12-14 19:30:09 +01001285 if not unsafe:
1286 _check_spec_arg_typos(kwargs)
Matthew Suozzodccdc502021-04-09 23:45:50 -04001287 if _is_instance_mock(spec):
1288 raise InvalidSpecError(
1289 f'Cannot spec attr {attribute!r} as the spec '
1290 f'has already been mocked out. [spec={spec!r}]')
1291 if _is_instance_mock(spec_set):
1292 raise InvalidSpecError(
1293 f'Cannot spec attr {attribute!r} as the spec_set '
1294 f'target has already been mocked out. [spec_set={spec_set!r}]')
Michael Foord345266a2012-03-14 12:24:34 -07001295
1296 self.getter = getter
1297 self.attribute = attribute
1298 self.new = new
1299 self.new_callable = new_callable
1300 self.spec = spec
1301 self.create = create
1302 self.has_local = False
1303 self.spec_set = spec_set
1304 self.autospec = autospec
1305 self.kwargs = kwargs
1306 self.additional_patchers = []
1307
1308
1309 def copy(self):
1310 patcher = _patch(
1311 self.getter, self.attribute, self.new, self.spec,
1312 self.create, self.spec_set,
1313 self.autospec, self.new_callable, self.kwargs
1314 )
1315 patcher.attribute_name = self.attribute_name
1316 patcher.additional_patchers = [
1317 p.copy() for p in self.additional_patchers
1318 ]
1319 return patcher
1320
1321
1322 def __call__(self, func):
1323 if isinstance(func, type):
1324 return self.decorate_class(func)
Xtreak436c2b02019-05-28 12:37:39 +05301325 if inspect.iscoroutinefunction(func):
1326 return self.decorate_async_callable(func)
Michael Foord345266a2012-03-14 12:24:34 -07001327 return self.decorate_callable(func)
1328
1329
1330 def decorate_class(self, klass):
1331 for attr in dir(klass):
1332 if not attr.startswith(patch.TEST_PREFIX):
1333 continue
1334
1335 attr_value = getattr(klass, attr)
1336 if not hasattr(attr_value, "__call__"):
1337 continue
1338
1339 patcher = self.copy()
1340 setattr(klass, attr, patcher(attr_value))
1341 return klass
1342
1343
Xtreak436c2b02019-05-28 12:37:39 +05301344 @contextlib.contextmanager
1345 def decoration_helper(self, patched, args, keywargs):
1346 extra_args = []
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001347 with contextlib.ExitStack() as exit_stack:
Xtreak436c2b02019-05-28 12:37:39 +05301348 for patching in patched.patchings:
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001349 arg = exit_stack.enter_context(patching)
Xtreak436c2b02019-05-28 12:37:39 +05301350 if patching.attribute_name is not None:
1351 keywargs.update(arg)
1352 elif patching.new is DEFAULT:
1353 extra_args.append(arg)
1354
1355 args += tuple(extra_args)
1356 yield (args, keywargs)
Xtreak436c2b02019-05-28 12:37:39 +05301357
1358
Michael Foord345266a2012-03-14 12:24:34 -07001359 def decorate_callable(self, func):
Xtreak436c2b02019-05-28 12:37:39 +05301360 # NB. Keep the method in sync with decorate_async_callable()
Michael Foord345266a2012-03-14 12:24:34 -07001361 if hasattr(func, 'patchings'):
1362 func.patchings.append(self)
1363 return func
1364
1365 @wraps(func)
1366 def patched(*args, **keywargs):
Xtreak436c2b02019-05-28 12:37:39 +05301367 with self.decoration_helper(patched,
1368 args,
1369 keywargs) as (newargs, newkeywargs):
1370 return func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001371
Xtreak436c2b02019-05-28 12:37:39 +05301372 patched.patchings = [self]
1373 return patched
Michael Foord345266a2012-03-14 12:24:34 -07001374
Xtreak436c2b02019-05-28 12:37:39 +05301375
1376 def decorate_async_callable(self, func):
1377 # NB. Keep the method in sync with decorate_callable()
1378 if hasattr(func, 'patchings'):
1379 func.patchings.append(self)
1380 return func
1381
1382 @wraps(func)
1383 async def patched(*args, **keywargs):
1384 with self.decoration_helper(patched,
1385 args,
1386 keywargs) as (newargs, newkeywargs):
1387 return await func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001388
1389 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001390 return patched
1391
1392
1393 def get_original(self):
1394 target = self.getter()
1395 name = self.attribute
1396
1397 original = DEFAULT
1398 local = False
1399
1400 try:
1401 original = target.__dict__[name]
1402 except (AttributeError, KeyError):
1403 original = getattr(target, name, DEFAULT)
1404 else:
1405 local = True
1406
Michael Foordfddcfa22014-04-14 16:25:20 -04001407 if name in _builtins and isinstance(target, ModuleType):
1408 self.create = True
1409
Michael Foord345266a2012-03-14 12:24:34 -07001410 if not self.create and original is DEFAULT:
1411 raise AttributeError(
1412 "%s does not have the attribute %r" % (target, name)
1413 )
1414 return original, local
1415
1416
1417 def __enter__(self):
1418 """Perform the patch."""
1419 new, spec, spec_set = self.new, self.spec, self.spec_set
1420 autospec, kwargs = self.autospec, self.kwargs
1421 new_callable = self.new_callable
1422 self.target = self.getter()
1423
Michael Foord50a8c0e2012-03-25 18:57:58 +01001424 # normalise False to None
1425 if spec is False:
1426 spec = None
1427 if spec_set is False:
1428 spec_set = None
1429 if autospec is False:
1430 autospec = None
1431
1432 if spec is not None and autospec is not None:
1433 raise TypeError("Can't specify spec and autospec")
1434 if ((spec is not None or autospec is not None) and
1435 spec_set not in (True, None)):
1436 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1437
Michael Foord345266a2012-03-14 12:24:34 -07001438 original, local = self.get_original()
1439
Michael Foord50a8c0e2012-03-25 18:57:58 +01001440 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001441 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001442 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001443 # set spec to the object we are replacing
1444 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001445 if spec_set is True:
1446 spec_set = original
1447 spec = None
1448 elif spec is not None:
1449 if spec_set is True:
1450 spec_set = spec
1451 spec = None
1452 elif spec_set is True:
1453 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001454
Michael Foord50a8c0e2012-03-25 18:57:58 +01001455 if spec is not None or spec_set is not None:
1456 if original is DEFAULT:
1457 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001458 if isinstance(original, type):
1459 # If we're patching out a class and there is a spec
1460 inherit = True
Lisa Roach77b3b772019-05-20 09:19:53 -07001461 if spec is None and _is_async_obj(original):
1462 Klass = AsyncMock
1463 else:
1464 Klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -07001465 _kwargs = {}
1466 if new_callable is not None:
1467 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001468 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001469 this_spec = spec
1470 if spec_set is not None:
1471 this_spec = spec_set
1472 if _is_list(this_spec):
1473 not_callable = '__call__' not in this_spec
1474 else:
1475 not_callable = not callable(this_spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07001476 if _is_async_obj(this_spec):
1477 Klass = AsyncMock
1478 elif not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001479 Klass = NonCallableMagicMock
1480
1481 if spec is not None:
1482 _kwargs['spec'] = spec
1483 if spec_set is not None:
1484 _kwargs['spec_set'] = spec_set
1485
1486 # add a name to mocks
1487 if (isinstance(Klass, type) and
1488 issubclass(Klass, NonCallableMock) and self.attribute):
1489 _kwargs['name'] = self.attribute
1490
1491 _kwargs.update(kwargs)
1492 new = Klass(**_kwargs)
1493
1494 if inherit and _is_instance_mock(new):
1495 # we can only tell if the instance should be callable if the
1496 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001497 this_spec = spec
1498 if spec_set is not None:
1499 this_spec = spec_set
1500 if (not _is_list(this_spec) and not
1501 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001502 Klass = NonCallableMagicMock
1503
1504 _kwargs.pop('name')
1505 new.return_value = Klass(_new_parent=new, _new_name='()',
1506 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001507 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001508 # spec is ignored, new *must* be default, spec_set is treated
1509 # as a boolean. Should we check spec is not None and that spec_set
1510 # is a bool?
1511 if new is not DEFAULT:
1512 raise TypeError(
1513 "autospec creates the mock for you. Can't specify "
1514 "autospec and new."
1515 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001516 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001517 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001518 spec_set = bool(spec_set)
1519 if autospec is True:
1520 autospec = original
1521
Matthew Suozzodccdc502021-04-09 23:45:50 -04001522 if _is_instance_mock(self.target):
1523 raise InvalidSpecError(
1524 f'Cannot autospec attr {self.attribute!r} as the patch '
1525 f'target has already been mocked out. '
1526 f'[target={self.target!r}, attr={autospec!r}]')
1527 if _is_instance_mock(autospec):
1528 target_name = getattr(self.target, '__name__', self.target)
1529 raise InvalidSpecError(
1530 f'Cannot autospec attr {self.attribute!r} from target '
1531 f'{target_name!r} as it has already been mocked out. '
1532 f'[target={self.target!r}, attr={autospec!r}]')
1533
Michael Foord345266a2012-03-14 12:24:34 -07001534 new = create_autospec(autospec, spec_set=spec_set,
1535 _name=self.attribute, **kwargs)
1536 elif kwargs:
1537 # can't set keyword args when we aren't creating the mock
1538 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1539 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1540
1541 new_attr = new
1542
1543 self.temp_original = original
1544 self.is_local = local
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001545 self._exit_stack = contextlib.ExitStack()
1546 try:
1547 setattr(self.target, self.attribute, new_attr)
1548 if self.attribute_name is not None:
1549 extra_args = {}
1550 if self.new is DEFAULT:
1551 extra_args[self.attribute_name] = new
1552 for patching in self.additional_patchers:
1553 arg = self._exit_stack.enter_context(patching)
1554 if patching.new is DEFAULT:
1555 extra_args.update(arg)
1556 return extra_args
Michael Foord345266a2012-03-14 12:24:34 -07001557
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001558 return new
1559 except:
1560 if not self.__exit__(*sys.exc_info()):
1561 raise
Michael Foord345266a2012-03-14 12:24:34 -07001562
Michael Foord50a8c0e2012-03-25 18:57:58 +01001563 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001564 """Undo the patch."""
Michael Foord345266a2012-03-14 12:24:34 -07001565 if self.is_local and self.temp_original is not DEFAULT:
1566 setattr(self.target, self.attribute, self.temp_original)
1567 else:
1568 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001569 if not self.create and (not hasattr(self.target, self.attribute) or
1570 self.attribute in ('__doc__', '__module__',
1571 '__defaults__', '__annotations__',
1572 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001573 # needed for proxy objects like django settings
1574 setattr(self.target, self.attribute, self.temp_original)
1575
1576 del self.temp_original
1577 del self.is_local
1578 del self.target
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001579 exit_stack = self._exit_stack
1580 del self._exit_stack
1581 return exit_stack.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001582
Michael Foordf7c41582012-06-10 20:36:32 +01001583
1584 def start(self):
1585 """Activate a patch, returning any created mock."""
1586 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001587 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001588 return result
1589
1590
1591 def stop(self):
1592 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001593 try:
1594 self._active_patches.remove(self)
1595 except ValueError:
1596 # If the patch hasn't been started this will fail
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001597 return None
Michael Foordebc1a302014-04-15 17:21:08 -04001598
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001599 return self.__exit__(None, None, None)
Michael Foord345266a2012-03-14 12:24:34 -07001600
1601
1602
1603def _get_target(target):
1604 try:
1605 target, attribute = target.rsplit('.', 1)
1606 except (TypeError, ValueError):
1607 raise TypeError("Need a valid target to patch. You supplied: %r" %
1608 (target,))
1609 getter = lambda: _importer(target)
1610 return getter, attribute
1611
1612
1613def _patch_object(
1614 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001615 create=False, spec_set=None, autospec=None,
vabr-gfdb9efc2020-12-14 19:30:09 +01001616 new_callable=None, *, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001617 ):
1618 """
Michael Foord345266a2012-03-14 12:24:34 -07001619 patch the named member (`attribute`) on an object (`target`) with a mock
1620 object.
1621
1622 `patch.object` can be used as a decorator, class decorator or a context
1623 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1624 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1625 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1626 the mock object it creates.
1627
1628 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1629 for choosing which methods to wrap.
1630 """
Elena Oatcd90a522019-12-08 12:14:38 -08001631 if type(target) is str:
1632 raise TypeError(
1633 f"{target!r} must be the actual object to be patched, not a str"
1634 )
Michael Foord345266a2012-03-14 12:24:34 -07001635 getter = lambda: target
1636 return _patch(
1637 getter, attribute, new, spec, create,
vabr-gfdb9efc2020-12-14 19:30:09 +01001638 spec_set, autospec, new_callable, kwargs, unsafe=unsafe
Michael Foord345266a2012-03-14 12:24:34 -07001639 )
1640
1641
Michael Foord50a8c0e2012-03-25 18:57:58 +01001642def _patch_multiple(target, spec=None, create=False, spec_set=None,
1643 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001644 """Perform multiple patches in a single call. It takes the object to be
1645 patched (either as an object or a string to fetch the object by importing)
1646 and keyword arguments for the patches::
1647
1648 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1649 ...
1650
1651 Use `DEFAULT` as the value if you want `patch.multiple` to create
1652 mocks for you. In this case the created mocks are passed into a decorated
1653 function by keyword, and a dictionary is returned when `patch.multiple` is
1654 used as a context manager.
1655
1656 `patch.multiple` can be used as a decorator, class decorator or a context
1657 manager. The arguments `spec`, `spec_set`, `create`,
1658 `autospec` and `new_callable` have the same meaning as for `patch`. These
1659 arguments will be applied to *all* patches done by `patch.multiple`.
1660
1661 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1662 for choosing which methods to wrap.
1663 """
1664 if type(target) is str:
1665 getter = lambda: _importer(target)
1666 else:
1667 getter = lambda: target
1668
1669 if not kwargs:
1670 raise ValueError(
1671 'Must supply at least one keyword argument with patch.multiple'
1672 )
1673 # need to wrap in a list for python 3, where items is a view
1674 items = list(kwargs.items())
1675 attribute, new = items[0]
1676 patcher = _patch(
1677 getter, attribute, new, spec, create, spec_set,
1678 autospec, new_callable, {}
1679 )
1680 patcher.attribute_name = attribute
1681 for attribute, new in items[1:]:
1682 this_patcher = _patch(
1683 getter, attribute, new, spec, create, spec_set,
1684 autospec, new_callable, {}
1685 )
1686 this_patcher.attribute_name = attribute
1687 patcher.additional_patchers.append(this_patcher)
1688 return patcher
1689
1690
1691def patch(
1692 target, new=DEFAULT, spec=None, create=False,
vabr-gfdb9efc2020-12-14 19:30:09 +01001693 spec_set=None, autospec=None, new_callable=None, *, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001694 ):
1695 """
1696 `patch` acts as a function decorator, class decorator or a context
1697 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001698 is patched with a `new` object. When the function/with statement exits
1699 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001700
Mario Corcherof5e7f392019-09-09 15:18:06 +01001701 If `new` is omitted, then the target is replaced with an
1702 `AsyncMock if the patched object is an async function or a
1703 `MagicMock` otherwise. If `patch` is used as a decorator and `new` is
Michael Foord54b3db82012-03-28 15:08:08 +01001704 omitted, the created mock is passed in as an extra argument to the
1705 decorated function. If `patch` is used as a context manager the created
1706 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001707
Michael Foord54b3db82012-03-28 15:08:08 +01001708 `target` should be a string in the form `'package.module.ClassName'`. The
1709 `target` is imported and the specified object replaced with the `new`
1710 object, so the `target` must be importable from the environment you are
1711 calling `patch` from. The target is imported when the decorated function
1712 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001713
1714 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1715 if patch is creating one for you.
1716
1717 In addition you can pass `spec=True` or `spec_set=True`, which causes
1718 patch to pass in the object being mocked as the spec/spec_set object.
1719
1720 `new_callable` allows you to specify a different class, or callable object,
Mario Corcherof5e7f392019-09-09 15:18:06 +01001721 that will be called to create the `new` object. By default `AsyncMock` is
1722 used for async functions and `MagicMock` for the rest.
Michael Foord345266a2012-03-14 12:24:34 -07001723
1724 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001725 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001726 All attributes of the mock will also have the spec of the corresponding
1727 attribute of the object being replaced. Methods and functions being
1728 mocked will have their arguments checked and will raise a `TypeError` if
1729 they are called with the wrong signature. For mocks replacing a class,
1730 their return value (the 'instance') will have the same spec as the class.
1731
1732 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1733 arbitrary object as the spec instead of the one being replaced.
1734
1735 By default `patch` will fail to replace attributes that don't exist. If
1736 you pass in `create=True`, and the attribute doesn't exist, patch will
1737 create the attribute for you when the patched function is called, and
1738 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001739 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001740 default because it can be dangerous. With it switched on you can write
1741 passing tests against APIs that don't actually exist!
1742
1743 Patch can be used as a `TestCase` class decorator. It works by
1744 decorating each test method in the class. This reduces the boilerplate
1745 code when your test methods share a common patchings set. `patch` finds
1746 tests by looking for method names that start with `patch.TEST_PREFIX`.
1747 By default this is `test`, which matches the way `unittest` finds tests.
1748 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1749
1750 Patch can be used as a context manager, with the with statement. Here the
1751 patching applies to the indented block after the with statement. If you
1752 use "as" then the patched object will be bound to the name after the
1753 "as"; very useful if `patch` is creating a mock object for you.
1754
vabr-gfdb9efc2020-12-14 19:30:09 +01001755 Patch will raise a `RuntimeError` if passed some common misspellings of
1756 the arguments autospec and spec_set. Pass the argument `unsafe` with the
1757 value True to disable that check.
1758
Michael Foord345266a2012-03-14 12:24:34 -07001759 `patch` takes arbitrary keyword arguments. These will be passed to
Paulo Henrique Silva40c08092020-01-25 07:53:54 -03001760 `AsyncMock` if the patched object is asynchronous, to `MagicMock`
1761 otherwise or to `new_callable` if specified.
Michael Foord345266a2012-03-14 12:24:34 -07001762
1763 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1764 available for alternate use-cases.
1765 """
1766 getter, attribute = _get_target(target)
1767 return _patch(
1768 getter, attribute, new, spec, create,
vabr-gfdb9efc2020-12-14 19:30:09 +01001769 spec_set, autospec, new_callable, kwargs, unsafe=unsafe
Michael Foord345266a2012-03-14 12:24:34 -07001770 )
1771
1772
1773class _patch_dict(object):
1774 """
1775 Patch a dictionary, or dictionary like object, and restore the dictionary
1776 to its original state after the test.
1777
1778 `in_dict` can be a dictionary or a mapping like container. If it is a
1779 mapping then it must at least support getting, setting and deleting items
1780 plus iterating over keys.
1781
1782 `in_dict` can also be a string specifying the name of the dictionary, which
1783 will then be fetched by importing it.
1784
1785 `values` can be a dictionary of values to set in the dictionary. `values`
1786 can also be an iterable of `(key, value)` pairs.
1787
1788 If `clear` is True then the dictionary will be cleared before the new
1789 values are set.
1790
1791 `patch.dict` can also be called with arbitrary keyword arguments to set
1792 values in the dictionary::
1793
1794 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1795 ...
1796
1797 `patch.dict` can be used as a context manager, decorator or class
1798 decorator. When used as a class decorator `patch.dict` honours
1799 `patch.TEST_PREFIX` for choosing which methods to wrap.
1800 """
1801
1802 def __init__(self, in_dict, values=(), clear=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001803 self.in_dict = in_dict
1804 # support any argument supported by dict(...) constructor
1805 self.values = dict(values)
1806 self.values.update(kwargs)
1807 self.clear = clear
1808 self._original = None
1809
1810
1811 def __call__(self, f):
1812 if isinstance(f, type):
1813 return self.decorate_class(f)
1814 @wraps(f)
1815 def _inner(*args, **kw):
1816 self._patch_dict()
1817 try:
1818 return f(*args, **kw)
1819 finally:
1820 self._unpatch_dict()
1821
1822 return _inner
1823
1824
1825 def decorate_class(self, klass):
1826 for attr in dir(klass):
1827 attr_value = getattr(klass, attr)
1828 if (attr.startswith(patch.TEST_PREFIX) and
1829 hasattr(attr_value, "__call__")):
1830 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1831 decorated = decorator(attr_value)
1832 setattr(klass, attr, decorated)
1833 return klass
1834
1835
1836 def __enter__(self):
1837 """Patch the dict."""
1838 self._patch_dict()
Mario Corchero04530812019-05-28 13:53:31 +01001839 return self.in_dict
Michael Foord345266a2012-03-14 12:24:34 -07001840
1841
1842 def _patch_dict(self):
1843 values = self.values
Xtreaka875ea52019-02-25 00:24:49 +05301844 if isinstance(self.in_dict, str):
1845 self.in_dict = _importer(self.in_dict)
Michael Foord345266a2012-03-14 12:24:34 -07001846 in_dict = self.in_dict
1847 clear = self.clear
1848
1849 try:
1850 original = in_dict.copy()
1851 except AttributeError:
1852 # dict like object with no copy method
1853 # must support iteration over keys
1854 original = {}
1855 for key in in_dict:
1856 original[key] = in_dict[key]
1857 self._original = original
1858
1859 if clear:
1860 _clear_dict(in_dict)
1861
1862 try:
1863 in_dict.update(values)
1864 except AttributeError:
1865 # dict like object with no update method
1866 for key in values:
1867 in_dict[key] = values[key]
1868
1869
1870 def _unpatch_dict(self):
1871 in_dict = self.in_dict
1872 original = self._original
1873
1874 _clear_dict(in_dict)
1875
1876 try:
1877 in_dict.update(original)
1878 except AttributeError:
1879 for key in original:
1880 in_dict[key] = original[key]
1881
1882
1883 def __exit__(self, *args):
1884 """Unpatch the dict."""
Chris Withersdb5e86a2020-01-29 16:24:54 +00001885 if self._original is not None:
1886 self._unpatch_dict()
Michael Foord345266a2012-03-14 12:24:34 -07001887 return False
1888
Mario Corcheroe131c972020-01-24 08:38:33 +00001889
1890 def start(self):
1891 """Activate a patch, returning any created mock."""
1892 result = self.__enter__()
1893 _patch._active_patches.append(self)
1894 return result
1895
1896
1897 def stop(self):
1898 """Stop an active patch."""
1899 try:
1900 _patch._active_patches.remove(self)
1901 except ValueError:
1902 # If the patch hasn't been started this will fail
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001903 return None
Mario Corcheroe131c972020-01-24 08:38:33 +00001904
Serhiy Storchaka4b222c92020-04-11 10:59:24 +03001905 return self.__exit__(None, None, None)
Michael Foord345266a2012-03-14 12:24:34 -07001906
1907
1908def _clear_dict(in_dict):
1909 try:
1910 in_dict.clear()
1911 except AttributeError:
1912 keys = list(in_dict)
1913 for key in keys:
1914 del in_dict[key]
1915
1916
Michael Foordf7c41582012-06-10 20:36:32 +01001917def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001918 """Stop all active patches. LIFO to unroll nested patches."""
1919 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001920 patch.stop()
1921
1922
Michael Foord345266a2012-03-14 12:24:34 -07001923patch.object = _patch_object
1924patch.dict = _patch_dict
1925patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001926patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001927patch.TEST_PREFIX = 'test'
1928
1929magic_methods = (
1930 "lt le gt ge eq ne "
1931 "getitem setitem delitem "
1932 "len contains iter "
1933 "hash str sizeof "
1934 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001935 # we added divmod and rdivmod here instead of numerics
1936 # because there is no idivmod
1937 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001938 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001939 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001940 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001941 "fspath "
Lisa Roach9a7d9512019-09-28 18:42:44 -07001942 "aiter "
Michael Foord345266a2012-03-14 12:24:34 -07001943)
1944
Michael Foordd2623d72014-04-14 11:23:48 -04001945numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001946 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001947)
Michael Foord345266a2012-03-14 12:24:34 -07001948inplace = ' '.join('i%s' % n for n in numerics.split())
1949right = ' '.join('r%s' % n for n in numerics.split())
1950
1951# not including __prepare__, __instancecheck__, __subclasscheck__
1952# (as they are metaclass methods)
1953# __del__ is not supported at all as it causes problems if it exists
1954
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001955_non_defaults = {
1956 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1957 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1958 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1959 '__repr__', '__dir__', '__subclasses__', '__format__',
Lisa Roach8b03f942019-09-19 21:04:18 -07001960 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001961}
Michael Foord345266a2012-03-14 12:24:34 -07001962
1963
1964def _get_method(name, func):
1965 "Turns a callable object (like a mock) into a real function"
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001966 def method(self, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -07001967 return func(self, *args, **kw)
1968 method.__name__ = name
1969 return method
1970
1971
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001972_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001973 '__%s__' % method for method in
1974 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001975}
Michael Foord345266a2012-03-14 12:24:34 -07001976
Lisa Roach77b3b772019-05-20 09:19:53 -07001977# Magic methods used for async `with` statements
1978_async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
Lisa Roach8b03f942019-09-19 21:04:18 -07001979# Magic methods that are only used with async calls but are synchronous functions themselves
1980_sync_async_magics = {"__aiter__"}
1981_async_magics = _async_method_magics | _sync_async_magics
Lisa Roach77b3b772019-05-20 09:19:53 -07001982
Lisa Roach8b03f942019-09-19 21:04:18 -07001983_all_sync_magics = _magics | _non_defaults
1984_all_magics = _all_sync_magics | _async_magics
Michael Foord345266a2012-03-14 12:24:34 -07001985
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001986_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001987 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001988 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001989 '__instancecheck__', '__subclasscheck__',
1990 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001991}
Michael Foord345266a2012-03-14 12:24:34 -07001992
1993_calculate_return_value = {
1994 '__hash__': lambda self: object.__hash__(self),
1995 '__str__': lambda self: object.__str__(self),
1996 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001997 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001998}
1999
2000_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01002001 '__lt__': NotImplemented,
2002 '__gt__': NotImplemented,
2003 '__le__': NotImplemented,
2004 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07002005 '__int__': 1,
2006 '__contains__': False,
2007 '__len__': 0,
2008 '__exit__': False,
2009 '__complex__': 1j,
2010 '__float__': 1.0,
2011 '__bool__': True,
2012 '__index__': 1,
Lisa Roach77b3b772019-05-20 09:19:53 -07002013 '__aexit__': False,
Michael Foord345266a2012-03-14 12:24:34 -07002014}
2015
2016
2017def _get_eq(self):
2018 def __eq__(other):
2019 ret_val = self.__eq__._mock_return_value
2020 if ret_val is not DEFAULT:
2021 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02002022 if self is other:
2023 return True
2024 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07002025 return __eq__
2026
2027def _get_ne(self):
2028 def __ne__(other):
2029 if self.__ne__._mock_return_value is not DEFAULT:
2030 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02002031 if self is other:
2032 return False
2033 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07002034 return __ne__
2035
2036def _get_iter(self):
2037 def __iter__():
2038 ret_val = self.__iter__._mock_return_value
2039 if ret_val is DEFAULT:
2040 return iter([])
2041 # if ret_val was already an iterator, then calling iter on it should
2042 # return the iterator unchanged
2043 return iter(ret_val)
2044 return __iter__
2045
Lisa Roach77b3b772019-05-20 09:19:53 -07002046def _get_async_iter(self):
2047 def __aiter__():
2048 ret_val = self.__aiter__._mock_return_value
2049 if ret_val is DEFAULT:
2050 return _AsyncIterator(iter([]))
2051 return _AsyncIterator(iter(ret_val))
2052 return __aiter__
2053
Michael Foord345266a2012-03-14 12:24:34 -07002054_side_effect_methods = {
2055 '__eq__': _get_eq,
2056 '__ne__': _get_ne,
2057 '__iter__': _get_iter,
Lisa Roach77b3b772019-05-20 09:19:53 -07002058 '__aiter__': _get_async_iter
Michael Foord345266a2012-03-14 12:24:34 -07002059}
2060
2061
2062
2063def _set_return_value(mock, method, name):
2064 fixed = _return_values.get(name, DEFAULT)
2065 if fixed is not DEFAULT:
2066 method.return_value = fixed
2067 return
2068
marcoramirezmxa9187c32019-09-16 11:34:46 -05002069 return_calculator = _calculate_return_value.get(name)
2070 if return_calculator is not None:
2071 return_value = return_calculator(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002072 method.return_value = return_value
2073 return
2074
2075 side_effector = _side_effect_methods.get(name)
2076 if side_effector is not None:
2077 method.side_effect = side_effector(mock)
2078
2079
2080
Lisa Roach9a7d9512019-09-28 18:42:44 -07002081class MagicMixin(Base):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002082 def __init__(self, /, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07002083 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10002084 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07002085 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002086
2087
2088 def _mock_set_magics(self):
Lisa Roach9a7d9512019-09-28 18:42:44 -07002089 orig_magics = _magics | _async_method_magics
2090 these_magics = orig_magics
Michael Foord345266a2012-03-14 12:24:34 -07002091
Łukasz Langaa468db92015-04-13 23:12:42 -07002092 if getattr(self, "_mock_methods", None) is not None:
Lisa Roach9a7d9512019-09-28 18:42:44 -07002093 these_magics = orig_magics.intersection(self._mock_methods)
Michael Foord345266a2012-03-14 12:24:34 -07002094
2095 remove_magics = set()
Lisa Roach9a7d9512019-09-28 18:42:44 -07002096 remove_magics = orig_magics - these_magics
Michael Foord345266a2012-03-14 12:24:34 -07002097
2098 for entry in remove_magics:
2099 if entry in type(self).__dict__:
2100 # remove unneeded magic methods
2101 delattr(self, entry)
2102
2103 # don't overwrite existing attributes if called a second time
2104 these_magics = these_magics - set(type(self).__dict__)
2105
2106 _type = type(self)
2107 for entry in these_magics:
2108 setattr(_type, entry, MagicProxy(entry, self))
2109
2110
2111
2112class NonCallableMagicMock(MagicMixin, NonCallableMock):
2113 """A version of `MagicMock` that isn't callable."""
2114 def mock_add_spec(self, spec, spec_set=False):
2115 """Add a spec to a mock. `spec` can either be an object or a
2116 list of strings. Only attributes on the `spec` can be fetched as
2117 attributes from the mock.
2118
2119 If `spec_set` is True then only attributes on the spec can be set."""
2120 self._mock_add_spec(spec, spec_set)
2121 self._mock_set_magics()
2122
2123
Lisa Roach9a7d9512019-09-28 18:42:44 -07002124class AsyncMagicMixin(MagicMixin):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002125 def __init__(self, /, *args, **kw):
Lisa Roach9a7d9512019-09-28 18:42:44 -07002126 self._mock_set_magics() # make magic work for kwargs in init
Lisa Roach77b3b772019-05-20 09:19:53 -07002127 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)
Lisa Roach9a7d9512019-09-28 18:42:44 -07002128 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002129
Lisa Roach9a7d9512019-09-28 18:42:44 -07002130class MagicMock(MagicMixin, Mock):
Michael Foord345266a2012-03-14 12:24:34 -07002131 """
2132 MagicMock is a subclass of Mock with default implementations
2133 of most of the magic methods. You can use MagicMock without having to
2134 configure the magic methods yourself.
2135
2136 If you use the `spec` or `spec_set` arguments then *only* magic
2137 methods that exist in the spec will be created.
2138
2139 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
2140 """
2141 def mock_add_spec(self, spec, spec_set=False):
2142 """Add a spec to a mock. `spec` can either be an object or a
2143 list of strings. Only attributes on the `spec` can be fetched as
2144 attributes from the mock.
2145
2146 If `spec_set` is True then only attributes on the spec can be set."""
2147 self._mock_add_spec(spec, spec_set)
2148 self._mock_set_magics()
2149
2150
2151
Lisa Roach9a7d9512019-09-28 18:42:44 -07002152class MagicProxy(Base):
Michael Foord345266a2012-03-14 12:24:34 -07002153 def __init__(self, name, parent):
2154 self.name = name
2155 self.parent = parent
2156
Michael Foord345266a2012-03-14 12:24:34 -07002157 def create_mock(self):
2158 entry = self.name
2159 parent = self.parent
2160 m = parent._get_child_mock(name=entry, _new_name=entry,
2161 _new_parent=parent)
2162 setattr(parent, entry, m)
2163 _set_return_value(parent, m, entry)
2164 return m
2165
2166 def __get__(self, obj, _type=None):
2167 return self.create_mock()
2168
2169
Lisa Roach77b3b772019-05-20 09:19:53 -07002170class AsyncMockMixin(Base):
Lisa Roach77b3b772019-05-20 09:19:53 -07002171 await_count = _delegating_property('await_count')
2172 await_args = _delegating_property('await_args')
2173 await_args_list = _delegating_property('await_args_list')
2174
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002175 def __init__(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002176 super().__init__(*args, **kwargs)
Chris Withersc7dd3c72020-01-27 14:11:19 +00002177 # iscoroutinefunction() checks _is_coroutine property to say if an
Lisa Roach77b3b772019-05-20 09:19:53 -07002178 # object is a coroutine. Without this check it looks to see if it is a
2179 # function/method, which in this case it is not (since it is an
2180 # AsyncMock).
2181 # It is set through __dict__ because when spec_set is True, this
2182 # attribute is likely undefined.
2183 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
Lisa Roach77b3b772019-05-20 09:19:53 -07002184 self.__dict__['_mock_await_count'] = 0
2185 self.__dict__['_mock_await_args'] = None
2186 self.__dict__['_mock_await_args_list'] = _CallList()
2187 code_mock = NonCallableMock(spec_set=CodeType)
2188 code_mock.co_flags = inspect.CO_COROUTINE
2189 self.__dict__['__code__'] = code_mock
2190
Jason Fried046442d2019-11-20 16:27:51 -08002191 async def _execute_mock_call(self, /, *args, **kwargs):
Chris Withersdb5e86a2020-01-29 16:24:54 +00002192 # This is nearly just like super(), except for special handling
Jason Fried046442d2019-11-20 16:27:51 -08002193 # of coroutines
Lisa Roach77b3b772019-05-20 09:19:53 -07002194
Karthikeyan Singaravelane553f202020-03-11 20:36:12 +05302195 _call = _Call((args, kwargs), two=True)
Jason Fried046442d2019-11-20 16:27:51 -08002196 self.await_count += 1
2197 self.await_args = _call
2198 self.await_args_list.append(_call)
Lisa Roach77b3b772019-05-20 09:19:53 -07002199
Jason Fried046442d2019-11-20 16:27:51 -08002200 effect = self.side_effect
2201 if effect is not None:
2202 if _is_exception(effect):
2203 raise effect
2204 elif not _callable(effect):
2205 try:
2206 result = next(effect)
2207 except StopIteration:
2208 # It is impossible to propogate a StopIteration
2209 # through coroutines because of PEP 479
2210 raise StopAsyncIteration
2211 if _is_exception(result):
2212 raise result
Chris Withersc7dd3c72020-01-27 14:11:19 +00002213 elif iscoroutinefunction(effect):
Jason Fried046442d2019-11-20 16:27:51 -08002214 result = await effect(*args, **kwargs)
2215 else:
2216 result = effect(*args, **kwargs)
Lisa Roach77b3b772019-05-20 09:19:53 -07002217
Jason Fried046442d2019-11-20 16:27:51 -08002218 if result is not DEFAULT:
2219 return result
2220
2221 if self._mock_return_value is not DEFAULT:
2222 return self.return_value
2223
2224 if self._mock_wraps is not None:
Chris Withersc7dd3c72020-01-27 14:11:19 +00002225 if iscoroutinefunction(self._mock_wraps):
Jason Fried046442d2019-11-20 16:27:51 -08002226 return await self._mock_wraps(*args, **kwargs)
2227 return self._mock_wraps(*args, **kwargs)
2228
2229 return self.return_value
Lisa Roach77b3b772019-05-20 09:19:53 -07002230
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002231 def assert_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002232 """
2233 Assert that the mock was awaited at least once.
2234 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002235 if self.await_count == 0:
2236 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2237 raise AssertionError(msg)
2238
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002239 def assert_awaited_once(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002240 """
2241 Assert that the mock was awaited exactly once.
2242 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002243 if not self.await_count == 1:
2244 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2245 f" Awaited {self.await_count} times.")
2246 raise AssertionError(msg)
2247
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002248 def assert_awaited_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002249 """
2250 Assert that the last await was with the specified arguments.
2251 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002252 if self.await_args is None:
2253 expected = self._format_mock_call_signature(args, kwargs)
2254 raise AssertionError(f'Expected await: {expected}\nNot awaited')
2255
2256 def _error_message():
Xtreak0ae022c2019-05-29 12:32:26 +05302257 msg = self._format_mock_failure_message(args, kwargs, action='await')
Lisa Roach77b3b772019-05-20 09:19:53 -07002258 return msg
2259
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002260 expected = self._call_matcher(_Call((args, kwargs), two=True))
Lisa Roach77b3b772019-05-20 09:19:53 -07002261 actual = self._call_matcher(self.await_args)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002262 if actual != expected:
Lisa Roach77b3b772019-05-20 09:19:53 -07002263 cause = expected if isinstance(expected, Exception) else None
2264 raise AssertionError(_error_message()) from cause
2265
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002266 def assert_awaited_once_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002267 """
2268 Assert that the mock was awaited exactly once and with the specified
2269 arguments.
2270 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002271 if not self.await_count == 1:
2272 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2273 f" Awaited {self.await_count} times.")
2274 raise AssertionError(msg)
2275 return self.assert_awaited_with(*args, **kwargs)
2276
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002277 def assert_any_await(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002278 """
2279 Assert the mock has ever been awaited with the specified arguments.
2280 """
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002281 expected = self._call_matcher(_Call((args, kwargs), two=True))
2282 cause = expected if isinstance(expected, Exception) else None
Lisa Roach77b3b772019-05-20 09:19:53 -07002283 actual = [self._call_matcher(c) for c in self.await_args_list]
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002284 if cause or expected not in _AnyComparer(actual):
Lisa Roach77b3b772019-05-20 09:19:53 -07002285 expected_string = self._format_mock_call_signature(args, kwargs)
2286 raise AssertionError(
2287 '%s await not found' % expected_string
2288 ) from cause
2289
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002290 def assert_has_awaits(self, calls, any_order=False):
Lisa Roach77b3b772019-05-20 09:19:53 -07002291 """
2292 Assert the mock has been awaited with the specified calls.
2293 The :attr:`await_args_list` list is checked for the awaits.
2294
2295 If `any_order` is False (the default) then the awaits must be
2296 sequential. There can be extra calls before or after the
2297 specified awaits.
2298
2299 If `any_order` is True then the awaits can be in any order, but
2300 they must all appear in :attr:`await_args_list`.
2301 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002302 expected = [self._call_matcher(c) for c in calls]
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002303 cause = next((e for e in expected if isinstance(e, Exception)), None)
Lisa Roach77b3b772019-05-20 09:19:53 -07002304 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2305 if not any_order:
2306 if expected not in all_awaits:
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002307 if cause is None:
2308 problem = 'Awaits not found.'
2309 else:
2310 problem = ('Error processing expected awaits.\n'
2311 'Errors: {}').format(
2312 [e if isinstance(e, Exception) else None
2313 for e in expected])
Lisa Roach77b3b772019-05-20 09:19:53 -07002314 raise AssertionError(
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002315 f'{problem}\n'
2316 f'Expected: {_CallList(calls)}\n'
Lisa Roach77b3b772019-05-20 09:19:53 -07002317 f'Actual: {self.await_args_list}'
2318 ) from cause
2319 return
2320
2321 all_awaits = list(all_awaits)
2322
2323 not_found = []
2324 for kall in expected:
2325 try:
2326 all_awaits.remove(kall)
2327 except ValueError:
2328 not_found.append(kall)
2329 if not_found:
2330 raise AssertionError(
2331 '%r not all found in await list' % (tuple(not_found),)
2332 ) from cause
2333
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002334 def assert_not_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002335 """
2336 Assert that the mock was never awaited.
2337 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002338 if self.await_count != 0:
Xtreakff6b2e62019-05-27 18:26:23 +05302339 msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
Lisa Roach77b3b772019-05-20 09:19:53 -07002340 f" Awaited {self.await_count} times.")
2341 raise AssertionError(msg)
2342
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002343 def reset_mock(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002344 """
2345 See :func:`.Mock.reset_mock()`
2346 """
2347 super().reset_mock(*args, **kwargs)
2348 self.await_count = 0
2349 self.await_args = None
2350 self.await_args_list = _CallList()
2351
2352
2353class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2354 """
2355 Enhance :class:`Mock` with features allowing to mock
2356 an async function.
2357
2358 The :class:`AsyncMock` object will behave so the object is
2359 recognized as an async function, and the result of a call is an awaitable:
2360
2361 >>> mock = AsyncMock()
Chris Withersc7dd3c72020-01-27 14:11:19 +00002362 >>> iscoroutinefunction(mock)
Lisa Roach77b3b772019-05-20 09:19:53 -07002363 True
2364 >>> inspect.isawaitable(mock())
2365 True
2366
2367
2368 The result of ``mock()`` is an async function which will have the outcome
2369 of ``side_effect`` or ``return_value``:
2370
2371 - if ``side_effect`` is a function, the async function will return the
2372 result of that function,
2373 - if ``side_effect`` is an exception, the async function will raise the
2374 exception,
2375 - if ``side_effect`` is an iterable, the async function will return the
2376 next value of the iterable, however, if the sequence of result is
2377 exhausted, ``StopIteration`` is raised immediately,
2378 - if ``side_effect`` is not defined, the async function will return the
2379 value defined by ``return_value``, hence, by default, the async function
2380 returns a new :class:`AsyncMock` object.
2381
2382 If the outcome of ``side_effect`` or ``return_value`` is an async function,
2383 the mock async function obtained when the mock object is called will be this
2384 async function itself (and not an async function returning an async
2385 function).
2386
2387 The test author can also specify a wrapped object with ``wraps``. In this
2388 case, the :class:`Mock` object behavior is the same as with an
2389 :class:`.Mock` object: the wrapped object may have methods
2390 defined as async function functions.
2391
Xtreake7cb23b2019-05-21 14:17:17 +05302392 Based on Martin Richard's asynctest project.
Lisa Roach77b3b772019-05-20 09:19:53 -07002393 """
2394
Michael Foord345266a2012-03-14 12:24:34 -07002395
2396class _ANY(object):
2397 "A helper object that compares equal to everything."
2398
2399 def __eq__(self, other):
2400 return True
2401
2402 def __ne__(self, other):
2403 return False
2404
2405 def __repr__(self):
2406 return '<ANY>'
2407
2408ANY = _ANY()
2409
2410
2411
2412def _format_call_signature(name, args, kwargs):
2413 message = '%s(%%s)' % name
2414 formatted_args = ''
2415 args_string = ', '.join([repr(arg) for arg in args])
2416 kwargs_string = ', '.join([
Xtreak9d607062019-09-09 16:25:22 +05302417 '%s=%r' % (key, value) for key, value in kwargs.items()
Michael Foord345266a2012-03-14 12:24:34 -07002418 ])
2419 if args_string:
2420 formatted_args = args_string
2421 if kwargs_string:
2422 if formatted_args:
2423 formatted_args += ', '
2424 formatted_args += kwargs_string
2425
2426 return message % formatted_args
2427
2428
2429
2430class _Call(tuple):
2431 """
2432 A tuple for holding the results of a call to a mock, either in the form
2433 `(args, kwargs)` or `(name, args, kwargs)`.
2434
2435 If args or kwargs are empty then a call tuple will compare equal to
2436 a tuple without those values. This makes comparisons less verbose::
2437
2438 _Call(('name', (), {})) == ('name',)
2439 _Call(('name', (1,), {})) == ('name', (1,))
2440 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2441
2442 The `_Call` object provides a useful shortcut for comparing with call::
2443
2444 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2445 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2446
2447 If the _Call has no name then it will match any name.
2448 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002449 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002450 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002451 args = ()
2452 kwargs = {}
2453 _len = len(value)
2454 if _len == 3:
2455 name, args, kwargs = value
2456 elif _len == 2:
2457 first, second = value
2458 if isinstance(first, str):
2459 name = first
2460 if isinstance(second, tuple):
2461 args = second
2462 else:
2463 kwargs = second
2464 else:
2465 args, kwargs = first, second
2466 elif _len == 1:
2467 value, = value
2468 if isinstance(value, str):
2469 name = value
2470 elif isinstance(value, tuple):
2471 args = value
2472 else:
2473 kwargs = value
2474
2475 if two:
2476 return tuple.__new__(cls, (args, kwargs))
2477
2478 return tuple.__new__(cls, (name, args, kwargs))
2479
2480
2481 def __init__(self, value=(), name=None, parent=None, two=False,
2482 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002483 self._mock_name = name
2484 self._mock_parent = parent
2485 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002486
2487
2488 def __eq__(self, other):
Michael Foord345266a2012-03-14 12:24:34 -07002489 try:
2490 len_other = len(other)
2491 except TypeError:
Serhiy Storchaka662db122019-08-08 08:42:54 +03002492 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07002493
2494 self_name = ''
2495 if len(self) == 2:
2496 self_args, self_kwargs = self
2497 else:
2498 self_name, self_args, self_kwargs = self
2499
Andrew Dunaie63e6172018-12-04 11:08:45 +02002500 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2501 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002502 return False
2503
Michael Foord345266a2012-03-14 12:24:34 -07002504 other_name = ''
2505 if len_other == 0:
2506 other_args, other_kwargs = (), {}
2507 elif len_other == 3:
2508 other_name, other_args, other_kwargs = other
2509 elif len_other == 1:
2510 value, = other
2511 if isinstance(value, tuple):
2512 other_args = value
2513 other_kwargs = {}
2514 elif isinstance(value, str):
2515 other_name = value
2516 other_args, other_kwargs = (), {}
2517 else:
2518 other_args = ()
2519 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002520 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002521 # could be (name, args) or (name, kwargs) or (args, kwargs)
2522 first, second = other
2523 if isinstance(first, str):
2524 other_name = first
2525 if isinstance(second, tuple):
2526 other_args, other_kwargs = second, {}
2527 else:
2528 other_args, other_kwargs = (), second
2529 else:
2530 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002531 else:
2532 return False
Michael Foord345266a2012-03-14 12:24:34 -07002533
2534 if self_name and other_name != self_name:
2535 return False
2536
2537 # this order is important for ANY to work!
2538 return (other_args, other_kwargs) == (self_args, self_kwargs)
2539
2540
Berker Peksagce913872016-03-28 00:30:02 +03002541 __ne__ = object.__ne__
2542
2543
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002544 def __call__(self, /, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002545 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002546 return _Call(('', args, kwargs), name='()')
2547
Andrew Dunaie63e6172018-12-04 11:08:45 +02002548 name = self._mock_name + '()'
2549 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002550
2551
2552 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002553 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002554 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002555 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002556 return _Call(name=name, parent=self, from_kall=False)
2557
2558
blhsing72c35992019-09-11 07:28:06 -07002559 def __getattribute__(self, attr):
2560 if attr in tuple.__dict__:
2561 raise AttributeError
2562 return tuple.__getattribute__(self, attr)
2563
2564
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302565 def _get_call_arguments(self):
2566 if len(self) == 2:
2567 args, kwargs = self
2568 else:
2569 name, args, kwargs = self
2570
2571 return args, kwargs
2572
2573 @property
2574 def args(self):
2575 return self._get_call_arguments()[0]
2576
2577 @property
2578 def kwargs(self):
2579 return self._get_call_arguments()[1]
2580
Michael Foord345266a2012-03-14 12:24:34 -07002581 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002582 if not self._mock_from_kall:
2583 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002584 if name.startswith('()'):
2585 name = 'call%s' % name
2586 return name
2587
2588 if len(self) == 2:
2589 name = 'call'
2590 args, kwargs = self
2591 else:
2592 name, args, kwargs = self
2593 if not name:
2594 name = 'call'
2595 elif not name.startswith('()'):
2596 name = 'call.%s' % name
2597 else:
2598 name = 'call%s' % name
2599 return _format_call_signature(name, args, kwargs)
2600
2601
2602 def call_list(self):
2603 """For a call object that represents multiple calls, `call_list`
2604 returns a list of all the intermediate calls as well as the
2605 final call."""
2606 vals = []
2607 thing = self
2608 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002609 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002610 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002611 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002612 return _CallList(reversed(vals))
2613
2614
2615call = _Call(from_kall=False)
2616
2617
Michael Foord345266a2012-03-14 12:24:34 -07002618def create_autospec(spec, spec_set=False, instance=False, _parent=None,
vabr-gfdb9efc2020-12-14 19:30:09 +01002619 _name=None, *, unsafe=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07002620 """Create a mock object using another object as a spec. Attributes on the
2621 mock will use the corresponding attribute on the `spec` object as their
2622 spec.
2623
2624 Functions or methods being mocked will have their arguments checked
2625 to check that they are called with the correct signature.
2626
2627 If `spec_set` is True then attempting to set attributes that don't exist
2628 on the spec object will raise an `AttributeError`.
2629
2630 If a class is used as a spec then the return value of the mock (the
2631 instance of the class) will have the same spec. You can use a class as the
2632 spec for an instance object by passing `instance=True`. The returned mock
2633 will only be callable if instances of the mock are callable.
2634
vabr-gfdb9efc2020-12-14 19:30:09 +01002635 `create_autospec` will raise a `RuntimeError` if passed some common
2636 misspellings of the arguments autospec and spec_set. Pass the argument
2637 `unsafe` with the value True to disable that check.
2638
Michael Foord345266a2012-03-14 12:24:34 -07002639 `create_autospec` also takes arbitrary keyword arguments that are passed to
2640 the constructor of the created mock."""
2641 if _is_list(spec):
2642 # can't pass a list instance to the mock constructor as it will be
2643 # interpreted as a list of strings
2644 spec = type(spec)
2645
2646 is_type = isinstance(spec, type)
Matthew Suozzodccdc502021-04-09 23:45:50 -04002647 if _is_instance_mock(spec):
2648 raise InvalidSpecError(f'Cannot autospec a Mock object. '
2649 f'[object={spec!r}]')
Xtreakff6b2e62019-05-27 18:26:23 +05302650 is_async_func = _is_async_func(spec)
Michael Foord345266a2012-03-14 12:24:34 -07002651 _kwargs = {'spec': spec}
2652 if spec_set:
2653 _kwargs = {'spec_set': spec}
2654 elif spec is None:
2655 # None we mock with a normal mock without a spec
2656 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002657 if _kwargs and instance:
2658 _kwargs['_spec_as_instance'] = True
vabr-gfdb9efc2020-12-14 19:30:09 +01002659 if not unsafe:
2660 _check_spec_arg_typos(kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07002661
2662 _kwargs.update(kwargs)
2663
2664 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002665 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002666 # descriptors don't have a spec
2667 # because we don't know what type they return
2668 _kwargs = {}
Lisa Roach77b3b772019-05-20 09:19:53 -07002669 elif is_async_func:
2670 if instance:
2671 raise RuntimeError("Instance can not be True when create_autospec "
2672 "is mocking an async function")
2673 Klass = AsyncMock
Michael Foord345266a2012-03-14 12:24:34 -07002674 elif not _callable(spec):
2675 Klass = NonCallableMagicMock
2676 elif is_type and instance and not _instance_callable(spec):
2677 Klass = NonCallableMagicMock
2678
Kushal Das484f8a82014-04-16 01:05:50 +05302679 _name = _kwargs.pop('name', _name)
2680
Michael Foord345266a2012-03-14 12:24:34 -07002681 _new_name = _name
2682 if _parent is None:
2683 # for a top level object no _new_name should be set
2684 _new_name = ''
2685
2686 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2687 name=_name, **_kwargs)
2688
2689 if isinstance(spec, FunctionTypes):
2690 # should only happen at the top level because we don't
2691 # recurse for functions
2692 mock = _set_signature(mock, spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07002693 if is_async_func:
Xtreakff6b2e62019-05-27 18:26:23 +05302694 _setup_async_mock(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002695 else:
2696 _check_signature(spec, mock, is_type, instance)
2697
2698 if _parent is not None and not instance:
2699 _parent._mock_children[_name] = mock
2700
2701 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002702 mock.return_value = create_autospec(spec, spec_set, instance=True,
2703 _name='()', _parent=mock)
2704
2705 for entry in dir(spec):
2706 if _is_magic(entry):
2707 # MagicMock already does the useful magic methods for us
2708 continue
2709
Michael Foord345266a2012-03-14 12:24:34 -07002710 # XXXX do we need a better way of getting attributes without
2711 # triggering code execution (?) Probably not - we need the actual
2712 # object to mock it so we would rather trigger a property than mock
2713 # the property descriptor. Likewise we want to mock out dynamically
2714 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002715 # XXXX what about attributes that raise exceptions other than
2716 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002717 # we could be resilient against it, or catch and propagate the
2718 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002719 try:
2720 original = getattr(spec, entry)
2721 except AttributeError:
2722 continue
Michael Foord345266a2012-03-14 12:24:34 -07002723
2724 kwargs = {'spec': original}
2725 if spec_set:
2726 kwargs = {'spec_set': original}
2727
2728 if not isinstance(original, FunctionTypes):
2729 new = _SpecState(original, spec_set, mock, entry, instance)
2730 mock._mock_children[entry] = new
2731 else:
2732 parent = mock
2733 if isinstance(spec, FunctionTypes):
2734 parent = mock.mock
2735
Michael Foord345266a2012-03-14 12:24:34 -07002736 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002737 kwargs['_eat_self'] = skipfirst
Chris Withersc7dd3c72020-01-27 14:11:19 +00002738 if iscoroutinefunction(original):
Lisa Roach77b3b772019-05-20 09:19:53 -07002739 child_klass = AsyncMock
2740 else:
2741 child_klass = MagicMock
2742 new = child_klass(parent=parent, name=entry, _new_name=entry,
2743 _new_parent=parent,
2744 **kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002745 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002746 _check_signature(original, new, skipfirst=skipfirst)
2747
2748 # so functions created with _set_signature become instance attributes,
2749 # *plus* their underlying mock exists in _mock_children of the parent
2750 # mock. Adding to _mock_children may be unnecessary where we are also
2751 # setting as an instance attribute?
2752 if isinstance(new, FunctionTypes):
2753 setattr(mock, entry, new)
2754
2755 return mock
2756
2757
2758def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002759 """
2760 Return whether we should skip the first argument on spec's `entry`
2761 attribute.
2762 """
Michael Foord345266a2012-03-14 12:24:34 -07002763 if not isinstance(spec, type):
2764 if entry in getattr(spec, '__dict__', {}):
2765 # instance attribute - shouldn't skip
2766 return False
Michael Foord345266a2012-03-14 12:24:34 -07002767 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002768
2769 for klass in spec.__mro__:
2770 result = klass.__dict__.get(entry, DEFAULT)
2771 if result is DEFAULT:
2772 continue
2773 if isinstance(result, (staticmethod, classmethod)):
2774 return False
Carl Friedrich Bolz-Tereicka3276772020-01-29 16:43:37 +01002775 elif isinstance(result, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002776 # Normal method => skip if looked up on type
2777 # (if looked up on instance, self is already skipped)
2778 return is_type
2779 else:
2780 return False
Michael Foord345266a2012-03-14 12:24:34 -07002781
Chris Withersadbf1782019-05-01 23:04:04 +01002782 # function is a dynamically provided attribute
Michael Foord345266a2012-03-14 12:24:34 -07002783 return is_type
2784
2785
Michael Foord345266a2012-03-14 12:24:34 -07002786class _SpecState(object):
2787
2788 def __init__(self, spec, spec_set=False, parent=None,
2789 name=None, ids=None, instance=False):
2790 self.spec = spec
2791 self.ids = ids
2792 self.spec_set = spec_set
2793 self.parent = parent
2794 self.instance = instance
2795 self.name = name
2796
2797
2798FunctionTypes = (
2799 # python function
2800 type(create_autospec),
2801 # instance method
2802 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002803)
2804
Michael Foord345266a2012-03-14 12:24:34 -07002805
Michael Foorda74561a2012-03-25 19:03:13 +01002806file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002807
Michael Foord04cbe0c2013-03-19 17:22:51 -07002808
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002809def _to_stream(read_data):
2810 if isinstance(read_data, bytes):
2811 return io.BytesIO(read_data)
Michael Foord04cbe0c2013-03-19 17:22:51 -07002812 else:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002813 return io.StringIO(read_data)
Michael Foord0dccf652012-03-25 19:11:50 +01002814
Robert Collins5329aaa2015-07-17 20:08:45 +12002815
Michael Foord0dccf652012-03-25 19:11:50 +01002816def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002817 """
2818 A helper function to create a mock to replace the use of `open`. It works
2819 for `open` called directly or used as a context manager.
2820
2821 The `mock` argument is the mock object to configure. If `None` (the
2822 default) then a `MagicMock` will be created for you, with the API limited
2823 to methods or attributes available on standard file handles.
2824
Xtreak71f82a22018-12-20 21:30:21 +05302825 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002826 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002827 """
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002828 _read_data = _to_stream(read_data)
2829 _state = [_read_data, None]
2830
Robert Collinsca647ef2015-07-24 03:48:20 +12002831 def _readlines_side_effect(*args, **kwargs):
2832 if handle.readlines.return_value is not None:
2833 return handle.readlines.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002834 return _state[0].readlines(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002835
2836 def _read_side_effect(*args, **kwargs):
2837 if handle.read.return_value is not None:
2838 return handle.read.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002839 return _state[0].read(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002840
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002841 def _readline_side_effect(*args, **kwargs):
Tony Flury20870232018-09-12 23:21:16 +01002842 yield from _iter_side_effect()
2843 while True:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002844 yield _state[0].readline(*args, **kwargs)
Tony Flury20870232018-09-12 23:21:16 +01002845
2846 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002847 if handle.readline.return_value is not None:
2848 while True:
2849 yield handle.readline.return_value
2850 for line in _state[0]:
2851 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002852
Damien Nadé394119a2019-05-23 12:03:25 +02002853 def _next_side_effect():
2854 if handle.readline.return_value is not None:
2855 return handle.readline.return_value
2856 return next(_state[0])
2857
Michael Foorda74561a2012-03-25 19:03:13 +01002858 global file_spec
2859 if file_spec is None:
2860 import _io
2861 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2862
Michael Foord345266a2012-03-14 12:24:34 -07002863 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002864 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002865
Robert Collinsca647ef2015-07-24 03:48:20 +12002866 handle = MagicMock(spec=file_spec)
2867 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002868
Robert Collinsca647ef2015-07-24 03:48:20 +12002869 handle.write.return_value = None
2870 handle.read.return_value = None
2871 handle.readline.return_value = None
2872 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002873
Robert Collinsca647ef2015-07-24 03:48:20 +12002874 handle.read.side_effect = _read_side_effect
2875 _state[1] = _readline_side_effect()
2876 handle.readline.side_effect = _state[1]
2877 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002878 handle.__iter__.side_effect = _iter_side_effect
Damien Nadé394119a2019-05-23 12:03:25 +02002879 handle.__next__.side_effect = _next_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002880
Robert Collinsca647ef2015-07-24 03:48:20 +12002881 def reset_data(*args, **kwargs):
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002882 _state[0] = _to_stream(read_data)
Robert Collinsca647ef2015-07-24 03:48:20 +12002883 if handle.readline.side_effect == _state[1]:
2884 # Only reset the side effect if the user hasn't overridden it.
2885 _state[1] = _readline_side_effect()
2886 handle.readline.side_effect = _state[1]
2887 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002888
Robert Collinsca647ef2015-07-24 03:48:20 +12002889 mock.side_effect = reset_data
2890 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002891 return mock
2892
2893
2894class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002895 """
2896 A mock intended to be used as a property, or other descriptor, on a class.
2897 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2898 a return value when it is fetched.
2899
2900 Fetching a `PropertyMock` instance from an object calls the mock, with
2901 no args. Setting it calls the mock with the value being set.
2902 """
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002903 def _get_child_mock(self, /, **kwargs):
Michael Foordc2870622012-04-13 16:57:22 +01002904 return MagicMock(**kwargs)
2905
Raymond Hettinger0dac68f2019-08-29 01:27:42 -07002906 def __get__(self, obj, obj_type=None):
Michael Foord345266a2012-03-14 12:24:34 -07002907 return self()
2908 def __set__(self, obj, val):
2909 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002910
2911
2912def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002913 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002914
2915 Given an input Mock, seals it to ensure no further mocks will be generated
2916 when accessing an attribute that was not already defined.
2917
Mario Corchero96200eb2018-10-19 22:57:37 +01002918 The operation recursively seals the mock passed in, meaning that
2919 the mock itself, any mocks generated by accessing one of its attributes,
2920 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002921 """
2922 mock._mock_sealed = True
2923 for attr in dir(mock):
2924 try:
2925 m = getattr(mock, attr)
2926 except AttributeError:
2927 continue
2928 if not isinstance(m, NonCallableMock):
2929 continue
2930 if m._mock_new_parent is mock:
2931 seal(m)
Lisa Roach77b3b772019-05-20 09:19:53 -07002932
2933
Lisa Roach77b3b772019-05-20 09:19:53 -07002934class _AsyncIterator:
2935 """
2936 Wraps an iterator in an asynchronous iterator.
2937 """
2938 def __init__(self, iterator):
2939 self.iterator = iterator
2940 code_mock = NonCallableMock(spec_set=CodeType)
2941 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
2942 self.__dict__['__code__'] = code_mock
2943
Lisa Roach77b3b772019-05-20 09:19:53 -07002944 async def __anext__(self):
2945 try:
2946 return next(self.iterator)
2947 except StopIteration:
2948 pass
2949 raise StopAsyncIteration