How to use _delegating_property method in autotest

Best Python code snippet using autotest_python

mock.py

Source:mock.py Github

copy

Full Screen

...251 'return_value', '_mock_return_value', 'side_effect',252 '_mock_side_effect', '_mock_parent', '_mock_new_parent',253 '_mock_name', '_mock_new_name'254}255def _delegating_property(name):256 _allowed_names.add(name)257 _the_name = '_mock_' + name258 def _get(self, name=name, _the_name=_the_name):259 sig = self._mock_delegate260 if sig is None:261 return getattr(self, _the_name)262 return getattr(sig, name)263 def _set(self, value, name=name, _the_name=_the_name):264 sig = self._mock_delegate265 if sig is None:266 self.__dict__[_the_name] = value267 else:268 setattr(sig, name, value)269 return property(_get, _set)270class _CallList(list):271 def __contains__(self, value):272 if not isinstance(value, list):273 return list.__contains__(self, value)274 len_value = len(value)275 len_self = len(self)276 if len_value > len_self:277 return False278 for i in range(0, len_self - len_value + 1):279 sub_list = self[i:i+len_value]280 if sub_list == value:281 return True282 return False283 def __repr__(self):284 return pprint.pformat(list(self))285def _check_and_set_parent(parent, value, name, new_name):286 value = _extract_mock(value)287 if not _is_instance_mock(value):288 return False289 if ((value._mock_name or value._mock_new_name) or290 (value._mock_parent is not None) or291 (value._mock_new_parent is not None)):292 return False293 _parent = parent294 while _parent is not None:295 # setting a mock (value) as a child or return value of itself296 # should not modify the mock297 if _parent is value:298 return False299 _parent = _parent._mock_new_parent300 if new_name:301 value._mock_new_parent = parent302 value._mock_new_name = new_name303 if name:304 value._mock_parent = parent305 value._mock_name = name306 return True307# Internal class to identify if we wrapped an iterator object or not.308class _MockIter(object):309 def __init__(self, obj):310 self.obj = iter(obj)311 def __next__(self):312 return next(self.obj)313class Base(object):314 _mock_return_value = DEFAULT315 _mock_side_effect = None316 def __init__(self, /, *args, **kwargs):317 pass318class NonCallableMock(Base):319 """A non-callable version of `Mock`"""320 def __new__(cls, /, *args, **kw):321 # every instance has its own class322 # so we can create magic methods on the323 # class without stomping on other mocks324 bases = (cls,)325 if not issubclass(cls, AsyncMockMixin):326 # Check if spec is an async object or function327 bound_args = _MOCK_SIG.bind_partial(cls, *args, **kw).arguments328 spec_arg = bound_args.get('spec_set', bound_args.get('spec'))329 if spec_arg is not None and _is_async_obj(spec_arg):330 bases = (AsyncMockMixin, cls)331 new = type(cls.__name__, bases, {'__doc__': cls.__doc__})332 instance = _safe_super(NonCallableMock, cls).__new__(new)333 return instance334 def __init__(335 self, spec=None, wraps=None, name=None, spec_set=None,336 parent=None, _spec_state=None, _new_name='', _new_parent=None,337 _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs338 ):339 if _new_parent is None:340 _new_parent = parent341 __dict__ = self.__dict__342 __dict__['_mock_parent'] = parent343 __dict__['_mock_name'] = name344 __dict__['_mock_new_name'] = _new_name345 __dict__['_mock_new_parent'] = _new_parent346 __dict__['_mock_sealed'] = False347 if spec_set is not None:348 spec = spec_set349 spec_set = True350 if _eat_self is None:351 _eat_self = parent is not None352 self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)353 __dict__['_mock_children'] = {}354 __dict__['_mock_wraps'] = wraps355 __dict__['_mock_delegate'] = None356 __dict__['_mock_called'] = False357 __dict__['_mock_call_args'] = None358 __dict__['_mock_call_count'] = 0359 __dict__['_mock_call_args_list'] = _CallList()360 __dict__['_mock_mock_calls'] = _CallList()361 __dict__['method_calls'] = _CallList()362 __dict__['_mock_unsafe'] = unsafe363 if kwargs:364 self.configure_mock(**kwargs)365 _safe_super(NonCallableMock, self).__init__(366 spec, wraps, name, spec_set, parent,367 _spec_state368 )369 def attach_mock(self, mock, attribute):370 """371 Attach a mock as an attribute of this one, replacing its name and372 parent. Calls to the attached mock will be recorded in the373 `method_calls` and `mock_calls` attributes of this one."""374 inner_mock = _extract_mock(mock)375 inner_mock._mock_parent = None376 inner_mock._mock_new_parent = None377 inner_mock._mock_name = ''378 inner_mock._mock_new_name = None379 setattr(self, attribute, mock)380 def mock_add_spec(self, spec, spec_set=False):381 """Add a spec to a mock. `spec` can either be an object or a382 list of strings. Only attributes on the `spec` can be fetched as383 attributes from the mock.384 If `spec_set` is True then only attributes on the spec can be set."""385 self._mock_add_spec(spec, spec_set)386 def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,387 _eat_self=False):388 _spec_class = None389 _spec_signature = None390 _spec_asyncs = []391 for attr in dir(spec):392 if iscoroutinefunction(getattr(spec, attr, None)):393 _spec_asyncs.append(attr)394 if spec is not None and not _is_list(spec):395 if isinstance(spec, type):396 _spec_class = spec397 else:398 _spec_class = type(spec)399 res = _get_signature_object(spec,400 _spec_as_instance, _eat_self)401 _spec_signature = res and res[1]402 spec = dir(spec)403 __dict__ = self.__dict__404 __dict__['_spec_class'] = _spec_class405 __dict__['_spec_set'] = spec_set406 __dict__['_spec_signature'] = _spec_signature407 __dict__['_mock_methods'] = spec408 __dict__['_spec_asyncs'] = _spec_asyncs409 def __get_return_value(self):410 ret = self._mock_return_value411 if self._mock_delegate is not None:412 ret = self._mock_delegate.return_value413 if ret is DEFAULT:414 ret = self._get_child_mock(415 _new_parent=self, _new_name='()'416 )417 self.return_value = ret418 return ret419 def __set_return_value(self, value):420 if self._mock_delegate is not None:421 self._mock_delegate.return_value = value422 else:423 self._mock_return_value = value424 _check_and_set_parent(self, value, None, '()')425 __return_value_doc = "The value to be returned when the mock is called."426 return_value = property(__get_return_value, __set_return_value,427 __return_value_doc)428 @property429 def __class__(self):430 if self._spec_class is None:431 return type(self)432 return self._spec_class433 called = _delegating_property('called')434 call_count = _delegating_property('call_count')435 call_args = _delegating_property('call_args')436 call_args_list = _delegating_property('call_args_list')437 mock_calls = _delegating_property('mock_calls')438 def __get_side_effect(self):439 delegated = self._mock_delegate440 if delegated is None:441 return self._mock_side_effect442 sf = delegated.side_effect443 if (sf is not None and not callable(sf)444 and not isinstance(sf, _MockIter) and not _is_exception(sf)):445 sf = _MockIter(sf)446 delegated.side_effect = sf447 return sf448 def __set_side_effect(self, value):449 value = _try_iter(value)450 delegated = self._mock_delegate451 if delegated is None:452 self._mock_side_effect = value453 else:454 delegated.side_effect = value455 side_effect = property(__get_side_effect, __set_side_effect)456 def reset_mock(self, visited=None,*, return_value=False, side_effect=False):457 "Restore the mock object to its initial state."458 if visited is None:459 visited = []460 if id(self) in visited:461 return462 visited.append(id(self))463 self.called = False464 self.call_args = None465 self.call_count = 0466 self.mock_calls = _CallList()467 self.call_args_list = _CallList()468 self.method_calls = _CallList()469 if return_value:470 self._mock_return_value = DEFAULT471 if side_effect:472 self._mock_side_effect = None473 for child in self._mock_children.values():474 if isinstance(child, _SpecState) or child is _deleted:475 continue476 child.reset_mock(visited, return_value=return_value, side_effect=side_effect)477 ret = self._mock_return_value478 if _is_instance_mock(ret) and ret is not self:479 ret.reset_mock(visited)480 def configure_mock(self, /, **kwargs):481 """Set attributes on the mock through keyword arguments.482 Attributes plus return values and side effects can be set on child483 mocks using standard dot notation and unpacking a dictionary in the484 method call:485 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}486 >>> mock.configure_mock(**attrs)"""487 for arg, val in sorted(kwargs.items(),488 # we sort on the number of dots so that489 # attributes are set before we set attributes on490 # attributes491 key=lambda entry: entry[0].count('.')):492 args = arg.split('.')493 final = args.pop()494 obj = self495 for entry in args:496 obj = getattr(obj, entry)497 setattr(obj, final, val)498 def __getattr__(self, name):499 if name in {'_mock_methods', '_mock_unsafe'}:500 raise AttributeError(name)501 elif self._mock_methods is not None:502 if name not in self._mock_methods or name in _all_magics:503 raise AttributeError("Mock object has no attribute %r" % name)504 elif _is_magic(name):505 raise AttributeError(name)506 if not self._mock_unsafe:507 if name.startswith(('assert', 'assret')):508 raise AttributeError("Attributes cannot start with 'assert' "509 "or 'assret'")510 result = self._mock_children.get(name)511 if result is _deleted:512 raise AttributeError(name)513 elif result is None:514 wraps = None515 if self._mock_wraps is not None:516 # XXXX should we get the attribute without triggering code517 # execution?518 wraps = getattr(self._mock_wraps, name)519 result = self._get_child_mock(520 parent=self, name=name, wraps=wraps, _new_name=name,521 _new_parent=self522 )523 self._mock_children[name] = result524 elif isinstance(result, _SpecState):525 result = create_autospec(526 result.spec, result.spec_set, result.instance,527 result.parent, result.name528 )529 self._mock_children[name] = result530 return result531 def _extract_mock_name(self):532 _name_list = [self._mock_new_name]533 _parent = self._mock_new_parent534 last = self535 dot = '.'536 if _name_list == ['()']:537 dot = ''538 while _parent is not None:539 last = _parent540 _name_list.append(_parent._mock_new_name + dot)541 dot = '.'542 if _parent._mock_new_name == '()':543 dot = ''544 _parent = _parent._mock_new_parent545 _name_list = list(reversed(_name_list))546 _first = last._mock_name or 'mock'547 if len(_name_list) > 1:548 if _name_list[1] not in ('()', '().'):549 _first += '.'550 _name_list[0] = _first551 return ''.join(_name_list)552 def __repr__(self):553 name = self._extract_mock_name()554 name_string = ''555 if name not in ('mock', 'mock.'):556 name_string = ' name=%r' % name557 spec_string = ''558 if self._spec_class is not None:559 spec_string = ' spec=%r'560 if self._spec_set:561 spec_string = ' spec_set=%r'562 spec_string = spec_string % self._spec_class.__name__563 return "<%s%s%s id='%s'>" % (564 type(self).__name__,565 name_string,566 spec_string,567 id(self)568 )569 def __dir__(self):570 """Filter the output of `dir(mock)` to only useful members."""571 if not FILTER_DIR:572 return object.__dir__(self)573 extras = self._mock_methods or []574 from_type = dir(type(self))575 from_dict = list(self.__dict__)576 from_child_mocks = [577 m_name for m_name, m_value in self._mock_children.items()578 if m_value is not _deleted]579 from_type = [e for e in from_type if not e.startswith('_')]580 from_dict = [e for e in from_dict if not e.startswith('_') or581 _is_magic(e)]582 return sorted(set(extras + from_type + from_dict + from_child_mocks))583 def __setattr__(self, name, value):584 if name in _allowed_names:585 # property setters go through here586 return object.__setattr__(self, name, value)587 elif (self._spec_set and self._mock_methods is not None and588 name not in self._mock_methods and589 name not in self.__dict__):590 raise AttributeError("Mock object has no attribute '%s'" % name)591 elif name in _unsupported_magics:592 msg = 'Attempting to set unsupported magic method %r.' % name593 raise AttributeError(msg)594 elif name in _all_magics:595 if self._mock_methods is not None and name not in self._mock_methods:596 raise AttributeError("Mock object has no attribute '%s'" % name)597 if not _is_instance_mock(value):598 setattr(type(self), name, _get_method(name, value))599 original = value600 value = lambda *args, **kw: original(self, *args, **kw)601 else:602 # only set _new_name and not name so that mock_calls is tracked603 # but not method calls604 _check_and_set_parent(self, value, None, name)605 setattr(type(self), name, value)606 self._mock_children[name] = value607 elif name == '__class__':608 self._spec_class = value609 return610 else:611 if _check_and_set_parent(self, value, name, name):612 self._mock_children[name] = value613 if self._mock_sealed and not hasattr(self, name):614 mock_name = f'{self._extract_mock_name()}.{name}'615 raise AttributeError(f'Cannot set {mock_name}')616 return object.__setattr__(self, name, value)617 def __delattr__(self, name):618 if name in _all_magics and name in type(self).__dict__:619 delattr(type(self), name)620 if name not in self.__dict__:621 # for magic methods that are still MagicProxy objects and622 # not set on the instance itself623 return624 obj = self._mock_children.get(name, _missing)625 if name in self.__dict__:626 _safe_super(NonCallableMock, self).__delattr__(name)627 elif obj is _deleted:628 raise AttributeError(name)629 if obj is not _missing:630 del self._mock_children[name]631 self._mock_children[name] = _deleted632 def _format_mock_call_signature(self, args, kwargs):633 name = self._mock_name or 'mock'634 return _format_call_signature(name, args, kwargs)635 def _format_mock_failure_message(self, args, kwargs, action='call'):636 message = 'expected %s not found.\nExpected: %s\nActual: %s'637 expected_string = self._format_mock_call_signature(args, kwargs)638 call_args = self.call_args639 actual_string = self._format_mock_call_signature(*call_args)640 return message % (action, expected_string, actual_string)641 def _get_call_signature_from_name(self, name):642 """643 * If call objects are asserted against a method/function like obj.meth1644 then there could be no name for the call object to lookup. Hence just645 return the spec_signature of the method/function being asserted against.646 * If the name is not empty then remove () and split by '.' to get647 list of names to iterate through the children until a potential648 match is found. A child mock is created only during attribute access649 so if we get a _SpecState then no attributes of the spec were accessed650 and can be safely exited.651 """652 if not name:653 return self._spec_signature654 sig = None655 names = name.replace('()', '').split('.')656 children = self._mock_children657 for name in names:658 child = children.get(name)659 if child is None or isinstance(child, _SpecState):660 break661 else:662 # If an autospecced object is attached using attach_mock the663 # child would be a function with mock object as attribute from664 # which signature has to be derived.665 child = _extract_mock(child)666 children = child._mock_children667 sig = child._spec_signature668 return sig669 def _call_matcher(self, _call):670 """671 Given a call (or simply an (args, kwargs) tuple), return a672 comparison key suitable for matching with other calls.673 This is a best effort method which relies on the spec's signature,674 if available, or falls back on the arguments themselves.675 """676 if isinstance(_call, tuple) and len(_call) > 2:677 sig = self._get_call_signature_from_name(_call[0])678 else:679 sig = self._spec_signature680 if sig is not None:681 if len(_call) == 2:682 name = ''683 args, kwargs = _call684 else:685 name, args, kwargs = _call686 try:687 bound_call = sig.bind(*args, **kwargs)688 return call(name, bound_call.args, bound_call.kwargs)689 except TypeError as e:690 return e.with_traceback(None)691 else:692 return _call693 def assert_not_called(self):694 """assert that the mock was never called.695 """696 if self.call_count != 0:697 msg = ("Expected '%s' to not have been called. Called %s times.%s"698 % (self._mock_name or 'mock',699 self.call_count,700 self._calls_repr()))701 raise AssertionError(msg)702 def assert_called(self):703 """assert that the mock was called at least once704 """705 if self.call_count == 0:706 msg = ("Expected '%s' to have been called." %707 (self._mock_name or 'mock'))708 raise AssertionError(msg)709 def assert_called_once(self):710 """assert that the mock was called only once.711 """712 if not self.call_count == 1:713 msg = ("Expected '%s' to have been called once. Called %s times.%s"714 % (self._mock_name or 'mock',715 self.call_count,716 self._calls_repr()))717 raise AssertionError(msg)718 def assert_called_with(self, /, *args, **kwargs):719 """assert that the last call was made with the specified arguments.720 Raises an AssertionError if the args and keyword args passed in are721 different to the last call to the mock."""722 if self.call_args is None:723 expected = self._format_mock_call_signature(args, kwargs)724 actual = 'not called.'725 error_message = ('expected call not found.\nExpected: %s\nActual: %s'726 % (expected, actual))727 raise AssertionError(error_message)728 def _error_message():729 msg = self._format_mock_failure_message(args, kwargs)730 return msg731 expected = self._call_matcher(_Call((args, kwargs), two=True))732 actual = self._call_matcher(self.call_args)733 if actual != expected:734 cause = expected if isinstance(expected, Exception) else None735 raise AssertionError(_error_message()) from cause736 def assert_called_once_with(self, /, *args, **kwargs):737 """assert that the mock was called exactly once and that that call was738 with the specified arguments."""739 if not self.call_count == 1:740 msg = ("Expected '%s' to be called once. Called %s times.%s"741 % (self._mock_name or 'mock',742 self.call_count,743 self._calls_repr()))744 raise AssertionError(msg)745 return self.assert_called_with(*args, **kwargs)746 def assert_has_calls(self, calls, any_order=False):747 """assert the mock has been called with the specified calls.748 The `mock_calls` list is checked for the calls.749 If `any_order` is False (the default) then the calls must be750 sequential. There can be extra calls before or after the751 specified calls.752 If `any_order` is True then the calls can be in any order, but753 they must all appear in `mock_calls`."""754 expected = [self._call_matcher(c) for c in calls]755 cause = next((e for e in expected if isinstance(e, Exception)), None)756 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)757 if not any_order:758 if expected not in all_calls:759 if cause is None:760 problem = 'Calls not found.'761 else:762 problem = ('Error processing expected calls.\n'763 'Errors: {}').format(764 [e if isinstance(e, Exception) else None765 for e in expected])766 raise AssertionError(767 f'{problem}\n'768 f'Expected: {_CallList(calls)}'769 f'{self._calls_repr(prefix="Actual").rstrip(".")}'770 ) from cause771 return772 all_calls = list(all_calls)773 not_found = []774 for kall in expected:775 try:776 all_calls.remove(kall)777 except ValueError:778 not_found.append(kall)779 if not_found:780 raise AssertionError(781 '%r does not contain all of %r in its call list, '782 'found %r instead' % (self._mock_name or 'mock',783 tuple(not_found), all_calls)784 ) from cause785 def assert_any_call(self, /, *args, **kwargs):786 """assert the mock has been called with the specified arguments.787 The assert passes if the mock has *ever* been called, unlike788 `assert_called_with` and `assert_called_once_with` that only pass if789 the call is the most recent one."""790 expected = self._call_matcher(_Call((args, kwargs), two=True))791 cause = expected if isinstance(expected, Exception) else None792 actual = [self._call_matcher(c) for c in self.call_args_list]793 if cause or expected not in _AnyComparer(actual):794 expected_string = self._format_mock_call_signature(args, kwargs)795 raise AssertionError(796 '%s call not found' % expected_string797 ) from cause798 def _get_child_mock(self, /, **kw):799 """Create the child mocks for attributes and return value.800 By default child mocks will be the same type as the parent.801 Subclasses of Mock may want to override this to customize the way802 child mocks are made.803 For non-callable mocks the callable variant will be used (rather than804 any custom subclass)."""805 _new_name = kw.get("_new_name")806 if _new_name in self.__dict__['_spec_asyncs']:807 return AsyncMock(**kw)808 if self._mock_sealed:809 attribute = f".{kw['name']}" if "name" in kw else "()"810 mock_name = self._extract_mock_name() + attribute811 raise AttributeError(mock_name)812 _type = type(self)813 if issubclass(_type, MagicMock) and _new_name in _async_method_magics:814 # Any asynchronous magic becomes an AsyncMock815 klass = AsyncMock816 elif issubclass(_type, AsyncMockMixin):817 if (_new_name in _all_sync_magics or818 self._mock_methods and _new_name in self._mock_methods):819 # Any synchronous method on AsyncMock becomes a MagicMock820 klass = MagicMock821 else:822 klass = AsyncMock823 elif not issubclass(_type, CallableMixin):824 if issubclass(_type, NonCallableMagicMock):825 klass = MagicMock826 elif issubclass(_type, NonCallableMock):827 klass = Mock828 else:829 klass = _type.__mro__[1]830 return klass(**kw)831 def _calls_repr(self, prefix="Calls"):832 """Renders self.mock_calls as a string.833 Example: "\nCalls: [call(1), call(2)]."834 If self.mock_calls is empty, an empty string is returned. The835 output will be truncated if very long.836 """837 if not self.mock_calls:838 return ""839 return f"\n{prefix}: {safe_repr(self.mock_calls)}."840_MOCK_SIG = inspect.signature(NonCallableMock.__init__)841class _AnyComparer(list):842 """A list which checks if it contains a call which may have an843 argument of ANY, flipping the components of item and self from844 their traditional locations so that ANY is guaranteed to be on845 the left."""846 def __contains__(self, item):847 for _call in self:848 assert len(item) == len(_call)849 if all([850 expected == actual851 for expected, actual in zip(item, _call)852 ]):853 return True854 return False855def _try_iter(obj):856 if obj is None:857 return obj858 if _is_exception(obj):859 return obj860 if _callable(obj):861 return obj862 try:863 return iter(obj)864 except TypeError:865 # XXXX backwards compatibility866 # but this will blow up on first call - so maybe we should fail early?867 return obj868class CallableMixin(Base):869 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,870 wraps=None, name=None, spec_set=None, parent=None,871 _spec_state=None, _new_name='', _new_parent=None, **kwargs):872 self.__dict__['_mock_return_value'] = return_value873 _safe_super(CallableMixin, self).__init__(874 spec, wraps, name, spec_set, parent,875 _spec_state, _new_name, _new_parent, **kwargs876 )877 self.side_effect = side_effect878 def _mock_check_sig(self, /, *args, **kwargs):879 # stub method that can be replaced with one with a specific signature880 pass881 def __call__(self, /, *args, **kwargs):882 # can't use self in-case a function / method we are mocking uses self883 # in the signature884 self._mock_check_sig(*args, **kwargs)885 self._increment_mock_call(*args, **kwargs)886 return self._mock_call(*args, **kwargs)887 def _mock_call(self, /, *args, **kwargs):888 return self._execute_mock_call(*args, **kwargs)889 def _increment_mock_call(self, /, *args, **kwargs):890 self.called = True891 self.call_count += 1892 # handle call_args893 # needs to be set here so assertions on call arguments pass before894 # execution in the case of awaited calls895 _call = _Call((args, kwargs), two=True)896 self.call_args = _call897 self.call_args_list.append(_call)898 # initial stuff for method_calls:899 do_method_calls = self._mock_parent is not None900 method_call_name = self._mock_name901 # initial stuff for mock_calls:902 mock_call_name = self._mock_new_name903 is_a_call = mock_call_name == '()'904 self.mock_calls.append(_Call(('', args, kwargs)))905 # follow up the chain of mocks:906 _new_parent = self._mock_new_parent907 while _new_parent is not None:908 # handle method_calls:909 if do_method_calls:910 _new_parent.method_calls.append(_Call((method_call_name, args, kwargs)))911 do_method_calls = _new_parent._mock_parent is not None912 if do_method_calls:913 method_call_name = _new_parent._mock_name + '.' + method_call_name914 # handle mock_calls:915 this_mock_call = _Call((mock_call_name, args, kwargs))916 _new_parent.mock_calls.append(this_mock_call)917 if _new_parent._mock_new_name:918 if is_a_call:919 dot = ''920 else:921 dot = '.'922 is_a_call = _new_parent._mock_new_name == '()'923 mock_call_name = _new_parent._mock_new_name + dot + mock_call_name924 # follow the parental chain:925 _new_parent = _new_parent._mock_new_parent926 def _execute_mock_call(self, /, *args, **kwargs):927 # separate from _increment_mock_call so that awaited functions are928 # executed separately from their call, also AsyncMock overrides this method929 effect = self.side_effect930 if effect is not None:931 if _is_exception(effect):932 raise effect933 elif not _callable(effect):934 result = next(effect)935 if _is_exception(result):936 raise result937 else:938 result = effect(*args, **kwargs)939 if result is not DEFAULT:940 return result941 if self._mock_return_value is not DEFAULT:942 return self.return_value943 if self._mock_wraps is not None:944 return self._mock_wraps(*args, **kwargs)945 return self.return_value946class Mock(CallableMixin, NonCallableMock):947 """948 Create a new `Mock` object. `Mock` takes several optional arguments949 that specify the behaviour of the Mock object:950 * `spec`: This can be either a list of strings or an existing object (a951 class or instance) that acts as the specification for the mock object. If952 you pass in an object then a list of strings is formed by calling dir on953 the object (excluding unsupported magic attributes and methods). Accessing954 any attribute not in this list will raise an `AttributeError`.955 If `spec` is an object (rather than a list of strings) then956 `mock.__class__` returns the class of the spec object. This allows mocks957 to pass `isinstance` tests.958 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*959 or get an attribute on the mock that isn't on the object passed as960 `spec_set` will raise an `AttributeError`.961 * `side_effect`: A function to be called whenever the Mock is called. See962 the `side_effect` attribute. Useful for raising exceptions or963 dynamically changing return values. The function is called with the same964 arguments as the mock, and unless it returns `DEFAULT`, the return965 value of this function is used as the return value.966 If `side_effect` is an iterable then each call to the mock will return967 the next value from the iterable. If any of the members of the iterable968 are exceptions they will be raised instead of returned.969 * `return_value`: The value returned when the mock is called. By default970 this is a new Mock (created on first access). See the971 `return_value` attribute.972 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then973 calling the Mock will pass the call through to the wrapped object974 (returning the real result). Attribute access on the mock will return a975 Mock object that wraps the corresponding attribute of the wrapped object976 (so attempting to access an attribute that doesn't exist will raise an977 `AttributeError`).978 If the mock has an explicit `return_value` set then calls are not passed979 to the wrapped object and the `return_value` is returned instead.980 * `name`: If the mock has a name then it will be used in the repr of the981 mock. This can be useful for debugging. The name is propagated to child982 mocks.983 Mocks can also be called with arbitrary keyword arguments. These will be984 used to set attributes on the mock after it is created.985 """986def _dot_lookup(thing, comp, import_path):987 try:988 return getattr(thing, comp)989 except AttributeError:990 __import__(import_path)991 return getattr(thing, comp)992def _importer(target):993 components = target.split('.')994 import_path = components.pop(0)995 thing = __import__(import_path)996 for comp in components:997 import_path += ".%s" % comp998 thing = _dot_lookup(thing, comp, import_path)999 return thing1000class _patch(object):1001 attribute_name = None1002 _active_patches = []1003 def __init__(1004 self, getter, attribute, new, spec, create,1005 spec_set, autospec, new_callable, kwargs1006 ):1007 if new_callable is not None:1008 if new is not DEFAULT:1009 raise ValueError(1010 "Cannot use 'new' and 'new_callable' together"1011 )1012 if autospec is not None:1013 raise ValueError(1014 "Cannot use 'autospec' and 'new_callable' together"1015 )1016 self.getter = getter1017 self.attribute = attribute1018 self.new = new1019 self.new_callable = new_callable1020 self.spec = spec1021 self.create = create1022 self.has_local = False1023 self.spec_set = spec_set1024 self.autospec = autospec1025 self.kwargs = kwargs1026 self.additional_patchers = []1027 def copy(self):1028 patcher = _patch(1029 self.getter, self.attribute, self.new, self.spec,1030 self.create, self.spec_set,1031 self.autospec, self.new_callable, self.kwargs1032 )1033 patcher.attribute_name = self.attribute_name1034 patcher.additional_patchers = [1035 p.copy() for p in self.additional_patchers1036 ]1037 return patcher1038 def __call__(self, func):1039 if isinstance(func, type):1040 return self.decorate_class(func)1041 if inspect.iscoroutinefunction(func):1042 return self.decorate_async_callable(func)1043 return self.decorate_callable(func)1044 def decorate_class(self, klass):1045 for attr in dir(klass):1046 if not attr.startswith(patch.TEST_PREFIX):1047 continue1048 attr_value = getattr(klass, attr)1049 if not hasattr(attr_value, "__call__"):1050 continue1051 patcher = self.copy()1052 setattr(klass, attr, patcher(attr_value))1053 return klass1054 @contextlib.contextmanager1055 def decoration_helper(self, patched, args, keywargs):1056 extra_args = []1057 with contextlib.ExitStack() as exit_stack:1058 for patching in patched.patchings:1059 arg = exit_stack.enter_context(patching)1060 if patching.attribute_name is not None:1061 keywargs.update(arg)1062 elif patching.new is DEFAULT:1063 extra_args.append(arg)1064 args += tuple(extra_args)1065 yield (args, keywargs)1066 def decorate_callable(self, func):1067 # NB. Keep the method in sync with decorate_async_callable()1068 if hasattr(func, 'patchings'):1069 func.patchings.append(self)1070 return func1071 @wraps(func)1072 def patched(*args, **keywargs):1073 with self.decoration_helper(patched,1074 args,1075 keywargs) as (newargs, newkeywargs):1076 return func(*newargs, **newkeywargs)1077 patched.patchings = [self]1078 return patched1079 def decorate_async_callable(self, func):1080 # NB. Keep the method in sync with decorate_callable()1081 if hasattr(func, 'patchings'):1082 func.patchings.append(self)1083 return func1084 @wraps(func)1085 async def patched(*args, **keywargs):1086 with self.decoration_helper(patched,1087 args,1088 keywargs) as (newargs, newkeywargs):1089 return await func(*newargs, **newkeywargs)1090 patched.patchings = [self]1091 return patched1092 def get_original(self):1093 target = self.getter()1094 name = self.attribute1095 original = DEFAULT1096 local = False1097 try:1098 original = target.__dict__[name]1099 except (AttributeError, KeyError):1100 original = getattr(target, name, DEFAULT)1101 else:1102 local = True1103 if name in _builtins and isinstance(target, ModuleType):1104 self.create = True1105 if not self.create and original is DEFAULT:1106 raise AttributeError(1107 "%s does not have the attribute %r" % (target, name)1108 )1109 return original, local1110 def __enter__(self):1111 """Perform the patch."""1112 new, spec, spec_set = self.new, self.spec, self.spec_set1113 autospec, kwargs = self.autospec, self.kwargs1114 new_callable = self.new_callable1115 self.target = self.getter()1116 # normalise False to None1117 if spec is False:1118 spec = None1119 if spec_set is False:1120 spec_set = None1121 if autospec is False:1122 autospec = None1123 if spec is not None and autospec is not None:1124 raise TypeError("Can't specify spec and autospec")1125 if ((spec is not None or autospec is not None) and1126 spec_set not in (True, None)):1127 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")1128 original, local = self.get_original()1129 if new is DEFAULT and autospec is None:1130 inherit = False1131 if spec is True:1132 # set spec to the object we are replacing1133 spec = original1134 if spec_set is True:1135 spec_set = original1136 spec = None1137 elif spec is not None:1138 if spec_set is True:1139 spec_set = spec1140 spec = None1141 elif spec_set is True:1142 spec_set = original1143 if spec is not None or spec_set is not None:1144 if original is DEFAULT:1145 raise TypeError("Can't use 'spec' with create=True")1146 if isinstance(original, type):1147 # If we're patching out a class and there is a spec1148 inherit = True1149 if spec is None and _is_async_obj(original):1150 Klass = AsyncMock1151 else:1152 Klass = MagicMock1153 _kwargs = {}1154 if new_callable is not None:1155 Klass = new_callable1156 elif spec is not None or spec_set is not None:1157 this_spec = spec1158 if spec_set is not None:1159 this_spec = spec_set1160 if _is_list(this_spec):1161 not_callable = '__call__' not in this_spec1162 else:1163 not_callable = not callable(this_spec)1164 if _is_async_obj(this_spec):1165 Klass = AsyncMock1166 elif not_callable:1167 Klass = NonCallableMagicMock1168 if spec is not None:1169 _kwargs['spec'] = spec1170 if spec_set is not None:1171 _kwargs['spec_set'] = spec_set1172 # add a name to mocks1173 if (isinstance(Klass, type) and1174 issubclass(Klass, NonCallableMock) and self.attribute):1175 _kwargs['name'] = self.attribute1176 _kwargs.update(kwargs)1177 new = Klass(**_kwargs)1178 if inherit and _is_instance_mock(new):1179 # we can only tell if the instance should be callable if the1180 # spec is not a list1181 this_spec = spec1182 if spec_set is not None:1183 this_spec = spec_set1184 if (not _is_list(this_spec) and not1185 _instance_callable(this_spec)):1186 Klass = NonCallableMagicMock1187 _kwargs.pop('name')1188 new.return_value = Klass(_new_parent=new, _new_name='()',1189 **_kwargs)1190 elif autospec is not None:1191 # spec is ignored, new *must* be default, spec_set is treated1192 # as a boolean. Should we check spec is not None and that spec_set1193 # is a bool?1194 if new is not DEFAULT:1195 raise TypeError(1196 "autospec creates the mock for you. Can't specify "1197 "autospec and new."1198 )1199 if original is DEFAULT:1200 raise TypeError("Can't use 'autospec' with create=True")1201 spec_set = bool(spec_set)1202 if autospec is True:1203 autospec = original1204 new = create_autospec(autospec, spec_set=spec_set,1205 _name=self.attribute, **kwargs)1206 elif kwargs:1207 # can't set keyword args when we aren't creating the mock1208 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)1209 raise TypeError("Can't pass kwargs to a mock we aren't creating")1210 new_attr = new1211 self.temp_original = original1212 self.is_local = local1213 self._exit_stack = contextlib.ExitStack()1214 try:1215 setattr(self.target, self.attribute, new_attr)1216 if self.attribute_name is not None:1217 extra_args = {}1218 if self.new is DEFAULT:1219 extra_args[self.attribute_name] = new1220 for patching in self.additional_patchers:1221 arg = self._exit_stack.enter_context(patching)1222 if patching.new is DEFAULT:1223 extra_args.update(arg)1224 return extra_args1225 return new1226 except:1227 if not self.__exit__(*sys.exc_info()):1228 raise1229 def __exit__(self, *exc_info):1230 """Undo the patch."""1231 if self.is_local and self.temp_original is not DEFAULT:1232 setattr(self.target, self.attribute, self.temp_original)1233 else:1234 delattr(self.target, self.attribute)1235 if not self.create and (not hasattr(self.target, self.attribute) or1236 self.attribute in ('__doc__', '__module__',1237 '__defaults__', '__annotations__',1238 '__kwdefaults__')):1239 # needed for proxy objects like django settings1240 setattr(self.target, self.attribute, self.temp_original)1241 del self.temp_original1242 del self.is_local1243 del self.target1244 exit_stack = self._exit_stack1245 del self._exit_stack1246 return exit_stack.__exit__(*exc_info)1247 def start(self):1248 """Activate a patch, returning any created mock."""1249 result = self.__enter__()1250 self._active_patches.append(self)1251 return result1252 def stop(self):1253 """Stop an active patch."""1254 try:1255 self._active_patches.remove(self)1256 except ValueError:1257 # If the patch hasn't been started this will fail1258 return None1259 return self.__exit__(None, None, None)1260def _get_target(target):1261 try:1262 target, attribute = target.rsplit('.', 1)1263 except (TypeError, ValueError, AttributeError):1264 raise TypeError(1265 f"Need a valid target to patch. You supplied: {target!r}")1266 getter = lambda: _importer(target)1267 return getter, attribute1268def _patch_object(1269 target, attribute, new=DEFAULT, spec=None,1270 create=False, spec_set=None, autospec=None,1271 new_callable=None, **kwargs1272 ):1273 """1274 patch the named member (`attribute`) on an object (`target`) with a mock1275 object.1276 `patch.object` can be used as a decorator, class decorator or a context1277 manager. Arguments `new`, `spec`, `create`, `spec_set`,1278 `autospec` and `new_callable` have the same meaning as for `patch`. Like1279 `patch`, `patch.object` takes arbitrary keyword arguments for configuring1280 the mock object it creates.1281 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`1282 for choosing which methods to wrap.1283 """1284 if type(target) is str:1285 raise TypeError(1286 f"{target!r} must be the actual object to be patched, not a str"1287 )1288 getter = lambda: target1289 return _patch(1290 getter, attribute, new, spec, create,1291 spec_set, autospec, new_callable, kwargs1292 )1293def _patch_multiple(target, spec=None, create=False, spec_set=None,1294 autospec=None, new_callable=None, **kwargs):1295 """Perform multiple patches in a single call. It takes the object to be1296 patched (either as an object or a string to fetch the object by importing)1297 and keyword arguments for the patches::1298 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):1299 ...1300 Use `DEFAULT` as the value if you want `patch.multiple` to create1301 mocks for you. In this case the created mocks are passed into a decorated1302 function by keyword, and a dictionary is returned when `patch.multiple` is1303 used as a context manager.1304 `patch.multiple` can be used as a decorator, class decorator or a context1305 manager. The arguments `spec`, `spec_set`, `create`,1306 `autospec` and `new_callable` have the same meaning as for `patch`. These1307 arguments will be applied to *all* patches done by `patch.multiple`.1308 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`1309 for choosing which methods to wrap.1310 """1311 if type(target) is str:1312 getter = lambda: _importer(target)1313 else:1314 getter = lambda: target1315 if not kwargs:1316 raise ValueError(1317 'Must supply at least one keyword argument with patch.multiple'1318 )1319 # need to wrap in a list for python 3, where items is a view1320 items = list(kwargs.items())1321 attribute, new = items[0]1322 patcher = _patch(1323 getter, attribute, new, spec, create, spec_set,1324 autospec, new_callable, {}1325 )1326 patcher.attribute_name = attribute1327 for attribute, new in items[1:]:1328 this_patcher = _patch(1329 getter, attribute, new, spec, create, spec_set,1330 autospec, new_callable, {}1331 )1332 this_patcher.attribute_name = attribute1333 patcher.additional_patchers.append(this_patcher)1334 return patcher1335def patch(1336 target, new=DEFAULT, spec=None, create=False,1337 spec_set=None, autospec=None, new_callable=None, **kwargs1338 ):1339 """1340 `patch` acts as a function decorator, class decorator or a context1341 manager. Inside the body of the function or with statement, the `target`1342 is patched with a `new` object. When the function/with statement exits1343 the patch is undone.1344 If `new` is omitted, then the target is replaced with an1345 `AsyncMock if the patched object is an async function or a1346 `MagicMock` otherwise. If `patch` is used as a decorator and `new` is1347 omitted, the created mock is passed in as an extra argument to the1348 decorated function. If `patch` is used as a context manager the created1349 mock is returned by the context manager.1350 `target` should be a string in the form `'package.module.ClassName'`. The1351 `target` is imported and the specified object replaced with the `new`1352 object, so the `target` must be importable from the environment you are1353 calling `patch` from. The target is imported when the decorated function1354 is executed, not at decoration time.1355 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`1356 if patch is creating one for you.1357 In addition you can pass `spec=True` or `spec_set=True`, which causes1358 patch to pass in the object being mocked as the spec/spec_set object.1359 `new_callable` allows you to specify a different class, or callable object,1360 that will be called to create the `new` object. By default `AsyncMock` is1361 used for async functions and `MagicMock` for the rest.1362 A more powerful form of `spec` is `autospec`. If you set `autospec=True`1363 then the mock will be created with a spec from the object being replaced.1364 All attributes of the mock will also have the spec of the corresponding1365 attribute of the object being replaced. Methods and functions being1366 mocked will have their arguments checked and will raise a `TypeError` if1367 they are called with the wrong signature. For mocks replacing a class,1368 their return value (the 'instance') will have the same spec as the class.1369 Instead of `autospec=True` you can pass `autospec=some_object` to use an1370 arbitrary object as the spec instead of the one being replaced.1371 By default `patch` will fail to replace attributes that don't exist. If1372 you pass in `create=True`, and the attribute doesn't exist, patch will1373 create the attribute for you when the patched function is called, and1374 delete it again afterwards. This is useful for writing tests against1375 attributes that your production code creates at runtime. It is off by1376 default because it can be dangerous. With it switched on you can write1377 passing tests against APIs that don't actually exist!1378 Patch can be used as a `TestCase` class decorator. It works by1379 decorating each test method in the class. This reduces the boilerplate1380 code when your test methods share a common patchings set. `patch` finds1381 tests by looking for method names that start with `patch.TEST_PREFIX`.1382 By default this is `test`, which matches the way `unittest` finds tests.1383 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.1384 Patch can be used as a context manager, with the with statement. Here the1385 patching applies to the indented block after the with statement. If you1386 use "as" then the patched object will be bound to the name after the1387 "as"; very useful if `patch` is creating a mock object for you.1388 `patch` takes arbitrary keyword arguments. These will be passed to1389 `AsyncMock` if the patched object is asynchronous, to `MagicMock`1390 otherwise or to `new_callable` if specified.1391 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are1392 available for alternate use-cases.1393 """1394 getter, attribute = _get_target(target)1395 return _patch(1396 getter, attribute, new, spec, create,1397 spec_set, autospec, new_callable, kwargs1398 )1399class _patch_dict(object):1400 """1401 Patch a dictionary, or dictionary like object, and restore the dictionary1402 to its original state after the test.1403 `in_dict` can be a dictionary or a mapping like container. If it is a1404 mapping then it must at least support getting, setting and deleting items1405 plus iterating over keys.1406 `in_dict` can also be a string specifying the name of the dictionary, which1407 will then be fetched by importing it.1408 `values` can be a dictionary of values to set in the dictionary. `values`1409 can also be an iterable of `(key, value)` pairs.1410 If `clear` is True then the dictionary will be cleared before the new1411 values are set.1412 `patch.dict` can also be called with arbitrary keyword arguments to set1413 values in the dictionary::1414 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):1415 ...1416 `patch.dict` can be used as a context manager, decorator or class1417 decorator. When used as a class decorator `patch.dict` honours1418 `patch.TEST_PREFIX` for choosing which methods to wrap.1419 """1420 def __init__(self, in_dict, values=(), clear=False, **kwargs):1421 self.in_dict = in_dict1422 # support any argument supported by dict(...) constructor1423 self.values = dict(values)1424 self.values.update(kwargs)1425 self.clear = clear1426 self._original = None1427 def __call__(self, f):1428 if isinstance(f, type):1429 return self.decorate_class(f)1430 @wraps(f)1431 def _inner(*args, **kw):1432 self._patch_dict()1433 try:1434 return f(*args, **kw)1435 finally:1436 self._unpatch_dict()1437 return _inner1438 def decorate_class(self, klass):1439 for attr in dir(klass):1440 attr_value = getattr(klass, attr)1441 if (attr.startswith(patch.TEST_PREFIX) and1442 hasattr(attr_value, "__call__")):1443 decorator = _patch_dict(self.in_dict, self.values, self.clear)1444 decorated = decorator(attr_value)1445 setattr(klass, attr, decorated)1446 return klass1447 def __enter__(self):1448 """Patch the dict."""1449 self._patch_dict()1450 return self.in_dict1451 def _patch_dict(self):1452 values = self.values1453 if isinstance(self.in_dict, str):1454 self.in_dict = _importer(self.in_dict)1455 in_dict = self.in_dict1456 clear = self.clear1457 try:1458 original = in_dict.copy()1459 except AttributeError:1460 # dict like object with no copy method1461 # must support iteration over keys1462 original = {}1463 for key in in_dict:1464 original[key] = in_dict[key]1465 self._original = original1466 if clear:1467 _clear_dict(in_dict)1468 try:1469 in_dict.update(values)1470 except AttributeError:1471 # dict like object with no update method1472 for key in values:1473 in_dict[key] = values[key]1474 def _unpatch_dict(self):1475 in_dict = self.in_dict1476 original = self._original1477 _clear_dict(in_dict)1478 try:1479 in_dict.update(original)1480 except AttributeError:1481 for key in original:1482 in_dict[key] = original[key]1483 def __exit__(self, *args):1484 """Unpatch the dict."""1485 if self._original is not None:1486 self._unpatch_dict()1487 return False1488 def start(self):1489 """Activate a patch, returning any created mock."""1490 result = self.__enter__()1491 _patch._active_patches.append(self)1492 return result1493 def stop(self):1494 """Stop an active patch."""1495 try:1496 _patch._active_patches.remove(self)1497 except ValueError:1498 # If the patch hasn't been started this will fail1499 return None1500 return self.__exit__(None, None, None)1501def _clear_dict(in_dict):1502 try:1503 in_dict.clear()1504 except AttributeError:1505 keys = list(in_dict)1506 for key in keys:1507 del in_dict[key]1508def _patch_stopall():1509 """Stop all active patches. LIFO to unroll nested patches."""1510 for patch in reversed(_patch._active_patches):1511 patch.stop()1512patch.object = _patch_object1513patch.dict = _patch_dict1514patch.multiple = _patch_multiple1515patch.stopall = _patch_stopall1516patch.TEST_PREFIX = 'test'1517magic_methods = (1518 "lt le gt ge eq ne "1519 "getitem setitem delitem "1520 "len contains iter "1521 "hash str sizeof "1522 "enter exit "1523 # we added divmod and rdivmod here instead of numerics1524 # because there is no idivmod1525 "divmod rdivmod neg pos abs invert "1526 "complex int float index "1527 "round trunc floor ceil "1528 "bool next "1529 "fspath "1530 "aiter "1531)1532numerics = (1533 "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv"1534)1535inplace = ' '.join('i%s' % n for n in numerics.split())1536right = ' '.join('r%s' % n for n in numerics.split())1537# not including __prepare__, __instancecheck__, __subclasscheck__1538# (as they are metaclass methods)1539# __del__ is not supported at all as it causes problems if it exists1540_non_defaults = {1541 '__get__', '__set__', '__delete__', '__reversed__', '__missing__',1542 '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__',1543 '__getstate__', '__setstate__', '__getformat__', '__setformat__',1544 '__repr__', '__dir__', '__subclasses__', '__format__',1545 '__getnewargs_ex__',1546}1547def _get_method(name, func):1548 "Turns a callable object (like a mock) into a real function"1549 def method(self, /, *args, **kw):1550 return func(self, *args, **kw)1551 method.__name__ = name1552 return method1553_magics = {1554 '__%s__' % method for method in1555 ' '.join([magic_methods, numerics, inplace, right]).split()1556}1557# Magic methods used for async `with` statements1558_async_method_magics = {"__aenter__", "__aexit__", "__anext__"}1559# Magic methods that are only used with async calls but are synchronous functions themselves1560_sync_async_magics = {"__aiter__"}1561_async_magics = _async_method_magics | _sync_async_magics1562_all_sync_magics = _magics | _non_defaults1563_all_magics = _all_sync_magics | _async_magics1564_unsupported_magics = {1565 '__getattr__', '__setattr__',1566 '__init__', '__new__', '__prepare__',1567 '__instancecheck__', '__subclasscheck__',1568 '__del__'1569}1570_calculate_return_value = {1571 '__hash__': lambda self: object.__hash__(self),1572 '__str__': lambda self: object.__str__(self),1573 '__sizeof__': lambda self: object.__sizeof__(self),1574 '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}",1575}1576_return_values = {1577 '__lt__': NotImplemented,1578 '__gt__': NotImplemented,1579 '__le__': NotImplemented,1580 '__ge__': NotImplemented,1581 '__int__': 1,1582 '__contains__': False,1583 '__len__': 0,1584 '__exit__': False,1585 '__complex__': 1j,1586 '__float__': 1.0,1587 '__bool__': True,1588 '__index__': 1,1589 '__aexit__': False,1590}1591def _get_eq(self):1592 def __eq__(other):1593 ret_val = self.__eq__._mock_return_value1594 if ret_val is not DEFAULT:1595 return ret_val1596 if self is other:1597 return True1598 return NotImplemented1599 return __eq__1600def _get_ne(self):1601 def __ne__(other):1602 if self.__ne__._mock_return_value is not DEFAULT:1603 return DEFAULT1604 if self is other:1605 return False1606 return NotImplemented1607 return __ne__1608def _get_iter(self):1609 def __iter__():1610 ret_val = self.__iter__._mock_return_value1611 if ret_val is DEFAULT:1612 return iter([])1613 # if ret_val was already an iterator, then calling iter on it should1614 # return the iterator unchanged1615 return iter(ret_val)1616 return __iter__1617def _get_async_iter(self):1618 def __aiter__():1619 ret_val = self.__aiter__._mock_return_value1620 if ret_val is DEFAULT:1621 return _AsyncIterator(iter([]))1622 return _AsyncIterator(iter(ret_val))1623 return __aiter__1624_side_effect_methods = {1625 '__eq__': _get_eq,1626 '__ne__': _get_ne,1627 '__iter__': _get_iter,1628 '__aiter__': _get_async_iter1629}1630def _set_return_value(mock, method, name):1631 fixed = _return_values.get(name, DEFAULT)1632 if fixed is not DEFAULT:1633 method.return_value = fixed1634 return1635 return_calculator = _calculate_return_value.get(name)1636 if return_calculator is not None:1637 return_value = return_calculator(mock)1638 method.return_value = return_value1639 return1640 side_effector = _side_effect_methods.get(name)1641 if side_effector is not None:1642 method.side_effect = side_effector(mock)1643class MagicMixin(Base):1644 def __init__(self, /, *args, **kw):1645 self._mock_set_magics() # make magic work for kwargs in init1646 _safe_super(MagicMixin, self).__init__(*args, **kw)1647 self._mock_set_magics() # fix magic broken by upper level init1648 def _mock_set_magics(self):1649 orig_magics = _magics | _async_method_magics1650 these_magics = orig_magics1651 if getattr(self, "_mock_methods", None) is not None:1652 these_magics = orig_magics.intersection(self._mock_methods)1653 remove_magics = set()1654 remove_magics = orig_magics - these_magics1655 for entry in remove_magics:1656 if entry in type(self).__dict__:1657 # remove unneeded magic methods1658 delattr(self, entry)1659 # don't overwrite existing attributes if called a second time1660 these_magics = these_magics - set(type(self).__dict__)1661 _type = type(self)1662 for entry in these_magics:1663 setattr(_type, entry, MagicProxy(entry, self))1664class NonCallableMagicMock(MagicMixin, NonCallableMock):1665 """A version of `MagicMock` that isn't callable."""1666 def mock_add_spec(self, spec, spec_set=False):1667 """Add a spec to a mock. `spec` can either be an object or a1668 list of strings. Only attributes on the `spec` can be fetched as1669 attributes from the mock.1670 If `spec_set` is True then only attributes on the spec can be set."""1671 self._mock_add_spec(spec, spec_set)1672 self._mock_set_magics()1673class AsyncMagicMixin(MagicMixin):1674 def __init__(self, /, *args, **kw):1675 self._mock_set_magics() # make magic work for kwargs in init1676 _safe_super(AsyncMagicMixin, self).__init__(*args, **kw)1677 self._mock_set_magics() # fix magic broken by upper level init1678class MagicMock(MagicMixin, Mock):1679 """1680 MagicMock is a subclass of Mock with default implementations1681 of most of the magic methods. You can use MagicMock without having to1682 configure the magic methods yourself.1683 If you use the `spec` or `spec_set` arguments then *only* magic1684 methods that exist in the spec will be created.1685 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.1686 """1687 def mock_add_spec(self, spec, spec_set=False):1688 """Add a spec to a mock. `spec` can either be an object or a1689 list of strings. Only attributes on the `spec` can be fetched as1690 attributes from the mock.1691 If `spec_set` is True then only attributes on the spec can be set."""1692 self._mock_add_spec(spec, spec_set)1693 self._mock_set_magics()1694class MagicProxy(Base):1695 def __init__(self, name, parent):1696 self.name = name1697 self.parent = parent1698 def create_mock(self):1699 entry = self.name1700 parent = self.parent1701 m = parent._get_child_mock(name=entry, _new_name=entry,1702 _new_parent=parent)1703 setattr(parent, entry, m)1704 _set_return_value(parent, m, entry)1705 return m1706 def __get__(self, obj, _type=None):1707 return self.create_mock()1708class AsyncMockMixin(Base):1709 await_count = _delegating_property('await_count')1710 await_args = _delegating_property('await_args')1711 await_args_list = _delegating_property('await_args_list')1712 def __init__(self, /, *args, **kwargs):1713 super().__init__(*args, **kwargs)1714 # iscoroutinefunction() checks _is_coroutine property to say if an1715 # object is a coroutine. Without this check it looks to see if it is a1716 # function/method, which in this case it is not (since it is an1717 # AsyncMock).1718 # It is set through __dict__ because when spec_set is True, this1719 # attribute is likely undefined.1720 self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine1721 self.__dict__['_mock_await_count'] = 01722 self.__dict__['_mock_await_args'] = None1723 self.__dict__['_mock_await_args_list'] = _CallList()1724 code_mock = NonCallableMock(spec_set=CodeType)1725 code_mock.co_flags = inspect.CO_COROUTINE...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful