blob: 5622917dc37439fc889faf162243ae1b5461c284 [file] [log] [blame]
Michael Foord345266a2012-03-14 12:24:34 -07001# mock.py
2# Test tools for mocking and patching.
Michael Foordc17adf42012-03-14 13:30:29 -07003# Maintained by Michael Foord
4# Backport for other versions of Python available from
Ned Deily9d6d06e2018-06-11 00:45:50 -04005# https://pypi.org/project/mock
Michael Foord345266a2012-03-14 12:24:34 -07006
7__all__ = (
8 'Mock',
9 'MagicMock',
10 'patch',
11 'sentinel',
12 'DEFAULT',
13 'ANY',
14 'call',
15 'create_autospec',
Lisa Roach77b3b772019-05-20 09:19:53 -070016 'AsyncMock',
Michael Foord345266a2012-03-14 12:24:34 -070017 'FILTER_DIR',
18 'NonCallableMock',
19 'NonCallableMagicMock',
20 'mock_open',
21 'PropertyMock',
Mario Corchero552be9d2017-10-17 12:35:11 +010022 'seal',
Michael Foord345266a2012-03-14 12:24:34 -070023)
24
25
Lisa Roach77b3b772019-05-20 09:19:53 -070026import asyncio
Xtreak436c2b02019-05-28 12:37:39 +053027import contextlib
Rémi Lapeyre11a88322019-05-07 12:48:36 +020028import io
Michael Foord345266a2012-03-14 12:24:34 -070029import inspect
30import pprint
31import sys
Michael Foordfddcfa22014-04-14 16:25:20 -040032import builtins
Lisa Roach77b3b772019-05-20 09:19:53 -070033from types import CodeType, ModuleType, MethodType
Petter Strandmark47d94242018-10-28 21:37:10 +010034from unittest.util import safe_repr
Antoine Pitrou5c64df72013-02-03 00:23:58 +010035from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070036
37
Michael Foordfddcfa22014-04-14 16:25:20 -040038_builtins = {name for name in dir(builtins) if not name.startswith('_')}
39
Michael Foord345266a2012-03-14 12:24:34 -070040FILTER_DIR = True
41
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100042# Workaround for issue #12370
43# Without this, the __class__ properties wouldn't be set correctly
44_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070045
Lisa Roach77b3b772019-05-20 09:19:53 -070046def _is_async_obj(obj):
Lisa Roachf1a297a2019-09-10 12:18:40 +010047 if _is_instance_mock(obj) and not isinstance(obj, AsyncMock):
Lisa Roach77b3b772019-05-20 09:19:53 -070048 return False
Lisa Roachf1a297a2019-09-10 12:18:40 +010049 return asyncio.iscoroutinefunction(obj) or inspect.isawaitable(obj)
Lisa Roach77b3b772019-05-20 09:19:53 -070050
51
Xtreakff6b2e62019-05-27 18:26:23 +053052def _is_async_func(func):
53 if getattr(func, '__code__', None):
54 return asyncio.iscoroutinefunction(func)
55 else:
56 return False
57
58
Michael Foord345266a2012-03-14 12:24:34 -070059def _is_instance_mock(obj):
60 # can't use isinstance on Mock objects because they override __class__
61 # The base class for all mocks is NonCallableMock
62 return issubclass(type(obj), NonCallableMock)
63
64
65def _is_exception(obj):
66 return (
Chris Withers49e27f02019-05-01 08:48:44 +010067 isinstance(obj, BaseException) or
68 isinstance(obj, type) and issubclass(obj, BaseException)
Michael Foord345266a2012-03-14 12:24:34 -070069 )
70
71
Xtreak7397cda2019-07-22 13:08:22 +053072def _extract_mock(obj):
73 # Autospecced functions will return a FunctionType with "mock" attribute
74 # which is the actual mock object that needs to be used.
75 if isinstance(obj, FunctionTypes) and hasattr(obj, 'mock'):
76 return obj.mock
77 else:
78 return obj
79
80
Antoine Pitrou5c64df72013-02-03 00:23:58 +010081def _get_signature_object(func, as_instance, eat_self):
82 """
83 Given an arbitrary, possibly callable object, try to create a suitable
84 signature object.
85 Return a (reduced func, signature) tuple, or None.
86 """
87 if isinstance(func, type) and not as_instance:
88 # If it's a type and should be modelled as a type, use __init__.
Chris Withersadbf1782019-05-01 23:04:04 +010089 func = func.__init__
Antoine Pitrou5c64df72013-02-03 00:23:58 +010090 # Skip the `self` argument in __init__
91 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070092 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010093 # If we really want to model an instance of the passed type,
94 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070095 try:
96 func = func.__call__
97 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010098 return None
99 if eat_self:
100 sig_func = partial(func, None)
101 else:
102 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -0700103 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100104 return func, inspect.signature(sig_func)
105 except ValueError:
106 # Certain callable types are not supported by inspect.signature()
107 return None
Michael Foord345266a2012-03-14 12:24:34 -0700108
109
110def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100111 sig = _get_signature_object(func, instance, skipfirst)
112 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -0700113 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100114 func, sig = sig
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300115 def checksig(self, /, *args, **kwargs):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100116 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700117 _copy_func_details(func, checksig)
118 type(mock)._mock_check_sig = checksig
Xtreakf7fa62e2018-12-12 13:24:54 +0530119 type(mock).__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700120
121
122def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700123 # we explicitly don't copy func.__dict__ into this copy as it would
124 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300125 for attribute in (
126 '__name__', '__doc__', '__text_signature__',
127 '__module__', '__defaults__', '__kwdefaults__',
128 ):
129 try:
130 setattr(funcopy, attribute, getattr(func, attribute))
131 except AttributeError:
132 pass
Michael Foord345266a2012-03-14 12:24:34 -0700133
134
135def _callable(obj):
136 if isinstance(obj, type):
137 return True
Xtreak9b218562019-04-22 08:00:23 +0530138 if isinstance(obj, (staticmethod, classmethod, MethodType)):
139 return _callable(obj.__func__)
Michael Foord345266a2012-03-14 12:24:34 -0700140 if getattr(obj, '__call__', None) is not None:
141 return True
142 return False
143
144
145def _is_list(obj):
146 # checks for list or tuples
147 # XXXX badly named!
148 return type(obj) in (list, tuple)
149
150
151def _instance_callable(obj):
152 """Given an object, return True if the object is callable.
153 For classes, return True if instances would be callable."""
154 if not isinstance(obj, type):
155 # already an instance
156 return getattr(obj, '__call__', None) is not None
157
Michael Foorda74b3aa2012-03-14 14:40:22 -0700158 # *could* be broken by a class overriding __mro__ or __dict__ via
159 # a metaclass
160 for base in (obj,) + obj.__mro__:
161 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700162 return True
163 return False
164
165
166def _set_signature(mock, original, instance=False):
167 # creates a function with signature (*args, **kwargs) that delegates to a
168 # mock. It still does signature checking by calling a lambda with the same
169 # signature as the original.
Michael Foord345266a2012-03-14 12:24:34 -0700170
171 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100172 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700173 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700174 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100175 func, sig = result
176 def checksig(*args, **kwargs):
177 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700178 _copy_func_details(func, checksig)
179
180 name = original.__name__
181 if not name.isidentifier():
182 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100183 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700184 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100185 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700186 return mock(*args, **kwargs)""" % name
187 exec (src, context)
188 funcopy = context[name]
Xtreakf7fa62e2018-12-12 13:24:54 +0530189 _setup_func(funcopy, mock, sig)
Michael Foord345266a2012-03-14 12:24:34 -0700190 return funcopy
191
192
Xtreakf7fa62e2018-12-12 13:24:54 +0530193def _setup_func(funcopy, mock, sig):
Michael Foord345266a2012-03-14 12:24:34 -0700194 funcopy.mock = mock
195
Michael Foord345266a2012-03-14 12:24:34 -0700196 def assert_called_with(*args, **kwargs):
197 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700198 def assert_called(*args, **kwargs):
199 return mock.assert_called(*args, **kwargs)
200 def assert_not_called(*args, **kwargs):
201 return mock.assert_not_called(*args, **kwargs)
202 def assert_called_once(*args, **kwargs):
203 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700204 def assert_called_once_with(*args, **kwargs):
205 return mock.assert_called_once_with(*args, **kwargs)
206 def assert_has_calls(*args, **kwargs):
207 return mock.assert_has_calls(*args, **kwargs)
208 def assert_any_call(*args, **kwargs):
209 return mock.assert_any_call(*args, **kwargs)
210 def reset_mock():
211 funcopy.method_calls = _CallList()
212 funcopy.mock_calls = _CallList()
213 mock.reset_mock()
214 ret = funcopy.return_value
215 if _is_instance_mock(ret) and not ret is mock:
216 ret.reset_mock()
217
218 funcopy.called = False
219 funcopy.call_count = 0
220 funcopy.call_args = None
221 funcopy.call_args_list = _CallList()
222 funcopy.method_calls = _CallList()
223 funcopy.mock_calls = _CallList()
224
225 funcopy.return_value = mock.return_value
226 funcopy.side_effect = mock.side_effect
227 funcopy._mock_children = mock._mock_children
228
229 funcopy.assert_called_with = assert_called_with
230 funcopy.assert_called_once_with = assert_called_once_with
231 funcopy.assert_has_calls = assert_has_calls
232 funcopy.assert_any_call = assert_any_call
233 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700234 funcopy.assert_called = assert_called
235 funcopy.assert_not_called = assert_not_called
236 funcopy.assert_called_once = assert_called_once
Xtreakf7fa62e2018-12-12 13:24:54 +0530237 funcopy.__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700238
239 mock._mock_delegate = funcopy
240
241
Xtreakff6b2e62019-05-27 18:26:23 +0530242def _setup_async_mock(mock):
243 mock._is_coroutine = asyncio.coroutines._is_coroutine
244 mock.await_count = 0
245 mock.await_args = None
246 mock.await_args_list = _CallList()
Xtreakff6b2e62019-05-27 18:26:23 +0530247
248 # Mock is not configured yet so the attributes are set
249 # to a function and then the corresponding mock helper function
250 # is called when the helper is accessed similar to _setup_func.
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300251 def wrapper(attr, /, *args, **kwargs):
Xtreakff6b2e62019-05-27 18:26:23 +0530252 return getattr(mock.mock, attr)(*args, **kwargs)
253
254 for attribute in ('assert_awaited',
255 'assert_awaited_once',
256 'assert_awaited_with',
257 'assert_awaited_once_with',
258 'assert_any_await',
259 'assert_has_awaits',
260 'assert_not_awaited'):
261
262 # setattr(mock, attribute, wrapper) causes late binding
263 # hence attribute will always be the last value in the loop
264 # Use partial(wrapper, attribute) to ensure the attribute is bound
265 # correctly.
266 setattr(mock, attribute, partial(wrapper, attribute))
267
268
Michael Foord345266a2012-03-14 12:24:34 -0700269def _is_magic(name):
270 return '__%s__' % name[2:-2] == name
271
272
273class _SentinelObject(object):
274 "A unique, named, sentinel object."
275 def __init__(self, name):
276 self.name = name
277
278 def __repr__(self):
279 return 'sentinel.%s' % self.name
280
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200281 def __reduce__(self):
282 return 'sentinel.%s' % self.name
283
Michael Foord345266a2012-03-14 12:24:34 -0700284
285class _Sentinel(object):
286 """Access attributes to return a named object, usable as a sentinel."""
287 def __init__(self):
288 self._sentinels = {}
289
290 def __getattr__(self, name):
291 if name == '__bases__':
292 # Without this help(unittest.mock) raises an exception
293 raise AttributeError
294 return self._sentinels.setdefault(name, _SentinelObject(name))
295
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200296 def __reduce__(self):
297 return 'sentinel'
298
Michael Foord345266a2012-03-14 12:24:34 -0700299
300sentinel = _Sentinel()
301
302DEFAULT = sentinel.DEFAULT
303_missing = sentinel.MISSING
304_deleted = sentinel.DELETED
305
306
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200307_allowed_names = {
308 'return_value', '_mock_return_value', 'side_effect',
309 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
310 '_mock_name', '_mock_new_name'
311}
Michael Foord345266a2012-03-14 12:24:34 -0700312
313
314def _delegating_property(name):
315 _allowed_names.add(name)
316 _the_name = '_mock_' + name
317 def _get(self, name=name, _the_name=_the_name):
318 sig = self._mock_delegate
319 if sig is None:
320 return getattr(self, _the_name)
321 return getattr(sig, name)
322 def _set(self, value, name=name, _the_name=_the_name):
323 sig = self._mock_delegate
324 if sig is None:
325 self.__dict__[_the_name] = value
326 else:
327 setattr(sig, name, value)
328
329 return property(_get, _set)
330
331
332
333class _CallList(list):
334
335 def __contains__(self, value):
336 if not isinstance(value, list):
337 return list.__contains__(self, value)
338 len_value = len(value)
339 len_self = len(self)
340 if len_value > len_self:
341 return False
342
343 for i in range(0, len_self - len_value + 1):
344 sub_list = self[i:i+len_value]
345 if sub_list == value:
346 return True
347 return False
348
349 def __repr__(self):
350 return pprint.pformat(list(self))
351
352
353def _check_and_set_parent(parent, value, name, new_name):
Xtreak7397cda2019-07-22 13:08:22 +0530354 value = _extract_mock(value)
Xtreak9c3f2842019-02-26 03:16:34 +0530355
Michael Foord345266a2012-03-14 12:24:34 -0700356 if not _is_instance_mock(value):
357 return False
358 if ((value._mock_name or value._mock_new_name) or
359 (value._mock_parent is not None) or
360 (value._mock_new_parent is not None)):
361 return False
362
363 _parent = parent
364 while _parent is not None:
365 # setting a mock (value) as a child or return value of itself
366 # should not modify the mock
367 if _parent is value:
368 return False
369 _parent = _parent._mock_new_parent
370
371 if new_name:
372 value._mock_new_parent = parent
373 value._mock_new_name = new_name
374 if name:
375 value._mock_parent = parent
376 value._mock_name = name
377 return True
378
Michael Foord01bafdc2014-04-14 16:09:42 -0400379# Internal class to identify if we wrapped an iterator object or not.
380class _MockIter(object):
381 def __init__(self, obj):
382 self.obj = iter(obj)
Michael Foord01bafdc2014-04-14 16:09:42 -0400383 def __next__(self):
384 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700385
386class Base(object):
387 _mock_return_value = DEFAULT
388 _mock_side_effect = None
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300389 def __init__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700390 pass
391
392
393
394class NonCallableMock(Base):
395 """A non-callable version of `Mock`"""
396
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300397 def __new__(cls, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700398 # every instance has its own class
399 # so we can create magic methods on the
400 # class without stomping on other mocks
Lisa Roach77b3b772019-05-20 09:19:53 -0700401 bases = (cls,)
Michael Foord14fd9252019-09-13 18:40:56 +0200402 if not issubclass(cls, AsyncMockMixin):
Lisa Roach77b3b772019-05-20 09:19:53 -0700403 # Check if spec is an async object or function
Michael Foord14fd9252019-09-13 18:40:56 +0200404 bound_args = _MOCK_SIG.bind_partial(cls, *args, **kw).arguments
405 spec_arg = bound_args.get('spec_set', bound_args.get('spec'))
406 if spec_arg and _is_async_obj(spec_arg):
407 bases = (AsyncMockMixin, cls)
Lisa Roach77b3b772019-05-20 09:19:53 -0700408 new = type(cls.__name__, bases, {'__doc__': cls.__doc__})
Lisa Roach9a7d9512019-09-28 18:42:44 -0700409 instance = _safe_super(NonCallableMock, cls).__new__(new)
Michael Foord345266a2012-03-14 12:24:34 -0700410 return instance
411
412
413 def __init__(
414 self, spec=None, wraps=None, name=None, spec_set=None,
415 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530416 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700417 ):
418 if _new_parent is None:
419 _new_parent = parent
420
421 __dict__ = self.__dict__
422 __dict__['_mock_parent'] = parent
423 __dict__['_mock_name'] = name
424 __dict__['_mock_new_name'] = _new_name
425 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100426 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700427
428 if spec_set is not None:
429 spec = spec_set
430 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100431 if _eat_self is None:
432 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700433
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100434 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700435
436 __dict__['_mock_children'] = {}
437 __dict__['_mock_wraps'] = wraps
438 __dict__['_mock_delegate'] = None
439
440 __dict__['_mock_called'] = False
441 __dict__['_mock_call_args'] = None
442 __dict__['_mock_call_count'] = 0
443 __dict__['_mock_call_args_list'] = _CallList()
444 __dict__['_mock_mock_calls'] = _CallList()
445
446 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530447 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700448
449 if kwargs:
450 self.configure_mock(**kwargs)
451
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000452 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700453 spec, wraps, name, spec_set, parent,
454 _spec_state
455 )
456
457
458 def attach_mock(self, mock, attribute):
459 """
460 Attach a mock as an attribute of this one, replacing its name and
461 parent. Calls to the attached mock will be recorded in the
462 `method_calls` and `mock_calls` attributes of this one."""
Xtreak7397cda2019-07-22 13:08:22 +0530463 inner_mock = _extract_mock(mock)
464
465 inner_mock._mock_parent = None
466 inner_mock._mock_new_parent = None
467 inner_mock._mock_name = ''
468 inner_mock._mock_new_name = None
Michael Foord345266a2012-03-14 12:24:34 -0700469
470 setattr(self, attribute, mock)
471
472
473 def mock_add_spec(self, spec, spec_set=False):
474 """Add a spec to a mock. `spec` can either be an object or a
475 list of strings. Only attributes on the `spec` can be fetched as
476 attributes from the mock.
477
478 If `spec_set` is True then only attributes on the spec can be set."""
479 self._mock_add_spec(spec, spec_set)
480
481
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100482 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
483 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700484 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100485 _spec_signature = None
Lisa Roach77b3b772019-05-20 09:19:53 -0700486 _spec_asyncs = []
487
488 for attr in dir(spec):
489 if asyncio.iscoroutinefunction(getattr(spec, attr, None)):
490 _spec_asyncs.append(attr)
Michael Foord345266a2012-03-14 12:24:34 -0700491
492 if spec is not None and not _is_list(spec):
493 if isinstance(spec, type):
494 _spec_class = spec
495 else:
Chris Withersadbf1782019-05-01 23:04:04 +0100496 _spec_class = type(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100497 res = _get_signature_object(spec,
498 _spec_as_instance, _eat_self)
499 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700500
501 spec = dir(spec)
502
503 __dict__ = self.__dict__
504 __dict__['_spec_class'] = _spec_class
505 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100506 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700507 __dict__['_mock_methods'] = spec
Lisa Roach77b3b772019-05-20 09:19:53 -0700508 __dict__['_spec_asyncs'] = _spec_asyncs
Michael Foord345266a2012-03-14 12:24:34 -0700509
510 def __get_return_value(self):
511 ret = self._mock_return_value
512 if self._mock_delegate is not None:
513 ret = self._mock_delegate.return_value
514
515 if ret is DEFAULT:
516 ret = self._get_child_mock(
517 _new_parent=self, _new_name='()'
518 )
519 self.return_value = ret
520 return ret
521
522
523 def __set_return_value(self, value):
524 if self._mock_delegate is not None:
525 self._mock_delegate.return_value = value
526 else:
527 self._mock_return_value = value
528 _check_and_set_parent(self, value, None, '()')
529
530 __return_value_doc = "The value to be returned when the mock is called."
531 return_value = property(__get_return_value, __set_return_value,
532 __return_value_doc)
533
534
535 @property
536 def __class__(self):
537 if self._spec_class is None:
538 return type(self)
539 return self._spec_class
540
541 called = _delegating_property('called')
542 call_count = _delegating_property('call_count')
543 call_args = _delegating_property('call_args')
544 call_args_list = _delegating_property('call_args_list')
545 mock_calls = _delegating_property('mock_calls')
546
547
548 def __get_side_effect(self):
549 delegated = self._mock_delegate
550 if delegated is None:
551 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400552 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200553 if (sf is not None and not callable(sf)
554 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400555 sf = _MockIter(sf)
556 delegated.side_effect = sf
557 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700558
559 def __set_side_effect(self, value):
560 value = _try_iter(value)
561 delegated = self._mock_delegate
562 if delegated is None:
563 self._mock_side_effect = value
564 else:
565 delegated.side_effect = value
566
567 side_effect = property(__get_side_effect, __set_side_effect)
568
569
Kushal Das9cd39a12016-06-02 10:20:16 -0700570 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700571 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200572 if visited is None:
573 visited = []
574 if id(self) in visited:
575 return
576 visited.append(id(self))
577
Michael Foord345266a2012-03-14 12:24:34 -0700578 self.called = False
579 self.call_args = None
580 self.call_count = 0
581 self.mock_calls = _CallList()
582 self.call_args_list = _CallList()
583 self.method_calls = _CallList()
584
Kushal Das9cd39a12016-06-02 10:20:16 -0700585 if return_value:
586 self._mock_return_value = DEFAULT
587 if side_effect:
588 self._mock_side_effect = None
589
Michael Foord345266a2012-03-14 12:24:34 -0700590 for child in self._mock_children.values():
Xtreakedeca922018-12-01 15:33:54 +0530591 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100592 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200593 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700594
595 ret = self._mock_return_value
596 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200597 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700598
599
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300600 def configure_mock(self, /, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700601 """Set attributes on the mock through keyword arguments.
602
603 Attributes plus return values and side effects can be set on child
604 mocks using standard dot notation and unpacking a dictionary in the
605 method call:
606
607 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
608 >>> mock.configure_mock(**attrs)"""
609 for arg, val in sorted(kwargs.items(),
610 # we sort on the number of dots so that
611 # attributes are set before we set attributes on
612 # attributes
613 key=lambda entry: entry[0].count('.')):
614 args = arg.split('.')
615 final = args.pop()
616 obj = self
617 for entry in args:
618 obj = getattr(obj, entry)
619 setattr(obj, final, val)
620
621
622 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530623 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700624 raise AttributeError(name)
625 elif self._mock_methods is not None:
626 if name not in self._mock_methods or name in _all_magics:
627 raise AttributeError("Mock object has no attribute %r" % name)
628 elif _is_magic(name):
629 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530630 if not self._mock_unsafe:
631 if name.startswith(('assert', 'assret')):
Zackery Spytzb9b08cd2019-05-08 11:32:24 -0600632 raise AttributeError("Attributes cannot start with 'assert' "
633 "or 'assret'")
Michael Foord345266a2012-03-14 12:24:34 -0700634
635 result = self._mock_children.get(name)
636 if result is _deleted:
637 raise AttributeError(name)
638 elif result is None:
639 wraps = None
640 if self._mock_wraps is not None:
641 # XXXX should we get the attribute without triggering code
642 # execution?
643 wraps = getattr(self._mock_wraps, name)
644
645 result = self._get_child_mock(
646 parent=self, name=name, wraps=wraps, _new_name=name,
647 _new_parent=self
648 )
649 self._mock_children[name] = result
650
651 elif isinstance(result, _SpecState):
652 result = create_autospec(
653 result.spec, result.spec_set, result.instance,
654 result.parent, result.name
655 )
656 self._mock_children[name] = result
657
658 return result
659
660
Mario Corchero552be9d2017-10-17 12:35:11 +0100661 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700662 _name_list = [self._mock_new_name]
663 _parent = self._mock_new_parent
664 last = self
665
666 dot = '.'
667 if _name_list == ['()']:
668 dot = ''
Chris Withersadbf1782019-05-01 23:04:04 +0100669
Michael Foord345266a2012-03-14 12:24:34 -0700670 while _parent is not None:
671 last = _parent
672
673 _name_list.append(_parent._mock_new_name + dot)
674 dot = '.'
675 if _parent._mock_new_name == '()':
676 dot = ''
677
678 _parent = _parent._mock_new_parent
679
Michael Foord345266a2012-03-14 12:24:34 -0700680 _name_list = list(reversed(_name_list))
681 _first = last._mock_name or 'mock'
682 if len(_name_list) > 1:
683 if _name_list[1] not in ('()', '().'):
684 _first += '.'
685 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100686 return ''.join(_name_list)
687
688 def __repr__(self):
689 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700690
691 name_string = ''
692 if name not in ('mock', 'mock.'):
693 name_string = ' name=%r' % name
694
695 spec_string = ''
696 if self._spec_class is not None:
697 spec_string = ' spec=%r'
698 if self._spec_set:
699 spec_string = ' spec_set=%r'
700 spec_string = spec_string % self._spec_class.__name__
701 return "<%s%s%s id='%s'>" % (
702 type(self).__name__,
703 name_string,
704 spec_string,
705 id(self)
706 )
707
708
709 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700710 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100711 if not FILTER_DIR:
712 return object.__dir__(self)
713
Michael Foord345266a2012-03-14 12:24:34 -0700714 extras = self._mock_methods or []
715 from_type = dir(type(self))
716 from_dict = list(self.__dict__)
Mario Corchero0df635c2019-04-30 19:56:36 +0100717 from_child_mocks = [
718 m_name for m_name, m_value in self._mock_children.items()
719 if m_value is not _deleted]
Michael Foord345266a2012-03-14 12:24:34 -0700720
Michael Foord313f85f2012-03-25 18:16:07 +0100721 from_type = [e for e in from_type if not e.startswith('_')]
722 from_dict = [e for e in from_dict if not e.startswith('_') or
723 _is_magic(e)]
Mario Corchero0df635c2019-04-30 19:56:36 +0100724 return sorted(set(extras + from_type + from_dict + from_child_mocks))
Michael Foord345266a2012-03-14 12:24:34 -0700725
726
727 def __setattr__(self, name, value):
728 if name in _allowed_names:
729 # property setters go through here
730 return object.__setattr__(self, name, value)
731 elif (self._spec_set and self._mock_methods is not None and
732 name not in self._mock_methods and
733 name not in self.__dict__):
734 raise AttributeError("Mock object has no attribute '%s'" % name)
735 elif name in _unsupported_magics:
736 msg = 'Attempting to set unsupported magic method %r.' % name
737 raise AttributeError(msg)
738 elif name in _all_magics:
739 if self._mock_methods is not None and name not in self._mock_methods:
740 raise AttributeError("Mock object has no attribute '%s'" % name)
741
742 if not _is_instance_mock(value):
743 setattr(type(self), name, _get_method(name, value))
744 original = value
745 value = lambda *args, **kw: original(self, *args, **kw)
746 else:
747 # only set _new_name and not name so that mock_calls is tracked
748 # but not method calls
749 _check_and_set_parent(self, value, None, name)
750 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100751 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700752 elif name == '__class__':
753 self._spec_class = value
754 return
755 else:
756 if _check_and_set_parent(self, value, name, name):
757 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100758
759 if self._mock_sealed and not hasattr(self, name):
760 mock_name = f'{self._extract_mock_name()}.{name}'
761 raise AttributeError(f'Cannot set {mock_name}')
762
Michael Foord345266a2012-03-14 12:24:34 -0700763 return object.__setattr__(self, name, value)
764
765
766 def __delattr__(self, name):
767 if name in _all_magics and name in type(self).__dict__:
768 delattr(type(self), name)
769 if name not in self.__dict__:
770 # for magic methods that are still MagicProxy objects and
771 # not set on the instance itself
772 return
773
Michael Foord345266a2012-03-14 12:24:34 -0700774 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000775 if name in self.__dict__:
Xtreak830b43d2019-04-14 00:42:33 +0530776 _safe_super(NonCallableMock, self).__delattr__(name)
Pablo Galindo222d3032019-01-21 08:57:46 +0000777 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700778 raise AttributeError(name)
779 if obj is not _missing:
780 del self._mock_children[name]
781 self._mock_children[name] = _deleted
782
783
Michael Foord345266a2012-03-14 12:24:34 -0700784 def _format_mock_call_signature(self, args, kwargs):
785 name = self._mock_name or 'mock'
786 return _format_call_signature(name, args, kwargs)
787
788
Xtreak0ae022c2019-05-29 12:32:26 +0530789 def _format_mock_failure_message(self, args, kwargs, action='call'):
790 message = 'expected %s not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700791 expected_string = self._format_mock_call_signature(args, kwargs)
792 call_args = self.call_args
Michael Foord345266a2012-03-14 12:24:34 -0700793 actual_string = self._format_mock_call_signature(*call_args)
Xtreak0ae022c2019-05-29 12:32:26 +0530794 return message % (action, expected_string, actual_string)
Michael Foord345266a2012-03-14 12:24:34 -0700795
796
Xtreakc9612782019-08-29 11:39:01 +0530797 def _get_call_signature_from_name(self, name):
798 """
799 * If call objects are asserted against a method/function like obj.meth1
800 then there could be no name for the call object to lookup. Hence just
801 return the spec_signature of the method/function being asserted against.
802 * If the name is not empty then remove () and split by '.' to get
803 list of names to iterate through the children until a potential
804 match is found. A child mock is created only during attribute access
805 so if we get a _SpecState then no attributes of the spec were accessed
806 and can be safely exited.
807 """
808 if not name:
809 return self._spec_signature
810
811 sig = None
812 names = name.replace('()', '').split('.')
813 children = self._mock_children
814
815 for name in names:
816 child = children.get(name)
817 if child is None or isinstance(child, _SpecState):
818 break
819 else:
820 children = child._mock_children
821 sig = child._spec_signature
822
823 return sig
824
825
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100826 def _call_matcher(self, _call):
827 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000828 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100829 comparison key suitable for matching with other calls.
830 This is a best effort method which relies on the spec's signature,
831 if available, or falls back on the arguments themselves.
832 """
Xtreakc9612782019-08-29 11:39:01 +0530833
834 if isinstance(_call, tuple) and len(_call) > 2:
835 sig = self._get_call_signature_from_name(_call[0])
836 else:
837 sig = self._spec_signature
838
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100839 if sig is not None:
840 if len(_call) == 2:
841 name = ''
842 args, kwargs = _call
843 else:
844 name, args, kwargs = _call
845 try:
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700846 bound_call = sig.bind(*args, **kwargs)
847 return call(name, bound_call.args, bound_call.kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100848 except TypeError as e:
849 return e.with_traceback(None)
850 else:
851 return _call
852
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300853 def assert_not_called(self):
Kushal Das8af9db32014-04-17 01:36:14 +0530854 """assert that the mock was never called.
855 """
Kushal Das8af9db32014-04-17 01:36:14 +0530856 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100857 msg = ("Expected '%s' to not have been called. Called %s times.%s"
858 % (self._mock_name or 'mock',
859 self.call_count,
860 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530861 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100862
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300863 def assert_called(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100864 """assert that the mock was called at least once
865 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100866 if self.call_count == 0:
867 msg = ("Expected '%s' to have been called." %
Abraham Toriz Cruz5f5f11f2019-09-17 06:16:08 -0500868 (self._mock_name or 'mock'))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100869 raise AssertionError(msg)
870
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300871 def assert_called_once(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100872 """assert that the mock was called only once.
873 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100874 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100875 msg = ("Expected '%s' to have been called once. Called %s times.%s"
876 % (self._mock_name or 'mock',
877 self.call_count,
878 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100879 raise AssertionError(msg)
880
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300881 def assert_called_with(self, /, *args, **kwargs):
Rémi Lapeyref5896a02019-08-29 08:15:53 +0200882 """assert that the last call was made with the specified arguments.
Michael Foord345266a2012-03-14 12:24:34 -0700883
884 Raises an AssertionError if the args and keyword args passed in are
885 different to the last call to the mock."""
Michael Foord345266a2012-03-14 12:24:34 -0700886 if self.call_args is None:
887 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800888 actual = 'not called.'
889 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
890 % (expected, actual))
891 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700892
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100893 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700894 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100895 return msg
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700896 expected = self._call_matcher(_Call((args, kwargs), two=True))
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100897 actual = self._call_matcher(self.call_args)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700898 if actual != expected:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100899 cause = expected if isinstance(expected, Exception) else None
900 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700901
902
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300903 def assert_called_once_with(self, /, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100904 """assert that the mock was called exactly once and that that call was
905 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700906 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100907 msg = ("Expected '%s' to be called once. Called %s times.%s"
908 % (self._mock_name or 'mock',
909 self.call_count,
910 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700911 raise AssertionError(msg)
912 return self.assert_called_with(*args, **kwargs)
913
914
915 def assert_has_calls(self, calls, any_order=False):
916 """assert the mock has been called with the specified calls.
917 The `mock_calls` list is checked for the calls.
918
919 If `any_order` is False (the default) then the calls must be
920 sequential. There can be extra calls before or after the
921 specified calls.
922
923 If `any_order` is True then the calls can be in any order, but
924 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100925 expected = [self._call_matcher(c) for c in calls]
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400926 cause = next((e for e in expected if isinstance(e, Exception)), None)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100927 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700928 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100929 if expected not in all_calls:
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400930 if cause is None:
931 problem = 'Calls not found.'
932 else:
933 problem = ('Error processing expected calls.\n'
934 'Errors: {}').format(
935 [e if isinstance(e, Exception) else None
936 for e in expected])
Michael Foord345266a2012-03-14 12:24:34 -0700937 raise AssertionError(
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -0400938 f'{problem}\n'
Samuel Freilich2180f6b2019-09-24 18:04:29 -0400939 f'Expected: {_CallList(calls)}'
940 f'{self._calls_repr(prefix="Actual").rstrip(".")}'
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100941 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700942 return
943
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100944 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700945
946 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100947 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700948 try:
949 all_calls.remove(kall)
950 except ValueError:
951 not_found.append(kall)
952 if not_found:
953 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400954 '%r does not contain all of %r in its call list, '
955 'found %r instead' % (self._mock_name or 'mock',
956 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100957 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700958
959
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300960 def assert_any_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700961 """assert the mock has been called with the specified arguments.
962
963 The assert passes if the mock has *ever* been called, unlike
964 `assert_called_with` and `assert_called_once_with` that only pass if
965 the call is the most recent one."""
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700966 expected = self._call_matcher(_Call((args, kwargs), two=True))
967 cause = expected if isinstance(expected, Exception) else None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100968 actual = [self._call_matcher(c) for c in self.call_args_list]
Elizabeth Useltond6a9d172019-09-13 08:54:32 -0700969 if cause or expected not in _AnyComparer(actual):
Michael Foord345266a2012-03-14 12:24:34 -0700970 expected_string = self._format_mock_call_signature(args, kwargs)
971 raise AssertionError(
972 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100973 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700974
975
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300976 def _get_child_mock(self, /, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700977 """Create the child mocks for attributes and return value.
978 By default child mocks will be the same type as the parent.
979 Subclasses of Mock may want to override this to customize the way
980 child mocks are made.
981
982 For non-callable mocks the callable variant will be used (rather than
983 any custom subclass)."""
Lisa Roach77b3b772019-05-20 09:19:53 -0700984 _new_name = kw.get("_new_name")
985 if _new_name in self.__dict__['_spec_asyncs']:
986 return AsyncMock(**kw)
987
Michael Foord345266a2012-03-14 12:24:34 -0700988 _type = type(self)
Lisa Roach77b3b772019-05-20 09:19:53 -0700989 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
Lisa Roach9a7d9512019-09-28 18:42:44 -0700990 # Any asynchronous magic becomes an AsyncMock
Lisa Roach77b3b772019-05-20 09:19:53 -0700991 klass = AsyncMock
Lisa Roach8b03f942019-09-19 21:04:18 -0700992 elif issubclass(_type, AsyncMockMixin):
Lisa Roach3667e1e2019-09-29 21:56:47 -0700993 if (_new_name in _all_sync_magics or
994 self._mock_methods and _new_name in self._mock_methods):
995 # Any synchronous method on AsyncMock becomes a MagicMock
Lisa Roach9a7d9512019-09-28 18:42:44 -0700996 klass = MagicMock
997 else:
998 klass = AsyncMock
Lisa Roach8b03f942019-09-19 21:04:18 -0700999 elif not issubclass(_type, CallableMixin):
Michael Foord345266a2012-03-14 12:24:34 -07001000 if issubclass(_type, NonCallableMagicMock):
1001 klass = MagicMock
Lisa Roach9a7d9512019-09-28 18:42:44 -07001002 elif issubclass(_type, NonCallableMock):
Michael Foord345266a2012-03-14 12:24:34 -07001003 klass = Mock
1004 else:
1005 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +01001006
1007 if self._mock_sealed:
1008 attribute = "." + kw["name"] if "name" in kw else "()"
1009 mock_name = self._extract_mock_name() + attribute
1010 raise AttributeError(mock_name)
1011
Michael Foord345266a2012-03-14 12:24:34 -07001012 return klass(**kw)
1013
1014
Petter Strandmark47d94242018-10-28 21:37:10 +01001015 def _calls_repr(self, prefix="Calls"):
1016 """Renders self.mock_calls as a string.
1017
1018 Example: "\nCalls: [call(1), call(2)]."
1019
1020 If self.mock_calls is empty, an empty string is returned. The
1021 output will be truncated if very long.
1022 """
1023 if not self.mock_calls:
1024 return ""
1025 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
1026
1027
Michael Foord14fd9252019-09-13 18:40:56 +02001028_MOCK_SIG = inspect.signature(NonCallableMock.__init__)
1029
1030
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07001031class _AnyComparer(list):
1032 """A list which checks if it contains a call which may have an
1033 argument of ANY, flipping the components of item and self from
1034 their traditional locations so that ANY is guaranteed to be on
1035 the left."""
1036 def __contains__(self, item):
1037 for _call in self:
1038 if len(item) != len(_call):
1039 continue
1040 if all([
1041 expected == actual
1042 for expected, actual in zip(item, _call)
1043 ]):
1044 return True
1045 return False
1046
Michael Foord345266a2012-03-14 12:24:34 -07001047
1048def _try_iter(obj):
1049 if obj is None:
1050 return obj
1051 if _is_exception(obj):
1052 return obj
1053 if _callable(obj):
1054 return obj
1055 try:
1056 return iter(obj)
1057 except TypeError:
1058 # XXXX backwards compatibility
1059 # but this will blow up on first call - so maybe we should fail early?
1060 return obj
1061
1062
Michael Foord345266a2012-03-14 12:24:34 -07001063class CallableMixin(Base):
1064
1065 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
1066 wraps=None, name=None, spec_set=None, parent=None,
1067 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
1068 self.__dict__['_mock_return_value'] = return_value
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001069 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -07001070 spec, wraps, name, spec_set, parent,
1071 _spec_state, _new_name, _new_parent, **kwargs
1072 )
1073
1074 self.side_effect = side_effect
1075
1076
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001077 def _mock_check_sig(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001078 # stub method that can be replaced with one with a specific signature
1079 pass
1080
1081
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001082 def __call__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001083 # can't use self in-case a function / method we are mocking uses self
1084 # in the signature
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001085 self._mock_check_sig(*args, **kwargs)
Lisa Roachef048512019-09-23 20:49:40 -07001086 self._increment_mock_call(*args, **kwargs)
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001087 return self._mock_call(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001088
1089
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001090 def _mock_call(self, /, *args, **kwargs):
Lisa Roachef048512019-09-23 20:49:40 -07001091 return self._execute_mock_call(*args, **kwargs)
1092
1093 def _increment_mock_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001094 self.called = True
1095 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001096
Chris Withers8ca0fa92018-12-03 21:31:37 +00001097 # handle call_args
Lisa Roachef048512019-09-23 20:49:40 -07001098 # needs to be set here so assertions on call arguments pass before
1099 # execution in the case of awaited calls
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001100 _call = _Call((args, kwargs), two=True)
1101 self.call_args = _call
1102 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -07001103
Chris Withers8ca0fa92018-12-03 21:31:37 +00001104 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001105 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +00001106 method_call_name = self._mock_name
1107
1108 # initial stuff for mock_calls:
1109 mock_call_name = self._mock_new_name
1110 is_a_call = mock_call_name == '()'
1111 self.mock_calls.append(_Call(('', args, kwargs)))
1112
1113 # follow up the chain of mocks:
1114 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001115 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001116
Chris Withers8ca0fa92018-12-03 21:31:37 +00001117 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001118 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001119 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001120 do_method_calls = _new_parent._mock_parent is not None
1121 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001122 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001123
Chris Withers8ca0fa92018-12-03 21:31:37 +00001124 # handle mock_calls:
1125 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001126 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001127
1128 if _new_parent._mock_new_name:
1129 if is_a_call:
1130 dot = ''
1131 else:
1132 dot = '.'
1133 is_a_call = _new_parent._mock_new_name == '()'
1134 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1135
1136 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001137 _new_parent = _new_parent._mock_new_parent
1138
Lisa Roachef048512019-09-23 20:49:40 -07001139 def _execute_mock_call(self, /, *args, **kwargs):
Jason Fried046442d2019-11-20 16:27:51 -08001140 # separate from _increment_mock_call so that awaited functions are
1141 # executed separately from their call, also AsyncMock overrides this method
Lisa Roachef048512019-09-23 20:49:40 -07001142
Michael Foord345266a2012-03-14 12:24:34 -07001143 effect = self.side_effect
1144 if effect is not None:
1145 if _is_exception(effect):
1146 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001147 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001148 result = next(effect)
1149 if _is_exception(result):
1150 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001151 else:
1152 result = effect(*args, **kwargs)
1153
1154 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001155 return result
Michael Foord345266a2012-03-14 12:24:34 -07001156
Mario Corcherof05df0a2018-12-08 11:25:02 +00001157 if self._mock_return_value is not DEFAULT:
1158 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001159
Mario Corcherof05df0a2018-12-08 11:25:02 +00001160 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001161 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001162
1163 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001164
1165
1166
1167class Mock(CallableMixin, NonCallableMock):
1168 """
1169 Create a new `Mock` object. `Mock` takes several optional arguments
1170 that specify the behaviour of the Mock object:
1171
1172 * `spec`: This can be either a list of strings or an existing object (a
1173 class or instance) that acts as the specification for the mock object. If
1174 you pass in an object then a list of strings is formed by calling dir on
1175 the object (excluding unsupported magic attributes and methods). Accessing
1176 any attribute not in this list will raise an `AttributeError`.
1177
1178 If `spec` is an object (rather than a list of strings) then
1179 `mock.__class__` returns the class of the spec object. This allows mocks
1180 to pass `isinstance` tests.
1181
1182 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1183 or get an attribute on the mock that isn't on the object passed as
1184 `spec_set` will raise an `AttributeError`.
1185
1186 * `side_effect`: A function to be called whenever the Mock is called. See
1187 the `side_effect` attribute. Useful for raising exceptions or
1188 dynamically changing return values. The function is called with the same
1189 arguments as the mock, and unless it returns `DEFAULT`, the return
1190 value of this function is used as the return value.
1191
Michael Foord2cd48732012-04-21 15:52:11 +01001192 If `side_effect` is an iterable then each call to the mock will return
1193 the next value from the iterable. If any of the members of the iterable
1194 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001195
Michael Foord345266a2012-03-14 12:24:34 -07001196 * `return_value`: The value returned when the mock is called. By default
1197 this is a new Mock (created on first access). See the
1198 `return_value` attribute.
1199
Michael Foord0682a0c2012-04-13 20:51:20 +01001200 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1201 calling the Mock will pass the call through to the wrapped object
1202 (returning the real result). Attribute access on the mock will return a
1203 Mock object that wraps the corresponding attribute of the wrapped object
1204 (so attempting to access an attribute that doesn't exist will raise an
1205 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001206
1207 If the mock has an explicit `return_value` set then calls are not passed
1208 to the wrapped object and the `return_value` is returned instead.
1209
1210 * `name`: If the mock has a name then it will be used in the repr of the
1211 mock. This can be useful for debugging. The name is propagated to child
1212 mocks.
1213
1214 Mocks can also be called with arbitrary keyword arguments. These will be
1215 used to set attributes on the mock after it is created.
1216 """
1217
1218
Michael Foord345266a2012-03-14 12:24:34 -07001219def _dot_lookup(thing, comp, import_path):
1220 try:
1221 return getattr(thing, comp)
1222 except AttributeError:
1223 __import__(import_path)
1224 return getattr(thing, comp)
1225
1226
1227def _importer(target):
1228 components = target.split('.')
1229 import_path = components.pop(0)
1230 thing = __import__(import_path)
1231
1232 for comp in components:
1233 import_path += ".%s" % comp
1234 thing = _dot_lookup(thing, comp, import_path)
1235 return thing
1236
1237
1238def _is_started(patcher):
1239 # XXXX horrible
1240 return hasattr(patcher, 'is_local')
1241
1242
1243class _patch(object):
1244
1245 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001246 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001247
1248 def __init__(
1249 self, getter, attribute, new, spec, create,
1250 spec_set, autospec, new_callable, kwargs
1251 ):
1252 if new_callable is not None:
1253 if new is not DEFAULT:
1254 raise ValueError(
1255 "Cannot use 'new' and 'new_callable' together"
1256 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001257 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001258 raise ValueError(
1259 "Cannot use 'autospec' and 'new_callable' together"
1260 )
1261
1262 self.getter = getter
1263 self.attribute = attribute
1264 self.new = new
1265 self.new_callable = new_callable
1266 self.spec = spec
1267 self.create = create
1268 self.has_local = False
1269 self.spec_set = spec_set
1270 self.autospec = autospec
1271 self.kwargs = kwargs
1272 self.additional_patchers = []
1273
1274
1275 def copy(self):
1276 patcher = _patch(
1277 self.getter, self.attribute, self.new, self.spec,
1278 self.create, self.spec_set,
1279 self.autospec, self.new_callable, self.kwargs
1280 )
1281 patcher.attribute_name = self.attribute_name
1282 patcher.additional_patchers = [
1283 p.copy() for p in self.additional_patchers
1284 ]
1285 return patcher
1286
1287
1288 def __call__(self, func):
1289 if isinstance(func, type):
1290 return self.decorate_class(func)
Xtreak436c2b02019-05-28 12:37:39 +05301291 if inspect.iscoroutinefunction(func):
1292 return self.decorate_async_callable(func)
Michael Foord345266a2012-03-14 12:24:34 -07001293 return self.decorate_callable(func)
1294
1295
1296 def decorate_class(self, klass):
1297 for attr in dir(klass):
1298 if not attr.startswith(patch.TEST_PREFIX):
1299 continue
1300
1301 attr_value = getattr(klass, attr)
1302 if not hasattr(attr_value, "__call__"):
1303 continue
1304
1305 patcher = self.copy()
1306 setattr(klass, attr, patcher(attr_value))
1307 return klass
1308
1309
Xtreak436c2b02019-05-28 12:37:39 +05301310 @contextlib.contextmanager
1311 def decoration_helper(self, patched, args, keywargs):
1312 extra_args = []
1313 entered_patchers = []
1314 patching = None
1315
1316 exc_info = tuple()
1317 try:
1318 for patching in patched.patchings:
1319 arg = patching.__enter__()
1320 entered_patchers.append(patching)
1321 if patching.attribute_name is not None:
1322 keywargs.update(arg)
1323 elif patching.new is DEFAULT:
1324 extra_args.append(arg)
1325
1326 args += tuple(extra_args)
1327 yield (args, keywargs)
1328 except:
1329 if (patching not in entered_patchers and
1330 _is_started(patching)):
1331 # the patcher may have been started, but an exception
1332 # raised whilst entering one of its additional_patchers
1333 entered_patchers.append(patching)
1334 # Pass the exception to __exit__
1335 exc_info = sys.exc_info()
1336 # re-raise the exception
1337 raise
1338 finally:
1339 for patching in reversed(entered_patchers):
1340 patching.__exit__(*exc_info)
1341
1342
Michael Foord345266a2012-03-14 12:24:34 -07001343 def decorate_callable(self, func):
Xtreak436c2b02019-05-28 12:37:39 +05301344 # NB. Keep the method in sync with decorate_async_callable()
Michael Foord345266a2012-03-14 12:24:34 -07001345 if hasattr(func, 'patchings'):
1346 func.patchings.append(self)
1347 return func
1348
1349 @wraps(func)
1350 def patched(*args, **keywargs):
Xtreak436c2b02019-05-28 12:37:39 +05301351 with self.decoration_helper(patched,
1352 args,
1353 keywargs) as (newargs, newkeywargs):
1354 return func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001355
Xtreak436c2b02019-05-28 12:37:39 +05301356 patched.patchings = [self]
1357 return patched
Michael Foord345266a2012-03-14 12:24:34 -07001358
Xtreak436c2b02019-05-28 12:37:39 +05301359
1360 def decorate_async_callable(self, func):
1361 # NB. Keep the method in sync with decorate_callable()
1362 if hasattr(func, 'patchings'):
1363 func.patchings.append(self)
1364 return func
1365
1366 @wraps(func)
1367 async def patched(*args, **keywargs):
1368 with self.decoration_helper(patched,
1369 args,
1370 keywargs) as (newargs, newkeywargs):
1371 return await func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001372
1373 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001374 return patched
1375
1376
1377 def get_original(self):
1378 target = self.getter()
1379 name = self.attribute
1380
1381 original = DEFAULT
1382 local = False
1383
1384 try:
1385 original = target.__dict__[name]
1386 except (AttributeError, KeyError):
1387 original = getattr(target, name, DEFAULT)
1388 else:
1389 local = True
1390
Michael Foordfddcfa22014-04-14 16:25:20 -04001391 if name in _builtins and isinstance(target, ModuleType):
1392 self.create = True
1393
Michael Foord345266a2012-03-14 12:24:34 -07001394 if not self.create and original is DEFAULT:
1395 raise AttributeError(
1396 "%s does not have the attribute %r" % (target, name)
1397 )
1398 return original, local
1399
1400
1401 def __enter__(self):
1402 """Perform the patch."""
1403 new, spec, spec_set = self.new, self.spec, self.spec_set
1404 autospec, kwargs = self.autospec, self.kwargs
1405 new_callable = self.new_callable
1406 self.target = self.getter()
1407
Michael Foord50a8c0e2012-03-25 18:57:58 +01001408 # normalise False to None
1409 if spec is False:
1410 spec = None
1411 if spec_set is False:
1412 spec_set = None
1413 if autospec is False:
1414 autospec = None
1415
1416 if spec is not None and autospec is not None:
1417 raise TypeError("Can't specify spec and autospec")
1418 if ((spec is not None or autospec is not None) and
1419 spec_set not in (True, None)):
1420 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1421
Michael Foord345266a2012-03-14 12:24:34 -07001422 original, local = self.get_original()
1423
Michael Foord50a8c0e2012-03-25 18:57:58 +01001424 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001425 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001426 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001427 # set spec to the object we are replacing
1428 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001429 if spec_set is True:
1430 spec_set = original
1431 spec = None
1432 elif spec is not None:
1433 if spec_set is True:
1434 spec_set = spec
1435 spec = None
1436 elif spec_set is True:
1437 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001438
Michael Foord50a8c0e2012-03-25 18:57:58 +01001439 if spec is not None or spec_set is not None:
1440 if original is DEFAULT:
1441 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001442 if isinstance(original, type):
1443 # If we're patching out a class and there is a spec
1444 inherit = True
Lisa Roach77b3b772019-05-20 09:19:53 -07001445 if spec is None and _is_async_obj(original):
1446 Klass = AsyncMock
1447 else:
1448 Klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -07001449 _kwargs = {}
1450 if new_callable is not None:
1451 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001452 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001453 this_spec = spec
1454 if spec_set is not None:
1455 this_spec = spec_set
1456 if _is_list(this_spec):
1457 not_callable = '__call__' not in this_spec
1458 else:
1459 not_callable = not callable(this_spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07001460 if _is_async_obj(this_spec):
1461 Klass = AsyncMock
1462 elif not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001463 Klass = NonCallableMagicMock
1464
1465 if spec is not None:
1466 _kwargs['spec'] = spec
1467 if spec_set is not None:
1468 _kwargs['spec_set'] = spec_set
1469
1470 # add a name to mocks
1471 if (isinstance(Klass, type) and
1472 issubclass(Klass, NonCallableMock) and self.attribute):
1473 _kwargs['name'] = self.attribute
1474
1475 _kwargs.update(kwargs)
1476 new = Klass(**_kwargs)
1477
1478 if inherit and _is_instance_mock(new):
1479 # we can only tell if the instance should be callable if the
1480 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001481 this_spec = spec
1482 if spec_set is not None:
1483 this_spec = spec_set
1484 if (not _is_list(this_spec) and not
1485 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001486 Klass = NonCallableMagicMock
1487
1488 _kwargs.pop('name')
1489 new.return_value = Klass(_new_parent=new, _new_name='()',
1490 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001491 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001492 # spec is ignored, new *must* be default, spec_set is treated
1493 # as a boolean. Should we check spec is not None and that spec_set
1494 # is a bool?
1495 if new is not DEFAULT:
1496 raise TypeError(
1497 "autospec creates the mock for you. Can't specify "
1498 "autospec and new."
1499 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001500 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001501 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001502 spec_set = bool(spec_set)
1503 if autospec is True:
1504 autospec = original
1505
1506 new = create_autospec(autospec, spec_set=spec_set,
1507 _name=self.attribute, **kwargs)
1508 elif kwargs:
1509 # can't set keyword args when we aren't creating the mock
1510 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1511 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1512
1513 new_attr = new
1514
1515 self.temp_original = original
1516 self.is_local = local
1517 setattr(self.target, self.attribute, new_attr)
1518 if self.attribute_name is not None:
1519 extra_args = {}
1520 if self.new is DEFAULT:
1521 extra_args[self.attribute_name] = new
1522 for patching in self.additional_patchers:
1523 arg = patching.__enter__()
1524 if patching.new is DEFAULT:
1525 extra_args.update(arg)
1526 return extra_args
1527
1528 return new
1529
1530
Michael Foord50a8c0e2012-03-25 18:57:58 +01001531 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001532 """Undo the patch."""
1533 if not _is_started(self):
Xtreak02b84cb2019-03-29 02:38:43 +05301534 return
Michael Foord345266a2012-03-14 12:24:34 -07001535
1536 if self.is_local and self.temp_original is not DEFAULT:
1537 setattr(self.target, self.attribute, self.temp_original)
1538 else:
1539 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001540 if not self.create and (not hasattr(self.target, self.attribute) or
1541 self.attribute in ('__doc__', '__module__',
1542 '__defaults__', '__annotations__',
1543 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001544 # needed for proxy objects like django settings
1545 setattr(self.target, self.attribute, self.temp_original)
1546
1547 del self.temp_original
1548 del self.is_local
1549 del self.target
1550 for patcher in reversed(self.additional_patchers):
1551 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001552 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001553
Michael Foordf7c41582012-06-10 20:36:32 +01001554
1555 def start(self):
1556 """Activate a patch, returning any created mock."""
1557 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001558 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001559 return result
1560
1561
1562 def stop(self):
1563 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001564 try:
1565 self._active_patches.remove(self)
1566 except ValueError:
1567 # If the patch hasn't been started this will fail
1568 pass
1569
Michael Foordf7c41582012-06-10 20:36:32 +01001570 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001571
1572
1573
1574def _get_target(target):
1575 try:
1576 target, attribute = target.rsplit('.', 1)
1577 except (TypeError, ValueError):
1578 raise TypeError("Need a valid target to patch. You supplied: %r" %
1579 (target,))
1580 getter = lambda: _importer(target)
1581 return getter, attribute
1582
1583
1584def _patch_object(
1585 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001586 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001587 new_callable=None, **kwargs
1588 ):
1589 """
Michael Foord345266a2012-03-14 12:24:34 -07001590 patch the named member (`attribute`) on an object (`target`) with a mock
1591 object.
1592
1593 `patch.object` can be used as a decorator, class decorator or a context
1594 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1595 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1596 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1597 the mock object it creates.
1598
1599 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1600 for choosing which methods to wrap.
1601 """
Elena Oatcd90a522019-12-08 12:14:38 -08001602 if type(target) is str:
1603 raise TypeError(
1604 f"{target!r} must be the actual object to be patched, not a str"
1605 )
Michael Foord345266a2012-03-14 12:24:34 -07001606 getter = lambda: target
1607 return _patch(
1608 getter, attribute, new, spec, create,
1609 spec_set, autospec, new_callable, kwargs
1610 )
1611
1612
Michael Foord50a8c0e2012-03-25 18:57:58 +01001613def _patch_multiple(target, spec=None, create=False, spec_set=None,
1614 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001615 """Perform multiple patches in a single call. It takes the object to be
1616 patched (either as an object or a string to fetch the object by importing)
1617 and keyword arguments for the patches::
1618
1619 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1620 ...
1621
1622 Use `DEFAULT` as the value if you want `patch.multiple` to create
1623 mocks for you. In this case the created mocks are passed into a decorated
1624 function by keyword, and a dictionary is returned when `patch.multiple` is
1625 used as a context manager.
1626
1627 `patch.multiple` can be used as a decorator, class decorator or a context
1628 manager. The arguments `spec`, `spec_set`, `create`,
1629 `autospec` and `new_callable` have the same meaning as for `patch`. These
1630 arguments will be applied to *all* patches done by `patch.multiple`.
1631
1632 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1633 for choosing which methods to wrap.
1634 """
1635 if type(target) is str:
1636 getter = lambda: _importer(target)
1637 else:
1638 getter = lambda: target
1639
1640 if not kwargs:
1641 raise ValueError(
1642 'Must supply at least one keyword argument with patch.multiple'
1643 )
1644 # need to wrap in a list for python 3, where items is a view
1645 items = list(kwargs.items())
1646 attribute, new = items[0]
1647 patcher = _patch(
1648 getter, attribute, new, spec, create, spec_set,
1649 autospec, new_callable, {}
1650 )
1651 patcher.attribute_name = attribute
1652 for attribute, new in items[1:]:
1653 this_patcher = _patch(
1654 getter, attribute, new, spec, create, spec_set,
1655 autospec, new_callable, {}
1656 )
1657 this_patcher.attribute_name = attribute
1658 patcher.additional_patchers.append(this_patcher)
1659 return patcher
1660
1661
1662def patch(
1663 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001664 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001665 ):
1666 """
1667 `patch` acts as a function decorator, class decorator or a context
1668 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001669 is patched with a `new` object. When the function/with statement exits
1670 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001671
Mario Corcherof5e7f392019-09-09 15:18:06 +01001672 If `new` is omitted, then the target is replaced with an
1673 `AsyncMock if the patched object is an async function or a
1674 `MagicMock` otherwise. If `patch` is used as a decorator and `new` is
Michael Foord54b3db82012-03-28 15:08:08 +01001675 omitted, the created mock is passed in as an extra argument to the
1676 decorated function. If `patch` is used as a context manager the created
1677 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001678
Michael Foord54b3db82012-03-28 15:08:08 +01001679 `target` should be a string in the form `'package.module.ClassName'`. The
1680 `target` is imported and the specified object replaced with the `new`
1681 object, so the `target` must be importable from the environment you are
1682 calling `patch` from. The target is imported when the decorated function
1683 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001684
1685 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1686 if patch is creating one for you.
1687
1688 In addition you can pass `spec=True` or `spec_set=True`, which causes
1689 patch to pass in the object being mocked as the spec/spec_set object.
1690
1691 `new_callable` allows you to specify a different class, or callable object,
Mario Corcherof5e7f392019-09-09 15:18:06 +01001692 that will be called to create the `new` object. By default `AsyncMock` is
1693 used for async functions and `MagicMock` for the rest.
Michael Foord345266a2012-03-14 12:24:34 -07001694
1695 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001696 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001697 All attributes of the mock will also have the spec of the corresponding
1698 attribute of the object being replaced. Methods and functions being
1699 mocked will have their arguments checked and will raise a `TypeError` if
1700 they are called with the wrong signature. For mocks replacing a class,
1701 their return value (the 'instance') will have the same spec as the class.
1702
1703 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1704 arbitrary object as the spec instead of the one being replaced.
1705
1706 By default `patch` will fail to replace attributes that don't exist. If
1707 you pass in `create=True`, and the attribute doesn't exist, patch will
1708 create the attribute for you when the patched function is called, and
1709 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001710 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001711 default because it can be dangerous. With it switched on you can write
1712 passing tests against APIs that don't actually exist!
1713
1714 Patch can be used as a `TestCase` class decorator. It works by
1715 decorating each test method in the class. This reduces the boilerplate
1716 code when your test methods share a common patchings set. `patch` finds
1717 tests by looking for method names that start with `patch.TEST_PREFIX`.
1718 By default this is `test`, which matches the way `unittest` finds tests.
1719 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1720
1721 Patch can be used as a context manager, with the with statement. Here the
1722 patching applies to the indented block after the with statement. If you
1723 use "as" then the patched object will be bound to the name after the
1724 "as"; very useful if `patch` is creating a mock object for you.
1725
1726 `patch` takes arbitrary keyword arguments. These will be passed to
1727 the `Mock` (or `new_callable`) on construction.
1728
1729 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1730 available for alternate use-cases.
1731 """
1732 getter, attribute = _get_target(target)
1733 return _patch(
1734 getter, attribute, new, spec, create,
1735 spec_set, autospec, new_callable, kwargs
1736 )
1737
1738
1739class _patch_dict(object):
1740 """
1741 Patch a dictionary, or dictionary like object, and restore the dictionary
1742 to its original state after the test.
1743
1744 `in_dict` can be a dictionary or a mapping like container. If it is a
1745 mapping then it must at least support getting, setting and deleting items
1746 plus iterating over keys.
1747
1748 `in_dict` can also be a string specifying the name of the dictionary, which
1749 will then be fetched by importing it.
1750
1751 `values` can be a dictionary of values to set in the dictionary. `values`
1752 can also be an iterable of `(key, value)` pairs.
1753
1754 If `clear` is True then the dictionary will be cleared before the new
1755 values are set.
1756
1757 `patch.dict` can also be called with arbitrary keyword arguments to set
1758 values in the dictionary::
1759
1760 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1761 ...
1762
1763 `patch.dict` can be used as a context manager, decorator or class
1764 decorator. When used as a class decorator `patch.dict` honours
1765 `patch.TEST_PREFIX` for choosing which methods to wrap.
1766 """
1767
1768 def __init__(self, in_dict, values=(), clear=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001769 self.in_dict = in_dict
1770 # support any argument supported by dict(...) constructor
1771 self.values = dict(values)
1772 self.values.update(kwargs)
1773 self.clear = clear
1774 self._original = None
1775
1776
1777 def __call__(self, f):
1778 if isinstance(f, type):
1779 return self.decorate_class(f)
1780 @wraps(f)
1781 def _inner(*args, **kw):
1782 self._patch_dict()
1783 try:
1784 return f(*args, **kw)
1785 finally:
1786 self._unpatch_dict()
1787
1788 return _inner
1789
1790
1791 def decorate_class(self, klass):
1792 for attr in dir(klass):
1793 attr_value = getattr(klass, attr)
1794 if (attr.startswith(patch.TEST_PREFIX) and
1795 hasattr(attr_value, "__call__")):
1796 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1797 decorated = decorator(attr_value)
1798 setattr(klass, attr, decorated)
1799 return klass
1800
1801
1802 def __enter__(self):
1803 """Patch the dict."""
1804 self._patch_dict()
Mario Corchero04530812019-05-28 13:53:31 +01001805 return self.in_dict
Michael Foord345266a2012-03-14 12:24:34 -07001806
1807
1808 def _patch_dict(self):
1809 values = self.values
Xtreaka875ea52019-02-25 00:24:49 +05301810 if isinstance(self.in_dict, str):
1811 self.in_dict = _importer(self.in_dict)
Michael Foord345266a2012-03-14 12:24:34 -07001812 in_dict = self.in_dict
1813 clear = self.clear
1814
1815 try:
1816 original = in_dict.copy()
1817 except AttributeError:
1818 # dict like object with no copy method
1819 # must support iteration over keys
1820 original = {}
1821 for key in in_dict:
1822 original[key] = in_dict[key]
1823 self._original = original
1824
1825 if clear:
1826 _clear_dict(in_dict)
1827
1828 try:
1829 in_dict.update(values)
1830 except AttributeError:
1831 # dict like object with no update method
1832 for key in values:
1833 in_dict[key] = values[key]
1834
1835
1836 def _unpatch_dict(self):
1837 in_dict = self.in_dict
1838 original = self._original
1839
1840 _clear_dict(in_dict)
1841
1842 try:
1843 in_dict.update(original)
1844 except AttributeError:
1845 for key in original:
1846 in_dict[key] = original[key]
1847
1848
1849 def __exit__(self, *args):
1850 """Unpatch the dict."""
1851 self._unpatch_dict()
1852 return False
1853
1854 start = __enter__
1855 stop = __exit__
1856
1857
1858def _clear_dict(in_dict):
1859 try:
1860 in_dict.clear()
1861 except AttributeError:
1862 keys = list(in_dict)
1863 for key in keys:
1864 del in_dict[key]
1865
1866
Michael Foordf7c41582012-06-10 20:36:32 +01001867def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001868 """Stop all active patches. LIFO to unroll nested patches."""
1869 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001870 patch.stop()
1871
1872
Michael Foord345266a2012-03-14 12:24:34 -07001873patch.object = _patch_object
1874patch.dict = _patch_dict
1875patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001876patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001877patch.TEST_PREFIX = 'test'
1878
1879magic_methods = (
1880 "lt le gt ge eq ne "
1881 "getitem setitem delitem "
1882 "len contains iter "
1883 "hash str sizeof "
1884 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001885 # we added divmod and rdivmod here instead of numerics
1886 # because there is no idivmod
1887 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001888 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001889 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001890 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001891 "fspath "
Lisa Roach9a7d9512019-09-28 18:42:44 -07001892 "aiter "
Michael Foord345266a2012-03-14 12:24:34 -07001893)
1894
Michael Foordd2623d72014-04-14 11:23:48 -04001895numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001896 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001897)
Michael Foord345266a2012-03-14 12:24:34 -07001898inplace = ' '.join('i%s' % n for n in numerics.split())
1899right = ' '.join('r%s' % n for n in numerics.split())
1900
1901# not including __prepare__, __instancecheck__, __subclasscheck__
1902# (as they are metaclass methods)
1903# __del__ is not supported at all as it causes problems if it exists
1904
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001905_non_defaults = {
1906 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1907 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1908 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1909 '__repr__', '__dir__', '__subclasses__', '__format__',
Lisa Roach8b03f942019-09-19 21:04:18 -07001910 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001911}
Michael Foord345266a2012-03-14 12:24:34 -07001912
1913
1914def _get_method(name, func):
1915 "Turns a callable object (like a mock) into a real function"
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001916 def method(self, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -07001917 return func(self, *args, **kw)
1918 method.__name__ = name
1919 return method
1920
1921
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001922_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001923 '__%s__' % method for method in
1924 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001925}
Michael Foord345266a2012-03-14 12:24:34 -07001926
Lisa Roach77b3b772019-05-20 09:19:53 -07001927# Magic methods used for async `with` statements
1928_async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
Lisa Roach8b03f942019-09-19 21:04:18 -07001929# Magic methods that are only used with async calls but are synchronous functions themselves
1930_sync_async_magics = {"__aiter__"}
1931_async_magics = _async_method_magics | _sync_async_magics
Lisa Roach77b3b772019-05-20 09:19:53 -07001932
Lisa Roach8b03f942019-09-19 21:04:18 -07001933_all_sync_magics = _magics | _non_defaults
1934_all_magics = _all_sync_magics | _async_magics
Michael Foord345266a2012-03-14 12:24:34 -07001935
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001936_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001937 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001938 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001939 '__instancecheck__', '__subclasscheck__',
1940 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001941}
Michael Foord345266a2012-03-14 12:24:34 -07001942
1943_calculate_return_value = {
1944 '__hash__': lambda self: object.__hash__(self),
1945 '__str__': lambda self: object.__str__(self),
1946 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001947 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001948}
1949
1950_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001951 '__lt__': NotImplemented,
1952 '__gt__': NotImplemented,
1953 '__le__': NotImplemented,
1954 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001955 '__int__': 1,
1956 '__contains__': False,
1957 '__len__': 0,
1958 '__exit__': False,
1959 '__complex__': 1j,
1960 '__float__': 1.0,
1961 '__bool__': True,
1962 '__index__': 1,
Lisa Roach77b3b772019-05-20 09:19:53 -07001963 '__aexit__': False,
Michael Foord345266a2012-03-14 12:24:34 -07001964}
1965
1966
1967def _get_eq(self):
1968 def __eq__(other):
1969 ret_val = self.__eq__._mock_return_value
1970 if ret_val is not DEFAULT:
1971 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001972 if self is other:
1973 return True
1974 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001975 return __eq__
1976
1977def _get_ne(self):
1978 def __ne__(other):
1979 if self.__ne__._mock_return_value is not DEFAULT:
1980 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001981 if self is other:
1982 return False
1983 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001984 return __ne__
1985
1986def _get_iter(self):
1987 def __iter__():
1988 ret_val = self.__iter__._mock_return_value
1989 if ret_val is DEFAULT:
1990 return iter([])
1991 # if ret_val was already an iterator, then calling iter on it should
1992 # return the iterator unchanged
1993 return iter(ret_val)
1994 return __iter__
1995
Lisa Roach77b3b772019-05-20 09:19:53 -07001996def _get_async_iter(self):
1997 def __aiter__():
1998 ret_val = self.__aiter__._mock_return_value
1999 if ret_val is DEFAULT:
2000 return _AsyncIterator(iter([]))
2001 return _AsyncIterator(iter(ret_val))
2002 return __aiter__
2003
Michael Foord345266a2012-03-14 12:24:34 -07002004_side_effect_methods = {
2005 '__eq__': _get_eq,
2006 '__ne__': _get_ne,
2007 '__iter__': _get_iter,
Lisa Roach77b3b772019-05-20 09:19:53 -07002008 '__aiter__': _get_async_iter
Michael Foord345266a2012-03-14 12:24:34 -07002009}
2010
2011
2012
2013def _set_return_value(mock, method, name):
2014 fixed = _return_values.get(name, DEFAULT)
2015 if fixed is not DEFAULT:
2016 method.return_value = fixed
2017 return
2018
marcoramirezmxa9187c32019-09-16 11:34:46 -05002019 return_calculator = _calculate_return_value.get(name)
2020 if return_calculator is not None:
2021 return_value = return_calculator(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002022 method.return_value = return_value
2023 return
2024
2025 side_effector = _side_effect_methods.get(name)
2026 if side_effector is not None:
2027 method.side_effect = side_effector(mock)
2028
2029
2030
Lisa Roach9a7d9512019-09-28 18:42:44 -07002031class MagicMixin(Base):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002032 def __init__(self, /, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07002033 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10002034 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07002035 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002036
2037
2038 def _mock_set_magics(self):
Lisa Roach9a7d9512019-09-28 18:42:44 -07002039 orig_magics = _magics | _async_method_magics
2040 these_magics = orig_magics
Michael Foord345266a2012-03-14 12:24:34 -07002041
Łukasz Langaa468db92015-04-13 23:12:42 -07002042 if getattr(self, "_mock_methods", None) is not None:
Lisa Roach9a7d9512019-09-28 18:42:44 -07002043 these_magics = orig_magics.intersection(self._mock_methods)
Michael Foord345266a2012-03-14 12:24:34 -07002044
2045 remove_magics = set()
Lisa Roach9a7d9512019-09-28 18:42:44 -07002046 remove_magics = orig_magics - these_magics
Michael Foord345266a2012-03-14 12:24:34 -07002047
2048 for entry in remove_magics:
2049 if entry in type(self).__dict__:
2050 # remove unneeded magic methods
2051 delattr(self, entry)
2052
2053 # don't overwrite existing attributes if called a second time
2054 these_magics = these_magics - set(type(self).__dict__)
2055
2056 _type = type(self)
2057 for entry in these_magics:
2058 setattr(_type, entry, MagicProxy(entry, self))
2059
2060
2061
2062class NonCallableMagicMock(MagicMixin, NonCallableMock):
2063 """A version of `MagicMock` that isn't callable."""
2064 def mock_add_spec(self, spec, spec_set=False):
2065 """Add a spec to a mock. `spec` can either be an object or a
2066 list of strings. Only attributes on the `spec` can be fetched as
2067 attributes from the mock.
2068
2069 If `spec_set` is True then only attributes on the spec can be set."""
2070 self._mock_add_spec(spec, spec_set)
2071 self._mock_set_magics()
2072
2073
Lisa Roach9a7d9512019-09-28 18:42:44 -07002074class AsyncMagicMixin(MagicMixin):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002075 def __init__(self, /, *args, **kw):
Lisa Roach9a7d9512019-09-28 18:42:44 -07002076 self._mock_set_magics() # make magic work for kwargs in init
Lisa Roach77b3b772019-05-20 09:19:53 -07002077 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)
Lisa Roach9a7d9512019-09-28 18:42:44 -07002078 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002079
Lisa Roach9a7d9512019-09-28 18:42:44 -07002080class MagicMock(MagicMixin, Mock):
Michael Foord345266a2012-03-14 12:24:34 -07002081 """
2082 MagicMock is a subclass of Mock with default implementations
2083 of most of the magic methods. You can use MagicMock without having to
2084 configure the magic methods yourself.
2085
2086 If you use the `spec` or `spec_set` arguments then *only* magic
2087 methods that exist in the spec will be created.
2088
2089 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
2090 """
2091 def mock_add_spec(self, spec, spec_set=False):
2092 """Add a spec to a mock. `spec` can either be an object or a
2093 list of strings. Only attributes on the `spec` can be fetched as
2094 attributes from the mock.
2095
2096 If `spec_set` is True then only attributes on the spec can be set."""
2097 self._mock_add_spec(spec, spec_set)
2098 self._mock_set_magics()
2099
2100
2101
Lisa Roach9a7d9512019-09-28 18:42:44 -07002102class MagicProxy(Base):
Michael Foord345266a2012-03-14 12:24:34 -07002103 def __init__(self, name, parent):
2104 self.name = name
2105 self.parent = parent
2106
Michael Foord345266a2012-03-14 12:24:34 -07002107 def create_mock(self):
2108 entry = self.name
2109 parent = self.parent
2110 m = parent._get_child_mock(name=entry, _new_name=entry,
2111 _new_parent=parent)
2112 setattr(parent, entry, m)
2113 _set_return_value(parent, m, entry)
2114 return m
2115
2116 def __get__(self, obj, _type=None):
2117 return self.create_mock()
2118
2119
Lisa Roach77b3b772019-05-20 09:19:53 -07002120class AsyncMockMixin(Base):
Lisa Roach77b3b772019-05-20 09:19:53 -07002121 await_count = _delegating_property('await_count')
2122 await_args = _delegating_property('await_args')
2123 await_args_list = _delegating_property('await_args_list')
2124
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002125 def __init__(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002126 super().__init__(*args, **kwargs)
2127 # asyncio.iscoroutinefunction() checks _is_coroutine property to say if an
2128 # object is a coroutine. Without this check it looks to see if it is a
2129 # function/method, which in this case it is not (since it is an
2130 # AsyncMock).
2131 # It is set through __dict__ because when spec_set is True, this
2132 # attribute is likely undefined.
2133 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
Lisa Roach77b3b772019-05-20 09:19:53 -07002134 self.__dict__['_mock_await_count'] = 0
2135 self.__dict__['_mock_await_args'] = None
2136 self.__dict__['_mock_await_args_list'] = _CallList()
2137 code_mock = NonCallableMock(spec_set=CodeType)
2138 code_mock.co_flags = inspect.CO_COROUTINE
2139 self.__dict__['__code__'] = code_mock
2140
Jason Fried046442d2019-11-20 16:27:51 -08002141 async def _execute_mock_call(self, /, *args, **kwargs):
2142 # This is nearly just like super(), except for sepcial handling
2143 # of coroutines
Lisa Roach77b3b772019-05-20 09:19:53 -07002144
2145 _call = self.call_args
Jason Fried046442d2019-11-20 16:27:51 -08002146 self.await_count += 1
2147 self.await_args = _call
2148 self.await_args_list.append(_call)
Lisa Roach77b3b772019-05-20 09:19:53 -07002149
Jason Fried046442d2019-11-20 16:27:51 -08002150 effect = self.side_effect
2151 if effect is not None:
2152 if _is_exception(effect):
2153 raise effect
2154 elif not _callable(effect):
2155 try:
2156 result = next(effect)
2157 except StopIteration:
2158 # It is impossible to propogate a StopIteration
2159 # through coroutines because of PEP 479
2160 raise StopAsyncIteration
2161 if _is_exception(result):
2162 raise result
2163 elif asyncio.iscoroutinefunction(effect):
2164 result = await effect(*args, **kwargs)
2165 else:
2166 result = effect(*args, **kwargs)
Lisa Roach77b3b772019-05-20 09:19:53 -07002167
Jason Fried046442d2019-11-20 16:27:51 -08002168 if result is not DEFAULT:
2169 return result
2170
2171 if self._mock_return_value is not DEFAULT:
2172 return self.return_value
2173
2174 if self._mock_wraps is not None:
2175 if asyncio.iscoroutinefunction(self._mock_wraps):
2176 return await self._mock_wraps(*args, **kwargs)
2177 return self._mock_wraps(*args, **kwargs)
2178
2179 return self.return_value
Lisa Roach77b3b772019-05-20 09:19:53 -07002180
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002181 def assert_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002182 """
2183 Assert that the mock was awaited at least once.
2184 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002185 if self.await_count == 0:
2186 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2187 raise AssertionError(msg)
2188
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002189 def assert_awaited_once(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002190 """
2191 Assert that the mock was awaited exactly once.
2192 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002193 if not self.await_count == 1:
2194 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2195 f" Awaited {self.await_count} times.")
2196 raise AssertionError(msg)
2197
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002198 def assert_awaited_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002199 """
2200 Assert that the last await was with the specified arguments.
2201 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002202 if self.await_args is None:
2203 expected = self._format_mock_call_signature(args, kwargs)
2204 raise AssertionError(f'Expected await: {expected}\nNot awaited')
2205
2206 def _error_message():
Xtreak0ae022c2019-05-29 12:32:26 +05302207 msg = self._format_mock_failure_message(args, kwargs, action='await')
Lisa Roach77b3b772019-05-20 09:19:53 -07002208 return msg
2209
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002210 expected = self._call_matcher(_Call((args, kwargs), two=True))
Lisa Roach77b3b772019-05-20 09:19:53 -07002211 actual = self._call_matcher(self.await_args)
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002212 if actual != expected:
Lisa Roach77b3b772019-05-20 09:19:53 -07002213 cause = expected if isinstance(expected, Exception) else None
2214 raise AssertionError(_error_message()) from cause
2215
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002216 def assert_awaited_once_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002217 """
2218 Assert that the mock was awaited exactly once and with the specified
2219 arguments.
2220 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002221 if not self.await_count == 1:
2222 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2223 f" Awaited {self.await_count} times.")
2224 raise AssertionError(msg)
2225 return self.assert_awaited_with(*args, **kwargs)
2226
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002227 def assert_any_await(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002228 """
2229 Assert the mock has ever been awaited with the specified arguments.
2230 """
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002231 expected = self._call_matcher(_Call((args, kwargs), two=True))
2232 cause = expected if isinstance(expected, Exception) else None
Lisa Roach77b3b772019-05-20 09:19:53 -07002233 actual = [self._call_matcher(c) for c in self.await_args_list]
Elizabeth Useltond6a9d172019-09-13 08:54:32 -07002234 if cause or expected not in _AnyComparer(actual):
Lisa Roach77b3b772019-05-20 09:19:53 -07002235 expected_string = self._format_mock_call_signature(args, kwargs)
2236 raise AssertionError(
2237 '%s await not found' % expected_string
2238 ) from cause
2239
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002240 def assert_has_awaits(self, calls, any_order=False):
Lisa Roach77b3b772019-05-20 09:19:53 -07002241 """
2242 Assert the mock has been awaited with the specified calls.
2243 The :attr:`await_args_list` list is checked for the awaits.
2244
2245 If `any_order` is False (the default) then the awaits must be
2246 sequential. There can be extra calls before or after the
2247 specified awaits.
2248
2249 If `any_order` is True then the awaits can be in any order, but
2250 they must all appear in :attr:`await_args_list`.
2251 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002252 expected = [self._call_matcher(c) for c in calls]
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002253 cause = next((e for e in expected if isinstance(e, Exception)), None)
Lisa Roach77b3b772019-05-20 09:19:53 -07002254 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2255 if not any_order:
2256 if expected not in all_awaits:
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002257 if cause is None:
2258 problem = 'Awaits not found.'
2259 else:
2260 problem = ('Error processing expected awaits.\n'
2261 'Errors: {}').format(
2262 [e if isinstance(e, Exception) else None
2263 for e in expected])
Lisa Roach77b3b772019-05-20 09:19:53 -07002264 raise AssertionError(
Samuel Freilichb5a7a4f2019-09-24 15:08:31 -04002265 f'{problem}\n'
2266 f'Expected: {_CallList(calls)}\n'
Lisa Roach77b3b772019-05-20 09:19:53 -07002267 f'Actual: {self.await_args_list}'
2268 ) from cause
2269 return
2270
2271 all_awaits = list(all_awaits)
2272
2273 not_found = []
2274 for kall in expected:
2275 try:
2276 all_awaits.remove(kall)
2277 except ValueError:
2278 not_found.append(kall)
2279 if not_found:
2280 raise AssertionError(
2281 '%r not all found in await list' % (tuple(not_found),)
2282 ) from cause
2283
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002284 def assert_not_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002285 """
2286 Assert that the mock was never awaited.
2287 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002288 if self.await_count != 0:
Xtreakff6b2e62019-05-27 18:26:23 +05302289 msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
Lisa Roach77b3b772019-05-20 09:19:53 -07002290 f" Awaited {self.await_count} times.")
2291 raise AssertionError(msg)
2292
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002293 def reset_mock(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002294 """
2295 See :func:`.Mock.reset_mock()`
2296 """
2297 super().reset_mock(*args, **kwargs)
2298 self.await_count = 0
2299 self.await_args = None
2300 self.await_args_list = _CallList()
2301
2302
2303class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2304 """
2305 Enhance :class:`Mock` with features allowing to mock
2306 an async function.
2307
2308 The :class:`AsyncMock` object will behave so the object is
2309 recognized as an async function, and the result of a call is an awaitable:
2310
2311 >>> mock = AsyncMock()
2312 >>> asyncio.iscoroutinefunction(mock)
2313 True
2314 >>> inspect.isawaitable(mock())
2315 True
2316
2317
2318 The result of ``mock()`` is an async function which will have the outcome
2319 of ``side_effect`` or ``return_value``:
2320
2321 - if ``side_effect`` is a function, the async function will return the
2322 result of that function,
2323 - if ``side_effect`` is an exception, the async function will raise the
2324 exception,
2325 - if ``side_effect`` is an iterable, the async function will return the
2326 next value of the iterable, however, if the sequence of result is
2327 exhausted, ``StopIteration`` is raised immediately,
2328 - if ``side_effect`` is not defined, the async function will return the
2329 value defined by ``return_value``, hence, by default, the async function
2330 returns a new :class:`AsyncMock` object.
2331
2332 If the outcome of ``side_effect`` or ``return_value`` is an async function,
2333 the mock async function obtained when the mock object is called will be this
2334 async function itself (and not an async function returning an async
2335 function).
2336
2337 The test author can also specify a wrapped object with ``wraps``. In this
2338 case, the :class:`Mock` object behavior is the same as with an
2339 :class:`.Mock` object: the wrapped object may have methods
2340 defined as async function functions.
2341
Xtreake7cb23b2019-05-21 14:17:17 +05302342 Based on Martin Richard's asynctest project.
Lisa Roach77b3b772019-05-20 09:19:53 -07002343 """
2344
Michael Foord345266a2012-03-14 12:24:34 -07002345
2346class _ANY(object):
2347 "A helper object that compares equal to everything."
2348
2349 def __eq__(self, other):
2350 return True
2351
2352 def __ne__(self, other):
2353 return False
2354
2355 def __repr__(self):
2356 return '<ANY>'
2357
2358ANY = _ANY()
2359
2360
2361
2362def _format_call_signature(name, args, kwargs):
2363 message = '%s(%%s)' % name
2364 formatted_args = ''
2365 args_string = ', '.join([repr(arg) for arg in args])
2366 kwargs_string = ', '.join([
Xtreak9d607062019-09-09 16:25:22 +05302367 '%s=%r' % (key, value) for key, value in kwargs.items()
Michael Foord345266a2012-03-14 12:24:34 -07002368 ])
2369 if args_string:
2370 formatted_args = args_string
2371 if kwargs_string:
2372 if formatted_args:
2373 formatted_args += ', '
2374 formatted_args += kwargs_string
2375
2376 return message % formatted_args
2377
2378
2379
2380class _Call(tuple):
2381 """
2382 A tuple for holding the results of a call to a mock, either in the form
2383 `(args, kwargs)` or `(name, args, kwargs)`.
2384
2385 If args or kwargs are empty then a call tuple will compare equal to
2386 a tuple without those values. This makes comparisons less verbose::
2387
2388 _Call(('name', (), {})) == ('name',)
2389 _Call(('name', (1,), {})) == ('name', (1,))
2390 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2391
2392 The `_Call` object provides a useful shortcut for comparing with call::
2393
2394 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2395 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2396
2397 If the _Call has no name then it will match any name.
2398 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002399 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002400 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002401 args = ()
2402 kwargs = {}
2403 _len = len(value)
2404 if _len == 3:
2405 name, args, kwargs = value
2406 elif _len == 2:
2407 first, second = value
2408 if isinstance(first, str):
2409 name = first
2410 if isinstance(second, tuple):
2411 args = second
2412 else:
2413 kwargs = second
2414 else:
2415 args, kwargs = first, second
2416 elif _len == 1:
2417 value, = value
2418 if isinstance(value, str):
2419 name = value
2420 elif isinstance(value, tuple):
2421 args = value
2422 else:
2423 kwargs = value
2424
2425 if two:
2426 return tuple.__new__(cls, (args, kwargs))
2427
2428 return tuple.__new__(cls, (name, args, kwargs))
2429
2430
2431 def __init__(self, value=(), name=None, parent=None, two=False,
2432 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002433 self._mock_name = name
2434 self._mock_parent = parent
2435 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002436
2437
2438 def __eq__(self, other):
Michael Foord345266a2012-03-14 12:24:34 -07002439 try:
2440 len_other = len(other)
2441 except TypeError:
Serhiy Storchaka662db122019-08-08 08:42:54 +03002442 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07002443
2444 self_name = ''
2445 if len(self) == 2:
2446 self_args, self_kwargs = self
2447 else:
2448 self_name, self_args, self_kwargs = self
2449
Andrew Dunaie63e6172018-12-04 11:08:45 +02002450 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2451 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002452 return False
2453
Michael Foord345266a2012-03-14 12:24:34 -07002454 other_name = ''
2455 if len_other == 0:
2456 other_args, other_kwargs = (), {}
2457 elif len_other == 3:
2458 other_name, other_args, other_kwargs = other
2459 elif len_other == 1:
2460 value, = other
2461 if isinstance(value, tuple):
2462 other_args = value
2463 other_kwargs = {}
2464 elif isinstance(value, str):
2465 other_name = value
2466 other_args, other_kwargs = (), {}
2467 else:
2468 other_args = ()
2469 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002470 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002471 # could be (name, args) or (name, kwargs) or (args, kwargs)
2472 first, second = other
2473 if isinstance(first, str):
2474 other_name = first
2475 if isinstance(second, tuple):
2476 other_args, other_kwargs = second, {}
2477 else:
2478 other_args, other_kwargs = (), second
2479 else:
2480 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002481 else:
2482 return False
Michael Foord345266a2012-03-14 12:24:34 -07002483
2484 if self_name and other_name != self_name:
2485 return False
2486
2487 # this order is important for ANY to work!
2488 return (other_args, other_kwargs) == (self_args, self_kwargs)
2489
2490
Berker Peksagce913872016-03-28 00:30:02 +03002491 __ne__ = object.__ne__
2492
2493
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002494 def __call__(self, /, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002495 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002496 return _Call(('', args, kwargs), name='()')
2497
Andrew Dunaie63e6172018-12-04 11:08:45 +02002498 name = self._mock_name + '()'
2499 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002500
2501
2502 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002503 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002504 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002505 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002506 return _Call(name=name, parent=self, from_kall=False)
2507
2508
blhsing72c35992019-09-11 07:28:06 -07002509 def __getattribute__(self, attr):
2510 if attr in tuple.__dict__:
2511 raise AttributeError
2512 return tuple.__getattribute__(self, attr)
2513
2514
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002515 def count(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302516 return self.__getattr__('count')(*args, **kwargs)
2517
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002518 def index(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302519 return self.__getattr__('index')(*args, **kwargs)
2520
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302521 def _get_call_arguments(self):
2522 if len(self) == 2:
2523 args, kwargs = self
2524 else:
2525 name, args, kwargs = self
2526
2527 return args, kwargs
2528
2529 @property
2530 def args(self):
2531 return self._get_call_arguments()[0]
2532
2533 @property
2534 def kwargs(self):
2535 return self._get_call_arguments()[1]
2536
Michael Foord345266a2012-03-14 12:24:34 -07002537 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002538 if not self._mock_from_kall:
2539 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002540 if name.startswith('()'):
2541 name = 'call%s' % name
2542 return name
2543
2544 if len(self) == 2:
2545 name = 'call'
2546 args, kwargs = self
2547 else:
2548 name, args, kwargs = self
2549 if not name:
2550 name = 'call'
2551 elif not name.startswith('()'):
2552 name = 'call.%s' % name
2553 else:
2554 name = 'call%s' % name
2555 return _format_call_signature(name, args, kwargs)
2556
2557
2558 def call_list(self):
2559 """For a call object that represents multiple calls, `call_list`
2560 returns a list of all the intermediate calls as well as the
2561 final call."""
2562 vals = []
2563 thing = self
2564 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002565 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002566 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002567 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002568 return _CallList(reversed(vals))
2569
2570
2571call = _Call(from_kall=False)
2572
2573
Michael Foord345266a2012-03-14 12:24:34 -07002574def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2575 _name=None, **kwargs):
2576 """Create a mock object using another object as a spec. Attributes on the
2577 mock will use the corresponding attribute on the `spec` object as their
2578 spec.
2579
2580 Functions or methods being mocked will have their arguments checked
2581 to check that they are called with the correct signature.
2582
2583 If `spec_set` is True then attempting to set attributes that don't exist
2584 on the spec object will raise an `AttributeError`.
2585
2586 If a class is used as a spec then the return value of the mock (the
2587 instance of the class) will have the same spec. You can use a class as the
2588 spec for an instance object by passing `instance=True`. The returned mock
2589 will only be callable if instances of the mock are callable.
2590
2591 `create_autospec` also takes arbitrary keyword arguments that are passed to
2592 the constructor of the created mock."""
2593 if _is_list(spec):
2594 # can't pass a list instance to the mock constructor as it will be
2595 # interpreted as a list of strings
2596 spec = type(spec)
2597
2598 is_type = isinstance(spec, type)
Xtreakff6b2e62019-05-27 18:26:23 +05302599 is_async_func = _is_async_func(spec)
Michael Foord345266a2012-03-14 12:24:34 -07002600 _kwargs = {'spec': spec}
2601 if spec_set:
2602 _kwargs = {'spec_set': spec}
2603 elif spec is None:
2604 # None we mock with a normal mock without a spec
2605 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002606 if _kwargs and instance:
2607 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002608
2609 _kwargs.update(kwargs)
2610
2611 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002612 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002613 # descriptors don't have a spec
2614 # because we don't know what type they return
2615 _kwargs = {}
Lisa Roach77b3b772019-05-20 09:19:53 -07002616 elif is_async_func:
2617 if instance:
2618 raise RuntimeError("Instance can not be True when create_autospec "
2619 "is mocking an async function")
2620 Klass = AsyncMock
Michael Foord345266a2012-03-14 12:24:34 -07002621 elif not _callable(spec):
2622 Klass = NonCallableMagicMock
2623 elif is_type and instance and not _instance_callable(spec):
2624 Klass = NonCallableMagicMock
2625
Kushal Das484f8a82014-04-16 01:05:50 +05302626 _name = _kwargs.pop('name', _name)
2627
Michael Foord345266a2012-03-14 12:24:34 -07002628 _new_name = _name
2629 if _parent is None:
2630 # for a top level object no _new_name should be set
2631 _new_name = ''
2632
2633 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2634 name=_name, **_kwargs)
2635
2636 if isinstance(spec, FunctionTypes):
2637 # should only happen at the top level because we don't
2638 # recurse for functions
2639 mock = _set_signature(mock, spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07002640 if is_async_func:
Xtreakff6b2e62019-05-27 18:26:23 +05302641 _setup_async_mock(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002642 else:
2643 _check_signature(spec, mock, is_type, instance)
2644
2645 if _parent is not None and not instance:
2646 _parent._mock_children[_name] = mock
2647
2648 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002649 mock.return_value = create_autospec(spec, spec_set, instance=True,
2650 _name='()', _parent=mock)
2651
2652 for entry in dir(spec):
2653 if _is_magic(entry):
2654 # MagicMock already does the useful magic methods for us
2655 continue
2656
Michael Foord345266a2012-03-14 12:24:34 -07002657 # XXXX do we need a better way of getting attributes without
2658 # triggering code execution (?) Probably not - we need the actual
2659 # object to mock it so we would rather trigger a property than mock
2660 # the property descriptor. Likewise we want to mock out dynamically
2661 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002662 # XXXX what about attributes that raise exceptions other than
2663 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002664 # we could be resilient against it, or catch and propagate the
2665 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002666 try:
2667 original = getattr(spec, entry)
2668 except AttributeError:
2669 continue
Michael Foord345266a2012-03-14 12:24:34 -07002670
2671 kwargs = {'spec': original}
2672 if spec_set:
2673 kwargs = {'spec_set': original}
2674
2675 if not isinstance(original, FunctionTypes):
2676 new = _SpecState(original, spec_set, mock, entry, instance)
2677 mock._mock_children[entry] = new
2678 else:
2679 parent = mock
2680 if isinstance(spec, FunctionTypes):
2681 parent = mock.mock
2682
Michael Foord345266a2012-03-14 12:24:34 -07002683 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002684 kwargs['_eat_self'] = skipfirst
Lisa Roach77b3b772019-05-20 09:19:53 -07002685 if asyncio.iscoroutinefunction(original):
2686 child_klass = AsyncMock
2687 else:
2688 child_klass = MagicMock
2689 new = child_klass(parent=parent, name=entry, _new_name=entry,
2690 _new_parent=parent,
2691 **kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002692 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002693 _check_signature(original, new, skipfirst=skipfirst)
2694
2695 # so functions created with _set_signature become instance attributes,
2696 # *plus* their underlying mock exists in _mock_children of the parent
2697 # mock. Adding to _mock_children may be unnecessary where we are also
2698 # setting as an instance attribute?
2699 if isinstance(new, FunctionTypes):
2700 setattr(mock, entry, new)
2701
2702 return mock
2703
2704
2705def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002706 """
2707 Return whether we should skip the first argument on spec's `entry`
2708 attribute.
2709 """
Michael Foord345266a2012-03-14 12:24:34 -07002710 if not isinstance(spec, type):
2711 if entry in getattr(spec, '__dict__', {}):
2712 # instance attribute - shouldn't skip
2713 return False
Michael Foord345266a2012-03-14 12:24:34 -07002714 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002715
2716 for klass in spec.__mro__:
2717 result = klass.__dict__.get(entry, DEFAULT)
2718 if result is DEFAULT:
2719 continue
2720 if isinstance(result, (staticmethod, classmethod)):
2721 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002722 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2723 # Normal method => skip if looked up on type
2724 # (if looked up on instance, self is already skipped)
2725 return is_type
2726 else:
2727 return False
Michael Foord345266a2012-03-14 12:24:34 -07002728
Chris Withersadbf1782019-05-01 23:04:04 +01002729 # function is a dynamically provided attribute
Michael Foord345266a2012-03-14 12:24:34 -07002730 return is_type
2731
2732
Michael Foord345266a2012-03-14 12:24:34 -07002733class _SpecState(object):
2734
2735 def __init__(self, spec, spec_set=False, parent=None,
2736 name=None, ids=None, instance=False):
2737 self.spec = spec
2738 self.ids = ids
2739 self.spec_set = spec_set
2740 self.parent = parent
2741 self.instance = instance
2742 self.name = name
2743
2744
2745FunctionTypes = (
2746 # python function
2747 type(create_autospec),
2748 # instance method
2749 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002750)
2751
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002752MethodWrapperTypes = (
2753 type(ANY.__eq__.__get__),
2754)
2755
Michael Foord345266a2012-03-14 12:24:34 -07002756
Michael Foorda74561a2012-03-25 19:03:13 +01002757file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002758
Michael Foord04cbe0c2013-03-19 17:22:51 -07002759
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002760def _to_stream(read_data):
2761 if isinstance(read_data, bytes):
2762 return io.BytesIO(read_data)
Michael Foord04cbe0c2013-03-19 17:22:51 -07002763 else:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002764 return io.StringIO(read_data)
Michael Foord0dccf652012-03-25 19:11:50 +01002765
Robert Collins5329aaa2015-07-17 20:08:45 +12002766
Michael Foord0dccf652012-03-25 19:11:50 +01002767def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002768 """
2769 A helper function to create a mock to replace the use of `open`. It works
2770 for `open` called directly or used as a context manager.
2771
2772 The `mock` argument is the mock object to configure. If `None` (the
2773 default) then a `MagicMock` will be created for you, with the API limited
2774 to methods or attributes available on standard file handles.
2775
Xtreak71f82a22018-12-20 21:30:21 +05302776 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002777 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002778 """
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002779 _read_data = _to_stream(read_data)
2780 _state = [_read_data, None]
2781
Robert Collinsca647ef2015-07-24 03:48:20 +12002782 def _readlines_side_effect(*args, **kwargs):
2783 if handle.readlines.return_value is not None:
2784 return handle.readlines.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002785 return _state[0].readlines(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002786
2787 def _read_side_effect(*args, **kwargs):
2788 if handle.read.return_value is not None:
2789 return handle.read.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002790 return _state[0].read(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002791
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002792 def _readline_side_effect(*args, **kwargs):
Tony Flury20870232018-09-12 23:21:16 +01002793 yield from _iter_side_effect()
2794 while True:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002795 yield _state[0].readline(*args, **kwargs)
Tony Flury20870232018-09-12 23:21:16 +01002796
2797 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002798 if handle.readline.return_value is not None:
2799 while True:
2800 yield handle.readline.return_value
2801 for line in _state[0]:
2802 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002803
Damien Nadé394119a2019-05-23 12:03:25 +02002804 def _next_side_effect():
2805 if handle.readline.return_value is not None:
2806 return handle.readline.return_value
2807 return next(_state[0])
2808
Michael Foorda74561a2012-03-25 19:03:13 +01002809 global file_spec
2810 if file_spec is None:
2811 import _io
2812 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2813
Michael Foord345266a2012-03-14 12:24:34 -07002814 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002815 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002816
Robert Collinsca647ef2015-07-24 03:48:20 +12002817 handle = MagicMock(spec=file_spec)
2818 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002819
Robert Collinsca647ef2015-07-24 03:48:20 +12002820 handle.write.return_value = None
2821 handle.read.return_value = None
2822 handle.readline.return_value = None
2823 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002824
Robert Collinsca647ef2015-07-24 03:48:20 +12002825 handle.read.side_effect = _read_side_effect
2826 _state[1] = _readline_side_effect()
2827 handle.readline.side_effect = _state[1]
2828 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002829 handle.__iter__.side_effect = _iter_side_effect
Damien Nadé394119a2019-05-23 12:03:25 +02002830 handle.__next__.side_effect = _next_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002831
Robert Collinsca647ef2015-07-24 03:48:20 +12002832 def reset_data(*args, **kwargs):
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002833 _state[0] = _to_stream(read_data)
Robert Collinsca647ef2015-07-24 03:48:20 +12002834 if handle.readline.side_effect == _state[1]:
2835 # Only reset the side effect if the user hasn't overridden it.
2836 _state[1] = _readline_side_effect()
2837 handle.readline.side_effect = _state[1]
2838 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002839
Robert Collinsca647ef2015-07-24 03:48:20 +12002840 mock.side_effect = reset_data
2841 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002842 return mock
2843
2844
2845class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002846 """
2847 A mock intended to be used as a property, or other descriptor, on a class.
2848 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2849 a return value when it is fetched.
2850
2851 Fetching a `PropertyMock` instance from an object calls the mock, with
2852 no args. Setting it calls the mock with the value being set.
2853 """
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002854 def _get_child_mock(self, /, **kwargs):
Michael Foordc2870622012-04-13 16:57:22 +01002855 return MagicMock(**kwargs)
2856
Raymond Hettinger0dac68f2019-08-29 01:27:42 -07002857 def __get__(self, obj, obj_type=None):
Michael Foord345266a2012-03-14 12:24:34 -07002858 return self()
2859 def __set__(self, obj, val):
2860 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002861
2862
2863def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002864 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002865
2866 Given an input Mock, seals it to ensure no further mocks will be generated
2867 when accessing an attribute that was not already defined.
2868
Mario Corchero96200eb2018-10-19 22:57:37 +01002869 The operation recursively seals the mock passed in, meaning that
2870 the mock itself, any mocks generated by accessing one of its attributes,
2871 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002872 """
2873 mock._mock_sealed = True
2874 for attr in dir(mock):
2875 try:
2876 m = getattr(mock, attr)
2877 except AttributeError:
2878 continue
2879 if not isinstance(m, NonCallableMock):
2880 continue
2881 if m._mock_new_parent is mock:
2882 seal(m)
Lisa Roach77b3b772019-05-20 09:19:53 -07002883
2884
Lisa Roach77b3b772019-05-20 09:19:53 -07002885class _AsyncIterator:
2886 """
2887 Wraps an iterator in an asynchronous iterator.
2888 """
2889 def __init__(self, iterator):
2890 self.iterator = iterator
2891 code_mock = NonCallableMock(spec_set=CodeType)
2892 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
2893 self.__dict__['__code__'] = code_mock
2894
2895 def __aiter__(self):
2896 return self
2897
2898 async def __anext__(self):
2899 try:
2900 return next(self.iterator)
2901 except StopIteration:
2902 pass
2903 raise StopAsyncIteration