Debian Codegraph @

Lib/unittest/mock.py

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