blob: 166c10037698488cba20df41ed290a068e5d4b7f [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
Rémi Lapeyre11a88322019-05-07 12:48:36 +020029import io
Michael Foord345266a2012-03-14 12:24:34 -070030import inspect
31import pprint
32import sys
Michael Foordfddcfa22014-04-14 16:25:20 -040033import builtins
Lisa Roach77b3b772019-05-20 09:19:53 -070034from types import CodeType, ModuleType, MethodType
Petter Strandmark47d94242018-10-28 21:37:10 +010035from unittest.util import safe_repr
Antoine Pitrou5c64df72013-02-03 00:23:58 +010036from functools import wraps, partial
Michael Foord345266a2012-03-14 12:24:34 -070037
38
Michael Foordfddcfa22014-04-14 16:25:20 -040039_builtins = {name for name in dir(builtins) if not name.startswith('_')}
40
Michael Foord345266a2012-03-14 12:24:34 -070041FILTER_DIR = True
42
Nick Coghlan0b43bcf2012-05-27 18:17:07 +100043# Workaround for issue #12370
44# Without this, the __class__ properties wouldn't be set correctly
45_safe_super = super
Michael Foord345266a2012-03-14 12:24:34 -070046
Lisa Roach77b3b772019-05-20 09:19:53 -070047def _is_async_obj(obj):
48 if getattr(obj, '__code__', None):
49 return asyncio.iscoroutinefunction(obj) or inspect.isawaitable(obj)
50 else:
51 return False
52
53
Michael Foord345266a2012-03-14 12:24:34 -070054def _is_instance_mock(obj):
55 # can't use isinstance on Mock objects because they override __class__
56 # The base class for all mocks is NonCallableMock
57 return issubclass(type(obj), NonCallableMock)
58
59
60def _is_exception(obj):
61 return (
Chris Withers49e27f02019-05-01 08:48:44 +010062 isinstance(obj, BaseException) or
63 isinstance(obj, type) and issubclass(obj, BaseException)
Michael Foord345266a2012-03-14 12:24:34 -070064 )
65
66
Antoine Pitrou5c64df72013-02-03 00:23:58 +010067def _get_signature_object(func, as_instance, eat_self):
68 """
69 Given an arbitrary, possibly callable object, try to create a suitable
70 signature object.
71 Return a (reduced func, signature) tuple, or None.
72 """
73 if isinstance(func, type) and not as_instance:
74 # If it's a type and should be modelled as a type, use __init__.
Chris Withersadbf1782019-05-01 23:04:04 +010075 func = func.__init__
Antoine Pitrou5c64df72013-02-03 00:23:58 +010076 # Skip the `self` argument in __init__
77 eat_self = True
Michael Foord345266a2012-03-14 12:24:34 -070078 elif not isinstance(func, FunctionTypes):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010079 # If we really want to model an instance of the passed type,
80 # __call__ should be looked up, not __init__.
Michael Foord345266a2012-03-14 12:24:34 -070081 try:
82 func = func.__call__
83 except AttributeError:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010084 return None
85 if eat_self:
86 sig_func = partial(func, None)
87 else:
88 sig_func = func
Michael Foord345266a2012-03-14 12:24:34 -070089 try:
Antoine Pitrou5c64df72013-02-03 00:23:58 +010090 return func, inspect.signature(sig_func)
91 except ValueError:
92 # Certain callable types are not supported by inspect.signature()
93 return None
Michael Foord345266a2012-03-14 12:24:34 -070094
95
96def _check_signature(func, mock, skipfirst, instance=False):
Antoine Pitrou5c64df72013-02-03 00:23:58 +010097 sig = _get_signature_object(func, instance, skipfirst)
98 if sig is None:
Michael Foord345266a2012-03-14 12:24:34 -070099 return
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100100 func, sig = sig
101 def checksig(_mock_self, *args, **kwargs):
102 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700103 _copy_func_details(func, checksig)
104 type(mock)._mock_check_sig = checksig
Xtreakf7fa62e2018-12-12 13:24:54 +0530105 type(mock).__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700106
107
108def _copy_func_details(func, funcopy):
Michael Foord345266a2012-03-14 12:24:34 -0700109 # we explicitly don't copy func.__dict__ into this copy as it would
110 # expose original attributes that should be mocked
Berker Peksag161a4dd2016-12-15 05:21:44 +0300111 for attribute in (
112 '__name__', '__doc__', '__text_signature__',
113 '__module__', '__defaults__', '__kwdefaults__',
114 ):
115 try:
116 setattr(funcopy, attribute, getattr(func, attribute))
117 except AttributeError:
118 pass
Michael Foord345266a2012-03-14 12:24:34 -0700119
120
121def _callable(obj):
122 if isinstance(obj, type):
123 return True
Xtreak9b218562019-04-22 08:00:23 +0530124 if isinstance(obj, (staticmethod, classmethod, MethodType)):
125 return _callable(obj.__func__)
Michael Foord345266a2012-03-14 12:24:34 -0700126 if getattr(obj, '__call__', None) is not None:
127 return True
128 return False
129
130
131def _is_list(obj):
132 # checks for list or tuples
133 # XXXX badly named!
134 return type(obj) in (list, tuple)
135
136
137def _instance_callable(obj):
138 """Given an object, return True if the object is callable.
139 For classes, return True if instances would be callable."""
140 if not isinstance(obj, type):
141 # already an instance
142 return getattr(obj, '__call__', None) is not None
143
Michael Foorda74b3aa2012-03-14 14:40:22 -0700144 # *could* be broken by a class overriding __mro__ or __dict__ via
145 # a metaclass
146 for base in (obj,) + obj.__mro__:
147 if base.__dict__.get('__call__') is not None:
Michael Foord345266a2012-03-14 12:24:34 -0700148 return True
149 return False
150
151
152def _set_signature(mock, original, instance=False):
153 # creates a function with signature (*args, **kwargs) that delegates to a
154 # mock. It still does signature checking by calling a lambda with the same
155 # signature as the original.
Michael Foord345266a2012-03-14 12:24:34 -0700156
157 skipfirst = isinstance(original, type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100158 result = _get_signature_object(original, instance, skipfirst)
Michael Foord345266a2012-03-14 12:24:34 -0700159 if result is None:
Aaron Gallagher856cbcc2017-07-19 17:01:14 -0700160 return mock
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100161 func, sig = result
162 def checksig(*args, **kwargs):
163 sig.bind(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700164 _copy_func_details(func, checksig)
165
166 name = original.__name__
167 if not name.isidentifier():
168 name = 'funcopy'
Michael Foord313f85f2012-03-25 18:16:07 +0100169 context = {'_checksig_': checksig, 'mock': mock}
Michael Foord345266a2012-03-14 12:24:34 -0700170 src = """def %s(*args, **kwargs):
Michael Foord313f85f2012-03-25 18:16:07 +0100171 _checksig_(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700172 return mock(*args, **kwargs)""" % name
173 exec (src, context)
174 funcopy = context[name]
Xtreakf7fa62e2018-12-12 13:24:54 +0530175 _setup_func(funcopy, mock, sig)
Michael Foord345266a2012-03-14 12:24:34 -0700176 return funcopy
177
178
Xtreakf7fa62e2018-12-12 13:24:54 +0530179def _setup_func(funcopy, mock, sig):
Michael Foord345266a2012-03-14 12:24:34 -0700180 funcopy.mock = mock
181
Michael Foord345266a2012-03-14 12:24:34 -0700182 def assert_called_with(*args, **kwargs):
183 return mock.assert_called_with(*args, **kwargs)
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700184 def assert_called(*args, **kwargs):
185 return mock.assert_called(*args, **kwargs)
186 def assert_not_called(*args, **kwargs):
187 return mock.assert_not_called(*args, **kwargs)
188 def assert_called_once(*args, **kwargs):
189 return mock.assert_called_once(*args, **kwargs)
Michael Foord345266a2012-03-14 12:24:34 -0700190 def assert_called_once_with(*args, **kwargs):
191 return mock.assert_called_once_with(*args, **kwargs)
192 def assert_has_calls(*args, **kwargs):
193 return mock.assert_has_calls(*args, **kwargs)
194 def assert_any_call(*args, **kwargs):
195 return mock.assert_any_call(*args, **kwargs)
196 def reset_mock():
197 funcopy.method_calls = _CallList()
198 funcopy.mock_calls = _CallList()
199 mock.reset_mock()
200 ret = funcopy.return_value
201 if _is_instance_mock(ret) and not ret is mock:
202 ret.reset_mock()
203
204 funcopy.called = False
205 funcopy.call_count = 0
206 funcopy.call_args = None
207 funcopy.call_args_list = _CallList()
208 funcopy.method_calls = _CallList()
209 funcopy.mock_calls = _CallList()
210
211 funcopy.return_value = mock.return_value
212 funcopy.side_effect = mock.side_effect
213 funcopy._mock_children = mock._mock_children
214
215 funcopy.assert_called_with = assert_called_with
216 funcopy.assert_called_once_with = assert_called_once_with
217 funcopy.assert_has_calls = assert_has_calls
218 funcopy.assert_any_call = assert_any_call
219 funcopy.reset_mock = reset_mock
Gregory P. Smithac5084b2016-10-06 14:31:23 -0700220 funcopy.assert_called = assert_called
221 funcopy.assert_not_called = assert_not_called
222 funcopy.assert_called_once = assert_called_once
Xtreakf7fa62e2018-12-12 13:24:54 +0530223 funcopy.__signature__ = sig
Michael Foord345266a2012-03-14 12:24:34 -0700224
225 mock._mock_delegate = funcopy
226
227
228def _is_magic(name):
229 return '__%s__' % name[2:-2] == name
230
231
232class _SentinelObject(object):
233 "A unique, named, sentinel object."
234 def __init__(self, name):
235 self.name = name
236
237 def __repr__(self):
238 return 'sentinel.%s' % self.name
239
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200240 def __reduce__(self):
241 return 'sentinel.%s' % self.name
242
Michael Foord345266a2012-03-14 12:24:34 -0700243
244class _Sentinel(object):
245 """Access attributes to return a named object, usable as a sentinel."""
246 def __init__(self):
247 self._sentinels = {}
248
249 def __getattr__(self, name):
250 if name == '__bases__':
251 # Without this help(unittest.mock) raises an exception
252 raise AttributeError
253 return self._sentinels.setdefault(name, _SentinelObject(name))
254
Serhiy Storchakad9c956f2017-01-11 20:13:03 +0200255 def __reduce__(self):
256 return 'sentinel'
257
Michael Foord345266a2012-03-14 12:24:34 -0700258
259sentinel = _Sentinel()
260
261DEFAULT = sentinel.DEFAULT
262_missing = sentinel.MISSING
263_deleted = sentinel.DELETED
264
265
Serhiy Storchakac02d1882014-12-11 10:28:14 +0200266_allowed_names = {
267 'return_value', '_mock_return_value', 'side_effect',
268 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
269 '_mock_name', '_mock_new_name'
270}
Michael Foord345266a2012-03-14 12:24:34 -0700271
272
273def _delegating_property(name):
274 _allowed_names.add(name)
275 _the_name = '_mock_' + name
276 def _get(self, name=name, _the_name=_the_name):
277 sig = self._mock_delegate
278 if sig is None:
279 return getattr(self, _the_name)
280 return getattr(sig, name)
281 def _set(self, value, name=name, _the_name=_the_name):
282 sig = self._mock_delegate
283 if sig is None:
284 self.__dict__[_the_name] = value
285 else:
286 setattr(sig, name, value)
287
288 return property(_get, _set)
289
290
291
292class _CallList(list):
293
294 def __contains__(self, value):
295 if not isinstance(value, list):
296 return list.__contains__(self, value)
297 len_value = len(value)
298 len_self = len(self)
299 if len_value > len_self:
300 return False
301
302 for i in range(0, len_self - len_value + 1):
303 sub_list = self[i:i+len_value]
304 if sub_list == value:
305 return True
306 return False
307
308 def __repr__(self):
309 return pprint.pformat(list(self))
310
311
312def _check_and_set_parent(parent, value, name, new_name):
Xtreak9c3f2842019-02-26 03:16:34 +0530313 # function passed to create_autospec will have mock
314 # attribute attached to which parent must be set
315 if isinstance(value, FunctionTypes):
316 try:
317 value = value.mock
318 except AttributeError:
319 pass
320
Michael Foord345266a2012-03-14 12:24:34 -0700321 if not _is_instance_mock(value):
322 return False
323 if ((value._mock_name or value._mock_new_name) or
324 (value._mock_parent is not None) or
325 (value._mock_new_parent is not None)):
326 return False
327
328 _parent = parent
329 while _parent is not None:
330 # setting a mock (value) as a child or return value of itself
331 # should not modify the mock
332 if _parent is value:
333 return False
334 _parent = _parent._mock_new_parent
335
336 if new_name:
337 value._mock_new_parent = parent
338 value._mock_new_name = new_name
339 if name:
340 value._mock_parent = parent
341 value._mock_name = name
342 return True
343
Michael Foord01bafdc2014-04-14 16:09:42 -0400344# Internal class to identify if we wrapped an iterator object or not.
345class _MockIter(object):
346 def __init__(self, obj):
347 self.obj = iter(obj)
Michael Foord01bafdc2014-04-14 16:09:42 -0400348 def __next__(self):
349 return next(self.obj)
Michael Foord345266a2012-03-14 12:24:34 -0700350
351class Base(object):
352 _mock_return_value = DEFAULT
353 _mock_side_effect = None
354 def __init__(self, *args, **kwargs):
355 pass
356
357
358
359class NonCallableMock(Base):
360 """A non-callable version of `Mock`"""
361
362 def __new__(cls, *args, **kw):
363 # every instance has its own class
364 # so we can create magic methods on the
365 # class without stomping on other mocks
Lisa Roach77b3b772019-05-20 09:19:53 -0700366 bases = (cls,)
367 if not issubclass(cls, AsyncMock):
368 # Check if spec is an async object or function
369 sig = inspect.signature(NonCallableMock.__init__)
370 bound_args = sig.bind_partial(cls, *args, **kw).arguments
371 spec_arg = [
372 arg for arg in bound_args.keys()
373 if arg.startswith('spec')
374 ]
375 if spec_arg:
376 # what if spec_set is different than spec?
377 if _is_async_obj(bound_args[spec_arg[0]]):
378 bases = (AsyncMockMixin, cls,)
379 new = type(cls.__name__, bases, {'__doc__': cls.__doc__})
Michael Foord345266a2012-03-14 12:24:34 -0700380 instance = object.__new__(new)
381 return instance
382
383
384 def __init__(
385 self, spec=None, wraps=None, name=None, spec_set=None,
386 parent=None, _spec_state=None, _new_name='', _new_parent=None,
Kushal Das8c145342014-04-16 23:32:21 +0530387 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -0700388 ):
389 if _new_parent is None:
390 _new_parent = parent
391
392 __dict__ = self.__dict__
393 __dict__['_mock_parent'] = parent
394 __dict__['_mock_name'] = name
395 __dict__['_mock_new_name'] = _new_name
396 __dict__['_mock_new_parent'] = _new_parent
Mario Corchero552be9d2017-10-17 12:35:11 +0100397 __dict__['_mock_sealed'] = False
Michael Foord345266a2012-03-14 12:24:34 -0700398
399 if spec_set is not None:
400 spec = spec_set
401 spec_set = True
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100402 if _eat_self is None:
403 _eat_self = parent is not None
Michael Foord345266a2012-03-14 12:24:34 -0700404
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100405 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
Michael Foord345266a2012-03-14 12:24:34 -0700406
407 __dict__['_mock_children'] = {}
408 __dict__['_mock_wraps'] = wraps
409 __dict__['_mock_delegate'] = None
410
411 __dict__['_mock_called'] = False
412 __dict__['_mock_call_args'] = None
413 __dict__['_mock_call_count'] = 0
414 __dict__['_mock_call_args_list'] = _CallList()
415 __dict__['_mock_mock_calls'] = _CallList()
416
417 __dict__['method_calls'] = _CallList()
Kushal Das8c145342014-04-16 23:32:21 +0530418 __dict__['_mock_unsafe'] = unsafe
Michael Foord345266a2012-03-14 12:24:34 -0700419
420 if kwargs:
421 self.configure_mock(**kwargs)
422
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000423 _safe_super(NonCallableMock, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700424 spec, wraps, name, spec_set, parent,
425 _spec_state
426 )
427
428
429 def attach_mock(self, mock, attribute):
430 """
431 Attach a mock as an attribute of this one, replacing its name and
432 parent. Calls to the attached mock will be recorded in the
433 `method_calls` and `mock_calls` attributes of this one."""
434 mock._mock_parent = None
435 mock._mock_new_parent = None
436 mock._mock_name = ''
437 mock._mock_new_name = None
438
439 setattr(self, attribute, mock)
440
441
442 def mock_add_spec(self, spec, spec_set=False):
443 """Add a spec to a mock. `spec` can either be an object or a
444 list of strings. Only attributes on the `spec` can be fetched as
445 attributes from the mock.
446
447 If `spec_set` is True then only attributes on the spec can be set."""
448 self._mock_add_spec(spec, spec_set)
449
450
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100451 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
452 _eat_self=False):
Michael Foord345266a2012-03-14 12:24:34 -0700453 _spec_class = None
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100454 _spec_signature = None
Lisa Roach77b3b772019-05-20 09:19:53 -0700455 _spec_asyncs = []
456
457 for attr in dir(spec):
458 if asyncio.iscoroutinefunction(getattr(spec, attr, None)):
459 _spec_asyncs.append(attr)
Michael Foord345266a2012-03-14 12:24:34 -0700460
461 if spec is not None and not _is_list(spec):
462 if isinstance(spec, type):
463 _spec_class = spec
464 else:
Chris Withersadbf1782019-05-01 23:04:04 +0100465 _spec_class = type(spec)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100466 res = _get_signature_object(spec,
467 _spec_as_instance, _eat_self)
468 _spec_signature = res and res[1]
Michael Foord345266a2012-03-14 12:24:34 -0700469
470 spec = dir(spec)
471
472 __dict__ = self.__dict__
473 __dict__['_spec_class'] = _spec_class
474 __dict__['_spec_set'] = spec_set
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100475 __dict__['_spec_signature'] = _spec_signature
Michael Foord345266a2012-03-14 12:24:34 -0700476 __dict__['_mock_methods'] = spec
Lisa Roach77b3b772019-05-20 09:19:53 -0700477 __dict__['_spec_asyncs'] = _spec_asyncs
Michael Foord345266a2012-03-14 12:24:34 -0700478
479 def __get_return_value(self):
480 ret = self._mock_return_value
481 if self._mock_delegate is not None:
482 ret = self._mock_delegate.return_value
483
484 if ret is DEFAULT:
485 ret = self._get_child_mock(
486 _new_parent=self, _new_name='()'
487 )
488 self.return_value = ret
489 return ret
490
491
492 def __set_return_value(self, value):
493 if self._mock_delegate is not None:
494 self._mock_delegate.return_value = value
495 else:
496 self._mock_return_value = value
497 _check_and_set_parent(self, value, None, '()')
498
499 __return_value_doc = "The value to be returned when the mock is called."
500 return_value = property(__get_return_value, __set_return_value,
501 __return_value_doc)
502
503
504 @property
505 def __class__(self):
506 if self._spec_class is None:
507 return type(self)
508 return self._spec_class
509
510 called = _delegating_property('called')
511 call_count = _delegating_property('call_count')
512 call_args = _delegating_property('call_args')
513 call_args_list = _delegating_property('call_args_list')
514 mock_calls = _delegating_property('mock_calls')
515
516
517 def __get_side_effect(self):
518 delegated = self._mock_delegate
519 if delegated is None:
520 return self._mock_side_effect
Michael Foord01bafdc2014-04-14 16:09:42 -0400521 sf = delegated.side_effect
Robert Collinsf58f88c2015-07-14 13:51:40 +1200522 if (sf is not None and not callable(sf)
523 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
Michael Foord01bafdc2014-04-14 16:09:42 -0400524 sf = _MockIter(sf)
525 delegated.side_effect = sf
526 return sf
Michael Foord345266a2012-03-14 12:24:34 -0700527
528 def __set_side_effect(self, value):
529 value = _try_iter(value)
530 delegated = self._mock_delegate
531 if delegated is None:
532 self._mock_side_effect = value
533 else:
534 delegated.side_effect = value
535
536 side_effect = property(__get_side_effect, __set_side_effect)
537
538
Kushal Das9cd39a12016-06-02 10:20:16 -0700539 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):
Michael Foord345266a2012-03-14 12:24:34 -0700540 "Restore the mock object to its initial state."
Robert Collinsb37f43f2015-07-15 11:42:28 +1200541 if visited is None:
542 visited = []
543 if id(self) in visited:
544 return
545 visited.append(id(self))
546
Michael Foord345266a2012-03-14 12:24:34 -0700547 self.called = False
548 self.call_args = None
549 self.call_count = 0
550 self.mock_calls = _CallList()
551 self.call_args_list = _CallList()
552 self.method_calls = _CallList()
553
Kushal Das9cd39a12016-06-02 10:20:16 -0700554 if return_value:
555 self._mock_return_value = DEFAULT
556 if side_effect:
557 self._mock_side_effect = None
558
Michael Foord345266a2012-03-14 12:24:34 -0700559 for child in self._mock_children.values():
Xtreakedeca922018-12-01 15:33:54 +0530560 if isinstance(child, _SpecState) or child is _deleted:
Michael Foord75963642012-06-09 17:31:59 +0100561 continue
Robert Collinsb37f43f2015-07-15 11:42:28 +1200562 child.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700563
564 ret = self._mock_return_value
565 if _is_instance_mock(ret) and ret is not self:
Robert Collinsb37f43f2015-07-15 11:42:28 +1200566 ret.reset_mock(visited)
Michael Foord345266a2012-03-14 12:24:34 -0700567
568
569 def configure_mock(self, **kwargs):
570 """Set attributes on the mock through keyword arguments.
571
572 Attributes plus return values and side effects can be set on child
573 mocks using standard dot notation and unpacking a dictionary in the
574 method call:
575
576 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
577 >>> mock.configure_mock(**attrs)"""
578 for arg, val in sorted(kwargs.items(),
579 # we sort on the number of dots so that
580 # attributes are set before we set attributes on
581 # attributes
582 key=lambda entry: entry[0].count('.')):
583 args = arg.split('.')
584 final = args.pop()
585 obj = self
586 for entry in args:
587 obj = getattr(obj, entry)
588 setattr(obj, final, val)
589
590
591 def __getattr__(self, name):
Kushal Das8c145342014-04-16 23:32:21 +0530592 if name in {'_mock_methods', '_mock_unsafe'}:
Michael Foord345266a2012-03-14 12:24:34 -0700593 raise AttributeError(name)
594 elif self._mock_methods is not None:
595 if name not in self._mock_methods or name in _all_magics:
596 raise AttributeError("Mock object has no attribute %r" % name)
597 elif _is_magic(name):
598 raise AttributeError(name)
Kushal Das8c145342014-04-16 23:32:21 +0530599 if not self._mock_unsafe:
600 if name.startswith(('assert', 'assret')):
Zackery Spytzb9b08cd2019-05-08 11:32:24 -0600601 raise AttributeError("Attributes cannot start with 'assert' "
602 "or 'assret'")
Michael Foord345266a2012-03-14 12:24:34 -0700603
604 result = self._mock_children.get(name)
605 if result is _deleted:
606 raise AttributeError(name)
607 elif result is None:
608 wraps = None
609 if self._mock_wraps is not None:
610 # XXXX should we get the attribute without triggering code
611 # execution?
612 wraps = getattr(self._mock_wraps, name)
613
614 result = self._get_child_mock(
615 parent=self, name=name, wraps=wraps, _new_name=name,
616 _new_parent=self
617 )
618 self._mock_children[name] = result
619
620 elif isinstance(result, _SpecState):
621 result = create_autospec(
622 result.spec, result.spec_set, result.instance,
623 result.parent, result.name
624 )
625 self._mock_children[name] = result
626
627 return result
628
629
Mario Corchero552be9d2017-10-17 12:35:11 +0100630 def _extract_mock_name(self):
Michael Foord345266a2012-03-14 12:24:34 -0700631 _name_list = [self._mock_new_name]
632 _parent = self._mock_new_parent
633 last = self
634
635 dot = '.'
636 if _name_list == ['()']:
637 dot = ''
Chris Withersadbf1782019-05-01 23:04:04 +0100638
Michael Foord345266a2012-03-14 12:24:34 -0700639 while _parent is not None:
640 last = _parent
641
642 _name_list.append(_parent._mock_new_name + dot)
643 dot = '.'
644 if _parent._mock_new_name == '()':
645 dot = ''
646
647 _parent = _parent._mock_new_parent
648
Michael Foord345266a2012-03-14 12:24:34 -0700649 _name_list = list(reversed(_name_list))
650 _first = last._mock_name or 'mock'
651 if len(_name_list) > 1:
652 if _name_list[1] not in ('()', '().'):
653 _first += '.'
654 _name_list[0] = _first
Mario Corchero552be9d2017-10-17 12:35:11 +0100655 return ''.join(_name_list)
656
657 def __repr__(self):
658 name = self._extract_mock_name()
Michael Foord345266a2012-03-14 12:24:34 -0700659
660 name_string = ''
661 if name not in ('mock', 'mock.'):
662 name_string = ' name=%r' % name
663
664 spec_string = ''
665 if self._spec_class is not None:
666 spec_string = ' spec=%r'
667 if self._spec_set:
668 spec_string = ' spec_set=%r'
669 spec_string = spec_string % self._spec_class.__name__
670 return "<%s%s%s id='%s'>" % (
671 type(self).__name__,
672 name_string,
673 spec_string,
674 id(self)
675 )
676
677
678 def __dir__(self):
Michael Foordd7c65e22012-03-14 14:56:54 -0700679 """Filter the output of `dir(mock)` to only useful members."""
Michael Foord313f85f2012-03-25 18:16:07 +0100680 if not FILTER_DIR:
681 return object.__dir__(self)
682
Michael Foord345266a2012-03-14 12:24:34 -0700683 extras = self._mock_methods or []
684 from_type = dir(type(self))
685 from_dict = list(self.__dict__)
Mario Corchero0df635c2019-04-30 19:56:36 +0100686 from_child_mocks = [
687 m_name for m_name, m_value in self._mock_children.items()
688 if m_value is not _deleted]
Michael Foord345266a2012-03-14 12:24:34 -0700689
Michael Foord313f85f2012-03-25 18:16:07 +0100690 from_type = [e for e in from_type if not e.startswith('_')]
691 from_dict = [e for e in from_dict if not e.startswith('_') or
692 _is_magic(e)]
Mario Corchero0df635c2019-04-30 19:56:36 +0100693 return sorted(set(extras + from_type + from_dict + from_child_mocks))
Michael Foord345266a2012-03-14 12:24:34 -0700694
695
696 def __setattr__(self, name, value):
697 if name in _allowed_names:
698 # property setters go through here
699 return object.__setattr__(self, name, value)
700 elif (self._spec_set and self._mock_methods is not None and
701 name not in self._mock_methods and
702 name not in self.__dict__):
703 raise AttributeError("Mock object has no attribute '%s'" % name)
704 elif name in _unsupported_magics:
705 msg = 'Attempting to set unsupported magic method %r.' % name
706 raise AttributeError(msg)
707 elif name in _all_magics:
708 if self._mock_methods is not None and name not in self._mock_methods:
709 raise AttributeError("Mock object has no attribute '%s'" % name)
710
711 if not _is_instance_mock(value):
712 setattr(type(self), name, _get_method(name, value))
713 original = value
714 value = lambda *args, **kw: original(self, *args, **kw)
715 else:
716 # only set _new_name and not name so that mock_calls is tracked
717 # but not method calls
718 _check_and_set_parent(self, value, None, name)
719 setattr(type(self), name, value)
Michael Foord75963642012-06-09 17:31:59 +0100720 self._mock_children[name] = value
Michael Foord345266a2012-03-14 12:24:34 -0700721 elif name == '__class__':
722 self._spec_class = value
723 return
724 else:
725 if _check_and_set_parent(self, value, name, name):
726 self._mock_children[name] = value
Mario Corchero552be9d2017-10-17 12:35:11 +0100727
728 if self._mock_sealed and not hasattr(self, name):
729 mock_name = f'{self._extract_mock_name()}.{name}'
730 raise AttributeError(f'Cannot set {mock_name}')
731
Michael Foord345266a2012-03-14 12:24:34 -0700732 return object.__setattr__(self, name, value)
733
734
735 def __delattr__(self, name):
736 if name in _all_magics and name in type(self).__dict__:
737 delattr(type(self), name)
738 if name not in self.__dict__:
739 # for magic methods that are still MagicProxy objects and
740 # not set on the instance itself
741 return
742
Michael Foord345266a2012-03-14 12:24:34 -0700743 obj = self._mock_children.get(name, _missing)
Pablo Galindo222d3032019-01-21 08:57:46 +0000744 if name in self.__dict__:
Xtreak830b43d2019-04-14 00:42:33 +0530745 _safe_super(NonCallableMock, self).__delattr__(name)
Pablo Galindo222d3032019-01-21 08:57:46 +0000746 elif obj is _deleted:
Michael Foord345266a2012-03-14 12:24:34 -0700747 raise AttributeError(name)
748 if obj is not _missing:
749 del self._mock_children[name]
750 self._mock_children[name] = _deleted
751
752
Michael Foord345266a2012-03-14 12:24:34 -0700753 def _format_mock_call_signature(self, args, kwargs):
754 name = self._mock_name or 'mock'
755 return _format_call_signature(name, args, kwargs)
756
757
758 def _format_mock_failure_message(self, args, kwargs):
Susan Su2bdd5852019-02-13 18:22:29 -0800759 message = 'expected call not found.\nExpected: %s\nActual: %s'
Michael Foord345266a2012-03-14 12:24:34 -0700760 expected_string = self._format_mock_call_signature(args, kwargs)
761 call_args = self.call_args
Michael Foord345266a2012-03-14 12:24:34 -0700762 actual_string = self._format_mock_call_signature(*call_args)
763 return message % (expected_string, actual_string)
764
765
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100766 def _call_matcher(self, _call):
767 """
Martin Panter204bf0b2016-07-11 07:51:37 +0000768 Given a call (or simply an (args, kwargs) tuple), return a
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100769 comparison key suitable for matching with other calls.
770 This is a best effort method which relies on the spec's signature,
771 if available, or falls back on the arguments themselves.
772 """
773 sig = self._spec_signature
774 if sig is not None:
775 if len(_call) == 2:
776 name = ''
777 args, kwargs = _call
778 else:
779 name, args, kwargs = _call
780 try:
781 return name, sig.bind(*args, **kwargs)
782 except TypeError as e:
783 return e.with_traceback(None)
784 else:
785 return _call
786
Kushal Das68290f42014-04-17 01:54:07 +0530787 def assert_not_called(_mock_self):
Kushal Das8af9db32014-04-17 01:36:14 +0530788 """assert that the mock was never called.
789 """
790 self = _mock_self
791 if self.call_count != 0:
Petter Strandmark47d94242018-10-28 21:37:10 +0100792 msg = ("Expected '%s' to not have been called. Called %s times.%s"
793 % (self._mock_name or 'mock',
794 self.call_count,
795 self._calls_repr()))
Kushal Das8af9db32014-04-17 01:36:14 +0530796 raise AssertionError(msg)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100797
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100798 def assert_called(_mock_self):
799 """assert that the mock was called at least once
800 """
801 self = _mock_self
802 if self.call_count == 0:
803 msg = ("Expected '%s' to have been called." %
804 self._mock_name or 'mock')
805 raise AssertionError(msg)
806
807 def assert_called_once(_mock_self):
808 """assert that the mock was called only once.
809 """
810 self = _mock_self
811 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100812 msg = ("Expected '%s' to have been called once. Called %s times.%s"
813 % (self._mock_name or 'mock',
814 self.call_count,
815 self._calls_repr()))
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100816 raise AssertionError(msg)
817
Michael Foord345266a2012-03-14 12:24:34 -0700818 def assert_called_with(_mock_self, *args, **kwargs):
819 """assert that the mock was called with the specified arguments.
820
821 Raises an AssertionError if the args and keyword args passed in are
822 different to the last call to the mock."""
823 self = _mock_self
824 if self.call_args is None:
825 expected = self._format_mock_call_signature(args, kwargs)
Susan Su2bdd5852019-02-13 18:22:29 -0800826 actual = 'not called.'
827 error_message = ('expected call not found.\nExpected: %s\nActual: %s'
828 % (expected, actual))
829 raise AssertionError(error_message)
Michael Foord345266a2012-03-14 12:24:34 -0700830
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100831 def _error_message():
Michael Foord345266a2012-03-14 12:24:34 -0700832 msg = self._format_mock_failure_message(args, kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100833 return msg
834 expected = self._call_matcher((args, kwargs))
835 actual = self._call_matcher(self.call_args)
836 if expected != actual:
837 cause = expected if isinstance(expected, Exception) else None
838 raise AssertionError(_error_message()) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700839
840
841 def assert_called_once_with(_mock_self, *args, **kwargs):
Arne de Laat324c5d82017-02-23 15:57:25 +0100842 """assert that the mock was called exactly once and that that call was
843 with the specified arguments."""
Michael Foord345266a2012-03-14 12:24:34 -0700844 self = _mock_self
845 if not self.call_count == 1:
Petter Strandmark47d94242018-10-28 21:37:10 +0100846 msg = ("Expected '%s' to be called once. Called %s times.%s"
847 % (self._mock_name or 'mock',
848 self.call_count,
849 self._calls_repr()))
Michael Foord345266a2012-03-14 12:24:34 -0700850 raise AssertionError(msg)
851 return self.assert_called_with(*args, **kwargs)
852
853
854 def assert_has_calls(self, calls, any_order=False):
855 """assert the mock has been called with the specified calls.
856 The `mock_calls` list is checked for the calls.
857
858 If `any_order` is False (the default) then the calls must be
859 sequential. There can be extra calls before or after the
860 specified calls.
861
862 If `any_order` is True then the calls can be in any order, but
863 they must all appear in `mock_calls`."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100864 expected = [self._call_matcher(c) for c in calls]
865 cause = expected if isinstance(expected, Exception) else None
866 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700867 if not any_order:
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100868 if expected not in all_calls:
Michael Foord345266a2012-03-14 12:24:34 -0700869 raise AssertionError(
Petter Strandmark47d94242018-10-28 21:37:10 +0100870 'Calls not found.\nExpected: %r%s'
871 % (_CallList(calls), self._calls_repr(prefix="Actual"))
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100872 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700873 return
874
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100875 all_calls = list(all_calls)
Michael Foord345266a2012-03-14 12:24:34 -0700876
877 not_found = []
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100878 for kall in expected:
Michael Foord345266a2012-03-14 12:24:34 -0700879 try:
880 all_calls.remove(kall)
881 except ValueError:
882 not_found.append(kall)
883 if not_found:
884 raise AssertionError(
davidair2b32da22018-08-17 15:09:58 -0400885 '%r does not contain all of %r in its call list, '
886 'found %r instead' % (self._mock_name or 'mock',
887 tuple(not_found), all_calls)
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100888 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700889
890
891 def assert_any_call(self, *args, **kwargs):
892 """assert the mock has been called with the specified arguments.
893
894 The assert passes if the mock has *ever* been called, unlike
895 `assert_called_with` and `assert_called_once_with` that only pass if
896 the call is the most recent one."""
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100897 expected = self._call_matcher((args, kwargs))
898 actual = [self._call_matcher(c) for c in self.call_args_list]
899 if expected not in actual:
900 cause = expected if isinstance(expected, Exception) else None
Michael Foord345266a2012-03-14 12:24:34 -0700901 expected_string = self._format_mock_call_signature(args, kwargs)
902 raise AssertionError(
903 '%s call not found' % expected_string
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100904 ) from cause
Michael Foord345266a2012-03-14 12:24:34 -0700905
906
907 def _get_child_mock(self, **kw):
908 """Create the child mocks for attributes and return value.
909 By default child mocks will be the same type as the parent.
910 Subclasses of Mock may want to override this to customize the way
911 child mocks are made.
912
913 For non-callable mocks the callable variant will be used (rather than
914 any custom subclass)."""
Lisa Roach77b3b772019-05-20 09:19:53 -0700915 _new_name = kw.get("_new_name")
916 if _new_name in self.__dict__['_spec_asyncs']:
917 return AsyncMock(**kw)
918
Michael Foord345266a2012-03-14 12:24:34 -0700919 _type = type(self)
Lisa Roach77b3b772019-05-20 09:19:53 -0700920 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
921 klass = AsyncMock
922 if issubclass(_type, AsyncMockMixin):
923 klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -0700924 if not issubclass(_type, CallableMixin):
925 if issubclass(_type, NonCallableMagicMock):
926 klass = MagicMock
927 elif issubclass(_type, NonCallableMock) :
928 klass = Mock
929 else:
930 klass = _type.__mro__[1]
Mario Corchero552be9d2017-10-17 12:35:11 +0100931
932 if self._mock_sealed:
933 attribute = "." + kw["name"] if "name" in kw else "()"
934 mock_name = self._extract_mock_name() + attribute
935 raise AttributeError(mock_name)
936
Michael Foord345266a2012-03-14 12:24:34 -0700937 return klass(**kw)
938
939
Petter Strandmark47d94242018-10-28 21:37:10 +0100940 def _calls_repr(self, prefix="Calls"):
941 """Renders self.mock_calls as a string.
942
943 Example: "\nCalls: [call(1), call(2)]."
944
945 If self.mock_calls is empty, an empty string is returned. The
946 output will be truncated if very long.
947 """
948 if not self.mock_calls:
949 return ""
950 return f"\n{prefix}: {safe_repr(self.mock_calls)}."
951
952
Michael Foord345266a2012-03-14 12:24:34 -0700953
954def _try_iter(obj):
955 if obj is None:
956 return obj
957 if _is_exception(obj):
958 return obj
959 if _callable(obj):
960 return obj
961 try:
962 return iter(obj)
963 except TypeError:
964 # XXXX backwards compatibility
965 # but this will blow up on first call - so maybe we should fail early?
966 return obj
967
968
Michael Foord345266a2012-03-14 12:24:34 -0700969class CallableMixin(Base):
970
971 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
972 wraps=None, name=None, spec_set=None, parent=None,
973 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
974 self.__dict__['_mock_return_value'] = return_value
Nick Coghlan0b43bcf2012-05-27 18:17:07 +1000975 _safe_super(CallableMixin, self).__init__(
Michael Foord345266a2012-03-14 12:24:34 -0700976 spec, wraps, name, spec_set, parent,
977 _spec_state, _new_name, _new_parent, **kwargs
978 )
979
980 self.side_effect = side_effect
981
982
983 def _mock_check_sig(self, *args, **kwargs):
984 # stub method that can be replaced with one with a specific signature
985 pass
986
987
988 def __call__(_mock_self, *args, **kwargs):
989 # can't use self in-case a function / method we are mocking uses self
990 # in the signature
991 _mock_self._mock_check_sig(*args, **kwargs)
992 return _mock_self._mock_call(*args, **kwargs)
993
994
995 def _mock_call(_mock_self, *args, **kwargs):
996 self = _mock_self
997 self.called = True
998 self.call_count += 1
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100999
Chris Withers8ca0fa92018-12-03 21:31:37 +00001000 # handle call_args
Antoine Pitrou5c64df72013-02-03 00:23:58 +01001001 _call = _Call((args, kwargs), two=True)
1002 self.call_args = _call
1003 self.call_args_list.append(_call)
Michael Foord345266a2012-03-14 12:24:34 -07001004
Chris Withers8ca0fa92018-12-03 21:31:37 +00001005 # initial stuff for method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001006 do_method_calls = self._mock_parent is not None
Chris Withers8ca0fa92018-12-03 21:31:37 +00001007 method_call_name = self._mock_name
1008
1009 # initial stuff for mock_calls:
1010 mock_call_name = self._mock_new_name
1011 is_a_call = mock_call_name == '()'
1012 self.mock_calls.append(_Call(('', args, kwargs)))
1013
1014 # follow up the chain of mocks:
1015 _new_parent = self._mock_new_parent
Michael Foord345266a2012-03-14 12:24:34 -07001016 while _new_parent is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001017
Chris Withers8ca0fa92018-12-03 21:31:37 +00001018 # handle method_calls:
Michael Foord345266a2012-03-14 12:24:34 -07001019 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001020 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
Michael Foord345266a2012-03-14 12:24:34 -07001021 do_method_calls = _new_parent._mock_parent is not None
1022 if do_method_calls:
Chris Withers8ca0fa92018-12-03 21:31:37 +00001023 method_call_name = _new_parent._mock_name + '.' + method_call_name
Michael Foord345266a2012-03-14 12:24:34 -07001024
Chris Withers8ca0fa92018-12-03 21:31:37 +00001025 # handle mock_calls:
1026 this_mock_call = _Call((mock_call_name, args, kwargs))
Michael Foord345266a2012-03-14 12:24:34 -07001027 _new_parent.mock_calls.append(this_mock_call)
Chris Withers8ca0fa92018-12-03 21:31:37 +00001028
1029 if _new_parent._mock_new_name:
1030 if is_a_call:
1031 dot = ''
1032 else:
1033 dot = '.'
1034 is_a_call = _new_parent._mock_new_name == '()'
1035 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1036
1037 # follow the parental chain:
Michael Foord345266a2012-03-14 12:24:34 -07001038 _new_parent = _new_parent._mock_new_parent
1039
Michael Foord345266a2012-03-14 12:24:34 -07001040 effect = self.side_effect
1041 if effect is not None:
1042 if _is_exception(effect):
1043 raise effect
Mario Corcherof05df0a2018-12-08 11:25:02 +00001044 elif not _callable(effect):
Michael Foord2cd48732012-04-21 15:52:11 +01001045 result = next(effect)
1046 if _is_exception(result):
1047 raise result
Mario Corcherof05df0a2018-12-08 11:25:02 +00001048 else:
1049 result = effect(*args, **kwargs)
1050
1051 if result is not DEFAULT:
Michael Foord2cd48732012-04-21 15:52:11 +01001052 return result
Michael Foord345266a2012-03-14 12:24:34 -07001053
Mario Corcherof05df0a2018-12-08 11:25:02 +00001054 if self._mock_return_value is not DEFAULT:
1055 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001056
Mario Corcherof05df0a2018-12-08 11:25:02 +00001057 if self._mock_wraps is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001058 return self._mock_wraps(*args, **kwargs)
Mario Corcherof05df0a2018-12-08 11:25:02 +00001059
1060 return self.return_value
Michael Foord345266a2012-03-14 12:24:34 -07001061
1062
1063
1064class Mock(CallableMixin, NonCallableMock):
1065 """
1066 Create a new `Mock` object. `Mock` takes several optional arguments
1067 that specify the behaviour of the Mock object:
1068
1069 * `spec`: This can be either a list of strings or an existing object (a
1070 class or instance) that acts as the specification for the mock object. If
1071 you pass in an object then a list of strings is formed by calling dir on
1072 the object (excluding unsupported magic attributes and methods). Accessing
1073 any attribute not in this list will raise an `AttributeError`.
1074
1075 If `spec` is an object (rather than a list of strings) then
1076 `mock.__class__` returns the class of the spec object. This allows mocks
1077 to pass `isinstance` tests.
1078
1079 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1080 or get an attribute on the mock that isn't on the object passed as
1081 `spec_set` will raise an `AttributeError`.
1082
1083 * `side_effect`: A function to be called whenever the Mock is called. See
1084 the `side_effect` attribute. Useful for raising exceptions or
1085 dynamically changing return values. The function is called with the same
1086 arguments as the mock, and unless it returns `DEFAULT`, the return
1087 value of this function is used as the return value.
1088
Michael Foord2cd48732012-04-21 15:52:11 +01001089 If `side_effect` is an iterable then each call to the mock will return
1090 the next value from the iterable. If any of the members of the iterable
1091 are exceptions they will be raised instead of returned.
Michael Foord345266a2012-03-14 12:24:34 -07001092
Michael Foord345266a2012-03-14 12:24:34 -07001093 * `return_value`: The value returned when the mock is called. By default
1094 this is a new Mock (created on first access). See the
1095 `return_value` attribute.
1096
Michael Foord0682a0c2012-04-13 20:51:20 +01001097 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1098 calling the Mock will pass the call through to the wrapped object
1099 (returning the real result). Attribute access on the mock will return a
1100 Mock object that wraps the corresponding attribute of the wrapped object
1101 (so attempting to access an attribute that doesn't exist will raise an
1102 `AttributeError`).
Michael Foord345266a2012-03-14 12:24:34 -07001103
1104 If the mock has an explicit `return_value` set then calls are not passed
1105 to the wrapped object and the `return_value` is returned instead.
1106
1107 * `name`: If the mock has a name then it will be used in the repr of the
1108 mock. This can be useful for debugging. The name is propagated to child
1109 mocks.
1110
1111 Mocks can also be called with arbitrary keyword arguments. These will be
1112 used to set attributes on the mock after it is created.
1113 """
1114
1115
Michael Foord345266a2012-03-14 12:24:34 -07001116def _dot_lookup(thing, comp, import_path):
1117 try:
1118 return getattr(thing, comp)
1119 except AttributeError:
1120 __import__(import_path)
1121 return getattr(thing, comp)
1122
1123
1124def _importer(target):
1125 components = target.split('.')
1126 import_path = components.pop(0)
1127 thing = __import__(import_path)
1128
1129 for comp in components:
1130 import_path += ".%s" % comp
1131 thing = _dot_lookup(thing, comp, import_path)
1132 return thing
1133
1134
1135def _is_started(patcher):
1136 # XXXX horrible
1137 return hasattr(patcher, 'is_local')
1138
1139
1140class _patch(object):
1141
1142 attribute_name = None
Michael Foordebc1a302014-04-15 17:21:08 -04001143 _active_patches = []
Michael Foord345266a2012-03-14 12:24:34 -07001144
1145 def __init__(
1146 self, getter, attribute, new, spec, create,
1147 spec_set, autospec, new_callable, kwargs
1148 ):
1149 if new_callable is not None:
1150 if new is not DEFAULT:
1151 raise ValueError(
1152 "Cannot use 'new' and 'new_callable' together"
1153 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001154 if autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001155 raise ValueError(
1156 "Cannot use 'autospec' and 'new_callable' together"
1157 )
1158
1159 self.getter = getter
1160 self.attribute = attribute
1161 self.new = new
1162 self.new_callable = new_callable
1163 self.spec = spec
1164 self.create = create
1165 self.has_local = False
1166 self.spec_set = spec_set
1167 self.autospec = autospec
1168 self.kwargs = kwargs
1169 self.additional_patchers = []
1170
1171
1172 def copy(self):
1173 patcher = _patch(
1174 self.getter, self.attribute, self.new, self.spec,
1175 self.create, self.spec_set,
1176 self.autospec, self.new_callable, self.kwargs
1177 )
1178 patcher.attribute_name = self.attribute_name
1179 patcher.additional_patchers = [
1180 p.copy() for p in self.additional_patchers
1181 ]
1182 return patcher
1183
1184
1185 def __call__(self, func):
1186 if isinstance(func, type):
1187 return self.decorate_class(func)
1188 return self.decorate_callable(func)
1189
1190
1191 def decorate_class(self, klass):
1192 for attr in dir(klass):
1193 if not attr.startswith(patch.TEST_PREFIX):
1194 continue
1195
1196 attr_value = getattr(klass, attr)
1197 if not hasattr(attr_value, "__call__"):
1198 continue
1199
1200 patcher = self.copy()
1201 setattr(klass, attr, patcher(attr_value))
1202 return klass
1203
1204
1205 def decorate_callable(self, func):
1206 if hasattr(func, 'patchings'):
1207 func.patchings.append(self)
1208 return func
1209
1210 @wraps(func)
1211 def patched(*args, **keywargs):
Michael Foord345266a2012-03-14 12:24:34 -07001212 extra_args = []
1213 entered_patchers = []
1214
Michael Foord50a8c0e2012-03-25 18:57:58 +01001215 exc_info = tuple()
Michael Foord345266a2012-03-14 12:24:34 -07001216 try:
Michael Foordd7c65e22012-03-14 14:56:54 -07001217 for patching in patched.patchings:
1218 arg = patching.__enter__()
1219 entered_patchers.append(patching)
1220 if patching.attribute_name is not None:
1221 keywargs.update(arg)
1222 elif patching.new is DEFAULT:
1223 extra_args.append(arg)
Michael Foord345266a2012-03-14 12:24:34 -07001224
Michael Foordd7c65e22012-03-14 14:56:54 -07001225 args += tuple(extra_args)
1226 return func(*args, **keywargs)
1227 except:
1228 if (patching not in entered_patchers and
1229 _is_started(patching)):
1230 # the patcher may have been started, but an exception
1231 # raised whilst entering one of its additional_patchers
1232 entered_patchers.append(patching)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001233 # Pass the exception to __exit__
1234 exc_info = sys.exc_info()
Michael Foordd7c65e22012-03-14 14:56:54 -07001235 # re-raise the exception
1236 raise
Michael Foord345266a2012-03-14 12:24:34 -07001237 finally:
1238 for patching in reversed(entered_patchers):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001239 patching.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001240
1241 patched.patchings = [self]
Michael Foord345266a2012-03-14 12:24:34 -07001242 return patched
1243
1244
1245 def get_original(self):
1246 target = self.getter()
1247 name = self.attribute
1248
1249 original = DEFAULT
1250 local = False
1251
1252 try:
1253 original = target.__dict__[name]
1254 except (AttributeError, KeyError):
1255 original = getattr(target, name, DEFAULT)
1256 else:
1257 local = True
1258
Michael Foordfddcfa22014-04-14 16:25:20 -04001259 if name in _builtins and isinstance(target, ModuleType):
1260 self.create = True
1261
Michael Foord345266a2012-03-14 12:24:34 -07001262 if not self.create and original is DEFAULT:
1263 raise AttributeError(
1264 "%s does not have the attribute %r" % (target, name)
1265 )
1266 return original, local
1267
1268
1269 def __enter__(self):
1270 """Perform the patch."""
1271 new, spec, spec_set = self.new, self.spec, self.spec_set
1272 autospec, kwargs = self.autospec, self.kwargs
1273 new_callable = self.new_callable
1274 self.target = self.getter()
1275
Michael Foord50a8c0e2012-03-25 18:57:58 +01001276 # normalise False to None
1277 if spec is False:
1278 spec = None
1279 if spec_set is False:
1280 spec_set = None
1281 if autospec is False:
1282 autospec = None
1283
1284 if spec is not None and autospec is not None:
1285 raise TypeError("Can't specify spec and autospec")
1286 if ((spec is not None or autospec is not None) and
1287 spec_set not in (True, None)):
1288 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1289
Michael Foord345266a2012-03-14 12:24:34 -07001290 original, local = self.get_original()
1291
Michael Foord50a8c0e2012-03-25 18:57:58 +01001292 if new is DEFAULT and autospec is None:
Michael Foord345266a2012-03-14 12:24:34 -07001293 inherit = False
Michael Foord50a8c0e2012-03-25 18:57:58 +01001294 if spec is True:
Michael Foord345266a2012-03-14 12:24:34 -07001295 # set spec to the object we are replacing
1296 spec = original
Michael Foord50a8c0e2012-03-25 18:57:58 +01001297 if spec_set is True:
1298 spec_set = original
1299 spec = None
1300 elif spec is not None:
1301 if spec_set is True:
1302 spec_set = spec
1303 spec = None
1304 elif spec_set is True:
1305 spec_set = original
Michael Foord345266a2012-03-14 12:24:34 -07001306
Michael Foord50a8c0e2012-03-25 18:57:58 +01001307 if spec is not None or spec_set is not None:
1308 if original is DEFAULT:
1309 raise TypeError("Can't use 'spec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001310 if isinstance(original, type):
1311 # If we're patching out a class and there is a spec
1312 inherit = True
Lisa Roach77b3b772019-05-20 09:19:53 -07001313 if spec is None and _is_async_obj(original):
1314 Klass = AsyncMock
1315 else:
1316 Klass = MagicMock
Michael Foord345266a2012-03-14 12:24:34 -07001317 _kwargs = {}
1318 if new_callable is not None:
1319 Klass = new_callable
Michael Foord50a8c0e2012-03-25 18:57:58 +01001320 elif spec is not None or spec_set is not None:
Michael Foorde58a5622012-03-25 19:53:18 +01001321 this_spec = spec
1322 if spec_set is not None:
1323 this_spec = spec_set
1324 if _is_list(this_spec):
1325 not_callable = '__call__' not in this_spec
1326 else:
1327 not_callable = not callable(this_spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07001328 if _is_async_obj(this_spec):
1329 Klass = AsyncMock
1330 elif not_callable:
Michael Foord345266a2012-03-14 12:24:34 -07001331 Klass = NonCallableMagicMock
1332
1333 if spec is not None:
1334 _kwargs['spec'] = spec
1335 if spec_set is not None:
1336 _kwargs['spec_set'] = spec_set
1337
1338 # add a name to mocks
1339 if (isinstance(Klass, type) and
1340 issubclass(Klass, NonCallableMock) and self.attribute):
1341 _kwargs['name'] = self.attribute
1342
1343 _kwargs.update(kwargs)
1344 new = Klass(**_kwargs)
1345
1346 if inherit and _is_instance_mock(new):
1347 # we can only tell if the instance should be callable if the
1348 # spec is not a list
Michael Foord50a8c0e2012-03-25 18:57:58 +01001349 this_spec = spec
1350 if spec_set is not None:
1351 this_spec = spec_set
1352 if (not _is_list(this_spec) and not
1353 _instance_callable(this_spec)):
Michael Foord345266a2012-03-14 12:24:34 -07001354 Klass = NonCallableMagicMock
1355
1356 _kwargs.pop('name')
1357 new.return_value = Klass(_new_parent=new, _new_name='()',
1358 **_kwargs)
Michael Foord50a8c0e2012-03-25 18:57:58 +01001359 elif autospec is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001360 # spec is ignored, new *must* be default, spec_set is treated
1361 # as a boolean. Should we check spec is not None and that spec_set
1362 # is a bool?
1363 if new is not DEFAULT:
1364 raise TypeError(
1365 "autospec creates the mock for you. Can't specify "
1366 "autospec and new."
1367 )
Michael Foord50a8c0e2012-03-25 18:57:58 +01001368 if original is DEFAULT:
Michael Foord99254732012-03-25 19:07:33 +01001369 raise TypeError("Can't use 'autospec' with create=True")
Michael Foord345266a2012-03-14 12:24:34 -07001370 spec_set = bool(spec_set)
1371 if autospec is True:
1372 autospec = original
1373
1374 new = create_autospec(autospec, spec_set=spec_set,
1375 _name=self.attribute, **kwargs)
1376 elif kwargs:
1377 # can't set keyword args when we aren't creating the mock
1378 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1379 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1380
1381 new_attr = new
1382
1383 self.temp_original = original
1384 self.is_local = local
1385 setattr(self.target, self.attribute, new_attr)
1386 if self.attribute_name is not None:
1387 extra_args = {}
1388 if self.new is DEFAULT:
1389 extra_args[self.attribute_name] = new
1390 for patching in self.additional_patchers:
1391 arg = patching.__enter__()
1392 if patching.new is DEFAULT:
1393 extra_args.update(arg)
1394 return extra_args
1395
1396 return new
1397
1398
Michael Foord50a8c0e2012-03-25 18:57:58 +01001399 def __exit__(self, *exc_info):
Michael Foord345266a2012-03-14 12:24:34 -07001400 """Undo the patch."""
1401 if not _is_started(self):
Xtreak02b84cb2019-03-29 02:38:43 +05301402 return
Michael Foord345266a2012-03-14 12:24:34 -07001403
1404 if self.is_local and self.temp_original is not DEFAULT:
1405 setattr(self.target, self.attribute, self.temp_original)
1406 else:
1407 delattr(self.target, self.attribute)
Senthil Kumaran81bc9272016-01-08 23:43:29 -08001408 if not self.create and (not hasattr(self.target, self.attribute) or
1409 self.attribute in ('__doc__', '__module__',
1410 '__defaults__', '__annotations__',
1411 '__kwdefaults__')):
Michael Foord345266a2012-03-14 12:24:34 -07001412 # needed for proxy objects like django settings
1413 setattr(self.target, self.attribute, self.temp_original)
1414
1415 del self.temp_original
1416 del self.is_local
1417 del self.target
1418 for patcher in reversed(self.additional_patchers):
1419 if _is_started(patcher):
Michael Foord50a8c0e2012-03-25 18:57:58 +01001420 patcher.__exit__(*exc_info)
Michael Foord345266a2012-03-14 12:24:34 -07001421
Michael Foordf7c41582012-06-10 20:36:32 +01001422
1423 def start(self):
1424 """Activate a patch, returning any created mock."""
1425 result = self.__enter__()
Michael Foordebc1a302014-04-15 17:21:08 -04001426 self._active_patches.append(self)
Michael Foordf7c41582012-06-10 20:36:32 +01001427 return result
1428
1429
1430 def stop(self):
1431 """Stop an active patch."""
Michael Foordebc1a302014-04-15 17:21:08 -04001432 try:
1433 self._active_patches.remove(self)
1434 except ValueError:
1435 # If the patch hasn't been started this will fail
1436 pass
1437
Michael Foordf7c41582012-06-10 20:36:32 +01001438 return self.__exit__()
Michael Foord345266a2012-03-14 12:24:34 -07001439
1440
1441
1442def _get_target(target):
1443 try:
1444 target, attribute = target.rsplit('.', 1)
1445 except (TypeError, ValueError):
1446 raise TypeError("Need a valid target to patch. You supplied: %r" %
1447 (target,))
1448 getter = lambda: _importer(target)
1449 return getter, attribute
1450
1451
1452def _patch_object(
1453 target, attribute, new=DEFAULT, spec=None,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001454 create=False, spec_set=None, autospec=None,
Michael Foord345266a2012-03-14 12:24:34 -07001455 new_callable=None, **kwargs
1456 ):
1457 """
Michael Foord345266a2012-03-14 12:24:34 -07001458 patch the named member (`attribute`) on an object (`target`) with a mock
1459 object.
1460
1461 `patch.object` can be used as a decorator, class decorator or a context
1462 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1463 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1464 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1465 the mock object it creates.
1466
1467 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1468 for choosing which methods to wrap.
1469 """
1470 getter = lambda: target
1471 return _patch(
1472 getter, attribute, new, spec, create,
1473 spec_set, autospec, new_callable, kwargs
1474 )
1475
1476
Michael Foord50a8c0e2012-03-25 18:57:58 +01001477def _patch_multiple(target, spec=None, create=False, spec_set=None,
1478 autospec=None, new_callable=None, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001479 """Perform multiple patches in a single call. It takes the object to be
1480 patched (either as an object or a string to fetch the object by importing)
1481 and keyword arguments for the patches::
1482
1483 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1484 ...
1485
1486 Use `DEFAULT` as the value if you want `patch.multiple` to create
1487 mocks for you. In this case the created mocks are passed into a decorated
1488 function by keyword, and a dictionary is returned when `patch.multiple` is
1489 used as a context manager.
1490
1491 `patch.multiple` can be used as a decorator, class decorator or a context
1492 manager. The arguments `spec`, `spec_set`, `create`,
1493 `autospec` and `new_callable` have the same meaning as for `patch`. These
1494 arguments will be applied to *all* patches done by `patch.multiple`.
1495
1496 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1497 for choosing which methods to wrap.
1498 """
1499 if type(target) is str:
1500 getter = lambda: _importer(target)
1501 else:
1502 getter = lambda: target
1503
1504 if not kwargs:
1505 raise ValueError(
1506 'Must supply at least one keyword argument with patch.multiple'
1507 )
1508 # need to wrap in a list for python 3, where items is a view
1509 items = list(kwargs.items())
1510 attribute, new = items[0]
1511 patcher = _patch(
1512 getter, attribute, new, spec, create, spec_set,
1513 autospec, new_callable, {}
1514 )
1515 patcher.attribute_name = attribute
1516 for attribute, new in items[1:]:
1517 this_patcher = _patch(
1518 getter, attribute, new, spec, create, spec_set,
1519 autospec, new_callable, {}
1520 )
1521 this_patcher.attribute_name = attribute
1522 patcher.additional_patchers.append(this_patcher)
1523 return patcher
1524
1525
1526def patch(
1527 target, new=DEFAULT, spec=None, create=False,
Michael Foord50a8c0e2012-03-25 18:57:58 +01001528 spec_set=None, autospec=None, new_callable=None, **kwargs
Michael Foord345266a2012-03-14 12:24:34 -07001529 ):
1530 """
1531 `patch` acts as a function decorator, class decorator or a context
1532 manager. Inside the body of the function or with statement, the `target`
Michael Foord54b3db82012-03-28 15:08:08 +01001533 is patched with a `new` object. When the function/with statement exits
1534 the patch is undone.
Michael Foord345266a2012-03-14 12:24:34 -07001535
Michael Foord54b3db82012-03-28 15:08:08 +01001536 If `new` is omitted, then the target is replaced with a
1537 `MagicMock`. If `patch` is used as a decorator and `new` is
1538 omitted, the created mock is passed in as an extra argument to the
1539 decorated function. If `patch` is used as a context manager the created
1540 mock is returned by the context manager.
Michael Foord345266a2012-03-14 12:24:34 -07001541
Michael Foord54b3db82012-03-28 15:08:08 +01001542 `target` should be a string in the form `'package.module.ClassName'`. The
1543 `target` is imported and the specified object replaced with the `new`
1544 object, so the `target` must be importable from the environment you are
1545 calling `patch` from. The target is imported when the decorated function
1546 is executed, not at decoration time.
Michael Foord345266a2012-03-14 12:24:34 -07001547
1548 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1549 if patch is creating one for you.
1550
1551 In addition you can pass `spec=True` or `spec_set=True`, which causes
1552 patch to pass in the object being mocked as the spec/spec_set object.
1553
1554 `new_callable` allows you to specify a different class, or callable object,
1555 that will be called to create the `new` object. By default `MagicMock` is
1556 used.
1557
1558 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
Robert Collins92b3e0652015-07-17 21:58:36 +12001559 then the mock will be created with a spec from the object being replaced.
Michael Foord345266a2012-03-14 12:24:34 -07001560 All attributes of the mock will also have the spec of the corresponding
1561 attribute of the object being replaced. Methods and functions being
1562 mocked will have their arguments checked and will raise a `TypeError` if
1563 they are called with the wrong signature. For mocks replacing a class,
1564 their return value (the 'instance') will have the same spec as the class.
1565
1566 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1567 arbitrary object as the spec instead of the one being replaced.
1568
1569 By default `patch` will fail to replace attributes that don't exist. If
1570 you pass in `create=True`, and the attribute doesn't exist, patch will
1571 create the attribute for you when the patched function is called, and
1572 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001573 attributes that your production code creates at runtime. It is off by
Michael Foord345266a2012-03-14 12:24:34 -07001574 default because it can be dangerous. With it switched on you can write
1575 passing tests against APIs that don't actually exist!
1576
1577 Patch can be used as a `TestCase` class decorator. It works by
1578 decorating each test method in the class. This reduces the boilerplate
1579 code when your test methods share a common patchings set. `patch` finds
1580 tests by looking for method names that start with `patch.TEST_PREFIX`.
1581 By default this is `test`, which matches the way `unittest` finds tests.
1582 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1583
1584 Patch can be used as a context manager, with the with statement. Here the
1585 patching applies to the indented block after the with statement. If you
1586 use "as" then the patched object will be bound to the name after the
1587 "as"; very useful if `patch` is creating a mock object for you.
1588
1589 `patch` takes arbitrary keyword arguments. These will be passed to
1590 the `Mock` (or `new_callable`) on construction.
1591
1592 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1593 available for alternate use-cases.
1594 """
1595 getter, attribute = _get_target(target)
1596 return _patch(
1597 getter, attribute, new, spec, create,
1598 spec_set, autospec, new_callable, kwargs
1599 )
1600
1601
1602class _patch_dict(object):
1603 """
1604 Patch a dictionary, or dictionary like object, and restore the dictionary
1605 to its original state after the test.
1606
1607 `in_dict` can be a dictionary or a mapping like container. If it is a
1608 mapping then it must at least support getting, setting and deleting items
1609 plus iterating over keys.
1610
1611 `in_dict` can also be a string specifying the name of the dictionary, which
1612 will then be fetched by importing it.
1613
1614 `values` can be a dictionary of values to set in the dictionary. `values`
1615 can also be an iterable of `(key, value)` pairs.
1616
1617 If `clear` is True then the dictionary will be cleared before the new
1618 values are set.
1619
1620 `patch.dict` can also be called with arbitrary keyword arguments to set
1621 values in the dictionary::
1622
1623 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1624 ...
1625
1626 `patch.dict` can be used as a context manager, decorator or class
1627 decorator. When used as a class decorator `patch.dict` honours
1628 `patch.TEST_PREFIX` for choosing which methods to wrap.
1629 """
1630
1631 def __init__(self, in_dict, values=(), clear=False, **kwargs):
Michael Foord345266a2012-03-14 12:24:34 -07001632 self.in_dict = in_dict
1633 # support any argument supported by dict(...) constructor
1634 self.values = dict(values)
1635 self.values.update(kwargs)
1636 self.clear = clear
1637 self._original = None
1638
1639
1640 def __call__(self, f):
1641 if isinstance(f, type):
1642 return self.decorate_class(f)
1643 @wraps(f)
1644 def _inner(*args, **kw):
1645 self._patch_dict()
1646 try:
1647 return f(*args, **kw)
1648 finally:
1649 self._unpatch_dict()
1650
1651 return _inner
1652
1653
1654 def decorate_class(self, klass):
1655 for attr in dir(klass):
1656 attr_value = getattr(klass, attr)
1657 if (attr.startswith(patch.TEST_PREFIX) and
1658 hasattr(attr_value, "__call__")):
1659 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1660 decorated = decorator(attr_value)
1661 setattr(klass, attr, decorated)
1662 return klass
1663
1664
1665 def __enter__(self):
1666 """Patch the dict."""
1667 self._patch_dict()
1668
1669
1670 def _patch_dict(self):
1671 values = self.values
Xtreaka875ea52019-02-25 00:24:49 +05301672 if isinstance(self.in_dict, str):
1673 self.in_dict = _importer(self.in_dict)
Michael Foord345266a2012-03-14 12:24:34 -07001674 in_dict = self.in_dict
1675 clear = self.clear
1676
1677 try:
1678 original = in_dict.copy()
1679 except AttributeError:
1680 # dict like object with no copy method
1681 # must support iteration over keys
1682 original = {}
1683 for key in in_dict:
1684 original[key] = in_dict[key]
1685 self._original = original
1686
1687 if clear:
1688 _clear_dict(in_dict)
1689
1690 try:
1691 in_dict.update(values)
1692 except AttributeError:
1693 # dict like object with no update method
1694 for key in values:
1695 in_dict[key] = values[key]
1696
1697
1698 def _unpatch_dict(self):
1699 in_dict = self.in_dict
1700 original = self._original
1701
1702 _clear_dict(in_dict)
1703
1704 try:
1705 in_dict.update(original)
1706 except AttributeError:
1707 for key in original:
1708 in_dict[key] = original[key]
1709
1710
1711 def __exit__(self, *args):
1712 """Unpatch the dict."""
1713 self._unpatch_dict()
1714 return False
1715
1716 start = __enter__
1717 stop = __exit__
1718
1719
1720def _clear_dict(in_dict):
1721 try:
1722 in_dict.clear()
1723 except AttributeError:
1724 keys = list(in_dict)
1725 for key in keys:
1726 del in_dict[key]
1727
1728
Michael Foordf7c41582012-06-10 20:36:32 +01001729def _patch_stopall():
Michael Foordebc1a302014-04-15 17:21:08 -04001730 """Stop all active patches. LIFO to unroll nested patches."""
1731 for patch in reversed(_patch._active_patches):
Michael Foordf7c41582012-06-10 20:36:32 +01001732 patch.stop()
1733
1734
Michael Foord345266a2012-03-14 12:24:34 -07001735patch.object = _patch_object
1736patch.dict = _patch_dict
1737patch.multiple = _patch_multiple
Michael Foordf7c41582012-06-10 20:36:32 +01001738patch.stopall = _patch_stopall
Michael Foord345266a2012-03-14 12:24:34 -07001739patch.TEST_PREFIX = 'test'
1740
1741magic_methods = (
1742 "lt le gt ge eq ne "
1743 "getitem setitem delitem "
1744 "len contains iter "
1745 "hash str sizeof "
1746 "enter exit "
Berker Peksaga785dec2015-03-15 01:51:56 +02001747 # we added divmod and rdivmod here instead of numerics
1748 # because there is no idivmod
1749 "divmod rdivmod neg pos abs invert "
Michael Foord345266a2012-03-14 12:24:34 -07001750 "complex int float index "
John Reese6c4fab02018-05-22 13:01:10 -07001751 "round trunc floor ceil "
Michael Foord345266a2012-03-14 12:24:34 -07001752 "bool next "
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001753 "fspath "
Michael Foord345266a2012-03-14 12:24:34 -07001754)
1755
Michael Foordd2623d72014-04-14 11:23:48 -04001756numerics = (
Berker Peksag9bd8af72015-03-12 20:42:48 +02001757 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"
Michael Foordd2623d72014-04-14 11:23:48 -04001758)
Michael Foord345266a2012-03-14 12:24:34 -07001759inplace = ' '.join('i%s' % n for n in numerics.split())
1760right = ' '.join('r%s' % n for n in numerics.split())
1761
1762# not including __prepare__, __instancecheck__, __subclasscheck__
1763# (as they are metaclass methods)
1764# __del__ is not supported at all as it causes problems if it exists
1765
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001766_non_defaults = {
1767 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
1768 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
1769 '__getstate__', '__setstate__', '__getformat__', '__setformat__',
1770 '__repr__', '__dir__', '__subclasses__', '__format__',
Lisa Roach77b3b772019-05-20 09:19:53 -07001771 '__getnewargs_ex__', '__aenter__', '__aexit__', '__anext__', '__aiter__',
Victor Stinnereb1a9952014-12-11 22:25:49 +01001772}
Michael Foord345266a2012-03-14 12:24:34 -07001773
1774
1775def _get_method(name, func):
1776 "Turns a callable object (like a mock) into a real function"
1777 def method(self, *args, **kw):
1778 return func(self, *args, **kw)
1779 method.__name__ = name
1780 return method
1781
1782
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001783_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001784 '__%s__' % method for method in
1785 ' '.join([magic_methods, numerics, inplace, right]).split()
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001786}
Michael Foord345266a2012-03-14 12:24:34 -07001787
Lisa Roach77b3b772019-05-20 09:19:53 -07001788# Magic methods used for async `with` statements
1789_async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
1790# `__aiter__` is a plain function but used with async calls
1791_async_magics = _async_method_magics | {"__aiter__"}
1792
Michael Foord345266a2012-03-14 12:24:34 -07001793_all_magics = _magics | _non_defaults
1794
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001795_unsupported_magics = {
Michael Foord345266a2012-03-14 12:24:34 -07001796 '__getattr__', '__setattr__',
Serhiy Storchaka34fd4c22018-11-05 16:20:25 +02001797 '__init__', '__new__', '__prepare__',
Michael Foord345266a2012-03-14 12:24:34 -07001798 '__instancecheck__', '__subclasscheck__',
1799 '__del__'
Serhiy Storchakac02d1882014-12-11 10:28:14 +02001800}
Michael Foord345266a2012-03-14 12:24:34 -07001801
1802_calculate_return_value = {
1803 '__hash__': lambda self: object.__hash__(self),
1804 '__str__': lambda self: object.__str__(self),
1805 '__sizeof__': lambda self: object.__sizeof__(self),
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001806 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
Michael Foord345266a2012-03-14 12:24:34 -07001807}
1808
1809_return_values = {
Michael Foord313f85f2012-03-25 18:16:07 +01001810 '__lt__': NotImplemented,
1811 '__gt__': NotImplemented,
1812 '__le__': NotImplemented,
1813 '__ge__': NotImplemented,
Michael Foord345266a2012-03-14 12:24:34 -07001814 '__int__': 1,
1815 '__contains__': False,
1816 '__len__': 0,
1817 '__exit__': False,
1818 '__complex__': 1j,
1819 '__float__': 1.0,
1820 '__bool__': True,
1821 '__index__': 1,
Lisa Roach77b3b772019-05-20 09:19:53 -07001822 '__aexit__': False,
Michael Foord345266a2012-03-14 12:24:34 -07001823}
1824
1825
1826def _get_eq(self):
1827 def __eq__(other):
1828 ret_val = self.__eq__._mock_return_value
1829 if ret_val is not DEFAULT:
1830 return ret_val
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001831 if self is other:
1832 return True
1833 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001834 return __eq__
1835
1836def _get_ne(self):
1837 def __ne__(other):
1838 if self.__ne__._mock_return_value is not DEFAULT:
1839 return DEFAULT
Serhiy Storchaka362f0582017-01-21 23:12:58 +02001840 if self is other:
1841 return False
1842 return NotImplemented
Michael Foord345266a2012-03-14 12:24:34 -07001843 return __ne__
1844
1845def _get_iter(self):
1846 def __iter__():
1847 ret_val = self.__iter__._mock_return_value
1848 if ret_val is DEFAULT:
1849 return iter([])
1850 # if ret_val was already an iterator, then calling iter on it should
1851 # return the iterator unchanged
1852 return iter(ret_val)
1853 return __iter__
1854
Lisa Roach77b3b772019-05-20 09:19:53 -07001855def _get_async_iter(self):
1856 def __aiter__():
1857 ret_val = self.__aiter__._mock_return_value
1858 if ret_val is DEFAULT:
1859 return _AsyncIterator(iter([]))
1860 return _AsyncIterator(iter(ret_val))
1861 return __aiter__
1862
Michael Foord345266a2012-03-14 12:24:34 -07001863_side_effect_methods = {
1864 '__eq__': _get_eq,
1865 '__ne__': _get_ne,
1866 '__iter__': _get_iter,
Lisa Roach77b3b772019-05-20 09:19:53 -07001867 '__aiter__': _get_async_iter
Michael Foord345266a2012-03-14 12:24:34 -07001868}
1869
1870
1871
1872def _set_return_value(mock, method, name):
1873 fixed = _return_values.get(name, DEFAULT)
1874 if fixed is not DEFAULT:
1875 method.return_value = fixed
1876 return
1877
1878 return_calulator = _calculate_return_value.get(name)
1879 if return_calulator is not None:
Chris Withersadbf1782019-05-01 23:04:04 +01001880 return_value = return_calulator(mock)
Michael Foord345266a2012-03-14 12:24:34 -07001881 method.return_value = return_value
1882 return
1883
1884 side_effector = _side_effect_methods.get(name)
1885 if side_effector is not None:
1886 method.side_effect = side_effector(mock)
1887
1888
1889
1890class MagicMixin(object):
1891 def __init__(self, *args, **kw):
Łukasz Langaa468db92015-04-13 23:12:42 -07001892 self._mock_set_magics() # make magic work for kwargs in init
Nick Coghlan0b43bcf2012-05-27 18:17:07 +10001893 _safe_super(MagicMixin, self).__init__(*args, **kw)
Łukasz Langaa468db92015-04-13 23:12:42 -07001894 self._mock_set_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001895
1896
1897 def _mock_set_magics(self):
1898 these_magics = _magics
1899
Łukasz Langaa468db92015-04-13 23:12:42 -07001900 if getattr(self, "_mock_methods", None) is not None:
Michael Foord345266a2012-03-14 12:24:34 -07001901 these_magics = _magics.intersection(self._mock_methods)
1902
1903 remove_magics = set()
1904 remove_magics = _magics - these_magics
1905
1906 for entry in remove_magics:
1907 if entry in type(self).__dict__:
1908 # remove unneeded magic methods
1909 delattr(self, entry)
1910
1911 # don't overwrite existing attributes if called a second time
1912 these_magics = these_magics - set(type(self).__dict__)
1913
1914 _type = type(self)
1915 for entry in these_magics:
1916 setattr(_type, entry, MagicProxy(entry, self))
1917
1918
1919
1920class NonCallableMagicMock(MagicMixin, NonCallableMock):
1921 """A version of `MagicMock` that isn't callable."""
1922 def mock_add_spec(self, spec, spec_set=False):
1923 """Add a spec to a mock. `spec` can either be an object or a
1924 list of strings. Only attributes on the `spec` can be fetched as
1925 attributes from the mock.
1926
1927 If `spec_set` is True then only attributes on the spec can be set."""
1928 self._mock_add_spec(spec, spec_set)
1929 self._mock_set_magics()
1930
1931
Lisa Roach77b3b772019-05-20 09:19:53 -07001932class AsyncMagicMixin:
1933 def __init__(self, *args, **kw):
1934 self._mock_set_async_magics() # make magic work for kwargs in init
1935 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)
1936 self._mock_set_async_magics() # fix magic broken by upper level init
Michael Foord345266a2012-03-14 12:24:34 -07001937
Lisa Roach77b3b772019-05-20 09:19:53 -07001938 def _mock_set_async_magics(self):
1939 these_magics = _async_magics
1940
1941 if getattr(self, "_mock_methods", None) is not None:
1942 these_magics = _async_magics.intersection(self._mock_methods)
1943 remove_magics = _async_magics - these_magics
1944
1945 for entry in remove_magics:
1946 if entry in type(self).__dict__:
1947 # remove unneeded magic methods
1948 delattr(self, entry)
1949
1950 # don't overwrite existing attributes if called a second time
1951 these_magics = these_magics - set(type(self).__dict__)
1952
1953 _type = type(self)
1954 for entry in these_magics:
1955 setattr(_type, entry, MagicProxy(entry, self))
1956
1957
1958class MagicMock(MagicMixin, AsyncMagicMixin, Mock):
Michael Foord345266a2012-03-14 12:24:34 -07001959 """
1960 MagicMock is a subclass of Mock with default implementations
1961 of most of the magic methods. You can use MagicMock without having to
1962 configure the magic methods yourself.
1963
1964 If you use the `spec` or `spec_set` arguments then *only* magic
1965 methods that exist in the spec will be created.
1966
1967 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1968 """
1969 def mock_add_spec(self, spec, spec_set=False):
1970 """Add a spec to a mock. `spec` can either be an object or a
1971 list of strings. Only attributes on the `spec` can be fetched as
1972 attributes from the mock.
1973
1974 If `spec_set` is True then only attributes on the spec can be set."""
1975 self._mock_add_spec(spec, spec_set)
1976 self._mock_set_magics()
1977
1978
1979
1980class MagicProxy(object):
1981 def __init__(self, name, parent):
1982 self.name = name
1983 self.parent = parent
1984
Michael Foord345266a2012-03-14 12:24:34 -07001985 def create_mock(self):
1986 entry = self.name
1987 parent = self.parent
1988 m = parent._get_child_mock(name=entry, _new_name=entry,
1989 _new_parent=parent)
1990 setattr(parent, entry, m)
1991 _set_return_value(parent, m, entry)
1992 return m
1993
1994 def __get__(self, obj, _type=None):
1995 return self.create_mock()
1996
1997
Lisa Roach77b3b772019-05-20 09:19:53 -07001998class AsyncMockMixin(Base):
1999 awaited = _delegating_property('awaited')
2000 await_count = _delegating_property('await_count')
2001 await_args = _delegating_property('await_args')
2002 await_args_list = _delegating_property('await_args_list')
2003
2004 def __init__(self, *args, **kwargs):
2005 super().__init__(*args, **kwargs)
2006 # asyncio.iscoroutinefunction() checks _is_coroutine property to say if an
2007 # object is a coroutine. Without this check it looks to see if it is a
2008 # function/method, which in this case it is not (since it is an
2009 # AsyncMock).
2010 # It is set through __dict__ because when spec_set is True, this
2011 # attribute is likely undefined.
2012 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
2013 self.__dict__['_mock_awaited'] = _AwaitEvent(self)
2014 self.__dict__['_mock_await_count'] = 0
2015 self.__dict__['_mock_await_args'] = None
2016 self.__dict__['_mock_await_args_list'] = _CallList()
2017 code_mock = NonCallableMock(spec_set=CodeType)
2018 code_mock.co_flags = inspect.CO_COROUTINE
2019 self.__dict__['__code__'] = code_mock
2020
2021 async def _mock_call(_mock_self, *args, **kwargs):
2022 self = _mock_self
2023 try:
2024 result = super()._mock_call(*args, **kwargs)
2025 except (BaseException, StopIteration) as e:
2026 side_effect = self.side_effect
2027 if side_effect is not None and not callable(side_effect):
2028 raise
2029 return await _raise(e)
2030
2031 _call = self.call_args
2032
2033 async def proxy():
2034 try:
2035 if inspect.isawaitable(result):
2036 return await result
2037 else:
2038 return result
2039 finally:
2040 self.await_count += 1
2041 self.await_args = _call
2042 self.await_args_list.append(_call)
2043 await self.awaited._notify()
2044
2045 return await proxy()
2046
2047 def assert_awaited(_mock_self):
2048 """
2049 Assert that the mock was awaited at least once.
2050 """
2051 self = _mock_self
2052 if self.await_count == 0:
2053 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2054 raise AssertionError(msg)
2055
2056 def assert_awaited_once(_mock_self):
2057 """
2058 Assert that the mock was awaited exactly once.
2059 """
2060 self = _mock_self
2061 if not self.await_count == 1:
2062 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2063 f" Awaited {self.await_count} times.")
2064 raise AssertionError(msg)
2065
2066 def assert_awaited_with(_mock_self, *args, **kwargs):
2067 """
2068 Assert that the last await was with the specified arguments.
2069 """
2070 self = _mock_self
2071 if self.await_args is None:
2072 expected = self._format_mock_call_signature(args, kwargs)
2073 raise AssertionError(f'Expected await: {expected}\nNot awaited')
2074
2075 def _error_message():
2076 msg = self._format_mock_failure_message(args, kwargs)
2077 return msg
2078
2079 expected = self._call_matcher((args, kwargs))
2080 actual = self._call_matcher(self.await_args)
2081 if expected != actual:
2082 cause = expected if isinstance(expected, Exception) else None
2083 raise AssertionError(_error_message()) from cause
2084
2085 def assert_awaited_once_with(_mock_self, *args, **kwargs):
2086 """
2087 Assert that the mock was awaited exactly once and with the specified
2088 arguments.
2089 """
2090 self = _mock_self
2091 if not self.await_count == 1:
2092 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2093 f" Awaited {self.await_count} times.")
2094 raise AssertionError(msg)
2095 return self.assert_awaited_with(*args, **kwargs)
2096
2097 def assert_any_await(_mock_self, *args, **kwargs):
2098 """
2099 Assert the mock has ever been awaited with the specified arguments.
2100 """
2101 self = _mock_self
2102 expected = self._call_matcher((args, kwargs))
2103 actual = [self._call_matcher(c) for c in self.await_args_list]
2104 if expected not in actual:
2105 cause = expected if isinstance(expected, Exception) else None
2106 expected_string = self._format_mock_call_signature(args, kwargs)
2107 raise AssertionError(
2108 '%s await not found' % expected_string
2109 ) from cause
2110
2111 def assert_has_awaits(_mock_self, calls, any_order=False):
2112 """
2113 Assert the mock has been awaited with the specified calls.
2114 The :attr:`await_args_list` list is checked for the awaits.
2115
2116 If `any_order` is False (the default) then the awaits must be
2117 sequential. There can be extra calls before or after the
2118 specified awaits.
2119
2120 If `any_order` is True then the awaits can be in any order, but
2121 they must all appear in :attr:`await_args_list`.
2122 """
2123 self = _mock_self
2124 expected = [self._call_matcher(c) for c in calls]
2125 cause = expected if isinstance(expected, Exception) else None
2126 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2127 if not any_order:
2128 if expected not in all_awaits:
2129 raise AssertionError(
2130 f'Awaits not found.\nExpected: {_CallList(calls)}\n',
2131 f'Actual: {self.await_args_list}'
2132 ) from cause
2133 return
2134
2135 all_awaits = list(all_awaits)
2136
2137 not_found = []
2138 for kall in expected:
2139 try:
2140 all_awaits.remove(kall)
2141 except ValueError:
2142 not_found.append(kall)
2143 if not_found:
2144 raise AssertionError(
2145 '%r not all found in await list' % (tuple(not_found),)
2146 ) from cause
2147
2148 def assert_not_awaited(_mock_self):
2149 """
2150 Assert that the mock was never awaited.
2151 """
2152 self = _mock_self
2153 if self.await_count != 0:
2154 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2155 f" Awaited {self.await_count} times.")
2156 raise AssertionError(msg)
2157
2158 def reset_mock(self, *args, **kwargs):
2159 """
2160 See :func:`.Mock.reset_mock()`
2161 """
2162 super().reset_mock(*args, **kwargs)
2163 self.await_count = 0
2164 self.await_args = None
2165 self.await_args_list = _CallList()
2166
2167
2168class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2169 """
2170 Enhance :class:`Mock` with features allowing to mock
2171 an async function.
2172
2173 The :class:`AsyncMock` object will behave so the object is
2174 recognized as an async function, and the result of a call is an awaitable:
2175
2176 >>> mock = AsyncMock()
2177 >>> asyncio.iscoroutinefunction(mock)
2178 True
2179 >>> inspect.isawaitable(mock())
2180 True
2181
2182
2183 The result of ``mock()`` is an async function which will have the outcome
2184 of ``side_effect`` or ``return_value``:
2185
2186 - if ``side_effect`` is a function, the async function will return the
2187 result of that function,
2188 - if ``side_effect`` is an exception, the async function will raise the
2189 exception,
2190 - if ``side_effect`` is an iterable, the async function will return the
2191 next value of the iterable, however, if the sequence of result is
2192 exhausted, ``StopIteration`` is raised immediately,
2193 - if ``side_effect`` is not defined, the async function will return the
2194 value defined by ``return_value``, hence, by default, the async function
2195 returns a new :class:`AsyncMock` object.
2196
2197 If the outcome of ``side_effect`` or ``return_value`` is an async function,
2198 the mock async function obtained when the mock object is called will be this
2199 async function itself (and not an async function returning an async
2200 function).
2201
2202 The test author can also specify a wrapped object with ``wraps``. In this
2203 case, the :class:`Mock` object behavior is the same as with an
2204 :class:`.Mock` object: the wrapped object may have methods
2205 defined as async function functions.
2206
2207 Based on Martin Richard's asyntest project.
2208 """
2209
Michael Foord345266a2012-03-14 12:24:34 -07002210
2211class _ANY(object):
2212 "A helper object that compares equal to everything."
2213
2214 def __eq__(self, other):
2215 return True
2216
2217 def __ne__(self, other):
2218 return False
2219
2220 def __repr__(self):
2221 return '<ANY>'
2222
2223ANY = _ANY()
2224
2225
2226
2227def _format_call_signature(name, args, kwargs):
2228 message = '%s(%%s)' % name
2229 formatted_args = ''
2230 args_string = ', '.join([repr(arg) for arg in args])
2231 kwargs_string = ', '.join([
Kushal Das047f14c2014-06-09 13:45:56 +05302232 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
Michael Foord345266a2012-03-14 12:24:34 -07002233 ])
2234 if args_string:
2235 formatted_args = args_string
2236 if kwargs_string:
2237 if formatted_args:
2238 formatted_args += ', '
2239 formatted_args += kwargs_string
2240
2241 return message % formatted_args
2242
2243
2244
2245class _Call(tuple):
2246 """
2247 A tuple for holding the results of a call to a mock, either in the form
2248 `(args, kwargs)` or `(name, args, kwargs)`.
2249
2250 If args or kwargs are empty then a call tuple will compare equal to
2251 a tuple without those values. This makes comparisons less verbose::
2252
2253 _Call(('name', (), {})) == ('name',)
2254 _Call(('name', (1,), {})) == ('name', (1,))
2255 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2256
2257 The `_Call` object provides a useful shortcut for comparing with call::
2258
2259 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2260 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2261
2262 If the _Call has no name then it will match any name.
2263 """
Victor Stinner84b6fb02017-01-06 18:15:51 +01002264 def __new__(cls, value=(), name='', parent=None, two=False,
Michael Foord345266a2012-03-14 12:24:34 -07002265 from_kall=True):
Michael Foord345266a2012-03-14 12:24:34 -07002266 args = ()
2267 kwargs = {}
2268 _len = len(value)
2269 if _len == 3:
2270 name, args, kwargs = value
2271 elif _len == 2:
2272 first, second = value
2273 if isinstance(first, str):
2274 name = first
2275 if isinstance(second, tuple):
2276 args = second
2277 else:
2278 kwargs = second
2279 else:
2280 args, kwargs = first, second
2281 elif _len == 1:
2282 value, = value
2283 if isinstance(value, str):
2284 name = value
2285 elif isinstance(value, tuple):
2286 args = value
2287 else:
2288 kwargs = value
2289
2290 if two:
2291 return tuple.__new__(cls, (args, kwargs))
2292
2293 return tuple.__new__(cls, (name, args, kwargs))
2294
2295
2296 def __init__(self, value=(), name=None, parent=None, two=False,
2297 from_kall=True):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002298 self._mock_name = name
2299 self._mock_parent = parent
2300 self._mock_from_kall = from_kall
Michael Foord345266a2012-03-14 12:24:34 -07002301
2302
2303 def __eq__(self, other):
2304 if other is ANY:
2305 return True
2306 try:
2307 len_other = len(other)
2308 except TypeError:
2309 return False
2310
2311 self_name = ''
2312 if len(self) == 2:
2313 self_args, self_kwargs = self
2314 else:
2315 self_name, self_args, self_kwargs = self
2316
Andrew Dunaie63e6172018-12-04 11:08:45 +02002317 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2318 and self._mock_parent != other._mock_parent):
Chris Withers8ca0fa92018-12-03 21:31:37 +00002319 return False
2320
Michael Foord345266a2012-03-14 12:24:34 -07002321 other_name = ''
2322 if len_other == 0:
2323 other_args, other_kwargs = (), {}
2324 elif len_other == 3:
2325 other_name, other_args, other_kwargs = other
2326 elif len_other == 1:
2327 value, = other
2328 if isinstance(value, tuple):
2329 other_args = value
2330 other_kwargs = {}
2331 elif isinstance(value, str):
2332 other_name = value
2333 other_args, other_kwargs = (), {}
2334 else:
2335 other_args = ()
2336 other_kwargs = value
Berker Peksag3fc536f2015-09-09 23:35:25 +03002337 elif len_other == 2:
Michael Foord345266a2012-03-14 12:24:34 -07002338 # could be (name, args) or (name, kwargs) or (args, kwargs)
2339 first, second = other
2340 if isinstance(first, str):
2341 other_name = first
2342 if isinstance(second, tuple):
2343 other_args, other_kwargs = second, {}
2344 else:
2345 other_args, other_kwargs = (), second
2346 else:
2347 other_args, other_kwargs = first, second
Berker Peksag3fc536f2015-09-09 23:35:25 +03002348 else:
2349 return False
Michael Foord345266a2012-03-14 12:24:34 -07002350
2351 if self_name and other_name != self_name:
2352 return False
2353
2354 # this order is important for ANY to work!
2355 return (other_args, other_kwargs) == (self_args, self_kwargs)
2356
2357
Berker Peksagce913872016-03-28 00:30:02 +03002358 __ne__ = object.__ne__
2359
2360
Michael Foord345266a2012-03-14 12:24:34 -07002361 def __call__(self, *args, **kwargs):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002362 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002363 return _Call(('', args, kwargs), name='()')
2364
Andrew Dunaie63e6172018-12-04 11:08:45 +02002365 name = self._mock_name + '()'
2366 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
Michael Foord345266a2012-03-14 12:24:34 -07002367
2368
2369 def __getattr__(self, attr):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002370 if self._mock_name is None:
Michael Foord345266a2012-03-14 12:24:34 -07002371 return _Call(name=attr, from_kall=False)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002372 name = '%s.%s' % (self._mock_name, attr)
Michael Foord345266a2012-03-14 12:24:34 -07002373 return _Call(name=name, parent=self, from_kall=False)
2374
2375
Kushal Dasa37b9582014-09-16 18:33:37 +05302376 def count(self, *args, **kwargs):
2377 return self.__getattr__('count')(*args, **kwargs)
2378
2379 def index(self, *args, **kwargs):
2380 return self.__getattr__('index')(*args, **kwargs)
2381
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302382 def _get_call_arguments(self):
2383 if len(self) == 2:
2384 args, kwargs = self
2385 else:
2386 name, args, kwargs = self
2387
2388 return args, kwargs
2389
2390 @property
2391 def args(self):
2392 return self._get_call_arguments()[0]
2393
2394 @property
2395 def kwargs(self):
2396 return self._get_call_arguments()[1]
2397
Michael Foord345266a2012-03-14 12:24:34 -07002398 def __repr__(self):
Andrew Dunaie63e6172018-12-04 11:08:45 +02002399 if not self._mock_from_kall:
2400 name = self._mock_name or 'call'
Michael Foord345266a2012-03-14 12:24:34 -07002401 if name.startswith('()'):
2402 name = 'call%s' % name
2403 return name
2404
2405 if len(self) == 2:
2406 name = 'call'
2407 args, kwargs = self
2408 else:
2409 name, args, kwargs = self
2410 if not name:
2411 name = 'call'
2412 elif not name.startswith('()'):
2413 name = 'call.%s' % name
2414 else:
2415 name = 'call%s' % name
2416 return _format_call_signature(name, args, kwargs)
2417
2418
2419 def call_list(self):
2420 """For a call object that represents multiple calls, `call_list`
2421 returns a list of all the intermediate calls as well as the
2422 final call."""
2423 vals = []
2424 thing = self
2425 while thing is not None:
Andrew Dunaie63e6172018-12-04 11:08:45 +02002426 if thing._mock_from_kall:
Michael Foord345266a2012-03-14 12:24:34 -07002427 vals.append(thing)
Andrew Dunaie63e6172018-12-04 11:08:45 +02002428 thing = thing._mock_parent
Michael Foord345266a2012-03-14 12:24:34 -07002429 return _CallList(reversed(vals))
2430
2431
2432call = _Call(from_kall=False)
2433
2434
Michael Foord345266a2012-03-14 12:24:34 -07002435def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2436 _name=None, **kwargs):
2437 """Create a mock object using another object as a spec. Attributes on the
2438 mock will use the corresponding attribute on the `spec` object as their
2439 spec.
2440
2441 Functions or methods being mocked will have their arguments checked
2442 to check that they are called with the correct signature.
2443
2444 If `spec_set` is True then attempting to set attributes that don't exist
2445 on the spec object will raise an `AttributeError`.
2446
2447 If a class is used as a spec then the return value of the mock (the
2448 instance of the class) will have the same spec. You can use a class as the
2449 spec for an instance object by passing `instance=True`. The returned mock
2450 will only be callable if instances of the mock are callable.
2451
2452 `create_autospec` also takes arbitrary keyword arguments that are passed to
2453 the constructor of the created mock."""
2454 if _is_list(spec):
2455 # can't pass a list instance to the mock constructor as it will be
2456 # interpreted as a list of strings
2457 spec = type(spec)
2458
2459 is_type = isinstance(spec, type)
Lisa Roach77b3b772019-05-20 09:19:53 -07002460 if getattr(spec, '__code__', None):
2461 is_async_func = asyncio.iscoroutinefunction(spec)
2462 else:
2463 is_async_func = False
Michael Foord345266a2012-03-14 12:24:34 -07002464 _kwargs = {'spec': spec}
2465 if spec_set:
2466 _kwargs = {'spec_set': spec}
2467 elif spec is None:
2468 # None we mock with a normal mock without a spec
2469 _kwargs = {}
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002470 if _kwargs and instance:
2471 _kwargs['_spec_as_instance'] = True
Michael Foord345266a2012-03-14 12:24:34 -07002472
2473 _kwargs.update(kwargs)
2474
2475 Klass = MagicMock
Gregory P. Smithd4583d72016-08-15 23:23:40 -07002476 if inspect.isdatadescriptor(spec):
Michael Foord345266a2012-03-14 12:24:34 -07002477 # descriptors don't have a spec
2478 # because we don't know what type they return
2479 _kwargs = {}
Lisa Roach77b3b772019-05-20 09:19:53 -07002480 elif is_async_func:
2481 if instance:
2482 raise RuntimeError("Instance can not be True when create_autospec "
2483 "is mocking an async function")
2484 Klass = AsyncMock
Michael Foord345266a2012-03-14 12:24:34 -07002485 elif not _callable(spec):
2486 Klass = NonCallableMagicMock
2487 elif is_type and instance and not _instance_callable(spec):
2488 Klass = NonCallableMagicMock
2489
Kushal Das484f8a82014-04-16 01:05:50 +05302490 _name = _kwargs.pop('name', _name)
2491
Michael Foord345266a2012-03-14 12:24:34 -07002492 _new_name = _name
2493 if _parent is None:
2494 # for a top level object no _new_name should be set
2495 _new_name = ''
2496
2497 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2498 name=_name, **_kwargs)
2499
2500 if isinstance(spec, FunctionTypes):
Lisa Roach77b3b772019-05-20 09:19:53 -07002501 wrapped_mock = mock
Michael Foord345266a2012-03-14 12:24:34 -07002502 # should only happen at the top level because we don't
2503 # recurse for functions
2504 mock = _set_signature(mock, spec)
Lisa Roach77b3b772019-05-20 09:19:53 -07002505 if is_async_func:
2506 mock._is_coroutine = asyncio.coroutines._is_coroutine
2507 mock.await_count = 0
2508 mock.await_args = None
2509 mock.await_args_list = _CallList()
2510
2511 for a in ('assert_awaited',
2512 'assert_awaited_once',
2513 'assert_awaited_with',
2514 'assert_awaited_once_with',
2515 'assert_any_await',
2516 'assert_has_awaits',
2517 'assert_not_awaited'):
2518 def f(*args, **kwargs):
2519 return getattr(wrapped_mock, a)(*args, **kwargs)
2520 setattr(mock, a, f)
Michael Foord345266a2012-03-14 12:24:34 -07002521 else:
2522 _check_signature(spec, mock, is_type, instance)
2523
2524 if _parent is not None and not instance:
2525 _parent._mock_children[_name] = mock
2526
2527 if is_type and not instance and 'return_value' not in kwargs:
Michael Foord345266a2012-03-14 12:24:34 -07002528 mock.return_value = create_autospec(spec, spec_set, instance=True,
2529 _name='()', _parent=mock)
2530
2531 for entry in dir(spec):
2532 if _is_magic(entry):
2533 # MagicMock already does the useful magic methods for us
2534 continue
2535
Michael Foord345266a2012-03-14 12:24:34 -07002536 # XXXX do we need a better way of getting attributes without
2537 # triggering code execution (?) Probably not - we need the actual
2538 # object to mock it so we would rather trigger a property than mock
2539 # the property descriptor. Likewise we want to mock out dynamically
2540 # provided attributes.
Michael Foord656319e2012-04-13 17:39:16 +01002541 # XXXX what about attributes that raise exceptions other than
2542 # AttributeError on being fetched?
Michael Foord345266a2012-03-14 12:24:34 -07002543 # we could be resilient against it, or catch and propagate the
2544 # exception when the attribute is fetched from the mock
Michael Foord656319e2012-04-13 17:39:16 +01002545 try:
2546 original = getattr(spec, entry)
2547 except AttributeError:
2548 continue
Michael Foord345266a2012-03-14 12:24:34 -07002549
2550 kwargs = {'spec': original}
2551 if spec_set:
2552 kwargs = {'spec_set': original}
2553
2554 if not isinstance(original, FunctionTypes):
2555 new = _SpecState(original, spec_set, mock, entry, instance)
2556 mock._mock_children[entry] = new
2557 else:
2558 parent = mock
2559 if isinstance(spec, FunctionTypes):
2560 parent = mock.mock
2561
Michael Foord345266a2012-03-14 12:24:34 -07002562 skipfirst = _must_skip(spec, entry, is_type)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002563 kwargs['_eat_self'] = skipfirst
Lisa Roach77b3b772019-05-20 09:19:53 -07002564 if asyncio.iscoroutinefunction(original):
2565 child_klass = AsyncMock
2566 else:
2567 child_klass = MagicMock
2568 new = child_klass(parent=parent, name=entry, _new_name=entry,
2569 _new_parent=parent,
2570 **kwargs)
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002571 mock._mock_children[entry] = new
Michael Foord345266a2012-03-14 12:24:34 -07002572 _check_signature(original, new, skipfirst=skipfirst)
2573
2574 # so functions created with _set_signature become instance attributes,
2575 # *plus* their underlying mock exists in _mock_children of the parent
2576 # mock. Adding to _mock_children may be unnecessary where we are also
2577 # setting as an instance attribute?
2578 if isinstance(new, FunctionTypes):
2579 setattr(mock, entry, new)
2580
2581 return mock
2582
2583
2584def _must_skip(spec, entry, is_type):
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002585 """
2586 Return whether we should skip the first argument on spec's `entry`
2587 attribute.
2588 """
Michael Foord345266a2012-03-14 12:24:34 -07002589 if not isinstance(spec, type):
2590 if entry in getattr(spec, '__dict__', {}):
2591 # instance attribute - shouldn't skip
2592 return False
Michael Foord345266a2012-03-14 12:24:34 -07002593 spec = spec.__class__
Michael Foord345266a2012-03-14 12:24:34 -07002594
2595 for klass in spec.__mro__:
2596 result = klass.__dict__.get(entry, DEFAULT)
2597 if result is DEFAULT:
2598 continue
2599 if isinstance(result, (staticmethod, classmethod)):
2600 return False
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002601 elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2602 # Normal method => skip if looked up on type
2603 # (if looked up on instance, self is already skipped)
2604 return is_type
2605 else:
2606 return False
Michael Foord345266a2012-03-14 12:24:34 -07002607
Chris Withersadbf1782019-05-01 23:04:04 +01002608 # function is a dynamically provided attribute
Michael Foord345266a2012-03-14 12:24:34 -07002609 return is_type
2610
2611
Michael Foord345266a2012-03-14 12:24:34 -07002612class _SpecState(object):
2613
2614 def __init__(self, spec, spec_set=False, parent=None,
2615 name=None, ids=None, instance=False):
2616 self.spec = spec
2617 self.ids = ids
2618 self.spec_set = spec_set
2619 self.parent = parent
2620 self.instance = instance
2621 self.name = name
2622
2623
2624FunctionTypes = (
2625 # python function
2626 type(create_autospec),
2627 # instance method
2628 type(ANY.__eq__),
Michael Foord345266a2012-03-14 12:24:34 -07002629)
2630
Antoine Pitrou5c64df72013-02-03 00:23:58 +01002631MethodWrapperTypes = (
2632 type(ANY.__eq__.__get__),
2633)
2634
Michael Foord345266a2012-03-14 12:24:34 -07002635
Michael Foorda74561a2012-03-25 19:03:13 +01002636file_spec = None
Michael Foord345266a2012-03-14 12:24:34 -07002637
Michael Foord04cbe0c2013-03-19 17:22:51 -07002638
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002639def _to_stream(read_data):
2640 if isinstance(read_data, bytes):
2641 return io.BytesIO(read_data)
Michael Foord04cbe0c2013-03-19 17:22:51 -07002642 else:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002643 return io.StringIO(read_data)
Michael Foord0dccf652012-03-25 19:11:50 +01002644
Robert Collins5329aaa2015-07-17 20:08:45 +12002645
Michael Foord0dccf652012-03-25 19:11:50 +01002646def mock_open(mock=None, read_data=''):
Michael Foord99254732012-03-25 19:07:33 +01002647 """
2648 A helper function to create a mock to replace the use of `open`. It works
2649 for `open` called directly or used as a context manager.
2650
2651 The `mock` argument is the mock object to configure. If `None` (the
2652 default) then a `MagicMock` will be created for you, with the API limited
2653 to methods or attributes available on standard file handles.
2654
Xtreak71f82a22018-12-20 21:30:21 +05302655 `read_data` is a string for the `read`, `readline` and `readlines` of the
Michael Foord04cbe0c2013-03-19 17:22:51 -07002656 file handle to return. This is an empty string by default.
Michael Foord99254732012-03-25 19:07:33 +01002657 """
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002658 _read_data = _to_stream(read_data)
2659 _state = [_read_data, None]
2660
Robert Collinsca647ef2015-07-24 03:48:20 +12002661 def _readlines_side_effect(*args, **kwargs):
2662 if handle.readlines.return_value is not None:
2663 return handle.readlines.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002664 return _state[0].readlines(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002665
2666 def _read_side_effect(*args, **kwargs):
2667 if handle.read.return_value is not None:
2668 return handle.read.return_value
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002669 return _state[0].read(*args, **kwargs)
Robert Collinsca647ef2015-07-24 03:48:20 +12002670
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002671 def _readline_side_effect(*args, **kwargs):
Tony Flury20870232018-09-12 23:21:16 +01002672 yield from _iter_side_effect()
2673 while True:
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002674 yield _state[0].readline(*args, **kwargs)
Tony Flury20870232018-09-12 23:21:16 +01002675
2676 def _iter_side_effect():
Robert Collinsca647ef2015-07-24 03:48:20 +12002677 if handle.readline.return_value is not None:
2678 while True:
2679 yield handle.readline.return_value
2680 for line in _state[0]:
2681 yield line
Robert Collinsca647ef2015-07-24 03:48:20 +12002682
Michael Foorda74561a2012-03-25 19:03:13 +01002683 global file_spec
2684 if file_spec is None:
2685 import _io
2686 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2687
Michael Foord345266a2012-03-14 12:24:34 -07002688 if mock is None:
Michael Foord0dccf652012-03-25 19:11:50 +01002689 mock = MagicMock(name='open', spec=open)
Michael Foord345266a2012-03-14 12:24:34 -07002690
Robert Collinsca647ef2015-07-24 03:48:20 +12002691 handle = MagicMock(spec=file_spec)
2692 handle.__enter__.return_value = handle
Michael Foord04cbe0c2013-03-19 17:22:51 -07002693
Robert Collinsca647ef2015-07-24 03:48:20 +12002694 handle.write.return_value = None
2695 handle.read.return_value = None
2696 handle.readline.return_value = None
2697 handle.readlines.return_value = None
Michael Foord04cbe0c2013-03-19 17:22:51 -07002698
Robert Collinsca647ef2015-07-24 03:48:20 +12002699 handle.read.side_effect = _read_side_effect
2700 _state[1] = _readline_side_effect()
2701 handle.readline.side_effect = _state[1]
2702 handle.readlines.side_effect = _readlines_side_effect
Tony Flury20870232018-09-12 23:21:16 +01002703 handle.__iter__.side_effect = _iter_side_effect
Michael Foord345266a2012-03-14 12:24:34 -07002704
Robert Collinsca647ef2015-07-24 03:48:20 +12002705 def reset_data(*args, **kwargs):
Rémi Lapeyre11a88322019-05-07 12:48:36 +02002706 _state[0] = _to_stream(read_data)
Robert Collinsca647ef2015-07-24 03:48:20 +12002707 if handle.readline.side_effect == _state[1]:
2708 # Only reset the side effect if the user hasn't overridden it.
2709 _state[1] = _readline_side_effect()
2710 handle.readline.side_effect = _state[1]
2711 return DEFAULT
Robert Collins5329aaa2015-07-17 20:08:45 +12002712
Robert Collinsca647ef2015-07-24 03:48:20 +12002713 mock.side_effect = reset_data
2714 mock.return_value = handle
Michael Foord345266a2012-03-14 12:24:34 -07002715 return mock
2716
2717
2718class PropertyMock(Mock):
Michael Foord99254732012-03-25 19:07:33 +01002719 """
2720 A mock intended to be used as a property, or other descriptor, on a class.
2721 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2722 a return value when it is fetched.
2723
2724 Fetching a `PropertyMock` instance from an object calls the mock, with
2725 no args. Setting it calls the mock with the value being set.
2726 """
Michael Foordc2870622012-04-13 16:57:22 +01002727 def _get_child_mock(self, **kwargs):
2728 return MagicMock(**kwargs)
2729
Michael Foord345266a2012-03-14 12:24:34 -07002730 def __get__(self, obj, obj_type):
2731 return self()
2732 def __set__(self, obj, val):
2733 self(val)
Mario Corchero552be9d2017-10-17 12:35:11 +01002734
2735
2736def seal(mock):
Mario Corchero96200eb2018-10-19 22:57:37 +01002737 """Disable the automatic generation of child mocks.
Mario Corchero552be9d2017-10-17 12:35:11 +01002738
2739 Given an input Mock, seals it to ensure no further mocks will be generated
2740 when accessing an attribute that was not already defined.
2741
Mario Corchero96200eb2018-10-19 22:57:37 +01002742 The operation recursively seals the mock passed in, meaning that
2743 the mock itself, any mocks generated by accessing one of its attributes,
2744 and all assigned mocks without a name or spec will be sealed.
Mario Corchero552be9d2017-10-17 12:35:11 +01002745 """
2746 mock._mock_sealed = True
2747 for attr in dir(mock):
2748 try:
2749 m = getattr(mock, attr)
2750 except AttributeError:
2751 continue
2752 if not isinstance(m, NonCallableMock):
2753 continue
2754 if m._mock_new_parent is mock:
2755 seal(m)
Lisa Roach77b3b772019-05-20 09:19:53 -07002756
2757
2758async def _raise(exception):
2759 raise exception
2760
2761
2762class _AsyncIterator:
2763 """
2764 Wraps an iterator in an asynchronous iterator.
2765 """
2766 def __init__(self, iterator):
2767 self.iterator = iterator
2768 code_mock = NonCallableMock(spec_set=CodeType)
2769 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
2770 self.__dict__['__code__'] = code_mock
2771
2772 def __aiter__(self):
2773 return self
2774
2775 async def __anext__(self):
2776 try:
2777 return next(self.iterator)
2778 except StopIteration:
2779 pass
2780 raise StopAsyncIteration
2781
2782
2783class _AwaitEvent:
2784 def __init__(self, mock):
2785 self._mock = mock
2786 self._condition = None
2787
2788 async def _notify(self):
2789 condition = self._get_condition()
2790 try:
2791 await condition.acquire()
2792 condition.notify_all()
2793 finally:
2794 condition.release()
2795
2796 def _get_condition(self):
2797 """
2798 Creation of condition is delayed, to minimize the chance of using the
2799 wrong loop.
2800 A user may create a mock with _AwaitEvent before selecting the
2801 execution loop. Requiring a user to delay creation is error-prone and
2802 inflexible. Instead, condition is created when user actually starts to
2803 use the mock.
2804 """
2805 # No synchronization is needed:
2806 # - asyncio is thread unsafe
2807 # - there are no awaits here, method will be executed without
2808 # switching asyncio context.
2809 if self._condition is None:
2810 self._condition = asyncio.Condition()
2811
2812 return self._condition