blob: d6e30679456a502bfaf430067ada73d32c77a64c [file] [log] [blame]
Michael Foord345266a2012-03-14 12:24:34 -07001# mock.py
2# Test tools for mocking and patching.
Michael Foordc17adf42012-03-14 13:30:29 -07003# Maintained by Michael Foord
4# Backport for other versions of Python available from
Ned Deily9d6d06e2018-06-11 00:45:50 -04005# https://pypi.org/project/mock
Michael Foord345266a2012-03-14 12:24:34 -07006
7__all__ = (
8 'Mock',
9 'MagicMock',
10 'patch',
11 'sentinel',
12 'DEFAULT',
13 'ANY',
14 'call',
15 'create_autospec',
Lisa Roach77b3b772019-05-20 09:19:53 -070016 'AsyncMock',
Michael Foord345266a2012-03-14 12:24:34 -070017 'FILTER_DIR',
18 'NonCallableMock',
19 'NonCallableMagicMock',
20 'mock_open',
21 'PropertyMock',
Mario Corchero552be9d2017-10-17 12:35:11 +010022 'seal',
Michael Foord345266a2012-03-14 12:24:34 -070023)
24
25
26__version__ = '1.0'
27
Lisa Roach77b3b772019-05-20 09:19:53 -070028import asyncio
Xtreak436c2b02019-05-28 12:37:39 +053029import contextlib
Rémi Lapeyre11a88322019-05-07 12:48:36 +020030import io
Michael Foord345266a2012-03-14 12:24:34 -070031import inspect
32import pprint
33import sys
Michael Foordfddcfa22014-04-14 16:25:20 -040034import builtins
Lisa Roach77b3b772019-05-20 09:19:53 -070035from types import CodeType, ModuleType, MethodType
Petter Strandmark47d94242018-10-28 21:37:10 +010036from unittest.util import safe_repr
Antoine Pitrou5c64df72013-02-03 00:23:58 +010037from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070038
39
Michael Foordfddcfa22014-04-14 16:25:20 -040040_builtins = {name for name in dir(builtins) if not name.startswith('_')}
41
Michael Foord345266a2012-03-14 12:24:34 -070042FILTER_DIR = True
43
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100044# Workaround for issue #12370
45# Without this, the __class__ properties wouldn't be set correctly
46_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070047
Lisa Roach77b3b772019-05-20 09:19:53 -070048def _is_async_obj(obj):
Miss Islington (bot)c3008dd2019-09-10 06:16:00 -070049 if _is_instance_mock(obj) and not isinstance(obj, AsyncMock):
Lisa Roach77b3b772019-05-20 09:19:53 -070050 return False
Miss Islington (bot)c3008dd2019-09-10 06:16:00 -070051 return asyncio.iscoroutinefunction(obj) or inspect.isawaitable(obj)
Lisa Roach77b3b772019-05-20 09:19:53 -070052
53
Xtreakff6b2e62019-05-27 18:26:23 +053054def _is_async_func(func):
55 if getattr(func, '__code__', None):
56 return asyncio.iscoroutinefunction(func)
57 else:
58 return False
59
60
Michael Foord345266a2012-03-14 12:24:34 -070061def _is_instance_mock(obj):
62 # can't use isinstance on Mock objects because they override __class__
63 # The base class for all mocks is NonCallableMock
64 return issubclass(type(obj), NonCallableMock)
65
66
67def _is_exception(obj):
68 return (
Chris Withers49e27f02019-05-01 08:48:44 +010069 isinstance(obj, BaseException) or
70 isinstance(obj, type) and issubclass(obj, BaseException)
Michael Foord345266a2012-03-14 12:24:34 -070071 )
72
73
Miss Islington (bot)22fd6792019-07-22 00:59:00 -070074def _extract_mock(obj):
75 # Autospecced functions will return a FunctionType with "mock" attribute
76 # which is the actual mock object that needs to be used.
77 if isinstance(obj, FunctionTypes) and hasattr(obj, 'mock'):
78 return obj.mock
79 else:
80 return obj
81
82
Antoine Pitrou5c64df72013-02-03 00:23:58 +010083def _get_signature_object(func, as_instance, eat_self):
84 """
85 Given an arbitrary, possibly callable object, try to create a suitable
86 signature object.
87 Return a (reduced func, signature) tuple, or None.
88 """
89 if isinstance(func, type) and not as_instance:
90 # If it's a type and should be modelled as a type, use __init__.
Chris Withersadbf1782019-05-01 23:04:04 +010091 func = func.__init__
Antoine Pitrou5c64df72013-02-03 00:23:58 +010092 # Skip the `self` argument in __init__
93 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070094 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010095 # If we really want to model an instance of the passed type,
96 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070097 try:
98 func = func.__call__
99 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100100 return None
101 if eat_self:
102 sig_func = partial(func, None)
103 else:
104 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -0700105 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100106 return func, inspect.signature(sig_func)
107 except ValueError:
108 # Certain callable types are not supported by inspect.signature()
109 return None
Michael Foord345266a2012-03-14 12:24:34 -0700110
111
112def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100113 sig = _get_signature_object(func, instance, skipfirst)
114 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -0700115 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100116 func, sig = sig
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300117 def checksig(self, /, *args, **kwargs):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100118 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700119 _copy_func_details(func, checksig)
120 type(mock)._mock_check_sig = checksig
Xtreakf7fa62e2018-12-12 13:24:54 +0530121 type(mock).__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700122
123
124def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700125 # we explicitly don't copy func.__dict__ into this copy as it would
126 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300127 for attribute in (
128 '__name__', '__doc__', '__text_signature__',
129 '__module__', '__defaults__', '__kwdefaults__',
130 ):
131 try:
132 setattr(funcopy, attribute, getattr(func, attribute))
133 except AttributeError:
134 pass
Michael Foord345266a2012-03-14 12:24:34 -0700135
136
137def _callable(obj):
138 if isinstance(obj, type):
139 return True
Xtreak9b218562019-04-22 08:00:23 +0530140 if isinstance(obj, (staticmethod, classmethod, MethodType)):
141 return _callable(obj.__func__)
Michael Foord345266a2012-03-14 12:24:34 -0700142 if getattr(obj, '__call__', None) is not None:
143 return True
144 return False
145
146
147def _is_list(obj):
148 # checks for list or tuples
149 # XXXX badly named!
150 return type(obj) in (list, tuple)
151
152
153def _instance_callable(obj):
154 """Given an object, return True if the object is callable.
155 For classes, return True if instances would be callable."""
156 if not isinstance(obj, type):
157 # already an instance
158 return getattr(obj, '__call__', None) is not None
159
Michael Foorda74b3aa2012-03-14 14:40:22 -0700160 # *could* be broken by a class overriding __mro__ or __dict__ via
161 # a metaclass
162 for base in (obj,) + obj.__mro__:
163 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700164 return True
165 return False
166
167
168def _set_signature(mock, original, instance=False):
169 # creates a function with signature (*args, **kwargs) that delegates to a
170 # mock. It still does signature checking by calling a lambda with the same
171 # signature as the original.
Michael Foord345266a2012-03-14 12:24:34 -0700172
173 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100174 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700175 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700176 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100177 func, sig = result
178 def checksig(*args, **kwargs):
179 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700180 _copy_func_details(func, checksig)
181
182 name = original.__name__
183 if not name.isidentifier():
184 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100185 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700186 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100187 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700188 return mock(*args, **kwargs)""" % name
189 exec (src, context)
190 funcopy = context[name]
Xtreakf7fa62e2018-12-12 13:24:54 +0530191 _setup_func(funcopy, mock, sig)
Michael Foord345266a2012-03-14 12:24:34 -0700192 return funcopy
193
194
Xtreakf7fa62e2018-12-12 13:24:54 +0530195def _setup_func(funcopy, mock, sig):
Michael Foord345266a2012-03-14 12:24:34 -0700196 funcopy.mock = mock
197
Michael Foord345266a2012-03-14 12:24:34 -0700198 def assert_called_with(*args, **kwargs):
199 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700200 def assert_called(*args, **kwargs):
201 return mock.assert_called(*args, **kwargs)
202 def assert_not_called(*args, **kwargs):
203 return mock.assert_not_called(*args, **kwargs)
204 def assert_called_once(*args, **kwargs):
205 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700206 def assert_called_once_with(*args, **kwargs):
207 return mock.assert_called_once_with(*args, **kwargs)
208 def assert_has_calls(*args, **kwargs):
209 return mock.assert_has_calls(*args, **kwargs)
210 def assert_any_call(*args, **kwargs):
211 return mock.assert_any_call(*args, **kwargs)
212 def reset_mock():
213 funcopy.method_calls = _CallList()
214 funcopy.mock_calls = _CallList()
215 mock.reset_mock()
216 ret = funcopy.return_value
217 if _is_instance_mock(ret) and not ret is mock:
218 ret.reset_mock()
219
220 funcopy.called = False
221 funcopy.call_count = 0
222 funcopy.call_args = None
223 funcopy.call_args_list = _CallList()
224 funcopy.method_calls = _CallList()
225 funcopy.mock_calls = _CallList()
226
227 funcopy.return_value = mock.return_value
228 funcopy.side_effect = mock.side_effect
229 funcopy._mock_children = mock._mock_children
230
231 funcopy.assert_called_with = assert_called_with
232 funcopy.assert_called_once_with = assert_called_once_with
233 funcopy.assert_has_calls = assert_has_calls
234 funcopy.assert_any_call = assert_any_call
235 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700236 funcopy.assert_called = assert_called
237 funcopy.assert_not_called = assert_not_called
238 funcopy.assert_called_once = assert_called_once
Xtreakf7fa62e2018-12-12 13:24:54 +0530239 funcopy.__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700240
241 mock._mock_delegate = funcopy
242
243
Xtreakff6b2e62019-05-27 18:26:23 +0530244def _setup_async_mock(mock):
245 mock._is_coroutine = asyncio.coroutines._is_coroutine
246 mock.await_count = 0
247 mock.await_args = None
248 mock.await_args_list = _CallList()
Xtreakff6b2e62019-05-27 18:26:23 +0530249
250 # Mock is not configured yet so the attributes are set
251 # to a function and then the corresponding mock helper function
252 # is called when the helper is accessed similar to _setup_func.
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300253 def wrapper(attr, /, *args, **kwargs):
Xtreakff6b2e62019-05-27 18:26:23 +0530254 return getattr(mock.mock, attr)(*args, **kwargs)
255
256 for attribute in ('assert_awaited',
257 'assert_awaited_once',
258 'assert_awaited_with',
259 'assert_awaited_once_with',
260 'assert_any_await',
261 'assert_has_awaits',
262 'assert_not_awaited'):
263
264 # setattr(mock, attribute, wrapper) causes late binding
265 # hence attribute will always be the last value in the loop
266 # Use partial(wrapper, attribute) to ensure the attribute is bound
267 # correctly.
268 setattr(mock, attribute, partial(wrapper, attribute))
269
270
Michael Foord345266a2012-03-14 12:24:34 -0700271def _is_magic(name):
272 return '__%s__' % name[2:-2] == name
273
274
275class _SentinelObject(object):
276 "A unique, named, sentinel object."
277 def __init__(self, name):
278 self.name = name
279
280 def __repr__(self):
281 return 'sentinel.%s' % self.name
282
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200283 def __reduce__(self):
284 return 'sentinel.%s' % self.name
285
Michael Foord345266a2012-03-14 12:24:34 -0700286
287class _Sentinel(object):
288 """Access attributes to return a named object, usable as a sentinel."""
289 def __init__(self):
290 self._sentinels = {}
291
292 def __getattr__(self, name):
293 if name == '__bases__':
294 # Without this help(unittest.mock) raises an exception
295 raise AttributeError
296 return self._sentinels.setdefault(name, _SentinelObject(name))
297
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200298 def __reduce__(self):
299 return 'sentinel'
300
Michael Foord345266a2012-03-14 12:24:34 -0700301
302sentinel = _Sentinel()
303
304DEFAULT = sentinel.DEFAULT
305_missing = sentinel.MISSING
306_deleted = sentinel.DELETED
307
308
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200309_allowed_names = {
310 'return_value', '_mock_return_value', 'side_effect',
311 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
312 '_mock_name', '_mock_new_name'
313}
Michael Foord345266a2012-03-14 12:24:34 -0700314
315
316def _delegating_property(name):
317 _allowed_names.add(name)
318 _the_name = '_mock_' + name
319 def _get(self, name=name, _the_name=_the_name):
320 sig = self._mock_delegate
321 if sig is None:
322 return getattr(self, _the_name)
323 return getattr(sig, name)
324 def _set(self, value, name=name, _the_name=_the_name):
325 sig = self._mock_delegate
326 if sig is None:
327 self.__dict__[_the_name] = value
328 else:
329 setattr(sig, name, value)
330
331 return property(_get, _set)
332
333
334
335class _CallList(list):
336
337 def __contains__(self, value):
338 if not isinstance(value, list):
339 return list.__contains__(self, value)
340 len_value = len(value)
341 len_self = len(self)
342 if len_value > len_self:
343 return False
344
345 for i in range(0, len_self - len_value + 1):
346 sub_list = self[i:i+len_value]
347 if sub_list == value:
348 return True
349 return False
350
351 def __repr__(self):
352 return pprint.pformat(list(self))
353
354
355def _check_and_set_parent(parent, value, name, new_name):
Miss Islington (bot)22fd6792019-07-22 00:59:00 -0700356 value = _extract_mock(value)
Xtreak9c3f2842019-02-26 03:16:34 +0530357
Michael Foord345266a2012-03-14 12:24:34 -0700358 if not _is_instance_mock(value):
359 return False
360 if ((value._mock_name or value._mock_new_name) or
361 (value._mock_parent is not None) or
362 (value._mock_new_parent is not None)):
363 return False
364
365 _parent = parent
366 while _parent is not None:
367 # setting a mock (value) as a child or return value of itself
368 # should not modify the mock
369 if _parent is value:
370 return False
371 _parent = _parent._mock_new_parent
372
373 if new_name:
374 value._mock_new_parent = parent
375 value._mock_new_name = new_name
376 if name:
377 value._mock_parent = parent
378 value._mock_name = name
379 return True
380
Michael Foord01bafdc2014-04-14 16:09:42 -0400381# Internal class to identify if we wrapped an iterator object or not.
382class _MockIter(object):
383 def __init__(self, obj):
384 self.obj = iter(obj)
Michael Foord01bafdc2014-04-14 16:09:42 -0400385 def __next__(self):
386 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700387
388class Base(object):
389 _mock_return_value = DEFAULT
390 _mock_side_effect = None
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300391 def __init__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700392 pass
393
394
395
396class NonCallableMock(Base):
397 """A non-callable version of `Mock`"""
398
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300399 def __new__(cls, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700400 # every instance has its own class
401 # so we can create magic methods on the
402 # class without stomping on other mocks
Lisa Roach77b3b772019-05-20 09:19:53 -0700403 bases = (cls,)
404 if not issubclass(cls, AsyncMock):
405 # Check if spec is an async object or function
406 sig = inspect.signature(NonCallableMock.__init__)
407 bound_args = sig.bind_partial(cls, *args, **kw).arguments
408 spec_arg = [
409 arg for arg in bound_args.keys()
410 if arg.startswith('spec')
411 ]
412 if spec_arg:
413 # what if spec_set is different than spec?
414 if _is_async_obj(bound_args[spec_arg[0]]):
415 bases = (AsyncMockMixin, cls,)
416 new = type(cls.__name__, bases, {'__doc__': cls.__doc__})
Miss Islington (bot)b76ab352019-09-29 21:02:46 -0700417 instance = _safe_super(NonCallableMock, cls).__new__(new)
Michael Foord345266a2012-03-14 12:24:34 -0700418 return instance
419
420
421 def __init__(
422 self, spec=None, wraps=None, name=None, spec_set=None,
423 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530424 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700425 ):
426 if _new_parent is None:
427 _new_parent = parent
428
429 __dict__ = self.__dict__
430 __dict__['_mock_parent'] = parent
431 __dict__['_mock_name'] = name
432 __dict__['_mock_new_name'] = _new_name
433 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100434 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700435
436 if spec_set is not None:
437 spec = spec_set
438 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100439 if _eat_self is None:
440 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700441
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100442 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700443
444 __dict__['_mock_children'] = {}
445 __dict__['_mock_wraps'] = wraps
446 __dict__['_mock_delegate'] = None
447
448 __dict__['_mock_called'] = False
449 __dict__['_mock_call_args'] = None
450 __dict__['_mock_call_count'] = 0
451 __dict__['_mock_call_args_list'] = _CallList()
452 __dict__['_mock_mock_calls'] = _CallList()
453
454 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530455 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700456
457 if kwargs:
458 self.configure_mock(**kwargs)
459
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000460 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700461 spec, wraps, name, spec_set, parent,
462 _spec_state
463 )
464
465
466 def attach_mock(self, mock, attribute):
467 """
468 Attach a mock as an attribute of this one, replacing its name and
469 parent. Calls to the attached mock will be recorded in the
470 `method_calls` and `mock_calls` attributes of this one."""
Miss Islington (bot)22fd6792019-07-22 00:59:00 -0700471 inner_mock = _extract_mock(mock)
472
473 inner_mock._mock_parent = None
474 inner_mock._mock_new_parent = None
475 inner_mock._mock_name = ''
476 inner_mock._mock_new_name = None
Michael Foord345266a2012-03-14 12:24:34 -0700477
478 setattr(self, attribute, mock)
479
480
481 def mock_add_spec(self, spec, spec_set=False):
482 """Add a spec to a mock. `spec` can either be an object or a
483 list of strings. Only attributes on the `spec` can be fetched as
484 attributes from the mock.
485
486 If `spec_set` is True then only attributes on the spec can be set."""
487 self._mock_add_spec(spec, spec_set)
488
489
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100490 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
491 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700492 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100493 _spec_signature = None
Lisa Roach77b3b772019-05-20 09:19:53 -0700494 _spec_asyncs = []
495
496 for attr in dir(spec):
497 if asyncio.iscoroutinefunction(getattr(spec, attr, None)):
498 _spec_asyncs.append(attr)
Michael Foord345266a2012-03-14 12:24:34 -0700499
500 if spec is not None and not _is_list(spec):
501 if isinstance(spec, type):
502 _spec_class = spec
503 else:
Chris Withersadbf1782019-05-01 23:04:04 +0100504 _spec_class = type(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100505 res = _get_signature_object(spec,
506 _spec_as_instance, _eat_self)
507 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700508
509 spec = dir(spec)
510
511 __dict__ = self.__dict__
512 __dict__['_spec_class'] = _spec_class
513 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100514 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700515 __dict__['_mock_methods'] = spec
Lisa Roach77b3b772019-05-20 09:19:53 -0700516 __dict__['_spec_asyncs'] = _spec_asyncs
Michael Foord345266a2012-03-14 12:24:34 -0700517
518 def __get_return_value(self):
519 ret = self._mock_return_value
520 if self._mock_delegate is not None:
521 ret = self._mock_delegate.return_value
522
523 if ret is DEFAULT:
524 ret = self._get_child_mock(
525 _new_parent=self, _new_name='()'
526 )
527 self.return_value = ret
528 return ret
529
530
531 def __set_return_value(self, value):
532 if self._mock_delegate is not None:
533 self._mock_delegate.return_value = value
534 else:
535 self._mock_return_value = value
536 _check_and_set_parent(self, value, None, '()')
537
538 __return_value_doc = "The value to be returned when the mock is called."
539 return_value = property(__get_return_value, __set_return_value,
540 __return_value_doc)
541
542
543 @property
544 def __class__(self):
545 if self._spec_class is None:
546 return type(self)
547 return self._spec_class
548
549 called = _delegating_property('called')
550 call_count = _delegating_property('call_count')
551 call_args = _delegating_property('call_args')
552 call_args_list = _delegating_property('call_args_list')
553 mock_calls = _delegating_property('mock_calls')
554
555
556 def __get_side_effect(self):
557 delegated = self._mock_delegate
558 if delegated is None:
559 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400560 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200561 if (sf is not None and not callable(sf)
562 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400563 sf = _MockIter(sf)
564 delegated.side_effect = sf
565 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700566
567 def __set_side_effect(self, value):
568 value = _try_iter(value)
569 delegated = self._mock_delegate
570 if delegated is None:
571 self._mock_side_effect = value
572 else:
573 delegated.side_effect = value
574
575 side_effect = property(__get_side_effect, __set_side_effect)
576
577
Kushal Das9cd39a12016-06-02 10:20:16 -0700578 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700579 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200580 if visited is None:
581 visited = []
582 if id(self) in visited:
583 return
584 visited.append(id(self))
585
Michael Foord345266a2012-03-14 12:24:34 -0700586 self.called = False
587 self.call_args = None
588 self.call_count = 0
589 self.mock_calls = _CallList()
590 self.call_args_list = _CallList()
591 self.method_calls = _CallList()
592
Kushal Das9cd39a12016-06-02 10:20:16 -0700593 if return_value:
594 self._mock_return_value = DEFAULT
595 if side_effect:
596 self._mock_side_effect = None
597
Michael Foord345266a2012-03-14 12:24:34 -0700598 for child in self._mock_children.values():
Xtreakedeca922018-12-01 15:33:54 +0530599 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100600 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200601 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700602
603 ret = self._mock_return_value
604 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200605 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700606
607
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300608 def configure_mock(self, /, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700609 """Set attributes on the mock through keyword arguments.
610
611 Attributes plus return values and side effects can be set on child
612 mocks using standard dot notation and unpacking a dictionary in the
613 method call:
614
615 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
616 >>> mock.configure_mock(**attrs)"""
617 for arg, val in sorted(kwargs.items(),
618 # we sort on the number of dots so that
619 # attributes are set before we set attributes on
620 # attributes
621 key=lambda entry: entry[0].count('.')):
622 args = arg.split('.')
623 final = args.pop()
624 obj = self
625 for entry in args:
626 obj = getattr(obj, entry)
627 setattr(obj, final, val)
628
629
630 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530631 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700632 raise AttributeError(name)
633 elif self._mock_methods is not None:
634 if name not in self._mock_methods or name in _all_magics:
635 raise AttributeError("Mock object has no attribute %r" % name)
636 elif _is_magic(name):
637 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530638 if not self._mock_unsafe:
639 if name.startswith(('assert', 'assret')):
Zackery Spytzb9b08cd2019-05-08 11:32:24 -0600640 raise AttributeError("Attributes cannot start with 'assert' "
641 "or 'assret'")
Michael Foord345266a2012-03-14 12:24:34 -0700642
643 result = self._mock_children.get(name)
644 if result is _deleted:
645 raise AttributeError(name)
646 elif result is None:
647 wraps = None
648 if self._mock_wraps is not None:
649 # XXXX should we get the attribute without triggering code
650 # execution?
651 wraps = getattr(self._mock_wraps, name)
652
653 result = self._get_child_mock(
654 parent=self, name=name, wraps=wraps, _new_name=name,
655 _new_parent=self
656 )
657 self._mock_children[name] = result
658
659 elif isinstance(result, _SpecState):
660 result = create_autospec(
661 result.spec, result.spec_set, result.instance,
662 result.parent, result.name
663 )
664 self._mock_children[name] = result
665
666 return result
667
668
Mario Corchero552be9d2017-10-17 12:35:11 +0100669 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700670 _name_list = [self._mock_new_name]
671 _parent = self._mock_new_parent
672 last = self
673
674 dot = '.'
675 if _name_list == ['()']:
676 dot = ''
Chris Withersadbf1782019-05-01 23:04:04 +0100677
Michael Foord345266a2012-03-14 12:24:34 -0700678 while _parent is not None:
679 last = _parent
680
681 _name_list.append(_parent._mock_new_name + dot)
682 dot = '.'
683 if _parent._mock_new_name == '()':
684 dot = ''
685
686 _parent = _parent._mock_new_parent
687
Michael Foord345266a2012-03-14 12:24:34 -0700688 _name_list = list(reversed(_name_list))
689 _first = last._mock_name or 'mock'
690 if len(_name_list) > 1:
691 if _name_list[1] not in ('()', '().'):
692 _first += '.'
693 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100694 return ''.join(_name_list)
695
696 def __repr__(self):
697 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700698
699 name_string = ''
700 if name not in ('mock', 'mock.'):
701 name_string = ' name=%r' % name
702
703 spec_string = ''
704 if self._spec_class is not None:
705 spec_string = ' spec=%r'
706 if self._spec_set:
707 spec_string = ' spec_set=%r'
708 spec_string = spec_string % self._spec_class.__name__
709 return "<%s%s%s id='%s'>" % (
710 type(self).__name__,
711 name_string,
712 spec_string,
713 id(self)
714 )
715
716
717 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700718 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100719 if not FILTER_DIR:
720 return object.__dir__(self)
721
Michael Foord345266a2012-03-14 12:24:34 -0700722 extras = self._mock_methods or []
723 from_type = dir(type(self))
724 from_dict = list(self.__dict__)
Mario Corchero0df635c2019-04-30 19:56:36 +0100725 from_child_mocks = [
726 m_name for m_name, m_value in self._mock_children.items()
727 if m_value is not _deleted]
Michael Foord345266a2012-03-14 12:24:34 -0700728
Michael Foord313f85f2012-03-25 18:16:07 +0100729 from_type = [e for e in from_type if not e.startswith('_')]
730 from_dict = [e for e in from_dict if not e.startswith('_') or
731 _is_magic(e)]
Mario Corchero0df635c2019-04-30 19:56:36 +0100732 return sorted(set(extras + from_type + from_dict + from_child_mocks))
Michael Foord345266a2012-03-14 12:24:34 -0700733
734
735 def __setattr__(self, name, value):
736 if name in _allowed_names:
737 # property setters go through here
738 return object.__setattr__(self, name, value)
739 elif (self._spec_set and self._mock_methods is not None and
740 name not in self._mock_methods and
741 name not in self.__dict__):
742 raise AttributeError("Mock object has no attribute '%s'" % name)
743 elif name in _unsupported_magics:
744 msg = 'Attempting to set unsupported magic method %r.' % name
745 raise AttributeError(msg)
746 elif name in _all_magics:
747 if self._mock_methods is not None and name not in self._mock_methods:
748 raise AttributeError("Mock object has no attribute '%s'" % name)
749
750 if not _is_instance_mock(value):
751 setattr(type(self), name, _get_method(name, value))
752 original = value
753 value = lambda *args, **kw: original(self, *args, **kw)
754 else:
755 # only set _new_name and not name so that mock_calls is tracked
756 # but not method calls
757 _check_and_set_parent(self, value, None, name)
758 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100759 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700760 elif name == '__class__':
761 self._spec_class = value
762 return
763 else:
764 if _check_and_set_parent(self, value, name, name):
765 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100766
767 if self._mock_sealed and not hasattr(self, name):
768 mock_name = f'{self._extract_mock_name()}.{name}'
769 raise AttributeError(f'Cannot set {mock_name}')
770
Michael Foord345266a2012-03-14 12:24:34 -0700771 return object.__setattr__(self, name, value)
772
773
774 def __delattr__(self, name):
775 if name in _all_magics and name in type(self).__dict__:
776 delattr(type(self), name)
777 if name not in self.__dict__:
778 # for magic methods that are still MagicProxy objects and
779 # not set on the instance itself
780 return
781
Michael Foord345266a2012-03-14 12:24:34 -0700782 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000783 if name in self.__dict__:
Xtreak830b43d2019-04-14 00:42:33 +0530784 _safe_super(NonCallableMock, self).__delattr__(name)
Pablo Galindo222d3032019-01-21 08:57:46 +0000785 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700786 raise AttributeError(name)
787 if obj is not _missing:
788 del self._mock_children[name]
789 self._mock_children[name] = _deleted
790
791
Michael Foord345266a2012-03-14 12:24:34 -0700792 def _format_mock_call_signature(self, args, kwargs):
793 name = self._mock_name or 'mock'
794 return _format_call_signature(name, args, kwargs)
795
796
Xtreak0ae022c2019-05-29 12:32:26 +0530797 def _format_mock_failure_message(self, args, kwargs, action='call'):
798 message = 'expected %s not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700799 expected_string = self._format_mock_call_signature(args, kwargs)
800 call_args = self.call_args
Michael Foord345266a2012-03-14 12:24:34 -0700801 actual_string = self._format_mock_call_signature(*call_args)
Xtreak0ae022c2019-05-29 12:32:26 +0530802 return message % (action, expected_string, actual_string)
Michael Foord345266a2012-03-14 12:24:34 -0700803
804
Miss Islington (bot)38d311d2019-08-28 23:58:27 -0700805 def _get_call_signature_from_name(self, name):
806 """
807 * If call objects are asserted against a method/function like obj.meth1
808 then there could be no name for the call object to lookup. Hence just
809 return the spec_signature of the method/function being asserted against.
810 * If the name is not empty then remove () and split by '.' to get
811 list of names to iterate through the children until a potential
812 match is found. A child mock is created only during attribute access
813 so if we get a _SpecState then no attributes of the spec were accessed
814 and can be safely exited.
815 """
816 if not name:
817 return self._spec_signature
818
819 sig = None
820 names = name.replace('()', '').split('.')
821 children = self._mock_children
822
823 for name in names:
824 child = children.get(name)
825 if child is None or isinstance(child, _SpecState):
826 break
827 else:
828 children = child._mock_children
829 sig = child._spec_signature
830
831 return sig
832
833
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100834 def _call_matcher(self, _call):
835 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000836 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100837 comparison key suitable for matching with other calls.
838 This is a best effort method which relies on the spec's signature,
839 if available, or falls back on the arguments themselves.
840 """
Miss Islington (bot)38d311d2019-08-28 23:58:27 -0700841
842 if isinstance(_call, tuple) and len(_call) > 2:
843 sig = self._get_call_signature_from_name(_call[0])
844 else:
845 sig = self._spec_signature
846
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100847 if sig is not None:
848 if len(_call) == 2:
849 name = ''
850 args, kwargs = _call
851 else:
852 name, args, kwargs = _call
853 try:
854 return name, sig.bind(*args, **kwargs)
855 except TypeError as e:
856 return e.with_traceback(None)
857 else:
858 return _call
859
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300860 def assert_not_called(self):
Kushal Das8af9db32014-04-17 01:36:14 +0530861 """assert that the mock was never called.
862 """
Kushal Das8af9db32014-04-17 01:36:14 +0530863 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100864 msg = ("Expected '%s' to not have been called. Called %s times.%s"
865 % (self._mock_name or 'mock',
866 self.call_count,
867 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530868 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100869
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300870 def assert_called(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100871 """assert that the mock was called at least once
872 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100873 if self.call_count == 0:
874 msg = ("Expected '%s' to have been called." %
Miss Islington (bot)f668d2b2019-09-17 04:35:56 -0700875 (self._mock_name or 'mock'))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100876 raise AssertionError(msg)
877
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300878 def assert_called_once(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100879 """assert that the mock was called only once.
880 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100881 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100882 msg = ("Expected '%s' to have been called once. Called %s times.%s"
883 % (self._mock_name or 'mock',
884 self.call_count,
885 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100886 raise AssertionError(msg)
887
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300888 def assert_called_with(self, /, *args, **kwargs):
Miss Islington (bot)612d3932019-08-28 23:39:47 -0700889 """assert that the last call was made with the specified arguments.
Michael Foord345266a2012-03-14 12:24:34 -0700890
891 Raises an AssertionError if the args and keyword args passed in are
892 different to the last call to the mock."""
Michael Foord345266a2012-03-14 12:24:34 -0700893 if self.call_args is None:
894 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800895 actual = 'not called.'
896 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
897 % (expected, actual))
898 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700899
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100900 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700901 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100902 return msg
903 expected = self._call_matcher((args, kwargs))
904 actual = self._call_matcher(self.call_args)
905 if expected != actual:
906 cause = expected if isinstance(expected, Exception) else None
907 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700908
909
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300910 def assert_called_once_with(self, /, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100911 """assert that the mock was called exactly once and that that call was
912 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700913 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100914 msg = ("Expected '%s' to be called once. Called %s times.%s"
915 % (self._mock_name or 'mock',
916 self.call_count,
917 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700918 raise AssertionError(msg)
919 return self.assert_called_with(*args, **kwargs)
920
921
922 def assert_has_calls(self, calls, any_order=False):
923 """assert the mock has been called with the specified calls.
924 The `mock_calls` list is checked for the calls.
925
926 If `any_order` is False (the default) then the calls must be
927 sequential. There can be extra calls before or after the
928 specified calls.
929
930 If `any_order` is True then the calls can be in any order, but
931 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100932 expected = [self._call_matcher(c) for c in calls]
Miss Islington (bot)1a17a052019-09-24 17:29:17 -0700933 cause = next((e for e in expected if isinstance(e, Exception)), None)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100934 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700935 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100936 if expected not in all_calls:
Miss Islington (bot)1a17a052019-09-24 17:29:17 -0700937 if cause is None:
938 problem = 'Calls not found.'
939 else:
940 problem = ('Error processing expected calls.\n'
941 'Errors: {}').format(
942 [e if isinstance(e, Exception) else None
943 for e in expected])
Michael Foord345266a2012-03-14 12:24:34 -0700944 raise AssertionError(
Miss Islington (bot)1a17a052019-09-24 17:29:17 -0700945 f'{problem}\n'
946 f'Expected: {_CallList(calls)}'
947 f'{self._calls_repr(prefix="Actual").rstrip(".")}'
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100948 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700949 return
950
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100951 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700952
953 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100954 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700955 try:
956 all_calls.remove(kall)
957 except ValueError:
958 not_found.append(kall)
959 if not_found:
960 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400961 '%r does not contain all of %r in its call list, '
962 'found %r instead' % (self._mock_name or 'mock',
963 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100964 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700965
966
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300967 def assert_any_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700968 """assert the mock has been called with the specified arguments.
969
970 The assert passes if the mock has *ever* been called, unlike
971 `assert_called_with` and `assert_called_once_with` that only pass if
972 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100973 expected = self._call_matcher((args, kwargs))
974 actual = [self._call_matcher(c) for c in self.call_args_list]
975 if expected not in actual:
976 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700977 expected_string = self._format_mock_call_signature(args, kwargs)
978 raise AssertionError(
979 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100980 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700981
982
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300983 def _get_child_mock(self, /, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700984 """Create the child mocks for attributes and return value.
985 By default child mocks will be the same type as the parent.
986 Subclasses of Mock may want to override this to customize the way
987 child mocks are made.
988
989 For non-callable mocks the callable variant will be used (rather than
990 any custom subclass)."""
Lisa Roach77b3b772019-05-20 09:19:53 -0700991 _new_name = kw.get("_new_name")
992 if _new_name in self.__dict__['_spec_asyncs']:
993 return AsyncMock(**kw)
994
Michael Foord345266a2012-03-14 12:24:34 -0700995 _type = type(self)
Lisa Roach77b3b772019-05-20 09:19:53 -0700996 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
Miss Islington (bot)b76ab352019-09-29 21:02:46 -0700997 # Any asynchronous magic becomes an AsyncMock
Lisa Roach77b3b772019-05-20 09:19:53 -0700998 klass = AsyncMock
Lisa Roach865bb682019-09-20 23:00:04 -0700999 elif issubclass(_type, AsyncMockMixin):
Lisa Roach21f24ea2019-09-29 22:22:44 -07001000 if (_new_name in _all_sync_magics or
1001 self._mock_methods and _new_name in self._mock_methods):
1002 # Any synchronous method on AsyncMock becomes a MagicMock
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07001003 klass = MagicMock
1004 else:
1005 klass = AsyncMock
Lisa Roach865bb682019-09-20 23:00:04 -07001006 elif not issubclass(_type, CallableMixin):
Michael Foord345266a2012-03-14 12:24:34 -07001007 if issubclass(_type, NonCallableMagicMock):
1008 klass = MagicMock
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07001009 elif issubclass(_type, NonCallableMock):
Michael Foord345266a2012-03-14 12:24:34 -07001010 klass = Mock
1011 else:
1012 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +01001013
1014 if self._mock_sealed:
1015 attribute = "." + kw["name"] if "name" in kw else "()"
1016 mock_name = self._extract_mock_name() + attribute
1017 raise AttributeError(mock_name)
1018
Michael Foord345266a2012-03-14 12:24:34 -07001019 return klass(**kw)
1020
1021
Petter Strandmark47d94242018-10-28 21:37:10 +01001022 def _calls_repr(self, prefix="Calls"):
1023 """Renders self.mock_calls as a string.
1024
1025 Example: "\nCalls: [call(1), call(2)]."
1026
1027 If self.mock_calls is empty, an empty string is returned. The
1028 output will be truncated if very long.
1029 """
1030 if not self.mock_calls:
1031 return ""
1032 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
1033
1034
Michael Foord345266a2012-03-14 12:24:34 -07001035
1036def _try_iter(obj):
1037 if obj is None:
1038 return obj
1039 if _is_exception(obj):
1040 return obj
1041 if _callable(obj):
1042 return obj
1043 try:
1044 return iter(obj)
1045 except TypeError:
1046 # XXXX backwards compatibility
1047 # but this will blow up on first call - so maybe we should fail early?
1048 return obj
1049
1050
Michael Foord345266a2012-03-14 12:24:34 -07001051class CallableMixin(Base):
1052
1053 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
1054 wraps=None, name=None, spec_set=None, parent=None,
1055 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
1056 self.__dict__['_mock_return_value'] = return_value
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001057 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -07001058 spec, wraps, name, spec_set, parent,
1059 _spec_state, _new_name, _new_parent, **kwargs
1060 )
1061
1062 self.side_effect = side_effect
1063
1064
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001065 def _mock_check_sig(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001066 # stub method that can be replaced with one with a specific signature
1067 pass
1068
1069
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001070 def __call__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001071 # can't use self in-case a function / method we are mocking uses self
1072 # in the signature
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001073 self._mock_check_sig(*args, **kwargs)
Lisa Roach52bdd412019-09-27 15:44:34 -07001074 self._increment_mock_call(*args, **kwargs)
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001075 return self._mock_call(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001076
1077
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001078 def _mock_call(self, /, *args, **kwargs):
Lisa Roach52bdd412019-09-27 15:44:34 -07001079 return self._execute_mock_call(*args, **kwargs)
1080
1081 def _increment_mock_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001082 self.called = True
1083 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001084
Chris Withers8ca0fa92018-12-03 21:31:37 +00001085 # handle call_args
Lisa Roach52bdd412019-09-27 15:44:34 -07001086 # needs to be set here so assertions on call arguments pass before
1087 # execution in the case of awaited calls
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001088 _call = _Call((args, kwargs), two=True)
1089 self.call_args = _call
1090 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -07001091
Chris Withers8ca0fa92018-12-03 21:31:37 +00001092 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001093 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +00001094 method_call_name = self._mock_name
1095
1096 # initial stuff for mock_calls:
1097 mock_call_name = self._mock_new_name
1098 is_a_call = mock_call_name == '()'
1099 self.mock_calls.append(_Call(('', args, kwargs)))
1100
1101 # follow up the chain of mocks:
1102 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001103 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001104
Chris Withers8ca0fa92018-12-03 21:31:37 +00001105 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001106 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001107 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001108 do_method_calls = _new_parent._mock_parent is not None
1109 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001110 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001111
Chris Withers8ca0fa92018-12-03 21:31:37 +00001112 # handle mock_calls:
1113 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001114 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001115
1116 if _new_parent._mock_new_name:
1117 if is_a_call:
1118 dot = ''
1119 else:
1120 dot = '.'
1121 is_a_call = _new_parent._mock_new_name == '()'
1122 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1123
1124 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001125 _new_parent = _new_parent._mock_new_parent
1126
Lisa Roach52bdd412019-09-27 15:44:34 -07001127 def _execute_mock_call(self, /, *args, **kwargs):
Lisa Roachb2744c12019-11-21 10:14:32 -08001128 # separate from _increment_mock_call so that awaited functions are
1129 # executed separately from their call, also AsyncMock overrides this method
Lisa Roach52bdd412019-09-27 15:44:34 -07001130
Michael Foord345266a2012-03-14 12:24:34 -07001131 effect = self.side_effect
1132 if effect is not None:
1133 if _is_exception(effect):
1134 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001135 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001136 result = next(effect)
1137 if _is_exception(result):
1138 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001139 else:
1140 result = effect(*args, **kwargs)
1141
1142 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001143 return result
Michael Foord345266a2012-03-14 12:24:34 -07001144
Mario Corcherof05df0a2018-12-08 11:25:02 +00001145 if self._mock_return_value is not DEFAULT:
1146 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001147
Mario Corcherof05df0a2018-12-08 11:25:02 +00001148 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001149 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001150
1151 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001152
1153
1154
1155class Mock(CallableMixin, NonCallableMock):
1156 """
1157 Create a new `Mock` object. `Mock` takes several optional arguments
1158 that specify the behaviour of the Mock object:
1159
1160 * `spec`: This can be either a list of strings or an existing object (a
1161 class or instance) that acts as the specification for the mock object. If
1162 you pass in an object then a list of strings is formed by calling dir on
1163 the object (excluding unsupported magic attributes and methods). Accessing
1164 any attribute not in this list will raise an `AttributeError`.
1165
1166 If `spec` is an object (rather than a list of strings) then
1167 `mock.__class__` returns the class of the spec object. This allows mocks
1168 to pass `isinstance` tests.
1169
1170 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1171 or get an attribute on the mock that isn't on the object passed as
1172 `spec_set` will raise an `AttributeError`.
1173
1174 * `side_effect`: A function to be called whenever the Mock is called. See
1175 the `side_effect` attribute. Useful for raising exceptions or
1176 dynamically changing return values. The function is called with the same
1177 arguments as the mock, and unless it returns `DEFAULT`, the return
1178 value of this function is used as the return value.
1179
Michael Foord2cd48732012-04-21 15:52:11 +01001180 If `side_effect` is an iterable then each call to the mock will return
1181 the next value from the iterable. If any of the members of the iterable
1182 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001183
Michael Foord345266a2012-03-14 12:24:34 -07001184 * `return_value`: The value returned when the mock is called. By default
1185 this is a new Mock (created on first access). See the
1186 `return_value` attribute.
1187
Michael Foord0682a0c2012-04-13 20:51:20 +01001188 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1189 calling the Mock will pass the call through to the wrapped object
1190 (returning the real result). Attribute access on the mock will return a
1191 Mock object that wraps the corresponding attribute of the wrapped object
1192 (so attempting to access an attribute that doesn't exist will raise an
1193 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001194
1195 If the mock has an explicit `return_value` set then calls are not passed
1196 to the wrapped object and the `return_value` is returned instead.
1197
1198 * `name`: If the mock has a name then it will be used in the repr of the
1199 mock. This can be useful for debugging. The name is propagated to child
1200 mocks.
1201
1202 Mocks can also be called with arbitrary keyword arguments. These will be
1203 used to set attributes on the mock after it is created.
1204 """
1205
1206
Michael Foord345266a2012-03-14 12:24:34 -07001207def _dot_lookup(thing, comp, import_path):
1208 try:
1209 return getattr(thing, comp)
1210 except AttributeError:
1211 __import__(import_path)
1212 return getattr(thing, comp)
1213
1214
1215def _importer(target):
1216 components = target.split('.')
1217 import_path = components.pop(0)
1218 thing = __import__(import_path)
1219
1220 for comp in components:
1221 import_path += ".%s" % comp
1222 thing = _dot_lookup(thing, comp, import_path)
1223 return thing
1224
1225
1226def _is_started(patcher):
1227 # XXXX horrible
1228 return hasattr(patcher, 'is_local')
1229
1230
1231class _patch(object):
1232
1233 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001234 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001235
1236 def __init__(
1237 self, getter, attribute, new, spec, create,
1238 spec_set, autospec, new_callable, kwargs
1239 ):
1240 if new_callable is not None:
1241 if new is not DEFAULT:
1242 raise ValueError(
1243 "Cannot use 'new' and 'new_callable' together"
1244 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001245 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001246 raise ValueError(
1247 "Cannot use 'autospec' and 'new_callable' together"
1248 )
1249
1250 self.getter = getter
1251 self.attribute = attribute
1252 self.new = new
1253 self.new_callable = new_callable
1254 self.spec = spec
1255 self.create = create
1256 self.has_local = False
1257 self.spec_set = spec_set
1258 self.autospec = autospec
1259 self.kwargs = kwargs
1260 self.additional_patchers = []
1261
1262
1263 def copy(self):
1264 patcher = _patch(
1265 self.getter, self.attribute, self.new, self.spec,
1266 self.create, self.spec_set,
1267 self.autospec, self.new_callable, self.kwargs
1268 )
1269 patcher.attribute_name = self.attribute_name
1270 patcher.additional_patchers = [
1271 p.copy() for p in self.additional_patchers
1272 ]
1273 return patcher
1274
1275
1276 def __call__(self, func):
1277 if isinstance(func, type):
1278 return self.decorate_class(func)
Xtreak436c2b02019-05-28 12:37:39 +05301279 if inspect.iscoroutinefunction(func):
1280 return self.decorate_async_callable(func)
Michael Foord345266a2012-03-14 12:24:34 -07001281 return self.decorate_callable(func)
1282
1283
1284 def decorate_class(self, klass):
1285 for attr in dir(klass):
1286 if not attr.startswith(patch.TEST_PREFIX):
1287 continue
1288
1289 attr_value = getattr(klass, attr)
1290 if not hasattr(attr_value, "__call__"):
1291 continue
1292
1293 patcher = self.copy()
1294 setattr(klass, attr, patcher(attr_value))
1295 return klass
1296
1297
Xtreak436c2b02019-05-28 12:37:39 +05301298 @contextlib.contextmanager
1299 def decoration_helper(self, patched, args, keywargs):
1300 extra_args = []
1301 entered_patchers = []
1302 patching = None
1303
1304 exc_info = tuple()
1305 try:
1306 for patching in patched.patchings:
1307 arg = patching.__enter__()
1308 entered_patchers.append(patching)
1309 if patching.attribute_name is not None:
1310 keywargs.update(arg)
1311 elif patching.new is DEFAULT:
1312 extra_args.append(arg)
1313
1314 args += tuple(extra_args)
1315 yield (args, keywargs)
1316 except:
1317 if (patching not in entered_patchers and
1318 _is_started(patching)):
1319 # the patcher may have been started, but an exception
1320 # raised whilst entering one of its additional_patchers
1321 entered_patchers.append(patching)
1322 # Pass the exception to __exit__
1323 exc_info = sys.exc_info()
1324 # re-raise the exception
1325 raise
1326 finally:
1327 for patching in reversed(entered_patchers):
1328 patching.__exit__(*exc_info)
1329
1330
Michael Foord345266a2012-03-14 12:24:34 -07001331 def decorate_callable(self, func):
Xtreak436c2b02019-05-28 12:37:39 +05301332 # NB. Keep the method in sync with decorate_async_callable()
Michael Foord345266a2012-03-14 12:24:34 -07001333 if hasattr(func, 'patchings'):
1334 func.patchings.append(self)
1335 return func
1336
1337 @wraps(func)
1338 def patched(*args, **keywargs):
Xtreak436c2b02019-05-28 12:37:39 +05301339 with self.decoration_helper(patched,
1340 args,
1341 keywargs) as (newargs, newkeywargs):
1342 return func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001343
Xtreak436c2b02019-05-28 12:37:39 +05301344 patched.patchings = [self]
1345 return patched
Michael Foord345266a2012-03-14 12:24:34 -07001346
Xtreak436c2b02019-05-28 12:37:39 +05301347
1348 def decorate_async_callable(self, func):
1349 # NB. Keep the method in sync with decorate_callable()
1350 if hasattr(func, 'patchings'):
1351 func.patchings.append(self)
1352 return func
1353
1354 @wraps(func)
1355 async def patched(*args, **keywargs):
1356 with self.decoration_helper(patched,
1357 args,
1358 keywargs) as (newargs, newkeywargs):
1359 return await func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001360
1361 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001362 return patched
1363
1364
1365 def get_original(self):
1366 target = self.getter()
1367 name = self.attribute
1368
1369 original = DEFAULT
1370 local = False
1371
1372 try:
1373 original = target.__dict__[name]
1374 except (AttributeError, KeyError):
1375 original = getattr(target, name, DEFAULT)
1376 else:
1377 local = True
1378
Michael Foordfddcfa22014-04-14 16:25:20 -04001379 if name in _builtins and isinstance(target, ModuleType):
1380 self.create = True
1381
Michael Foord345266a2012-03-14 12:24:34 -07001382 if not self.create and original is DEFAULT:
1383 raise AttributeError(
1384 "%s does not have the attribute %r" % (target, name)
1385 )
1386 return original, local
1387
1388
1389 def __enter__(self):
1390 """Perform the patch."""
1391 new, spec, spec_set = self.new, self.spec, self.spec_set
1392 autospec, kwargs = self.autospec, self.kwargs
1393 new_callable = self.new_callable
1394 self.target = self.getter()
1395
Michael Foord50a8c0e2012-03-25 18:57:58 +01001396 # normalise False to None
1397 if spec is False:
1398 spec = None
1399 if spec_set is False:
1400 spec_set = None
1401 if autospec is False:
1402 autospec = None
1403
1404 if spec is not None and autospec is not None:
1405 raise TypeError("Can't specify spec and autospec")
1406 if ((spec is not None or autospec is not None) and
1407 spec_set not in (True, None)):
1408 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1409
Michael Foord345266a2012-03-14 12:24:34 -07001410 original, local = self.get_original()
1411
Michael Foord50a8c0e2012-03-25 18:57:58 +01001412 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001413 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001414 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001415 # set spec to the object we are replacing
1416 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001417 if spec_set is True:
1418 spec_set = original
1419 spec = None
1420 elif spec is not None:
1421 if spec_set is True:
1422 spec_set = spec
1423 spec = None
1424 elif spec_set is True:
1425 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001426
Michael Foord50a8c0e2012-03-25 18:57:58 +01001427 if spec is not None or spec_set is not None:
1428 if original is DEFAULT:
1429 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001430 if isinstance(original, type):
1431 # If we're patching out a class and there is a spec
1432 inherit = True
Lisa Roach77b3b772019-05-20 09:19:53 -07001433 if spec is None and _is_async_obj(original):
1434 Klass = AsyncMock
1435 else:
1436 Klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -07001437 _kwargs = {}
1438 if new_callable is not None:
1439 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001440 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001441 this_spec = spec
1442 if spec_set is not None:
1443 this_spec = spec_set
1444 if _is_list(this_spec):
1445 not_callable = '__call__' not in this_spec
1446 else:
1447 not_callable = not callable(this_spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07001448 if _is_async_obj(this_spec):
1449 Klass = AsyncMock
1450 elif not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001451 Klass = NonCallableMagicMock
1452
1453 if spec is not None:
1454 _kwargs['spec'] = spec
1455 if spec_set is not None:
1456 _kwargs['spec_set'] = spec_set
1457
1458 # add a name to mocks
1459 if (isinstance(Klass, type) and
1460 issubclass(Klass, NonCallableMock) and self.attribute):
1461 _kwargs['name'] = self.attribute
1462
1463 _kwargs.update(kwargs)
1464 new = Klass(**_kwargs)
1465
1466 if inherit and _is_instance_mock(new):
1467 # we can only tell if the instance should be callable if the
1468 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001469 this_spec = spec
1470 if spec_set is not None:
1471 this_spec = spec_set
1472 if (not _is_list(this_spec) and not
1473 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001474 Klass = NonCallableMagicMock
1475
1476 _kwargs.pop('name')
1477 new.return_value = Klass(_new_parent=new, _new_name='()',
1478 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001479 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001480 # spec is ignored, new *must* be default, spec_set is treated
1481 # as a boolean. Should we check spec is not None and that spec_set
1482 # is a bool?
1483 if new is not DEFAULT:
1484 raise TypeError(
1485 "autospec creates the mock for you. Can't specify "
1486 "autospec and new."
1487 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001488 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001489 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001490 spec_set = bool(spec_set)
1491 if autospec is True:
1492 autospec = original
1493
1494 new = create_autospec(autospec, spec_set=spec_set,
1495 _name=self.attribute, **kwargs)
1496 elif kwargs:
1497 # can't set keyword args when we aren't creating the mock
1498 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1499 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1500
1501 new_attr = new
1502
1503 self.temp_original = original
1504 self.is_local = local
1505 setattr(self.target, self.attribute, new_attr)
1506 if self.attribute_name is not None:
1507 extra_args = {}
1508 if self.new is DEFAULT:
1509 extra_args[self.attribute_name] = new
1510 for patching in self.additional_patchers:
1511 arg = patching.__enter__()
1512 if patching.new is DEFAULT:
1513 extra_args.update(arg)
1514 return extra_args
1515
1516 return new
1517
1518
Michael Foord50a8c0e2012-03-25 18:57:58 +01001519 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001520 """Undo the patch."""
1521 if not _is_started(self):
Xtreak02b84cb2019-03-29 02:38:43 +05301522 return
Michael Foord345266a2012-03-14 12:24:34 -07001523
1524 if self.is_local and self.temp_original is not DEFAULT:
1525 setattr(self.target, self.attribute, self.temp_original)
1526 else:
1527 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001528 if not self.create and (not hasattr(self.target, self.attribute) or
1529 self.attribute in ('__doc__', '__module__',
1530 '__defaults__', '__annotations__',
1531 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001532 # needed for proxy objects like django settings
1533 setattr(self.target, self.attribute, self.temp_original)
1534
1535 del self.temp_original
1536 del self.is_local
1537 del self.target
1538 for patcher in reversed(self.additional_patchers):
1539 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001540 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001541
Michael Foordf7c41582012-06-10 20:36:32 +01001542
1543 def start(self):
1544 """Activate a patch, returning any created mock."""
1545 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001546 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001547 return result
1548
1549
1550 def stop(self):
1551 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001552 try:
1553 self._active_patches.remove(self)
1554 except ValueError:
1555 # If the patch hasn't been started this will fail
1556 pass
1557
Michael Foordf7c41582012-06-10 20:36:32 +01001558 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001559
1560
1561
1562def _get_target(target):
1563 try:
1564 target, attribute = target.rsplit('.', 1)
1565 except (TypeError, ValueError):
1566 raise TypeError("Need a valid target to patch. You supplied: %r" %
1567 (target,))
1568 getter = lambda: _importer(target)
1569 return getter, attribute
1570
1571
1572def _patch_object(
1573 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001574 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001575 new_callable=None, **kwargs
1576 ):
1577 """
Michael Foord345266a2012-03-14 12:24:34 -07001578 patch the named member (`attribute`) on an object (`target`) with a mock
1579 object.
1580
1581 `patch.object` can be used as a decorator, class decorator or a context
1582 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1583 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1584 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1585 the mock object it creates.
1586
1587 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1588 for choosing which methods to wrap.
1589 """
1590 getter = lambda: target
1591 return _patch(
1592 getter, attribute, new, spec, create,
1593 spec_set, autospec, new_callable, kwargs
1594 )
1595
1596
Michael Foord50a8c0e2012-03-25 18:57:58 +01001597def _patch_multiple(target, spec=None, create=False, spec_set=None,
1598 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001599 """Perform multiple patches in a single call. It takes the object to be
1600 patched (either as an object or a string to fetch the object by importing)
1601 and keyword arguments for the patches::
1602
1603 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1604 ...
1605
1606 Use `DEFAULT` as the value if you want `patch.multiple` to create
1607 mocks for you. In this case the created mocks are passed into a decorated
1608 function by keyword, and a dictionary is returned when `patch.multiple` is
1609 used as a context manager.
1610
1611 `patch.multiple` can be used as a decorator, class decorator or a context
1612 manager. The arguments `spec`, `spec_set`, `create`,
1613 `autospec` and `new_callable` have the same meaning as for `patch`. These
1614 arguments will be applied to *all* patches done by `patch.multiple`.
1615
1616 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1617 for choosing which methods to wrap.
1618 """
1619 if type(target) is str:
1620 getter = lambda: _importer(target)
1621 else:
1622 getter = lambda: target
1623
1624 if not kwargs:
1625 raise ValueError(
1626 'Must supply at least one keyword argument with patch.multiple'
1627 )
1628 # need to wrap in a list for python 3, where items is a view
1629 items = list(kwargs.items())
1630 attribute, new = items[0]
1631 patcher = _patch(
1632 getter, attribute, new, spec, create, spec_set,
1633 autospec, new_callable, {}
1634 )
1635 patcher.attribute_name = attribute
1636 for attribute, new in items[1:]:
1637 this_patcher = _patch(
1638 getter, attribute, new, spec, create, spec_set,
1639 autospec, new_callable, {}
1640 )
1641 this_patcher.attribute_name = attribute
1642 patcher.additional_patchers.append(this_patcher)
1643 return patcher
1644
1645
1646def patch(
1647 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001648 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001649 ):
1650 """
1651 `patch` acts as a function decorator, class decorator or a context
1652 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001653 is patched with a `new` object. When the function/with statement exits
1654 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001655
Miss Islington (bot)eaa1b092019-09-10 06:15:19 -07001656 If `new` is omitted, then the target is replaced with an
1657 `AsyncMock if the patched object is an async function or a
1658 `MagicMock` otherwise. If `patch` is used as a decorator and `new` is
Michael Foord54b3db82012-03-28 15:08:08 +01001659 omitted, the created mock is passed in as an extra argument to the
1660 decorated function. If `patch` is used as a context manager the created
1661 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001662
Michael Foord54b3db82012-03-28 15:08:08 +01001663 `target` should be a string in the form `'package.module.ClassName'`. The
1664 `target` is imported and the specified object replaced with the `new`
1665 object, so the `target` must be importable from the environment you are
1666 calling `patch` from. The target is imported when the decorated function
1667 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001668
1669 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1670 if patch is creating one for you.
1671
1672 In addition you can pass `spec=True` or `spec_set=True`, which causes
1673 patch to pass in the object being mocked as the spec/spec_set object.
1674
1675 `new_callable` allows you to specify a different class, or callable object,
Miss Islington (bot)eaa1b092019-09-10 06:15:19 -07001676 that will be called to create the `new` object. By default `AsyncMock` is
1677 used for async functions and `MagicMock` for the rest.
Michael Foord345266a2012-03-14 12:24:34 -07001678
1679 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001680 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001681 All attributes of the mock will also have the spec of the corresponding
1682 attribute of the object being replaced. Methods and functions being
1683 mocked will have their arguments checked and will raise a `TypeError` if
1684 they are called with the wrong signature. For mocks replacing a class,
1685 their return value (the 'instance') will have the same spec as the class.
1686
1687 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1688 arbitrary object as the spec instead of the one being replaced.
1689
1690 By default `patch` will fail to replace attributes that don't exist. If
1691 you pass in `create=True`, and the attribute doesn't exist, patch will
1692 create the attribute for you when the patched function is called, and
1693 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001694 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001695 default because it can be dangerous. With it switched on you can write
1696 passing tests against APIs that don't actually exist!
1697
1698 Patch can be used as a `TestCase` class decorator. It works by
1699 decorating each test method in the class. This reduces the boilerplate
1700 code when your test methods share a common patchings set. `patch` finds
1701 tests by looking for method names that start with `patch.TEST_PREFIX`.
1702 By default this is `test`, which matches the way `unittest` finds tests.
1703 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1704
1705 Patch can be used as a context manager, with the with statement. Here the
1706 patching applies to the indented block after the with statement. If you
1707 use "as" then the patched object will be bound to the name after the
1708 "as"; very useful if `patch` is creating a mock object for you.
1709
1710 `patch` takes arbitrary keyword arguments. These will be passed to
1711 the `Mock` (or `new_callable`) on construction.
1712
1713 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1714 available for alternate use-cases.
1715 """
1716 getter, attribute = _get_target(target)
1717 return _patch(
1718 getter, attribute, new, spec, create,
1719 spec_set, autospec, new_callable, kwargs
1720 )
1721
1722
1723class _patch_dict(object):
1724 """
1725 Patch a dictionary, or dictionary like object, and restore the dictionary
1726 to its original state after the test.
1727
1728 `in_dict` can be a dictionary or a mapping like container. If it is a
1729 mapping then it must at least support getting, setting and deleting items
1730 plus iterating over keys.
1731
1732 `in_dict` can also be a string specifying the name of the dictionary, which
1733 will then be fetched by importing it.
1734
1735 `values` can be a dictionary of values to set in the dictionary. `values`
1736 can also be an iterable of `(key, value)` pairs.
1737
1738 If `clear` is True then the dictionary will be cleared before the new
1739 values are set.
1740
1741 `patch.dict` can also be called with arbitrary keyword arguments to set
1742 values in the dictionary::
1743
1744 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1745 ...
1746
1747 `patch.dict` can be used as a context manager, decorator or class
1748 decorator. When used as a class decorator `patch.dict` honours
1749 `patch.TEST_PREFIX` for choosing which methods to wrap.
1750 """
1751
1752 def __init__(self, in_dict, values=(), clear=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001753 self.in_dict = in_dict
1754 # support any argument supported by dict(...) constructor
1755 self.values = dict(values)
1756 self.values.update(kwargs)
1757 self.clear = clear
1758 self._original = None
1759
1760
1761 def __call__(self, f):
1762 if isinstance(f, type):
1763 return self.decorate_class(f)
1764 @wraps(f)
1765 def _inner(*args, **kw):
1766 self._patch_dict()
1767 try:
1768 return f(*args, **kw)
1769 finally:
1770 self._unpatch_dict()
1771
1772 return _inner
1773
1774
1775 def decorate_class(self, klass):
1776 for attr in dir(klass):
1777 attr_value = getattr(klass, attr)
1778 if (attr.startswith(patch.TEST_PREFIX) and
1779 hasattr(attr_value, "__call__")):
1780 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1781 decorated = decorator(attr_value)
1782 setattr(klass, attr, decorated)
1783 return klass
1784
1785
1786 def __enter__(self):
1787 """Patch the dict."""
1788 self._patch_dict()
Mario Corchero04530812019-05-28 13:53:31 +01001789 return self.in_dict
Michael Foord345266a2012-03-14 12:24:34 -07001790
1791
1792 def _patch_dict(self):
1793 values = self.values
Xtreaka875ea52019-02-25 00:24:49 +05301794 if isinstance(self.in_dict, str):
1795 self.in_dict = _importer(self.in_dict)
Michael Foord345266a2012-03-14 12:24:34 -07001796 in_dict = self.in_dict
1797 clear = self.clear
1798
1799 try:
1800 original = in_dict.copy()
1801 except AttributeError:
1802 # dict like object with no copy method
1803 # must support iteration over keys
1804 original = {}
1805 for key in in_dict:
1806 original[key] = in_dict[key]
1807 self._original = original
1808
1809 if clear:
1810 _clear_dict(in_dict)
1811
1812 try:
1813 in_dict.update(values)
1814 except AttributeError:
1815 # dict like object with no update method
1816 for key in values:
1817 in_dict[key] = values[key]
1818
1819
1820 def _unpatch_dict(self):
1821 in_dict = self.in_dict
1822 original = self._original
1823
1824 _clear_dict(in_dict)
1825
1826 try:
1827 in_dict.update(original)
1828 except AttributeError:
1829 for key in original:
1830 in_dict[key] = original[key]
1831
1832
1833 def __exit__(self, *args):
1834 """Unpatch the dict."""
1835 self._unpatch_dict()
1836 return False
1837
1838 start = __enter__
1839 stop = __exit__
1840
1841
1842def _clear_dict(in_dict):
1843 try:
1844 in_dict.clear()
1845 except AttributeError:
1846 keys = list(in_dict)
1847 for key in keys:
1848 del in_dict[key]
1849
1850
Michael Foordf7c41582012-06-10 20:36:32 +01001851def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001852 """Stop all active patches. LIFO to unroll nested patches."""
1853 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001854 patch.stop()
1855
1856
Michael Foord345266a2012-03-14 12:24:34 -07001857patch.object = _patch_object
1858patch.dict = _patch_dict
1859patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001860patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001861patch.TEST_PREFIX = 'test'
1862
1863magic_methods = (
1864 "lt le gt ge eq ne "
1865 "getitem setitem delitem "
1866 "len contains iter "
1867 "hash str sizeof "
1868 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001869 # we added divmod and rdivmod here instead of numerics
1870 # because there is no idivmod
1871 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001872 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001873 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001874 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001875 "fspath "
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07001876 "aiter "
Michael Foord345266a2012-03-14 12:24:34 -07001877)
1878
Michael Foordd2623d72014-04-14 11:23:48 -04001879numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001880 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001881)
Michael Foord345266a2012-03-14 12:24:34 -07001882inplace = ' '.join('i%s' % n for n in numerics.split())
1883right = ' '.join('r%s' % n for n in numerics.split())
1884
1885# not including __prepare__, __instancecheck__, __subclasscheck__
1886# (as they are metaclass methods)
1887# __del__ is not supported at all as it causes problems if it exists
1888
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001889_non_defaults = {
1890 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1891 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1892 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1893 '__repr__', '__dir__', '__subclasses__', '__format__',
Lisa Roach865bb682019-09-20 23:00:04 -07001894 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001895}
Michael Foord345266a2012-03-14 12:24:34 -07001896
1897
1898def _get_method(name, func):
1899 "Turns a callable object (like a mock) into a real function"
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001900 def method(self, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -07001901 return func(self, *args, **kw)
1902 method.__name__ = name
1903 return method
1904
1905
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001906_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001907 '__%s__' % method for method in
1908 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001909}
Michael Foord345266a2012-03-14 12:24:34 -07001910
Lisa Roach77b3b772019-05-20 09:19:53 -07001911# Magic methods used for async `with` statements
1912_async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
Lisa Roach865bb682019-09-20 23:00:04 -07001913# Magic methods that are only used with async calls but are synchronous functions themselves
1914_sync_async_magics = {"__aiter__"}
1915_async_magics = _async_method_magics | _sync_async_magics
Lisa Roach77b3b772019-05-20 09:19:53 -07001916
Lisa Roach865bb682019-09-20 23:00:04 -07001917_all_sync_magics = _magics | _non_defaults
1918_all_magics = _all_sync_magics | _async_magics
Michael Foord345266a2012-03-14 12:24:34 -07001919
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001920_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001921 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001922 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001923 '__instancecheck__', '__subclasscheck__',
1924 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001925}
Michael Foord345266a2012-03-14 12:24:34 -07001926
1927_calculate_return_value = {
1928 '__hash__': lambda self: object.__hash__(self),
1929 '__str__': lambda self: object.__str__(self),
1930 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001931 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001932}
1933
1934_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001935 '__lt__': NotImplemented,
1936 '__gt__': NotImplemented,
1937 '__le__': NotImplemented,
1938 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001939 '__int__': 1,
1940 '__contains__': False,
1941 '__len__': 0,
1942 '__exit__': False,
1943 '__complex__': 1j,
1944 '__float__': 1.0,
1945 '__bool__': True,
1946 '__index__': 1,
Lisa Roach77b3b772019-05-20 09:19:53 -07001947 '__aexit__': False,
Michael Foord345266a2012-03-14 12:24:34 -07001948}
1949
1950
1951def _get_eq(self):
1952 def __eq__(other):
1953 ret_val = self.__eq__._mock_return_value
1954 if ret_val is not DEFAULT:
1955 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001956 if self is other:
1957 return True
1958 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001959 return __eq__
1960
1961def _get_ne(self):
1962 def __ne__(other):
1963 if self.__ne__._mock_return_value is not DEFAULT:
1964 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001965 if self is other:
1966 return False
1967 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001968 return __ne__
1969
1970def _get_iter(self):
1971 def __iter__():
1972 ret_val = self.__iter__._mock_return_value
1973 if ret_val is DEFAULT:
1974 return iter([])
1975 # if ret_val was already an iterator, then calling iter on it should
1976 # return the iterator unchanged
1977 return iter(ret_val)
1978 return __iter__
1979
Lisa Roach77b3b772019-05-20 09:19:53 -07001980def _get_async_iter(self):
1981 def __aiter__():
1982 ret_val = self.__aiter__._mock_return_value
1983 if ret_val is DEFAULT:
1984 return _AsyncIterator(iter([]))
1985 return _AsyncIterator(iter(ret_val))
1986 return __aiter__
1987
Michael Foord345266a2012-03-14 12:24:34 -07001988_side_effect_methods = {
1989 '__eq__': _get_eq,
1990 '__ne__': _get_ne,
1991 '__iter__': _get_iter,
Lisa Roach77b3b772019-05-20 09:19:53 -07001992 '__aiter__': _get_async_iter
Michael Foord345266a2012-03-14 12:24:34 -07001993}
1994
1995
1996
1997def _set_return_value(mock, method, name):
1998 fixed = _return_values.get(name, DEFAULT)
1999 if fixed is not DEFAULT:
2000 method.return_value = fixed
2001 return
2002
Miss Islington (bot)cc8edfb2019-09-16 09:52:45 -07002003 return_calculator = _calculate_return_value.get(name)
2004 if return_calculator is not None:
2005 return_value = return_calculator(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002006 method.return_value = return_value
2007 return
2008
2009 side_effector = _side_effect_methods.get(name)
2010 if side_effector is not None:
2011 method.side_effect = side_effector(mock)
2012
2013
2014
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002015class MagicMixin(Base):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002016 def __init__(self, /, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07002017 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10002018 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07002019 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002020
2021
2022 def _mock_set_magics(self):
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002023 orig_magics = _magics | _async_method_magics
2024 these_magics = orig_magics
Michael Foord345266a2012-03-14 12:24:34 -07002025
Łukasz Langaa468db92015-04-13 23:12:42 -07002026 if getattr(self, "_mock_methods", None) is not None:
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002027 these_magics = orig_magics.intersection(self._mock_methods)
Michael Foord345266a2012-03-14 12:24:34 -07002028
2029 remove_magics = set()
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002030 remove_magics = orig_magics - these_magics
Michael Foord345266a2012-03-14 12:24:34 -07002031
2032 for entry in remove_magics:
2033 if entry in type(self).__dict__:
2034 # remove unneeded magic methods
2035 delattr(self, entry)
2036
2037 # don't overwrite existing attributes if called a second time
2038 these_magics = these_magics - set(type(self).__dict__)
2039
2040 _type = type(self)
2041 for entry in these_magics:
2042 setattr(_type, entry, MagicProxy(entry, self))
2043
2044
2045
2046class NonCallableMagicMock(MagicMixin, NonCallableMock):
2047 """A version of `MagicMock` that isn't callable."""
2048 def mock_add_spec(self, spec, spec_set=False):
2049 """Add a spec to a mock. `spec` can either be an object or a
2050 list of strings. Only attributes on the `spec` can be fetched as
2051 attributes from the mock.
2052
2053 If `spec_set` is True then only attributes on the spec can be set."""
2054 self._mock_add_spec(spec, spec_set)
2055 self._mock_set_magics()
2056
2057
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002058class AsyncMagicMixin(MagicMixin):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002059 def __init__(self, /, *args, **kw):
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002060 self._mock_set_magics() # make magic work for kwargs in init
Lisa Roach77b3b772019-05-20 09:19:53 -07002061 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002062 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002063
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002064class MagicMock(MagicMixin, Mock):
Michael Foord345266a2012-03-14 12:24:34 -07002065 """
2066 MagicMock is a subclass of Mock with default implementations
2067 of most of the magic methods. You can use MagicMock without having to
2068 configure the magic methods yourself.
2069
2070 If you use the `spec` or `spec_set` arguments then *only* magic
2071 methods that exist in the spec will be created.
2072
2073 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
2074 """
2075 def mock_add_spec(self, spec, spec_set=False):
2076 """Add a spec to a mock. `spec` can either be an object or a
2077 list of strings. Only attributes on the `spec` can be fetched as
2078 attributes from the mock.
2079
2080 If `spec_set` is True then only attributes on the spec can be set."""
2081 self._mock_add_spec(spec, spec_set)
2082 self._mock_set_magics()
2083
2084
2085
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002086class MagicProxy(Base):
Michael Foord345266a2012-03-14 12:24:34 -07002087 def __init__(self, name, parent):
2088 self.name = name
2089 self.parent = parent
2090
Michael Foord345266a2012-03-14 12:24:34 -07002091 def create_mock(self):
2092 entry = self.name
2093 parent = self.parent
2094 m = parent._get_child_mock(name=entry, _new_name=entry,
2095 _new_parent=parent)
2096 setattr(parent, entry, m)
2097 _set_return_value(parent, m, entry)
2098 return m
2099
2100 def __get__(self, obj, _type=None):
2101 return self.create_mock()
2102
2103
Lisa Roach77b3b772019-05-20 09:19:53 -07002104class AsyncMockMixin(Base):
Lisa Roach77b3b772019-05-20 09:19:53 -07002105 await_count = _delegating_property('await_count')
2106 await_args = _delegating_property('await_args')
2107 await_args_list = _delegating_property('await_args_list')
2108
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002109 def __init__(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002110 super().__init__(*args, **kwargs)
2111 # asyncio.iscoroutinefunction() checks _is_coroutine property to say if an
2112 # object is a coroutine. Without this check it looks to see if it is a
2113 # function/method, which in this case it is not (since it is an
2114 # AsyncMock).
2115 # It is set through __dict__ because when spec_set is True, this
2116 # attribute is likely undefined.
2117 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
Lisa Roach77b3b772019-05-20 09:19:53 -07002118 self.__dict__['_mock_await_count'] = 0
2119 self.__dict__['_mock_await_args'] = None
2120 self.__dict__['_mock_await_args_list'] = _CallList()
2121 code_mock = NonCallableMock(spec_set=CodeType)
2122 code_mock.co_flags = inspect.CO_COROUTINE
2123 self.__dict__['__code__'] = code_mock
2124
Lisa Roachb2744c12019-11-21 10:14:32 -08002125 async def _execute_mock_call(self, /, *args, **kwargs):
2126 # This is nearly just like super(), except for sepcial handling
2127 # of coroutines
Lisa Roach77b3b772019-05-20 09:19:53 -07002128
2129 _call = self.call_args
Lisa Roachb2744c12019-11-21 10:14:32 -08002130 self.await_count += 1
2131 self.await_args = _call
2132 self.await_args_list.append(_call)
Lisa Roach77b3b772019-05-20 09:19:53 -07002133
Lisa Roachb2744c12019-11-21 10:14:32 -08002134 effect = self.side_effect
2135 if effect is not None:
2136 if _is_exception(effect):
2137 raise effect
2138 elif not _callable(effect):
2139 try:
2140 result = next(effect)
2141 except StopIteration:
2142 # It is impossible to propogate a StopIteration
2143 # through coroutines because of PEP 479
2144 raise StopAsyncIteration
2145 if _is_exception(result):
2146 raise result
2147 elif asyncio.iscoroutinefunction(effect):
2148 result = await effect(*args, **kwargs)
2149 else:
2150 result = effect(*args, **kwargs)
Lisa Roach77b3b772019-05-20 09:19:53 -07002151
Lisa Roachb2744c12019-11-21 10:14:32 -08002152 if result is not DEFAULT:
2153 return result
2154
2155 if self._mock_return_value is not DEFAULT:
2156 return self.return_value
2157
2158 if self._mock_wraps is not None:
2159 if asyncio.iscoroutinefunction(self._mock_wraps):
2160 return await self._mock_wraps(*args, **kwargs)
2161 return self._mock_wraps(*args, **kwargs)
2162
2163 return self.return_value
Lisa Roach77b3b772019-05-20 09:19:53 -07002164
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002165 def assert_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002166 """
2167 Assert that the mock was awaited at least once.
2168 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002169 if self.await_count == 0:
2170 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2171 raise AssertionError(msg)
2172
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002173 def assert_awaited_once(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002174 """
2175 Assert that the mock was awaited exactly once.
2176 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002177 if not self.await_count == 1:
2178 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2179 f" Awaited {self.await_count} times.")
2180 raise AssertionError(msg)
2181
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002182 def assert_awaited_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002183 """
2184 Assert that the last await was with the specified arguments.
2185 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002186 if self.await_args is None:
2187 expected = self._format_mock_call_signature(args, kwargs)
2188 raise AssertionError(f'Expected await: {expected}\nNot awaited')
2189
2190 def _error_message():
Xtreak0ae022c2019-05-29 12:32:26 +05302191 msg = self._format_mock_failure_message(args, kwargs, action='await')
Lisa Roach77b3b772019-05-20 09:19:53 -07002192 return msg
2193
2194 expected = self._call_matcher((args, kwargs))
2195 actual = self._call_matcher(self.await_args)
2196 if expected != actual:
2197 cause = expected if isinstance(expected, Exception) else None
2198 raise AssertionError(_error_message()) from cause
2199
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002200 def assert_awaited_once_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002201 """
2202 Assert that the mock was awaited exactly once and with the specified
2203 arguments.
2204 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002205 if not self.await_count == 1:
2206 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2207 f" Awaited {self.await_count} times.")
2208 raise AssertionError(msg)
2209 return self.assert_awaited_with(*args, **kwargs)
2210
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002211 def assert_any_await(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002212 """
2213 Assert the mock has ever been awaited with the specified arguments.
2214 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002215 expected = self._call_matcher((args, kwargs))
2216 actual = [self._call_matcher(c) for c in self.await_args_list]
2217 if expected not in actual:
2218 cause = expected if isinstance(expected, Exception) else None
2219 expected_string = self._format_mock_call_signature(args, kwargs)
2220 raise AssertionError(
2221 '%s await not found' % expected_string
2222 ) from cause
2223
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002224 def assert_has_awaits(self, calls, any_order=False):
Lisa Roach77b3b772019-05-20 09:19:53 -07002225 """
2226 Assert the mock has been awaited with the specified calls.
2227 The :attr:`await_args_list` list is checked for the awaits.
2228
2229 If `any_order` is False (the default) then the awaits must be
2230 sequential. There can be extra calls before or after the
2231 specified awaits.
2232
2233 If `any_order` is True then the awaits can be in any order, but
2234 they must all appear in :attr:`await_args_list`.
2235 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002236 expected = [self._call_matcher(c) for c in calls]
Miss Islington (bot)1a17a052019-09-24 17:29:17 -07002237 cause = next((e for e in expected if isinstance(e, Exception)), None)
Lisa Roach77b3b772019-05-20 09:19:53 -07002238 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2239 if not any_order:
2240 if expected not in all_awaits:
Miss Islington (bot)1a17a052019-09-24 17:29:17 -07002241 if cause is None:
2242 problem = 'Awaits not found.'
2243 else:
2244 problem = ('Error processing expected awaits.\n'
2245 'Errors: {}').format(
2246 [e if isinstance(e, Exception) else None
2247 for e in expected])
Lisa Roach77b3b772019-05-20 09:19:53 -07002248 raise AssertionError(
Miss Islington (bot)1a17a052019-09-24 17:29:17 -07002249 f'{problem}\n'
2250 f'Expected: {_CallList(calls)}\n'
Lisa Roach77b3b772019-05-20 09:19:53 -07002251 f'Actual: {self.await_args_list}'
2252 ) from cause
2253 return
2254
2255 all_awaits = list(all_awaits)
2256
2257 not_found = []
2258 for kall in expected:
2259 try:
2260 all_awaits.remove(kall)
2261 except ValueError:
2262 not_found.append(kall)
2263 if not_found:
2264 raise AssertionError(
2265 '%r not all found in await list' % (tuple(not_found),)
2266 ) from cause
2267
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002268 def assert_not_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002269 """
2270 Assert that the mock was never awaited.
2271 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002272 if self.await_count != 0:
Xtreakff6b2e62019-05-27 18:26:23 +05302273 msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
Lisa Roach77b3b772019-05-20 09:19:53 -07002274 f" Awaited {self.await_count} times.")
2275 raise AssertionError(msg)
2276
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002277 def reset_mock(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002278 """
2279 See :func:`.Mock.reset_mock()`
2280 """
2281 super().reset_mock(*args, **kwargs)
2282 self.await_count = 0
2283 self.await_args = None
2284 self.await_args_list = _CallList()
2285
2286
2287class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2288 """
2289 Enhance :class:`Mock` with features allowing to mock
2290 an async function.
2291
2292 The :class:`AsyncMock` object will behave so the object is
2293 recognized as an async function, and the result of a call is an awaitable:
2294
2295 >>> mock = AsyncMock()
2296 >>> asyncio.iscoroutinefunction(mock)
2297 True
2298 >>> inspect.isawaitable(mock())
2299 True
2300
2301
2302 The result of ``mock()`` is an async function which will have the outcome
2303 of ``side_effect`` or ``return_value``:
2304
2305 - if ``side_effect`` is a function, the async function will return the
2306 result of that function,
2307 - if ``side_effect`` is an exception, the async function will raise the
2308 exception,
2309 - if ``side_effect`` is an iterable, the async function will return the
2310 next value of the iterable, however, if the sequence of result is
2311 exhausted, ``StopIteration`` is raised immediately,
2312 - if ``side_effect`` is not defined, the async function will return the
2313 value defined by ``return_value``, hence, by default, the async function
2314 returns a new :class:`AsyncMock` object.
2315
2316 If the outcome of ``side_effect`` or ``return_value`` is an async function,
2317 the mock async function obtained when the mock object is called will be this
2318 async function itself (and not an async function returning an async
2319 function).
2320
2321 The test author can also specify a wrapped object with ``wraps``. In this
2322 case, the :class:`Mock` object behavior is the same as with an
2323 :class:`.Mock` object: the wrapped object may have methods
2324 defined as async function functions.
2325
Xtreake7cb23b2019-05-21 14:17:17 +05302326 Based on Martin Richard's asynctest project.
Lisa Roach77b3b772019-05-20 09:19:53 -07002327 """
2328
Michael Foord345266a2012-03-14 12:24:34 -07002329
2330class _ANY(object):
2331 "A helper object that compares equal to everything."
2332
2333 def __eq__(self, other):
2334 return True
2335
2336 def __ne__(self, other):
2337 return False
2338
2339 def __repr__(self):
2340 return '<ANY>'
2341
2342ANY = _ANY()
2343
2344
2345
2346def _format_call_signature(name, args, kwargs):
2347 message = '%s(%%s)' % name
2348 formatted_args = ''
2349 args_string = ', '.join([repr(arg) for arg in args])
2350 kwargs_string = ', '.join([
Miss Islington (bot)bee8bfe2019-09-09 04:42:43 -07002351 '%s=%r' % (key, value) for key, value in kwargs.items()
Michael Foord345266a2012-03-14 12:24:34 -07002352 ])
2353 if args_string:
2354 formatted_args = args_string
2355 if kwargs_string:
2356 if formatted_args:
2357 formatted_args += ', '
2358 formatted_args += kwargs_string
2359
2360 return message % formatted_args
2361
2362
2363
2364class _Call(tuple):
2365 """
2366 A tuple for holding the results of a call to a mock, either in the form
2367 `(args, kwargs)` or `(name, args, kwargs)`.
2368
2369 If args or kwargs are empty then a call tuple will compare equal to
2370 a tuple without those values. This makes comparisons less verbose::
2371
2372 _Call(('name', (), {})) == ('name',)
2373 _Call(('name', (1,), {})) == ('name', (1,))
2374 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2375
2376 The `_Call` object provides a useful shortcut for comparing with call::
2377
2378 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2379 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2380
2381 If the _Call has no name then it will match any name.
2382 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002383 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002384 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002385 args = ()
2386 kwargs = {}
2387 _len = len(value)
2388 if _len == 3:
2389 name, args, kwargs = value
2390 elif _len == 2:
2391 first, second = value
2392 if isinstance(first, str):
2393 name = first
2394 if isinstance(second, tuple):
2395 args = second
2396 else:
2397 kwargs = second
2398 else:
2399 args, kwargs = first, second
2400 elif _len == 1:
2401 value, = value
2402 if isinstance(value, str):
2403 name = value
2404 elif isinstance(value, tuple):
2405 args = value
2406 else:
2407 kwargs = value
2408
2409 if two:
2410 return tuple.__new__(cls, (args, kwargs))
2411
2412 return tuple.__new__(cls, (name, args, kwargs))
2413
2414
2415 def __init__(self, value=(), name=None, parent=None, two=False,
2416 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002417 self._mock_name = name
2418 self._mock_parent = parent
2419 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002420
2421
2422 def __eq__(self, other):
2423 if other is ANY:
2424 return True
2425 try:
2426 len_other = len(other)
2427 except TypeError:
2428 return False
2429
2430 self_name = ''
2431 if len(self) == 2:
2432 self_args, self_kwargs = self
2433 else:
2434 self_name, self_args, self_kwargs = self
2435
Andrew Dunaie63e6172018-12-04 11:08:45 +02002436 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2437 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002438 return False
2439
Michael Foord345266a2012-03-14 12:24:34 -07002440 other_name = ''
2441 if len_other == 0:
2442 other_args, other_kwargs = (), {}
2443 elif len_other == 3:
2444 other_name, other_args, other_kwargs = other
2445 elif len_other == 1:
2446 value, = other
2447 if isinstance(value, tuple):
2448 other_args = value
2449 other_kwargs = {}
2450 elif isinstance(value, str):
2451 other_name = value
2452 other_args, other_kwargs = (), {}
2453 else:
2454 other_args = ()
2455 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002456 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002457 # could be (name, args) or (name, kwargs) or (args, kwargs)
2458 first, second = other
2459 if isinstance(first, str):
2460 other_name = first
2461 if isinstance(second, tuple):
2462 other_args, other_kwargs = second, {}
2463 else:
2464 other_args, other_kwargs = (), second
2465 else:
2466 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002467 else:
2468 return False
Michael Foord345266a2012-03-14 12:24:34 -07002469
2470 if self_name and other_name != self_name:
2471 return False
2472
2473 # this order is important for ANY to work!
2474 return (other_args, other_kwargs) == (self_args, self_kwargs)
2475
2476
Berker Peksagce913872016-03-28 00:30:02 +03002477 __ne__ = object.__ne__
2478
2479
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002480 def __call__(self, /, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002481 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002482 return _Call(('', args, kwargs), name='()')
2483
Andrew Dunaie63e6172018-12-04 11:08:45 +02002484 name = self._mock_name + '()'
2485 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002486
2487
2488 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002489 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002490 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002491 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002492 return _Call(name=name, parent=self, from_kall=False)
2493
2494
Miss Islington (bot)db0d8a52019-09-12 03:52:49 -07002495 def __getattribute__(self, attr):
2496 if attr in tuple.__dict__:
2497 raise AttributeError
2498 return tuple.__getattribute__(self, attr)
2499
2500
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002501 def count(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302502 return self.__getattr__('count')(*args, **kwargs)
2503
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002504 def index(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302505 return self.__getattr__('index')(*args, **kwargs)
2506
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302507 def _get_call_arguments(self):
2508 if len(self) == 2:
2509 args, kwargs = self
2510 else:
2511 name, args, kwargs = self
2512
2513 return args, kwargs
2514
2515 @property
2516 def args(self):
2517 return self._get_call_arguments()[0]
2518
2519 @property
2520 def kwargs(self):
2521 return self._get_call_arguments()[1]
2522
Michael Foord345266a2012-03-14 12:24:34 -07002523 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002524 if not self._mock_from_kall:
2525 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002526 if name.startswith('()'):
2527 name = 'call%s' % name
2528 return name
2529
2530 if len(self) == 2:
2531 name = 'call'
2532 args, kwargs = self
2533 else:
2534 name, args, kwargs = self
2535 if not name:
2536 name = 'call'
2537 elif not name.startswith('()'):
2538 name = 'call.%s' % name
2539 else:
2540 name = 'call%s' % name
2541 return _format_call_signature(name, args, kwargs)
2542
2543
2544 def call_list(self):
2545 """For a call object that represents multiple calls, `call_list`
2546 returns a list of all the intermediate calls as well as the
2547 final call."""
2548 vals = []
2549 thing = self
2550 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002551 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002552 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002553 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002554 return _CallList(reversed(vals))
2555
2556
2557call = _Call(from_kall=False)
2558
2559
Michael Foord345266a2012-03-14 12:24:34 -07002560def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2561 _name=None, **kwargs):
2562 """Create a mock object using another object as a spec. Attributes on the
2563 mock will use the corresponding attribute on the `spec` object as their
2564 spec.
2565
2566 Functions or methods being mocked will have their arguments checked
2567 to check that they are called with the correct signature.
2568
2569 If `spec_set` is True then attempting to set attributes that don't exist
2570 on the spec object will raise an `AttributeError`.
2571
2572 If a class is used as a spec then the return value of the mock (the
2573 instance of the class) will have the same spec. You can use a class as the
2574 spec for an instance object by passing `instance=True`. The returned mock
2575 will only be callable if instances of the mock are callable.
2576
2577 `create_autospec` also takes arbitrary keyword arguments that are passed to
2578 the constructor of the created mock."""
2579 if _is_list(spec):
2580 # can't pass a list instance to the mock constructor as it will be
2581 # interpreted as a list of strings
2582 spec = type(spec)
2583
2584 is_type = isinstance(spec, type)
Xtreakff6b2e62019-05-27 18:26:23 +05302585 is_async_func = _is_async_func(spec)
Michael Foord345266a2012-03-14 12:24:34 -07002586 _kwargs = {'spec': spec}
2587 if spec_set:
2588 _kwargs = {'spec_set': spec}
2589 elif spec is None:
2590 # None we mock with a normal mock without a spec
2591 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002592 if _kwargs and instance:
2593 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002594
2595 _kwargs.update(kwargs)
2596
2597 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002598 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002599 # descriptors don't have a spec
2600 # because we don't know what type they return
2601 _kwargs = {}
Lisa Roach77b3b772019-05-20 09:19:53 -07002602 elif is_async_func:
2603 if instance:
2604 raise RuntimeError("Instance can not be True when create_autospec "
2605 "is mocking an async function")
2606 Klass = AsyncMock
Michael Foord345266a2012-03-14 12:24:34 -07002607 elif not _callable(spec):
2608 Klass = NonCallableMagicMock
2609 elif is_type and instance and not _instance_callable(spec):
2610 Klass = NonCallableMagicMock
2611
Kushal Das484f8a82014-04-16 01:05:50 +05302612 _name = _kwargs.pop('name', _name)
2613
Michael Foord345266a2012-03-14 12:24:34 -07002614 _new_name = _name
2615 if _parent is None:
2616 # for a top level object no _new_name should be set
2617 _new_name = ''
2618
2619 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2620 name=_name, **_kwargs)
2621
2622 if isinstance(spec, FunctionTypes):
2623 # should only happen at the top level because we don't
2624 # recurse for functions
2625 mock = _set_signature(mock, spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07002626 if is_async_func:
Xtreakff6b2e62019-05-27 18:26:23 +05302627 _setup_async_mock(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002628 else:
2629 _check_signature(spec, mock, is_type, instance)
2630
2631 if _parent is not None and not instance:
2632 _parent._mock_children[_name] = mock
2633
2634 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002635 mock.return_value = create_autospec(spec, spec_set, instance=True,
2636 _name='()', _parent=mock)
2637
2638 for entry in dir(spec):
2639 if _is_magic(entry):
2640 # MagicMock already does the useful magic methods for us
2641 continue
2642
Michael Foord345266a2012-03-14 12:24:34 -07002643 # XXXX do we need a better way of getting attributes without
2644 # triggering code execution (?) Probably not - we need the actual
2645 # object to mock it so we would rather trigger a property than mock
2646 # the property descriptor. Likewise we want to mock out dynamically
2647 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002648 # XXXX what about attributes that raise exceptions other than
2649 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002650 # we could be resilient against it, or catch and propagate the
2651 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002652 try:
2653 original = getattr(spec, entry)
2654 except AttributeError:
2655 continue
Michael Foord345266a2012-03-14 12:24:34 -07002656
2657 kwargs = {'spec': original}
2658 if spec_set:
2659 kwargs = {'spec_set': original}
2660
2661 if not isinstance(original, FunctionTypes):
2662 new = _SpecState(original, spec_set, mock, entry, instance)
2663 mock._mock_children[entry] = new
2664 else:
2665 parent = mock
2666 if isinstance(spec, FunctionTypes):
2667 parent = mock.mock
2668
Michael Foord345266a2012-03-14 12:24:34 -07002669 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002670 kwargs['_eat_self'] = skipfirst
Lisa Roach77b3b772019-05-20 09:19:53 -07002671 if asyncio.iscoroutinefunction(original):
2672 child_klass = AsyncMock
2673 else:
2674 child_klass = MagicMock
2675 new = child_klass(parent=parent, name=entry, _new_name=entry,
2676 _new_parent=parent,
2677 **kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002678 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002679 _check_signature(original, new, skipfirst=skipfirst)
2680
2681 # so functions created with _set_signature become instance attributes,
2682 # *plus* their underlying mock exists in _mock_children of the parent
2683 # mock. Adding to _mock_children may be unnecessary where we are also
2684 # setting as an instance attribute?
2685 if isinstance(new, FunctionTypes):
2686 setattr(mock, entry, new)
2687
2688 return mock
2689
2690
2691def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002692 """
2693 Return whether we should skip the first argument on spec's `entry`
2694 attribute.
2695 """
Michael Foord345266a2012-03-14 12:24:34 -07002696 if not isinstance(spec, type):
2697 if entry in getattr(spec, '__dict__', {}):
2698 # instance attribute - shouldn't skip
2699 return False
Michael Foord345266a2012-03-14 12:24:34 -07002700 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002701
2702 for klass in spec.__mro__:
2703 result = klass.__dict__.get(entry, DEFAULT)
2704 if result is DEFAULT:
2705 continue
2706 if isinstance(result, (staticmethod, classmethod)):
2707 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002708 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2709 # Normal method => skip if looked up on type
2710 # (if looked up on instance, self is already skipped)
2711 return is_type
2712 else:
2713 return False
Michael Foord345266a2012-03-14 12:24:34 -07002714
Chris Withersadbf1782019-05-01 23:04:04 +01002715 # function is a dynamically provided attribute
Michael Foord345266a2012-03-14 12:24:34 -07002716 return is_type
2717
2718
Michael Foord345266a2012-03-14 12:24:34 -07002719class _SpecState(object):
2720
2721 def __init__(self, spec, spec_set=False, parent=None,
2722 name=None, ids=None, instance=False):
2723 self.spec = spec
2724 self.ids = ids
2725 self.spec_set = spec_set
2726 self.parent = parent
2727 self.instance = instance
2728 self.name = name
2729
2730
2731FunctionTypes = (
2732 # python function
2733 type(create_autospec),
2734 # instance method
2735 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002736)
2737
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002738MethodWrapperTypes = (
2739 type(ANY.__eq__.__get__),
2740)
2741
Michael Foord345266a2012-03-14 12:24:34 -07002742
Michael Foorda74561a2012-03-25 19:03:13 +01002743file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002744
Michael Foord04cbe0c2013-03-19 17:22:51 -07002745
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002746def _to_stream(read_data):
2747 if isinstance(read_data, bytes):
2748 return io.BytesIO(read_data)
Michael Foord04cbe0c2013-03-19 17:22:51 -07002749 else:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002750 return io.StringIO(read_data)
Michael Foord0dccf652012-03-25 19:11:50 +01002751
Robert Collins5329aaa2015-07-17 20:08:45 +12002752
Michael Foord0dccf652012-03-25 19:11:50 +01002753def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002754 """
2755 A helper function to create a mock to replace the use of `open`. It works
2756 for `open` called directly or used as a context manager.
2757
2758 The `mock` argument is the mock object to configure. If `None` (the
2759 default) then a `MagicMock` will be created for you, with the API limited
2760 to methods or attributes available on standard file handles.
2761
Xtreak71f82a22018-12-20 21:30:21 +05302762 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002763 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002764 """
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002765 _read_data = _to_stream(read_data)
2766 _state = [_read_data, None]
2767
Robert Collinsca647ef2015-07-24 03:48:20 +12002768 def _readlines_side_effect(*args, **kwargs):
2769 if handle.readlines.return_value is not None:
2770 return handle.readlines.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002771 return _state[0].readlines(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002772
2773 def _read_side_effect(*args, **kwargs):
2774 if handle.read.return_value is not None:
2775 return handle.read.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002776 return _state[0].read(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002777
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002778 def _readline_side_effect(*args, **kwargs):
Tony Flury20870232018-09-12 23:21:16 +01002779 yield from _iter_side_effect()
2780 while True:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002781 yield _state[0].readline(*args, **kwargs)
Tony Flury20870232018-09-12 23:21:16 +01002782
2783 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002784 if handle.readline.return_value is not None:
2785 while True:
2786 yield handle.readline.return_value
2787 for line in _state[0]:
2788 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002789
Damien Nadé394119a2019-05-23 12:03:25 +02002790 def _next_side_effect():
2791 if handle.readline.return_value is not None:
2792 return handle.readline.return_value
2793 return next(_state[0])
2794
Michael Foorda74561a2012-03-25 19:03:13 +01002795 global file_spec
2796 if file_spec is None:
2797 import _io
2798 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2799
Michael Foord345266a2012-03-14 12:24:34 -07002800 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002801 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002802
Robert Collinsca647ef2015-07-24 03:48:20 +12002803 handle = MagicMock(spec=file_spec)
2804 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002805
Robert Collinsca647ef2015-07-24 03:48:20 +12002806 handle.write.return_value = None
2807 handle.read.return_value = None
2808 handle.readline.return_value = None
2809 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002810
Robert Collinsca647ef2015-07-24 03:48:20 +12002811 handle.read.side_effect = _read_side_effect
2812 _state[1] = _readline_side_effect()
2813 handle.readline.side_effect = _state[1]
2814 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002815 handle.__iter__.side_effect = _iter_side_effect
Damien Nadé394119a2019-05-23 12:03:25 +02002816 handle.__next__.side_effect = _next_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002817
Robert Collinsca647ef2015-07-24 03:48:20 +12002818 def reset_data(*args, **kwargs):
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002819 _state[0] = _to_stream(read_data)
Robert Collinsca647ef2015-07-24 03:48:20 +12002820 if handle.readline.side_effect == _state[1]:
2821 # Only reset the side effect if the user hasn't overridden it.
2822 _state[1] = _readline_side_effect()
2823 handle.readline.side_effect = _state[1]
2824 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002825
Robert Collinsca647ef2015-07-24 03:48:20 +12002826 mock.side_effect = reset_data
2827 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002828 return mock
2829
2830
2831class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002832 """
2833 A mock intended to be used as a property, or other descriptor, on a class.
2834 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2835 a return value when it is fetched.
2836
2837 Fetching a `PropertyMock` instance from an object calls the mock, with
2838 no args. Setting it calls the mock with the value being set.
2839 """
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002840 def _get_child_mock(self, /, **kwargs):
Michael Foordc2870622012-04-13 16:57:22 +01002841 return MagicMock(**kwargs)
2842
Miss Islington (bot)c71ae1a2019-08-29 02:02:51 -07002843 def __get__(self, obj, obj_type=None):
Michael Foord345266a2012-03-14 12:24:34 -07002844 return self()
2845 def __set__(self, obj, val):
2846 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002847
2848
2849def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002850 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002851
2852 Given an input Mock, seals it to ensure no further mocks will be generated
2853 when accessing an attribute that was not already defined.
2854
Mario Corchero96200eb2018-10-19 22:57:37 +01002855 The operation recursively seals the mock passed in, meaning that
2856 the mock itself, any mocks generated by accessing one of its attributes,
2857 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002858 """
2859 mock._mock_sealed = True
2860 for attr in dir(mock):
2861 try:
2862 m = getattr(mock, attr)
2863 except AttributeError:
2864 continue
2865 if not isinstance(m, NonCallableMock):
2866 continue
2867 if m._mock_new_parent is mock:
2868 seal(m)
Lisa Roach77b3b772019-05-20 09:19:53 -07002869
2870
Lisa Roach77b3b772019-05-20 09:19:53 -07002871class _AsyncIterator:
2872 """
2873 Wraps an iterator in an asynchronous iterator.
2874 """
2875 def __init__(self, iterator):
2876 self.iterator = iterator
2877 code_mock = NonCallableMock(spec_set=CodeType)
2878 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
2879 self.__dict__['__code__'] = code_mock
2880
2881 def __aiter__(self):
2882 return self
2883
2884 async def __anext__(self):
2885 try:
2886 return next(self.iterator)
2887 except StopIteration:
2888 pass
2889 raise StopAsyncIteration