blob: c2802726d75d9c59db7fc1b264b1e1aec1182f09 [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
Antoine Pitrou5c64df72013-02-03 00:23:58 +010075def _get_signature_object(func, as_instance, eat_self):
76 """
77 Given an arbitrary, possibly callable object, try to create a suitable
78 signature object.
79 Return a (reduced func, signature) tuple, or None.
80 """
81 if isinstance(func, type) and not as_instance:
82 # If it's a type and should be modelled as a type, use __init__.
Chris Withersadbf1782019-05-01 23:04:04 +010083 func = func.__init__
Antoine Pitrou5c64df72013-02-03 00:23:58 +010084 # Skip the `self` argument in __init__
85 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070086 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010087 # If we really want to model an instance of the passed type,
88 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070089 try:
90 func = func.__call__
91 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010092 return None
93 if eat_self:
94 sig_func = partial(func, None)
95 else:
96 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -070097 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010098 return func, inspect.signature(sig_func)
99 except ValueError:
100 # Certain callable types are not supported by inspect.signature()
101 return None
Michael Foord345266a2012-03-14 12:24:34 -0700102
103
104def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100105 sig = _get_signature_object(func, instance, skipfirst)
106 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -0700107 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100108 func, sig = sig
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300109 def checksig(self, /, *args, **kwargs):
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100110 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700111 _copy_func_details(func, checksig)
112 type(mock)._mock_check_sig = checksig
Xtreakf7fa62e2018-12-12 13:24:54 +0530113 type(mock).__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700114
115
116def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700117 # we explicitly don't copy func.__dict__ into this copy as it would
118 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300119 for attribute in (
120 '__name__', '__doc__', '__text_signature__',
121 '__module__', '__defaults__', '__kwdefaults__',
122 ):
123 try:
124 setattr(funcopy, attribute, getattr(func, attribute))
125 except AttributeError:
126 pass
Michael Foord345266a2012-03-14 12:24:34 -0700127
128
129def _callable(obj):
130 if isinstance(obj, type):
131 return True
Xtreak9b218562019-04-22 08:00:23 +0530132 if isinstance(obj, (staticmethod, classmethod, MethodType)):
133 return _callable(obj.__func__)
Michael Foord345266a2012-03-14 12:24:34 -0700134 if getattr(obj, '__call__', None) is not None:
135 return True
136 return False
137
138
139def _is_list(obj):
140 # checks for list or tuples
141 # XXXX badly named!
142 return type(obj) in (list, tuple)
143
144
145def _instance_callable(obj):
146 """Given an object, return True if the object is callable.
147 For classes, return True if instances would be callable."""
148 if not isinstance(obj, type):
149 # already an instance
150 return getattr(obj, '__call__', None) is not None
151
Michael Foorda74b3aa2012-03-14 14:40:22 -0700152 # *could* be broken by a class overriding __mro__ or __dict__ via
153 # a metaclass
154 for base in (obj,) + obj.__mro__:
155 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700156 return True
157 return False
158
159
160def _set_signature(mock, original, instance=False):
161 # creates a function with signature (*args, **kwargs) that delegates to a
162 # mock. It still does signature checking by calling a lambda with the same
163 # signature as the original.
Michael Foord345266a2012-03-14 12:24:34 -0700164
165 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100166 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700167 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700168 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100169 func, sig = result
170 def checksig(*args, **kwargs):
171 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700172 _copy_func_details(func, checksig)
173
174 name = original.__name__
175 if not name.isidentifier():
176 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100177 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700178 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100179 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700180 return mock(*args, **kwargs)""" % name
181 exec (src, context)
182 funcopy = context[name]
Xtreakf7fa62e2018-12-12 13:24:54 +0530183 _setup_func(funcopy, mock, sig)
Michael Foord345266a2012-03-14 12:24:34 -0700184 return funcopy
185
186
Xtreakf7fa62e2018-12-12 13:24:54 +0530187def _setup_func(funcopy, mock, sig):
Michael Foord345266a2012-03-14 12:24:34 -0700188 funcopy.mock = mock
189
Michael Foord345266a2012-03-14 12:24:34 -0700190 def assert_called_with(*args, **kwargs):
191 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700192 def assert_called(*args, **kwargs):
193 return mock.assert_called(*args, **kwargs)
194 def assert_not_called(*args, **kwargs):
195 return mock.assert_not_called(*args, **kwargs)
196 def assert_called_once(*args, **kwargs):
197 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700198 def assert_called_once_with(*args, **kwargs):
199 return mock.assert_called_once_with(*args, **kwargs)
200 def assert_has_calls(*args, **kwargs):
201 return mock.assert_has_calls(*args, **kwargs)
202 def assert_any_call(*args, **kwargs):
203 return mock.assert_any_call(*args, **kwargs)
204 def reset_mock():
205 funcopy.method_calls = _CallList()
206 funcopy.mock_calls = _CallList()
207 mock.reset_mock()
208 ret = funcopy.return_value
209 if _is_instance_mock(ret) and not ret is mock:
210 ret.reset_mock()
211
212 funcopy.called = False
213 funcopy.call_count = 0
214 funcopy.call_args = None
215 funcopy.call_args_list = _CallList()
216 funcopy.method_calls = _CallList()
217 funcopy.mock_calls = _CallList()
218
219 funcopy.return_value = mock.return_value
220 funcopy.side_effect = mock.side_effect
221 funcopy._mock_children = mock._mock_children
222
223 funcopy.assert_called_with = assert_called_with
224 funcopy.assert_called_once_with = assert_called_once_with
225 funcopy.assert_has_calls = assert_has_calls
226 funcopy.assert_any_call = assert_any_call
227 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700228 funcopy.assert_called = assert_called
229 funcopy.assert_not_called = assert_not_called
230 funcopy.assert_called_once = assert_called_once
Xtreakf7fa62e2018-12-12 13:24:54 +0530231 funcopy.__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700232
233 mock._mock_delegate = funcopy
234
235
Xtreakff6b2e62019-05-27 18:26:23 +0530236def _setup_async_mock(mock):
237 mock._is_coroutine = asyncio.coroutines._is_coroutine
238 mock.await_count = 0
239 mock.await_args = None
240 mock.await_args_list = _CallList()
241 mock.awaited = _AwaitEvent(mock)
242
243 # Mock is not configured yet so the attributes are set
244 # to a function and then the corresponding mock helper function
245 # is called when the helper is accessed similar to _setup_func.
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300246 def wrapper(attr, /, *args, **kwargs):
Xtreakff6b2e62019-05-27 18:26:23 +0530247 return getattr(mock.mock, attr)(*args, **kwargs)
248
249 for attribute in ('assert_awaited',
250 'assert_awaited_once',
251 'assert_awaited_with',
252 'assert_awaited_once_with',
253 'assert_any_await',
254 'assert_has_awaits',
255 'assert_not_awaited'):
256
257 # setattr(mock, attribute, wrapper) causes late binding
258 # hence attribute will always be the last value in the loop
259 # Use partial(wrapper, attribute) to ensure the attribute is bound
260 # correctly.
261 setattr(mock, attribute, partial(wrapper, attribute))
262
263
Michael Foord345266a2012-03-14 12:24:34 -0700264def _is_magic(name):
265 return '__%s__' % name[2:-2] == name
266
267
268class _SentinelObject(object):
269 "A unique, named, sentinel object."
270 def __init__(self, name):
271 self.name = name
272
273 def __repr__(self):
274 return 'sentinel.%s' % self.name
275
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200276 def __reduce__(self):
277 return 'sentinel.%s' % self.name
278
Michael Foord345266a2012-03-14 12:24:34 -0700279
280class _Sentinel(object):
281 """Access attributes to return a named object, usable as a sentinel."""
282 def __init__(self):
283 self._sentinels = {}
284
285 def __getattr__(self, name):
286 if name == '__bases__':
287 # Without this help(unittest.mock) raises an exception
288 raise AttributeError
289 return self._sentinels.setdefault(name, _SentinelObject(name))
290
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200291 def __reduce__(self):
292 return 'sentinel'
293
Michael Foord345266a2012-03-14 12:24:34 -0700294
295sentinel = _Sentinel()
296
297DEFAULT = sentinel.DEFAULT
298_missing = sentinel.MISSING
299_deleted = sentinel.DELETED
300
301
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200302_allowed_names = {
303 'return_value', '_mock_return_value', 'side_effect',
304 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
305 '_mock_name', '_mock_new_name'
306}
Michael Foord345266a2012-03-14 12:24:34 -0700307
308
309def _delegating_property(name):
310 _allowed_names.add(name)
311 _the_name = '_mock_' + name
312 def _get(self, name=name, _the_name=_the_name):
313 sig = self._mock_delegate
314 if sig is None:
315 return getattr(self, _the_name)
316 return getattr(sig, name)
317 def _set(self, value, name=name, _the_name=_the_name):
318 sig = self._mock_delegate
319 if sig is None:
320 self.__dict__[_the_name] = value
321 else:
322 setattr(sig, name, value)
323
324 return property(_get, _set)
325
326
327
328class _CallList(list):
329
330 def __contains__(self, value):
331 if not isinstance(value, list):
332 return list.__contains__(self, value)
333 len_value = len(value)
334 len_self = len(self)
335 if len_value > len_self:
336 return False
337
338 for i in range(0, len_self - len_value + 1):
339 sub_list = self[i:i+len_value]
340 if sub_list == value:
341 return True
342 return False
343
344 def __repr__(self):
345 return pprint.pformat(list(self))
346
347
348def _check_and_set_parent(parent, value, name, new_name):
Xtreak9c3f2842019-02-26 03:16:34 +0530349 # function passed to create_autospec will have mock
350 # attribute attached to which parent must be set
351 if isinstance(value, FunctionTypes):
352 try:
353 value = value.mock
354 except AttributeError:
355 pass
356
Michael Foord345266a2012-03-14 12:24:34 -0700357 if not _is_instance_mock(value):
358 return False
359 if ((value._mock_name or value._mock_new_name) or
360 (value._mock_parent is not None) or
361 (value._mock_new_parent is not None)):
362 return False
363
364 _parent = parent
365 while _parent is not None:
366 # setting a mock (value) as a child or return value of itself
367 # should not modify the mock
368 if _parent is value:
369 return False
370 _parent = _parent._mock_new_parent
371
372 if new_name:
373 value._mock_new_parent = parent
374 value._mock_new_name = new_name
375 if name:
376 value._mock_parent = parent
377 value._mock_name = name
378 return True
379
Michael Foord01bafdc2014-04-14 16:09:42 -0400380# Internal class to identify if we wrapped an iterator object or not.
381class _MockIter(object):
382 def __init__(self, obj):
383 self.obj = iter(obj)
Michael Foord01bafdc2014-04-14 16:09:42 -0400384 def __next__(self):
385 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700386
387class Base(object):
388 _mock_return_value = DEFAULT
389 _mock_side_effect = None
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300390 def __init__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700391 pass
392
393
394
395class NonCallableMock(Base):
396 """A non-callable version of `Mock`"""
397
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300398 def __new__(cls, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700399 # every instance has its own class
400 # so we can create magic methods on the
401 # class without stomping on other mocks
Lisa Roach77b3b772019-05-20 09:19:53 -0700402 bases = (cls,)
403 if not issubclass(cls, AsyncMock):
404 # Check if spec is an async object or function
405 sig = inspect.signature(NonCallableMock.__init__)
406 bound_args = sig.bind_partial(cls, *args, **kw).arguments
407 spec_arg = [
408 arg for arg in bound_args.keys()
409 if arg.startswith('spec')
410 ]
411 if spec_arg:
412 # what if spec_set is different than spec?
413 if _is_async_obj(bound_args[spec_arg[0]]):
414 bases = (AsyncMockMixin, cls,)
415 new = type(cls.__name__, bases, {'__doc__': cls.__doc__})
Michael Foord345266a2012-03-14 12:24:34 -0700416 instance = object.__new__(new)
417 return instance
418
419
420 def __init__(
421 self, spec=None, wraps=None, name=None, spec_set=None,
422 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530423 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700424 ):
425 if _new_parent is None:
426 _new_parent = parent
427
428 __dict__ = self.__dict__
429 __dict__['_mock_parent'] = parent
430 __dict__['_mock_name'] = name
431 __dict__['_mock_new_name'] = _new_name
432 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100433 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700434
435 if spec_set is not None:
436 spec = spec_set
437 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100438 if _eat_self is None:
439 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700440
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100441 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700442
443 __dict__['_mock_children'] = {}
444 __dict__['_mock_wraps'] = wraps
445 __dict__['_mock_delegate'] = None
446
447 __dict__['_mock_called'] = False
448 __dict__['_mock_call_args'] = None
449 __dict__['_mock_call_count'] = 0
450 __dict__['_mock_call_args_list'] = _CallList()
451 __dict__['_mock_mock_calls'] = _CallList()
452
453 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530454 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700455
456 if kwargs:
457 self.configure_mock(**kwargs)
458
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000459 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700460 spec, wraps, name, spec_set, parent,
461 _spec_state
462 )
463
464
465 def attach_mock(self, mock, attribute):
466 """
467 Attach a mock as an attribute of this one, replacing its name and
468 parent. Calls to the attached mock will be recorded in the
469 `method_calls` and `mock_calls` attributes of this one."""
470 mock._mock_parent = None
471 mock._mock_new_parent = None
472 mock._mock_name = ''
473 mock._mock_new_name = None
474
475 setattr(self, attribute, mock)
476
477
478 def mock_add_spec(self, spec, spec_set=False):
479 """Add a spec to a mock. `spec` can either be an object or a
480 list of strings. Only attributes on the `spec` can be fetched as
481 attributes from the mock.
482
483 If `spec_set` is True then only attributes on the spec can be set."""
484 self._mock_add_spec(spec, spec_set)
485
486
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100487 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
488 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700489 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100490 _spec_signature = None
Lisa Roach77b3b772019-05-20 09:19:53 -0700491 _spec_asyncs = []
492
493 for attr in dir(spec):
494 if asyncio.iscoroutinefunction(getattr(spec, attr, None)):
495 _spec_asyncs.append(attr)
Michael Foord345266a2012-03-14 12:24:34 -0700496
497 if spec is not None and not _is_list(spec):
498 if isinstance(spec, type):
499 _spec_class = spec
500 else:
Chris Withersadbf1782019-05-01 23:04:04 +0100501 _spec_class = type(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100502 res = _get_signature_object(spec,
503 _spec_as_instance, _eat_self)
504 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700505
506 spec = dir(spec)
507
508 __dict__ = self.__dict__
509 __dict__['_spec_class'] = _spec_class
510 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100511 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700512 __dict__['_mock_methods'] = spec
Lisa Roach77b3b772019-05-20 09:19:53 -0700513 __dict__['_spec_asyncs'] = _spec_asyncs
Michael Foord345266a2012-03-14 12:24:34 -0700514
515 def __get_return_value(self):
516 ret = self._mock_return_value
517 if self._mock_delegate is not None:
518 ret = self._mock_delegate.return_value
519
520 if ret is DEFAULT:
521 ret = self._get_child_mock(
522 _new_parent=self, _new_name='()'
523 )
524 self.return_value = ret
525 return ret
526
527
528 def __set_return_value(self, value):
529 if self._mock_delegate is not None:
530 self._mock_delegate.return_value = value
531 else:
532 self._mock_return_value = value
533 _check_and_set_parent(self, value, None, '()')
534
535 __return_value_doc = "The value to be returned when the mock is called."
536 return_value = property(__get_return_value, __set_return_value,
537 __return_value_doc)
538
539
540 @property
541 def __class__(self):
542 if self._spec_class is None:
543 return type(self)
544 return self._spec_class
545
546 called = _delegating_property('called')
547 call_count = _delegating_property('call_count')
548 call_args = _delegating_property('call_args')
549 call_args_list = _delegating_property('call_args_list')
550 mock_calls = _delegating_property('mock_calls')
551
552
553 def __get_side_effect(self):
554 delegated = self._mock_delegate
555 if delegated is None:
556 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400557 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200558 if (sf is not None and not callable(sf)
559 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400560 sf = _MockIter(sf)
561 delegated.side_effect = sf
562 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700563
564 def __set_side_effect(self, value):
565 value = _try_iter(value)
566 delegated = self._mock_delegate
567 if delegated is None:
568 self._mock_side_effect = value
569 else:
570 delegated.side_effect = value
571
572 side_effect = property(__get_side_effect, __set_side_effect)
573
574
Kushal Das9cd39a12016-06-02 10:20:16 -0700575 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700576 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200577 if visited is None:
578 visited = []
579 if id(self) in visited:
580 return
581 visited.append(id(self))
582
Michael Foord345266a2012-03-14 12:24:34 -0700583 self.called = False
584 self.call_args = None
585 self.call_count = 0
586 self.mock_calls = _CallList()
587 self.call_args_list = _CallList()
588 self.method_calls = _CallList()
589
Kushal Das9cd39a12016-06-02 10:20:16 -0700590 if return_value:
591 self._mock_return_value = DEFAULT
592 if side_effect:
593 self._mock_side_effect = None
594
Michael Foord345266a2012-03-14 12:24:34 -0700595 for child in self._mock_children.values():
Xtreakedeca922018-12-01 15:33:54 +0530596 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100597 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200598 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700599
600 ret = self._mock_return_value
601 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200602 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700603
604
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300605 def configure_mock(self, /, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700606 """Set attributes on the mock through keyword arguments.
607
608 Attributes plus return values and side effects can be set on child
609 mocks using standard dot notation and unpacking a dictionary in the
610 method call:
611
612 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
613 >>> mock.configure_mock(**attrs)"""
614 for arg, val in sorted(kwargs.items(),
615 # we sort on the number of dots so that
616 # attributes are set before we set attributes on
617 # attributes
618 key=lambda entry: entry[0].count('.')):
619 args = arg.split('.')
620 final = args.pop()
621 obj = self
622 for entry in args:
623 obj = getattr(obj, entry)
624 setattr(obj, final, val)
625
626
627 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530628 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700629 raise AttributeError(name)
630 elif self._mock_methods is not None:
631 if name not in self._mock_methods or name in _all_magics:
632 raise AttributeError("Mock object has no attribute %r" % name)
633 elif _is_magic(name):
634 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530635 if not self._mock_unsafe:
636 if name.startswith(('assert', 'assret')):
Zackery Spytzb9b08cd2019-05-08 11:32:24 -0600637 raise AttributeError("Attributes cannot start with 'assert' "
638 "or 'assret'")
Michael Foord345266a2012-03-14 12:24:34 -0700639
640 result = self._mock_children.get(name)
641 if result is _deleted:
642 raise AttributeError(name)
643 elif result is None:
644 wraps = None
645 if self._mock_wraps is not None:
646 # XXXX should we get the attribute without triggering code
647 # execution?
648 wraps = getattr(self._mock_wraps, name)
649
650 result = self._get_child_mock(
651 parent=self, name=name, wraps=wraps, _new_name=name,
652 _new_parent=self
653 )
654 self._mock_children[name] = result
655
656 elif isinstance(result, _SpecState):
657 result = create_autospec(
658 result.spec, result.spec_set, result.instance,
659 result.parent, result.name
660 )
661 self._mock_children[name] = result
662
663 return result
664
665
Mario Corchero552be9d2017-10-17 12:35:11 +0100666 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700667 _name_list = [self._mock_new_name]
668 _parent = self._mock_new_parent
669 last = self
670
671 dot = '.'
672 if _name_list == ['()']:
673 dot = ''
Chris Withersadbf1782019-05-01 23:04:04 +0100674
Michael Foord345266a2012-03-14 12:24:34 -0700675 while _parent is not None:
676 last = _parent
677
678 _name_list.append(_parent._mock_new_name + dot)
679 dot = '.'
680 if _parent._mock_new_name == '()':
681 dot = ''
682
683 _parent = _parent._mock_new_parent
684
Michael Foord345266a2012-03-14 12:24:34 -0700685 _name_list = list(reversed(_name_list))
686 _first = last._mock_name or 'mock'
687 if len(_name_list) > 1:
688 if _name_list[1] not in ('()', '().'):
689 _first += '.'
690 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100691 return ''.join(_name_list)
692
693 def __repr__(self):
694 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700695
696 name_string = ''
697 if name not in ('mock', 'mock.'):
698 name_string = ' name=%r' % name
699
700 spec_string = ''
701 if self._spec_class is not None:
702 spec_string = ' spec=%r'
703 if self._spec_set:
704 spec_string = ' spec_set=%r'
705 spec_string = spec_string % self._spec_class.__name__
706 return "<%s%s%s id='%s'>" % (
707 type(self).__name__,
708 name_string,
709 spec_string,
710 id(self)
711 )
712
713
714 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700715 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100716 if not FILTER_DIR:
717 return object.__dir__(self)
718
Michael Foord345266a2012-03-14 12:24:34 -0700719 extras = self._mock_methods or []
720 from_type = dir(type(self))
721 from_dict = list(self.__dict__)
Mario Corchero0df635c2019-04-30 19:56:36 +0100722 from_child_mocks = [
723 m_name for m_name, m_value in self._mock_children.items()
724 if m_value is not _deleted]
Michael Foord345266a2012-03-14 12:24:34 -0700725
Michael Foord313f85f2012-03-25 18:16:07 +0100726 from_type = [e for e in from_type if not e.startswith('_')]
727 from_dict = [e for e in from_dict if not e.startswith('_') or
728 _is_magic(e)]
Mario Corchero0df635c2019-04-30 19:56:36 +0100729 return sorted(set(extras + from_type + from_dict + from_child_mocks))
Michael Foord345266a2012-03-14 12:24:34 -0700730
731
732 def __setattr__(self, name, value):
733 if name in _allowed_names:
734 # property setters go through here
735 return object.__setattr__(self, name, value)
736 elif (self._spec_set and self._mock_methods is not None and
737 name not in self._mock_methods and
738 name not in self.__dict__):
739 raise AttributeError("Mock object has no attribute '%s'" % name)
740 elif name in _unsupported_magics:
741 msg = 'Attempting to set unsupported magic method %r.' % name
742 raise AttributeError(msg)
743 elif name in _all_magics:
744 if self._mock_methods is not None and name not in self._mock_methods:
745 raise AttributeError("Mock object has no attribute '%s'" % name)
746
747 if not _is_instance_mock(value):
748 setattr(type(self), name, _get_method(name, value))
749 original = value
750 value = lambda *args, **kw: original(self, *args, **kw)
751 else:
752 # only set _new_name and not name so that mock_calls is tracked
753 # but not method calls
754 _check_and_set_parent(self, value, None, name)
755 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100756 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700757 elif name == '__class__':
758 self._spec_class = value
759 return
760 else:
761 if _check_and_set_parent(self, value, name, name):
762 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100763
764 if self._mock_sealed and not hasattr(self, name):
765 mock_name = f'{self._extract_mock_name()}.{name}'
766 raise AttributeError(f'Cannot set {mock_name}')
767
Michael Foord345266a2012-03-14 12:24:34 -0700768 return object.__setattr__(self, name, value)
769
770
771 def __delattr__(self, name):
772 if name in _all_magics and name in type(self).__dict__:
773 delattr(type(self), name)
774 if name not in self.__dict__:
775 # for magic methods that are still MagicProxy objects and
776 # not set on the instance itself
777 return
778
Michael Foord345266a2012-03-14 12:24:34 -0700779 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000780 if name in self.__dict__:
Xtreak830b43d2019-04-14 00:42:33 +0530781 _safe_super(NonCallableMock, self).__delattr__(name)
Pablo Galindo222d3032019-01-21 08:57:46 +0000782 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700783 raise AttributeError(name)
784 if obj is not _missing:
785 del self._mock_children[name]
786 self._mock_children[name] = _deleted
787
788
Michael Foord345266a2012-03-14 12:24:34 -0700789 def _format_mock_call_signature(self, args, kwargs):
790 name = self._mock_name or 'mock'
791 return _format_call_signature(name, args, kwargs)
792
793
Xtreak0ae022c2019-05-29 12:32:26 +0530794 def _format_mock_failure_message(self, args, kwargs, action='call'):
795 message = 'expected %s not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700796 expected_string = self._format_mock_call_signature(args, kwargs)
797 call_args = self.call_args
Michael Foord345266a2012-03-14 12:24:34 -0700798 actual_string = self._format_mock_call_signature(*call_args)
Xtreak0ae022c2019-05-29 12:32:26 +0530799 return message % (action, expected_string, actual_string)
Michael Foord345266a2012-03-14 12:24:34 -0700800
801
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100802 def _call_matcher(self, _call):
803 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000804 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100805 comparison key suitable for matching with other calls.
806 This is a best effort method which relies on the spec's signature,
807 if available, or falls back on the arguments themselves.
808 """
809 sig = self._spec_signature
810 if sig is not None:
811 if len(_call) == 2:
812 name = ''
813 args, kwargs = _call
814 else:
815 name, args, kwargs = _call
816 try:
817 return name, sig.bind(*args, **kwargs)
818 except TypeError as e:
819 return e.with_traceback(None)
820 else:
821 return _call
822
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300823 def assert_not_called(self):
Kushal Das8af9db32014-04-17 01:36:14 +0530824 """assert that the mock was never called.
825 """
Kushal Das8af9db32014-04-17 01:36:14 +0530826 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100827 msg = ("Expected '%s' to not have been called. Called %s times.%s"
828 % (self._mock_name or 'mock',
829 self.call_count,
830 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530831 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100832
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300833 def assert_called(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100834 """assert that the mock was called at least once
835 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100836 if self.call_count == 0:
837 msg = ("Expected '%s' to have been called." %
838 self._mock_name or 'mock')
839 raise AssertionError(msg)
840
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300841 def assert_called_once(self):
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100842 """assert that the mock was called only once.
843 """
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100844 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100845 msg = ("Expected '%s' to have been called once. Called %s times.%s"
846 % (self._mock_name or 'mock',
847 self.call_count,
848 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100849 raise AssertionError(msg)
850
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300851 def assert_called_with(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700852 """assert that the mock was called with the specified arguments.
853
854 Raises an AssertionError if the args and keyword args passed in are
855 different to the last call to the mock."""
Michael Foord345266a2012-03-14 12:24:34 -0700856 if self.call_args is None:
857 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800858 actual = 'not called.'
859 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
860 % (expected, actual))
861 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700862
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100863 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700864 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100865 return msg
866 expected = self._call_matcher((args, kwargs))
867 actual = self._call_matcher(self.call_args)
868 if expected != actual:
869 cause = expected if isinstance(expected, Exception) else None
870 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700871
872
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300873 def assert_called_once_with(self, /, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100874 """assert that the mock was called exactly once and that that call was
875 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700876 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100877 msg = ("Expected '%s' to be called once. Called %s times.%s"
878 % (self._mock_name or 'mock',
879 self.call_count,
880 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700881 raise AssertionError(msg)
882 return self.assert_called_with(*args, **kwargs)
883
884
885 def assert_has_calls(self, calls, any_order=False):
886 """assert the mock has been called with the specified calls.
887 The `mock_calls` list is checked for the calls.
888
889 If `any_order` is False (the default) then the calls must be
890 sequential. There can be extra calls before or after the
891 specified calls.
892
893 If `any_order` is True then the calls can be in any order, but
894 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100895 expected = [self._call_matcher(c) for c in calls]
896 cause = expected if isinstance(expected, Exception) else None
897 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700898 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100899 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700900 raise AssertionError(
Petter Strandmark47d94242018-10-28 21:37:10 +0100901 'Calls not found.\nExpected: %r%s'
902 % (_CallList(calls), self._calls_repr(prefix="Actual"))
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100903 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700904 return
905
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100906 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700907
908 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100909 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700910 try:
911 all_calls.remove(kall)
912 except ValueError:
913 not_found.append(kall)
914 if not_found:
915 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400916 '%r does not contain all of %r in its call list, '
917 'found %r instead' % (self._mock_name or 'mock',
918 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100919 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700920
921
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300922 def assert_any_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -0700923 """assert the mock has been called with the specified arguments.
924
925 The assert passes if the mock has *ever* been called, unlike
926 `assert_called_with` and `assert_called_once_with` that only pass if
927 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100928 expected = self._call_matcher((args, kwargs))
929 actual = [self._call_matcher(c) for c in self.call_args_list]
930 if expected not in actual:
931 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700932 expected_string = self._format_mock_call_signature(args, kwargs)
933 raise AssertionError(
934 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100935 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700936
937
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300938 def _get_child_mock(self, /, **kw):
Michael Foord345266a2012-03-14 12:24:34 -0700939 """Create the child mocks for attributes and return value.
940 By default child mocks will be the same type as the parent.
941 Subclasses of Mock may want to override this to customize the way
942 child mocks are made.
943
944 For non-callable mocks the callable variant will be used (rather than
945 any custom subclass)."""
Lisa Roach77b3b772019-05-20 09:19:53 -0700946 _new_name = kw.get("_new_name")
947 if _new_name in self.__dict__['_spec_asyncs']:
948 return AsyncMock(**kw)
949
Michael Foord345266a2012-03-14 12:24:34 -0700950 _type = type(self)
Lisa Roach77b3b772019-05-20 09:19:53 -0700951 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
952 klass = AsyncMock
953 if issubclass(_type, AsyncMockMixin):
954 klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -0700955 if not issubclass(_type, CallableMixin):
956 if issubclass(_type, NonCallableMagicMock):
957 klass = MagicMock
958 elif issubclass(_type, NonCallableMock) :
959 klass = Mock
960 else:
961 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +0100962
963 if self._mock_sealed:
964 attribute = "." + kw["name"] if "name" in kw else "()"
965 mock_name = self._extract_mock_name() + attribute
966 raise AttributeError(mock_name)
967
Michael Foord345266a2012-03-14 12:24:34 -0700968 return klass(**kw)
969
970
Petter Strandmark47d94242018-10-28 21:37:10 +0100971 def _calls_repr(self, prefix="Calls"):
972 """Renders self.mock_calls as a string.
973
974 Example: "\nCalls: [call(1), call(2)]."
975
976 If self.mock_calls is empty, an empty string is returned. The
977 output will be truncated if very long.
978 """
979 if not self.mock_calls:
980 return ""
981 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
982
983
Michael Foord345266a2012-03-14 12:24:34 -0700984
985def _try_iter(obj):
986 if obj is None:
987 return obj
988 if _is_exception(obj):
989 return obj
990 if _callable(obj):
991 return obj
992 try:
993 return iter(obj)
994 except TypeError:
995 # XXXX backwards compatibility
996 # but this will blow up on first call - so maybe we should fail early?
997 return obj
998
999
Michael Foord345266a2012-03-14 12:24:34 -07001000class CallableMixin(Base):
1001
1002 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
1003 wraps=None, name=None, spec_set=None, parent=None,
1004 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
1005 self.__dict__['_mock_return_value'] = return_value
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001006 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -07001007 spec, wraps, name, spec_set, parent,
1008 _spec_state, _new_name, _new_parent, **kwargs
1009 )
1010
1011 self.side_effect = side_effect
1012
1013
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001014 def _mock_check_sig(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001015 # stub method that can be replaced with one with a specific signature
1016 pass
1017
1018
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001019 def __call__(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001020 # can't use self in-case a function / method we are mocking uses self
1021 # in the signature
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001022 self._mock_check_sig(*args, **kwargs)
1023 return self._mock_call(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -07001024
1025
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001026 def _mock_call(self, /, *args, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001027 self.called = True
1028 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001029
Chris Withers8ca0fa92018-12-03 21:31:37 +00001030 # handle call_args
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001031 _call = _Call((args, kwargs), two=True)
1032 self.call_args = _call
1033 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -07001034
Chris Withers8ca0fa92018-12-03 21:31:37 +00001035 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001036 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +00001037 method_call_name = self._mock_name
1038
1039 # initial stuff for mock_calls:
1040 mock_call_name = self._mock_new_name
1041 is_a_call = mock_call_name == '()'
1042 self.mock_calls.append(_Call(('', args, kwargs)))
1043
1044 # follow up the chain of mocks:
1045 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001046 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001047
Chris Withers8ca0fa92018-12-03 21:31:37 +00001048 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001049 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001050 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001051 do_method_calls = _new_parent._mock_parent is not None
1052 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001053 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001054
Chris Withers8ca0fa92018-12-03 21:31:37 +00001055 # handle mock_calls:
1056 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001057 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001058
1059 if _new_parent._mock_new_name:
1060 if is_a_call:
1061 dot = ''
1062 else:
1063 dot = '.'
1064 is_a_call = _new_parent._mock_new_name == '()'
1065 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1066
1067 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001068 _new_parent = _new_parent._mock_new_parent
1069
Michael Foord345266a2012-03-14 12:24:34 -07001070 effect = self.side_effect
1071 if effect is not None:
1072 if _is_exception(effect):
1073 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001074 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001075 result = next(effect)
1076 if _is_exception(result):
1077 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001078 else:
1079 result = effect(*args, **kwargs)
1080
1081 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001082 return result
Michael Foord345266a2012-03-14 12:24:34 -07001083
Mario Corcherof05df0a2018-12-08 11:25:02 +00001084 if self._mock_return_value is not DEFAULT:
1085 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001086
Mario Corcherof05df0a2018-12-08 11:25:02 +00001087 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001088 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001089
1090 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001091
1092
1093
1094class Mock(CallableMixin, NonCallableMock):
1095 """
1096 Create a new `Mock` object. `Mock` takes several optional arguments
1097 that specify the behaviour of the Mock object:
1098
1099 * `spec`: This can be either a list of strings or an existing object (a
1100 class or instance) that acts as the specification for the mock object. If
1101 you pass in an object then a list of strings is formed by calling dir on
1102 the object (excluding unsupported magic attributes and methods). Accessing
1103 any attribute not in this list will raise an `AttributeError`.
1104
1105 If `spec` is an object (rather than a list of strings) then
1106 `mock.__class__` returns the class of the spec object. This allows mocks
1107 to pass `isinstance` tests.
1108
1109 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1110 or get an attribute on the mock that isn't on the object passed as
1111 `spec_set` will raise an `AttributeError`.
1112
1113 * `side_effect`: A function to be called whenever the Mock is called. See
1114 the `side_effect` attribute. Useful for raising exceptions or
1115 dynamically changing return values. The function is called with the same
1116 arguments as the mock, and unless it returns `DEFAULT`, the return
1117 value of this function is used as the return value.
1118
Michael Foord2cd48732012-04-21 15:52:11 +01001119 If `side_effect` is an iterable then each call to the mock will return
1120 the next value from the iterable. If any of the members of the iterable
1121 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001122
Michael Foord345266a2012-03-14 12:24:34 -07001123 * `return_value`: The value returned when the mock is called. By default
1124 this is a new Mock (created on first access). See the
1125 `return_value` attribute.
1126
Michael Foord0682a0c2012-04-13 20:51:20 +01001127 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1128 calling the Mock will pass the call through to the wrapped object
1129 (returning the real result). Attribute access on the mock will return a
1130 Mock object that wraps the corresponding attribute of the wrapped object
1131 (so attempting to access an attribute that doesn't exist will raise an
1132 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001133
1134 If the mock has an explicit `return_value` set then calls are not passed
1135 to the wrapped object and the `return_value` is returned instead.
1136
1137 * `name`: If the mock has a name then it will be used in the repr of the
1138 mock. This can be useful for debugging. The name is propagated to child
1139 mocks.
1140
1141 Mocks can also be called with arbitrary keyword arguments. These will be
1142 used to set attributes on the mock after it is created.
1143 """
1144
1145
Michael Foord345266a2012-03-14 12:24:34 -07001146def _dot_lookup(thing, comp, import_path):
1147 try:
1148 return getattr(thing, comp)
1149 except AttributeError:
1150 __import__(import_path)
1151 return getattr(thing, comp)
1152
1153
1154def _importer(target):
1155 components = target.split('.')
1156 import_path = components.pop(0)
1157 thing = __import__(import_path)
1158
1159 for comp in components:
1160 import_path += ".%s" % comp
1161 thing = _dot_lookup(thing, comp, import_path)
1162 return thing
1163
1164
1165def _is_started(patcher):
1166 # XXXX horrible
1167 return hasattr(patcher, 'is_local')
1168
1169
1170class _patch(object):
1171
1172 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001173 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001174
1175 def __init__(
1176 self, getter, attribute, new, spec, create,
1177 spec_set, autospec, new_callable, kwargs
1178 ):
1179 if new_callable is not None:
1180 if new is not DEFAULT:
1181 raise ValueError(
1182 "Cannot use 'new' and 'new_callable' together"
1183 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001184 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001185 raise ValueError(
1186 "Cannot use 'autospec' and 'new_callable' together"
1187 )
1188
1189 self.getter = getter
1190 self.attribute = attribute
1191 self.new = new
1192 self.new_callable = new_callable
1193 self.spec = spec
1194 self.create = create
1195 self.has_local = False
1196 self.spec_set = spec_set
1197 self.autospec = autospec
1198 self.kwargs = kwargs
1199 self.additional_patchers = []
1200
1201
1202 def copy(self):
1203 patcher = _patch(
1204 self.getter, self.attribute, self.new, self.spec,
1205 self.create, self.spec_set,
1206 self.autospec, self.new_callable, self.kwargs
1207 )
1208 patcher.attribute_name = self.attribute_name
1209 patcher.additional_patchers = [
1210 p.copy() for p in self.additional_patchers
1211 ]
1212 return patcher
1213
1214
1215 def __call__(self, func):
1216 if isinstance(func, type):
1217 return self.decorate_class(func)
Xtreak436c2b02019-05-28 12:37:39 +05301218 if inspect.iscoroutinefunction(func):
1219 return self.decorate_async_callable(func)
Michael Foord345266a2012-03-14 12:24:34 -07001220 return self.decorate_callable(func)
1221
1222
1223 def decorate_class(self, klass):
1224 for attr in dir(klass):
1225 if not attr.startswith(patch.TEST_PREFIX):
1226 continue
1227
1228 attr_value = getattr(klass, attr)
1229 if not hasattr(attr_value, "__call__"):
1230 continue
1231
1232 patcher = self.copy()
1233 setattr(klass, attr, patcher(attr_value))
1234 return klass
1235
1236
Xtreak436c2b02019-05-28 12:37:39 +05301237 @contextlib.contextmanager
1238 def decoration_helper(self, patched, args, keywargs):
1239 extra_args = []
1240 entered_patchers = []
1241 patching = None
1242
1243 exc_info = tuple()
1244 try:
1245 for patching in patched.patchings:
1246 arg = patching.__enter__()
1247 entered_patchers.append(patching)
1248 if patching.attribute_name is not None:
1249 keywargs.update(arg)
1250 elif patching.new is DEFAULT:
1251 extra_args.append(arg)
1252
1253 args += tuple(extra_args)
1254 yield (args, keywargs)
1255 except:
1256 if (patching not in entered_patchers and
1257 _is_started(patching)):
1258 # the patcher may have been started, but an exception
1259 # raised whilst entering one of its additional_patchers
1260 entered_patchers.append(patching)
1261 # Pass the exception to __exit__
1262 exc_info = sys.exc_info()
1263 # re-raise the exception
1264 raise
1265 finally:
1266 for patching in reversed(entered_patchers):
1267 patching.__exit__(*exc_info)
1268
1269
Michael Foord345266a2012-03-14 12:24:34 -07001270 def decorate_callable(self, func):
Xtreak436c2b02019-05-28 12:37:39 +05301271 # NB. Keep the method in sync with decorate_async_callable()
Michael Foord345266a2012-03-14 12:24:34 -07001272 if hasattr(func, 'patchings'):
1273 func.patchings.append(self)
1274 return func
1275
1276 @wraps(func)
1277 def patched(*args, **keywargs):
Xtreak436c2b02019-05-28 12:37:39 +05301278 with self.decoration_helper(patched,
1279 args,
1280 keywargs) as (newargs, newkeywargs):
1281 return func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001282
Xtreak436c2b02019-05-28 12:37:39 +05301283 patched.patchings = [self]
1284 return patched
Michael Foord345266a2012-03-14 12:24:34 -07001285
Xtreak436c2b02019-05-28 12:37:39 +05301286
1287 def decorate_async_callable(self, func):
1288 # NB. Keep the method in sync with decorate_callable()
1289 if hasattr(func, 'patchings'):
1290 func.patchings.append(self)
1291 return func
1292
1293 @wraps(func)
1294 async def patched(*args, **keywargs):
1295 with self.decoration_helper(patched,
1296 args,
1297 keywargs) as (newargs, newkeywargs):
1298 return await func(*newargs, **newkeywargs)
Michael Foord345266a2012-03-14 12:24:34 -07001299
1300 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001301 return patched
1302
1303
1304 def get_original(self):
1305 target = self.getter()
1306 name = self.attribute
1307
1308 original = DEFAULT
1309 local = False
1310
1311 try:
1312 original = target.__dict__[name]
1313 except (AttributeError, KeyError):
1314 original = getattr(target, name, DEFAULT)
1315 else:
1316 local = True
1317
Michael Foordfddcfa22014-04-14 16:25:20 -04001318 if name in _builtins and isinstance(target, ModuleType):
1319 self.create = True
1320
Michael Foord345266a2012-03-14 12:24:34 -07001321 if not self.create and original is DEFAULT:
1322 raise AttributeError(
1323 "%s does not have the attribute %r" % (target, name)
1324 )
1325 return original, local
1326
1327
1328 def __enter__(self):
1329 """Perform the patch."""
1330 new, spec, spec_set = self.new, self.spec, self.spec_set
1331 autospec, kwargs = self.autospec, self.kwargs
1332 new_callable = self.new_callable
1333 self.target = self.getter()
1334
Michael Foord50a8c0e2012-03-25 18:57:58 +01001335 # normalise False to None
1336 if spec is False:
1337 spec = None
1338 if spec_set is False:
1339 spec_set = None
1340 if autospec is False:
1341 autospec = None
1342
1343 if spec is not None and autospec is not None:
1344 raise TypeError("Can't specify spec and autospec")
1345 if ((spec is not None or autospec is not None) and
1346 spec_set not in (True, None)):
1347 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1348
Michael Foord345266a2012-03-14 12:24:34 -07001349 original, local = self.get_original()
1350
Michael Foord50a8c0e2012-03-25 18:57:58 +01001351 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001352 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001353 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001354 # set spec to the object we are replacing
1355 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001356 if spec_set is True:
1357 spec_set = original
1358 spec = None
1359 elif spec is not None:
1360 if spec_set is True:
1361 spec_set = spec
1362 spec = None
1363 elif spec_set is True:
1364 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001365
Michael Foord50a8c0e2012-03-25 18:57:58 +01001366 if spec is not None or spec_set is not None:
1367 if original is DEFAULT:
1368 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001369 if isinstance(original, type):
1370 # If we're patching out a class and there is a spec
1371 inherit = True
Lisa Roach77b3b772019-05-20 09:19:53 -07001372 if spec is None and _is_async_obj(original):
1373 Klass = AsyncMock
1374 else:
1375 Klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -07001376 _kwargs = {}
1377 if new_callable is not None:
1378 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001379 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001380 this_spec = spec
1381 if spec_set is not None:
1382 this_spec = spec_set
1383 if _is_list(this_spec):
1384 not_callable = '__call__' not in this_spec
1385 else:
1386 not_callable = not callable(this_spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07001387 if _is_async_obj(this_spec):
1388 Klass = AsyncMock
1389 elif not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001390 Klass = NonCallableMagicMock
1391
1392 if spec is not None:
1393 _kwargs['spec'] = spec
1394 if spec_set is not None:
1395 _kwargs['spec_set'] = spec_set
1396
1397 # add a name to mocks
1398 if (isinstance(Klass, type) and
1399 issubclass(Klass, NonCallableMock) and self.attribute):
1400 _kwargs['name'] = self.attribute
1401
1402 _kwargs.update(kwargs)
1403 new = Klass(**_kwargs)
1404
1405 if inherit and _is_instance_mock(new):
1406 # we can only tell if the instance should be callable if the
1407 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001408 this_spec = spec
1409 if spec_set is not None:
1410 this_spec = spec_set
1411 if (not _is_list(this_spec) and not
1412 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001413 Klass = NonCallableMagicMock
1414
1415 _kwargs.pop('name')
1416 new.return_value = Klass(_new_parent=new, _new_name='()',
1417 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001418 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001419 # spec is ignored, new *must* be default, spec_set is treated
1420 # as a boolean. Should we check spec is not None and that spec_set
1421 # is a bool?
1422 if new is not DEFAULT:
1423 raise TypeError(
1424 "autospec creates the mock for you. Can't specify "
1425 "autospec and new."
1426 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001427 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001428 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001429 spec_set = bool(spec_set)
1430 if autospec is True:
1431 autospec = original
1432
1433 new = create_autospec(autospec, spec_set=spec_set,
1434 _name=self.attribute, **kwargs)
1435 elif kwargs:
1436 # can't set keyword args when we aren't creating the mock
1437 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1438 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1439
1440 new_attr = new
1441
1442 self.temp_original = original
1443 self.is_local = local
1444 setattr(self.target, self.attribute, new_attr)
1445 if self.attribute_name is not None:
1446 extra_args = {}
1447 if self.new is DEFAULT:
1448 extra_args[self.attribute_name] = new
1449 for patching in self.additional_patchers:
1450 arg = patching.__enter__()
1451 if patching.new is DEFAULT:
1452 extra_args.update(arg)
1453 return extra_args
1454
1455 return new
1456
1457
Michael Foord50a8c0e2012-03-25 18:57:58 +01001458 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001459 """Undo the patch."""
1460 if not _is_started(self):
Xtreak02b84cb2019-03-29 02:38:43 +05301461 return
Michael Foord345266a2012-03-14 12:24:34 -07001462
1463 if self.is_local and self.temp_original is not DEFAULT:
1464 setattr(self.target, self.attribute, self.temp_original)
1465 else:
1466 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001467 if not self.create and (not hasattr(self.target, self.attribute) or
1468 self.attribute in ('__doc__', '__module__',
1469 '__defaults__', '__annotations__',
1470 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001471 # needed for proxy objects like django settings
1472 setattr(self.target, self.attribute, self.temp_original)
1473
1474 del self.temp_original
1475 del self.is_local
1476 del self.target
1477 for patcher in reversed(self.additional_patchers):
1478 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001479 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001480
Michael Foordf7c41582012-06-10 20:36:32 +01001481
1482 def start(self):
1483 """Activate a patch, returning any created mock."""
1484 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001485 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001486 return result
1487
1488
1489 def stop(self):
1490 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001491 try:
1492 self._active_patches.remove(self)
1493 except ValueError:
1494 # If the patch hasn't been started this will fail
1495 pass
1496
Michael Foordf7c41582012-06-10 20:36:32 +01001497 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001498
1499
1500
1501def _get_target(target):
1502 try:
1503 target, attribute = target.rsplit('.', 1)
1504 except (TypeError, ValueError):
1505 raise TypeError("Need a valid target to patch. You supplied: %r" %
1506 (target,))
1507 getter = lambda: _importer(target)
1508 return getter, attribute
1509
1510
1511def _patch_object(
1512 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001513 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001514 new_callable=None, **kwargs
1515 ):
1516 """
Michael Foord345266a2012-03-14 12:24:34 -07001517 patch the named member (`attribute`) on an object (`target`) with a mock
1518 object.
1519
1520 `patch.object` can be used as a decorator, class decorator or a context
1521 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1522 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1523 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1524 the mock object it creates.
1525
1526 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1527 for choosing which methods to wrap.
1528 """
1529 getter = lambda: target
1530 return _patch(
1531 getter, attribute, new, spec, create,
1532 spec_set, autospec, new_callable, kwargs
1533 )
1534
1535
Michael Foord50a8c0e2012-03-25 18:57:58 +01001536def _patch_multiple(target, spec=None, create=False, spec_set=None,
1537 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001538 """Perform multiple patches in a single call. It takes the object to be
1539 patched (either as an object or a string to fetch the object by importing)
1540 and keyword arguments for the patches::
1541
1542 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1543 ...
1544
1545 Use `DEFAULT` as the value if you want `patch.multiple` to create
1546 mocks for you. In this case the created mocks are passed into a decorated
1547 function by keyword, and a dictionary is returned when `patch.multiple` is
1548 used as a context manager.
1549
1550 `patch.multiple` can be used as a decorator, class decorator or a context
1551 manager. The arguments `spec`, `spec_set`, `create`,
1552 `autospec` and `new_callable` have the same meaning as for `patch`. These
1553 arguments will be applied to *all* patches done by `patch.multiple`.
1554
1555 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1556 for choosing which methods to wrap.
1557 """
1558 if type(target) is str:
1559 getter = lambda: _importer(target)
1560 else:
1561 getter = lambda: target
1562
1563 if not kwargs:
1564 raise ValueError(
1565 'Must supply at least one keyword argument with patch.multiple'
1566 )
1567 # need to wrap in a list for python 3, where items is a view
1568 items = list(kwargs.items())
1569 attribute, new = items[0]
1570 patcher = _patch(
1571 getter, attribute, new, spec, create, spec_set,
1572 autospec, new_callable, {}
1573 )
1574 patcher.attribute_name = attribute
1575 for attribute, new in items[1:]:
1576 this_patcher = _patch(
1577 getter, attribute, new, spec, create, spec_set,
1578 autospec, new_callable, {}
1579 )
1580 this_patcher.attribute_name = attribute
1581 patcher.additional_patchers.append(this_patcher)
1582 return patcher
1583
1584
1585def patch(
1586 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001587 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001588 ):
1589 """
1590 `patch` acts as a function decorator, class decorator or a context
1591 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001592 is patched with a `new` object. When the function/with statement exits
1593 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001594
Michael Foord54b3db82012-03-28 15:08:08 +01001595 If `new` is omitted, then the target is replaced with a
1596 `MagicMock`. If `patch` is used as a decorator and `new` is
1597 omitted, the created mock is passed in as an extra argument to the
1598 decorated function. If `patch` is used as a context manager the created
1599 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001600
Michael Foord54b3db82012-03-28 15:08:08 +01001601 `target` should be a string in the form `'package.module.ClassName'`. The
1602 `target` is imported and the specified object replaced with the `new`
1603 object, so the `target` must be importable from the environment you are
1604 calling `patch` from. The target is imported when the decorated function
1605 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001606
1607 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1608 if patch is creating one for you.
1609
1610 In addition you can pass `spec=True` or `spec_set=True`, which causes
1611 patch to pass in the object being mocked as the spec/spec_set object.
1612
1613 `new_callable` allows you to specify a different class, or callable object,
1614 that will be called to create the `new` object. By default `MagicMock` is
1615 used.
1616
1617 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001618 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001619 All attributes of the mock will also have the spec of the corresponding
1620 attribute of the object being replaced. Methods and functions being
1621 mocked will have their arguments checked and will raise a `TypeError` if
1622 they are called with the wrong signature. For mocks replacing a class,
1623 their return value (the 'instance') will have the same spec as the class.
1624
1625 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1626 arbitrary object as the spec instead of the one being replaced.
1627
1628 By default `patch` will fail to replace attributes that don't exist. If
1629 you pass in `create=True`, and the attribute doesn't exist, patch will
1630 create the attribute for you when the patched function is called, and
1631 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001632 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001633 default because it can be dangerous. With it switched on you can write
1634 passing tests against APIs that don't actually exist!
1635
1636 Patch can be used as a `TestCase` class decorator. It works by
1637 decorating each test method in the class. This reduces the boilerplate
1638 code when your test methods share a common patchings set. `patch` finds
1639 tests by looking for method names that start with `patch.TEST_PREFIX`.
1640 By default this is `test`, which matches the way `unittest` finds tests.
1641 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1642
1643 Patch can be used as a context manager, with the with statement. Here the
1644 patching applies to the indented block after the with statement. If you
1645 use "as" then the patched object will be bound to the name after the
1646 "as"; very useful if `patch` is creating a mock object for you.
1647
1648 `patch` takes arbitrary keyword arguments. These will be passed to
1649 the `Mock` (or `new_callable`) on construction.
1650
1651 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1652 available for alternate use-cases.
1653 """
1654 getter, attribute = _get_target(target)
1655 return _patch(
1656 getter, attribute, new, spec, create,
1657 spec_set, autospec, new_callable, kwargs
1658 )
1659
1660
1661class _patch_dict(object):
1662 """
1663 Patch a dictionary, or dictionary like object, and restore the dictionary
1664 to its original state after the test.
1665
1666 `in_dict` can be a dictionary or a mapping like container. If it is a
1667 mapping then it must at least support getting, setting and deleting items
1668 plus iterating over keys.
1669
1670 `in_dict` can also be a string specifying the name of the dictionary, which
1671 will then be fetched by importing it.
1672
1673 `values` can be a dictionary of values to set in the dictionary. `values`
1674 can also be an iterable of `(key, value)` pairs.
1675
1676 If `clear` is True then the dictionary will be cleared before the new
1677 values are set.
1678
1679 `patch.dict` can also be called with arbitrary keyword arguments to set
1680 values in the dictionary::
1681
1682 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1683 ...
1684
1685 `patch.dict` can be used as a context manager, decorator or class
1686 decorator. When used as a class decorator `patch.dict` honours
1687 `patch.TEST_PREFIX` for choosing which methods to wrap.
1688 """
1689
1690 def __init__(self, in_dict, values=(), clear=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001691 self.in_dict = in_dict
1692 # support any argument supported by dict(...) constructor
1693 self.values = dict(values)
1694 self.values.update(kwargs)
1695 self.clear = clear
1696 self._original = None
1697
1698
1699 def __call__(self, f):
1700 if isinstance(f, type):
1701 return self.decorate_class(f)
1702 @wraps(f)
1703 def _inner(*args, **kw):
1704 self._patch_dict()
1705 try:
1706 return f(*args, **kw)
1707 finally:
1708 self._unpatch_dict()
1709
1710 return _inner
1711
1712
1713 def decorate_class(self, klass):
1714 for attr in dir(klass):
1715 attr_value = getattr(klass, attr)
1716 if (attr.startswith(patch.TEST_PREFIX) and
1717 hasattr(attr_value, "__call__")):
1718 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1719 decorated = decorator(attr_value)
1720 setattr(klass, attr, decorated)
1721 return klass
1722
1723
1724 def __enter__(self):
1725 """Patch the dict."""
1726 self._patch_dict()
Mario Corchero04530812019-05-28 13:53:31 +01001727 return self.in_dict
Michael Foord345266a2012-03-14 12:24:34 -07001728
1729
1730 def _patch_dict(self):
1731 values = self.values
Xtreaka875ea52019-02-25 00:24:49 +05301732 if isinstance(self.in_dict, str):
1733 self.in_dict = _importer(self.in_dict)
Michael Foord345266a2012-03-14 12:24:34 -07001734 in_dict = self.in_dict
1735 clear = self.clear
1736
1737 try:
1738 original = in_dict.copy()
1739 except AttributeError:
1740 # dict like object with no copy method
1741 # must support iteration over keys
1742 original = {}
1743 for key in in_dict:
1744 original[key] = in_dict[key]
1745 self._original = original
1746
1747 if clear:
1748 _clear_dict(in_dict)
1749
1750 try:
1751 in_dict.update(values)
1752 except AttributeError:
1753 # dict like object with no update method
1754 for key in values:
1755 in_dict[key] = values[key]
1756
1757
1758 def _unpatch_dict(self):
1759 in_dict = self.in_dict
1760 original = self._original
1761
1762 _clear_dict(in_dict)
1763
1764 try:
1765 in_dict.update(original)
1766 except AttributeError:
1767 for key in original:
1768 in_dict[key] = original[key]
1769
1770
1771 def __exit__(self, *args):
1772 """Unpatch the dict."""
1773 self._unpatch_dict()
1774 return False
1775
1776 start = __enter__
1777 stop = __exit__
1778
1779
1780def _clear_dict(in_dict):
1781 try:
1782 in_dict.clear()
1783 except AttributeError:
1784 keys = list(in_dict)
1785 for key in keys:
1786 del in_dict[key]
1787
1788
Michael Foordf7c41582012-06-10 20:36:32 +01001789def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001790 """Stop all active patches. LIFO to unroll nested patches."""
1791 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001792 patch.stop()
1793
1794
Michael Foord345266a2012-03-14 12:24:34 -07001795patch.object = _patch_object
1796patch.dict = _patch_dict
1797patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001798patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001799patch.TEST_PREFIX = 'test'
1800
1801magic_methods = (
1802 "lt le gt ge eq ne "
1803 "getitem setitem delitem "
1804 "len contains iter "
1805 "hash str sizeof "
1806 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001807 # we added divmod and rdivmod here instead of numerics
1808 # because there is no idivmod
1809 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001810 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001811 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001812 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001813 "fspath "
Michael Foord345266a2012-03-14 12:24:34 -07001814)
1815
Michael Foordd2623d72014-04-14 11:23:48 -04001816numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001817 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001818)
Michael Foord345266a2012-03-14 12:24:34 -07001819inplace = ' '.join('i%s' % n for n in numerics.split())
1820right = ' '.join('r%s' % n for n in numerics.split())
1821
1822# not including __prepare__, __instancecheck__, __subclasscheck__
1823# (as they are metaclass methods)
1824# __del__ is not supported at all as it causes problems if it exists
1825
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001826_non_defaults = {
1827 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1828 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1829 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1830 '__repr__', '__dir__', '__subclasses__', '__format__',
Lisa Roach77b3b772019-05-20 09:19:53 -07001831 '__getnewargs_ex__', '__aenter__', '__aexit__', '__anext__', '__aiter__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001832}
Michael Foord345266a2012-03-14 12:24:34 -07001833
1834
1835def _get_method(name, func):
1836 "Turns a callable object (like a mock) into a real function"
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001837 def method(self, /, *args, **kw):
Michael Foord345266a2012-03-14 12:24:34 -07001838 return func(self, *args, **kw)
1839 method.__name__ = name
1840 return method
1841
1842
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001843_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001844 '__%s__' % method for method in
1845 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001846}
Michael Foord345266a2012-03-14 12:24:34 -07001847
Lisa Roach77b3b772019-05-20 09:19:53 -07001848# Magic methods used for async `with` statements
1849_async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
1850# `__aiter__` is a plain function but used with async calls
1851_async_magics = _async_method_magics | {"__aiter__"}
1852
Michael Foord345266a2012-03-14 12:24:34 -07001853_all_magics = _magics | _non_defaults
1854
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001855_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001856 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001857 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001858 '__instancecheck__', '__subclasscheck__',
1859 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001860}
Michael Foord345266a2012-03-14 12:24:34 -07001861
1862_calculate_return_value = {
1863 '__hash__': lambda self: object.__hash__(self),
1864 '__str__': lambda self: object.__str__(self),
1865 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001866 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001867}
1868
1869_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001870 '__lt__': NotImplemented,
1871 '__gt__': NotImplemented,
1872 '__le__': NotImplemented,
1873 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001874 '__int__': 1,
1875 '__contains__': False,
1876 '__len__': 0,
1877 '__exit__': False,
1878 '__complex__': 1j,
1879 '__float__': 1.0,
1880 '__bool__': True,
1881 '__index__': 1,
Lisa Roach77b3b772019-05-20 09:19:53 -07001882 '__aexit__': False,
Michael Foord345266a2012-03-14 12:24:34 -07001883}
1884
1885
1886def _get_eq(self):
1887 def __eq__(other):
1888 ret_val = self.__eq__._mock_return_value
1889 if ret_val is not DEFAULT:
1890 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001891 if self is other:
1892 return True
1893 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001894 return __eq__
1895
1896def _get_ne(self):
1897 def __ne__(other):
1898 if self.__ne__._mock_return_value is not DEFAULT:
1899 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001900 if self is other:
1901 return False
1902 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001903 return __ne__
1904
1905def _get_iter(self):
1906 def __iter__():
1907 ret_val = self.__iter__._mock_return_value
1908 if ret_val is DEFAULT:
1909 return iter([])
1910 # if ret_val was already an iterator, then calling iter on it should
1911 # return the iterator unchanged
1912 return iter(ret_val)
1913 return __iter__
1914
Lisa Roach77b3b772019-05-20 09:19:53 -07001915def _get_async_iter(self):
1916 def __aiter__():
1917 ret_val = self.__aiter__._mock_return_value
1918 if ret_val is DEFAULT:
1919 return _AsyncIterator(iter([]))
1920 return _AsyncIterator(iter(ret_val))
1921 return __aiter__
1922
Michael Foord345266a2012-03-14 12:24:34 -07001923_side_effect_methods = {
1924 '__eq__': _get_eq,
1925 '__ne__': _get_ne,
1926 '__iter__': _get_iter,
Lisa Roach77b3b772019-05-20 09:19:53 -07001927 '__aiter__': _get_async_iter
Michael Foord345266a2012-03-14 12:24:34 -07001928}
1929
1930
1931
1932def _set_return_value(mock, method, name):
1933 fixed = _return_values.get(name, DEFAULT)
1934 if fixed is not DEFAULT:
1935 method.return_value = fixed
1936 return
1937
1938 return_calulator = _calculate_return_value.get(name)
1939 if return_calulator is not None:
Chris Withersadbf1782019-05-01 23:04:04 +01001940 return_value = return_calulator(mock)
Michael Foord345266a2012-03-14 12:24:34 -07001941 method.return_value = return_value
1942 return
1943
1944 side_effector = _side_effect_methods.get(name)
1945 if side_effector is not None:
1946 method.side_effect = side_effector(mock)
1947
1948
1949
1950class MagicMixin(object):
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001951 def __init__(self, /, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001952 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001953 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001954 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001955
1956
1957 def _mock_set_magics(self):
1958 these_magics = _magics
1959
Łukasz Langaa468db92015-04-13 23:12:42 -07001960 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001961 these_magics = _magics.intersection(self._mock_methods)
1962
1963 remove_magics = set()
1964 remove_magics = _magics - these_magics
1965
1966 for entry in remove_magics:
1967 if entry in type(self).__dict__:
1968 # remove unneeded magic methods
1969 delattr(self, entry)
1970
1971 # don't overwrite existing attributes if called a second time
1972 these_magics = these_magics - set(type(self).__dict__)
1973
1974 _type = type(self)
1975 for entry in these_magics:
1976 setattr(_type, entry, MagicProxy(entry, self))
1977
1978
1979
1980class NonCallableMagicMock(MagicMixin, NonCallableMock):
1981 """A version of `MagicMock` that isn't callable."""
1982 def mock_add_spec(self, spec, spec_set=False):
1983 """Add a spec to a mock. `spec` can either be an object or a
1984 list of strings. Only attributes on the `spec` can be fetched as
1985 attributes from the mock.
1986
1987 If `spec_set` is True then only attributes on the spec can be set."""
1988 self._mock_add_spec(spec, spec_set)
1989 self._mock_set_magics()
1990
1991
Lisa Roach77b3b772019-05-20 09:19:53 -07001992class AsyncMagicMixin:
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001993 def __init__(self, /, *args, **kw):
Lisa Roach77b3b772019-05-20 09:19:53 -07001994 self._mock_set_async_magics() # make magic work for kwargs in init
1995 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)
1996 self._mock_set_async_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001997
Lisa Roach77b3b772019-05-20 09:19:53 -07001998 def _mock_set_async_magics(self):
1999 these_magics = _async_magics
2000
2001 if getattr(self, "_mock_methods", None) is not None:
2002 these_magics = _async_magics.intersection(self._mock_methods)
2003 remove_magics = _async_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
2018class MagicMock(MagicMixin, AsyncMagicMixin, Mock):
Michael Foord345266a2012-03-14 12:24:34 -07002019 """
2020 MagicMock is a subclass of Mock with default implementations
2021 of most of the magic methods. You can use MagicMock without having to
2022 configure the magic methods yourself.
2023
2024 If you use the `spec` or `spec_set` arguments then *only* magic
2025 methods that exist in the spec will be created.
2026
2027 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
2028 """
2029 def mock_add_spec(self, spec, spec_set=False):
2030 """Add a spec to a mock. `spec` can either be an object or a
2031 list of strings. Only attributes on the `spec` can be fetched as
2032 attributes from the mock.
2033
2034 If `spec_set` is True then only attributes on the spec can be set."""
2035 self._mock_add_spec(spec, spec_set)
2036 self._mock_set_magics()
2037
2038
2039
2040class MagicProxy(object):
2041 def __init__(self, name, parent):
2042 self.name = name
2043 self.parent = parent
2044
Michael Foord345266a2012-03-14 12:24:34 -07002045 def create_mock(self):
2046 entry = self.name
2047 parent = self.parent
2048 m = parent._get_child_mock(name=entry, _new_name=entry,
2049 _new_parent=parent)
2050 setattr(parent, entry, m)
2051 _set_return_value(parent, m, entry)
2052 return m
2053
2054 def __get__(self, obj, _type=None):
2055 return self.create_mock()
2056
2057
Lisa Roach77b3b772019-05-20 09:19:53 -07002058class AsyncMockMixin(Base):
2059 awaited = _delegating_property('awaited')
2060 await_count = _delegating_property('await_count')
2061 await_args = _delegating_property('await_args')
2062 await_args_list = _delegating_property('await_args_list')
2063
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002064 def __init__(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002065 super().__init__(*args, **kwargs)
2066 # asyncio.iscoroutinefunction() checks _is_coroutine property to say if an
2067 # object is a coroutine. Without this check it looks to see if it is a
2068 # function/method, which in this case it is not (since it is an
2069 # AsyncMock).
2070 # It is set through __dict__ because when spec_set is True, this
2071 # attribute is likely undefined.
2072 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
2073 self.__dict__['_mock_awaited'] = _AwaitEvent(self)
2074 self.__dict__['_mock_await_count'] = 0
2075 self.__dict__['_mock_await_args'] = None
2076 self.__dict__['_mock_await_args_list'] = _CallList()
2077 code_mock = NonCallableMock(spec_set=CodeType)
2078 code_mock.co_flags = inspect.CO_COROUTINE
2079 self.__dict__['__code__'] = code_mock
2080
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002081 async def _mock_call(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002082 try:
2083 result = super()._mock_call(*args, **kwargs)
2084 except (BaseException, StopIteration) as e:
2085 side_effect = self.side_effect
2086 if side_effect is not None and not callable(side_effect):
2087 raise
2088 return await _raise(e)
2089
2090 _call = self.call_args
2091
2092 async def proxy():
2093 try:
2094 if inspect.isawaitable(result):
2095 return await result
2096 else:
2097 return result
2098 finally:
2099 self.await_count += 1
2100 self.await_args = _call
2101 self.await_args_list.append(_call)
2102 await self.awaited._notify()
2103
2104 return await proxy()
2105
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002106 def assert_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002107 """
2108 Assert that the mock was awaited at least once.
2109 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002110 if self.await_count == 0:
2111 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2112 raise AssertionError(msg)
2113
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002114 def assert_awaited_once(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002115 """
2116 Assert that the mock was awaited exactly once.
2117 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002118 if not self.await_count == 1:
2119 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2120 f" Awaited {self.await_count} times.")
2121 raise AssertionError(msg)
2122
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002123 def assert_awaited_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002124 """
2125 Assert that the last await was with the specified arguments.
2126 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002127 if self.await_args is None:
2128 expected = self._format_mock_call_signature(args, kwargs)
2129 raise AssertionError(f'Expected await: {expected}\nNot awaited')
2130
2131 def _error_message():
Xtreak0ae022c2019-05-29 12:32:26 +05302132 msg = self._format_mock_failure_message(args, kwargs, action='await')
Lisa Roach77b3b772019-05-20 09:19:53 -07002133 return msg
2134
2135 expected = self._call_matcher((args, kwargs))
2136 actual = self._call_matcher(self.await_args)
2137 if expected != actual:
2138 cause = expected if isinstance(expected, Exception) else None
2139 raise AssertionError(_error_message()) from cause
2140
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002141 def assert_awaited_once_with(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002142 """
2143 Assert that the mock was awaited exactly once and with the specified
2144 arguments.
2145 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002146 if not self.await_count == 1:
2147 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2148 f" Awaited {self.await_count} times.")
2149 raise AssertionError(msg)
2150 return self.assert_awaited_with(*args, **kwargs)
2151
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002152 def assert_any_await(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002153 """
2154 Assert the mock has ever been awaited with the specified arguments.
2155 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002156 expected = self._call_matcher((args, kwargs))
2157 actual = [self._call_matcher(c) for c in self.await_args_list]
2158 if expected not in actual:
2159 cause = expected if isinstance(expected, Exception) else None
2160 expected_string = self._format_mock_call_signature(args, kwargs)
2161 raise AssertionError(
2162 '%s await not found' % expected_string
2163 ) from cause
2164
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002165 def assert_has_awaits(self, calls, any_order=False):
Lisa Roach77b3b772019-05-20 09:19:53 -07002166 """
2167 Assert the mock has been awaited with the specified calls.
2168 The :attr:`await_args_list` list is checked for the awaits.
2169
2170 If `any_order` is False (the default) then the awaits must be
2171 sequential. There can be extra calls before or after the
2172 specified awaits.
2173
2174 If `any_order` is True then the awaits can be in any order, but
2175 they must all appear in :attr:`await_args_list`.
2176 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002177 expected = [self._call_matcher(c) for c in calls]
2178 cause = expected if isinstance(expected, Exception) else None
2179 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2180 if not any_order:
2181 if expected not in all_awaits:
2182 raise AssertionError(
Xtreak0ae022c2019-05-29 12:32:26 +05302183 f'Awaits not found.\nExpected: {_CallList(calls)}\n'
Lisa Roach77b3b772019-05-20 09:19:53 -07002184 f'Actual: {self.await_args_list}'
2185 ) from cause
2186 return
2187
2188 all_awaits = list(all_awaits)
2189
2190 not_found = []
2191 for kall in expected:
2192 try:
2193 all_awaits.remove(kall)
2194 except ValueError:
2195 not_found.append(kall)
2196 if not_found:
2197 raise AssertionError(
2198 '%r not all found in await list' % (tuple(not_found),)
2199 ) from cause
2200
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002201 def assert_not_awaited(self):
Lisa Roach77b3b772019-05-20 09:19:53 -07002202 """
2203 Assert that the mock was never awaited.
2204 """
Lisa Roach77b3b772019-05-20 09:19:53 -07002205 if self.await_count != 0:
Xtreakff6b2e62019-05-27 18:26:23 +05302206 msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
Lisa Roach77b3b772019-05-20 09:19:53 -07002207 f" Awaited {self.await_count} times.")
2208 raise AssertionError(msg)
2209
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002210 def reset_mock(self, /, *args, **kwargs):
Lisa Roach77b3b772019-05-20 09:19:53 -07002211 """
2212 See :func:`.Mock.reset_mock()`
2213 """
2214 super().reset_mock(*args, **kwargs)
2215 self.await_count = 0
2216 self.await_args = None
2217 self.await_args_list = _CallList()
2218
2219
2220class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2221 """
2222 Enhance :class:`Mock` with features allowing to mock
2223 an async function.
2224
2225 The :class:`AsyncMock` object will behave so the object is
2226 recognized as an async function, and the result of a call is an awaitable:
2227
2228 >>> mock = AsyncMock()
2229 >>> asyncio.iscoroutinefunction(mock)
2230 True
2231 >>> inspect.isawaitable(mock())
2232 True
2233
2234
2235 The result of ``mock()`` is an async function which will have the outcome
2236 of ``side_effect`` or ``return_value``:
2237
2238 - if ``side_effect`` is a function, the async function will return the
2239 result of that function,
2240 - if ``side_effect`` is an exception, the async function will raise the
2241 exception,
2242 - if ``side_effect`` is an iterable, the async function will return the
2243 next value of the iterable, however, if the sequence of result is
2244 exhausted, ``StopIteration`` is raised immediately,
2245 - if ``side_effect`` is not defined, the async function will return the
2246 value defined by ``return_value``, hence, by default, the async function
2247 returns a new :class:`AsyncMock` object.
2248
2249 If the outcome of ``side_effect`` or ``return_value`` is an async function,
2250 the mock async function obtained when the mock object is called will be this
2251 async function itself (and not an async function returning an async
2252 function).
2253
2254 The test author can also specify a wrapped object with ``wraps``. In this
2255 case, the :class:`Mock` object behavior is the same as with an
2256 :class:`.Mock` object: the wrapped object may have methods
2257 defined as async function functions.
2258
Xtreake7cb23b2019-05-21 14:17:17 +05302259 Based on Martin Richard's asynctest project.
Lisa Roach77b3b772019-05-20 09:19:53 -07002260 """
2261
Michael Foord345266a2012-03-14 12:24:34 -07002262
2263class _ANY(object):
2264 "A helper object that compares equal to everything."
2265
2266 def __eq__(self, other):
2267 return True
2268
2269 def __ne__(self, other):
2270 return False
2271
2272 def __repr__(self):
2273 return '<ANY>'
2274
2275ANY = _ANY()
2276
2277
2278
2279def _format_call_signature(name, args, kwargs):
2280 message = '%s(%%s)' % name
2281 formatted_args = ''
2282 args_string = ', '.join([repr(arg) for arg in args])
2283 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05302284 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07002285 ])
2286 if args_string:
2287 formatted_args = args_string
2288 if kwargs_string:
2289 if formatted_args:
2290 formatted_args += ', '
2291 formatted_args += kwargs_string
2292
2293 return message % formatted_args
2294
2295
2296
2297class _Call(tuple):
2298 """
2299 A tuple for holding the results of a call to a mock, either in the form
2300 `(args, kwargs)` or `(name, args, kwargs)`.
2301
2302 If args or kwargs are empty then a call tuple will compare equal to
2303 a tuple without those values. This makes comparisons less verbose::
2304
2305 _Call(('name', (), {})) == ('name',)
2306 _Call(('name', (1,), {})) == ('name', (1,))
2307 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2308
2309 The `_Call` object provides a useful shortcut for comparing with call::
2310
2311 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2312 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2313
2314 If the _Call has no name then it will match any name.
2315 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002316 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002317 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002318 args = ()
2319 kwargs = {}
2320 _len = len(value)
2321 if _len == 3:
2322 name, args, kwargs = value
2323 elif _len == 2:
2324 first, second = value
2325 if isinstance(first, str):
2326 name = first
2327 if isinstance(second, tuple):
2328 args = second
2329 else:
2330 kwargs = second
2331 else:
2332 args, kwargs = first, second
2333 elif _len == 1:
2334 value, = value
2335 if isinstance(value, str):
2336 name = value
2337 elif isinstance(value, tuple):
2338 args = value
2339 else:
2340 kwargs = value
2341
2342 if two:
2343 return tuple.__new__(cls, (args, kwargs))
2344
2345 return tuple.__new__(cls, (name, args, kwargs))
2346
2347
2348 def __init__(self, value=(), name=None, parent=None, two=False,
2349 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002350 self._mock_name = name
2351 self._mock_parent = parent
2352 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002353
2354
2355 def __eq__(self, other):
2356 if other is ANY:
2357 return True
2358 try:
2359 len_other = len(other)
2360 except TypeError:
2361 return False
2362
2363 self_name = ''
2364 if len(self) == 2:
2365 self_args, self_kwargs = self
2366 else:
2367 self_name, self_args, self_kwargs = self
2368
Andrew Dunaie63e6172018-12-04 11:08:45 +02002369 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2370 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002371 return False
2372
Michael Foord345266a2012-03-14 12:24:34 -07002373 other_name = ''
2374 if len_other == 0:
2375 other_args, other_kwargs = (), {}
2376 elif len_other == 3:
2377 other_name, other_args, other_kwargs = other
2378 elif len_other == 1:
2379 value, = other
2380 if isinstance(value, tuple):
2381 other_args = value
2382 other_kwargs = {}
2383 elif isinstance(value, str):
2384 other_name = value
2385 other_args, other_kwargs = (), {}
2386 else:
2387 other_args = ()
2388 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002389 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002390 # could be (name, args) or (name, kwargs) or (args, kwargs)
2391 first, second = other
2392 if isinstance(first, str):
2393 other_name = first
2394 if isinstance(second, tuple):
2395 other_args, other_kwargs = second, {}
2396 else:
2397 other_args, other_kwargs = (), second
2398 else:
2399 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002400 else:
2401 return False
Michael Foord345266a2012-03-14 12:24:34 -07002402
2403 if self_name and other_name != self_name:
2404 return False
2405
2406 # this order is important for ANY to work!
2407 return (other_args, other_kwargs) == (self_args, self_kwargs)
2408
2409
Berker Peksagce913872016-03-28 00:30:02 +03002410 __ne__ = object.__ne__
2411
2412
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002413 def __call__(self, /, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002414 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002415 return _Call(('', args, kwargs), name='()')
2416
Andrew Dunaie63e6172018-12-04 11:08:45 +02002417 name = self._mock_name + '()'
2418 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002419
2420
2421 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002422 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002423 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002424 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002425 return _Call(name=name, parent=self, from_kall=False)
2426
2427
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002428 def count(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302429 return self.__getattr__('count')(*args, **kwargs)
2430
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002431 def index(self, /, *args, **kwargs):
Kushal Dasa37b9582014-09-16 18:33:37 +05302432 return self.__getattr__('index')(*args, **kwargs)
2433
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302434 def _get_call_arguments(self):
2435 if len(self) == 2:
2436 args, kwargs = self
2437 else:
2438 name, args, kwargs = self
2439
2440 return args, kwargs
2441
2442 @property
2443 def args(self):
2444 return self._get_call_arguments()[0]
2445
2446 @property
2447 def kwargs(self):
2448 return self._get_call_arguments()[1]
2449
Michael Foord345266a2012-03-14 12:24:34 -07002450 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002451 if not self._mock_from_kall:
2452 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002453 if name.startswith('()'):
2454 name = 'call%s' % name
2455 return name
2456
2457 if len(self) == 2:
2458 name = 'call'
2459 args, kwargs = self
2460 else:
2461 name, args, kwargs = self
2462 if not name:
2463 name = 'call'
2464 elif not name.startswith('()'):
2465 name = 'call.%s' % name
2466 else:
2467 name = 'call%s' % name
2468 return _format_call_signature(name, args, kwargs)
2469
2470
2471 def call_list(self):
2472 """For a call object that represents multiple calls, `call_list`
2473 returns a list of all the intermediate calls as well as the
2474 final call."""
2475 vals = []
2476 thing = self
2477 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002478 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002479 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002480 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002481 return _CallList(reversed(vals))
2482
2483
2484call = _Call(from_kall=False)
2485
2486
Michael Foord345266a2012-03-14 12:24:34 -07002487def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2488 _name=None, **kwargs):
2489 """Create a mock object using another object as a spec. Attributes on the
2490 mock will use the corresponding attribute on the `spec` object as their
2491 spec.
2492
2493 Functions or methods being mocked will have their arguments checked
2494 to check that they are called with the correct signature.
2495
2496 If `spec_set` is True then attempting to set attributes that don't exist
2497 on the spec object will raise an `AttributeError`.
2498
2499 If a class is used as a spec then the return value of the mock (the
2500 instance of the class) will have the same spec. You can use a class as the
2501 spec for an instance object by passing `instance=True`. The returned mock
2502 will only be callable if instances of the mock are callable.
2503
2504 `create_autospec` also takes arbitrary keyword arguments that are passed to
2505 the constructor of the created mock."""
2506 if _is_list(spec):
2507 # can't pass a list instance to the mock constructor as it will be
2508 # interpreted as a list of strings
2509 spec = type(spec)
2510
2511 is_type = isinstance(spec, type)
Xtreakff6b2e62019-05-27 18:26:23 +05302512 is_async_func = _is_async_func(spec)
Michael Foord345266a2012-03-14 12:24:34 -07002513 _kwargs = {'spec': spec}
2514 if spec_set:
2515 _kwargs = {'spec_set': spec}
2516 elif spec is None:
2517 # None we mock with a normal mock without a spec
2518 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002519 if _kwargs and instance:
2520 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002521
2522 _kwargs.update(kwargs)
2523
2524 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002525 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002526 # descriptors don't have a spec
2527 # because we don't know what type they return
2528 _kwargs = {}
Lisa Roach77b3b772019-05-20 09:19:53 -07002529 elif is_async_func:
2530 if instance:
2531 raise RuntimeError("Instance can not be True when create_autospec "
2532 "is mocking an async function")
2533 Klass = AsyncMock
Michael Foord345266a2012-03-14 12:24:34 -07002534 elif not _callable(spec):
2535 Klass = NonCallableMagicMock
2536 elif is_type and instance and not _instance_callable(spec):
2537 Klass = NonCallableMagicMock
2538
Kushal Das484f8a82014-04-16 01:05:50 +05302539 _name = _kwargs.pop('name', _name)
2540
Michael Foord345266a2012-03-14 12:24:34 -07002541 _new_name = _name
2542 if _parent is None:
2543 # for a top level object no _new_name should be set
2544 _new_name = ''
2545
2546 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2547 name=_name, **_kwargs)
2548
2549 if isinstance(spec, FunctionTypes):
2550 # should only happen at the top level because we don't
2551 # recurse for functions
2552 mock = _set_signature(mock, spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07002553 if is_async_func:
Xtreakff6b2e62019-05-27 18:26:23 +05302554 _setup_async_mock(mock)
Michael Foord345266a2012-03-14 12:24:34 -07002555 else:
2556 _check_signature(spec, mock, is_type, instance)
2557
2558 if _parent is not None and not instance:
2559 _parent._mock_children[_name] = mock
2560
2561 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002562 mock.return_value = create_autospec(spec, spec_set, instance=True,
2563 _name='()', _parent=mock)
2564
2565 for entry in dir(spec):
2566 if _is_magic(entry):
2567 # MagicMock already does the useful magic methods for us
2568 continue
2569
Michael Foord345266a2012-03-14 12:24:34 -07002570 # XXXX do we need a better way of getting attributes without
2571 # triggering code execution (?) Probably not - we need the actual
2572 # object to mock it so we would rather trigger a property than mock
2573 # the property descriptor. Likewise we want to mock out dynamically
2574 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002575 # XXXX what about attributes that raise exceptions other than
2576 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002577 # we could be resilient against it, or catch and propagate the
2578 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002579 try:
2580 original = getattr(spec, entry)
2581 except AttributeError:
2582 continue
Michael Foord345266a2012-03-14 12:24:34 -07002583
2584 kwargs = {'spec': original}
2585 if spec_set:
2586 kwargs = {'spec_set': original}
2587
2588 if not isinstance(original, FunctionTypes):
2589 new = _SpecState(original, spec_set, mock, entry, instance)
2590 mock._mock_children[entry] = new
2591 else:
2592 parent = mock
2593 if isinstance(spec, FunctionTypes):
2594 parent = mock.mock
2595
Michael Foord345266a2012-03-14 12:24:34 -07002596 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002597 kwargs['_eat_self'] = skipfirst
Lisa Roach77b3b772019-05-20 09:19:53 -07002598 if asyncio.iscoroutinefunction(original):
2599 child_klass = AsyncMock
2600 else:
2601 child_klass = MagicMock
2602 new = child_klass(parent=parent, name=entry, _new_name=entry,
2603 _new_parent=parent,
2604 **kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002605 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002606 _check_signature(original, new, skipfirst=skipfirst)
2607
2608 # so functions created with _set_signature become instance attributes,
2609 # *plus* their underlying mock exists in _mock_children of the parent
2610 # mock. Adding to _mock_children may be unnecessary where we are also
2611 # setting as an instance attribute?
2612 if isinstance(new, FunctionTypes):
2613 setattr(mock, entry, new)
2614
2615 return mock
2616
2617
2618def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002619 """
2620 Return whether we should skip the first argument on spec's `entry`
2621 attribute.
2622 """
Michael Foord345266a2012-03-14 12:24:34 -07002623 if not isinstance(spec, type):
2624 if entry in getattr(spec, '__dict__', {}):
2625 # instance attribute - shouldn't skip
2626 return False
Michael Foord345266a2012-03-14 12:24:34 -07002627 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002628
2629 for klass in spec.__mro__:
2630 result = klass.__dict__.get(entry, DEFAULT)
2631 if result is DEFAULT:
2632 continue
2633 if isinstance(result, (staticmethod, classmethod)):
2634 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002635 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2636 # Normal method => skip if looked up on type
2637 # (if looked up on instance, self is already skipped)
2638 return is_type
2639 else:
2640 return False
Michael Foord345266a2012-03-14 12:24:34 -07002641
Chris Withersadbf1782019-05-01 23:04:04 +01002642 # function is a dynamically provided attribute
Michael Foord345266a2012-03-14 12:24:34 -07002643 return is_type
2644
2645
Michael Foord345266a2012-03-14 12:24:34 -07002646class _SpecState(object):
2647
2648 def __init__(self, spec, spec_set=False, parent=None,
2649 name=None, ids=None, instance=False):
2650 self.spec = spec
2651 self.ids = ids
2652 self.spec_set = spec_set
2653 self.parent = parent
2654 self.instance = instance
2655 self.name = name
2656
2657
2658FunctionTypes = (
2659 # python function
2660 type(create_autospec),
2661 # instance method
2662 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002663)
2664
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002665MethodWrapperTypes = (
2666 type(ANY.__eq__.__get__),
2667)
2668
Michael Foord345266a2012-03-14 12:24:34 -07002669
Michael Foorda74561a2012-03-25 19:03:13 +01002670file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002671
Michael Foord04cbe0c2013-03-19 17:22:51 -07002672
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002673def _to_stream(read_data):
2674 if isinstance(read_data, bytes):
2675 return io.BytesIO(read_data)
Michael Foord04cbe0c2013-03-19 17:22:51 -07002676 else:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002677 return io.StringIO(read_data)
Michael Foord0dccf652012-03-25 19:11:50 +01002678
Robert Collins5329aaa2015-07-17 20:08:45 +12002679
Michael Foord0dccf652012-03-25 19:11:50 +01002680def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002681 """
2682 A helper function to create a mock to replace the use of `open`. It works
2683 for `open` called directly or used as a context manager.
2684
2685 The `mock` argument is the mock object to configure. If `None` (the
2686 default) then a `MagicMock` will be created for you, with the API limited
2687 to methods or attributes available on standard file handles.
2688
Xtreak71f82a22018-12-20 21:30:21 +05302689 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002690 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002691 """
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002692 _read_data = _to_stream(read_data)
2693 _state = [_read_data, None]
2694
Robert Collinsca647ef2015-07-24 03:48:20 +12002695 def _readlines_side_effect(*args, **kwargs):
2696 if handle.readlines.return_value is not None:
2697 return handle.readlines.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002698 return _state[0].readlines(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002699
2700 def _read_side_effect(*args, **kwargs):
2701 if handle.read.return_value is not None:
2702 return handle.read.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002703 return _state[0].read(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002704
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002705 def _readline_side_effect(*args, **kwargs):
Tony Flury20870232018-09-12 23:21:16 +01002706 yield from _iter_side_effect()
2707 while True:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002708 yield _state[0].readline(*args, **kwargs)
Tony Flury20870232018-09-12 23:21:16 +01002709
2710 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002711 if handle.readline.return_value is not None:
2712 while True:
2713 yield handle.readline.return_value
2714 for line in _state[0]:
2715 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002716
Damien Nadé394119a2019-05-23 12:03:25 +02002717 def _next_side_effect():
2718 if handle.readline.return_value is not None:
2719 return handle.readline.return_value
2720 return next(_state[0])
2721
Michael Foorda74561a2012-03-25 19:03:13 +01002722 global file_spec
2723 if file_spec is None:
2724 import _io
2725 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2726
Michael Foord345266a2012-03-14 12:24:34 -07002727 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002728 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002729
Robert Collinsca647ef2015-07-24 03:48:20 +12002730 handle = MagicMock(spec=file_spec)
2731 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002732
Robert Collinsca647ef2015-07-24 03:48:20 +12002733 handle.write.return_value = None
2734 handle.read.return_value = None
2735 handle.readline.return_value = None
2736 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002737
Robert Collinsca647ef2015-07-24 03:48:20 +12002738 handle.read.side_effect = _read_side_effect
2739 _state[1] = _readline_side_effect()
2740 handle.readline.side_effect = _state[1]
2741 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002742 handle.__iter__.side_effect = _iter_side_effect
Damien Nadé394119a2019-05-23 12:03:25 +02002743 handle.__next__.side_effect = _next_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002744
Robert Collinsca647ef2015-07-24 03:48:20 +12002745 def reset_data(*args, **kwargs):
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002746 _state[0] = _to_stream(read_data)
Robert Collinsca647ef2015-07-24 03:48:20 +12002747 if handle.readline.side_effect == _state[1]:
2748 # Only reset the side effect if the user hasn't overridden it.
2749 _state[1] = _readline_side_effect()
2750 handle.readline.side_effect = _state[1]
2751 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002752
Robert Collinsca647ef2015-07-24 03:48:20 +12002753 mock.side_effect = reset_data
2754 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002755 return mock
2756
2757
2758class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002759 """
2760 A mock intended to be used as a property, or other descriptor, on a class.
2761 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2762 a return value when it is fetched.
2763
2764 Fetching a `PropertyMock` instance from an object calls the mock, with
2765 no args. Setting it calls the mock with the value being set.
2766 """
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03002767 def _get_child_mock(self, /, **kwargs):
Michael Foordc2870622012-04-13 16:57:22 +01002768 return MagicMock(**kwargs)
2769
Michael Foord345266a2012-03-14 12:24:34 -07002770 def __get__(self, obj, obj_type):
2771 return self()
2772 def __set__(self, obj, val):
2773 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002774
2775
2776def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002777 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002778
2779 Given an input Mock, seals it to ensure no further mocks will be generated
2780 when accessing an attribute that was not already defined.
2781
Mario Corchero96200eb2018-10-19 22:57:37 +01002782 The operation recursively seals the mock passed in, meaning that
2783 the mock itself, any mocks generated by accessing one of its attributes,
2784 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002785 """
2786 mock._mock_sealed = True
2787 for attr in dir(mock):
2788 try:
2789 m = getattr(mock, attr)
2790 except AttributeError:
2791 continue
2792 if not isinstance(m, NonCallableMock):
2793 continue
2794 if m._mock_new_parent is mock:
2795 seal(m)
Lisa Roach77b3b772019-05-20 09:19:53 -07002796
2797
2798async def _raise(exception):
2799 raise exception
2800
2801
2802class _AsyncIterator:
2803 """
2804 Wraps an iterator in an asynchronous iterator.
2805 """
2806 def __init__(self, iterator):
2807 self.iterator = iterator
2808 code_mock = NonCallableMock(spec_set=CodeType)
2809 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
2810 self.__dict__['__code__'] = code_mock
2811
2812 def __aiter__(self):
2813 return self
2814
2815 async def __anext__(self):
2816 try:
2817 return next(self.iterator)
2818 except StopIteration:
2819 pass
2820 raise StopAsyncIteration
2821
2822
2823class _AwaitEvent:
2824 def __init__(self, mock):
2825 self._mock = mock
2826 self._condition = None
2827
2828 async def _notify(self):
2829 condition = self._get_condition()
2830 try:
2831 await condition.acquire()
2832 condition.notify_all()
2833 finally:
2834 condition.release()
2835
2836 def _get_condition(self):
2837 """
2838 Creation of condition is delayed, to minimize the chance of using the
2839 wrong loop.
2840 A user may create a mock with _AwaitEvent before selecting the
2841 execution loop. Requiring a user to delay creation is error-prone and
2842 inflexible. Instead, condition is created when user actually starts to
2843 use the mock.
2844 """
2845 # No synchronization is needed:
2846 # - asyncio is thread unsafe
2847 # - there are no awaits here, method will be executed without
2848 # switching asyncio context.
2849 if self._condition is None:
2850 self._condition = asyncio.Condition()
2851
2852 return self._condition