Debian Codegraph @

Lib/unittest/mock.py

raw
1 # mock.py
2 # Test tools for mocking and patching.
3 # Maintained by Michael Foord
4 # Backport for other versions of Python available from
5 # https://pypi.org/project/mock
6
7 __all__ = (
8 'Mock',
9 'MagicMock',
10 'patch',
11 'sentinel',
12 'DEFAULT',
13 'ANY',
14 'call',
15 'create_autospec',
16 'AsyncMock',
17 'ThreadingMock',
18 'FILTER_DIR',
19 'NonCallableMock',
20 'NonCallableMagicMock',
21 'mock_open',
22 'PropertyMock',
23 'seal',
24 )
25
26
27 import asyncio
28 import contextlib
29 import io
30 import inspect
31 import pprint
32 import sys
33 import builtins
34 import pkgutil
35 from inspect import iscoroutinefunction
36 import threading
37 from annotationlib import Format
38 from dataclasses import fields, is_dataclass
39 from types import CodeType, ModuleType, MethodType
40 from unittest.util import safe_repr
41 from functools import wraps, partial
42 from threading import RLock
43
44
45 class InvalidSpecError(Exception):
46 """Indicates that an invalid value was used as a mock spec."""
47
48
49 _builtins = {name for name in dir(builtins) if not name.startswith('_')}
50
51 FILTER_DIR = True
52
53 # Workaround for issue #12370
54 # Without this, the __class__ properties wouldn't be set correctly
55 _safe_super = super
56
57 def _is_async_obj(obj):
58 if _is_instance_mock(obj) and not isinstance(obj, AsyncMock):
59 return False
60 if hasattr(obj, '__func__'):
61 obj = getattr(obj, '__func__')
62 return iscoroutinefunction(obj) or inspect.isawaitable(obj)
63
64
65 def _is_async_func(func):
66 if getattr(func, '__code__', None):
67 return iscoroutinefunction(func)
68 else:
69 return False
70
71
72 def _is_instance_mock(obj):
73 # can't use isinstance on Mock objects because they override __class__
74 # The base class for all mocks is NonCallableMock
75 return issubclass(type(obj), NonCallableMock)
76
77
78 def _is_exception(obj):
79 return (
80 isinstance(obj, BaseException) or
81 isinstance(obj, type) and issubclass(obj, BaseException)
82 )
83
84
85 def _extract_mock(obj):
86 # Autospecced functions will return a FunctionType with "mock" attribute
87 # which is the actual mock object that needs to be used.
88 if isinstance(obj, FunctionTypes) and hasattr(obj, 'mock'):
89 return obj.mock
90 else:
91 return obj
92
93
94 def _get_signature_object(func, as_instance, eat_self):
95 """
96 Given an arbitrary, possibly callable object, try to create a suitable
97 signature object.
98 Return a (reduced func, signature) tuple, or None.
99 """
100 if isinstance(func, type) and not as_instance:
101 # If it's a type and should be modelled as a type, use __init__.
102 func = func.__init__
103 # Skip the `self` argument in __init__
104 eat_self = True
105 elif isinstance(func, (classmethod, staticmethod)):
106 if isinstance(func, classmethod):
107 # Skip the `cls` argument of a class method
108 eat_self = True
109 # Use the original decorated method to extract the correct function signature
110 func = func.__func__
111 elif not isinstance(func, FunctionTypes):
112 # If we really want to model an instance of the passed type,
113 # __call__ should be looked up, not __init__.
114 try:
115 func = func.__call__
116 except AttributeError:
117 return None
118 if eat_self:
119 sig_func = partial(func, None)
120 else:
121 sig_func = func
122 try:
123 return func, inspect.signature(sig_func, annotation_format=Format.FORWARDREF)
124 except ValueError:
125 # Certain callable types are not supported by inspect.signature()
126 return None
127
128
129 def _check_signature(func, mock, skipfirst, instance=False):
130 sig = _get_signature_object(func, instance, skipfirst)
131 if sig is None:
132 return
133 func, sig = sig
134 def checksig(self, /, *args, **kwargs):
135 sig.bind(*args, **kwargs)
136 _copy_func_details(func, checksig)
137 type(mock)._mock_check_sig = checksig
138 type(mock).__signature__ = sig
139
140
141 def _copy_func_details(func, funcopy):
142 # we explicitly don't copy func.__dict__ into this copy as it would
143 # expose original attributes that should be mocked
144 for attribute in (
145 '__name__', '__doc__', '__text_signature__',
146 '__module__', '__defaults__', '__kwdefaults__',
147 ):
148 try:
149 setattr(funcopy, attribute, getattr(func, attribute))
150 except AttributeError:
151 pass
152
153
154 def _callable(obj):
155 if isinstance(obj, type):
156 return True
157 if isinstance(obj, (staticmethod, classmethod, MethodType)):
158 return _callable(obj.__func__)
159 if getattr(obj, '__call__', None) is not None:
160 return True
161 return False
162
163
164 def _is_list(obj):
165 # checks for list or tuples
166 # XXXX badly named!
167 return type(obj) in (list, tuple)
168
169
170 def _instance_callable(obj):
171 """Given an object, return True if the object is callable.
172 For classes, return True if instances would be callable."""
173 if not isinstance(obj, type):
174 # already an instance
175 return getattr(obj, '__call__', None) is not None
176
177 # *could* be broken by a class overriding __mro__ or __dict__ via
178 # a metaclass
179 for base in (obj,) + obj.__mro__:
180 if base.__dict__.get('__call__') is not None:
181 return True
182 return False
183
184
185 def _set_signature(mock, original, instance=False):
186 # creates a function with signature (*args, **kwargs) that delegates to a
187 # mock. It still does signature checking by calling a lambda with the same
188 # signature as the original.
189
190 skipfirst = isinstance(original, type)
191 result = _get_signature_object(original, instance, skipfirst)
192 if result is None:
193 return mock
194 func, sig = result
195 def checksig(*args, **kwargs):
196 sig.bind(*args, **kwargs)
197 _copy_func_details(func, checksig)
198
199 name = original.__name__
200 if not name.isidentifier():
201 name = 'funcopy'
202 context = {'_checksig_': checksig, 'mock': mock}
203 src = """def %s(*args, **kwargs):
204 _checksig_(*args, **kwargs)
205 return mock(*args, **kwargs)""" % name
206 exec (src, context)
207 funcopy = context[name]
208 _setup_func(funcopy, mock, sig)
209 return funcopy
210
211 def _set_async_signature(mock, original, instance=False, is_async_mock=False):
212 # creates an async function with signature (*args, **kwargs) that delegates to a
213 # mock. It still does signature checking by calling a lambda with the same
214 # signature as the original.
215
216 skipfirst = isinstance(original, type)
217 func, sig = _get_signature_object(original, instance, skipfirst)
218 def checksig(*args, **kwargs):
219 sig.bind(*args, **kwargs)
220 _copy_func_details(func, checksig)
221
222 name = original.__name__
223 context = {'_checksig_': checksig, 'mock': mock}
224 src = """async def %s(*args, **kwargs):
225 _checksig_(*args, **kwargs)
226 return await mock(*args, **kwargs)""" % name
227 exec (src, context)
228 funcopy = context[name]
229 _setup_func(funcopy, mock, sig)
230 _setup_async_mock(funcopy)
231 return funcopy
232
233
234 def _setup_func(funcopy, mock, sig):
235 funcopy.mock = mock
236
237 def assert_called_with(*args, **kwargs):
238 return mock.assert_called_with(*args, **kwargs)
239 def assert_called(*args, **kwargs):
240 return mock.assert_called(*args, **kwargs)
241 def assert_not_called(*args, **kwargs):
242 return mock.assert_not_called(*args, **kwargs)
243 def assert_called_once(*args, **kwargs):
244 return mock.assert_called_once(*args, **kwargs)
245 def assert_called_once_with(*args, **kwargs):
246 return mock.assert_called_once_with(*args, **kwargs)
247 def assert_has_calls(*args, **kwargs):
248 return mock.assert_has_calls(*args, **kwargs)
249 def assert_any_call(*args, **kwargs):
250 return mock.assert_any_call(*args, **kwargs)
251 def reset_mock():
252 funcopy.method_calls = _CallList()
253 funcopy.mock_calls = _CallList()
254 mock.reset_mock()
255 ret = funcopy.return_value
256 if _is_instance_mock(ret) and not ret is mock:
257 ret.reset_mock()
258
259 funcopy.called = False
260 funcopy.call_count = 0
261 funcopy.call_args = None
262 funcopy.call_args_list = _CallList()
263 funcopy.method_calls = _CallList()
264 funcopy.mock_calls = _CallList()
265
266 funcopy.return_value = mock.return_value
267 funcopy.side_effect = mock.side_effect
268 funcopy._mock_children = mock._mock_children
269
270 funcopy.assert_called_with = assert_called_with
271 funcopy.assert_called_once_with = assert_called_once_with
272 funcopy.assert_has_calls = assert_has_calls
273 funcopy.assert_any_call = assert_any_call
274 funcopy.reset_mock = reset_mock
275 funcopy.assert_called = assert_called
276 funcopy.assert_not_called = assert_not_called
277 funcopy.assert_called_once = assert_called_once
278 funcopy.__signature__ = sig
279
280 mock._mock_delegate = funcopy
281
282
283 def _setup_async_mock(mock):
284 mock._is_coroutine = asyncio.coroutines._is_coroutine
285 mock.await_count = 0
286 mock.await_args = None
287 mock.await_args_list = _CallList()
288
289 # Mock is not configured yet so the attributes are set
290 # to a function and then the corresponding mock helper function
291 # is called when the helper is accessed similar to _setup_func.
292 def wrapper(attr, /, *args, **kwargs):
293 return getattr(mock.mock, attr)(*args, **kwargs)
294
295 for attribute in ('assert_awaited',
296 'assert_awaited_once',
297 'assert_awaited_with',
298 'assert_awaited_once_with',
299 'assert_any_await',
300 'assert_has_awaits',
301 'assert_not_awaited'):
302
303 # setattr(mock, attribute, wrapper) causes late binding
304 # hence attribute will always be the last value in the loop
305 # Use partial(wrapper, attribute) to ensure the attribute is bound
306 # correctly.
307 setattr(mock, attribute, partial(wrapper, attribute))
308
309
310 def _is_magic(name):
311 return '__%s__' % name[2:-2] == name
312
313
314 class _SentinelObject(object):
315 "A unique, named, sentinel object."
316 def __init__(self, name):
317 self.name = name
318
319 def __repr__(self):
320 return 'sentinel.%s' % self.name
321
322 def __reduce__(self):
323 return 'sentinel.%s' % self.name
324
325
326 class _Sentinel(object):
327 """Access attributes to return a named object, usable as a sentinel."""
328 def __init__(self):
329 self._sentinels = {}
330
331 def __getattr__(self, name):
332 if name == '__bases__':
333 # Without this help(unittest.mock) raises an exception
334 raise AttributeError
335 return self._sentinels.setdefault(name, _SentinelObject(name))
336
337 def __reduce__(self):
338 return 'sentinel'
339
340
341 sentinel = _Sentinel()
342
343 DEFAULT = sentinel.DEFAULT
344 _missing = sentinel.MISSING
345 _deleted = sentinel.DELETED
346
347
348 _allowed_names = {
349 'return_value', '_mock_return_value', 'side_effect',
350 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
351 '_mock_name', '_mock_new_name'
352 }
353
354
355 def _delegating_property(name):
356 _allowed_names.add(name)
357 _the_name = '_mock_' + name
358 def _get(self, name=name, _the_name=_the_name):
359 sig = self._mock_delegate
360 if sig is None:
361 return getattr(self, _the_name)
362 return getattr(sig, name)
363 def _set(self, value, name=name, _the_name=_the_name):
364 sig = self._mock_delegate
365 if sig is None:
366 self.__dict__[_the_name] = value
367 else:
368 setattr(sig, name, value)
369
370 return property(_get, _set)
371
372
373
374 class _CallList(list):
375
376 def __contains__(self, value):
377 if not isinstance(value, list):
378 return list.__contains__(self, value)
379 len_value = len(value)
380 len_self = len(self)
381 if len_value > len_self:
382 return False
383
384 for i in range(0, len_self - len_value + 1):
385 sub_list = self[i:i+len_value]
386 if sub_list == value:
387 return True
388 return False
389
390 def __repr__(self):
391 return pprint.pformat(list(self))
392
393
394 def _check_and_set_parent(parent, value, name, new_name):
395 value = _extract_mock(value)
396
397 if not _is_instance_mock(value):
398 return False
399 if ((value._mock_name or value._mock_new_name) or
400 (value._mock_parent is not None) or
401 (value._mock_new_parent is not None)):
402 return False
403
404 _parent = parent
405 while _parent is not None:
406 # setting a mock (value) as a child or return value of itself
407 # should not modify the mock
408 if _parent is value:
409 return False
410 _parent = _parent._mock_new_parent
411
412 if new_name:
413 value._mock_new_parent = parent
414 value._mock_new_name = new_name
415 if name:
416 value._mock_parent = parent
417 value._mock_name = name
418 return True
419
420 # Internal class to identify if we wrapped an iterator object or not.
421 class _MockIter(object):
422 def __init__(self, obj):
423 self.obj = iter(obj)
424 def __next__(self):
425 return next(self.obj)
426
427 class Base(object):
428 _mock_return_value = DEFAULT
429 _mock_side_effect = None
430 def __init__(self, /, *args, **kwargs):
431 pass
432
433
434
435 class NonCallableMock(Base):
436 """A non-callable version of `Mock`"""
437
438 # Store a mutex as a class attribute in order to protect concurrent access
439 # to mock attributes. Using a class attribute allows all NonCallableMock
440 # instances to share the mutex for simplicity.
441 #
442 # See https://github.com/python/cpython/issues/98624 for why this is
443 # necessary.
444 _lock = RLock()
445
446 def __new__(
447 cls, spec=None, wraps=None, name=None, spec_set=None,
448 parent=None, _spec_state=None, _new_name='', _new_parent=None,
449 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
450 ):
451 # every instance has its own class
452 # so we can create magic methods on the
453 # class without stomping on other mocks
454 bases = (cls,)
455 if not issubclass(cls, AsyncMockMixin):
456 # Check if spec is an async object or function
457 spec_arg = spec_set or spec
458 if spec_arg is not None and _is_async_obj(spec_arg):
459 bases = (AsyncMockMixin, cls)
460 new = type(cls.__name__, bases, {'__doc__': cls.__doc__})
461 instance = _safe_super(NonCallableMock, cls).__new__(new)
462 return instance
463
464
465 def __init__(
466 self, spec=None, wraps=None, name=None, spec_set=None,
467 parent=None, _spec_state=None, _new_name='', _new_parent=None,
468 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
469 ):
470 if _new_parent is None:
471 _new_parent = parent
472
473 __dict__ = self.__dict__
474 __dict__['_mock_parent'] = parent
475 __dict__['_mock_name'] = name
476 __dict__['_mock_new_name'] = _new_name
477 __dict__['_mock_new_parent'] = _new_parent
478 __dict__['_mock_sealed'] = False
479
480 if spec_set is not None:
481 spec = spec_set
482 spec_set = True
483 if _eat_self is None:
484 _eat_self = parent is not None
485
486 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
487
488 __dict__['_mock_children'] = {}
489 __dict__['_mock_wraps'] = wraps
490 __dict__['_mock_delegate'] = None
491
492 __dict__['_mock_called'] = False
493 __dict__['_mock_call_args'] = None
494 __dict__['_mock_call_count'] = 0
495 __dict__['_mock_call_args_list'] = _CallList()
496 __dict__['_mock_mock_calls'] = _CallList()
497
498 __dict__['method_calls'] = _CallList()
499 __dict__['_mock_unsafe'] = unsafe
500
501 if kwargs:
502 self.configure_mock(**kwargs)
503
504 _safe_super(NonCallableMock, self).__init__(
505 spec, wraps, name, spec_set, parent,
506 _spec_state
507 )
508
509
510 def attach_mock(self, mock, attribute):
511 """
512 Attach a mock as an attribute of this one, replacing its name and
513 parent. Calls to the attached mock will be recorded in the
514 `method_calls` and `mock_calls` attributes of this one."""
515 inner_mock = _extract_mock(mock)
516
517 inner_mock._mock_parent = None
518 inner_mock._mock_new_parent = None
519 inner_mock._mock_name = ''
520 inner_mock._mock_new_name = None
521
522 setattr(self, attribute, mock)
523
524
525 def mock_add_spec(self, spec, spec_set=False):
526 """Add a spec to a mock. `spec` can either be an object or a
527 list of strings. Only attributes on the `spec` can be fetched as
528 attributes from the mock.
529
530 If `spec_set` is True then only attributes on the spec can be set."""
531 self._mock_add_spec(spec, spec_set)
532
533
534 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
535 _eat_self=False):
536 if _is_instance_mock(spec):
537 raise InvalidSpecError(f'Cannot spec a Mock object. [object={spec!r}]')
538
539 _spec_class = None
540 _spec_signature = None
541 _spec_asyncs = []
542
543 if spec is not None and not _is_list(spec):
544 if isinstance(spec, type):
545 _spec_class = spec
546 else:
547 _spec_class = type(spec)
548 res = _get_signature_object(spec,
549 _spec_as_instance, _eat_self)
550 _spec_signature = res and res[1]
551
552 spec_list = dir(spec)
553
554 for attr in spec_list:
555 static_attr = inspect.getattr_static(spec, attr, None)
556 unwrapped_attr = static_attr
557 try:
558 unwrapped_attr = inspect.unwrap(unwrapped_attr)
559 except ValueError:
560 pass
561 if iscoroutinefunction(unwrapped_attr):
562 _spec_asyncs.append(attr)
563
564 spec = spec_list
565
566 __dict__ = self.__dict__
567 __dict__['_spec_class'] = _spec_class
568 __dict__['_spec_set'] = spec_set
569 __dict__['_spec_signature'] = _spec_signature
570 __dict__['_mock_methods'] = spec
571 __dict__['_spec_asyncs'] = _spec_asyncs
572
573 def _mock_extend_spec_methods(self, spec_methods):
574 methods = self.__dict__.get('_mock_methods') or []
575 methods.extend(spec_methods)
576 self.__dict__['_mock_methods'] = methods
577
578 def __get_return_value(self):
579 ret = self._mock_return_value
580 if self._mock_delegate is not None:
581 ret = self._mock_delegate.return_value
582
583 if ret is DEFAULT and self._mock_wraps is None:
584 ret = self._get_child_mock(
585 _new_parent=self, _new_name='()'
586 )
587 self.return_value = ret
588 return ret
589
590
591 def __set_return_value(self, value):
592 if self._mock_delegate is not None:
593 self._mock_delegate.return_value = value
594 else:
595 self._mock_return_value = value
596 _check_and_set_parent(self, value, None, '()')
597
598 __return_value_doc = "The value to be returned when the mock is called."
599 return_value = property(__get_return_value, __set_return_value,
600 __return_value_doc)
601
602
603 @property
604 def __class__(self):
605 if self._spec_class is None:
606 return type(self)
607 return self._spec_class
608
609 called = _delegating_property('called')
610 call_count = _delegating_property('call_count')
611 call_args = _delegating_property('call_args')
612 call_args_list = _delegating_property('call_args_list')
613 mock_calls = _delegating_property('mock_calls')
614
615
616 def __get_side_effect(self):
617 delegated = self._mock_delegate
618 if delegated is None:
619 return self._mock_side_effect
620 sf = delegated.side_effect
621 if (sf is not None and not callable(sf)
622 and not isinstance(sf, _MockIter) and not _is_exception(sf)):
623 sf = _MockIter(sf)
624 delegated.side_effect = sf
625 return sf
626
627 def __set_side_effect(self, value):
628 value = _try_iter(value)
629 delegated = self._mock_delegate
630 if delegated is None:
631 self._mock_side_effect = value
632 else:
633 delegated.side_effect = value
634
635 side_effect = property(__get_side_effect, __set_side_effect)
636
637
638 def reset_mock(self, visited=None, *,
639 return_value: bool = False,
640 side_effect: bool = False):
641 "Restore the mock object to its initial state."
642 if visited is None:
643 visited = []
644 if id(self) in visited:
645 return
646 visited.append(id(self))
647
648 self.called = False
649 self.call_args = None
650 self.call_count = 0
651 self.mock_calls = _CallList()
652 self.call_args_list = _CallList()
653 self.method_calls = _CallList()
654
655 if return_value:
656 self._mock_return_value = DEFAULT
657 if side_effect:
658 self._mock_side_effect = None
659
660 for child in self._mock_children.values():
661 if isinstance(child, _SpecState) or child is _deleted:
662 continue
663 child.reset_mock(visited, return_value=return_value, side_effect=side_effect)
664
665 ret = self._mock_return_value
666 if _is_instance_mock(ret) and ret is not self:
667 ret.reset_mock(visited)
668
669
670 def configure_mock(self, /, **kwargs):
671 """Set attributes on the mock through keyword arguments.
672
673 Attributes plus return values and side effects can be set on child
674 mocks using standard dot notation and unpacking a dictionary in the
675 method call:
676
677 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
678 >>> mock.configure_mock(**attrs)"""
679 for arg, val in sorted(kwargs.items(),
680 # we sort on the number of dots so that
681 # attributes are set before we set attributes on
682 # attributes
683 key=lambda entry: entry[0].count('.')):
684 args = arg.split('.')
685 final = args.pop()
686 obj = self
687 for entry in args:
688 obj = getattr(obj, entry)
689 setattr(obj, final, val)
690
691
692 def __getattr__(self, name):
693 if name in {'_mock_methods', '_mock_unsafe'}:
694 raise AttributeError(name)
695 elif self._mock_methods is not None:
696 if name not in self._mock_methods or name in _all_magics:
697 raise AttributeError("Mock object has no attribute %r" % name)
698 elif _is_magic(name):
699 raise AttributeError(name)
700 if not self._mock_unsafe and (not self._mock_methods or name not in self._mock_methods):
701 if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')) or name in _ATTRIB_DENY_LIST:
702 raise AttributeError(
703 f"{name!r} is not a valid assertion. Use a spec "
704 f"for the mock if {name!r} is meant to be an attribute.")
705
706 with NonCallableMock._lock:
707 result = self._mock_children.get(name)
708 if result is _deleted:
709 raise AttributeError(name)
710 elif result is None:
711 wraps = None
712 if self._mock_wraps is not None:
713 # XXXX should we get the attribute without triggering code
714 # execution?
715 wraps = getattr(self._mock_wraps, name)
716
717 result = self._get_child_mock(
718 parent=self, name=name, wraps=wraps, _new_name=name,
719 _new_parent=self
720 )
721 self._mock_children[name] = result
722
723 elif isinstance(result, _SpecState):
724 try:
725 result = create_autospec(
726 result.spec, result.spec_set, result.instance,
727 result.parent, result.name
728 )
729 except InvalidSpecError:
730 target_name = self.__dict__['_mock_name'] or self
731 raise InvalidSpecError(
732 f'Cannot autospec attr {name!r} from target '
733 f'{target_name!r} as it has already been mocked out. '
734 f'[target={self!r}, attr={result.spec!r}]')
735 self._mock_children[name] = result
736
737 return result
738
739
740 def _extract_mock_name(self):
741 _name_list = [self._mock_new_name]
742 _parent = self._mock_new_parent
743 last = self
744
745 dot = '.'
746 if _name_list == ['()']:
747 dot = ''
748
749 while _parent is not None:
750 last = _parent
751
752 _name_list.append(_parent._mock_new_name + dot)
753 dot = '.'
754 if _parent._mock_new_name == '()':
755 dot = ''
756
757 _parent = _parent._mock_new_parent
758
759 _name_list = list(reversed(_name_list))
760 _first = last._mock_name or 'mock'
761 if len(_name_list) > 1:
762 if _name_list[1] not in ('()', '().'):
763 _first += '.'
764 _name_list[0] = _first
765 return ''.join(_name_list)
766
767 def __repr__(self):
768 name = self._extract_mock_name()
769
770 name_string = ''
771 if name not in ('mock', 'mock.'):
772 name_string = ' name=%r' % name
773
774 spec_string = ''
775 if self._spec_class is not None:
776 spec_string = ' spec=%r'
777 if self._spec_set:
778 spec_string = ' spec_set=%r'
779 spec_string = spec_string % self._spec_class.__name__
780 return "<%s%s%s id='%s'>" % (
781 type(self).__name__,
782 name_string,
783 spec_string,
784 id(self)
785 )
786
787
788 def __dir__(self):
789 """Filter the output of `dir(mock)` to only useful members."""
790 if not FILTER_DIR:
791 return object.__dir__(self)
792
793 extras = self._mock_methods or []
794 from_type = dir(type(self))
795 from_dict = list(self.__dict__)
796 from_child_mocks = [
797 m_name for m_name, m_value in self._mock_children.items()
798 if m_value is not _deleted]
799
800 from_type = [e for e in from_type if not e.startswith('_')]
801 from_dict = [e for e in from_dict if not e.startswith('_') or
802 _is_magic(e)]
803 return sorted(set(extras + from_type + from_dict + from_child_mocks))
804
805
806 def __setattr__(self, name, value):
807 if name in _allowed_names:
808 # property setters go through here
809 return object.__setattr__(self, name, value)
810 elif (self._spec_set and self._mock_methods is not None and
811 name not in self._mock_methods and
812 name not in self.__dict__):
813 raise AttributeError("Mock object has no attribute '%s'" % name)
814 elif name in _unsupported_magics:
815 msg = 'Attempting to set unsupported magic method %r.' % name
816 raise AttributeError(msg)
817 elif name in _all_magics:
818 if self._mock_methods is not None and name not in self._mock_methods:
819 raise AttributeError("Mock object has no attribute '%s'" % name)
820
821 if not _is_instance_mock(value):
822 setattr(type(self), name, _get_method(name, value))
823 original = value
824 value = lambda *args, **kw: original(self, *args, **kw)
825 else:
826 # only set _new_name and not name so that mock_calls is tracked
827 # but not method calls
828 _check_and_set_parent(self, value, None, name)
829 setattr(type(self), name, value)
830 self._mock_children[name] = value
831 elif name == '__class__':
832 self._spec_class = value
833 return
834 else:
835 if _check_and_set_parent(self, value, name, name):
836 self._mock_children[name] = value
837
838 if self._mock_sealed and not hasattr(self, name):
839 mock_name = f'{self._extract_mock_name()}.{name}'
840 raise AttributeError(f'Cannot set {mock_name}')
841
842 if isinstance(value, PropertyMock):
843 self.__dict__[name] = value
844 return
845 return object.__setattr__(self, name, value)
846
847
848 def __delattr__(self, name):
849 if name in _all_magics and name in type(self).__dict__:
850 delattr(type(self), name)
851 if name not in self.__dict__:
852 # for magic methods that are still MagicProxy objects and
853 # not set on the instance itself
854 return
855
856 obj = self._mock_children.get(name, _missing)
857 if name in self.__dict__:
858 _safe_super(NonCallableMock, self).__delattr__(name)
859 elif obj is _deleted:
860 raise AttributeError(name)
861 if obj is not _missing:
862 del self._mock_children[name]
863 self._mock_children[name] = _deleted
864
865
866 def _format_mock_call_signature(self, args, kwargs):
867 name = self._mock_name or 'mock'
868 return _format_call_signature(name, args, kwargs)
869
870
871 def _format_mock_failure_message(self, args, kwargs, action='call'):
872 message = 'expected %s not found.\nExpected: %s\n Actual: %s'
873 expected_string = self._format_mock_call_signature(args, kwargs)
874 call_args = self.call_args
875 actual_string = self._format_mock_call_signature(*call_args)
876 return message % (action, expected_string, actual_string)
877
878
879 def _get_call_signature_from_name(self, name):
880 """
881 * If call objects are asserted against a method/function like obj.meth1
882 then there could be no name for the call object to lookup. Hence just
883 return the spec_signature of the method/function being asserted against.
884 * If the name is not empty then remove () and split by '.' to get
885 list of names to iterate through the children until a potential
886 match is found. A child mock is created only during attribute access
887 so if we get a _SpecState then no attributes of the spec were accessed
888 and can be safely exited.
889 """
890 if not name:
891 return self._spec_signature
892
893 sig = None
894 names = name.replace('()', '').split('.')
895 children = self._mock_children
896
897 for name in names:
898 child = children.get(name)
899 if child is None or isinstance(child, _SpecState):
900 break
901 else:
902 # If an autospecced object is attached using attach_mock the
903 # child would be a function with mock object as attribute from
904 # which signature has to be derived.
905 child = _extract_mock(child)
906 children = child._mock_children
907 sig = child._spec_signature
908
909 return sig
910
911
912 def _call_matcher(self, _call):
913 """
914 Given a call (or simply an (args, kwargs) tuple), return a
915 comparison key suitable for matching with other calls.
916 This is a best effort method which relies on the spec's signature,
917 if available, or falls back on the arguments themselves.
918 """
919
920 if isinstance(_call, tuple) and len(_call) > 2:
921 sig = self._get_call_signature_from_name(_call[0])
922 else:
923 sig = self._spec_signature
924
925 if sig is not None:
926 if len(_call) == 2:
927 name = ''
928 args, kwargs = _call
929 else:
930 name, args, kwargs = _call
931 try:
932 bound_call = sig.bind(*args, **kwargs)
933 return call(name, bound_call.args, bound_call.kwargs)
934 except TypeError as e:
935 return e.with_traceback(None)
936 else:
937 return _call
938
939 def assert_not_called(self):
940 """assert that the mock was never called.
941 """
942 if self.call_count != 0:
943 msg = ("Expected '%s' to not have been called. Called %s times.%s"
944 % (self._mock_name or 'mock',
945 self.call_count,
946 self._calls_repr()))
947 raise AssertionError(msg)
948
949 def assert_called(self):
950 """assert that the mock was called at least once
951 """
952 if self.call_count == 0:
953 msg = ("Expected '%s' to have been called." %
954 (self._mock_name or 'mock'))
955 raise AssertionError(msg)
956
957 def assert_called_once(self):
958 """assert that the mock was called only once.
959 """
960 if not self.call_count == 1:
961 msg = ("Expected '%s' to have been called once. Called %s times.%s"
962 % (self._mock_name or 'mock',
963 self.call_count,
964 self._calls_repr()))
965 raise AssertionError(msg)
966
967 def assert_called_with(self, /, *args, **kwargs):
968 """assert that the last call was made with the specified arguments.
969
970 Raises an AssertionError if the args and keyword args passed in are
971 different to the last call to the mock."""
972 if self.call_args is None:
973 expected = self._format_mock_call_signature(args, kwargs)
974 actual = 'not called.'
975 error_message = ('expected call not found.\nExpected: %s\n Actual: %s'
976 % (expected, actual))
977 raise AssertionError(error_message)
978
979 def _error_message():
980 msg = self._format_mock_failure_message(args, kwargs)
981 return msg
982 expected = self._call_matcher(_Call((args, kwargs), two=True))
983 actual = self._call_matcher(self.call_args)
984 if actual != expected:
985 cause = expected if isinstance(expected, Exception) else None
986 raise AssertionError(_error_message()) from cause
987
988
989 def assert_called_once_with(self, /, *args, **kwargs):
990 """assert that the mock was called exactly once and that that call was
991 with the specified arguments."""
992 if not self.call_count == 1:
993 msg = ("Expected '%s' to be called once. Called %s times.%s"
994 % (self._mock_name or 'mock',
995 self.call_count,
996 self._calls_repr()))
997 raise AssertionError(msg)
998 return self.assert_called_with(*args, **kwargs)
999
1000
1001 def assert_has_calls(self, calls, any_order=False):
1002 """assert the mock has been called with the specified calls.
1003 The `mock_calls` list is checked for the calls.
1004
1005 If `any_order` is False (the default) then the calls must be
1006 sequential. There can be extra calls before or after the
1007 specified calls.
1008
1009 If `any_order` is True then the calls can be in any order, but
1010 they must all appear in `mock_calls`."""
1011 expected = [self._call_matcher(c) for c in calls]
1012 cause = next((e for e in expected if isinstance(e, Exception)), None)
1013 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
1014 if not any_order:
1015 if expected not in all_calls:
1016 if cause is None:
1017 problem = 'Calls not found.'
1018 else:
1019 problem = ('Error processing expected calls.\n'
1020 'Errors: {}').format(
1021 [e if isinstance(e, Exception) else None
1022 for e in expected])
1023 raise AssertionError(
1024 f'{problem}\n'
1025 f'Expected: {_CallList(calls)}\n'
1026 f' Actual: {safe_repr(self.mock_calls)}'
1027 ) from cause
1028 return
1029
1030 all_calls = list(all_calls)
1031
1032 not_found = []
1033 for kall in expected:
1034 try:
1035 all_calls.remove(kall)
1036 except ValueError:
1037 not_found.append(kall)
1038 if not_found:
1039 raise AssertionError(
1040 '%r does not contain all of %r in its call list, '
1041 'found %r instead' % (self._mock_name or 'mock',
1042 tuple(not_found), all_calls)
1043 ) from cause
1044
1045
1046 def assert_any_call(self, /, *args, **kwargs):
1047 """assert the mock has been called with the specified arguments.
1048
1049 The assert passes if the mock has *ever* been called, unlike
1050 `assert_called_with` and `assert_called_once_with` that only pass if
1051 the call is the most recent one."""
1052 expected = self._call_matcher(_Call((args, kwargs), two=True))
1053 cause = expected if isinstance(expected, Exception) else None
1054 actual = [self._call_matcher(c) for c in self.call_args_list]
1055 if cause or expected not in _AnyComparer(actual):
1056 expected_string = self._format_mock_call_signature(args, kwargs)
1057 raise AssertionError(
1058 '%s call not found' % expected_string
1059 ) from cause
1060
1061
1062 def _get_child_mock(self, /, **kw):
1063 """Create the child mocks for attributes and return value.
1064 By default child mocks will be the same type as the parent.
1065 Subclasses of Mock may want to override this to customize the way
1066 child mocks are made.
1067
1068 For non-callable mocks the callable variant will be used (rather than
1069 any custom subclass)."""
1070 if self._mock_sealed:
1071 attribute = f".{kw['name']}" if "name" in kw else "()"
1072 mock_name = self._extract_mock_name() + attribute
1073 raise AttributeError(mock_name)
1074
1075 _new_name = kw.get("_new_name")
1076 if _new_name in self.__dict__['_spec_asyncs']:
1077 return AsyncMock(**kw)
1078
1079 _type = type(self)
1080 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
1081 # Any asynchronous magic becomes an AsyncMock
1082 klass = AsyncMock
1083 elif issubclass(_type, AsyncMockMixin):
1084 if (_new_name in _all_sync_magics or
1085 self._mock_methods and _new_name in self._mock_methods):
1086 # Any synchronous method on AsyncMock becomes a MagicMock
1087 klass = MagicMock
1088 else:
1089 klass = AsyncMock
1090 elif not issubclass(_type, CallableMixin):
1091 if issubclass(_type, NonCallableMagicMock):
1092 klass = MagicMock
1093 elif issubclass(_type, NonCallableMock):
1094 klass = Mock
1095 else:
1096 klass = _type.__mro__[1]
1097 return klass(**kw)
1098
1099
1100 def _calls_repr(self):
1101 """Renders self.mock_calls as a string.
1102
1103 Example: "\nCalls: [call(1), call(2)]."
1104
1105 If self.mock_calls is empty, an empty string is returned. The
1106 output will be truncated if very long.
1107 """
1108 if not self.mock_calls:
1109 return ""
1110 return f"\nCalls: {safe_repr(self.mock_calls)}."
1111
1112
1113 # Denylist for forbidden attribute names in safe mode
1114 _ATTRIB_DENY_LIST = frozenset({
1115 name.removeprefix("assert_")
1116 for name in dir(NonCallableMock)
1117 if name.startswith("assert_")
1118 })
1119
1120
1121 class _AnyComparer(list):
1122 """A list which checks if it contains a call which may have an
1123 argument of ANY, flipping the components of item and self from
1124 their traditional locations so that ANY is guaranteed to be on
1125 the left."""
1126 def __contains__(self, item):
1127 for _call in self:
1128 assert len(item) == len(_call)
1129 if all([
1130 expected == actual
1131 for expected, actual in zip(item, _call)
1132 ]):
1133 return True
1134 return False
1135
1136
1137 def _try_iter(obj):
1138 if obj is None:
1139 return obj
1140 if _is_exception(obj):
1141 return obj
1142 if _callable(obj):
1143 return obj
1144 try:
1145 return iter(obj)
1146 except TypeError:
1147 # XXXX backwards compatibility
1148 # but this will blow up on first call - so maybe we should fail early?
1149 return obj
1150
1151
1152 class CallableMixin(Base):
1153
1154 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
1155 wraps=None, name=None, spec_set=None, parent=None,
1156 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
1157 self.__dict__['_mock_return_value'] = return_value
1158 _safe_super(CallableMixin, self).__init__(
1159 spec, wraps, name, spec_set, parent,
1160 _spec_state, _new_name, _new_parent, **kwargs
1161 )
1162
1163 self.side_effect = side_effect
1164
1165
1166 def _mock_check_sig(self, /, *args, **kwargs):
1167 # stub method that can be replaced with one with a specific signature
1168 pass
1169
1170
1171 def __call__(self, /, *args, **kwargs):
1172 # can't use self in-case a function / method we are mocking uses self
1173 # in the signature
1174 self._mock_check_sig(*args, **kwargs)
1175 self._increment_mock_call(*args, **kwargs)
1176 return self._mock_call(*args, **kwargs)
1177
1178
1179 def _mock_call(self, /, *args, **kwargs):
1180 return self._execute_mock_call(*args, **kwargs)
1181
1182 def _increment_mock_call(self, /, *args, **kwargs):
1183 self.called = True
1184
1185 # handle call_args
1186 # needs to be set here so assertions on call arguments pass before
1187 # execution in the case of awaited calls
1188 with NonCallableMock._lock:
1189 # Lock is used here so that call_args_list and call_count are
1190 # set atomically otherwise it is possible that by the time call_count
1191 # is set another thread may have appended to call_args_list.
1192 # The rest of this function relies on list.append being atomic and
1193 # skips locking.
1194 _call = _Call((args, kwargs), two=True)
1195 self.call_args = _call
1196 self.call_args_list.append(_call)
1197 self.call_count = len(self.call_args_list)
1198
1199 # initial stuff for method_calls:
1200 do_method_calls = self._mock_parent is not None
1201 method_call_name = self._mock_name
1202
1203 # initial stuff for mock_calls:
1204 mock_call_name = self._mock_new_name
1205 is_a_call = mock_call_name == '()'
1206 self.mock_calls.append(_Call(('', args, kwargs)))
1207
1208 # follow up the chain of mocks:
1209 _new_parent = self._mock_new_parent
1210 while _new_parent is not None:
1211
1212 # handle method_calls:
1213 if do_method_calls:
1214 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))
1215 do_method_calls = _new_parent._mock_parent is not None
1216 if do_method_calls:
1217 method_call_name = _new_parent._mock_name + '.' + method_call_name
1218
1219 # handle mock_calls:
1220 this_mock_call = _Call((mock_call_name, args, kwargs))
1221 _new_parent.mock_calls.append(this_mock_call)
1222
1223 if _new_parent._mock_new_name:
1224 if is_a_call:
1225 dot = ''
1226 else:
1227 dot = '.'
1228 is_a_call = _new_parent._mock_new_name == '()'
1229 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name
1230
1231 # follow the parental chain:
1232 _new_parent = _new_parent._mock_new_parent
1233
1234 def _execute_mock_call(self, /, *args, **kwargs):
1235 # separate from _increment_mock_call so that awaited functions are
1236 # executed separately from their call, also AsyncMock overrides this method
1237
1238 effect = self.side_effect
1239 if effect is not None:
1240 if _is_exception(effect):
1241 raise effect
1242 elif not _callable(effect):
1243 result = next(effect)
1244 if _is_exception(result):
1245 raise result
1246 else:
1247 result = effect(*args, **kwargs)
1248
1249 if result is not DEFAULT:
1250 return result
1251
1252 if self._mock_return_value is not DEFAULT:
1253 return self.return_value
1254
1255 if self._mock_delegate and self._mock_delegate.return_value is not DEFAULT:
1256 return self.return_value
1257
1258 if self._mock_wraps is not None:
1259 return self._mock_wraps(*args, **kwargs)
1260
1261 return self.return_value
1262
1263
1264
1265 class Mock(CallableMixin, NonCallableMock):
1266 """
1267 Create a new `Mock` object. `Mock` takes several optional arguments
1268 that specify the behaviour of the Mock object:
1269
1270 * `spec`: This can be either a list of strings or an existing object (a
1271 class or instance) that acts as the specification for the mock object. If
1272 you pass in an object then a list of strings is formed by calling dir on
1273 the object (excluding unsupported magic attributes and methods). Accessing
1274 any attribute not in this list will raise an `AttributeError`.
1275
1276 If `spec` is an object (rather than a list of strings) then
1277 `mock.__class__` returns the class of the spec object. This allows mocks
1278 to pass `isinstance` tests.
1279
1280 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1281 or get an attribute on the mock that isn't on the object passed as
1282 `spec_set` will raise an `AttributeError`.
1283
1284 * `side_effect`: A function to be called whenever the Mock is called. See
1285 the `side_effect` attribute. Useful for raising exceptions or
1286 dynamically changing return values. The function is called with the same
1287 arguments as the mock, and unless it returns `DEFAULT`, the return
1288 value of this function is used as the return value.
1289
1290 If `side_effect` is an iterable then each call to the mock will return
1291 the next value from the iterable. If any of the members of the iterable
1292 are exceptions they will be raised instead of returned.
1293
1294 * `return_value`: The value returned when the mock is called. By default
1295 this is a new Mock (created on first access). See the
1296 `return_value` attribute.
1297
1298 * `unsafe`: By default, accessing any attribute whose name starts with
1299 *assert*, *assret*, *asert*, *aseert*, or *assrt* raises an AttributeError.
1300 Additionally, an AttributeError is raised when accessing
1301 attributes that match the name of an assertion method without the prefix
1302 `assert_`, e.g. accessing `called_once` instead of `assert_called_once`.
1303 Passing `unsafe=True` will allow access to these attributes.
1304
1305 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1306 calling the Mock will pass the call through to the wrapped object
1307 (returning the real result). Attribute access on the mock will return a
1308 Mock object that wraps the corresponding attribute of the wrapped object
1309 (so attempting to access an attribute that doesn't exist will raise an
1310 `AttributeError`).
1311
1312 If the mock has an explicit `return_value` set then calls are not passed
1313 to the wrapped object and the `return_value` is returned instead.
1314
1315 * `name`: If the mock has a name then it will be used in the repr of the
1316 mock. This can be useful for debugging. The name is propagated to child
1317 mocks.
1318
1319 Mocks can also be called with arbitrary keyword arguments. These will be
1320 used to set attributes on the mock after it is created.
1321 """
1322
1323
1324 # _check_spec_arg_typos takes kwargs from commands like patch and checks that
1325 # they don't contain common misspellings of arguments related to autospeccing.
1326 def _check_spec_arg_typos(kwargs_to_check):
1327 typos = ("autospect", "auto_spec", "set_spec")
1328 for typo in typos:
1329 if typo in kwargs_to_check:
1330 raise RuntimeError(
1331 f"{typo!r} might be a typo; use unsafe=True if this is intended"
1332 )
1333
1334
1335 class _patch(object):
1336
1337 attribute_name = None
1338 _active_patches = []
1339
1340 def __init__(
1341 self, getter, attribute, new, spec, create,
1342 spec_set, autospec, new_callable, kwargs, *, unsafe=False
1343 ):
1344 if new_callable is not None:
1345 if new is not DEFAULT:
1346 raise ValueError(
1347 "Cannot use 'new' and 'new_callable' together"
1348 )
1349 if autospec is not None:
1350 raise ValueError(
1351 "Cannot use 'autospec' and 'new_callable' together"
1352 )
1353 if not unsafe:
1354 _check_spec_arg_typos(kwargs)
1355 if _is_instance_mock(spec):
1356 raise InvalidSpecError(
1357 f'Cannot spec attr {attribute!r} as the spec '
1358 f'has already been mocked out. [spec={spec!r}]')
1359 if _is_instance_mock(spec_set):
1360 raise InvalidSpecError(
1361 f'Cannot spec attr {attribute!r} as the spec_set '
1362 f'target has already been mocked out. [spec_set={spec_set!r}]')
1363
1364 self.getter = getter
1365 self.attribute = attribute
1366 self.new = new
1367 self.new_callable = new_callable
1368 self.spec = spec
1369 self.create = create
1370 self.has_local = False
1371 self.spec_set = spec_set
1372 self.autospec = autospec
1373 self.kwargs = kwargs
1374 self.additional_patchers = []
1375 self.is_started = False
1376
1377
1378 def copy(self):
1379 patcher = _patch(
1380 self.getter, self.attribute, self.new, self.spec,
1381 self.create, self.spec_set,
1382 self.autospec, self.new_callable, self.kwargs
1383 )
1384 patcher.attribute_name = self.attribute_name
1385 patcher.additional_patchers = [
1386 p.copy() for p in self.additional_patchers
1387 ]
1388 return patcher
1389
1390
1391 def __call__(self, func):
1392 if isinstance(func, type):
1393 return self.decorate_class(func)
1394 if inspect.iscoroutinefunction(func):
1395 return self.decorate_async_callable(func)
1396 return self.decorate_callable(func)
1397
1398
1399 def decorate_class(self, klass):
1400 for attr in dir(klass):
1401 if not attr.startswith(patch.TEST_PREFIX):
1402 continue
1403
1404 attr_value = getattr(klass, attr)
1405 if not hasattr(attr_value, "__call__"):
1406 continue
1407
1408 patcher = self.copy()
1409 setattr(klass, attr, patcher(attr_value))
1410 return klass
1411
1412
1413 @contextlib.contextmanager
1414 def decoration_helper(self, patched, args, keywargs):
1415 extra_args = []
1416 with contextlib.ExitStack() as exit_stack:
1417 for patching in patched.patchings:
1418 arg = exit_stack.enter_context(patching)
1419 if patching.attribute_name is not None:
1420 keywargs.update(arg)
1421 elif patching.new is DEFAULT:
1422 extra_args.append(arg)
1423
1424 args += tuple(extra_args)
1425 yield (args, keywargs)
1426
1427
1428 def decorate_callable(self, func):
1429 # NB. Keep the method in sync with decorate_async_callable()
1430 if hasattr(func, 'patchings'):
1431 func.patchings.append(self)
1432 return func
1433
1434 @wraps(func)
1435 def patched(*args, **keywargs):
1436 with self.decoration_helper(patched,
1437 args,
1438 keywargs) as (newargs, newkeywargs):
1439 return func(*newargs, **newkeywargs)
1440
1441 patched.patchings = [self]
1442 return patched
1443
1444
1445 def decorate_async_callable(self, func):
1446 # NB. Keep the method in sync with decorate_callable()
1447 if hasattr(func, 'patchings'):
1448 func.patchings.append(self)
1449 return func
1450
1451 @wraps(func)
1452 async def patched(*args, **keywargs):
1453 with self.decoration_helper(patched,
1454 args,
1455 keywargs) as (newargs, newkeywargs):
1456 return await func(*newargs, **newkeywargs)
1457
1458 patched.patchings = [self]
1459 return patched
1460
1461
1462 def get_original(self):
1463 target = self.getter()
1464 name = self.attribute
1465
1466 original = DEFAULT
1467 local = False
1468
1469 try:
1470 original = target.__dict__[name]
1471 except (AttributeError, KeyError):
1472 original = getattr(target, name, DEFAULT)
1473 else:
1474 local = True
1475
1476 if name in _builtins and isinstance(target, ModuleType):
1477 self.create = True
1478
1479 if not self.create and original is DEFAULT:
1480 raise AttributeError(
1481 "%s does not have the attribute %r" % (target, name)
1482 )
1483 return original, local
1484
1485
1486 def __enter__(self):
1487 """Perform the patch."""
1488 if self.is_started:
1489 raise RuntimeError("Patch is already started")
1490
1491 new, spec, spec_set = self.new, self.spec, self.spec_set
1492 autospec, kwargs = self.autospec, self.kwargs
1493 new_callable = self.new_callable
1494 self.target = self.getter()
1495
1496 # normalise False to None
1497 if spec is False:
1498 spec = None
1499 if spec_set is False:
1500 spec_set = None
1501 if autospec is False:
1502 autospec = None
1503
1504 if spec is not None and autospec is not None:
1505 raise TypeError("Can't specify spec and autospec")
1506 if ((spec is not None or autospec is not None) and
1507 spec_set not in (True, None)):
1508 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1509
1510 original, local = self.get_original()
1511
1512 if new is DEFAULT and autospec is None:
1513 inherit = False
1514 if spec is True:
1515 # set spec to the object we are replacing
1516 spec = original
1517 if spec_set is True:
1518 spec_set = original
1519 spec = None
1520 elif spec is not None:
1521 if spec_set is True:
1522 spec_set = spec
1523 spec = None
1524 elif spec_set is True:
1525 spec_set = original
1526
1527 if spec is not None or spec_set is not None:
1528 if original is DEFAULT:
1529 raise TypeError("Can't use 'spec' with create=True")
1530 if isinstance(original, type):
1531 # If we're patching out a class and there is a spec
1532 inherit = True
1533
1534 # Determine the Klass to use
1535 if new_callable is not None:
1536 Klass = new_callable
1537 elif spec is None and _is_async_obj(original):
1538 Klass = AsyncMock
1539 elif spec is not None or spec_set is not None:
1540 this_spec = spec
1541 if spec_set is not None:
1542 this_spec = spec_set
1543 if _is_list(this_spec):
1544 not_callable = '__call__' not in this_spec
1545 else:
1546 not_callable = not callable(this_spec)
1547 if _is_async_obj(this_spec):
1548 Klass = AsyncMock
1549 elif not_callable:
1550 Klass = NonCallableMagicMock
1551 else:
1552 Klass = MagicMock
1553 else:
1554 Klass = MagicMock
1555
1556 _kwargs = {}
1557 if spec is not None:
1558 _kwargs['spec'] = spec
1559 if spec_set is not None:
1560 _kwargs['spec_set'] = spec_set
1561
1562 # add a name to mocks
1563 if (isinstance(Klass, type) and
1564 issubclass(Klass, NonCallableMock) and self.attribute):
1565 _kwargs['name'] = self.attribute
1566
1567 _kwargs.update(kwargs)
1568 new = Klass(**_kwargs)
1569
1570 if inherit and _is_instance_mock(new):
1571 # we can only tell if the instance should be callable if the
1572 # spec is not a list
1573 this_spec = spec
1574 if spec_set is not None:
1575 this_spec = spec_set
1576 if (not _is_list(this_spec) and not
1577 _instance_callable(this_spec)):
1578 Klass = NonCallableMagicMock
1579
1580 _kwargs.pop('name')
1581 new.return_value = Klass(_new_parent=new, _new_name='()',
1582 **_kwargs)
1583 elif autospec is not None:
1584 # spec is ignored, new *must* be default, spec_set is treated
1585 # as a boolean. Should we check spec is not None and that spec_set
1586 # is a bool?
1587 if new is not DEFAULT:
1588 raise TypeError(
1589 "autospec creates the mock for you. Can't specify "
1590 "autospec and new."
1591 )
1592 if original is DEFAULT:
1593 raise TypeError("Can't use 'autospec' with create=True")
1594 spec_set = bool(spec_set)
1595 if autospec is True:
1596 autospec = original
1597
1598 if _is_instance_mock(self.target):
1599 raise InvalidSpecError(
1600 f'Cannot autospec attr {self.attribute!r} as the patch '
1601 f'target has already been mocked out. '
1602 f'[target={self.target!r}, attr={autospec!r}]')
1603 if _is_instance_mock(autospec):
1604 target_name = getattr(self.target, '__name__', self.target)
1605 raise InvalidSpecError(
1606 f'Cannot autospec attr {self.attribute!r} from target '
1607 f'{target_name!r} as it has already been mocked out. '
1608 f'[target={self.target!r}, attr={autospec!r}]')
1609
1610 new = create_autospec(autospec, spec_set=spec_set,
1611 _name=self.attribute, **kwargs)
1612 elif kwargs:
1613 # can't set keyword args when we aren't creating the mock
1614 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1615 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1616
1617 new_attr = new
1618
1619 self.temp_original = original
1620 self.is_local = local
1621 self._exit_stack = contextlib.ExitStack()
1622 self.is_started = True
1623 try:
1624 setattr(self.target, self.attribute, new_attr)
1625 if self.attribute_name is not None:
1626 extra_args = {}
1627 if self.new is DEFAULT:
1628 extra_args[self.attribute_name] = new
1629 for patching in self.additional_patchers:
1630 arg = self._exit_stack.enter_context(patching)
1631 if patching.new is DEFAULT:
1632 extra_args.update(arg)
1633 return extra_args
1634
1635 return new
1636 except:
1637 if not self.__exit__(*sys.exc_info()):
1638 raise
1639
1640 def __exit__(self, *exc_info):
1641 """Undo the patch."""
1642 if not self.is_started:
1643 return
1644
1645 if self.is_local and self.temp_original is not DEFAULT:
1646 setattr(self.target, self.attribute, self.temp_original)
1647 else:
1648 delattr(self.target, self.attribute)
1649 if not self.create and (not hasattr(self.target, self.attribute) or
1650 self.attribute in ('__doc__', '__module__',
1651 '__defaults__', '__annotations__',
1652 '__kwdefaults__')):
1653 # needed for proxy objects like django settings
1654 setattr(self.target, self.attribute, self.temp_original)
1655
1656 del self.temp_original
1657 del self.is_local
1658 del self.target
1659 exit_stack = self._exit_stack
1660 del self._exit_stack
1661 self.is_started = False
1662 return exit_stack.__exit__(*exc_info)
1663
1664
1665 def start(self):
1666 """Activate a patch, returning any created mock."""
1667 result = self.__enter__()
1668 self._active_patches.append(self)
1669 return result
1670
1671
1672 def stop(self):
1673 """Stop an active patch."""
1674 try:
1675 self._active_patches.remove(self)
1676 except ValueError:
1677 # If the patch hasn't been started this will fail
1678 return None
1679
1680 return self.__exit__(None, None, None)
1681
1682
1683
1684 def _get_target(target):
1685 try:
1686 target, attribute = target.rsplit('.', 1)
1687 except (TypeError, ValueError, AttributeError):
1688 raise TypeError(
1689 f"Need a valid target to patch. You supplied: {target!r}")
1690 return partial(pkgutil.resolve_name, target), attribute
1691
1692
1693 def _patch_object(
1694 target, attribute, new=DEFAULT, spec=None,
1695 create=False, spec_set=None, autospec=None,
1696 new_callable=None, *, unsafe=False, **kwargs
1697 ):
1698 """
1699 patch the named member (`attribute`) on an object (`target`) with a mock
1700 object.
1701
1702 `patch.object` can be used as a decorator, class decorator or a context
1703 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1704 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1705 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1706 the mock object it creates.
1707
1708 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1709 for choosing which methods to wrap.
1710 """
1711 if type(target) is str:
1712 raise TypeError(
1713 f"{target!r} must be the actual object to be patched, not a str"
1714 )
1715 getter = lambda: target
1716 return _patch(
1717 getter, attribute, new, spec, create,
1718 spec_set, autospec, new_callable, kwargs, unsafe=unsafe
1719 )
1720
1721
1722 def _patch_multiple(target, spec=None, create=False, spec_set=None,
1723 autospec=None, new_callable=None, **kwargs):
1724 """Perform multiple patches in a single call. It takes the object to be
1725 patched (either as an object or a string to fetch the object by importing)
1726 and keyword arguments for the patches::
1727
1728 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1729 ...
1730
1731 Use `DEFAULT` as the value if you want `patch.multiple` to create
1732 mocks for you. In this case the created mocks are passed into a decorated
1733 function by keyword, and a dictionary is returned when `patch.multiple` is
1734 used as a context manager.
1735
1736 `patch.multiple` can be used as a decorator, class decorator or a context
1737 manager. The arguments `spec`, `spec_set`, `create`,
1738 `autospec` and `new_callable` have the same meaning as for `patch`. These
1739 arguments will be applied to *all* patches done by `patch.multiple`.
1740
1741 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1742 for choosing which methods to wrap.
1743 """
1744 if type(target) is str:
1745 getter = partial(pkgutil.resolve_name, target)
1746 else:
1747 getter = lambda: target
1748
1749 if not kwargs:
1750 raise ValueError(
1751 'Must supply at least one keyword argument with patch.multiple'
1752 )
1753 # need to wrap in a list for python 3, where items is a view
1754 items = list(kwargs.items())
1755 attribute, new = items[0]
1756 patcher = _patch(
1757 getter, attribute, new, spec, create, spec_set,
1758 autospec, new_callable, {}
1759 )
1760 patcher.attribute_name = attribute
1761 for attribute, new in items[1:]:
1762 this_patcher = _patch(
1763 getter, attribute, new, spec, create, spec_set,
1764 autospec, new_callable, {}
1765 )
1766 this_patcher.attribute_name = attribute
1767 patcher.additional_patchers.append(this_patcher)
1768 return patcher
1769
1770
1771 def patch(
1772 target, new=DEFAULT, spec=None, create=False,
1773 spec_set=None, autospec=None, new_callable=None, *, unsafe=False, **kwargs
1774 ):
1775 """
1776 `patch` acts as a function decorator, class decorator or a context
1777 manager. Inside the body of the function or with statement, the `target`
1778 is patched with a `new` object. When the function/with statement exits
1779 the patch is undone.
1780
1781 If `new` is omitted, then the target is replaced with an
1782 `AsyncMock` if the patched object is an async function or a
1783 `MagicMock` otherwise. If `patch` is used as a decorator and `new` is
1784 omitted, the created mock is passed in as an extra argument to the
1785 decorated function. If `patch` is used as a context manager the created
1786 mock is returned by the context manager.
1787
1788 `target` should be a string in the form `'package.module.ClassName'`. The
1789 `target` is imported and the specified object replaced with the `new`
1790 object, so the `target` must be importable from the environment you are
1791 calling `patch` from. The target is imported when the decorated function
1792 is executed, not at decoration time.
1793
1794 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1795 if patch is creating one for you.
1796
1797 In addition you can pass `spec=True` or `spec_set=True`, which causes
1798 patch to pass in the object being mocked as the spec/spec_set object.
1799
1800 `new_callable` allows you to specify a different class, or callable object,
1801 that will be called to create the `new` object. By default `AsyncMock` is
1802 used for async functions and `MagicMock` for the rest.
1803
1804 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1805 then the mock will be created with a spec from the object being replaced.
1806 All attributes of the mock will also have the spec of the corresponding
1807 attribute of the object being replaced. Methods and functions being
1808 mocked will have their arguments checked and will raise a `TypeError` if
1809 they are called with the wrong signature. For mocks replacing a class,
1810 their return value (the 'instance') will have the same spec as the class.
1811
1812 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1813 arbitrary object as the spec instead of the one being replaced.
1814
1815 By default `patch` will fail to replace attributes that don't exist. If
1816 you pass in `create=True`, and the attribute doesn't exist, patch will
1817 create the attribute for you when the patched function is called, and
1818 delete it again afterwards. This is useful for writing tests against
1819 attributes that your production code creates at runtime. It is off by
1820 default because it can be dangerous. With it switched on you can write
1821 passing tests against APIs that don't actually exist!
1822
1823 Patch can be used as a `TestCase` class decorator. It works by
1824 decorating each test method in the class. This reduces the boilerplate
1825 code when your test methods share a common patchings set. `patch` finds
1826 tests by looking for method names that start with `patch.TEST_PREFIX`.
1827 By default this is `test`, which matches the way `unittest` finds tests.
1828 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1829
1830 Patch can be used as a context manager, with the with statement. Here the
1831 patching applies to the indented block after the with statement. If you
1832 use "as" then the patched object will be bound to the name after the
1833 "as"; very useful if `patch` is creating a mock object for you.
1834
1835 Patch will raise a `RuntimeError` if passed some common misspellings of
1836 the arguments autospec and spec_set. Pass the argument `unsafe` with the
1837 value True to disable that check.
1838
1839 `patch` takes arbitrary keyword arguments. These will be passed to
1840 `AsyncMock` if the patched object is asynchronous, to `MagicMock`
1841 otherwise or to `new_callable` if specified.
1842
1843 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1844 available for alternate use-cases.
1845 """
1846 getter, attribute = _get_target(target)
1847 return _patch(
1848 getter, attribute, new, spec, create,
1849 spec_set, autospec, new_callable, kwargs, unsafe=unsafe
1850 )
1851
1852
1853 class _patch_dict(object):
1854 """
1855 Patch a dictionary, or dictionary like object, and restore the dictionary
1856 to its original state after the test, where the restored dictionary is
1857 a copy of the dictionary as it was before the test.
1858
1859 `in_dict` can be a dictionary or a mapping like container. If it is a
1860 mapping then it must at least support getting, setting and deleting items
1861 plus iterating over keys.
1862
1863 `in_dict` can also be a string specifying the name of the dictionary, which
1864 will then be fetched by importing it.
1865
1866 `values` can be a dictionary of values to set in the dictionary. `values`
1867 can also be an iterable of `(key, value)` pairs.
1868
1869 If `clear` is True then the dictionary will be cleared before the new
1870 values are set.
1871
1872 `patch.dict` can also be called with arbitrary keyword arguments to set
1873 values in the dictionary::
1874
1875 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1876 ...
1877
1878 `patch.dict` can be used as a context manager, decorator or class
1879 decorator. When used as a class decorator `patch.dict` honours
1880 `patch.TEST_PREFIX` for choosing which methods to wrap.
1881 """
1882
1883 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1884 self.in_dict = in_dict
1885 # support any argument supported by dict(...) constructor
1886 self.values = dict(values)
1887 self.values.update(kwargs)
1888 self.clear = clear
1889 self._original = None
1890
1891
1892 def __call__(self, f):
1893 if isinstance(f, type):
1894 return self.decorate_class(f)
1895 if inspect.iscoroutinefunction(f):
1896 return self.decorate_async_callable(f)
1897 return self.decorate_callable(f)
1898
1899
1900 def decorate_callable(self, f):
1901 @wraps(f)
1902 def _inner(*args, **kw):
1903 self._patch_dict()
1904 try:
1905 return f(*args, **kw)
1906 finally:
1907 self._unpatch_dict()
1908
1909 return _inner
1910
1911
1912 def decorate_async_callable(self, f):
1913 @wraps(f)
1914 async def _inner(*args, **kw):
1915 self._patch_dict()
1916 try:
1917 return await f(*args, **kw)
1918 finally:
1919 self._unpatch_dict()
1920
1921 return _inner
1922
1923
1924 def decorate_class(self, klass):
1925 for attr in dir(klass):
1926 attr_value = getattr(klass, attr)
1927 if (attr.startswith(patch.TEST_PREFIX) and
1928 hasattr(attr_value, "__call__")):
1929 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1930 decorated = decorator(attr_value)
1931 setattr(klass, attr, decorated)
1932 return klass
1933
1934
1935 def __enter__(self):
1936 """Patch the dict."""
1937 self._patch_dict()
1938 return self.in_dict
1939
1940
1941 def _patch_dict(self):
1942 values = self.values
1943 if isinstance(self.in_dict, str):
1944 self.in_dict = pkgutil.resolve_name(self.in_dict)
1945 in_dict = self.in_dict
1946 clear = self.clear
1947
1948 try:
1949 original = in_dict.copy()
1950 except AttributeError:
1951 # dict like object with no copy method
1952 # must support iteration over keys
1953 original = {}
1954 for key in in_dict:
1955 original[key] = in_dict[key]
1956 self._original = original
1957
1958 if clear:
1959 _clear_dict(in_dict)
1960
1961 try:
1962 in_dict.update(values)
1963 except AttributeError:
1964 # dict like object with no update method
1965 for key in values:
1966 in_dict[key] = values[key]
1967
1968
1969 def _unpatch_dict(self):
1970 in_dict = self.in_dict
1971 original = self._original
1972
1973 _clear_dict(in_dict)
1974
1975 try:
1976 in_dict.update(original)
1977 except AttributeError:
1978 for key in original:
1979 in_dict[key] = original[key]
1980
1981
1982 def __exit__(self, *args):
1983 """Unpatch the dict."""
1984 if self._original is not None:
1985 self._unpatch_dict()
1986 return False
1987
1988
1989 def start(self):
1990 """Activate a patch, returning any created mock."""
1991 result = self.__enter__()
1992 _patch._active_patches.append(self)
1993 return result
1994
1995
1996 def stop(self):
1997 """Stop an active patch."""
1998 try:
1999 _patch._active_patches.remove(self)
2000 except ValueError:
2001 # If the patch hasn't been started this will fail
2002 return None
2003
2004 return self.__exit__(None, None, None)
2005
2006
2007 def _clear_dict(in_dict):
2008 try:
2009 in_dict.clear()
2010 except AttributeError:
2011 keys = list(in_dict)
2012 for key in keys:
2013 del in_dict[key]
2014
2015
2016 def _patch_stopall():
2017 """Stop all active patches. LIFO to unroll nested patches."""
2018 for patch in reversed(_patch._active_patches):
2019 patch.stop()
2020
2021
2022 patch.object = _patch_object
2023 patch.dict = _patch_dict
2024 patch.multiple = _patch_multiple
2025 patch.stopall = _patch_stopall
2026 patch.TEST_PREFIX = 'test'
2027
2028 magic_methods = (
2029 "lt le gt ge eq ne "
2030 "getitem setitem delitem "
2031 "len contains iter "
2032 "hash str sizeof "
2033 "enter exit "
2034 # we added divmod and rdivmod here instead of numerics
2035 # because there is no idivmod
2036 "divmod rdivmod neg pos abs invert "
2037 "complex int float index "
2038 "round trunc floor ceil "
2039 "bool next "
2040 "fspath "
2041 "aiter "
2042 )
2043
2044 numerics = (
2045 "add sub mul matmul truediv floordiv mod lshift rshift and xor or pow"
2046 )
2047 inplace = ' '.join('i%s' % n for n in numerics.split())
2048 right = ' '.join('r%s' % n for n in numerics.split())
2049
2050 # not including __prepare__, __instancecheck__, __subclasscheck__
2051 # (as they are metaclass methods)
2052 # __del__ is not supported at all as it causes problems if it exists
2053
2054 _non_defaults = {
2055 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',
2056 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',
2057 '__getstate__', '__setstate__', '__getformat__',
2058 '__repr__', '__dir__', '__subclasses__', '__format__',
2059 '__getnewargs_ex__',
2060 }
2061
2062
2063 def _get_method(name, func):
2064 "Turns a callable object (like a mock) into a real function"
2065 def method(self, /, *args, **kw):
2066 return func(self, *args, **kw)
2067 method.__name__ = name
2068 return method
2069
2070
2071 _magics = {
2072 '__%s__' % method for method in
2073 ' '.join([magic_methods, numerics, inplace, right]).split()
2074 }
2075
2076 # Magic methods used for async `with` statements
2077 _async_method_magics = {"__aenter__", "__aexit__", "__anext__"}
2078 # Magic methods that are only used with async calls but are synchronous functions themselves
2079 _sync_async_magics = {"__aiter__"}
2080 _async_magics = _async_method_magics | _sync_async_magics
2081
2082 _all_sync_magics = _magics | _non_defaults
2083 _all_magics = _all_sync_magics | _async_magics
2084
2085 _unsupported_magics = {
2086 '__getattr__', '__setattr__',
2087 '__init__', '__new__', '__prepare__',
2088 '__instancecheck__', '__subclasscheck__',
2089 '__del__'
2090 }
2091
2092 _calculate_return_value = {
2093 '__hash__': lambda self: object.__hash__(self),
2094 '__str__': lambda self: object.__str__(self),
2095 '__sizeof__': lambda self: object.__sizeof__(self),
2096 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",
2097 }
2098
2099 _return_values = {
2100 '__lt__': NotImplemented,
2101 '__gt__': NotImplemented,
2102 '__le__': NotImplemented,
2103 '__ge__': NotImplemented,
2104 '__int__': 1,
2105 '__contains__': False,
2106 '__len__': 0,
2107 '__exit__': False,
2108 '__complex__': 1j,
2109 '__float__': 1.0,
2110 '__bool__': True,
2111 '__index__': 1,
2112 '__aexit__': False,
2113 }
2114
2115
2116 def _get_eq(self):
2117 def __eq__(other):
2118 ret_val = self.__eq__._mock_return_value
2119 if ret_val is not DEFAULT:
2120 return ret_val
2121 if self is other:
2122 return True
2123 return NotImplemented
2124 return __eq__
2125
2126 def _get_ne(self):
2127 def __ne__(other):
2128 if self.__ne__._mock_return_value is not DEFAULT:
2129 return DEFAULT
2130 if self is other:
2131 return False
2132 return NotImplemented
2133 return __ne__
2134
2135 def _get_iter(self):
2136 def __iter__():
2137 ret_val = self.__iter__._mock_return_value
2138 if ret_val is DEFAULT:
2139 return iter([])
2140 # if ret_val was already an iterator, then calling iter on it should
2141 # return the iterator unchanged
2142 return iter(ret_val)
2143 return __iter__
2144
2145 def _get_async_iter(self):
2146 def __aiter__():
2147 ret_val = self.__aiter__._mock_return_value
2148 if ret_val is DEFAULT:
2149 return _AsyncIterator(iter([]))
2150 return _AsyncIterator(iter(ret_val))
2151 return __aiter__
2152
2153 _side_effect_methods = {
2154 '__eq__': _get_eq,
2155 '__ne__': _get_ne,
2156 '__iter__': _get_iter,
2157 '__aiter__': _get_async_iter
2158 }
2159
2160
2161
2162 def _set_return_value(mock, method, name):
2163 fixed = _return_values.get(name, DEFAULT)
2164 if fixed is not DEFAULT:
2165 method.return_value = fixed
2166 return
2167
2168 return_calculator = _calculate_return_value.get(name)
2169 if return_calculator is not None:
2170 return_value = return_calculator(mock)
2171 method.return_value = return_value
2172 return
2173
2174 side_effector = _side_effect_methods.get(name)
2175 if side_effector is not None:
2176 method.side_effect = side_effector(mock)
2177
2178
2179
2180 class MagicMixin(Base):
2181 def __init__(self, /, *args, **kw):
2182 self._mock_set_magics() # make magic work for kwargs in init
2183 _safe_super(MagicMixin, self).__init__(*args, **kw)
2184 self._mock_set_magics() # fix magic broken by upper level init
2185
2186
2187 def _mock_set_magics(self):
2188 orig_magics = _magics | _async_method_magics
2189 these_magics = orig_magics
2190
2191 if getattr(self, "_mock_methods", None) is not None:
2192 these_magics = orig_magics.intersection(self._mock_methods)
2193 remove_magics = orig_magics - these_magics
2194
2195 for entry in remove_magics:
2196 if entry in type(self).__dict__:
2197 # remove unneeded magic methods
2198 delattr(self, entry)
2199
2200 # don't overwrite existing attributes if called a second time
2201 these_magics = these_magics - set(type(self).__dict__)
2202
2203 _type = type(self)
2204 for entry in these_magics:
2205 setattr(_type, entry, MagicProxy(entry, self))
2206
2207
2208
2209 class NonCallableMagicMock(MagicMixin, NonCallableMock):
2210 """A version of `MagicMock` that isn't callable."""
2211 def mock_add_spec(self, spec, spec_set=False):
2212 """Add a spec to a mock. `spec` can either be an object or a
2213 list of strings. Only attributes on the `spec` can be fetched as
2214 attributes from the mock.
2215
2216 If `spec_set` is True then only attributes on the spec can be set."""
2217 self._mock_add_spec(spec, spec_set)
2218 self._mock_set_magics()
2219
2220
2221 class AsyncMagicMixin(MagicMixin):
2222 pass
2223
2224
2225 class MagicMock(MagicMixin, Mock):
2226 """
2227 MagicMock is a subclass of Mock with default implementations
2228 of most of the magic methods. You can use MagicMock without having to
2229 configure the magic methods yourself.
2230
2231 If you use the `spec` or `spec_set` arguments then *only* magic
2232 methods that exist in the spec will be created.
2233
2234 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
2235 """
2236 def mock_add_spec(self, spec, spec_set=False):
2237 """Add a spec to a mock. `spec` can either be an object or a
2238 list of strings. Only attributes on the `spec` can be fetched as
2239 attributes from the mock.
2240
2241 If `spec_set` is True then only attributes on the spec can be set."""
2242 self._mock_add_spec(spec, spec_set)
2243 self._mock_set_magics()
2244
2245 def reset_mock(self, /, *args, return_value: bool = False, **kwargs):
2246 if (
2247 return_value
2248 and self._mock_name
2249 and _is_magic(self._mock_name)
2250 ):
2251 # Don't reset return values for magic methods,
2252 # otherwise `m.__str__` will start
2253 # to return `MagicMock` instances, instead of `str` instances.
2254 return_value = False
2255 super().reset_mock(*args, return_value=return_value, **kwargs)
2256
2257
2258 class MagicProxy(Base):
2259 def __init__(self, name, parent):
2260 self.name = name
2261 self.parent = parent
2262
2263 def create_mock(self):
2264 entry = self.name
2265 parent = self.parent
2266 m = parent._get_child_mock(name=entry, _new_name=entry,
2267 _new_parent=parent)
2268 setattr(parent, entry, m)
2269 _set_return_value(parent, m, entry)
2270 return m
2271
2272 def __get__(self, obj, _type=None):
2273 return self.create_mock()
2274
2275
2276 try:
2277 _CODE_SIG = inspect.signature(partial(CodeType.__init__, None))
2278 _CODE_ATTRS = dir(CodeType)
2279 except ValueError:
2280 _CODE_SIG = None
2281
2282
2283 class AsyncMockMixin(Base):
2284 await_count = _delegating_property('await_count')
2285 await_args = _delegating_property('await_args')
2286 await_args_list = _delegating_property('await_args_list')
2287
2288 def __init__(self, /, *args, **kwargs):
2289 super().__init__(*args, **kwargs)
2290 # iscoroutinefunction() checks _is_coroutine property to say if an
2291 # object is a coroutine. Without this check it looks to see if it is a
2292 # function/method, which in this case it is not (since it is an
2293 # AsyncMock).
2294 # It is set through __dict__ because when spec_set is True, this
2295 # attribute is likely undefined.
2296 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine
2297 self.__dict__['_mock_await_count'] = 0
2298 self.__dict__['_mock_await_args'] = None
2299 self.__dict__['_mock_await_args_list'] = _CallList()
2300 if _CODE_SIG:
2301 code_mock = NonCallableMock(spec_set=_CODE_ATTRS)
2302 code_mock.__dict__["_spec_class"] = CodeType
2303 code_mock.__dict__["_spec_signature"] = _CODE_SIG
2304 else:
2305 code_mock = NonCallableMock(spec_set=CodeType)
2306 code_mock.co_flags = (
2307 inspect.CO_COROUTINE
2308 + inspect.CO_VARARGS
2309 + inspect.CO_VARKEYWORDS
2310 )
2311 code_mock.co_argcount = 0
2312 code_mock.co_varnames = ('args', 'kwargs')
2313 code_mock.co_posonlyargcount = 0
2314 code_mock.co_kwonlyargcount = 0
2315 self.__dict__['__code__'] = code_mock
2316 self.__dict__['__name__'] = 'AsyncMock'
2317 self.__dict__['__defaults__'] = tuple()
2318 self.__dict__['__kwdefaults__'] = {}
2319 self.__dict__['__annotations__'] = None
2320
2321 async def _execute_mock_call(self, /, *args, **kwargs):
2322 # This is nearly just like super(), except for special handling
2323 # of coroutines
2324
2325 _call = _Call((args, kwargs), two=True)
2326 self.await_count += 1
2327 self.await_args = _call
2328 self.await_args_list.append(_call)
2329
2330 effect = self.side_effect
2331 if effect is not None:
2332 if _is_exception(effect):
2333 raise effect
2334 elif not _callable(effect):
2335 try:
2336 result = next(effect)
2337 except StopIteration:
2338 # It is impossible to propagate a StopIteration
2339 # through coroutines because of PEP 479
2340 raise StopAsyncIteration
2341 if _is_exception(result):
2342 raise result
2343 elif iscoroutinefunction(effect):
2344 result = await effect(*args, **kwargs)
2345 else:
2346 result = effect(*args, **kwargs)
2347
2348 if result is not DEFAULT:
2349 return result
2350
2351 if self._mock_return_value is not DEFAULT:
2352 return self.return_value
2353
2354 if self._mock_wraps is not None:
2355 if iscoroutinefunction(self._mock_wraps):
2356 return await self._mock_wraps(*args, **kwargs)
2357 return self._mock_wraps(*args, **kwargs)
2358
2359 return self.return_value
2360
2361 def assert_awaited(self):
2362 """
2363 Assert that the mock was awaited at least once.
2364 """
2365 if self.await_count == 0:
2366 msg = f"Expected {self._mock_name or 'mock'} to have been awaited."
2367 raise AssertionError(msg)
2368
2369 def assert_awaited_once(self):
2370 """
2371 Assert that the mock was awaited exactly once.
2372 """
2373 if not self.await_count == 1:
2374 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2375 f" Awaited {self.await_count} times.")
2376 raise AssertionError(msg)
2377
2378 def assert_awaited_with(self, /, *args, **kwargs):
2379 """
2380 Assert that the last await was with the specified arguments.
2381 """
2382 if self.await_args is None:
2383 expected = self._format_mock_call_signature(args, kwargs)
2384 raise AssertionError(f'Expected await: {expected}\nNot awaited')
2385
2386 def _error_message():
2387 msg = self._format_mock_failure_message(args, kwargs, action='await')
2388 return msg
2389
2390 expected = self._call_matcher(_Call((args, kwargs), two=True))
2391 actual = self._call_matcher(self.await_args)
2392 if actual != expected:
2393 cause = expected if isinstance(expected, Exception) else None
2394 raise AssertionError(_error_message()) from cause
2395
2396 def assert_awaited_once_with(self, /, *args, **kwargs):
2397 """
2398 Assert that the mock was awaited exactly once and with the specified
2399 arguments.
2400 """
2401 if not self.await_count == 1:
2402 msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once."
2403 f" Awaited {self.await_count} times.")
2404 raise AssertionError(msg)
2405 return self.assert_awaited_with(*args, **kwargs)
2406
2407 def assert_any_await(self, /, *args, **kwargs):
2408 """
2409 Assert the mock has ever been awaited with the specified arguments.
2410 """
2411 expected = self._call_matcher(_Call((args, kwargs), two=True))
2412 cause = expected if isinstance(expected, Exception) else None
2413 actual = [self._call_matcher(c) for c in self.await_args_list]
2414 if cause or expected not in _AnyComparer(actual):
2415 expected_string = self._format_mock_call_signature(args, kwargs)
2416 raise AssertionError(
2417 '%s await not found' % expected_string
2418 ) from cause
2419
2420 def assert_has_awaits(self, calls, any_order=False):
2421 """
2422 Assert the mock has been awaited with the specified calls.
2423 The :attr:`await_args_list` list is checked for the awaits.
2424
2425 If `any_order` is False (the default) then the awaits must be
2426 sequential. There can be extra calls before or after the
2427 specified awaits.
2428
2429 If `any_order` is True then the awaits can be in any order, but
2430 they must all appear in :attr:`await_args_list`.
2431 """
2432 expected = [self._call_matcher(c) for c in calls]
2433 cause = next((e for e in expected if isinstance(e, Exception)), None)
2434 all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
2435 if not any_order:
2436 if expected not in all_awaits:
2437 if cause is None:
2438 problem = 'Awaits not found.'
2439 else:
2440 problem = ('Error processing expected awaits.\n'
2441 'Errors: {}').format(
2442 [e if isinstance(e, Exception) else None
2443 for e in expected])
2444 raise AssertionError(
2445 f'{problem}\n'
2446 f'Expected: {_CallList(calls)}\n'
2447 f'Actual: {self.await_args_list}'
2448 ) from cause
2449 return
2450
2451 all_awaits = list(all_awaits)
2452
2453 not_found = []
2454 for kall in expected:
2455 try:
2456 all_awaits.remove(kall)
2457 except ValueError:
2458 not_found.append(kall)
2459 if not_found:
2460 raise AssertionError(
2461 '%r not all found in await list' % (tuple(not_found),)
2462 ) from cause
2463
2464 def assert_not_awaited(self):
2465 """
2466 Assert that the mock was never awaited.
2467 """
2468 if self.await_count != 0:
2469 msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited."
2470 f" Awaited {self.await_count} times.")
2471 raise AssertionError(msg)
2472
2473 def reset_mock(self, /, *args, **kwargs):
2474 """
2475 See :func:`.Mock.reset_mock()`
2476 """
2477 super().reset_mock(*args, **kwargs)
2478 self.await_count = 0
2479 self.await_args = None
2480 self.await_args_list = _CallList()
2481
2482
2483 class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):
2484 """
2485 Enhance :class:`Mock` with features allowing to mock
2486 an async function.
2487
2488 The :class:`AsyncMock` object will behave so the object is
2489 recognized as an async function, and the result of a call is an awaitable:
2490
2491 >>> mock = AsyncMock()
2492 >>> inspect.iscoroutinefunction(mock)
2493 True
2494 >>> inspect.isawaitable(mock())
2495 True
2496
2497
2498 The result of ``mock()`` is an async function which will have the outcome
2499 of ``side_effect`` or ``return_value``:
2500
2501 - if ``side_effect`` is a function, the async function will return the
2502 result of that function,
2503 - if ``side_effect`` is an exception, the async function will raise the
2504 exception,
2505 - if ``side_effect`` is an iterable, the async function will return the
2506 next value of the iterable, however, if the sequence of result is
2507 exhausted, ``StopIteration`` is raised immediately,
2508 - if ``side_effect`` is not defined, the async function will return the
2509 value defined by ``return_value``, hence, by default, the async function
2510 returns a new :class:`AsyncMock` object.
2511
2512 If the outcome of ``side_effect`` or ``return_value`` is an async function,
2513 the mock async function obtained when the mock object is called will be this
2514 async function itself (and not an async function returning an async
2515 function).
2516
2517 The test author can also specify a wrapped object with ``wraps``. In this
2518 case, the :class:`Mock` object behavior is the same as with an
2519 :class:`.Mock` object: the wrapped object may have methods
2520 defined as async function functions.
2521
2522 Based on Martin Richard's asynctest project.
2523 """
2524
2525
2526 class _ANY(object):
2527 "A helper object that compares equal to everything."
2528
2529 def __eq__(self, other):
2530 return True
2531
2532 def __ne__(self, other):
2533 return False
2534
2535 def __repr__(self):
2536 return '<ANY>'
2537
2538 ANY = _ANY()
2539
2540
2541
2542 def _format_call_signature(name, args, kwargs):
2543 message = '%s(%%s)' % name
2544 formatted_args = ''
2545 args_string = ', '.join([repr(arg) for arg in args])
2546 kwargs_string = ', '.join([
2547 '%s=%r' % (key, value) for key, value in kwargs.items()
2548 ])
2549 if args_string:
2550 formatted_args = args_string
2551 if kwargs_string:
2552 if formatted_args:
2553 formatted_args += ', '
2554 formatted_args += kwargs_string
2555
2556 return message % formatted_args
2557
2558
2559
2560 class _Call(tuple):
2561 """
2562 A tuple for holding the results of a call to a mock, either in the form
2563 `(args, kwargs)` or `(name, args, kwargs)`.
2564
2565 If args or kwargs are empty then a call tuple will compare equal to
2566 a tuple without those values. This makes comparisons less verbose::
2567
2568 _Call(('name', (), {})) == ('name',)
2569 _Call(('name', (1,), {})) == ('name', (1,))
2570 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
2571
2572 The `_Call` object provides a useful shortcut for comparing with call::
2573
2574 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
2575 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
2576
2577 If the _Call has no name then it will match any name.
2578 """
2579 def __new__(cls, value=(), name='', parent=None, two=False,
2580 from_kall=True):
2581 args = ()
2582 kwargs = {}
2583 _len = len(value)
2584 if _len == 3:
2585 name, args, kwargs = value
2586 elif _len == 2:
2587 first, second = value
2588 if isinstance(first, str):
2589 name = first
2590 if isinstance(second, tuple):
2591 args = second
2592 else:
2593 kwargs = second
2594 else:
2595 args, kwargs = first, second
2596 elif _len == 1:
2597 value, = value
2598 if isinstance(value, str):
2599 name = value
2600 elif isinstance(value, tuple):
2601 args = value
2602 else:
2603 kwargs = value
2604
2605 if two:
2606 return tuple.__new__(cls, (args, kwargs))
2607
2608 return tuple.__new__(cls, (name, args, kwargs))
2609
2610
2611 def __init__(self, value=(), name=None, parent=None, two=False,
2612 from_kall=True):
2613 self._mock_name = name
2614 self._mock_parent = parent
2615 self._mock_from_kall = from_kall
2616
2617
2618 def __eq__(self, other):
2619 try:
2620 len_other = len(other)
2621 except TypeError:
2622 return NotImplemented
2623
2624 self_name = ''
2625 if len(self) == 2:
2626 self_args, self_kwargs = self
2627 else:
2628 self_name, self_args, self_kwargs = self
2629
2630 if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None)
2631 and self._mock_parent != other._mock_parent):
2632 return False
2633
2634 other_name = ''
2635 if len_other == 0:
2636 other_args, other_kwargs = (), {}
2637 elif len_other == 3:
2638 other_name, other_args, other_kwargs = other
2639 elif len_other == 1:
2640 value, = other
2641 if isinstance(value, tuple):
2642 other_args = value
2643 other_kwargs = {}
2644 elif isinstance(value, str):
2645 other_name = value
2646 other_args, other_kwargs = (), {}
2647 else:
2648 other_args = ()
2649 other_kwargs = value
2650 elif len_other == 2:
2651 # could be (name, args) or (name, kwargs) or (args, kwargs)
2652 first, second = other
2653 if isinstance(first, str):
2654 other_name = first
2655 if isinstance(second, tuple):
2656 other_args, other_kwargs = second, {}
2657 else:
2658 other_args, other_kwargs = (), second
2659 else:
2660 other_args, other_kwargs = first, second
2661 else:
2662 return False
2663
2664 if self_name and other_name != self_name:
2665 return False
2666
2667 # this order is important for ANY to work!
2668 return (other_args, other_kwargs) == (self_args, self_kwargs)
2669
2670
2671 __ne__ = object.__ne__
2672
2673
2674 def __call__(self, /, *args, **kwargs):
2675 if self._mock_name is None:
2676 return _Call(('', args, kwargs), name='()')
2677
2678 name = self._mock_name + '()'
2679 return _Call((self._mock_name, args, kwargs), name=name, parent=self)
2680
2681
2682 def __getattr__(self, attr):
2683 if self._mock_name is None:
2684 return _Call(name=attr, from_kall=False)
2685 name = '%s.%s' % (self._mock_name, attr)
2686 return _Call(name=name, parent=self, from_kall=False)
2687
2688
2689 def __getattribute__(self, attr):
2690 if attr in tuple.__dict__:
2691 raise AttributeError
2692 return tuple.__getattribute__(self, attr)
2693
2694
2695 def _get_call_arguments(self):
2696 if len(self) == 2:
2697 args, kwargs = self
2698 else:
2699 name, args, kwargs = self
2700
2701 return args, kwargs
2702
2703 @property
2704 def args(self):
2705 return self._get_call_arguments()[0]
2706
2707 @property
2708 def kwargs(self):
2709 return self._get_call_arguments()[1]
2710
2711 def __repr__(self):
2712 if not self._mock_from_kall:
2713 name = self._mock_name or 'call'
2714 if name.startswith('()'):
2715 name = 'call%s' % name
2716 return name
2717
2718 if len(self) == 2:
2719 name = 'call'
2720 args, kwargs = self
2721 else:
2722 name, args, kwargs = self
2723 if not name:
2724 name = 'call'
2725 elif not name.startswith('()'):
2726 name = 'call.%s' % name
2727 else:
2728 name = 'call%s' % name
2729 return _format_call_signature(name, args, kwargs)
2730
2731
2732 def call_list(self):
2733 """For a call object that represents multiple calls, `call_list`
2734 returns a list of all the intermediate calls as well as the
2735 final call."""
2736 vals = []
2737 thing = self
2738 while thing is not None:
2739 if thing._mock_from_kall:
2740 vals.append(thing)
2741 thing = thing._mock_parent
2742 return _CallList(reversed(vals))
2743
2744
2745 call = _Call(from_kall=False)
2746
2747
2748 def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2749 _name=None, *, unsafe=False, **kwargs):
2750 """Create a mock object using another object as a spec. Attributes on the
2751 mock will use the corresponding attribute on the `spec` object as their
2752 spec.
2753
2754 Functions or methods being mocked will have their arguments checked
2755 to check that they are called with the correct signature.
2756
2757 If `spec_set` is True then attempting to set attributes that don't exist
2758 on the spec object will raise an `AttributeError`.
2759
2760 If a class is used as a spec then the return value of the mock (the
2761 instance of the class) will have the same spec. You can use a class as the
2762 spec for an instance object by passing `instance=True`. The returned mock
2763 will only be callable if instances of the mock are callable.
2764
2765 `create_autospec` will raise a `RuntimeError` if passed some common
2766 misspellings of the arguments autospec and spec_set. Pass the argument
2767 `unsafe` with the value True to disable that check.
2768
2769 `create_autospec` also takes arbitrary keyword arguments that are passed to
2770 the constructor of the created mock."""
2771 if _is_list(spec):
2772 # can't pass a list instance to the mock constructor as it will be
2773 # interpreted as a list of strings
2774 spec = type(spec)
2775
2776 is_type = isinstance(spec, type)
2777 if _is_instance_mock(spec):
2778 raise InvalidSpecError(f'Cannot autospec a Mock object. '
2779 f'[object={spec!r}]')
2780 is_async_func = _is_async_func(spec)
2781 _kwargs = {'spec': spec}
2782
2783 entries = [(entry, _missing) for entry in dir(spec)]
2784 if is_type and instance and is_dataclass(spec):
2785 is_dataclass_spec = True
2786 dataclass_fields = fields(spec)
2787 entries.extend((f.name, f.type) for f in dataclass_fields)
2788 dataclass_spec_list = [f.name for f in dataclass_fields]
2789 else:
2790 is_dataclass_spec = False
2791
2792 if spec_set:
2793 _kwargs = {'spec_set': spec}
2794 elif spec is None:
2795 # None we mock with a normal mock without a spec
2796 _kwargs = {}
2797 if _kwargs and instance:
2798 _kwargs['_spec_as_instance'] = True
2799 if not unsafe:
2800 _check_spec_arg_typos(kwargs)
2801
2802 _name = kwargs.pop('name', _name)
2803 _new_name = _name
2804 if _parent is None:
2805 # for a top level object no _new_name should be set
2806 _new_name = ''
2807
2808 _kwargs.update(kwargs)
2809
2810 Klass = MagicMock
2811 if inspect.isdatadescriptor(spec):
2812 # descriptors don't have a spec
2813 # because we don't know what type they return
2814 _kwargs = {}
2815 elif is_async_func:
2816 if instance:
2817 raise RuntimeError("Instance can not be True when create_autospec "
2818 "is mocking an async function")
2819 Klass = AsyncMock
2820 elif not _callable(spec):
2821 Klass = NonCallableMagicMock
2822 elif is_type and instance and not _instance_callable(spec):
2823 Klass = NonCallableMagicMock
2824
2825 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2826 name=_name, **_kwargs)
2827 if is_dataclass_spec:
2828 mock._mock_extend_spec_methods(dataclass_spec_list)
2829
2830 if isinstance(spec, FunctionTypes):
2831 # should only happen at the top level because we don't
2832 # recurse for functions
2833 if is_async_func:
2834 mock = _set_async_signature(mock, spec)
2835 else:
2836 mock = _set_signature(mock, spec)
2837 else:
2838 _check_signature(spec, mock, is_type, instance)
2839
2840 if _parent is not None and not instance:
2841 _parent._mock_children[_name] = mock
2842
2843 # Pop wraps from kwargs because it must not be passed to configure_mock.
2844 wrapped = kwargs.pop('wraps', None)
2845 if is_type and not instance and 'return_value' not in kwargs:
2846 mock.return_value = create_autospec(spec, spec_set, instance=True,
2847 _name='()', _parent=mock,
2848 wraps=wrapped)
2849
2850 for entry, original in entries:
2851 if _is_magic(entry):
2852 # MagicMock already does the useful magic methods for us
2853 continue
2854
2855 # XXXX do we need a better way of getting attributes without
2856 # triggering code execution (?) Probably not - we need the actual
2857 # object to mock it so we would rather trigger a property than mock
2858 # the property descriptor. Likewise we want to mock out dynamically
2859 # provided attributes.
2860 # XXXX what about attributes that raise exceptions other than
2861 # AttributeError on being fetched?
2862 # we could be resilient against it, or catch and propagate the
2863 # exception when the attribute is fetched from the mock
2864 if original is _missing:
2865 try:
2866 original = getattr(spec, entry)
2867 except AttributeError:
2868 continue
2869
2870 child_kwargs = {'spec': original}
2871 # Wrap child attributes also.
2872 if wrapped and hasattr(wrapped, entry):
2873 child_kwargs.update(wraps=original)
2874 if spec_set:
2875 child_kwargs = {'spec_set': original}
2876
2877 if not isinstance(original, FunctionTypes):
2878 new = _SpecState(original, spec_set, mock, entry, instance)
2879 mock._mock_children[entry] = new
2880 else:
2881 parent = mock
2882 if isinstance(spec, FunctionTypes):
2883 parent = mock.mock
2884
2885 skipfirst = _must_skip(spec, entry, is_type)
2886 child_kwargs['_eat_self'] = skipfirst
2887 if iscoroutinefunction(original):
2888 child_klass = AsyncMock
2889 else:
2890 child_klass = MagicMock
2891 new = child_klass(parent=parent, name=entry, _new_name=entry,
2892 _new_parent=parent, **child_kwargs)
2893 mock._mock_children[entry] = new
2894 new.return_value = child_klass()
2895 _check_signature(original, new, skipfirst=skipfirst)
2896
2897 # so functions created with _set_signature become instance attributes,
2898 # *plus* their underlying mock exists in _mock_children of the parent
2899 # mock. Adding to _mock_children may be unnecessary where we are also
2900 # setting as an instance attribute?
2901 if isinstance(new, FunctionTypes):
2902 setattr(mock, entry, new)
2903 # kwargs are passed with respect to the parent mock so, they are not used
2904 # for creating return_value of the parent mock. So, this condition
2905 # should be true only for the parent mock if kwargs are given.
2906 if _is_instance_mock(mock) and kwargs:
2907 mock.configure_mock(**kwargs)
2908
2909 return mock
2910
2911
2912 def _must_skip(spec, entry, is_type):
2913 """
2914 Return whether we should skip the first argument on spec's `entry`
2915 attribute.
2916 """
2917 if not isinstance(spec, type):
2918 if entry in getattr(spec, '__dict__', {}):
2919 # instance attribute - shouldn't skip
2920 return False
2921 spec = spec.__class__
2922
2923 for klass in spec.__mro__:
2924 result = klass.__dict__.get(entry, DEFAULT)
2925 if result is DEFAULT:
2926 continue
2927 if isinstance(result, (staticmethod, classmethod)):
2928 return False
2929 elif isinstance(result, FunctionTypes):
2930 # Normal method => skip if looked up on type
2931 # (if looked up on instance, self is already skipped)
2932 return is_type
2933 else:
2934 return False
2935
2936 # function is a dynamically provided attribute
2937 return is_type
2938
2939
2940 class _SpecState(object):
2941
2942 def __init__(self, spec, spec_set=False, parent=None,
2943 name=None, ids=None, instance=False):
2944 self.spec = spec
2945 self.ids = ids
2946 self.spec_set = spec_set
2947 self.parent = parent
2948 self.instance = instance
2949 self.name = name
2950
2951
2952 FunctionTypes = (
2953 # python function
2954 type(create_autospec),
2955 # instance method
2956 type(ANY.__eq__),
2957 )
2958
2959
2960 file_spec = None
2961 open_spec = None
2962
2963
2964 def _to_stream(read_data):
2965 if isinstance(read_data, bytes):
2966 return io.BytesIO(read_data)
2967 else:
2968 return io.StringIO(read_data)
2969
2970
2971 def mock_open(mock=None, read_data=''):
2972 """
2973 A helper function to create a mock to replace the use of `open`. It works
2974 for `open` called directly or used as a context manager.
2975
2976 The `mock` argument is the mock object to configure. If `None` (the
2977 default) then a `MagicMock` will be created for you, with the API limited
2978 to methods or attributes available on standard file handles.
2979
2980 `read_data` is a string for the `read`, `readline` and `readlines` of the
2981 file handle to return. This is an empty string by default.
2982 """
2983 _read_data = _to_stream(read_data)
2984 _state = [_read_data, None]
2985
2986 def _readlines_side_effect(*args, **kwargs):
2987 if handle.readlines.return_value is not None:
2988 return handle.readlines.return_value
2989 return _state[0].readlines(*args, **kwargs)
2990
2991 def _read_side_effect(*args, **kwargs):
2992 if handle.read.return_value is not None:
2993 return handle.read.return_value
2994 return _state[0].read(*args, **kwargs)
2995
2996 def _readline_side_effect(*args, **kwargs):
2997 yield from _iter_side_effect()
2998 while True:
2999 yield _state[0].readline(*args, **kwargs)
3000
3001 def _iter_side_effect():
3002 if handle.readline.return_value is not None:
3003 while True:
3004 yield handle.readline.return_value
3005 for line in _state[0]:
3006 yield line
3007
3008 def _next_side_effect():
3009 if handle.readline.return_value is not None:
3010 return handle.readline.return_value
3011 return next(_state[0])
3012
3013 def _exit_side_effect(exctype, excinst, exctb):
3014 handle.close()
3015
3016 global file_spec
3017 if file_spec is None:
3018 import _io
3019 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
3020
3021 global open_spec
3022 if open_spec is None:
3023 import _io
3024 open_spec = list(set(dir(_io.open)))
3025 if mock is None:
3026 mock = MagicMock(name='open', spec=open_spec)
3027
3028 handle = MagicMock(spec=file_spec)
3029 handle.__enter__.return_value = handle
3030
3031 handle.write.return_value = None
3032 handle.read.return_value = None
3033 handle.readline.return_value = None
3034 handle.readlines.return_value = None
3035
3036 handle.read.side_effect = _read_side_effect
3037 _state[1] = _readline_side_effect()
3038 handle.readline.side_effect = _state[1]
3039 handle.readlines.side_effect = _readlines_side_effect
3040 handle.__iter__.side_effect = _iter_side_effect
3041 handle.__next__.side_effect = _next_side_effect
3042 handle.__exit__.side_effect = _exit_side_effect
3043
3044 def reset_data(*args, **kwargs):
3045 _state[0] = _to_stream(read_data)
3046 if handle.readline.side_effect == _state[1]:
3047 # Only reset the side effect if the user hasn't overridden it.
3048 _state[1] = _readline_side_effect()
3049 handle.readline.side_effect = _state[1]
3050 return DEFAULT
3051
3052 mock.side_effect = reset_data
3053 mock.return_value = handle
3054 return mock
3055
3056
3057 class PropertyMock(Mock):
3058 """
3059 A mock intended to be used as a property, or other descriptor, on a class.
3060 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
3061 a return value when it is fetched.
3062
3063 Fetching a `PropertyMock` instance from an object calls the mock, with
3064 no args. Setting it calls the mock with the value being set.
3065 """
3066 def _get_child_mock(self, /, **kwargs):
3067 return MagicMock(**kwargs)
3068
3069 def __get__(self, obj, obj_type=None):
3070 return self()
3071 def __set__(self, obj, val):
3072 self(val)
3073
3074
3075 _timeout_unset = sentinel.TIMEOUT_UNSET
3076
3077 class ThreadingMixin(Base):
3078
3079 DEFAULT_TIMEOUT = None
3080
3081 def _get_child_mock(self, /, **kw):
3082 if isinstance(kw.get("parent"), ThreadingMixin):
3083 kw["timeout"] = kw["parent"]._mock_wait_timeout
3084 elif isinstance(kw.get("_new_parent"), ThreadingMixin):
3085 kw["timeout"] = kw["_new_parent"]._mock_wait_timeout
3086 return super()._get_child_mock(**kw)
3087
3088 def __init__(self, *args, timeout=_timeout_unset, **kwargs):
3089 super().__init__(*args, **kwargs)
3090 if timeout is _timeout_unset:
3091 timeout = self.DEFAULT_TIMEOUT
3092 self.__dict__["_mock_event"] = threading.Event() # Event for any call
3093 self.__dict__["_mock_calls_events"] = [] # Events for each of the calls
3094 self.__dict__["_mock_calls_events_lock"] = threading.Lock()
3095 self.__dict__["_mock_wait_timeout"] = timeout
3096
3097 def reset_mock(self, /, *args, **kwargs):
3098 """
3099 See :func:`.Mock.reset_mock()`
3100 """
3101 super().reset_mock(*args, **kwargs)
3102 self.__dict__["_mock_event"] = threading.Event()
3103 self.__dict__["_mock_calls_events"] = []
3104
3105 def __get_event(self, expected_args, expected_kwargs):
3106 with self._mock_calls_events_lock:
3107 for args, kwargs, event in self._mock_calls_events:
3108 if (args, kwargs) == (expected_args, expected_kwargs):
3109 return event
3110 new_event = threading.Event()
3111 self._mock_calls_events.append((expected_args, expected_kwargs, new_event))
3112 return new_event
3113
3114 def _mock_call(self, *args, **kwargs):
3115 ret_value = super()._mock_call(*args, **kwargs)
3116
3117 call_event = self.__get_event(args, kwargs)
3118 call_event.set()
3119
3120 self._mock_event.set()
3121
3122 return ret_value
3123
3124 def _increment_mock_call(self, /, *args, **kwargs):
3125 with self._mock_calls_events_lock:
3126 super()._increment_mock_call(*args, **kwargs)
3127
3128 def wait_until_called(self, *, timeout=_timeout_unset):
3129 """Wait until the mock object is called.
3130
3131 `timeout` - time to wait for in seconds, waits forever otherwise.
3132 Defaults to the constructor provided timeout.
3133 Use None to block undefinetively.
3134 """
3135 if timeout is _timeout_unset:
3136 timeout = self._mock_wait_timeout
3137 if not self._mock_event.wait(timeout=timeout):
3138 msg = (f"{self._mock_name or 'mock'} was not called before"
3139 f" timeout({timeout}).")
3140 raise AssertionError(msg)
3141
3142 def wait_until_any_call_with(self, *args, **kwargs):
3143 """Wait until the mock object is called with given args.
3144
3145 Waits for the timeout in seconds provided in the constructor.
3146 """
3147 event = self.__get_event(args, kwargs)
3148 if not event.wait(timeout=self._mock_wait_timeout):
3149 expected_string = self._format_mock_call_signature(args, kwargs)
3150 raise AssertionError(f'{expected_string} call not found')
3151
3152
3153 class ThreadingMock(ThreadingMixin, MagicMixin, Mock):
3154 """
3155 A mock that can be used to wait until on calls happening
3156 in a different thread.
3157
3158 The constructor can take a `timeout` argument which
3159 controls the timeout in seconds for all `wait` calls of the mock.
3160
3161 You can change the default timeout of all instances via the
3162 `ThreadingMock.DEFAULT_TIMEOUT` attribute.
3163
3164 If no timeout is set, it will block undefinetively.
3165 """
3166 pass
3167
3168
3169 def seal(mock):
3170 """Disable the automatic generation of child mocks.
3171
3172 Given an input Mock, seals it to ensure no further mocks will be generated
3173 when accessing an attribute that was not already defined.
3174
3175 The operation recursively seals the mock passed in, meaning that
3176 the mock itself, any mocks generated by accessing one of its attributes,
3177 and all assigned mocks without a name or spec will be sealed.
3178 """
3179 mock._mock_sealed = True
3180 for attr in dir(mock):
3181 try:
3182 m = getattr(mock, attr)
3183 except AttributeError:
3184 continue
3185 if not isinstance(m, NonCallableMock):
3186 continue
3187 if isinstance(m._mock_children.get(attr), _SpecState):
3188 continue
3189 if m._mock_new_parent is mock:
3190 seal(m)
3191
3192
3193 class _AsyncIterator:
3194 """
3195 Wraps an iterator in an asynchronous iterator.
3196 """
3197 def __init__(self, iterator):
3198 self.iterator = iterator
3199 code_mock = NonCallableMock(spec_set=CodeType)
3200 code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE
3201 self.__dict__['__code__'] = code_mock
3202
3203 async def __anext__(self):
3204 try:
3205 return next(self.iterator)
3206 except StopIteration:
3207 pass
3208 raise StopAsyncIteration