blob: 89312f18c96746252ca606ed36dd01985c18a341 [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):
49 if getattr(obj, '__code__', None):
50 return asyncio.iscoroutinefunction(obj) or inspect.isawaitable(obj)
51 else:
52 return False
53
54
Xtreakff6b2e62019-05-27 18:26:23 +053055def _is_async_func(func):
56 if getattr(func, '__code__', None):
57 return asyncio.iscoroutinefunction(func)
58 else:
59 return False
60
61
Michael Foord345266a2012-03-14 12:24:34 -070062def _is_instance_mock(obj):
63 # can't use isinstance on Mock objects because they override __class__
64 # The base class for all mocks is NonCallableMock
65 return issubclass(type(obj), NonCallableMock)
66
67
68def _is_exception(obj):
69 return (
Chris Withers49e27f02019-05-01 08:48:44 +010070 isinstance(obj, BaseException) or
71 isinstance(obj, type) and issubclass(obj, BaseException)
Michael Foord345266a2012-03-14 12:24:34 -070072 )
73
74
Xtreak7397cda2019-07-22 13:08:22 +053075def _extract_mock(obj):
76 # Autospecced functions will return a FunctionType with "mock" attribute
77 # which is the actual mock object that needs to be used.
78 if isinstance(obj, FunctionTypes) and hasattr(obj, 'mock'):
79 return obj.mock
80 else:
81 return obj
82
83
Antoine Pitrou5c64df72013-02-03 00:23:58 +010084def _get_signature_object(func, as_instance, eat_self):
85 """
86 Given an arbitrary, possibly callable object, try to create a suitable
87 signature object.
88 Return a (reduced func, signature) tuple, or None.
89 """
90 if isinstance(func, type) and not as_instance:
91 # If it's a type and should be modelled as a type, use __init__.
Chris Withersadbf1782019-05-01 23:04:04 +010092 func = func.__init__
Antoine Pitrou5c64df72013-02-03 00:23:58 +010093 # Skip the `self` argument in __init__
94 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070095 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010096 # If we really want to model an instance of the passed type,
97 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070098 try:
99 func = func.__call__
100 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100101 return None
102 if eat_self:
103 sig_func = partial(func, None)
104 else:
105 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -0700106 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100107 return func, inspect.signature(sig_func)
108 except ValueError:
109 # Certain callable types are not supported by inspect.signature()
110 return None
Michael Foord345266a2012-03-14 12:24:34 -0700111
112
113def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100114 sig = _get_signature_object(func, instance, skipfirst)
115 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -0700116 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100117 func, sig = sig
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300118 def checksig(self, /, *args, **kwargs):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100119 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700120 _copy_func_details(func, checksig)
121 type(mock)._mock_check_sig = checksig
Xtreakf7fa62e2018-12-12 13:24:54 +0530122 type(mock).__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700123
124
125def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700126 # we explicitly don't copy func.__dict__ into this copy as it would
127 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300128 for attribute in (
129 '__name__', '__doc__', '__text_signature__',
130 '__module__', '__defaults__', '__kwdefaults__',
131 ):
132 try:
133 setattr(funcopy, attribute, getattr(func, attribute))
134 except AttributeError:
135 pass
Michael Foord345266a2012-03-14 12:24:34 -0700136
137
138def _callable(obj):
139 if isinstance(obj, type):
140 return True
Xtreak9b218562019-04-22 08:00:23 +0530141 if isinstance(obj, (staticmethod, classmethod, MethodType)):
142 return _callable(obj.__func__)
Michael Foord345266a2012-03-14 12:24:34 -0700143 if getattr(obj, '__call__', None) is not None:
144 return True
145 return False
146
147
148def _is_list(obj):
149 # checks for list or tuples
150 # XXXX badly named!
151 return type(obj) in (list, tuple)
152
153
154def _instance_callable(obj):
155 """Given an object, return True if the object is callable.
156 For classes, return True if instances would be callable."""
157 if not isinstance(obj, type):
158 # already an instance
159 return getattr(obj, '__call__', None) is not None
160
Michael Foorda74b3aa2012-03-14 14:40:22 -0700161 # *could* be broken by a class overriding __mro__ or __dict__ via
162 # a metaclass
163 for base in (obj,) + obj.__mro__:
164 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700165 return True
166 return False
167
168
169def _set_signature(mock, original, instance=False):
170 # creates a function with signature (*args, **kwargs) that delegates to a
171 # mock. It still does signature checking by calling a lambda with the same
172 # signature as the original.
Michael Foord345266a2012-03-14 12:24:34 -0700173
174 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100175 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700176 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700177 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100178 func, sig = result
179 def checksig(*args, **kwargs):
180 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700181 _copy_func_details(func, checksig)
182
183 name = original.__name__
184 if not name.isidentifier():
185 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100186 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700187 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100188 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700189 return mock(*args, **kwargs)""" % name
190 exec (src, context)
191 funcopy = context[name]
Xtreakf7fa62e2018-12-12 13:24:54 +0530192 _setup_func(funcopy, mock, sig)
Michael Foord345266a2012-03-14 12:24:34 -0700193 return funcopy
194
195
Xtreakf7fa62e2018-12-12 13:24:54 +0530196def _setup_func(funcopy, mock, sig):
Michael Foord345266a2012-03-14 12:24:34 -0700197 funcopy.mock = mock
198
Michael Foord345266a2012-03-14 12:24:34 -0700199 def assert_called_with(*args, **kwargs):
200 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700201 def assert_called(*args, **kwargs):
202 return mock.assert_called(*args, **kwargs)
203 def assert_not_called(*args, **kwargs):
204 return mock.assert_not_called(*args, **kwargs)
205 def assert_called_once(*args, **kwargs):
206 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700207 def assert_called_once_with(*args, **kwargs):
208 return mock.assert_called_once_with(*args, **kwargs)
209 def assert_has_calls(*args, **kwargs):
210 return mock.assert_has_calls(*args, **kwargs)
211 def assert_any_call(*args, **kwargs):
212 return mock.assert_any_call(*args, **kwargs)
213 def reset_mock():
214 funcopy.method_calls = _CallList()
215 funcopy.mock_calls = _CallList()
216 mock.reset_mock()
217 ret = funcopy.return_value
218 if _is_instance_mock(ret) and not ret is mock:
219 ret.reset_mock()
220
221 funcopy.called = False
222 funcopy.call_count = 0
223 funcopy.call_args = None
224 funcopy.call_args_list = _CallList()
225 funcopy.method_calls = _CallList()
226 funcopy.mock_calls = _CallList()
227
228 funcopy.return_value = mock.return_value
229 funcopy.side_effect = mock.side_effect
230 funcopy._mock_children = mock._mock_children
231
232 funcopy.assert_called_with = assert_called_with
233 funcopy.assert_called_once_with = assert_called_once_with
234 funcopy.assert_has_calls = assert_has_calls
235 funcopy.assert_any_call = assert_any_call
236 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700237 funcopy.assert_called = assert_called
238 funcopy.assert_not_called = assert_not_called
239 funcopy.assert_called_once = assert_called_once
Xtreakf7fa62e2018-12-12 13:24:54 +0530240 funcopy.__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700241
242 mock._mock_delegate = funcopy
243
244
Xtreakff6b2e62019-05-27 18:26:23 +0530245def _setup_async_mock(mock):
246 mock._is_coroutine = asyncio.coroutines._is_coroutine
247 mock.await_count = 0
248 mock.await_args = None
249 mock.await_args_list = _CallList()
250 mock.awaited = _AwaitEvent(mock)
251
252 # Mock is not configured yet so the attributes are set
253 # to a function and then the corresponding mock helper function
254 # is called when the helper is accessed similar to _setup_func.
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300255 def wrapper(attr, /, *args, **kwargs):
Xtreakff6b2e62019-05-27 18:26:23 +0530256 return getattr(mock.mock, attr)(*args, **kwargs)
257
258 for attribute in ('assert_awaited',
259 'assert_awaited_once',
260 'assert_awaited_with',
261 'assert_awaited_once_with',
262 'assert_any_await',
263 'assert_has_awaits',
264 'assert_not_awaited'):
265
266 # setattr(mock, attribute, wrapper) causes late binding
267 # hence attribute will always be the last value in the loop
268 # Use partial(wrapper, attribute) to ensure the attribute is bound
269 # correctly.
270 setattr(mock, attribute, partial(wrapper, attribute))
271
272
Michael Foord345266a2012-03-14 12:24:34 -0700273def _is_magic(name):
274 return '__%s__' % name[2:-2] == name
275
276
277class _SentinelObject(object):
278 "A unique, named, sentinel object."
279 def __init__(self, name):
280 self.name = name
281
282 def __repr__(self):
283 return 'sentinel.%s' % self.name
284
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200285 def __reduce__(self):
286 return 'sentinel.%s' % self.name
287
Michael Foord345266a2012-03-14 12:24:34 -0700288
289class _Sentinel(object):
290 """Access attributes to return a named object, usable as a sentinel."""
291 def __init__(self):
292 self._sentinels = {}
293
294 def __getattr__(self, name):
295 if name == '__bases__':
296 # Without this help(unittest.mock) raises an exception
297 raise AttributeError
298 return self._sentinels.setdefault(name, _SentinelObject(name))
299
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200300 def __reduce__(self):
301 return 'sentinel'
302
Michael Foord345266a2012-03-14 12:24:34 -0700303
304sentinel = _Sentinel()
305
306DEFAULT = sentinel.DEFAULT
307_missing = sentinel.MISSING
308_deleted = sentinel.DELETED
309
310
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200311_allowed_names = {
312 'return_value', '_mock_return_value', 'side_effect',
313 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
314 '_mock_name', '_mock_new_name'
315}
Michael Foord345266a2012-03-14 12:24:34 -0700316
317
318def _delegating_property(name):
319 _allowed_names.add(name)
320 _the_name = '_mock_' + name
321 def _get(self, name=name, _the_name=_the_name):
322 sig = self._mock_delegate
323 if sig is None:
324 return getattr(self, _the_name)
325 return getattr(sig, name)
326 def _set(self, value, name=name, _the_name=_the_name):
327 sig = self._mock_delegate
328 if sig is None:
329 self.__dict__[_the_name] = value
330 else:
331 setattr(sig, name, value)
332
333 return property(_get, _set)
334
335
336
337class _CallList(list):
338
339 def __contains__(self, value):
340 if not isinstance(value, list):
341 return list.__contains__(self, value)
342 len_value = len(value)
343 len_self = len(self)
344 if len_value > len_self:
345 return False
346
347 for i in range(0, len_self - len_value + 1):
348 sub_list = self[i:i+len_value]
349 if sub_list == value:
350 return True
351 return False
352
353 def __repr__(self):
354 return pprint.pformat(list(self))
355
356
357def _check_and_set_parent(parent, value, name, new_name):
Xtreak7397cda2019-07-22 13:08:22 +0530358 value = _extract_mock(value)
Xtreak9c3f2842019-02-26 03:16:34 +0530359
Michael Foord345266a2012-03-14 12:24:34 -0700360 if not _is_instance_mock(value):
361 return False
362 if ((value._mock_name or value._mock_new_name) or
363 (value._mock_parent is not None) or
364 (value._mock_new_parent is not None)):
365 return False
366
367 _parent = parent
368 while _parent is not None:
369 # setting a mock (value) as a child or return value of itself
370 # should not modify the mock
371 if _parent is value:
372 return False
373 _parent = _parent._mock_new_parent
374
375 if new_name:
376 value._mock_new_parent = parent
377 value._mock_new_name = new_name
378 if name:
379 value._mock_parent = parent
380 value._mock_name = name
381 return True
382
Michael Foord01bafdc2014-04-14 16:09:42 -0400383# Internal class to identify if we wrapped an iterator object or not.
384class _MockIter(object):
385 def __init__(self, obj):
386 self.obj = iter(obj)
Michael Foord01bafdc2014-04-14 16:09:42 -0400387 def __next__(self):
388 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700389
390class Base(object):
391 _mock_return_value = DEFAULT
392 _mock_side_effect = None
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300393 def __init__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700394 pass
395
396
397
398class NonCallableMock(Base):
399 """A non-callable version of `Mock`"""
400
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300401 def __new__(cls, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700402 # every instance has its own class
403 # so we can create magic methods on the
404 # class without stomping on other mocks
Lisa Roach77b3b772019-05-20 09:19:53 -0700405 bases = (cls,)
406 if not issubclass(cls, AsyncMock):
407 # Check if spec is an async object or function
408 sig = inspect.signature(NonCallableMock.__init__)
409 bound_args = sig.bind_partial(cls, *args, **kw).arguments
410 spec_arg = [
411 arg for arg in bound_args.keys()
412 if arg.startswith('spec')
413 ]
414 if spec_arg:
415 # what if spec_set is different than spec?
416 if _is_async_obj(bound_args[spec_arg[0]]):
417 bases = (AsyncMockMixin, cls,)
418 new = type(cls.__name__, bases, {'__doc__': cls.__doc__})
Michael Foord345266a2012-03-14 12:24:34 -0700419 instance = object.__new__(new)
420 return instance
421
422
423 def __init__(
424 self, spec=None, wraps=None, name=None, spec_set=None,
425 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530426 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700427 ):
428 if _new_parent is None:
429 _new_parent = parent
430
431 __dict__ = self.__dict__
432 __dict__['_mock_parent'] = parent
433 __dict__['_mock_name'] = name
434 __dict__['_mock_new_name'] = _new_name
435 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100436 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700437
438 if spec_set is not None:
439 spec = spec_set
440 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100441 if _eat_self is None:
442 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700443
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100444 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700445
446 __dict__['_mock_children'] = {}
447 __dict__['_mock_wraps'] = wraps
448 __dict__['_mock_delegate'] = None
449
450 __dict__['_mock_called'] = False
451 __dict__['_mock_call_args'] = None
452 __dict__['_mock_call_count'] = 0
453 __dict__['_mock_call_args_list'] = _CallList()
454 __dict__['_mock_mock_calls'] = _CallList()
455
456 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530457 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700458
459 if kwargs:
460 self.configure_mock(**kwargs)
461
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000462 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700463 spec, wraps, name, spec_set, parent,
464 _spec_state
465 )
466
467
468 def attach_mock(self, mock, attribute):
469 """
470 Attach a mock as an attribute of this one, replacing its name and
471 parent. Calls to the attached mock will be recorded in the
472 `method_calls` and `mock_calls` attributes of this one."""
Xtreak7397cda2019-07-22 13:08:22 +0530473 inner_mock = _extract_mock(mock)
474
475 inner_mock._mock_parent = None
476 inner_mock._mock_new_parent = None
477 inner_mock._mock_name = ''
478 inner_mock._mock_new_name = None
Michael Foord345266a2012-03-14 12:24:34 -0700479
480 setattr(self, attribute, mock)
481
482
483 def mock_add_spec(self, spec, spec_set=False):
484 """Add a spec to a mock. `spec` can either be an object or a
485 list of strings. Only attributes on the `spec` can be fetched as
486 attributes from the mock.
487
488 If `spec_set` is True then only attributes on the spec can be set."""
489 self._mock_add_spec(spec, spec_set)
490
491
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100492 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
493 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700494 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100495 _spec_signature = None
Lisa Roach77b3b772019-05-20 09:19:53 -0700496 _spec_asyncs = []
497
498 for attr in dir(spec):
499 if asyncio.iscoroutinefunction(getattr(spec, attr, None)):
500 _spec_asyncs.append(attr)
Michael Foord345266a2012-03-14 12:24:34 -0700501
502 if spec is not None and not _is_list(spec):
503 if isinstance(spec, type):
504 _spec_class = spec
505 else:
Chris Withersadbf1782019-05-01 23:04:04 +0100506 _spec_class = type(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100507 res = _get_signature_object(spec,
508 _spec_as_instance, _eat_self)
509 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700510
511 spec = dir(spec)
512
513 __dict__ = self.__dict__
514 __dict__['_spec_class'] = _spec_class
515 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100516 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700517 __dict__['_mock_methods'] = spec
Lisa Roach77b3b772019-05-20 09:19:53 -0700518 __dict__['_spec_asyncs'] = _spec_asyncs
Michael Foord345266a2012-03-14 12:24:34 -0700519
520 def __get_return_value(self):
521 ret = self._mock_return_value
522 if self._mock_delegate is not None:
523 ret = self._mock_delegate.return_value
524
525 if ret is DEFAULT:
526 ret = self._get_child_mock(
527 _new_parent=self, _new_name='()'
528 )
529 self.return_value = ret
530 return ret
531
532
533 def __set_return_value(self, value):
534 if self._mock_delegate is not None:
535 self._mock_delegate.return_value = value
536 else:
537 self._mock_return_value = value
538 _check_and_set_parent(self, value, None, '()')
539
540 __return_value_doc = "The value to be returned when the mock is called."
541 return_value = property(__get_return_value, __set_return_value,
542 __return_value_doc)
543
544
545 @property
546 def __class__(self):
547 if self._spec_class is None:
548 return type(self)
549 return self._spec_class
550
551 called = _delegating_property('called')
552 call_count = _delegating_property('call_count')
553 call_args = _delegating_property('call_args')
554 call_args_list = _delegating_property('call_args_list')
555 mock_calls = _delegating_property('mock_calls')
556
557
558 def __get_side_effect(self):
559 delegated = self._mock_delegate
560 if delegated is None:
561 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400562 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200563 if (sf is not None and not callable(sf)
564 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400565 sf = _MockIter(sf)
566 delegated.side_effect = sf
567 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700568
569 def __set_side_effect(self, value):
570 value = _try_iter(value)
571 delegated = self._mock_delegate
572 if delegated is None:
573 self._mock_side_effect = value
574 else:
575 delegated.side_effect = value
576
577 side_effect = property(__get_side_effect, __set_side_effect)
578
579
Kushal Das9cd39a12016-06-02 10:20:16 -0700580 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700581 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200582 if visited is None:
583 visited = []
584 if id(self) in visited:
585 return
586 visited.append(id(self))
587
Michael Foord345266a2012-03-14 12:24:34 -0700588 self.called = False
589 self.call_args = None
590 self.call_count = 0
591 self.mock_calls = _CallList()
592 self.call_args_list = _CallList()
593 self.method_calls = _CallList()
594
Kushal Das9cd39a12016-06-02 10:20:16 -0700595 if return_value:
596 self._mock_return_value = DEFAULT
597 if side_effect:
598 self._mock_side_effect = None
599
Michael Foord345266a2012-03-14 12:24:34 -0700600 for child in self._mock_children.values():
Xtreakedeca922018-12-01 15:33:54 +0530601 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100602 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200603 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700604
605 ret = self._mock_return_value
606 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200607 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700608
609
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300610 def configure_mock(self, /, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700611 """Set attributes on the mock through keyword arguments.
612
613 Attributes plus return values and side effects can be set on child
614 mocks using standard dot notation and unpacking a dictionary in the
615 method call:
616
617 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
618 >>> mock.configure_mock(**attrs)"""
619 for arg, val in sorted(kwargs.items(),
620 # we sort on the number of dots so that
621 # attributes are set before we set attributes on
622 # attributes
623 key=lambda entry: entry[0].count('.')):
624 args = arg.split('.')
625 final = args.pop()
626 obj = self
627 for entry in args:
628 obj = getattr(obj, entry)
629 setattr(obj, final, val)
630
631
632 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530633 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700634 raise AttributeError(name)
635 elif self._mock_methods is not None:
636 if name not in self._mock_methods or name in _all_magics:
637 raise AttributeError("Mock object has no attribute %r" % name)
638 elif _is_magic(name):
639 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530640 if not self._mock_unsafe:
641 if name.startswith(('assert', 'assret')):
Zackery Spytzb9b08cd2019-05-08 11:32:24 -0600642 raise AttributeError("Attributes cannot start with 'assert' "
643 "or 'assret'")
Michael Foord345266a2012-03-14 12:24:34 -0700644
645 result = self._mock_children.get(name)
646 if result is _deleted:
647 raise AttributeError(name)
648 elif result is None:
649 wraps = None
650 if self._mock_wraps is not None:
651 # XXXX should we get the attribute without triggering code
652 # execution?
653 wraps = getattr(self._mock_wraps, name)
654
655 result = self._get_child_mock(
656 parent=self, name=name, wraps=wraps, _new_name=name,
657 _new_parent=self
658 )
659 self._mock_children[name] = result
660
661 elif isinstance(result, _SpecState):
662 result = create_autospec(
663 result.spec, result.spec_set, result.instance,
664 result.parent, result.name
665 )
666 self._mock_children[name] = result
667
668 return result
669
670
Mario Corchero552be9d2017-10-17 12:35:11 +0100671 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700672 _name_list = [self._mock_new_name]
673 _parent = self._mock_new_parent
674 last = self
675
676 dot = '.'
677 if _name_list == ['()']:
678 dot = ''
Chris Withersadbf1782019-05-01 23:04:04 +0100679
Michael Foord345266a2012-03-14 12:24:34 -0700680 while _parent is not None:
681 last = _parent
682
683 _name_list.append(_parent._mock_new_name + dot)
684 dot = '.'
685 if _parent._mock_new_name == '()':
686 dot = ''
687
688 _parent = _parent._mock_new_parent
689
Michael Foord345266a2012-03-14 12:24:34 -0700690 _name_list = list(reversed(_name_list))
691 _first = last._mock_name or 'mock'
692 if len(_name_list) > 1:
693 if _name_list[1] not in ('()', '().'):
694 _first += '.'
695 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100696 return ''.join(_name_list)
697
698 def __repr__(self):
699 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700700
701 name_string = ''
702 if name not in ('mock', 'mock.'):
703 name_string = ' name=%r' % name
704
705 spec_string = ''
706 if self._spec_class is not None:
707 spec_string = ' spec=%r'
708 if self._spec_set:
709 spec_string = ' spec_set=%r'
710 spec_string = spec_string % self._spec_class.__name__
711 return "<%s%s%s id='%s'>" % (
712 type(self).__name__,
713 name_string,
714 spec_string,
715 id(self)
716 )
717
718
719 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700720 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100721 if not FILTER_DIR:
722 return object.__dir__(self)
723
Michael Foord345266a2012-03-14 12:24:34 -0700724 extras = self._mock_methods or []
725 from_type = dir(type(self))
726 from_dict = list(self.__dict__)
Mario Corchero0df635c2019-04-30 19:56:36 +0100727 from_child_mocks = [
728 m_name for m_name, m_value in self._mock_children.items()
729 if m_value is not _deleted]
Michael Foord345266a2012-03-14 12:24:34 -0700730
Michael Foord313f85f2012-03-25 18:16:07 +0100731 from_type = [e for e in from_type if not e.startswith('_')]
732 from_dict = [e for e in from_dict if not e.startswith('_') or
733 _is_magic(e)]
Mario Corchero0df635c2019-04-30 19:56:36 +0100734 return sorted(set(extras + from_type + from_dict + from_child_mocks))
Michael Foord345266a2012-03-14 12:24:34 -0700735
736
737 def __setattr__(self, name, value):
738 if name in _allowed_names:
739 # property setters go through here
740 return object.__setattr__(self, name, value)
741 elif (self._spec_set and self._mock_methods is not None and
742 name not in self._mock_methods and
743 name not in self.__dict__):
744 raise AttributeError("Mock object has no attribute '%s'" % name)
745 elif name in _unsupported_magics:
746 msg = 'Attempting to set unsupported magic method %r.' % name
747 raise AttributeError(msg)
748 elif name in _all_magics:
749 if self._mock_methods is not None and name not in self._mock_methods:
750 raise AttributeError("Mock object has no attribute '%s'" % name)
751
752 if not _is_instance_mock(value):
753 setattr(type(self), name, _get_method(name, value))
754 original = value
755 value = lambda *args, **kw: original(self, *args, **kw)
756 else:
757 # only set _new_name and not name so that mock_calls is tracked
758 # but not method calls
759 _check_and_set_parent(self, value, None, name)
760 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100761 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700762 elif name == '__class__':
763 self._spec_class = value
764 return
765 else:
766 if _check_and_set_parent(self, value, name, name):
767 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100768
769 if self._mock_sealed and not hasattr(self, name):
770 mock_name = f'{self._extract_mock_name()}.{name}'
771 raise AttributeError(f'Cannot set {mock_name}')
772
Michael Foord345266a2012-03-14 12:24:34 -0700773 return object.__setattr__(self, name, value)
774
775
776 def __delattr__(self, name):
777 if name in _all_magics and name in type(self).__dict__:
778 delattr(type(self), name)
779 if name not in self.__dict__:
780 # for magic methods that are still MagicProxy objects and
781 # not set on the instance itself
782 return
783
Michael Foord345266a2012-03-14 12:24:34 -0700784 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000785 if name in self.__dict__:
Xtreak830b43d2019-04-14 00:42:33 +0530786 _safe_super(NonCallableMock, self).__delattr__(name)
Pablo Galindo222d3032019-01-21 08:57:46 +0000787 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700788 raise AttributeError(name)
789 if obj is not _missing:
790 del self._mock_children[name]
791 self._mock_children[name] = _deleted
792
793
Michael Foord345266a2012-03-14 12:24:34 -0700794 def _format_mock_call_signature(self, args, kwargs):
795 name = self._mock_name or 'mock'
796 return _format_call_signature(name, args, kwargs)
797
798
Xtreak0ae022c2019-05-29 12:32:26 +0530799 def _format_mock_failure_message(self, args, kwargs, action='call'):
800 message = 'expected %s not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700801 expected_string = self._format_mock_call_signature(args, kwargs)
802 call_args = self.call_args
Michael Foord345266a2012-03-14 12:24:34 -0700803 actual_string = self._format_mock_call_signature(*call_args)
Xtreak0ae022c2019-05-29 12:32:26 +0530804 return message % (action, expected_string, actual_string)
Michael Foord345266a2012-03-14 12:24:34 -0700805
806
Xtreakc9612782019-08-29 11:39:01 +0530807 def _get_call_signature_from_name(self, name):
808 """
809 * If call objects are asserted against a method/function like obj.meth1
810 then there could be no name for the call object to lookup. Hence just
811 return the spec_signature of the method/function being asserted against.
812 * If the name is not empty then remove () and split by '.' to get
813 list of names to iterate through the children until a potential
814 match is found. A child mock is created only during attribute access
815 so if we get a _SpecState then no attributes of the spec were accessed
816 and can be safely exited.
817 """
818 if not name:
819 return self._spec_signature
820
821 sig = None
822 names = name.replace('()', '').split('.')
823 children = self._mock_children
824
825 for name in names:
826 child = children.get(name)
827 if child is None or isinstance(child, _SpecState):
828 break
829 else:
830 children = child._mock_children
831 sig = child._spec_signature
832
833 return sig
834
835
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100836 def _call_matcher(self, _call):
837 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000838 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100839 comparison key suitable for matching with other calls.
840 This is a best effort method which relies on the spec's signature,
841 if available, or falls back on the arguments themselves.
842 """
Xtreakc9612782019-08-29 11:39:01 +0530843
844 if isinstance(_call, tuple) and len(_call) > 2:
845 sig = self._get_call_signature_from_name(_call[0])
846 else:
847 sig = self._spec_signature
848
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100849 if sig is not None:
850 if len(_call) == 2:
851 name = ''
852 args, kwargs = _call
853 else:
854 name, args, kwargs = _call
855 try:
856 return name, sig.bind(*args, **kwargs)
857 except TypeError as e:
858 return e.with_traceback(None)
859 else:
860 return _call
861
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300862 def assert_not_called(self):
Kushal Das8af9db32014-04-17 01:36:14 +0530863 """assert that the mock was never called.
864 """
Kushal Das8af9db32014-04-17 01:36:14 +0530865 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100866 msg = ("Expected '%s' to not have been called. Called %s times.%s"
867 % (self._mock_name or 'mock',
868 self.call_count,
869 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530870 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100871
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300872 def assert_called(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100873 """assert that the mock was called at least once
874 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100875 if self.call_count == 0:
876 msg = ("Expected '%s' to have been called." %
877 self._mock_name or 'mock')
878 raise AssertionError(msg)
879
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300880 def assert_called_once(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100881 """assert that the mock was called only once.
882 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100883 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100884 msg = ("Expected '%s' to have been called once. Called %s times.%s"
885 % (self._mock_name or 'mock',
886 self.call_count,
887 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100888 raise AssertionError(msg)
889
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300890 def assert_called_with(self, /, *args, **kwargs):
Rémi Lapeyref5896a02019-08-29 08:15:53 +0200891 """assert that the last call was made with the specified arguments.
Michael Foord345266a2012-03-14 12:24:34 -0700892
893 Raises an AssertionError if the args and keyword args passed in are
894 different to the last call to the mock."""
Michael Foord345266a2012-03-14 12:24:34 -0700895 if self.call_args is None:
896 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800897 actual = 'not called.'
898 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
899 % (expected, actual))
900 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700901
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100902 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700903 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100904 return msg
905 expected = self._call_matcher((args, kwargs))
906 actual = self._call_matcher(self.call_args)
907 if expected != actual:
908 cause = expected if isinstance(expected, Exception) else None
909 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700910
911
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300912 def assert_called_once_with(self, /, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100913 """assert that the mock was called exactly once and that that call was
914 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700915 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100916 msg = ("Expected '%s' to be called once. Called %s times.%s"
917 % (self._mock_name or 'mock',
918 self.call_count,
919 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700920 raise AssertionError(msg)
921 return self.assert_called_with(*args, **kwargs)
922
923
924 def assert_has_calls(self, calls, any_order=False):
925 """assert the mock has been called with the specified calls.
926 The `mock_calls` list is checked for the calls.
927
928 If `any_order` is False (the default) then the calls must be
929 sequential. There can be extra calls before or after the
930 specified calls.
931
932 If `any_order` is True then the calls can be in any order, but
933 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100934 expected = [self._call_matcher(c) for c in calls]
935 cause = expected if isinstance(expected, Exception) else None
936 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700937 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100938 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700939 raise AssertionError(
Petter Strandmark47d94242018-10-28 21:37:10 +0100940 'Calls not found.\nExpected: %r%s'
941 % (_CallList(calls), self._calls_repr(prefix="Actual"))
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100942 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700943 return
944
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100945 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700946
947 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100948 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700949 try:
950 all_calls.remove(kall)
951 except ValueError:
952 not_found.append(kall)
953 if not_found:
954 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400955 '%r does not contain all of %r in its call list, '
956 'found %r instead' % (self._mock_name or 'mock',
957 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100958 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700959
960
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300961 def assert_any_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700962 """assert the mock has been called with the specified arguments.
963
964 The assert passes if the mock has *ever* been called, unlike
965 `assert_called_with` and `assert_called_once_with` that only pass if
966 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100967 expected = self._call_matcher((args, kwargs))
968 actual = [self._call_matcher(c) for c in self.call_args_list]
969 if expected not in actual:
970 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700971 expected_string = self._format_mock_call_signature(args, kwargs)
972 raise AssertionError(
973 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100974 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700975
976
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300977 def _get_child_mock(self, /, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700978 """Create the child mocks for attributes and return value.
979 By default child mocks will be the same type as the parent.
980 Subclasses of Mock may want to override this to customize the way
981 child mocks are made.
982
983 For non-callable mocks the callable variant will be used (rather than
984 any custom subclass)."""
Lisa Roach77b3b772019-05-20 09:19:53 -0700985 _new_name = kw.get("_new_name")
986 if _new_name in self.__dict__['_spec_asyncs']:
987 return AsyncMock(**kw)
988
Michael Foord345266a2012-03-14 12:24:34 -0700989 _type = type(self)
Lisa Roach77b3b772019-05-20 09:19:53 -0700990 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
991 klass = AsyncMock
992 if issubclass(_type, AsyncMockMixin):
993 klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -0700994 if not issubclass(_type, CallableMixin):
995 if issubclass(_type, NonCallableMagicMock):
996 klass = MagicMock
997 elif issubclass(_type, NonCallableMock) :
998 klass = Mock
999 else:
1000 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +01001001
1002 if self._mock_sealed:
1003 attribute = "." + kw["name"] if "name" in kw else "()"
1004 mock_name = self._extract_mock_name() + attribute
1005 raise AttributeError(mock_name)
1006
Michael Foord345266a2012-03-14 12:24:34 -07001007 return klass(**kw)
1008
1009
Petter Strandmark47d94242018-10-28 21:37:10 +01001010 def _calls_repr(self, prefix="Calls"):
1011 """Renders self.mock_calls as a string.
1012
1013 Example: "\nCalls: [call(1), call(2)]."
1014
1015 If self.mock_calls is empty, an empty string is returned. The
1016 output will be truncated if very long.
1017 """
1018 if not self.mock_calls:
1019 return ""
1020 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
1021
1022
Michael Foord345266a2012-03-14 12:24:34 -07001023
1024def _try_iter(obj):
1025 if obj is None:
1026 return obj
1027 if _is_exception(obj):
1028 return obj
1029 if _callable(obj):
1030 return obj
1031 try:
1032 return iter(obj)
1033 except TypeError:
1034 # XXXX backwards compatibility
1035 # but this will blow up on first call - so maybe we should fail early?
1036 return obj
1037
1038
Michael Foord345266a2012-03-14 12:24:34 -07001039class CallableMixin(Base):
1040
1041 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
1042 wraps=None, name=None, spec_set=None, parent=None,
1043 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
1044 self.__dict__['_mock_return_value'] = return_value
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001045 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -07001046 spec, wraps, name, spec_set, parent,
1047 _spec_state, _new_name, _new_parent, **kwargs
1048 )
1049
1050 self.side_effect = side_effect
1051
1052
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001053 def _mock_check_sig(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001054 # stub method that can be replaced with one with a specific signature
1055 pass
1056
1057
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001058 def __call__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001059 # can't use self in-case a function / method we are mocking uses self
1060 # in the signature
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001061 self._mock_check_sig(*args, **kwargs)
1062 return self._mock_call(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001063
1064
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001065 def _mock_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001066 self.called = True
1067 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001068
Chris Withers8ca0fa92018-12-03 21:31:37 +00001069 # handle call_args
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001070 _call = _Call((args, kwargs), two=True)
1071 self.call_args = _call
1072 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -07001073
Chris Withers8ca0fa92018-12-03 21:31:37 +00001074 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001075 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +00001076 method_call_name = self._mock_name
1077
1078 # initial stuff for mock_calls:
1079 mock_call_name = self._mock_new_name
1080 is_a_call = mock_call_name == '()'
1081 self.mock_calls.append(_Call(('', args, kwargs)))
1082
1083 # follow up the chain of mocks:
1084 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001085 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001086
Chris Withers8ca0fa92018-12-03 21:31:37 +00001087 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001088 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001089 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001090 do_method_calls = _new_parent._mock_parent is not None
1091 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001092 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001093
Chris Withers8ca0fa92018-12-03 21:31:37 +00001094 # handle mock_calls:
1095 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001096 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001097
1098 if _new_parent._mock_new_name:
1099 if is_a_call:
1100 dot = ''
1101 else:
1102 dot = '.'
1103 is_a_call = _new_parent._mock_new_name == '()'
1104 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1105
1106 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001107 _new_parent = _new_parent._mock_new_parent
1108
Michael Foord345266a2012-03-14 12:24:34 -07001109 effect = self.side_effect
1110 if effect is not None:
1111 if _is_exception(effect):
1112 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001113 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001114 result = next(effect)
1115 if _is_exception(result):
1116 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001117 else:
1118 result = effect(*args, **kwargs)
1119
1120 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001121 return result
Michael Foord345266a2012-03-14 12:24:34 -07001122
Mario Corcherof05df0a2018-12-08 11:25:02 +00001123 if self._mock_return_value is not DEFAULT:
1124 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001125
Mario Corcherof05df0a2018-12-08 11:25:02 +00001126 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001127 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001128
1129 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001130
1131
1132
1133class Mock(CallableMixin, NonCallableMock):
1134 """
1135 Create a new `Mock` object. `Mock` takes several optional arguments
1136 that specify the behaviour of the Mock object:
1137
1138 * `spec`: This can be either a list of strings or an existing object (a
1139 class or instance) that acts as the specification for the mock object. If
1140 you pass in an object then a list of strings is formed by calling dir on
1141 the object (excluding unsupported magic attributes and methods). Accessing
1142 any attribute not in this list will raise an `AttributeError`.
1143
1144 If `spec` is an object (rather than a list of strings) then
1145 `mock.__class__` returns the class of the spec object. This allows mocks
1146 to pass `isinstance` tests.
1147
1148 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1149 or get an attribute on the mock that isn't on the object passed as
1150 `spec_set` will raise an `AttributeError`.
1151
1152 * `side_effect`: A function to be called whenever the Mock is called. See
1153 the `side_effect` attribute. Useful for raising exceptions or
1154 dynamically changing return values. The function is called with the same
1155 arguments as the mock, and unless it returns `DEFAULT`, the return
1156 value of this function is used as the return value.
1157
Michael Foord2cd48732012-04-21 15:52:11 +01001158 If `side_effect` is an iterable then each call to the mock will return
1159 the next value from the iterable. If any of the members of the iterable
1160 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001161
Michael Foord345266a2012-03-14 12:24:34 -07001162 * `return_value`: The value returned when the mock is called. By default
1163 this is a new Mock (created on first access). See the
1164 `return_value` attribute.
1165
Michael Foord0682a0c2012-04-13 20:51:20 +01001166 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1167 calling the Mock will pass the call through to the wrapped object
1168 (returning the real result). Attribute access on the mock will return a
1169 Mock object that wraps the corresponding attribute of the wrapped object
1170 (so attempting to access an attribute that doesn't exist will raise an
1171 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001172
1173 If the mock has an explicit `return_value` set then calls are not passed
1174 to the wrapped object and the `return_value` is returned instead.
1175
1176 * `name`: If the mock has a name then it will be used in the repr of the
1177 mock. This can be useful for debugging. The name is propagated to child
1178 mocks.
1179
1180 Mocks can also be called with arbitrary keyword arguments. These will be
1181 used to set attributes on the mock after it is created.
1182 """
1183
1184
Michael Foord345266a2012-03-14 12:24:34 -07001185def _dot_lookup(thing, comp, import_path):
1186 try:
1187 return getattr(thing, comp)
1188 except AttributeError:
1189 __import__(import_path)
1190 return getattr(thing, comp)
1191
1192
1193def _importer(target):
1194 components = target.split('.')
1195 import_path = components.pop(0)
1196 thing = __import__(import_path)
1197
1198 for comp in components:
1199 import_path += ".%s" % comp
1200 thing = _dot_lookup(thing, comp, import_path)
1201 return thing
1202
1203
1204def _is_started(patcher):
1205 # XXXX horrible
1206 return hasattr(patcher, 'is_local')
1207
1208
1209class _patch(object):
1210
1211 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001212 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001213
1214 def __init__(
1215 self, getter, attribute, new, spec, create,
1216 spec_set, autospec, new_callable, kwargs
1217 ):
1218 if new_callable is not None:
1219 if new is not DEFAULT:
1220 raise ValueError(
1221 "Cannot use 'new' and 'new_callable' together"
1222 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001223 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001224 raise ValueError(
1225 "Cannot use 'autospec' and 'new_callable' together"
1226 )
1227
1228 self.getter = getter
1229 self.attribute = attribute
1230 self.new = new
1231 self.new_callable = new_callable
1232 self.spec = spec
1233 self.create = create
1234 self.has_local = False
1235 self.spec_set = spec_set
1236 self.autospec = autospec
1237 self.kwargs = kwargs
1238 self.additional_patchers = []
1239
1240
1241 def copy(self):
1242 patcher = _patch(
1243 self.getter, self.attribute, self.new, self.spec,
1244 self.create, self.spec_set,
1245 self.autospec, self.new_callable, self.kwargs
1246 )
1247 patcher.attribute_name = self.attribute_name
1248 patcher.additional_patchers = [
1249 p.copy() for p in self.additional_patchers
1250 ]
1251 return patcher
1252
1253
1254 def __call__(self, func):
1255 if isinstance(func, type):
1256 return self.decorate_class(func)
Xtreak436c2b02019-05-28 12:37:39 +05301257 if inspect.iscoroutinefunction(func):
1258 return self.decorate_async_callable(func)
Michael Foord345266a2012-03-14 12:24:34 -07001259 return self.decorate_callable(func)
1260
1261
1262 def decorate_class(self, klass):
1263 for attr in dir(klass):
1264 if not attr.startswith(patch.TEST_PREFIX):
1265 continue
1266
1267 attr_value = getattr(klass, attr)
1268 if not hasattr(attr_value, "__call__"):
1269 continue
1270
1271 patcher = self.copy()
1272 setattr(klass, attr, patcher(attr_value))
1273 return klass
1274
1275
Xtreak436c2b02019-05-28 12:37:39 +05301276 @contextlib.contextmanager
1277 def decoration_helper(self, patched, args, keywargs):
1278 extra_args = []
1279 entered_patchers = []
1280 patching = None
1281
1282 exc_info = tuple()
1283 try:
1284 for patching in patched.patchings:
1285 arg = patching.__enter__()
1286 entered_patchers.append(patching)
1287 if patching.attribute_name is not None:
1288 keywargs.update(arg)
1289 elif patching.new is DEFAULT:
1290 extra_args.append(arg)
1291
1292 args += tuple(extra_args)
1293 yield (args, keywargs)
1294 except:
1295 if (patching not in entered_patchers and
1296 _is_started(patching)):
1297 # the patcher may have been started, but an exception
1298 # raised whilst entering one of its additional_patchers
1299 entered_patchers.append(patching)
1300 # Pass the exception to __exit__
1301 exc_info = sys.exc_info()
1302 # re-raise the exception
1303 raise
1304 finally:
1305 for patching in reversed(entered_patchers):
1306 patching.__exit__(*exc_info)
1307
1308
Michael Foord345266a2012-03-14 12:24:34 -07001309 def decorate_callable(self, func):
Xtreak436c2b02019-05-28 12:37:39 +05301310 # NB. Keep the method in sync with decorate_async_callable()
Michael Foord345266a2012-03-14 12:24:34 -07001311 if hasattr(func, 'patchings'):
1312 func.patchings.append(self)
1313 return func
1314
1315 @wraps(func)
1316 def patched(*args, **keywargs):
Xtreak436c2b02019-05-28 12:37:39 +05301317 with self.decoration_helper(patched,
1318 args,
1319 keywargs) as (newargs, newkeywargs):
1320 return func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001321
Xtreak436c2b02019-05-28 12:37:39 +05301322 patched.patchings = [self]
1323 return patched
Michael Foord345266a2012-03-14 12:24:34 -07001324
Xtreak436c2b02019-05-28 12:37:39 +05301325
1326 def decorate_async_callable(self, func):
1327 # NB. Keep the method in sync with decorate_callable()
1328 if hasattr(func, 'patchings'):
1329 func.patchings.append(self)
1330 return func
1331
1332 @wraps(func)
1333 async def patched(*args, **keywargs):
1334 with self.decoration_helper(patched,
1335 args,
1336 keywargs) as (newargs, newkeywargs):
1337 return await func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001338
1339 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001340 return patched
1341
1342
1343 def get_original(self):
1344 target = self.getter()
1345 name = self.attribute
1346
1347 original = DEFAULT
1348 local = False
1349
1350 try:
1351 original = target.__dict__[name]
1352 except (AttributeError, KeyError):
1353 original = getattr(target, name, DEFAULT)
1354 else:
1355 local = True
1356
Michael Foordfddcfa22014-04-14 16:25:20 -04001357 if name in _builtins and isinstance(target, ModuleType):
1358 self.create = True
1359
Michael Foord345266a2012-03-14 12:24:34 -07001360 if not self.create and original is DEFAULT:
1361 raise AttributeError(
1362 "%s does not have the attribute %r" % (target, name)
1363 )
1364 return original, local
1365
1366
1367 def __enter__(self):
1368 """Perform the patch."""
1369 new, spec, spec_set = self.new, self.spec, self.spec_set
1370 autospec, kwargs = self.autospec, self.kwargs
1371 new_callable = self.new_callable
1372 self.target = self.getter()
1373
Michael Foord50a8c0e2012-03-25 18:57:58 +01001374 # normalise False to None
1375 if spec is False:
1376 spec = None
1377 if spec_set is False:
1378 spec_set = None
1379 if autospec is False:
1380 autospec = None
1381
1382 if spec is not None and autospec is not None:
1383 raise TypeError("Can't specify spec and autospec")
1384 if ((spec is not None or autospec is not None) and
1385 spec_set not in (True, None)):
1386 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1387
Michael Foord345266a2012-03-14 12:24:34 -07001388 original, local = self.get_original()
1389
Michael Foord50a8c0e2012-03-25 18:57:58 +01001390 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001391 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001392 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001393 # set spec to the object we are replacing
1394 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001395 if spec_set is True:
1396 spec_set = original
1397 spec = None
1398 elif spec is not None:
1399 if spec_set is True:
1400 spec_set = spec
1401 spec = None
1402 elif spec_set is True:
1403 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001404
Michael Foord50a8c0e2012-03-25 18:57:58 +01001405 if spec is not None or spec_set is not None:
1406 if original is DEFAULT:
1407 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001408 if isinstance(original, type):
1409 # If we're patching out a class and there is a spec
1410 inherit = True
Lisa Roach77b3b772019-05-20 09:19:53 -07001411 if spec is None and _is_async_obj(original):
1412 Klass = AsyncMock
1413 else:
1414 Klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -07001415 _kwargs = {}
1416 if new_callable is not None:
1417 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001418 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001419 this_spec = spec
1420 if spec_set is not None:
1421 this_spec = spec_set
1422 if _is_list(this_spec):
1423 not_callable = '__call__' not in this_spec
1424 else:
1425 not_callable = not callable(this_spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07001426 if _is_async_obj(this_spec):
1427 Klass = AsyncMock
1428 elif not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001429 Klass = NonCallableMagicMock
1430
1431 if spec is not None:
1432 _kwargs['spec'] = spec
1433 if spec_set is not None:
1434 _kwargs['spec_set'] = spec_set
1435
1436 # add a name to mocks
1437 if (isinstance(Klass, type) and
1438 issubclass(Klass, NonCallableMock) and self.attribute):
1439 _kwargs['name'] = self.attribute
1440
1441 _kwargs.update(kwargs)
1442 new = Klass(**_kwargs)
1443
1444 if inherit and _is_instance_mock(new):
1445 # we can only tell if the instance should be callable if the
1446 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001447 this_spec = spec
1448 if spec_set is not None:
1449 this_spec = spec_set
1450 if (not _is_list(this_spec) and not
1451 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001452 Klass = NonCallableMagicMock
1453
1454 _kwargs.pop('name')
1455 new.return_value = Klass(_new_parent=new, _new_name='()',
1456 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001457 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001458 # spec is ignored, new *must* be default, spec_set is treated
1459 # as a boolean. Should we check spec is not None and that spec_set
1460 # is a bool?
1461 if new is not DEFAULT:
1462 raise TypeError(
1463 "autospec creates the mock for you. Can't specify "
1464 "autospec and new."
1465 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001466 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001467 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001468 spec_set = bool(spec_set)
1469 if autospec is True:
1470 autospec = original
1471
1472 new = create_autospec(autospec, spec_set=spec_set,
1473 _name=self.attribute, **kwargs)
1474 elif kwargs:
1475 # can't set keyword args when we aren't creating the mock
1476 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1477 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1478
1479 new_attr = new
1480
1481 self.temp_original = original
1482 self.is_local = local
1483 setattr(self.target, self.attribute, new_attr)
1484 if self.attribute_name is not None:
1485 extra_args = {}
1486 if self.new is DEFAULT:
1487 extra_args[self.attribute_name] = new
1488 for patching in self.additional_patchers:
1489 arg = patching.__enter__()
1490 if patching.new is DEFAULT:
1491 extra_args.update(arg)
1492 return extra_args
1493
1494 return new
1495
1496
Michael Foord50a8c0e2012-03-25 18:57:58 +01001497 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001498 """Undo the patch."""
1499 if not _is_started(self):
Xtreak02b84cb2019-03-29 02:38:43 +05301500 return
Michael Foord345266a2012-03-14 12:24:34 -07001501
1502 if self.is_local and self.temp_original is not DEFAULT:
1503 setattr(self.target, self.attribute, self.temp_original)
1504 else:
1505 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001506 if not self.create and (not hasattr(self.target, self.attribute) or
1507 self.attribute in ('__doc__', '__module__',
1508 '__defaults__', '__annotations__',
1509 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001510 # needed for proxy objects like django settings
1511 setattr(self.target, self.attribute, self.temp_original)
1512
1513 del self.temp_original
1514 del self.is_local
1515 del self.target
1516 for patcher in reversed(self.additional_patchers):
1517 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001518 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001519
Michael Foordf7c41582012-06-10 20:36:32 +01001520
1521 def start(self):
1522 """Activate a patch, returning any created mock."""
1523 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001524 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001525 return result
1526
1527
1528 def stop(self):
1529 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001530 try:
1531 self._active_patches.remove(self)
1532 except ValueError:
1533 # If the patch hasn't been started this will fail
1534 pass
1535
Michael Foordf7c41582012-06-10 20:36:32 +01001536 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001537
1538
1539
1540def _get_target(target):
1541 try:
1542 target, attribute = target.rsplit('.', 1)
1543 except (TypeError, ValueError):
1544 raise TypeError("Need a valid target to patch. You supplied: %r" %
1545 (target,))
1546 getter = lambda: _importer(target)
1547 return getter, attribute
1548
1549
1550def _patch_object(
1551 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001552 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001553 new_callable=None, **kwargs
1554 ):
1555 """
Michael Foord345266a2012-03-14 12:24:34 -07001556 patch the named member (`attribute`) on an object (`target`) with a mock
1557 object.
1558
1559 `patch.object` can be used as a decorator, class decorator or a context
1560 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1561 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1562 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1563 the mock object it creates.
1564
1565 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1566 for choosing which methods to wrap.
1567 """
1568 getter = lambda: target
1569 return _patch(
1570 getter, attribute, new, spec, create,
1571 spec_set, autospec, new_callable, kwargs
1572 )
1573
1574
Michael Foord50a8c0e2012-03-25 18:57:58 +01001575def _patch_multiple(target, spec=None, create=False, spec_set=None,
1576 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001577 """Perform multiple patches in a single call. It takes the object to be
1578 patched (either as an object or a string to fetch the object by importing)
1579 and keyword arguments for the patches::
1580
1581 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1582 ...
1583
1584 Use `DEFAULT` as the value if you want `patch.multiple` to create
1585 mocks for you. In this case the created mocks are passed into a decorated
1586 function by keyword, and a dictionary is returned when `patch.multiple` is
1587 used as a context manager.
1588
1589 `patch.multiple` can be used as a decorator, class decorator or a context
1590 manager. The arguments `spec`, `spec_set`, `create`,
1591 `autospec` and `new_callable` have the same meaning as for `patch`. These
1592 arguments will be applied to *all* patches done by `patch.multiple`.
1593
1594 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1595 for choosing which methods to wrap.
1596 """
1597 if type(target) is str:
1598 getter = lambda: _importer(target)
1599 else:
1600 getter = lambda: target
1601
1602 if not kwargs:
1603 raise ValueError(
1604 'Must supply at least one keyword argument with patch.multiple'
1605 )
1606 # need to wrap in a list for python 3, where items is a view
1607 items = list(kwargs.items())
1608 attribute, new = items[0]
1609 patcher = _patch(
1610 getter, attribute, new, spec, create, spec_set,
1611 autospec, new_callable, {}
1612 )
1613 patcher.attribute_name = attribute
1614 for attribute, new in items[1:]:
1615 this_patcher = _patch(
1616 getter, attribute, new, spec, create, spec_set,
1617 autospec, new_callable, {}
1618 )
1619 this_patcher.attribute_name = attribute
1620 patcher.additional_patchers.append(this_patcher)
1621 return patcher
1622
1623
1624def patch(
1625 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001626 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001627 ):
1628 """
1629 `patch` acts as a function decorator, class decorator or a context
1630 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001631 is patched with a `new` object. When the function/with statement exits
1632 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001633
Michael Foord54b3db82012-03-28 15:08:08 +01001634 If `new` is omitted, then the target is replaced with a
1635 `MagicMock`. If `patch` is used as a decorator and `new` is
1636 omitted, the created mock is passed in as an extra argument to the
1637 decorated function. If `patch` is used as a context manager the created
1638 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001639
Michael Foord54b3db82012-03-28 15:08:08 +01001640 `target` should be a string in the form `'package.module.ClassName'`. The
1641 `target` is imported and the specified object replaced with the `new`
1642 object, so the `target` must be importable from the environment you are
1643 calling `patch` from. The target is imported when the decorated function
1644 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001645
1646 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1647 if patch is creating one for you.
1648
1649 In addition you can pass `spec=True` or `spec_set=True`, which causes
1650 patch to pass in the object being mocked as the spec/spec_set object.
1651
1652 `new_callable` allows you to specify a different class, or callable object,
1653 that will be called to create the `new` object. By default `MagicMock` is
1654 used.
1655
1656 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001657 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001658 All attributes of the mock will also have the spec of the corresponding
1659 attribute of the object being replaced. Methods and functions being
1660 mocked will have their arguments checked and will raise a `TypeError` if
1661 they are called with the wrong signature. For mocks replacing a class,
1662 their return value (the 'instance') will have the same spec as the class.
1663
1664 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1665 arbitrary object as the spec instead of the one being replaced.
1666
1667 By default `patch` will fail to replace attributes that don't exist. If
1668 you pass in `create=True`, and the attribute doesn't exist, patch will
1669 create the attribute for you when the patched function is called, and
1670 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001671 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001672 default because it can be dangerous. With it switched on you can write
1673 passing tests against APIs that don't actually exist!
1674
1675 Patch can be used as a `TestCase` class decorator. It works by
1676 decorating each test method in the class. This reduces the boilerplate
1677 code when your test methods share a common patchings set. `patch` finds
1678 tests by looking for method names that start with `patch.TEST_PREFIX`.
1679 By default this is `test`, which matches the way `unittest` finds tests.
1680 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1681
1682 Patch can be used as a context manager, with the with statement. Here the
1683 patching applies to the indented block after the with statement. If you
1684 use "as" then the patched object will be bound to the name after the
1685 "as"; very useful if `patch` is creating a mock object for you.
1686
1687 `patch` takes arbitrary keyword arguments. These will be passed to
1688 the `Mock` (or `new_callable`) on construction.
1689
1690 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1691 available for alternate use-cases.
1692 """
1693 getter, attribute = _get_target(target)
1694 return _patch(
1695 getter, attribute, new, spec, create,
1696 spec_set, autospec, new_callable, kwargs
1697 )
1698
1699
1700class _patch_dict(object):
1701 """
1702 Patch a dictionary, or dictionary like object, and restore the dictionary
1703 to its original state after the test.
1704
1705 `in_dict` can be a dictionary or a mapping like container. If it is a
1706 mapping then it must at least support getting, setting and deleting items
1707 plus iterating over keys.
1708
1709 `in_dict` can also be a string specifying the name of the dictionary, which
1710 will then be fetched by importing it.
1711
1712 `values` can be a dictionary of values to set in the dictionary. `values`
1713 can also be an iterable of `(key, value)` pairs.
1714
1715 If `clear` is True then the dictionary will be cleared before the new
1716 values are set.
1717
1718 `patch.dict` can also be called with arbitrary keyword arguments to set
1719 values in the dictionary::
1720
1721 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1722 ...
1723
1724 `patch.dict` can be used as a context manager, decorator or class
1725 decorator. When used as a class decorator `patch.dict` honours
1726 `patch.TEST_PREFIX` for choosing which methods to wrap.
1727 """
1728
1729 def __init__(self, in_dict, values=(), clear=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001730 self.in_dict = in_dict
1731 # support any argument supported by dict(...) constructor
1732 self.values = dict(values)
1733 self.values.update(kwargs)
1734 self.clear = clear
1735 self._original = None
1736
1737
1738 def __call__(self, f):
1739 if isinstance(f, type):
1740 return self.decorate_class(f)
1741 @wraps(f)
1742 def _inner(*args, **kw):
1743 self._patch_dict()
1744 try:
1745 return f(*args, **kw)
1746 finally:
1747 self._unpatch_dict()
1748
1749 return _inner
1750
1751
1752 def decorate_class(self, klass):
1753 for attr in dir(klass):
1754 attr_value = getattr(klass, attr)
1755 if (attr.startswith(patch.TEST_PREFIX) and
1756 hasattr(attr_value, "__call__")):
1757 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1758 decorated = decorator(attr_value)
1759 setattr(klass, attr, decorated)
1760 return klass
1761
1762
1763 def __enter__(self):
1764 """Patch the dict."""
1765 self._patch_dict()
Mario Corchero04530812019-05-28 13:53:31 +01001766 return self.in_dict
Michael Foord345266a2012-03-14 12:24:34 -07001767
1768
1769 def _patch_dict(self):
1770 values = self.values
Xtreaka875ea52019-02-25 00:24:49 +05301771 if isinstance(self.in_dict, str):
1772 self.in_dict = _importer(self.in_dict)
Michael Foord345266a2012-03-14 12:24:34 -07001773 in_dict = self.in_dict
1774 clear = self.clear
1775
1776 try:
1777 original = in_dict.copy()
1778 except AttributeError:
1779 # dict like object with no copy method
1780 # must support iteration over keys
1781 original = {}
1782 for key in in_dict:
1783 original[key] = in_dict[key]
1784 self._original = original
1785
1786 if clear:
1787 _clear_dict(in_dict)
1788
1789 try:
1790 in_dict.update(values)
1791 except AttributeError:
1792 # dict like object with no update method
1793 for key in values:
1794 in_dict[key] = values[key]
1795
1796
1797 def _unpatch_dict(self):
1798 in_dict = self.in_dict
1799 original = self._original
1800
1801 _clear_dict(in_dict)
1802
1803 try:
1804 in_dict.update(original)
1805 except AttributeError:
1806 for key in original:
1807 in_dict[key] = original[key]
1808
1809
1810 def __exit__(self, *args):
1811 """Unpatch the dict."""
1812 self._unpatch_dict()
1813 return False
1814
1815 start = __enter__
1816 stop = __exit__
1817
1818
1819def _clear_dict(in_dict):
1820 try:
1821 in_dict.clear()
1822 except AttributeError:
1823 keys = list(in_dict)
1824 for key in keys:
1825 del in_dict[key]
1826
1827
Michael Foordf7c41582012-06-10 20:36:32 +01001828def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001829 """Stop all active patches. LIFO to unroll nested patches."""
1830 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001831 patch.stop()
1832
1833
Michael Foord345266a2012-03-14 12:24:34 -07001834patch.object = _patch_object
1835patch.dict = _patch_dict
1836patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001837patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001838patch.TEST_PREFIX = 'test'
1839
1840magic_methods = (
1841 "lt le gt ge eq ne "
1842 "getitem setitem delitem "
1843 "len contains iter "
1844 "hash str sizeof "
1845 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001846 # we added divmod and rdivmod here instead of numerics
1847 # because there is no idivmod
1848 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001849 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001850 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001851 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001852 "fspath "
Michael Foord345266a2012-03-14 12:24:34 -07001853)
1854
Michael Foordd2623d72014-04-14 11:23:48 -04001855numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001856 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001857)
Michael Foord345266a2012-03-14 12:24:34 -07001858inplace = ' '.join('i%s' % n for n in numerics.split())
1859right = ' '.join('r%s' % n for n in numerics.split())
1860
1861# not including __prepare__, __instancecheck__, __subclasscheck__
1862# (as they are metaclass methods)
1863# __del__ is not supported at all as it causes problems if it exists
1864
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001865_non_defaults = {
1866 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1867 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1868 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1869 '__repr__', '__dir__', '__subclasses__', '__format__',
Lisa Roach77b3b772019-05-20 09:19:53 -07001870 '__getnewargs_ex__', '__aenter__', '__aexit__', '__anext__', '__aiter__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001871}
Michael Foord345266a2012-03-14 12:24:34 -07001872
1873
1874def _get_method(name, func):
1875 "Turns a callable object (like a mock) into a real function"
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001876 def method(self, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -07001877 return func(self, *args, **kw)
1878 method.__name__ = name
1879 return method
1880
1881
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001882_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001883 '__%s__' % method for method in
1884 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001885}
Michael Foord345266a2012-03-14 12:24:34 -07001886
Lisa Roach77b3b772019-05-20 09:19:53 -07001887# Magic methods used for async `with` statements
1888_async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
1889# `__aiter__` is a plain function but used with async calls
1890_async_magics = _async_method_magics | {"__aiter__"}
1891
Michael Foord345266a2012-03-14 12:24:34 -07001892_all_magics = _magics | _non_defaults
1893
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001894_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001895 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001896 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001897 '__instancecheck__', '__subclasscheck__',
1898 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001899}
Michael Foord345266a2012-03-14 12:24:34 -07001900
1901_calculate_return_value = {
1902 '__hash__': lambda self: object.__hash__(self),
1903 '__str__': lambda self: object.__str__(self),
1904 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001905 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001906}
1907
1908_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001909 '__lt__': NotImplemented,
1910 '__gt__': NotImplemented,
1911 '__le__': NotImplemented,
1912 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001913 '__int__': 1,
1914 '__contains__': False,
1915 '__len__': 0,
1916 '__exit__': False,
1917 '__complex__': 1j,
1918 '__float__': 1.0,
1919 '__bool__': True,
1920 '__index__': 1,
Lisa Roach77b3b772019-05-20 09:19:53 -07001921 '__aexit__': False,
Michael Foord345266a2012-03-14 12:24:34 -07001922}
1923
1924
1925def _get_eq(self):
1926 def __eq__(other):
1927 ret_val = self.__eq__._mock_return_value
1928 if ret_val is not DEFAULT:
1929 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001930 if self is other:
1931 return True
1932 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001933 return __eq__
1934
1935def _get_ne(self):
1936 def __ne__(other):
1937 if self.__ne__._mock_return_value is not DEFAULT:
1938 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001939 if self is other:
1940 return False
1941 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001942 return __ne__
1943
1944def _get_iter(self):
1945 def __iter__():
1946 ret_val = self.__iter__._mock_return_value
1947 if ret_val is DEFAULT:
1948 return iter([])
1949 # if ret_val was already an iterator, then calling iter on it should
1950 # return the iterator unchanged
1951 return iter(ret_val)
1952 return __iter__
1953
Lisa Roach77b3b772019-05-20 09:19:53 -07001954def _get_async_iter(self):
1955 def __aiter__():
1956 ret_val = self.__aiter__._mock_return_value
1957 if ret_val is DEFAULT:
1958 return _AsyncIterator(iter([]))
1959 return _AsyncIterator(iter(ret_val))
1960 return __aiter__
1961
Michael Foord345266a2012-03-14 12:24:34 -07001962_side_effect_methods = {
1963 '__eq__': _get_eq,
1964 '__ne__': _get_ne,
1965 '__iter__': _get_iter,
Lisa Roach77b3b772019-05-20 09:19:53 -07001966 '__aiter__': _get_async_iter
Michael Foord345266a2012-03-14 12:24:34 -07001967}
1968
1969
1970
1971def _set_return_value(mock, method, name):
1972 fixed = _return_values.get(name, DEFAULT)
1973 if fixed is not DEFAULT:
1974 method.return_value = fixed
1975 return
1976
1977 return_calulator = _calculate_return_value.get(name)
1978 if return_calulator is not None:
Chris Withersadbf1782019-05-01 23:04:04 +01001979 return_value = return_calulator(mock)
Michael Foord345266a2012-03-14 12:24:34 -07001980 method.return_value = return_value
1981 return
1982
1983 side_effector = _side_effect_methods.get(name)
1984 if side_effector is not None:
1985 method.side_effect = side_effector(mock)
1986
1987
1988
1989class MagicMixin(object):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001990 def __init__(self, /, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001991 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001992 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001993 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001994
1995
1996 def _mock_set_magics(self):
1997 these_magics = _magics
1998
Łukasz Langaa468db92015-04-13 23:12:42 -07001999 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07002000 these_magics = _magics.intersection(self._mock_methods)
2001
2002 remove_magics = set()
2003 remove_magics = _magics - these_magics
2004
2005 for entry in remove_magics:
2006 if entry in type(self).__dict__:
2007 # remove unneeded magic methods
2008 delattr(self, entry)
2009
2010 # don't overwrite existing attributes if called a second time
2011 these_magics = these_magics - set(type(self).__dict__)
2012
2013 _type = type(self)
2014 for entry in these_magics:
2015 setattr(_type, entry, MagicProxy(entry, self))
2016
2017
2018
2019class NonCallableMagicMock(MagicMixin, NonCallableMock):
2020 """A version of `MagicMock` that isn't callable."""
2021 def mock_add_spec(self, spec, spec_set=False):
2022 """Add a spec to a mock. `spec` can either be an object or a
2023 list of strings. Only attributes on the `spec` can be fetched as
2024 attributes from the mock.
2025
2026 If `spec_set` is True then only attributes on the spec can be set."""
2027 self._mock_add_spec(spec, spec_set)
2028 self._mock_set_magics()
2029
2030
Lisa Roach77b3b772019-05-20 09:19:53 -07002031class AsyncMagicMixin:
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002032 def __init__(self, /, *args, **kw):
Lisa Roach77b3b772019-05-20 09:19:53 -07002033 self._mock_set_async_magics() # make magic work for kwargs in init
2034 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)
2035 self._mock_set_async_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07002036
Lisa Roach77b3b772019-05-20 09:19:53 -07002037 def _mock_set_async_magics(self):
2038 these_magics = _async_magics
2039
2040 if getattr(self, "_mock_methods", None) is not None:
2041 these_magics = _async_magics.intersection(self._mock_methods)
2042 remove_magics = _async_magics - these_magics
2043
2044 for entry in remove_magics:
2045 if entry in type(self).__dict__:
2046 # remove unneeded magic methods
2047 delattr(self, entry)
2048
2049 # don't overwrite existing attributes if called a second time
2050 these_magics = these_magics - set(type(self).__dict__)
2051
2052 _type = type(self)
2053 for entry in these_magics:
2054 setattr(_type, entry, MagicProxy(entry, self))
2055
2056
2057class MagicMock(MagicMixin, AsyncMagicMixin, Mock):
Michael Foord345266a2012-03-14 12:24:34 -07002058 """
2059 MagicMock is a subclass of Mock with default implementations
2060 of most of the magic methods. You can use MagicMock without having to
2061 configure the magic methods yourself.
2062
2063 If you use the `spec` or `spec_set` arguments then *only* magic
2064 methods that exist in the spec will be created.
2065
2066 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
2067 """
2068 def mock_add_spec(self, spec, spec_set=False):
2069 """Add a spec to a mock. `spec` can either be an object or a
2070 list of strings. Only attributes on the `spec` can be fetched as
2071 attributes from the mock.
2072
2073 If `spec_set` is True then only attributes on the spec can be set."""
2074 self._mock_add_spec(spec, spec_set)
2075 self._mock_set_magics()
2076
2077
2078
2079class MagicProxy(object):
2080 def __init__(self, name, parent):
2081 self.name = name
2082 self.parent = parent
2083
Michael Foord345266a2012-03-14 12:24:34 -07002084 def create_mock(self):
2085 entry = self.name
2086 parent = self.parent
2087 m = parent._get_child_mock(name=entry, _new_name=entry,
2088 _new_parent=parent)
2089 setattr(parent, entry, m)
2090 _set_return_value(parent, m, entry)
2091 return m
2092
2093 def __get__(self, obj, _type=None):
2094 return self.create_mock()
2095
2096
Lisa Roach77b3b772019-05-20 09:19:53 -07002097class AsyncMockMixin(Base):
2098 awaited = _delegating_property('awaited')
2099 await_count = _delegating_property('await_count')
2100 await_args = _delegating_property('await_args')
2101 await_args_list = _delegating_property('await_args_list')
2102
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002103 def __init__(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002104 super().__init__(*args, **kwargs)
2105 # asyncio.iscoroutinefunction() checks _is_coroutine property to say if an
2106 # object is a coroutine. Without this check it looks to see if it is a
2107 # function/method, which in this case it is not (since it is an
2108 # AsyncMock).
2109 # It is set through __dict__ because when spec_set is True, this
2110 # attribute is likely undefined.
2111 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
2112 self.__dict__['_mock_awaited'] = _AwaitEvent(self)
2113 self.__dict__['_mock_await_count'] = 0
2114 self.__dict__['_mock_await_args'] = None
2115 self.__dict__['_mock_await_args_list'] = _CallList()
2116 code_mock = NonCallableMock(spec_set=CodeType)
2117 code_mock.co_flags = inspect.CO_COROUTINE
2118 self.__dict__['__code__'] = code_mock
2119
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002120 async def _mock_call(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002121 try:
2122 result = super()._mock_call(*args, **kwargs)
2123 except (BaseException, StopIteration) as e:
2124 side_effect = self.side_effect
2125 if side_effect is not None and not callable(side_effect):
2126 raise
2127 return await _raise(e)
2128
2129 _call = self.call_args
2130
2131 async def proxy():
2132 try:
2133 if inspect.isawaitable(result):
2134 return await result
2135 else:
2136 return result
2137 finally:
2138 self.await_count += 1
2139 self.await_args = _call
2140 self.await_args_list.append(_call)
2141 await self.awaited._notify()
2142
2143 return await proxy()
2144
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002145 def assert_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002146 """
2147 Assert that the mock was awaited at least once.
2148 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002149 if self.await_count == 0:
2150 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2151 raise AssertionError(msg)
2152
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002153 def assert_awaited_once(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002154 """
2155 Assert that the mock was awaited exactly once.
2156 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002157 if not self.await_count == 1:
2158 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2159 f" Awaited {self.await_count} times.")
2160 raise AssertionError(msg)
2161
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002162 def assert_awaited_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002163 """
2164 Assert that the last await was with the specified arguments.
2165 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002166 if self.await_args is None:
2167 expected = self._format_mock_call_signature(args, kwargs)
2168 raise AssertionError(f'Expected await: {expected}\nNot awaited')
2169
2170 def _error_message():
Xtreak0ae022c2019-05-29 12:32:26 +05302171 msg = self._format_mock_failure_message(args, kwargs, action='await')
Lisa Roach77b3b772019-05-20 09:19:53 -07002172 return msg
2173
2174 expected = self._call_matcher((args, kwargs))
2175 actual = self._call_matcher(self.await_args)
2176 if expected != actual:
2177 cause = expected if isinstance(expected, Exception) else None
2178 raise AssertionError(_error_message()) from cause
2179
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002180 def assert_awaited_once_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002181 """
2182 Assert that the mock was awaited exactly once and with the specified
2183 arguments.
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 return self.assert_awaited_with(*args, **kwargs)
2190
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002191 def assert_any_await(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002192 """
2193 Assert the mock has ever been awaited with the specified arguments.
2194 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002195 expected = self._call_matcher((args, kwargs))
2196 actual = [self._call_matcher(c) for c in self.await_args_list]
2197 if expected not in actual:
2198 cause = expected if isinstance(expected, Exception) else None
2199 expected_string = self._format_mock_call_signature(args, kwargs)
2200 raise AssertionError(
2201 '%s await not found' % expected_string
2202 ) from cause
2203
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002204 def assert_has_awaits(self, calls, any_order=False):
Lisa Roach77b3b772019-05-20 09:19:53 -07002205 """
2206 Assert the mock has been awaited with the specified calls.
2207 The :attr:`await_args_list` list is checked for the awaits.
2208
2209 If `any_order` is False (the default) then the awaits must be
2210 sequential. There can be extra calls before or after the
2211 specified awaits.
2212
2213 If `any_order` is True then the awaits can be in any order, but
2214 they must all appear in :attr:`await_args_list`.
2215 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002216 expected = [self._call_matcher(c) for c in calls]
2217 cause = expected if isinstance(expected, Exception) else None
2218 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2219 if not any_order:
2220 if expected not in all_awaits:
2221 raise AssertionError(
Xtreak0ae022c2019-05-29 12:32:26 +05302222 f'Awaits not found.\nExpected: {_CallList(calls)}\n'
Lisa Roach77b3b772019-05-20 09:19:53 -07002223 f'Actual: {self.await_args_list}'
2224 ) from cause
2225 return
2226
2227 all_awaits = list(all_awaits)
2228
2229 not_found = []
2230 for kall in expected:
2231 try:
2232 all_awaits.remove(kall)
2233 except ValueError:
2234 not_found.append(kall)
2235 if not_found:
2236 raise AssertionError(
2237 '%r not all found in await list' % (tuple(not_found),)
2238 ) from cause
2239
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002240 def assert_not_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002241 """
2242 Assert that the mock was never awaited.
2243 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002244 if self.await_count != 0:
Xtreakff6b2e62019-05-27 18:26:23 +05302245 msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
Lisa Roach77b3b772019-05-20 09:19:53 -07002246 f" Awaited {self.await_count} times.")
2247 raise AssertionError(msg)
2248
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002249 def reset_mock(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002250 """
2251 See :func:`.Mock.reset_mock()`
2252 """
2253 super().reset_mock(*args, **kwargs)
2254 self.await_count = 0
2255 self.await_args = None
2256 self.await_args_list = _CallList()
2257
2258
2259class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2260 """
2261 Enhance :class:`Mock` with features allowing to mock
2262 an async function.
2263
2264 The :class:`AsyncMock` object will behave so the object is
2265 recognized as an async function, and the result of a call is an awaitable:
2266
2267 >>> mock = AsyncMock()
2268 >>> asyncio.iscoroutinefunction(mock)
2269 True
2270 >>> inspect.isawaitable(mock())
2271 True
2272
2273
2274 The result of ``mock()`` is an async function which will have the outcome
2275 of ``side_effect`` or ``return_value``:
2276
2277 - if ``side_effect`` is a function, the async function will return the
2278 result of that function,
2279 - if ``side_effect`` is an exception, the async function will raise the
2280 exception,
2281 - if ``side_effect`` is an iterable, the async function will return the
2282 next value of the iterable, however, if the sequence of result is
2283 exhausted, ``StopIteration`` is raised immediately,
2284 - if ``side_effect`` is not defined, the async function will return the
2285 value defined by ``return_value``, hence, by default, the async function
2286 returns a new :class:`AsyncMock` object.
2287
2288 If the outcome of ``side_effect`` or ``return_value`` is an async function,
2289 the mock async function obtained when the mock object is called will be this
2290 async function itself (and not an async function returning an async
2291 function).
2292
2293 The test author can also specify a wrapped object with ``wraps``. In this
2294 case, the :class:`Mock` object behavior is the same as with an
2295 :class:`.Mock` object: the wrapped object may have methods
2296 defined as async function functions.
2297
Xtreake7cb23b2019-05-21 14:17:17 +05302298 Based on Martin Richard's asynctest project.
Lisa Roach77b3b772019-05-20 09:19:53 -07002299 """
2300
Michael Foord345266a2012-03-14 12:24:34 -07002301
2302class _ANY(object):
2303 "A helper object that compares equal to everything."
2304
2305 def __eq__(self, other):
2306 return True
2307
2308 def __ne__(self, other):
2309 return False
2310
2311 def __repr__(self):
2312 return '<ANY>'
2313
2314ANY = _ANY()
2315
2316
2317
2318def _format_call_signature(name, args, kwargs):
2319 message = '%s(%%s)' % name
2320 formatted_args = ''
2321 args_string = ', '.join([repr(arg) for arg in args])
2322 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05302323 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07002324 ])
2325 if args_string:
2326 formatted_args = args_string
2327 if kwargs_string:
2328 if formatted_args:
2329 formatted_args += ', '
2330 formatted_args += kwargs_string
2331
2332 return message % formatted_args
2333
2334
2335
2336class _Call(tuple):
2337 """
2338 A tuple for holding the results of a call to a mock, either in the form
2339 `(args, kwargs)` or `(name, args, kwargs)`.
2340
2341 If args or kwargs are empty then a call tuple will compare equal to
2342 a tuple without those values. This makes comparisons less verbose::
2343
2344 _Call(('name', (), {})) == ('name',)
2345 _Call(('name', (1,), {})) == ('name', (1,))
2346 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2347
2348 The `_Call` object provides a useful shortcut for comparing with call::
2349
2350 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2351 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2352
2353 If the _Call has no name then it will match any name.
2354 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002355 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002356 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002357 args = ()
2358 kwargs = {}
2359 _len = len(value)
2360 if _len == 3:
2361 name, args, kwargs = value
2362 elif _len == 2:
2363 first, second = value
2364 if isinstance(first, str):
2365 name = first
2366 if isinstance(second, tuple):
2367 args = second
2368 else:
2369 kwargs = second
2370 else:
2371 args, kwargs = first, second
2372 elif _len == 1:
2373 value, = value
2374 if isinstance(value, str):
2375 name = value
2376 elif isinstance(value, tuple):
2377 args = value
2378 else:
2379 kwargs = value
2380
2381 if two:
2382 return tuple.__new__(cls, (args, kwargs))
2383
2384 return tuple.__new__(cls, (name, args, kwargs))
2385
2386
2387 def __init__(self, value=(), name=None, parent=None, two=False,
2388 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002389 self._mock_name = name
2390 self._mock_parent = parent
2391 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002392
2393
2394 def __eq__(self, other):
Michael Foord345266a2012-03-14 12:24:34 -07002395 try:
2396 len_other = len(other)
2397 except TypeError:
Serhiy Storchaka662db122019-08-08 08:42:54 +03002398 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07002399
2400 self_name = ''
2401 if len(self) == 2:
2402 self_args, self_kwargs = self
2403 else:
2404 self_name, self_args, self_kwargs = self
2405
Andrew Dunaie63e6172018-12-04 11:08:45 +02002406 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2407 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002408 return False
2409
Michael Foord345266a2012-03-14 12:24:34 -07002410 other_name = ''
2411 if len_other == 0:
2412 other_args, other_kwargs = (), {}
2413 elif len_other == 3:
2414 other_name, other_args, other_kwargs = other
2415 elif len_other == 1:
2416 value, = other
2417 if isinstance(value, tuple):
2418 other_args = value
2419 other_kwargs = {}
2420 elif isinstance(value, str):
2421 other_name = value
2422 other_args, other_kwargs = (), {}
2423 else:
2424 other_args = ()
2425 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002426 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002427 # could be (name, args) or (name, kwargs) or (args, kwargs)
2428 first, second = other
2429 if isinstance(first, str):
2430 other_name = first
2431 if isinstance(second, tuple):
2432 other_args, other_kwargs = second, {}
2433 else:
2434 other_args, other_kwargs = (), second
2435 else:
2436 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002437 else:
2438 return False
Michael Foord345266a2012-03-14 12:24:34 -07002439
2440 if self_name and other_name != self_name:
2441 return False
2442
2443 # this order is important for ANY to work!
2444 return (other_args, other_kwargs) == (self_args, self_kwargs)
2445
2446
Berker Peksagce913872016-03-28 00:30:02 +03002447 __ne__ = object.__ne__
2448
2449
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002450 def __call__(self, /, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002451 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002452 return _Call(('', args, kwargs), name='()')
2453
Andrew Dunaie63e6172018-12-04 11:08:45 +02002454 name = self._mock_name + '()'
2455 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002456
2457
2458 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002459 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002460 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002461 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002462 return _Call(name=name, parent=self, from_kall=False)
2463
2464
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002465 def count(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302466 return self.__getattr__('count')(*args, **kwargs)
2467
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002468 def index(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302469 return self.__getattr__('index')(*args, **kwargs)
2470
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302471 def _get_call_arguments(self):
2472 if len(self) == 2:
2473 args, kwargs = self
2474 else:
2475 name, args, kwargs = self
2476
2477 return args, kwargs
2478
2479 @property
2480 def args(self):
2481 return self._get_call_arguments()[0]
2482
2483 @property
2484 def kwargs(self):
2485 return self._get_call_arguments()[1]
2486
Michael Foord345266a2012-03-14 12:24:34 -07002487 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002488 if not self._mock_from_kall:
2489 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002490 if name.startswith('()'):
2491 name = 'call%s' % name
2492 return name
2493
2494 if len(self) == 2:
2495 name = 'call'
2496 args, kwargs = self
2497 else:
2498 name, args, kwargs = self
2499 if not name:
2500 name = 'call'
2501 elif not name.startswith('()'):
2502 name = 'call.%s' % name
2503 else:
2504 name = 'call%s' % name
2505 return _format_call_signature(name, args, kwargs)
2506
2507
2508 def call_list(self):
2509 """For a call object that represents multiple calls, `call_list`
2510 returns a list of all the intermediate calls as well as the
2511 final call."""
2512 vals = []
2513 thing = self
2514 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002515 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002516 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002517 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002518 return _CallList(reversed(vals))
2519
2520
2521call = _Call(from_kall=False)
2522
2523
Michael Foord345266a2012-03-14 12:24:34 -07002524def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2525 _name=None, **kwargs):
2526 """Create a mock object using another object as a spec. Attributes on the
2527 mock will use the corresponding attribute on the `spec` object as their
2528 spec.
2529
2530 Functions or methods being mocked will have their arguments checked
2531 to check that they are called with the correct signature.
2532
2533 If `spec_set` is True then attempting to set attributes that don't exist
2534 on the spec object will raise an `AttributeError`.
2535
2536 If a class is used as a spec then the return value of the mock (the
2537 instance of the class) will have the same spec. You can use a class as the
2538 spec for an instance object by passing `instance=True`. The returned mock
2539 will only be callable if instances of the mock are callable.
2540
2541 `create_autospec` also takes arbitrary keyword arguments that are passed to
2542 the constructor of the created mock."""
2543 if _is_list(spec):
2544 # can't pass a list instance to the mock constructor as it will be
2545 # interpreted as a list of strings
2546 spec = type(spec)
2547
2548 is_type = isinstance(spec, type)
Xtreakff6b2e62019-05-27 18:26:23 +05302549 is_async_func = _is_async_func(spec)
Michael Foord345266a2012-03-14 12:24:34 -07002550 _kwargs = {'spec': spec}
2551 if spec_set:
2552 _kwargs = {'spec_set': spec}
2553 elif spec is None:
2554 # None we mock with a normal mock without a spec
2555 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002556 if _kwargs and instance:
2557 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002558
2559 _kwargs.update(kwargs)
2560
2561 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002562 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002563 # descriptors don't have a spec
2564 # because we don't know what type they return
2565 _kwargs = {}
Lisa Roach77b3b772019-05-20 09:19:53 -07002566 elif is_async_func:
2567 if instance:
2568 raise RuntimeError("Instance can not be True when create_autospec "
2569 "is mocking an async function")
2570 Klass = AsyncMock
Michael Foord345266a2012-03-14 12:24:34 -07002571 elif not _callable(spec):
2572 Klass = NonCallableMagicMock
2573 elif is_type and instance and not _instance_callable(spec):
2574 Klass = NonCallableMagicMock
2575
Kushal Das484f8a82014-04-16 01:05:50 +05302576 _name = _kwargs.pop('name', _name)
2577
Michael Foord345266a2012-03-14 12:24:34 -07002578 _new_name = _name
2579 if _parent is None:
2580 # for a top level object no _new_name should be set
2581 _new_name = ''
2582
2583 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2584 name=_name, **_kwargs)
2585
2586 if isinstance(spec, FunctionTypes):
2587 # should only happen at the top level because we don't
2588 # recurse for functions
2589 mock = _set_signature(mock, spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07002590 if is_async_func:
Xtreakff6b2e62019-05-27 18:26:23 +05302591 _setup_async_mock(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002592 else:
2593 _check_signature(spec, mock, is_type, instance)
2594
2595 if _parent is not None and not instance:
2596 _parent._mock_children[_name] = mock
2597
2598 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002599 mock.return_value = create_autospec(spec, spec_set, instance=True,
2600 _name='()', _parent=mock)
2601
2602 for entry in dir(spec):
2603 if _is_magic(entry):
2604 # MagicMock already does the useful magic methods for us
2605 continue
2606
Michael Foord345266a2012-03-14 12:24:34 -07002607 # XXXX do we need a better way of getting attributes without
2608 # triggering code execution (?) Probably not - we need the actual
2609 # object to mock it so we would rather trigger a property than mock
2610 # the property descriptor. Likewise we want to mock out dynamically
2611 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002612 # XXXX what about attributes that raise exceptions other than
2613 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002614 # we could be resilient against it, or catch and propagate the
2615 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002616 try:
2617 original = getattr(spec, entry)
2618 except AttributeError:
2619 continue
Michael Foord345266a2012-03-14 12:24:34 -07002620
2621 kwargs = {'spec': original}
2622 if spec_set:
2623 kwargs = {'spec_set': original}
2624
2625 if not isinstance(original, FunctionTypes):
2626 new = _SpecState(original, spec_set, mock, entry, instance)
2627 mock._mock_children[entry] = new
2628 else:
2629 parent = mock
2630 if isinstance(spec, FunctionTypes):
2631 parent = mock.mock
2632
Michael Foord345266a2012-03-14 12:24:34 -07002633 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002634 kwargs['_eat_self'] = skipfirst
Lisa Roach77b3b772019-05-20 09:19:53 -07002635 if asyncio.iscoroutinefunction(original):
2636 child_klass = AsyncMock
2637 else:
2638 child_klass = MagicMock
2639 new = child_klass(parent=parent, name=entry, _new_name=entry,
2640 _new_parent=parent,
2641 **kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002642 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002643 _check_signature(original, new, skipfirst=skipfirst)
2644
2645 # so functions created with _set_signature become instance attributes,
2646 # *plus* their underlying mock exists in _mock_children of the parent
2647 # mock. Adding to _mock_children may be unnecessary where we are also
2648 # setting as an instance attribute?
2649 if isinstance(new, FunctionTypes):
2650 setattr(mock, entry, new)
2651
2652 return mock
2653
2654
2655def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002656 """
2657 Return whether we should skip the first argument on spec's `entry`
2658 attribute.
2659 """
Michael Foord345266a2012-03-14 12:24:34 -07002660 if not isinstance(spec, type):
2661 if entry in getattr(spec, '__dict__', {}):
2662 # instance attribute - shouldn't skip
2663 return False
Michael Foord345266a2012-03-14 12:24:34 -07002664 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002665
2666 for klass in spec.__mro__:
2667 result = klass.__dict__.get(entry, DEFAULT)
2668 if result is DEFAULT:
2669 continue
2670 if isinstance(result, (staticmethod, classmethod)):
2671 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002672 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2673 # Normal method => skip if looked up on type
2674 # (if looked up on instance, self is already skipped)
2675 return is_type
2676 else:
2677 return False
Michael Foord345266a2012-03-14 12:24:34 -07002678
Chris Withersadbf1782019-05-01 23:04:04 +01002679 # function is a dynamically provided attribute
Michael Foord345266a2012-03-14 12:24:34 -07002680 return is_type
2681
2682
Michael Foord345266a2012-03-14 12:24:34 -07002683class _SpecState(object):
2684
2685 def __init__(self, spec, spec_set=False, parent=None,
2686 name=None, ids=None, instance=False):
2687 self.spec = spec
2688 self.ids = ids
2689 self.spec_set = spec_set
2690 self.parent = parent
2691 self.instance = instance
2692 self.name = name
2693
2694
2695FunctionTypes = (
2696 # python function
2697 type(create_autospec),
2698 # instance method
2699 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002700)
2701
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002702MethodWrapperTypes = (
2703 type(ANY.__eq__.__get__),
2704)
2705
Michael Foord345266a2012-03-14 12:24:34 -07002706
Michael Foorda74561a2012-03-25 19:03:13 +01002707file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002708
Michael Foord04cbe0c2013-03-19 17:22:51 -07002709
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002710def _to_stream(read_data):
2711 if isinstance(read_data, bytes):
2712 return io.BytesIO(read_data)
Michael Foord04cbe0c2013-03-19 17:22:51 -07002713 else:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002714 return io.StringIO(read_data)
Michael Foord0dccf652012-03-25 19:11:50 +01002715
Robert Collins5329aaa2015-07-17 20:08:45 +12002716
Michael Foord0dccf652012-03-25 19:11:50 +01002717def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002718 """
2719 A helper function to create a mock to replace the use of `open`. It works
2720 for `open` called directly or used as a context manager.
2721
2722 The `mock` argument is the mock object to configure. If `None` (the
2723 default) then a `MagicMock` will be created for you, with the API limited
2724 to methods or attributes available on standard file handles.
2725
Xtreak71f82a22018-12-20 21:30:21 +05302726 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002727 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002728 """
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002729 _read_data = _to_stream(read_data)
2730 _state = [_read_data, None]
2731
Robert Collinsca647ef2015-07-24 03:48:20 +12002732 def _readlines_side_effect(*args, **kwargs):
2733 if handle.readlines.return_value is not None:
2734 return handle.readlines.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002735 return _state[0].readlines(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002736
2737 def _read_side_effect(*args, **kwargs):
2738 if handle.read.return_value is not None:
2739 return handle.read.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002740 return _state[0].read(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002741
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002742 def _readline_side_effect(*args, **kwargs):
Tony Flury20870232018-09-12 23:21:16 +01002743 yield from _iter_side_effect()
2744 while True:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002745 yield _state[0].readline(*args, **kwargs)
Tony Flury20870232018-09-12 23:21:16 +01002746
2747 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002748 if handle.readline.return_value is not None:
2749 while True:
2750 yield handle.readline.return_value
2751 for line in _state[0]:
2752 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002753
Damien Nadé394119a2019-05-23 12:03:25 +02002754 def _next_side_effect():
2755 if handle.readline.return_value is not None:
2756 return handle.readline.return_value
2757 return next(_state[0])
2758
Michael Foorda74561a2012-03-25 19:03:13 +01002759 global file_spec
2760 if file_spec is None:
2761 import _io
2762 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2763
Michael Foord345266a2012-03-14 12:24:34 -07002764 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002765 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002766
Robert Collinsca647ef2015-07-24 03:48:20 +12002767 handle = MagicMock(spec=file_spec)
2768 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002769
Robert Collinsca647ef2015-07-24 03:48:20 +12002770 handle.write.return_value = None
2771 handle.read.return_value = None
2772 handle.readline.return_value = None
2773 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002774
Robert Collinsca647ef2015-07-24 03:48:20 +12002775 handle.read.side_effect = _read_side_effect
2776 _state[1] = _readline_side_effect()
2777 handle.readline.side_effect = _state[1]
2778 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002779 handle.__iter__.side_effect = _iter_side_effect
Damien Nadé394119a2019-05-23 12:03:25 +02002780 handle.__next__.side_effect = _next_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002781
Robert Collinsca647ef2015-07-24 03:48:20 +12002782 def reset_data(*args, **kwargs):
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002783 _state[0] = _to_stream(read_data)
Robert Collinsca647ef2015-07-24 03:48:20 +12002784 if handle.readline.side_effect == _state[1]:
2785 # Only reset the side effect if the user hasn't overridden it.
2786 _state[1] = _readline_side_effect()
2787 handle.readline.side_effect = _state[1]
2788 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002789
Robert Collinsca647ef2015-07-24 03:48:20 +12002790 mock.side_effect = reset_data
2791 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002792 return mock
2793
2794
2795class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002796 """
2797 A mock intended to be used as a property, or other descriptor, on a class.
2798 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2799 a return value when it is fetched.
2800
2801 Fetching a `PropertyMock` instance from an object calls the mock, with
2802 no args. Setting it calls the mock with the value being set.
2803 """
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002804 def _get_child_mock(self, /, **kwargs):
Michael Foordc2870622012-04-13 16:57:22 +01002805 return MagicMock(**kwargs)
2806
Raymond Hettinger0dac68f2019-08-29 01:27:42 -07002807 def __get__(self, obj, obj_type=None):
Michael Foord345266a2012-03-14 12:24:34 -07002808 return self()
2809 def __set__(self, obj, val):
2810 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002811
2812
2813def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002814 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002815
2816 Given an input Mock, seals it to ensure no further mocks will be generated
2817 when accessing an attribute that was not already defined.
2818
Mario Corchero96200eb2018-10-19 22:57:37 +01002819 The operation recursively seals the mock passed in, meaning that
2820 the mock itself, any mocks generated by accessing one of its attributes,
2821 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002822 """
2823 mock._mock_sealed = True
2824 for attr in dir(mock):
2825 try:
2826 m = getattr(mock, attr)
2827 except AttributeError:
2828 continue
2829 if not isinstance(m, NonCallableMock):
2830 continue
2831 if m._mock_new_parent is mock:
2832 seal(m)
Lisa Roach77b3b772019-05-20 09:19:53 -07002833
2834
2835async def _raise(exception):
2836 raise exception
2837
2838
2839class _AsyncIterator:
2840 """
2841 Wraps an iterator in an asynchronous iterator.
2842 """
2843 def __init__(self, iterator):
2844 self.iterator = iterator
2845 code_mock = NonCallableMock(spec_set=CodeType)
2846 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
2847 self.__dict__['__code__'] = code_mock
2848
2849 def __aiter__(self):
2850 return self
2851
2852 async def __anext__(self):
2853 try:
2854 return next(self.iterator)
2855 except StopIteration:
2856 pass
2857 raise StopAsyncIteration
2858
2859
2860class _AwaitEvent:
2861 def __init__(self, mock):
2862 self._mock = mock
2863 self._condition = None
2864
2865 async def _notify(self):
2866 condition = self._get_condition()
2867 try:
2868 await condition.acquire()
2869 condition.notify_all()
2870 finally:
2871 condition.release()
2872
2873 def _get_condition(self):
2874 """
2875 Creation of condition is delayed, to minimize the chance of using the
2876 wrong loop.
2877 A user may create a mock with _AwaitEvent before selecting the
2878 execution loop. Requiring a user to delay creation is error-prone and
2879 inflexible. Instead, condition is created when user actually starts to
2880 use the mock.
2881 """
2882 # No synchronization is needed:
2883 # - asyncio is thread unsafe
2884 # - there are no awaits here, method will be executed without
2885 # switching asyncio context.
2886 if self._condition is None:
2887 self._condition = asyncio.Condition()
2888
2889 return self._condition