Debian Codegraph @

lib-python/3/unittest/mock.py

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