blob: 34f2dd77ec6cd3493b55601d616904a60e922012 [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:
Miss Islington (bot)a5906b22020-01-25 06:53:08 -0800828 # If an autospecced object is attached using attach_mock the
829 # child would be a function with mock object as attribute from
830 # which signature has to be derived.
831 child = _extract_mock(child)
Miss Islington (bot)38d311d2019-08-28 23:58:27 -0700832 children = child._mock_children
833 sig = child._spec_signature
834
835 return sig
836
837
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100838 def _call_matcher(self, _call):
839 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000840 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100841 comparison key suitable for matching with other calls.
842 This is a best effort method which relies on the spec's signature,
843 if available, or falls back on the arguments themselves.
844 """
Miss Islington (bot)38d311d2019-08-28 23:58:27 -0700845
846 if isinstance(_call, tuple) and len(_call) > 2:
847 sig = self._get_call_signature_from_name(_call[0])
848 else:
849 sig = self._spec_signature
850
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100851 if sig is not None:
852 if len(_call) == 2:
853 name = ''
854 args, kwargs = _call
855 else:
856 name, args, kwargs = _call
857 try:
858 return name, sig.bind(*args, **kwargs)
859 except TypeError as e:
860 return e.with_traceback(None)
861 else:
862 return _call
863
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300864 def assert_not_called(self):
Kushal Das8af9db32014-04-17 01:36:14 +0530865 """assert that the mock was never called.
866 """
Kushal Das8af9db32014-04-17 01:36:14 +0530867 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100868 msg = ("Expected '%s' to not have been called. Called %s times.%s"
869 % (self._mock_name or 'mock',
870 self.call_count,
871 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530872 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100873
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300874 def assert_called(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100875 """assert that the mock was called at least once
876 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100877 if self.call_count == 0:
878 msg = ("Expected '%s' to have been called." %
Miss Islington (bot)f668d2b2019-09-17 04:35:56 -0700879 (self._mock_name or 'mock'))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100880 raise AssertionError(msg)
881
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300882 def assert_called_once(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100883 """assert that the mock was called only once.
884 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100885 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100886 msg = ("Expected '%s' to have been called once. Called %s times.%s"
887 % (self._mock_name or 'mock',
888 self.call_count,
889 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100890 raise AssertionError(msg)
891
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300892 def assert_called_with(self, /, *args, **kwargs):
Miss Islington (bot)612d3932019-08-28 23:39:47 -0700893 """assert that the last call was made with the specified arguments.
Michael Foord345266a2012-03-14 12:24:34 -0700894
895 Raises an AssertionError if the args and keyword args passed in are
896 different to the last call to the mock."""
Michael Foord345266a2012-03-14 12:24:34 -0700897 if self.call_args is None:
898 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800899 actual = 'not called.'
900 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
901 % (expected, actual))
902 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700903
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100904 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700905 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100906 return msg
907 expected = self._call_matcher((args, kwargs))
908 actual = self._call_matcher(self.call_args)
909 if expected != actual:
910 cause = expected if isinstance(expected, Exception) else None
911 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700912
913
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300914 def assert_called_once_with(self, /, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100915 """assert that the mock was called exactly once and that that call was
916 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700917 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100918 msg = ("Expected '%s' to be called once. Called %s times.%s"
919 % (self._mock_name or 'mock',
920 self.call_count,
921 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700922 raise AssertionError(msg)
923 return self.assert_called_with(*args, **kwargs)
924
925
926 def assert_has_calls(self, calls, any_order=False):
927 """assert the mock has been called with the specified calls.
928 The `mock_calls` list is checked for the calls.
929
930 If `any_order` is False (the default) then the calls must be
931 sequential. There can be extra calls before or after the
932 specified calls.
933
934 If `any_order` is True then the calls can be in any order, but
935 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100936 expected = [self._call_matcher(c) for c in calls]
Miss Islington (bot)1a17a052019-09-24 17:29:17 -0700937 cause = next((e for e in expected if isinstance(e, Exception)), None)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100938 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700939 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100940 if expected not in all_calls:
Miss Islington (bot)1a17a052019-09-24 17:29:17 -0700941 if cause is None:
942 problem = 'Calls not found.'
943 else:
944 problem = ('Error processing expected calls.\n'
945 'Errors: {}').format(
946 [e if isinstance(e, Exception) else None
947 for e in expected])
Michael Foord345266a2012-03-14 12:24:34 -0700948 raise AssertionError(
Miss Islington (bot)1a17a052019-09-24 17:29:17 -0700949 f'{problem}\n'
950 f'Expected: {_CallList(calls)}'
951 f'{self._calls_repr(prefix="Actual").rstrip(".")}'
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100952 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700953 return
954
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100955 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700956
957 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100958 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700959 try:
960 all_calls.remove(kall)
961 except ValueError:
962 not_found.append(kall)
963 if not_found:
964 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400965 '%r does not contain all of %r in its call list, '
966 'found %r instead' % (self._mock_name or 'mock',
967 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100968 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700969
970
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300971 def assert_any_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700972 """assert the mock has been called with the specified arguments.
973
974 The assert passes if the mock has *ever* been called, unlike
975 `assert_called_with` and `assert_called_once_with` that only pass if
976 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100977 expected = self._call_matcher((args, kwargs))
978 actual = [self._call_matcher(c) for c in self.call_args_list]
979 if expected not in actual:
980 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700981 expected_string = self._format_mock_call_signature(args, kwargs)
982 raise AssertionError(
983 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100984 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700985
986
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300987 def _get_child_mock(self, /, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700988 """Create the child mocks for attributes and return value.
989 By default child mocks will be the same type as the parent.
990 Subclasses of Mock may want to override this to customize the way
991 child mocks are made.
992
993 For non-callable mocks the callable variant will be used (rather than
994 any custom subclass)."""
Lisa Roach77b3b772019-05-20 09:19:53 -0700995 _new_name = kw.get("_new_name")
996 if _new_name in self.__dict__['_spec_asyncs']:
997 return AsyncMock(**kw)
998
Michael Foord345266a2012-03-14 12:24:34 -0700999 _type = type(self)
Lisa Roach77b3b772019-05-20 09:19:53 -07001000 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07001001 # Any asynchronous magic becomes an AsyncMock
Lisa Roach77b3b772019-05-20 09:19:53 -07001002 klass = AsyncMock
Lisa Roach865bb682019-09-20 23:00:04 -07001003 elif issubclass(_type, AsyncMockMixin):
Lisa Roach21f24ea2019-09-29 22:22:44 -07001004 if (_new_name in _all_sync_magics or
1005 self._mock_methods and _new_name in self._mock_methods):
1006 # Any synchronous method on AsyncMock becomes a MagicMock
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07001007 klass = MagicMock
1008 else:
1009 klass = AsyncMock
Lisa Roach865bb682019-09-20 23:00:04 -07001010 elif not issubclass(_type, CallableMixin):
Michael Foord345266a2012-03-14 12:24:34 -07001011 if issubclass(_type, NonCallableMagicMock):
1012 klass = MagicMock
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07001013 elif issubclass(_type, NonCallableMock):
Michael Foord345266a2012-03-14 12:24:34 -07001014 klass = Mock
1015 else:
1016 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +01001017
1018 if self._mock_sealed:
1019 attribute = "." + kw["name"] if "name" in kw else "()"
1020 mock_name = self._extract_mock_name() + attribute
1021 raise AttributeError(mock_name)
1022
Michael Foord345266a2012-03-14 12:24:34 -07001023 return klass(**kw)
1024
1025
Petter Strandmark47d94242018-10-28 21:37:10 +01001026 def _calls_repr(self, prefix="Calls"):
1027 """Renders self.mock_calls as a string.
1028
1029 Example: "\nCalls: [call(1), call(2)]."
1030
1031 If self.mock_calls is empty, an empty string is returned. The
1032 output will be truncated if very long.
1033 """
1034 if not self.mock_calls:
1035 return ""
1036 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
1037
1038
Michael Foord345266a2012-03-14 12:24:34 -07001039
1040def _try_iter(obj):
1041 if obj is None:
1042 return obj
1043 if _is_exception(obj):
1044 return obj
1045 if _callable(obj):
1046 return obj
1047 try:
1048 return iter(obj)
1049 except TypeError:
1050 # XXXX backwards compatibility
1051 # but this will blow up on first call - so maybe we should fail early?
1052 return obj
1053
1054
Michael Foord345266a2012-03-14 12:24:34 -07001055class CallableMixin(Base):
1056
1057 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
1058 wraps=None, name=None, spec_set=None, parent=None,
1059 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
1060 self.__dict__['_mock_return_value'] = return_value
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001061 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -07001062 spec, wraps, name, spec_set, parent,
1063 _spec_state, _new_name, _new_parent, **kwargs
1064 )
1065
1066 self.side_effect = side_effect
1067
1068
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001069 def _mock_check_sig(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001070 # stub method that can be replaced with one with a specific signature
1071 pass
1072
1073
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001074 def __call__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001075 # can't use self in-case a function / method we are mocking uses self
1076 # in the signature
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001077 self._mock_check_sig(*args, **kwargs)
Lisa Roach52bdd412019-09-27 15:44:34 -07001078 self._increment_mock_call(*args, **kwargs)
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001079 return self._mock_call(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001080
1081
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001082 def _mock_call(self, /, *args, **kwargs):
Lisa Roach52bdd412019-09-27 15:44:34 -07001083 return self._execute_mock_call(*args, **kwargs)
1084
1085 def _increment_mock_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001086 self.called = True
1087 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001088
Chris Withers8ca0fa92018-12-03 21:31:37 +00001089 # handle call_args
Lisa Roach52bdd412019-09-27 15:44:34 -07001090 # needs to be set here so assertions on call arguments pass before
1091 # execution in the case of awaited calls
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001092 _call = _Call((args, kwargs), two=True)
1093 self.call_args = _call
1094 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -07001095
Chris Withers8ca0fa92018-12-03 21:31:37 +00001096 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001097 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +00001098 method_call_name = self._mock_name
1099
1100 # initial stuff for mock_calls:
1101 mock_call_name = self._mock_new_name
1102 is_a_call = mock_call_name == '()'
1103 self.mock_calls.append(_Call(('', args, kwargs)))
1104
1105 # follow up the chain of mocks:
1106 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001107 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001108
Chris Withers8ca0fa92018-12-03 21:31:37 +00001109 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001110 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001111 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001112 do_method_calls = _new_parent._mock_parent is not None
1113 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001114 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001115
Chris Withers8ca0fa92018-12-03 21:31:37 +00001116 # handle mock_calls:
1117 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001118 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001119
1120 if _new_parent._mock_new_name:
1121 if is_a_call:
1122 dot = ''
1123 else:
1124 dot = '.'
1125 is_a_call = _new_parent._mock_new_name == '()'
1126 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1127
1128 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001129 _new_parent = _new_parent._mock_new_parent
1130
Lisa Roach52bdd412019-09-27 15:44:34 -07001131 def _execute_mock_call(self, /, *args, **kwargs):
Lisa Roachb2744c12019-11-21 10:14:32 -08001132 # separate from _increment_mock_call so that awaited functions are
1133 # executed separately from their call, also AsyncMock overrides this method
Lisa Roach52bdd412019-09-27 15:44:34 -07001134
Michael Foord345266a2012-03-14 12:24:34 -07001135 effect = self.side_effect
1136 if effect is not None:
1137 if _is_exception(effect):
1138 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001139 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001140 result = next(effect)
1141 if _is_exception(result):
1142 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001143 else:
1144 result = effect(*args, **kwargs)
1145
1146 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001147 return result
Michael Foord345266a2012-03-14 12:24:34 -07001148
Mario Corcherof05df0a2018-12-08 11:25:02 +00001149 if self._mock_return_value is not DEFAULT:
1150 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001151
Mario Corcherof05df0a2018-12-08 11:25:02 +00001152 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001153 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001154
1155 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001156
1157
1158
1159class Mock(CallableMixin, NonCallableMock):
1160 """
1161 Create a new `Mock` object. `Mock` takes several optional arguments
1162 that specify the behaviour of the Mock object:
1163
1164 * `spec`: This can be either a list of strings or an existing object (a
1165 class or instance) that acts as the specification for the mock object. If
1166 you pass in an object then a list of strings is formed by calling dir on
1167 the object (excluding unsupported magic attributes and methods). Accessing
1168 any attribute not in this list will raise an `AttributeError`.
1169
1170 If `spec` is an object (rather than a list of strings) then
1171 `mock.__class__` returns the class of the spec object. This allows mocks
1172 to pass `isinstance` tests.
1173
1174 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1175 or get an attribute on the mock that isn't on the object passed as
1176 `spec_set` will raise an `AttributeError`.
1177
1178 * `side_effect`: A function to be called whenever the Mock is called. See
1179 the `side_effect` attribute. Useful for raising exceptions or
1180 dynamically changing return values. The function is called with the same
1181 arguments as the mock, and unless it returns `DEFAULT`, the return
1182 value of this function is used as the return value.
1183
Michael Foord2cd48732012-04-21 15:52:11 +01001184 If `side_effect` is an iterable then each call to the mock will return
1185 the next value from the iterable. If any of the members of the iterable
1186 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001187
Michael Foord345266a2012-03-14 12:24:34 -07001188 * `return_value`: The value returned when the mock is called. By default
1189 this is a new Mock (created on first access). See the
1190 `return_value` attribute.
1191
Michael Foord0682a0c2012-04-13 20:51:20 +01001192 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1193 calling the Mock will pass the call through to the wrapped object
1194 (returning the real result). Attribute access on the mock will return a
1195 Mock object that wraps the corresponding attribute of the wrapped object
1196 (so attempting to access an attribute that doesn't exist will raise an
1197 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001198
1199 If the mock has an explicit `return_value` set then calls are not passed
1200 to the wrapped object and the `return_value` is returned instead.
1201
1202 * `name`: If the mock has a name then it will be used in the repr of the
1203 mock. This can be useful for debugging. The name is propagated to child
1204 mocks.
1205
1206 Mocks can also be called with arbitrary keyword arguments. These will be
1207 used to set attributes on the mock after it is created.
1208 """
1209
1210
Michael Foord345266a2012-03-14 12:24:34 -07001211def _dot_lookup(thing, comp, import_path):
1212 try:
1213 return getattr(thing, comp)
1214 except AttributeError:
1215 __import__(import_path)
1216 return getattr(thing, comp)
1217
1218
1219def _importer(target):
1220 components = target.split('.')
1221 import_path = components.pop(0)
1222 thing = __import__(import_path)
1223
1224 for comp in components:
1225 import_path += ".%s" % comp
1226 thing = _dot_lookup(thing, comp, import_path)
1227 return thing
1228
1229
1230def _is_started(patcher):
1231 # XXXX horrible
1232 return hasattr(patcher, 'is_local')
1233
1234
1235class _patch(object):
1236
1237 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001238 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001239
1240 def __init__(
1241 self, getter, attribute, new, spec, create,
1242 spec_set, autospec, new_callable, kwargs
1243 ):
1244 if new_callable is not None:
1245 if new is not DEFAULT:
1246 raise ValueError(
1247 "Cannot use 'new' and 'new_callable' together"
1248 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001249 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001250 raise ValueError(
1251 "Cannot use 'autospec' and 'new_callable' together"
1252 )
1253
1254 self.getter = getter
1255 self.attribute = attribute
1256 self.new = new
1257 self.new_callable = new_callable
1258 self.spec = spec
1259 self.create = create
1260 self.has_local = False
1261 self.spec_set = spec_set
1262 self.autospec = autospec
1263 self.kwargs = kwargs
1264 self.additional_patchers = []
1265
1266
1267 def copy(self):
1268 patcher = _patch(
1269 self.getter, self.attribute, self.new, self.spec,
1270 self.create, self.spec_set,
1271 self.autospec, self.new_callable, self.kwargs
1272 )
1273 patcher.attribute_name = self.attribute_name
1274 patcher.additional_patchers = [
1275 p.copy() for p in self.additional_patchers
1276 ]
1277 return patcher
1278
1279
1280 def __call__(self, func):
1281 if isinstance(func, type):
1282 return self.decorate_class(func)
Xtreak436c2b02019-05-28 12:37:39 +05301283 if inspect.iscoroutinefunction(func):
1284 return self.decorate_async_callable(func)
Michael Foord345266a2012-03-14 12:24:34 -07001285 return self.decorate_callable(func)
1286
1287
1288 def decorate_class(self, klass):
1289 for attr in dir(klass):
1290 if not attr.startswith(patch.TEST_PREFIX):
1291 continue
1292
1293 attr_value = getattr(klass, attr)
1294 if not hasattr(attr_value, "__call__"):
1295 continue
1296
1297 patcher = self.copy()
1298 setattr(klass, attr, patcher(attr_value))
1299 return klass
1300
1301
Xtreak436c2b02019-05-28 12:37:39 +05301302 @contextlib.contextmanager
1303 def decoration_helper(self, patched, args, keywargs):
1304 extra_args = []
1305 entered_patchers = []
1306 patching = None
1307
1308 exc_info = tuple()
1309 try:
1310 for patching in patched.patchings:
1311 arg = patching.__enter__()
1312 entered_patchers.append(patching)
1313 if patching.attribute_name is not None:
1314 keywargs.update(arg)
1315 elif patching.new is DEFAULT:
1316 extra_args.append(arg)
1317
1318 args += tuple(extra_args)
1319 yield (args, keywargs)
1320 except:
1321 if (patching not in entered_patchers and
1322 _is_started(patching)):
1323 # the patcher may have been started, but an exception
1324 # raised whilst entering one of its additional_patchers
1325 entered_patchers.append(patching)
1326 # Pass the exception to __exit__
1327 exc_info = sys.exc_info()
1328 # re-raise the exception
1329 raise
1330 finally:
1331 for patching in reversed(entered_patchers):
1332 patching.__exit__(*exc_info)
1333
1334
Michael Foord345266a2012-03-14 12:24:34 -07001335 def decorate_callable(self, func):
Xtreak436c2b02019-05-28 12:37:39 +05301336 # NB. Keep the method in sync with decorate_async_callable()
Michael Foord345266a2012-03-14 12:24:34 -07001337 if hasattr(func, 'patchings'):
1338 func.patchings.append(self)
1339 return func
1340
1341 @wraps(func)
1342 def patched(*args, **keywargs):
Xtreak436c2b02019-05-28 12:37:39 +05301343 with self.decoration_helper(patched,
1344 args,
1345 keywargs) as (newargs, newkeywargs):
1346 return func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001347
Xtreak436c2b02019-05-28 12:37:39 +05301348 patched.patchings = [self]
1349 return patched
Michael Foord345266a2012-03-14 12:24:34 -07001350
Xtreak436c2b02019-05-28 12:37:39 +05301351
1352 def decorate_async_callable(self, func):
1353 # NB. Keep the method in sync with decorate_callable()
1354 if hasattr(func, 'patchings'):
1355 func.patchings.append(self)
1356 return func
1357
1358 @wraps(func)
1359 async def patched(*args, **keywargs):
1360 with self.decoration_helper(patched,
1361 args,
1362 keywargs) as (newargs, newkeywargs):
1363 return await func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001364
1365 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001366 return patched
1367
1368
1369 def get_original(self):
1370 target = self.getter()
1371 name = self.attribute
1372
1373 original = DEFAULT
1374 local = False
1375
1376 try:
1377 original = target.__dict__[name]
1378 except (AttributeError, KeyError):
1379 original = getattr(target, name, DEFAULT)
1380 else:
1381 local = True
1382
Michael Foordfddcfa22014-04-14 16:25:20 -04001383 if name in _builtins and isinstance(target, ModuleType):
1384 self.create = True
1385
Michael Foord345266a2012-03-14 12:24:34 -07001386 if not self.create and original is DEFAULT:
1387 raise AttributeError(
1388 "%s does not have the attribute %r" % (target, name)
1389 )
1390 return original, local
1391
1392
1393 def __enter__(self):
1394 """Perform the patch."""
1395 new, spec, spec_set = self.new, self.spec, self.spec_set
1396 autospec, kwargs = self.autospec, self.kwargs
1397 new_callable = self.new_callable
1398 self.target = self.getter()
1399
Michael Foord50a8c0e2012-03-25 18:57:58 +01001400 # normalise False to None
1401 if spec is False:
1402 spec = None
1403 if spec_set is False:
1404 spec_set = None
1405 if autospec is False:
1406 autospec = None
1407
1408 if spec is not None and autospec is not None:
1409 raise TypeError("Can't specify spec and autospec")
1410 if ((spec is not None or autospec is not None) and
1411 spec_set not in (True, None)):
1412 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1413
Michael Foord345266a2012-03-14 12:24:34 -07001414 original, local = self.get_original()
1415
Michael Foord50a8c0e2012-03-25 18:57:58 +01001416 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001417 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001418 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001419 # set spec to the object we are replacing
1420 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001421 if spec_set is True:
1422 spec_set = original
1423 spec = None
1424 elif spec is not None:
1425 if spec_set is True:
1426 spec_set = spec
1427 spec = None
1428 elif spec_set is True:
1429 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001430
Michael Foord50a8c0e2012-03-25 18:57:58 +01001431 if spec is not None or spec_set is not None:
1432 if original is DEFAULT:
1433 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001434 if isinstance(original, type):
1435 # If we're patching out a class and there is a spec
1436 inherit = True
Lisa Roach77b3b772019-05-20 09:19:53 -07001437 if spec is None and _is_async_obj(original):
1438 Klass = AsyncMock
1439 else:
1440 Klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -07001441 _kwargs = {}
1442 if new_callable is not None:
1443 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001444 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001445 this_spec = spec
1446 if spec_set is not None:
1447 this_spec = spec_set
1448 if _is_list(this_spec):
1449 not_callable = '__call__' not in this_spec
1450 else:
1451 not_callable = not callable(this_spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07001452 if _is_async_obj(this_spec):
1453 Klass = AsyncMock
1454 elif not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001455 Klass = NonCallableMagicMock
1456
1457 if spec is not None:
1458 _kwargs['spec'] = spec
1459 if spec_set is not None:
1460 _kwargs['spec_set'] = spec_set
1461
1462 # add a name to mocks
1463 if (isinstance(Klass, type) and
1464 issubclass(Klass, NonCallableMock) and self.attribute):
1465 _kwargs['name'] = self.attribute
1466
1467 _kwargs.update(kwargs)
1468 new = Klass(**_kwargs)
1469
1470 if inherit and _is_instance_mock(new):
1471 # we can only tell if the instance should be callable if the
1472 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001473 this_spec = spec
1474 if spec_set is not None:
1475 this_spec = spec_set
1476 if (not _is_list(this_spec) and not
1477 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001478 Klass = NonCallableMagicMock
1479
1480 _kwargs.pop('name')
1481 new.return_value = Klass(_new_parent=new, _new_name='()',
1482 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001483 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001484 # spec is ignored, new *must* be default, spec_set is treated
1485 # as a boolean. Should we check spec is not None and that spec_set
1486 # is a bool?
1487 if new is not DEFAULT:
1488 raise TypeError(
1489 "autospec creates the mock for you. Can't specify "
1490 "autospec and new."
1491 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001492 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001493 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001494 spec_set = bool(spec_set)
1495 if autospec is True:
1496 autospec = original
1497
1498 new = create_autospec(autospec, spec_set=spec_set,
1499 _name=self.attribute, **kwargs)
1500 elif kwargs:
1501 # can't set keyword args when we aren't creating the mock
1502 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1503 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1504
1505 new_attr = new
1506
1507 self.temp_original = original
1508 self.is_local = local
1509 setattr(self.target, self.attribute, new_attr)
1510 if self.attribute_name is not None:
1511 extra_args = {}
1512 if self.new is DEFAULT:
1513 extra_args[self.attribute_name] = new
1514 for patching in self.additional_patchers:
1515 arg = patching.__enter__()
1516 if patching.new is DEFAULT:
1517 extra_args.update(arg)
1518 return extra_args
1519
1520 return new
1521
1522
Michael Foord50a8c0e2012-03-25 18:57:58 +01001523 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001524 """Undo the patch."""
1525 if not _is_started(self):
Xtreak02b84cb2019-03-29 02:38:43 +05301526 return
Michael Foord345266a2012-03-14 12:24:34 -07001527
1528 if self.is_local and self.temp_original is not DEFAULT:
1529 setattr(self.target, self.attribute, self.temp_original)
1530 else:
1531 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001532 if not self.create and (not hasattr(self.target, self.attribute) or
1533 self.attribute in ('__doc__', '__module__',
1534 '__defaults__', '__annotations__',
1535 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001536 # needed for proxy objects like django settings
1537 setattr(self.target, self.attribute, self.temp_original)
1538
1539 del self.temp_original
1540 del self.is_local
1541 del self.target
1542 for patcher in reversed(self.additional_patchers):
1543 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001544 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001545
Michael Foordf7c41582012-06-10 20:36:32 +01001546
1547 def start(self):
1548 """Activate a patch, returning any created mock."""
1549 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001550 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001551 return result
1552
1553
1554 def stop(self):
1555 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001556 try:
1557 self._active_patches.remove(self)
1558 except ValueError:
1559 # If the patch hasn't been started this will fail
1560 pass
1561
Michael Foordf7c41582012-06-10 20:36:32 +01001562 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001563
1564
1565
1566def _get_target(target):
1567 try:
1568 target, attribute = target.rsplit('.', 1)
1569 except (TypeError, ValueError):
1570 raise TypeError("Need a valid target to patch. You supplied: %r" %
1571 (target,))
1572 getter = lambda: _importer(target)
1573 return getter, attribute
1574
1575
1576def _patch_object(
1577 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001578 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001579 new_callable=None, **kwargs
1580 ):
1581 """
Michael Foord345266a2012-03-14 12:24:34 -07001582 patch the named member (`attribute`) on an object (`target`) with a mock
1583 object.
1584
1585 `patch.object` can be used as a decorator, class decorator or a context
1586 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1587 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1588 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1589 the mock object it creates.
1590
1591 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1592 for choosing which methods to wrap.
1593 """
Miss Islington (bot)45945652019-12-08 22:59:04 -08001594 if type(target) is str:
1595 raise TypeError(
1596 f"{target!r} must be the actual object to be patched, not a str"
1597 )
Michael Foord345266a2012-03-14 12:24:34 -07001598 getter = lambda: target
1599 return _patch(
1600 getter, attribute, new, spec, create,
1601 spec_set, autospec, new_callable, kwargs
1602 )
1603
1604
Michael Foord50a8c0e2012-03-25 18:57:58 +01001605def _patch_multiple(target, spec=None, create=False, spec_set=None,
1606 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001607 """Perform multiple patches in a single call. It takes the object to be
1608 patched (either as an object or a string to fetch the object by importing)
1609 and keyword arguments for the patches::
1610
1611 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1612 ...
1613
1614 Use `DEFAULT` as the value if you want `patch.multiple` to create
1615 mocks for you. In this case the created mocks are passed into a decorated
1616 function by keyword, and a dictionary is returned when `patch.multiple` is
1617 used as a context manager.
1618
1619 `patch.multiple` can be used as a decorator, class decorator or a context
1620 manager. The arguments `spec`, `spec_set`, `create`,
1621 `autospec` and `new_callable` have the same meaning as for `patch`. These
1622 arguments will be applied to *all* patches done by `patch.multiple`.
1623
1624 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1625 for choosing which methods to wrap.
1626 """
1627 if type(target) is str:
1628 getter = lambda: _importer(target)
1629 else:
1630 getter = lambda: target
1631
1632 if not kwargs:
1633 raise ValueError(
1634 'Must supply at least one keyword argument with patch.multiple'
1635 )
1636 # need to wrap in a list for python 3, where items is a view
1637 items = list(kwargs.items())
1638 attribute, new = items[0]
1639 patcher = _patch(
1640 getter, attribute, new, spec, create, spec_set,
1641 autospec, new_callable, {}
1642 )
1643 patcher.attribute_name = attribute
1644 for attribute, new in items[1:]:
1645 this_patcher = _patch(
1646 getter, attribute, new, spec, create, spec_set,
1647 autospec, new_callable, {}
1648 )
1649 this_patcher.attribute_name = attribute
1650 patcher.additional_patchers.append(this_patcher)
1651 return patcher
1652
1653
1654def patch(
1655 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001656 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001657 ):
1658 """
1659 `patch` acts as a function decorator, class decorator or a context
1660 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001661 is patched with a `new` object. When the function/with statement exits
1662 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001663
Miss Islington (bot)eaa1b092019-09-10 06:15:19 -07001664 If `new` is omitted, then the target is replaced with an
1665 `AsyncMock if the patched object is an async function or a
1666 `MagicMock` otherwise. If `patch` is used as a decorator and `new` is
Michael Foord54b3db82012-03-28 15:08:08 +01001667 omitted, the created mock is passed in as an extra argument to the
1668 decorated function. If `patch` is used as a context manager the created
1669 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001670
Michael Foord54b3db82012-03-28 15:08:08 +01001671 `target` should be a string in the form `'package.module.ClassName'`. The
1672 `target` is imported and the specified object replaced with the `new`
1673 object, so the `target` must be importable from the environment you are
1674 calling `patch` from. The target is imported when the decorated function
1675 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001676
1677 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1678 if patch is creating one for you.
1679
1680 In addition you can pass `spec=True` or `spec_set=True`, which causes
1681 patch to pass in the object being mocked as the spec/spec_set object.
1682
1683 `new_callable` allows you to specify a different class, or callable object,
Miss Islington (bot)eaa1b092019-09-10 06:15:19 -07001684 that will be called to create the `new` object. By default `AsyncMock` is
1685 used for async functions and `MagicMock` for the rest.
Michael Foord345266a2012-03-14 12:24:34 -07001686
1687 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001688 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001689 All attributes of the mock will also have the spec of the corresponding
1690 attribute of the object being replaced. Methods and functions being
1691 mocked will have their arguments checked and will raise a `TypeError` if
1692 they are called with the wrong signature. For mocks replacing a class,
1693 their return value (the 'instance') will have the same spec as the class.
1694
1695 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1696 arbitrary object as the spec instead of the one being replaced.
1697
1698 By default `patch` will fail to replace attributes that don't exist. If
1699 you pass in `create=True`, and the attribute doesn't exist, patch will
1700 create the attribute for you when the patched function is called, and
1701 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001702 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001703 default because it can be dangerous. With it switched on you can write
1704 passing tests against APIs that don't actually exist!
1705
1706 Patch can be used as a `TestCase` class decorator. It works by
1707 decorating each test method in the class. This reduces the boilerplate
1708 code when your test methods share a common patchings set. `patch` finds
1709 tests by looking for method names that start with `patch.TEST_PREFIX`.
1710 By default this is `test`, which matches the way `unittest` finds tests.
1711 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1712
1713 Patch can be used as a context manager, with the with statement. Here the
1714 patching applies to the indented block after the with statement. If you
1715 use "as" then the patched object will be bound to the name after the
1716 "as"; very useful if `patch` is creating a mock object for you.
1717
1718 `patch` takes arbitrary keyword arguments. These will be passed to
1719 the `Mock` (or `new_callable`) on construction.
1720
1721 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1722 available for alternate use-cases.
1723 """
1724 getter, attribute = _get_target(target)
1725 return _patch(
1726 getter, attribute, new, spec, create,
1727 spec_set, autospec, new_callable, kwargs
1728 )
1729
1730
1731class _patch_dict(object):
1732 """
1733 Patch a dictionary, or dictionary like object, and restore the dictionary
1734 to its original state after the test.
1735
1736 `in_dict` can be a dictionary or a mapping like container. If it is a
1737 mapping then it must at least support getting, setting and deleting items
1738 plus iterating over keys.
1739
1740 `in_dict` can also be a string specifying the name of the dictionary, which
1741 will then be fetched by importing it.
1742
1743 `values` can be a dictionary of values to set in the dictionary. `values`
1744 can also be an iterable of `(key, value)` pairs.
1745
1746 If `clear` is True then the dictionary will be cleared before the new
1747 values are set.
1748
1749 `patch.dict` can also be called with arbitrary keyword arguments to set
1750 values in the dictionary::
1751
1752 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1753 ...
1754
1755 `patch.dict` can be used as a context manager, decorator or class
1756 decorator. When used as a class decorator `patch.dict` honours
1757 `patch.TEST_PREFIX` for choosing which methods to wrap.
1758 """
1759
1760 def __init__(self, in_dict, values=(), clear=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001761 self.in_dict = in_dict
1762 # support any argument supported by dict(...) constructor
1763 self.values = dict(values)
1764 self.values.update(kwargs)
1765 self.clear = clear
1766 self._original = None
1767
1768
1769 def __call__(self, f):
1770 if isinstance(f, type):
1771 return self.decorate_class(f)
1772 @wraps(f)
1773 def _inner(*args, **kw):
1774 self._patch_dict()
1775 try:
1776 return f(*args, **kw)
1777 finally:
1778 self._unpatch_dict()
1779
1780 return _inner
1781
1782
1783 def decorate_class(self, klass):
1784 for attr in dir(klass):
1785 attr_value = getattr(klass, attr)
1786 if (attr.startswith(patch.TEST_PREFIX) and
1787 hasattr(attr_value, "__call__")):
1788 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1789 decorated = decorator(attr_value)
1790 setattr(klass, attr, decorated)
1791 return klass
1792
1793
1794 def __enter__(self):
1795 """Patch the dict."""
1796 self._patch_dict()
Mario Corchero04530812019-05-28 13:53:31 +01001797 return self.in_dict
Michael Foord345266a2012-03-14 12:24:34 -07001798
1799
1800 def _patch_dict(self):
1801 values = self.values
Xtreaka875ea52019-02-25 00:24:49 +05301802 if isinstance(self.in_dict, str):
1803 self.in_dict = _importer(self.in_dict)
Michael Foord345266a2012-03-14 12:24:34 -07001804 in_dict = self.in_dict
1805 clear = self.clear
1806
1807 try:
1808 original = in_dict.copy()
1809 except AttributeError:
1810 # dict like object with no copy method
1811 # must support iteration over keys
1812 original = {}
1813 for key in in_dict:
1814 original[key] = in_dict[key]
1815 self._original = original
1816
1817 if clear:
1818 _clear_dict(in_dict)
1819
1820 try:
1821 in_dict.update(values)
1822 except AttributeError:
1823 # dict like object with no update method
1824 for key in values:
1825 in_dict[key] = values[key]
1826
1827
1828 def _unpatch_dict(self):
1829 in_dict = self.in_dict
1830 original = self._original
1831
1832 _clear_dict(in_dict)
1833
1834 try:
1835 in_dict.update(original)
1836 except AttributeError:
1837 for key in original:
1838 in_dict[key] = original[key]
1839
1840
1841 def __exit__(self, *args):
1842 """Unpatch the dict."""
1843 self._unpatch_dict()
1844 return False
1845
1846 start = __enter__
1847 stop = __exit__
1848
1849
1850def _clear_dict(in_dict):
1851 try:
1852 in_dict.clear()
1853 except AttributeError:
1854 keys = list(in_dict)
1855 for key in keys:
1856 del in_dict[key]
1857
1858
Michael Foordf7c41582012-06-10 20:36:32 +01001859def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001860 """Stop all active patches. LIFO to unroll nested patches."""
1861 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001862 patch.stop()
1863
1864
Michael Foord345266a2012-03-14 12:24:34 -07001865patch.object = _patch_object
1866patch.dict = _patch_dict
1867patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001868patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001869patch.TEST_PREFIX = 'test'
1870
1871magic_methods = (
1872 "lt le gt ge eq ne "
1873 "getitem setitem delitem "
1874 "len contains iter "
1875 "hash str sizeof "
1876 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001877 # we added divmod and rdivmod here instead of numerics
1878 # because there is no idivmod
1879 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001880 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001881 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001882 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001883 "fspath "
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07001884 "aiter "
Michael Foord345266a2012-03-14 12:24:34 -07001885)
1886
Michael Foordd2623d72014-04-14 11:23:48 -04001887numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001888 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001889)
Michael Foord345266a2012-03-14 12:24:34 -07001890inplace = ' '.join('i%s' % n for n in numerics.split())
1891right = ' '.join('r%s' % n for n in numerics.split())
1892
1893# not including __prepare__, __instancecheck__, __subclasscheck__
1894# (as they are metaclass methods)
1895# __del__ is not supported at all as it causes problems if it exists
1896
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001897_non_defaults = {
1898 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1899 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1900 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1901 '__repr__', '__dir__', '__subclasses__', '__format__',
Lisa Roach865bb682019-09-20 23:00:04 -07001902 '__getnewargs_ex__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001903}
Michael Foord345266a2012-03-14 12:24:34 -07001904
1905
1906def _get_method(name, func):
1907 "Turns a callable object (like a mock) into a real function"
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001908 def method(self, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -07001909 return func(self, *args, **kw)
1910 method.__name__ = name
1911 return method
1912
1913
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001914_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001915 '__%s__' % method for method in
1916 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001917}
Michael Foord345266a2012-03-14 12:24:34 -07001918
Lisa Roach77b3b772019-05-20 09:19:53 -07001919# Magic methods used for async `with` statements
1920_async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
Lisa Roach865bb682019-09-20 23:00:04 -07001921# Magic methods that are only used with async calls but are synchronous functions themselves
1922_sync_async_magics = {"__aiter__"}
1923_async_magics = _async_method_magics | _sync_async_magics
Lisa Roach77b3b772019-05-20 09:19:53 -07001924
Lisa Roach865bb682019-09-20 23:00:04 -07001925_all_sync_magics = _magics | _non_defaults
1926_all_magics = _all_sync_magics | _async_magics
Michael Foord345266a2012-03-14 12:24:34 -07001927
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001928_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001929 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001930 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001931 '__instancecheck__', '__subclasscheck__',
1932 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001933}
Michael Foord345266a2012-03-14 12:24:34 -07001934
1935_calculate_return_value = {
1936 '__hash__': lambda self: object.__hash__(self),
1937 '__str__': lambda self: object.__str__(self),
1938 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001939 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001940}
1941
1942_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001943 '__lt__': NotImplemented,
1944 '__gt__': NotImplemented,
1945 '__le__': NotImplemented,
1946 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001947 '__int__': 1,
1948 '__contains__': False,
1949 '__len__': 0,
1950 '__exit__': False,
1951 '__complex__': 1j,
1952 '__float__': 1.0,
1953 '__bool__': True,
1954 '__index__': 1,
Lisa Roach77b3b772019-05-20 09:19:53 -07001955 '__aexit__': False,
Michael Foord345266a2012-03-14 12:24:34 -07001956}
1957
1958
1959def _get_eq(self):
1960 def __eq__(other):
1961 ret_val = self.__eq__._mock_return_value
1962 if ret_val is not DEFAULT:
1963 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001964 if self is other:
1965 return True
1966 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001967 return __eq__
1968
1969def _get_ne(self):
1970 def __ne__(other):
1971 if self.__ne__._mock_return_value is not DEFAULT:
1972 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001973 if self is other:
1974 return False
1975 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001976 return __ne__
1977
1978def _get_iter(self):
1979 def __iter__():
1980 ret_val = self.__iter__._mock_return_value
1981 if ret_val is DEFAULT:
1982 return iter([])
1983 # if ret_val was already an iterator, then calling iter on it should
1984 # return the iterator unchanged
1985 return iter(ret_val)
1986 return __iter__
1987
Lisa Roach77b3b772019-05-20 09:19:53 -07001988def _get_async_iter(self):
1989 def __aiter__():
1990 ret_val = self.__aiter__._mock_return_value
1991 if ret_val is DEFAULT:
1992 return _AsyncIterator(iter([]))
1993 return _AsyncIterator(iter(ret_val))
1994 return __aiter__
1995
Michael Foord345266a2012-03-14 12:24:34 -07001996_side_effect_methods = {
1997 '__eq__': _get_eq,
1998 '__ne__': _get_ne,
1999 '__iter__': _get_iter,
Lisa Roach77b3b772019-05-20 09:19:53 -07002000 '__aiter__': _get_async_iter
Michael Foord345266a2012-03-14 12:24:34 -07002001}
2002
2003
2004
2005def _set_return_value(mock, method, name):
2006 fixed = _return_values.get(name, DEFAULT)
2007 if fixed is not DEFAULT:
2008 method.return_value = fixed
2009 return
2010
Miss Islington (bot)cc8edfb2019-09-16 09:52:45 -07002011 return_calculator = _calculate_return_value.get(name)
2012 if return_calculator is not None:
2013 return_value = return_calculator(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002014 method.return_value = return_value
2015 return
2016
2017 side_effector = _side_effect_methods.get(name)
2018 if side_effector is not None:
2019 method.side_effect = side_effector(mock)
2020
2021
2022
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002023class MagicMixin(Base):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002024 def __init__(self, /, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07002025 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10002026 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07002027 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002028
2029
2030 def _mock_set_magics(self):
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002031 orig_magics = _magics | _async_method_magics
2032 these_magics = orig_magics
Michael Foord345266a2012-03-14 12:24:34 -07002033
Łukasz Langaa468db92015-04-13 23:12:42 -07002034 if getattr(self, "_mock_methods", None) is not None:
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002035 these_magics = orig_magics.intersection(self._mock_methods)
Michael Foord345266a2012-03-14 12:24:34 -07002036
2037 remove_magics = set()
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002038 remove_magics = orig_magics - these_magics
Michael Foord345266a2012-03-14 12:24:34 -07002039
2040 for entry in remove_magics:
2041 if entry in type(self).__dict__:
2042 # remove unneeded magic methods
2043 delattr(self, entry)
2044
2045 # don't overwrite existing attributes if called a second time
2046 these_magics = these_magics - set(type(self).__dict__)
2047
2048 _type = type(self)
2049 for entry in these_magics:
2050 setattr(_type, entry, MagicProxy(entry, self))
2051
2052
2053
2054class NonCallableMagicMock(MagicMixin, NonCallableMock):
2055 """A version of `MagicMock` that isn't callable."""
2056 def mock_add_spec(self, spec, spec_set=False):
2057 """Add a spec to a mock. `spec` can either be an object or a
2058 list of strings. Only attributes on the `spec` can be fetched as
2059 attributes from the mock.
2060
2061 If `spec_set` is True then only attributes on the spec can be set."""
2062 self._mock_add_spec(spec, spec_set)
2063 self._mock_set_magics()
2064
2065
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002066class AsyncMagicMixin(MagicMixin):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002067 def __init__(self, /, *args, **kw):
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002068 self._mock_set_magics() # make magic work for kwargs in init
Lisa Roach77b3b772019-05-20 09:19:53 -07002069 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002070 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002071
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002072class MagicMock(MagicMixin, Mock):
Michael Foord345266a2012-03-14 12:24:34 -07002073 """
2074 MagicMock is a subclass of Mock with default implementations
2075 of most of the magic methods. You can use MagicMock without having to
2076 configure the magic methods yourself.
2077
2078 If you use the `spec` or `spec_set` arguments then *only* magic
2079 methods that exist in the spec will be created.
2080
2081 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
2082 """
2083 def mock_add_spec(self, spec, spec_set=False):
2084 """Add a spec to a mock. `spec` can either be an object or a
2085 list of strings. Only attributes on the `spec` can be fetched as
2086 attributes from the mock.
2087
2088 If `spec_set` is True then only attributes on the spec can be set."""
2089 self._mock_add_spec(spec, spec_set)
2090 self._mock_set_magics()
2091
2092
2093
Miss Islington (bot)b76ab352019-09-29 21:02:46 -07002094class MagicProxy(Base):
Michael Foord345266a2012-03-14 12:24:34 -07002095 def __init__(self, name, parent):
2096 self.name = name
2097 self.parent = parent
2098
Michael Foord345266a2012-03-14 12:24:34 -07002099 def create_mock(self):
2100 entry = self.name
2101 parent = self.parent
2102 m = parent._get_child_mock(name=entry, _new_name=entry,
2103 _new_parent=parent)
2104 setattr(parent, entry, m)
2105 _set_return_value(parent, m, entry)
2106 return m
2107
2108 def __get__(self, obj, _type=None):
2109 return self.create_mock()
2110
2111
Lisa Roach77b3b772019-05-20 09:19:53 -07002112class AsyncMockMixin(Base):
Lisa Roach77b3b772019-05-20 09:19:53 -07002113 await_count = _delegating_property('await_count')
2114 await_args = _delegating_property('await_args')
2115 await_args_list = _delegating_property('await_args_list')
2116
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002117 def __init__(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002118 super().__init__(*args, **kwargs)
2119 # asyncio.iscoroutinefunction() checks _is_coroutine property to say if an
2120 # object is a coroutine. Without this check it looks to see if it is a
2121 # function/method, which in this case it is not (since it is an
2122 # AsyncMock).
2123 # It is set through __dict__ because when spec_set is True, this
2124 # attribute is likely undefined.
2125 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
Lisa Roach77b3b772019-05-20 09:19:53 -07002126 self.__dict__['_mock_await_count'] = 0
2127 self.__dict__['_mock_await_args'] = None
2128 self.__dict__['_mock_await_args_list'] = _CallList()
2129 code_mock = NonCallableMock(spec_set=CodeType)
2130 code_mock.co_flags = inspect.CO_COROUTINE
2131 self.__dict__['__code__'] = code_mock
2132
Lisa Roachb2744c12019-11-21 10:14:32 -08002133 async def _execute_mock_call(self, /, *args, **kwargs):
2134 # This is nearly just like super(), except for sepcial handling
2135 # of coroutines
Lisa Roach77b3b772019-05-20 09:19:53 -07002136
2137 _call = self.call_args
Lisa Roachb2744c12019-11-21 10:14:32 -08002138 self.await_count += 1
2139 self.await_args = _call
2140 self.await_args_list.append(_call)
Lisa Roach77b3b772019-05-20 09:19:53 -07002141
Lisa Roachb2744c12019-11-21 10:14:32 -08002142 effect = self.side_effect
2143 if effect is not None:
2144 if _is_exception(effect):
2145 raise effect
2146 elif not _callable(effect):
2147 try:
2148 result = next(effect)
2149 except StopIteration:
2150 # It is impossible to propogate a StopIteration
2151 # through coroutines because of PEP 479
2152 raise StopAsyncIteration
2153 if _is_exception(result):
2154 raise result
2155 elif asyncio.iscoroutinefunction(effect):
2156 result = await effect(*args, **kwargs)
2157 else:
2158 result = effect(*args, **kwargs)
Lisa Roach77b3b772019-05-20 09:19:53 -07002159
Lisa Roachb2744c12019-11-21 10:14:32 -08002160 if result is not DEFAULT:
2161 return result
2162
2163 if self._mock_return_value is not DEFAULT:
2164 return self.return_value
2165
2166 if self._mock_wraps is not None:
2167 if asyncio.iscoroutinefunction(self._mock_wraps):
2168 return await self._mock_wraps(*args, **kwargs)
2169 return self._mock_wraps(*args, **kwargs)
2170
2171 return self.return_value
Lisa Roach77b3b772019-05-20 09:19:53 -07002172
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002173 def assert_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002174 """
2175 Assert that the mock was awaited at least once.
2176 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002177 if self.await_count == 0:
2178 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2179 raise AssertionError(msg)
2180
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002181 def assert_awaited_once(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002182 """
2183 Assert that the mock was awaited exactly once.
2184 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002185 if not self.await_count == 1:
2186 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2187 f" Awaited {self.await_count} times.")
2188 raise AssertionError(msg)
2189
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002190 def assert_awaited_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002191 """
2192 Assert that the last await was with the specified arguments.
2193 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002194 if self.await_args is None:
2195 expected = self._format_mock_call_signature(args, kwargs)
2196 raise AssertionError(f'Expected await: {expected}\nNot awaited')
2197
2198 def _error_message():
Xtreak0ae022c2019-05-29 12:32:26 +05302199 msg = self._format_mock_failure_message(args, kwargs, action='await')
Lisa Roach77b3b772019-05-20 09:19:53 -07002200 return msg
2201
2202 expected = self._call_matcher((args, kwargs))
2203 actual = self._call_matcher(self.await_args)
2204 if expected != actual:
2205 cause = expected if isinstance(expected, Exception) else None
2206 raise AssertionError(_error_message()) from cause
2207
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002208 def assert_awaited_once_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002209 """
2210 Assert that the mock was awaited exactly once and with the specified
2211 arguments.
2212 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002213 if not self.await_count == 1:
2214 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2215 f" Awaited {self.await_count} times.")
2216 raise AssertionError(msg)
2217 return self.assert_awaited_with(*args, **kwargs)
2218
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002219 def assert_any_await(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002220 """
2221 Assert the mock has ever been awaited with the specified arguments.
2222 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002223 expected = self._call_matcher((args, kwargs))
2224 actual = [self._call_matcher(c) for c in self.await_args_list]
2225 if expected not in actual:
2226 cause = expected if isinstance(expected, Exception) else None
2227 expected_string = self._format_mock_call_signature(args, kwargs)
2228 raise AssertionError(
2229 '%s await not found' % expected_string
2230 ) from cause
2231
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002232 def assert_has_awaits(self, calls, any_order=False):
Lisa Roach77b3b772019-05-20 09:19:53 -07002233 """
2234 Assert the mock has been awaited with the specified calls.
2235 The :attr:`await_args_list` list is checked for the awaits.
2236
2237 If `any_order` is False (the default) then the awaits must be
2238 sequential. There can be extra calls before or after the
2239 specified awaits.
2240
2241 If `any_order` is True then the awaits can be in any order, but
2242 they must all appear in :attr:`await_args_list`.
2243 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002244 expected = [self._call_matcher(c) for c in calls]
Miss Islington (bot)1a17a052019-09-24 17:29:17 -07002245 cause = next((e for e in expected if isinstance(e, Exception)), None)
Lisa Roach77b3b772019-05-20 09:19:53 -07002246 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2247 if not any_order:
2248 if expected not in all_awaits:
Miss Islington (bot)1a17a052019-09-24 17:29:17 -07002249 if cause is None:
2250 problem = 'Awaits not found.'
2251 else:
2252 problem = ('Error processing expected awaits.\n'
2253 'Errors: {}').format(
2254 [e if isinstance(e, Exception) else None
2255 for e in expected])
Lisa Roach77b3b772019-05-20 09:19:53 -07002256 raise AssertionError(
Miss Islington (bot)1a17a052019-09-24 17:29:17 -07002257 f'{problem}\n'
2258 f'Expected: {_CallList(calls)}\n'
Lisa Roach77b3b772019-05-20 09:19:53 -07002259 f'Actual: {self.await_args_list}'
2260 ) from cause
2261 return
2262
2263 all_awaits = list(all_awaits)
2264
2265 not_found = []
2266 for kall in expected:
2267 try:
2268 all_awaits.remove(kall)
2269 except ValueError:
2270 not_found.append(kall)
2271 if not_found:
2272 raise AssertionError(
2273 '%r not all found in await list' % (tuple(not_found),)
2274 ) from cause
2275
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002276 def assert_not_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002277 """
2278 Assert that the mock was never awaited.
2279 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002280 if self.await_count != 0:
Xtreakff6b2e62019-05-27 18:26:23 +05302281 msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
Lisa Roach77b3b772019-05-20 09:19:53 -07002282 f" Awaited {self.await_count} times.")
2283 raise AssertionError(msg)
2284
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002285 def reset_mock(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002286 """
2287 See :func:`.Mock.reset_mock()`
2288 """
2289 super().reset_mock(*args, **kwargs)
2290 self.await_count = 0
2291 self.await_args = None
2292 self.await_args_list = _CallList()
2293
2294
2295class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2296 """
2297 Enhance :class:`Mock` with features allowing to mock
2298 an async function.
2299
2300 The :class:`AsyncMock` object will behave so the object is
2301 recognized as an async function, and the result of a call is an awaitable:
2302
2303 >>> mock = AsyncMock()
2304 >>> asyncio.iscoroutinefunction(mock)
2305 True
2306 >>> inspect.isawaitable(mock())
2307 True
2308
2309
2310 The result of ``mock()`` is an async function which will have the outcome
2311 of ``side_effect`` or ``return_value``:
2312
2313 - if ``side_effect`` is a function, the async function will return the
2314 result of that function,
2315 - if ``side_effect`` is an exception, the async function will raise the
2316 exception,
2317 - if ``side_effect`` is an iterable, the async function will return the
2318 next value of the iterable, however, if the sequence of result is
2319 exhausted, ``StopIteration`` is raised immediately,
2320 - if ``side_effect`` is not defined, the async function will return the
2321 value defined by ``return_value``, hence, by default, the async function
2322 returns a new :class:`AsyncMock` object.
2323
2324 If the outcome of ``side_effect`` or ``return_value`` is an async function,
2325 the mock async function obtained when the mock object is called will be this
2326 async function itself (and not an async function returning an async
2327 function).
2328
2329 The test author can also specify a wrapped object with ``wraps``. In this
2330 case, the :class:`Mock` object behavior is the same as with an
2331 :class:`.Mock` object: the wrapped object may have methods
2332 defined as async function functions.
2333
Xtreake7cb23b2019-05-21 14:17:17 +05302334 Based on Martin Richard's asynctest project.
Lisa Roach77b3b772019-05-20 09:19:53 -07002335 """
2336
Michael Foord345266a2012-03-14 12:24:34 -07002337
2338class _ANY(object):
2339 "A helper object that compares equal to everything."
2340
2341 def __eq__(self, other):
2342 return True
2343
2344 def __ne__(self, other):
2345 return False
2346
2347 def __repr__(self):
2348 return '<ANY>'
2349
2350ANY = _ANY()
2351
2352
2353
2354def _format_call_signature(name, args, kwargs):
2355 message = '%s(%%s)' % name
2356 formatted_args = ''
2357 args_string = ', '.join([repr(arg) for arg in args])
2358 kwargs_string = ', '.join([
Miss Islington (bot)bee8bfe2019-09-09 04:42:43 -07002359 '%s=%r' % (key, value) for key, value in kwargs.items()
Michael Foord345266a2012-03-14 12:24:34 -07002360 ])
2361 if args_string:
2362 formatted_args = args_string
2363 if kwargs_string:
2364 if formatted_args:
2365 formatted_args += ', '
2366 formatted_args += kwargs_string
2367
2368 return message % formatted_args
2369
2370
2371
2372class _Call(tuple):
2373 """
2374 A tuple for holding the results of a call to a mock, either in the form
2375 `(args, kwargs)` or `(name, args, kwargs)`.
2376
2377 If args or kwargs are empty then a call tuple will compare equal to
2378 a tuple without those values. This makes comparisons less verbose::
2379
2380 _Call(('name', (), {})) == ('name',)
2381 _Call(('name', (1,), {})) == ('name', (1,))
2382 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2383
2384 The `_Call` object provides a useful shortcut for comparing with call::
2385
2386 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2387 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2388
2389 If the _Call has no name then it will match any name.
2390 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002391 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002392 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002393 args = ()
2394 kwargs = {}
2395 _len = len(value)
2396 if _len == 3:
2397 name, args, kwargs = value
2398 elif _len == 2:
2399 first, second = value
2400 if isinstance(first, str):
2401 name = first
2402 if isinstance(second, tuple):
2403 args = second
2404 else:
2405 kwargs = second
2406 else:
2407 args, kwargs = first, second
2408 elif _len == 1:
2409 value, = value
2410 if isinstance(value, str):
2411 name = value
2412 elif isinstance(value, tuple):
2413 args = value
2414 else:
2415 kwargs = value
2416
2417 if two:
2418 return tuple.__new__(cls, (args, kwargs))
2419
2420 return tuple.__new__(cls, (name, args, kwargs))
2421
2422
2423 def __init__(self, value=(), name=None, parent=None, two=False,
2424 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002425 self._mock_name = name
2426 self._mock_parent = parent
2427 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002428
2429
2430 def __eq__(self, other):
2431 if other is ANY:
2432 return True
2433 try:
2434 len_other = len(other)
2435 except TypeError:
2436 return False
2437
2438 self_name = ''
2439 if len(self) == 2:
2440 self_args, self_kwargs = self
2441 else:
2442 self_name, self_args, self_kwargs = self
2443
Andrew Dunaie63e6172018-12-04 11:08:45 +02002444 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2445 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002446 return False
2447
Michael Foord345266a2012-03-14 12:24:34 -07002448 other_name = ''
2449 if len_other == 0:
2450 other_args, other_kwargs = (), {}
2451 elif len_other == 3:
2452 other_name, other_args, other_kwargs = other
2453 elif len_other == 1:
2454 value, = other
2455 if isinstance(value, tuple):
2456 other_args = value
2457 other_kwargs = {}
2458 elif isinstance(value, str):
2459 other_name = value
2460 other_args, other_kwargs = (), {}
2461 else:
2462 other_args = ()
2463 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002464 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002465 # could be (name, args) or (name, kwargs) or (args, kwargs)
2466 first, second = other
2467 if isinstance(first, str):
2468 other_name = first
2469 if isinstance(second, tuple):
2470 other_args, other_kwargs = second, {}
2471 else:
2472 other_args, other_kwargs = (), second
2473 else:
2474 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002475 else:
2476 return False
Michael Foord345266a2012-03-14 12:24:34 -07002477
2478 if self_name and other_name != self_name:
2479 return False
2480
2481 # this order is important for ANY to work!
2482 return (other_args, other_kwargs) == (self_args, self_kwargs)
2483
2484
Berker Peksagce913872016-03-28 00:30:02 +03002485 __ne__ = object.__ne__
2486
2487
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002488 def __call__(self, /, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002489 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002490 return _Call(('', args, kwargs), name='()')
2491
Andrew Dunaie63e6172018-12-04 11:08:45 +02002492 name = self._mock_name + '()'
2493 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002494
2495
2496 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002497 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002498 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002499 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002500 return _Call(name=name, parent=self, from_kall=False)
2501
2502
Miss Islington (bot)db0d8a52019-09-12 03:52:49 -07002503 def __getattribute__(self, attr):
2504 if attr in tuple.__dict__:
2505 raise AttributeError
2506 return tuple.__getattribute__(self, attr)
2507
2508
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002509 def count(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302510 return self.__getattr__('count')(*args, **kwargs)
2511
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002512 def index(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302513 return self.__getattr__('index')(*args, **kwargs)
2514
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302515 def _get_call_arguments(self):
2516 if len(self) == 2:
2517 args, kwargs = self
2518 else:
2519 name, args, kwargs = self
2520
2521 return args, kwargs
2522
2523 @property
2524 def args(self):
2525 return self._get_call_arguments()[0]
2526
2527 @property
2528 def kwargs(self):
2529 return self._get_call_arguments()[1]
2530
Michael Foord345266a2012-03-14 12:24:34 -07002531 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002532 if not self._mock_from_kall:
2533 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002534 if name.startswith('()'):
2535 name = 'call%s' % name
2536 return name
2537
2538 if len(self) == 2:
2539 name = 'call'
2540 args, kwargs = self
2541 else:
2542 name, args, kwargs = self
2543 if not name:
2544 name = 'call'
2545 elif not name.startswith('()'):
2546 name = 'call.%s' % name
2547 else:
2548 name = 'call%s' % name
2549 return _format_call_signature(name, args, kwargs)
2550
2551
2552 def call_list(self):
2553 """For a call object that represents multiple calls, `call_list`
2554 returns a list of all the intermediate calls as well as the
2555 final call."""
2556 vals = []
2557 thing = self
2558 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002559 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002560 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002561 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002562 return _CallList(reversed(vals))
2563
2564
2565call = _Call(from_kall=False)
2566
2567
Michael Foord345266a2012-03-14 12:24:34 -07002568def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2569 _name=None, **kwargs):
2570 """Create a mock object using another object as a spec. Attributes on the
2571 mock will use the corresponding attribute on the `spec` object as their
2572 spec.
2573
2574 Functions or methods being mocked will have their arguments checked
2575 to check that they are called with the correct signature.
2576
2577 If `spec_set` is True then attempting to set attributes that don't exist
2578 on the spec object will raise an `AttributeError`.
2579
2580 If a class is used as a spec then the return value of the mock (the
2581 instance of the class) will have the same spec. You can use a class as the
2582 spec for an instance object by passing `instance=True`. The returned mock
2583 will only be callable if instances of the mock are callable.
2584
2585 `create_autospec` also takes arbitrary keyword arguments that are passed to
2586 the constructor of the created mock."""
2587 if _is_list(spec):
2588 # can't pass a list instance to the mock constructor as it will be
2589 # interpreted as a list of strings
2590 spec = type(spec)
2591
2592 is_type = isinstance(spec, type)
Xtreakff6b2e62019-05-27 18:26:23 +05302593 is_async_func = _is_async_func(spec)
Michael Foord345266a2012-03-14 12:24:34 -07002594 _kwargs = {'spec': spec}
2595 if spec_set:
2596 _kwargs = {'spec_set': spec}
2597 elif spec is None:
2598 # None we mock with a normal mock without a spec
2599 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002600 if _kwargs and instance:
2601 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002602
2603 _kwargs.update(kwargs)
2604
2605 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002606 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002607 # descriptors don't have a spec
2608 # because we don't know what type they return
2609 _kwargs = {}
Lisa Roach77b3b772019-05-20 09:19:53 -07002610 elif is_async_func:
2611 if instance:
2612 raise RuntimeError("Instance can not be True when create_autospec "
2613 "is mocking an async function")
2614 Klass = AsyncMock
Michael Foord345266a2012-03-14 12:24:34 -07002615 elif not _callable(spec):
2616 Klass = NonCallableMagicMock
2617 elif is_type and instance and not _instance_callable(spec):
2618 Klass = NonCallableMagicMock
2619
Kushal Das484f8a82014-04-16 01:05:50 +05302620 _name = _kwargs.pop('name', _name)
2621
Michael Foord345266a2012-03-14 12:24:34 -07002622 _new_name = _name
2623 if _parent is None:
2624 # for a top level object no _new_name should be set
2625 _new_name = ''
2626
2627 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2628 name=_name, **_kwargs)
2629
2630 if isinstance(spec, FunctionTypes):
2631 # should only happen at the top level because we don't
2632 # recurse for functions
2633 mock = _set_signature(mock, spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07002634 if is_async_func:
Xtreakff6b2e62019-05-27 18:26:23 +05302635 _setup_async_mock(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002636 else:
2637 _check_signature(spec, mock, is_type, instance)
2638
2639 if _parent is not None and not instance:
2640 _parent._mock_children[_name] = mock
2641
2642 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002643 mock.return_value = create_autospec(spec, spec_set, instance=True,
2644 _name='()', _parent=mock)
2645
2646 for entry in dir(spec):
2647 if _is_magic(entry):
2648 # MagicMock already does the useful magic methods for us
2649 continue
2650
Michael Foord345266a2012-03-14 12:24:34 -07002651 # XXXX do we need a better way of getting attributes without
2652 # triggering code execution (?) Probably not - we need the actual
2653 # object to mock it so we would rather trigger a property than mock
2654 # the property descriptor. Likewise we want to mock out dynamically
2655 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002656 # XXXX what about attributes that raise exceptions other than
2657 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002658 # we could be resilient against it, or catch and propagate the
2659 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002660 try:
2661 original = getattr(spec, entry)
2662 except AttributeError:
2663 continue
Michael Foord345266a2012-03-14 12:24:34 -07002664
2665 kwargs = {'spec': original}
2666 if spec_set:
2667 kwargs = {'spec_set': original}
2668
2669 if not isinstance(original, FunctionTypes):
2670 new = _SpecState(original, spec_set, mock, entry, instance)
2671 mock._mock_children[entry] = new
2672 else:
2673 parent = mock
2674 if isinstance(spec, FunctionTypes):
2675 parent = mock.mock
2676
Michael Foord345266a2012-03-14 12:24:34 -07002677 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002678 kwargs['_eat_self'] = skipfirst
Lisa Roach77b3b772019-05-20 09:19:53 -07002679 if asyncio.iscoroutinefunction(original):
2680 child_klass = AsyncMock
2681 else:
2682 child_klass = MagicMock
2683 new = child_klass(parent=parent, name=entry, _new_name=entry,
2684 _new_parent=parent,
2685 **kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002686 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002687 _check_signature(original, new, skipfirst=skipfirst)
2688
2689 # so functions created with _set_signature become instance attributes,
2690 # *plus* their underlying mock exists in _mock_children of the parent
2691 # mock. Adding to _mock_children may be unnecessary where we are also
2692 # setting as an instance attribute?
2693 if isinstance(new, FunctionTypes):
2694 setattr(mock, entry, new)
2695
2696 return mock
2697
2698
2699def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002700 """
2701 Return whether we should skip the first argument on spec's `entry`
2702 attribute.
2703 """
Michael Foord345266a2012-03-14 12:24:34 -07002704 if not isinstance(spec, type):
2705 if entry in getattr(spec, '__dict__', {}):
2706 # instance attribute - shouldn't skip
2707 return False
Michael Foord345266a2012-03-14 12:24:34 -07002708 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002709
2710 for klass in spec.__mro__:
2711 result = klass.__dict__.get(entry, DEFAULT)
2712 if result is DEFAULT:
2713 continue
2714 if isinstance(result, (staticmethod, classmethod)):
2715 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002716 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2717 # Normal method => skip if looked up on type
2718 # (if looked up on instance, self is already skipped)
2719 return is_type
2720 else:
2721 return False
Michael Foord345266a2012-03-14 12:24:34 -07002722
Chris Withersadbf1782019-05-01 23:04:04 +01002723 # function is a dynamically provided attribute
Michael Foord345266a2012-03-14 12:24:34 -07002724 return is_type
2725
2726
Michael Foord345266a2012-03-14 12:24:34 -07002727class _SpecState(object):
2728
2729 def __init__(self, spec, spec_set=False, parent=None,
2730 name=None, ids=None, instance=False):
2731 self.spec = spec
2732 self.ids = ids
2733 self.spec_set = spec_set
2734 self.parent = parent
2735 self.instance = instance
2736 self.name = name
2737
2738
2739FunctionTypes = (
2740 # python function
2741 type(create_autospec),
2742 # instance method
2743 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002744)
2745
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002746MethodWrapperTypes = (
2747 type(ANY.__eq__.__get__),
2748)
2749
Michael Foord345266a2012-03-14 12:24:34 -07002750
Michael Foorda74561a2012-03-25 19:03:13 +01002751file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002752
Michael Foord04cbe0c2013-03-19 17:22:51 -07002753
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002754def _to_stream(read_data):
2755 if isinstance(read_data, bytes):
2756 return io.BytesIO(read_data)
Michael Foord04cbe0c2013-03-19 17:22:51 -07002757 else:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002758 return io.StringIO(read_data)
Michael Foord0dccf652012-03-25 19:11:50 +01002759
Robert Collins5329aaa2015-07-17 20:08:45 +12002760
Michael Foord0dccf652012-03-25 19:11:50 +01002761def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002762 """
2763 A helper function to create a mock to replace the use of `open`. It works
2764 for `open` called directly or used as a context manager.
2765
2766 The `mock` argument is the mock object to configure. If `None` (the
2767 default) then a `MagicMock` will be created for you, with the API limited
2768 to methods or attributes available on standard file handles.
2769
Xtreak71f82a22018-12-20 21:30:21 +05302770 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002771 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002772 """
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002773 _read_data = _to_stream(read_data)
2774 _state = [_read_data, None]
2775
Robert Collinsca647ef2015-07-24 03:48:20 +12002776 def _readlines_side_effect(*args, **kwargs):
2777 if handle.readlines.return_value is not None:
2778 return handle.readlines.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002779 return _state[0].readlines(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002780
2781 def _read_side_effect(*args, **kwargs):
2782 if handle.read.return_value is not None:
2783 return handle.read.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002784 return _state[0].read(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002785
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002786 def _readline_side_effect(*args, **kwargs):
Tony Flury20870232018-09-12 23:21:16 +01002787 yield from _iter_side_effect()
2788 while True:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002789 yield _state[0].readline(*args, **kwargs)
Tony Flury20870232018-09-12 23:21:16 +01002790
2791 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002792 if handle.readline.return_value is not None:
2793 while True:
2794 yield handle.readline.return_value
2795 for line in _state[0]:
2796 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002797
Damien Nadé394119a2019-05-23 12:03:25 +02002798 def _next_side_effect():
2799 if handle.readline.return_value is not None:
2800 return handle.readline.return_value
2801 return next(_state[0])
2802
Michael Foorda74561a2012-03-25 19:03:13 +01002803 global file_spec
2804 if file_spec is None:
2805 import _io
2806 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2807
Michael Foord345266a2012-03-14 12:24:34 -07002808 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002809 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002810
Robert Collinsca647ef2015-07-24 03:48:20 +12002811 handle = MagicMock(spec=file_spec)
2812 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002813
Robert Collinsca647ef2015-07-24 03:48:20 +12002814 handle.write.return_value = None
2815 handle.read.return_value = None
2816 handle.readline.return_value = None
2817 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002818
Robert Collinsca647ef2015-07-24 03:48:20 +12002819 handle.read.side_effect = _read_side_effect
2820 _state[1] = _readline_side_effect()
2821 handle.readline.side_effect = _state[1]
2822 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002823 handle.__iter__.side_effect = _iter_side_effect
Damien Nadé394119a2019-05-23 12:03:25 +02002824 handle.__next__.side_effect = _next_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002825
Robert Collinsca647ef2015-07-24 03:48:20 +12002826 def reset_data(*args, **kwargs):
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002827 _state[0] = _to_stream(read_data)
Robert Collinsca647ef2015-07-24 03:48:20 +12002828 if handle.readline.side_effect == _state[1]:
2829 # Only reset the side effect if the user hasn't overridden it.
2830 _state[1] = _readline_side_effect()
2831 handle.readline.side_effect = _state[1]
2832 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002833
Robert Collinsca647ef2015-07-24 03:48:20 +12002834 mock.side_effect = reset_data
2835 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002836 return mock
2837
2838
2839class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002840 """
2841 A mock intended to be used as a property, or other descriptor, on a class.
2842 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2843 a return value when it is fetched.
2844
2845 Fetching a `PropertyMock` instance from an object calls the mock, with
2846 no args. Setting it calls the mock with the value being set.
2847 """
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002848 def _get_child_mock(self, /, **kwargs):
Michael Foordc2870622012-04-13 16:57:22 +01002849 return MagicMock(**kwargs)
2850
Miss Islington (bot)c71ae1a2019-08-29 02:02:51 -07002851 def __get__(self, obj, obj_type=None):
Michael Foord345266a2012-03-14 12:24:34 -07002852 return self()
2853 def __set__(self, obj, val):
2854 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002855
2856
2857def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002858 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002859
2860 Given an input Mock, seals it to ensure no further mocks will be generated
2861 when accessing an attribute that was not already defined.
2862
Mario Corchero96200eb2018-10-19 22:57:37 +01002863 The operation recursively seals the mock passed in, meaning that
2864 the mock itself, any mocks generated by accessing one of its attributes,
2865 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002866 """
2867 mock._mock_sealed = True
2868 for attr in dir(mock):
2869 try:
2870 m = getattr(mock, attr)
2871 except AttributeError:
2872 continue
2873 if not isinstance(m, NonCallableMock):
2874 continue
2875 if m._mock_new_parent is mock:
2876 seal(m)
Lisa Roach77b3b772019-05-20 09:19:53 -07002877
2878
Lisa Roach77b3b772019-05-20 09:19:53 -07002879class _AsyncIterator:
2880 """
2881 Wraps an iterator in an asynchronous iterator.
2882 """
2883 def __init__(self, iterator):
2884 self.iterator = iterator
2885 code_mock = NonCallableMock(spec_set=CodeType)
2886 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
2887 self.__dict__['__code__'] = code_mock
2888
2889 def __aiter__(self):
2890 return self
2891
2892 async def __anext__(self):
2893 try:
2894 return next(self.iterator)
2895 except StopIteration:
2896 pass
2897 raise StopAsyncIteration