How to use _format_call_signature method in autotest

Best Python code snippet using autotest_python

_mock_backport.py

Source:_mock_backport.py Github

copy

Full Screen

...576 del self._mock_children[name]577 self._mock_children[name] = _deleted578 def _format_mock_call_signature(self, args, kwargs):579 name = self._mock_name or 'mock'580 return _format_call_signature(name, args, kwargs)581 def _format_mock_failure_message(self, args, kwargs):582 message = 'Expected call: %s\nActual call: %s'583 expected_string = self._format_mock_call_signature(args, kwargs)584 call_args = self.call_args585 if len(call_args) == 3:586 call_args = call_args[1:]587 actual_string = self._format_mock_call_signature(*call_args)588 return message % (expected_string, actual_string)589 def _call_matcher(self, _call):590 """591 Given a call (or simply an (args, kwargs) tuple), return a592 comparison key suitable for matching with other calls.593 This is a best effort method which relies on the spec's signature,594 if available, or falls back on the arguments themselves.595 """596 sig = self._spec_signature597 if sig is not None:598 if len(_call) == 2:599 name = ''600 args, kwargs = _call601 else:602 name, args, kwargs = _call603 try:604 return name, sig.bind(*args, **kwargs)605 except TypeError as e:606 return e.with_traceback(None)607 else:608 return _call609 def assert_not_called(_mock_self):610 """assert that the mock was never called.611 """612 self = _mock_self613 if self.call_count != 0:614 msg = ("Expected '%s' to not have been called. Called %s times." %615 (self._mock_name or 'mock', self.call_count))616 raise AssertionError(msg)617 def assert_called_with(_mock_self, *args, **kwargs):618 """assert that the mock was called with the specified arguments.619 Raises an AssertionError if the args and keyword args passed in are620 different to the last call to the mock."""621 self = _mock_self622 if self.call_args is None:623 expected = self._format_mock_call_signature(args, kwargs)624 raise AssertionError('Expected call: %s\nNot called' % (expected,))625 def _error_message():626 msg = self._format_mock_failure_message(args, kwargs)627 return msg628 expected = self._call_matcher((args, kwargs))629 actual = self._call_matcher(self.call_args)630 if expected != actual:631 raise AssertionError(_error_message())632 def assert_called_once_with(_mock_self, *args, **kwargs):633 """assert that the mock was called exactly once and with the specified634 arguments."""635 self = _mock_self636 if not self.call_count == 1:637 msg = ("Expected '%s' to be called once. Called %s times." %638 (self._mock_name or 'mock', self.call_count))639 raise AssertionError(msg)640 return self.assert_called_with(*args, **kwargs)641 def assert_has_calls(self, calls, any_order=False):642 """assert the mock has been called with the specified calls.643 The `mock_calls` list is checked for the calls.644 If `any_order` is False (the default) then the calls must be645 sequential. There can be extra calls before or after the646 specified calls.647 If `any_order` is True then the calls can be in any order, but648 they must all appear in `mock_calls`."""649 expected = [self._call_matcher(c) for c in calls]650 all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)651 if not any_order:652 if expected not in all_calls:653 raise AssertionError(654 'Calls not found.\nExpected: %r\n'655 'Actual: %r' % (calls, self.mock_calls)656 )657 return658 all_calls = list(all_calls)659 not_found = []660 for kall in expected:661 try:662 all_calls.remove(kall)663 except ValueError:664 not_found.append(kall)665 if not_found:666 raise AssertionError(667 '%r not all found in call list' % (tuple(not_found),)668 )669 def assert_any_call(self, *args, **kwargs):670 """assert the mock has been called with the specified arguments.671 The assert passes if the mock has *ever* been called, unlike672 `assert_called_with` and `assert_called_once_with` that only pass if673 the call is the most recent one."""674 expected = self._call_matcher((args, kwargs))675 actual = [self._call_matcher(c) for c in self.call_args_list]676 if expected not in actual:677 expected_string = self._format_mock_call_signature(args, kwargs)678 raise AssertionError(679 '%s call not found' % expected_string680 )681 def _get_child_mock(self, **kw):682 """Create the child mocks for attributes and return value.683 By default child mocks will be the same type as the parent.684 Subclasses of Mock may want to override this to customize the way685 child mocks are made.686 For non-callable mocks the callable variant will be used (rather than687 any custom subclass)."""688 _type = type(self)689 if not issubclass(_type, CallableMixin):690 if issubclass(_type, NonCallableMagicMock):691 klass = MagicMock692 elif issubclass(_type, NonCallableMock) :693 klass = Mock694 else:695 klass = _type.__mro__[1]696 return klass(**kw)697def _try_iter(obj):698 if obj is None:699 return obj700 if _is_exception(obj):701 return obj702 if _callable(obj):703 return obj704 try:705 return iter(obj)706 except TypeError:707 # XXXX backwards compatibility708 # but this will blow up on first call - so maybe we should fail early?709 return obj710class CallableMixin(Base):711 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,712 wraps=None, name=None, spec_set=None, parent=None,713 _spec_state=None, _new_name='', _new_parent=None, **kwargs):714 self.__dict__['_mock_return_value'] = return_value715 _safe_super(CallableMixin, self).__init__(716 spec, wraps, name, spec_set, parent,717 _spec_state, _new_name, _new_parent, **kwargs718 )719 self.side_effect = side_effect720 def _mock_check_sig(self, *args, **kwargs):721 # stub method that can be replaced with one with a specific signature722 pass723 def __call__(_mock_self, *args, **kwargs):724 # can't use self in-case a function / method we are mocking uses self725 # in the signature726 _mock_self._mock_check_sig(*args, **kwargs)727 return _mock_self._mock_call(*args, **kwargs)728 def _mock_call(_mock_self, *args, **kwargs):729 self = _mock_self730 self.called = True731 self.call_count += 1732 _new_name = self._mock_new_name733 _new_parent = self._mock_new_parent734 _call = _Call((args, kwargs), two=True)735 self.call_args = _call736 self.call_args_list.append(_call)737 self.mock_calls.append(_Call(('', args, kwargs)))738 seen = set()739 skip_next_dot = _new_name == '()'740 do_method_calls = self._mock_parent is not None741 name = self._mock_name742 while _new_parent is not None:743 this_mock_call = _Call((_new_name, args, kwargs))744 if _new_parent._mock_new_name:745 dot = '.'746 if skip_next_dot:747 dot = ''748 skip_next_dot = False749 if _new_parent._mock_new_name == '()':750 skip_next_dot = True751 _new_name = _new_parent._mock_new_name + dot + _new_name752 if do_method_calls:753 if _new_name == name:754 this_method_call = this_mock_call755 else:756 this_method_call = _Call((name, args, kwargs))757 _new_parent.method_calls.append(this_method_call)758 do_method_calls = _new_parent._mock_parent is not None759 if do_method_calls:760 name = _new_parent._mock_name + '.' + name761 _new_parent.mock_calls.append(this_mock_call)762 _new_parent = _new_parent._mock_new_parent763 # use ids here so as not to call __hash__ on the mocks764 _new_parent_id = id(_new_parent)765 if _new_parent_id in seen:766 break767 seen.add(_new_parent_id)768 ret_val = DEFAULT769 effect = self.side_effect770 if effect is not None:771 if _is_exception(effect):772 raise effect773 if not _callable(effect):774 result = next(effect)775 if _is_exception(result):776 raise result777 if result is DEFAULT:778 result = self.return_value779 return result780 ret_val = effect(*args, **kwargs)781 if (self._mock_wraps is not None and782 self._mock_return_value is DEFAULT):783 return self._mock_wraps(*args, **kwargs)784 if ret_val is DEFAULT:785 ret_val = self.return_value786 return ret_val787class Mock(CallableMixin, NonCallableMock):788 """789 Create a new `Mock` object. `Mock` takes several optional arguments790 that specify the behaviour of the Mock object:791 * `spec`: This can be either a list of strings or an existing object (a792 class or instance) that acts as the specification for the mock object. If793 you pass in an object then a list of strings is formed by calling dir on794 the object (excluding unsupported magic attributes and methods). Accessing795 any attribute not in this list will raise an `AttributeError`.796 If `spec` is an object (rather than a list of strings) then797 `mock.__class__` returns the class of the spec object. This allows mocks798 to pass `isinstance` tests.799 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*800 or get an attribute on the mock that isn't on the object passed as801 `spec_set` will raise an `AttributeError`.802 * `side_effect`: A function to be called whenever the Mock is called. See803 the `side_effect` attribute. Useful for raising exceptions or804 dynamically changing return values. The function is called with the same805 arguments as the mock, and unless it returns `DEFAULT`, the return806 value of this function is used as the return value.807 If `side_effect` is an iterable then each call to the mock will return808 the next value from the iterable. If any of the members of the iterable809 are exceptions they will be raised instead of returned.810 * `return_value`: The value returned when the mock is called. By default811 this is a new Mock (created on first access). See the812 `return_value` attribute.813 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then814 calling the Mock will pass the call through to the wrapped object815 (returning the real result). Attribute access on the mock will return a816 Mock object that wraps the corresponding attribute of the wrapped object817 (so attempting to access an attribute that doesn't exist will raise an818 `AttributeError`).819 If the mock has an explicit `return_value` set then calls are not passed820 to the wrapped object and the `return_value` is returned instead.821 * `name`: If the mock has a name then it will be used in the repr of the822 mock. This can be useful for debugging. The name is propagated to child823 mocks.824 Mocks can also be called with arbitrary keyword arguments. These will be825 used to set attributes on the mock after it is created.826 """827def _dot_lookup(thing, comp, import_path):828 try:829 return getattr(thing, comp)830 except AttributeError:831 __import__(import_path)832 return getattr(thing, comp)833def _importer(target):834 components = target.split('.')835 import_path = components.pop(0)836 thing = __import__(import_path)837 for comp in components:838 import_path += ".%s" % comp839 thing = _dot_lookup(thing, comp, import_path)840 return thing841def _is_started(patcher):842 # XXXX horrible843 return hasattr(patcher, 'is_local')844class _patch(object):845 attribute_name = None846 _active_patches = []847 def __init__(848 self, getter, attribute, new, spec, create,849 spec_set, autospec, new_callable, kwargs850 ):851 if new_callable is not None:852 if new is not DEFAULT:853 raise ValueError(854 "Cannot use 'new' and 'new_callable' together"855 )856 if autospec is not None:857 raise ValueError(858 "Cannot use 'autospec' and 'new_callable' together"859 )860 self.getter = getter861 self.attribute = attribute862 self.new = new863 self.new_callable = new_callable864 self.spec = spec865 self.create = create866 self.has_local = False867 self.spec_set = spec_set868 self.autospec = autospec869 self.kwargs = kwargs870 self.additional_patchers = []871 def copy(self):872 patcher = _patch(873 self.getter, self.attribute, self.new, self.spec,874 self.create, self.spec_set,875 self.autospec, self.new_callable, self.kwargs876 )877 patcher.attribute_name = self.attribute_name878 patcher.additional_patchers = [879 p.copy() for p in self.additional_patchers880 ]881 return patcher882 def __call__(self, func):883 if isinstance(func, type):884 return self.decorate_class(func)885 return self.decorate_callable(func)886 def decorate_class(self, klass):887 for attr in dir(klass):888 if not attr.startswith(patch.TEST_PREFIX):889 continue890 attr_value = getattr(klass, attr)891 if not hasattr(attr_value, "__call__"):892 continue893 patcher = self.copy()894 setattr(klass, attr, patcher(attr_value))895 return klass896 def decorate_callable(self, func):897 if hasattr(func, 'patchings'):898 func.patchings.append(self)899 return func900 @wraps(func)901 def patched(*args, **keywargs):902 extra_args = []903 entered_patchers = []904 exc_info = tuple()905 try:906 for patching in patched.patchings:907 arg = patching.__enter__()908 entered_patchers.append(patching)909 if patching.attribute_name is not None:910 keywargs.update(arg)911 elif patching.new is DEFAULT:912 extra_args.append(arg)913 args += tuple(extra_args)914 return func(*args, **keywargs)915 except:916 if (patching not in entered_patchers and917 _is_started(patching)):918 # the patcher may have been started, but an exception919 # raised whilst entering one of its additional_patchers920 entered_patchers.append(patching)921 # Pass the exception to __exit__922 exc_info = sys.exc_info()923 # re-raise the exception924 raise925 finally:926 for patching in reversed(entered_patchers):927 patching.__exit__(*exc_info)928 patched.patchings = [self]929 return patched930 def get_original(self):931 target = self.getter()932 name = self.attribute933 original = DEFAULT934 local = False935 try:936 original = target.__dict__[name]937 except (AttributeError, KeyError):938 original = getattr(target, name, DEFAULT)939 else:940 local = True941 if name in _builtins and isinstance(target, ModuleType):942 self.create = True943 if not self.create and original is DEFAULT:944 raise AttributeError(945 "%s does not have the attribute %r" % (target, name)946 )947 return original, local948 def __enter__(self):949 """Perform the patch."""950 new, spec, spec_set = self.new, self.spec, self.spec_set951 autospec, kwargs = self.autospec, self.kwargs952 new_callable = self.new_callable953 self.target = self.getter()954 # normalise False to None955 if spec is False:956 spec = None957 if spec_set is False:958 spec_set = None959 if autospec is False:960 autospec = None961 if spec is not None and autospec is not None:962 raise TypeError("Can't specify spec and autospec")963 if ((spec is not None or autospec is not None) and964 spec_set not in (True, None)):965 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")966 original, local = self.get_original()967 if new is DEFAULT and autospec is None:968 inherit = False969 if spec is True:970 # set spec to the object we are replacing971 spec = original972 if spec_set is True:973 spec_set = original974 spec = None975 elif spec is not None:976 if spec_set is True:977 spec_set = spec978 spec = None979 elif spec_set is True:980 spec_set = original981 if spec is not None or spec_set is not None:982 if original is DEFAULT:983 raise TypeError("Can't use 'spec' with create=True")984 if isinstance(original, type):985 # If we're patching out a class and there is a spec986 inherit = True987 Klass = MagicMock988 _kwargs = {}989 if new_callable is not None:990 Klass = new_callable991 elif spec is not None or spec_set is not None:992 this_spec = spec993 if spec_set is not None:994 this_spec = spec_set995 if _is_list(this_spec):996 not_callable = '__call__' not in this_spec997 else:998 not_callable = not callable(this_spec)999 if not_callable:1000 Klass = NonCallableMagicMock1001 if spec is not None:1002 _kwargs['spec'] = spec1003 if spec_set is not None:1004 _kwargs['spec_set'] = spec_set1005 # add a name to mocks1006 if (isinstance(Klass, type) and1007 issubclass(Klass, NonCallableMock) and self.attribute):1008 _kwargs['name'] = self.attribute1009 _kwargs.update(kwargs)1010 new = Klass(**_kwargs)1011 if inherit and _is_instance_mock(new):1012 # we can only tell if the instance should be callable if the1013 # spec is not a list1014 this_spec = spec1015 if spec_set is not None:1016 this_spec = spec_set1017 if (not _is_list(this_spec) and not1018 _instance_callable(this_spec)):1019 Klass = NonCallableMagicMock1020 _kwargs.pop('name')1021 new.return_value = Klass(_new_parent=new, _new_name='()',1022 **_kwargs)1023 elif autospec is not None:1024 # spec is ignored, new *must* be default, spec_set is treated1025 # as a boolean. Should we check spec is not None and that spec_set1026 # is a bool?1027 if new is not DEFAULT:1028 raise TypeError(1029 "autospec creates the mock for you. Can't specify "1030 "autospec and new."1031 )1032 if original is DEFAULT:1033 raise TypeError("Can't use 'autospec' with create=True")1034 spec_set = bool(spec_set)1035 if autospec is True:1036 autospec = original1037 new = create_autospec(autospec, spec_set=spec_set,1038 _name=self.attribute, **kwargs)1039 elif kwargs:1040 # can't set keyword args when we aren't creating the mock1041 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)1042 raise TypeError("Can't pass kwargs to a mock we aren't creating")1043 new_attr = new1044 self.temp_original = original1045 self.is_local = local1046 setattr(self.target, self.attribute, new_attr)1047 if self.attribute_name is not None:1048 extra_args = {}1049 if self.new is DEFAULT:1050 extra_args[self.attribute_name] = new1051 for patching in self.additional_patchers:1052 arg = patching.__enter__()1053 if patching.new is DEFAULT:1054 extra_args.update(arg)1055 return extra_args1056 return new1057 def __exit__(self, *exc_info):1058 """Undo the patch."""1059 if not _is_started(self):1060 raise RuntimeError('stop called on unstarted patcher')1061 if self.is_local and self.temp_original is not DEFAULT:1062 setattr(self.target, self.attribute, self.temp_original)1063 else:1064 delattr(self.target, self.attribute)1065 if not self.create and not hasattr(self.target, self.attribute):1066 # needed for proxy objects like django settings1067 setattr(self.target, self.attribute, self.temp_original)1068 del self.temp_original1069 del self.is_local1070 del self.target1071 for patcher in reversed(self.additional_patchers):1072 if _is_started(patcher):1073 patcher.__exit__(*exc_info)1074 def start(self):1075 """Activate a patch, returning any created mock."""1076 result = self.__enter__()1077 self._active_patches.append(self)1078 return result1079 def stop(self):1080 """Stop an active patch."""1081 try:1082 self._active_patches.remove(self)1083 except ValueError:1084 # If the patch hasn't been started this will fail1085 pass1086 return self.__exit__()1087def _get_target(target):1088 try:1089 target, attribute = target.rsplit('.', 1)1090 except (TypeError, ValueError):1091 raise TypeError("Need a valid target to patch. You supplied: %r" %1092 (target,))1093 getter = lambda: _importer(target)1094 return getter, attribute1095def _patch_object(1096 target, attribute, new=DEFAULT, spec=None,1097 create=False, spec_set=None, autospec=None,1098 new_callable=None, **kwargs1099 ):1100 """1101 patch the named member (`attribute`) on an object (`target`) with a mock1102 object.1103 `patch.object` can be used as a decorator, class decorator or a context1104 manager. Arguments `new`, `spec`, `create`, `spec_set`,1105 `autospec` and `new_callable` have the same meaning as for `patch`. Like1106 `patch`, `patch.object` takes arbitrary keyword arguments for configuring1107 the mock object it creates.1108 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`1109 for choosing which methods to wrap.1110 """1111 getter = lambda: target1112 return _patch(1113 getter, attribute, new, spec, create,1114 spec_set, autospec, new_callable, kwargs1115 )1116def _patch_multiple(target, spec=None, create=False, spec_set=None,1117 autospec=None, new_callable=None, **kwargs):1118 """Perform multiple patches in a single call. It takes the object to be1119 patched (either as an object or a string to fetch the object by importing)1120 and keyword arguments for the patches::1121 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):1122 ...1123 Use `DEFAULT` as the value if you want `patch.multiple` to create1124 mocks for you. In this case the created mocks are passed into a decorated1125 function by keyword, and a dictionary is returned when `patch.multiple` is1126 used as a context manager.1127 `patch.multiple` can be used as a decorator, class decorator or a context1128 manager. The arguments `spec`, `spec_set`, `create`,1129 `autospec` and `new_callable` have the same meaning as for `patch`. These1130 arguments will be applied to *all* patches done by `patch.multiple`.1131 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`1132 for choosing which methods to wrap.1133 """1134 if type(target) is str:1135 getter = lambda: _importer(target)1136 else:1137 getter = lambda: target1138 if not kwargs:1139 raise ValueError(1140 'Must supply at least one keyword argument with patch.multiple'1141 )1142 # need to wrap in a list for python 3, where items is a view1143 items = list(kwargs.items())1144 attribute, new = items[0]1145 patcher = _patch(1146 getter, attribute, new, spec, create, spec_set,1147 autospec, new_callable, {}1148 )1149 patcher.attribute_name = attribute1150 for attribute, new in items[1:]:1151 this_patcher = _patch(1152 getter, attribute, new, spec, create, spec_set,1153 autospec, new_callable, {}1154 )1155 this_patcher.attribute_name = attribute1156 patcher.additional_patchers.append(this_patcher)1157 return patcher1158def patch(1159 target, new=DEFAULT, spec=None, create=False,1160 spec_set=None, autospec=None, new_callable=None, **kwargs1161 ):1162 """1163 `patch` acts as a function decorator, class decorator or a context1164 manager. Inside the body of the function or with statement, the `target`1165 is patched with a `new` object. When the function/with statement exits1166 the patch is undone.1167 If `new` is omitted, then the target is replaced with a1168 `MagicMock`. If `patch` is used as a decorator and `new` is1169 omitted, the created mock is passed in as an extra argument to the1170 decorated function. If `patch` is used as a context manager the created1171 mock is returned by the context manager.1172 `target` should be a string in the form `'package.module.ClassName'`. The1173 `target` is imported and the specified object replaced with the `new`1174 object, so the `target` must be importable from the environment you are1175 calling `patch` from. The target is imported when the decorated function1176 is executed, not at decoration time.1177 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`1178 if patch is creating one for you.1179 In addition you can pass `spec=True` or `spec_set=True`, which causes1180 patch to pass in the object being mocked as the spec/spec_set object.1181 `new_callable` allows you to specify a different class, or callable object,1182 that will be called to create the `new` object. By default `MagicMock` is1183 used.1184 A more powerful form of `spec` is `autospec`. If you set `autospec=True`1185 then the mock with be created with a spec from the object being replaced.1186 All attributes of the mock will also have the spec of the corresponding1187 attribute of the object being replaced. Methods and functions being1188 mocked will have their arguments checked and will raise a `TypeError` if1189 they are called with the wrong signature. For mocks replacing a class,1190 their return value (the 'instance') will have the same spec as the class.1191 Instead of `autospec=True` you can pass `autospec=some_object` to use an1192 arbitrary object as the spec instead of the one being replaced.1193 By default `patch` will fail to replace attributes that don't exist. If1194 you pass in `create=True`, and the attribute doesn't exist, patch will1195 create the attribute for you when the patched function is called, and1196 delete it again afterwards. This is useful for writing tests against1197 attributes that your production code creates at runtime. It is off by1198 default because it can be dangerous. With it switched on you can write1199 passing tests against APIs that don't actually exist!1200 Patch can be used as a `TestCase` class decorator. It works by1201 decorating each test method in the class. This reduces the boilerplate1202 code when your test methods share a common patchings set. `patch` finds1203 tests by looking for method names that start with `patch.TEST_PREFIX`.1204 By default this is `test`, which matches the way `unittest` finds tests.1205 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.1206 Patch can be used as a context manager, with the with statement. Here the1207 patching applies to the indented block after the with statement. If you1208 use "as" then the patched object will be bound to the name after the1209 "as"; very useful if `patch` is creating a mock object for you.1210 `patch` takes arbitrary keyword arguments. These will be passed to1211 the `Mock` (or `new_callable`) on construction.1212 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are1213 available for alternate use-cases.1214 """1215 getter, attribute = _get_target(target)1216 return _patch(1217 getter, attribute, new, spec, create,1218 spec_set, autospec, new_callable, kwargs1219 )1220class _patch_dict(object):1221 """1222 Patch a dictionary, or dictionary like object, and restore the dictionary1223 to its original state after the test.1224 `in_dict` can be a dictionary or a mapping like container. If it is a1225 mapping then it must at least support getting, setting and deleting items1226 plus iterating over keys.1227 `in_dict` can also be a string specifying the name of the dictionary, which1228 will then be fetched by importing it.1229 `values` can be a dictionary of values to set in the dictionary. `values`1230 can also be an iterable of `(key, value)` pairs.1231 If `clear` is True then the dictionary will be cleared before the new1232 values are set.1233 `patch.dict` can also be called with arbitrary keyword arguments to set1234 values in the dictionary::1235 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):1236 ...1237 `patch.dict` can be used as a context manager, decorator or class1238 decorator. When used as a class decorator `patch.dict` honours1239 `patch.TEST_PREFIX` for choosing which methods to wrap.1240 """1241 def __init__(self, in_dict, values=(), clear=False, **kwargs):1242 if isinstance(in_dict, str):1243 in_dict = _importer(in_dict)1244 self.in_dict = in_dict1245 # support any argument supported by dict(...) constructor1246 self.values = dict(values)1247 self.values.update(kwargs)1248 self.clear = clear1249 self._original = None1250 def __call__(self, f):1251 if isinstance(f, type):1252 return self.decorate_class(f)1253 @wraps(f)1254 def _inner(*args, **kw):1255 self._patch_dict()1256 try:1257 return f(*args, **kw)1258 finally:1259 self._unpatch_dict()1260 return _inner1261 def decorate_class(self, klass):1262 for attr in dir(klass):1263 attr_value = getattr(klass, attr)1264 if (attr.startswith(patch.TEST_PREFIX) and1265 hasattr(attr_value, "__call__")):1266 decorator = _patch_dict(self.in_dict, self.values, self.clear)1267 decorated = decorator(attr_value)1268 setattr(klass, attr, decorated)1269 return klass1270 def __enter__(self):1271 """Patch the dict."""1272 self._patch_dict()1273 def _patch_dict(self):1274 values = self.values1275 in_dict = self.in_dict1276 clear = self.clear1277 try:1278 original = in_dict.copy()1279 except AttributeError:1280 # dict like object with no copy method1281 # must support iteration over keys1282 original = {}1283 for key in in_dict:1284 original[key] = in_dict[key]1285 self._original = original1286 if clear:1287 _clear_dict(in_dict)1288 try:1289 in_dict.update(values)1290 except AttributeError:1291 # dict like object with no update method1292 for key in values:1293 in_dict[key] = values[key]1294 def _unpatch_dict(self):1295 in_dict = self.in_dict1296 original = self._original1297 _clear_dict(in_dict)1298 try:1299 in_dict.update(original)1300 except AttributeError:1301 for key in original:1302 in_dict[key] = original[key]1303 def __exit__(self, *args):1304 """Unpatch the dict."""1305 self._unpatch_dict()1306 return False1307 start = __enter__1308 stop = __exit__1309def _clear_dict(in_dict):1310 try:1311 in_dict.clear()1312 except AttributeError:1313 keys = list(in_dict)1314 for key in keys:1315 del in_dict[key]1316def _patch_stopall():1317 """Stop all active patches. LIFO to unroll nested patches."""1318 for patch in reversed(_patch._active_patches):1319 patch.stop()1320patch.object = _patch_object1321patch.dict = _patch_dict1322patch.multiple = _patch_multiple1323patch.stopall = _patch_stopall1324patch.TEST_PREFIX = 'test'1325magic_methods = (1326 "lt le gt ge eq ne "1327 "getitem setitem delitem "1328 "len contains iter "1329 "hash str sizeof "1330 "enter exit "1331 "divmod neg pos abs invert "1332 "complex int float index "1333 "trunc floor ceil "1334 "bool next "1335)1336numerics = (1337 "add sub mul div floordiv mod lshift rshift and xor or pow truediv"1338)1339inplace = ' '.join('i%s' % n for n in numerics.split())1340right = ' '.join('r%s' % n for n in numerics.split())1341# not including __prepare__, __instancecheck__, __subclasscheck__1342# (as they are metaclass methods)1343# __del__ is not supported at all as it causes problems if it exists1344_non_defaults = set('__%s__' % method for method in [1345 'get', 'set', 'delete', 'reversed', 'missing', 'reduce', 'reduce_ex',1346 'getinitargs', 'getnewargs', 'getstate', 'setstate', 'getformat',1347 'setformat', 'repr', 'dir', 'subclasses', 'format',1348])1349def _get_method(name, func):1350 "Turns a callable object (like a mock) into a real function"1351 def method(self, *args, **kw):1352 return func(self, *args, **kw)1353 method.__name__ = name1354 return method1355_magics = set(1356 '__%s__' % method for method in1357 ' '.join([magic_methods, numerics, inplace, right]).split()1358)1359_all_magics = _magics | _non_defaults1360_unsupported_magics = set([1361 '__getattr__', '__setattr__',1362 '__init__', '__new__', '__prepare__'1363 '__instancecheck__', '__subclasscheck__',1364 '__del__'1365])1366_calculate_return_value = {1367 '__hash__': lambda self: object.__hash__(self),1368 '__str__': lambda self: object.__str__(self),1369 '__sizeof__': lambda self: object.__sizeof__(self),1370}1371_return_values = {1372 '__lt__': NotImplemented,1373 '__gt__': NotImplemented,1374 '__le__': NotImplemented,1375 '__ge__': NotImplemented,1376 '__int__': 1,1377 '__contains__': False,1378 '__len__': 0,1379 '__exit__': False,1380 '__complex__': 1j,1381 '__float__': 1.0,1382 '__bool__': True,1383 '__index__': 1,1384}1385def _get_eq(self):1386 def __eq__(other):1387 ret_val = self.__eq__._mock_return_value1388 if ret_val is not DEFAULT:1389 return ret_val1390 return self is other1391 return __eq__1392def _get_ne(self):1393 def __ne__(other):1394 if self.__ne__._mock_return_value is not DEFAULT:1395 return DEFAULT1396 return self is not other1397 return __ne__1398def _get_iter(self):1399 def __iter__():1400 ret_val = self.__iter__._mock_return_value1401 if ret_val is DEFAULT:1402 return iter([])1403 # if ret_val was already an iterator, then calling iter on it should1404 # return the iterator unchanged1405 return iter(ret_val)1406 return __iter__1407_side_effect_methods = {1408 '__eq__': _get_eq,1409 '__ne__': _get_ne,1410 '__iter__': _get_iter,1411}1412def _set_return_value(mock, method, name):1413 fixed = _return_values.get(name, DEFAULT)1414 if fixed is not DEFAULT:1415 method.return_value = fixed1416 return1417 return_calulator = _calculate_return_value.get(name)1418 if return_calulator is not None:1419 try:1420 return_value = return_calulator(mock)1421 except AttributeError:1422 # XXXX why do we return AttributeError here?1423 # set it as a side_effect instead?1424 return_value = AttributeError(name)1425 method.return_value = return_value1426 return1427 side_effector = _side_effect_methods.get(name)1428 if side_effector is not None:1429 method.side_effect = side_effector(mock)1430class MagicMixin(object):1431 def __init__(self, *args, **kw):1432 _safe_super(MagicMixin, self).__init__(*args, **kw)1433 self._mock_set_magics()1434 def _mock_set_magics(self):1435 these_magics = _magics1436 if self._mock_methods is not None:1437 these_magics = _magics.intersection(self._mock_methods)1438 remove_magics = set()1439 remove_magics = _magics - these_magics1440 for entry in remove_magics:1441 if entry in type(self).__dict__:1442 # remove unneeded magic methods1443 delattr(self, entry)1444 # don't overwrite existing attributes if called a second time1445 these_magics = these_magics - set(type(self).__dict__)1446 _type = type(self)1447 for entry in these_magics:1448 setattr(_type, entry, MagicProxy(entry, self))1449class NonCallableMagicMock(MagicMixin, NonCallableMock):1450 """A version of `MagicMock` that isn't callable."""1451 def mock_add_spec(self, spec, spec_set=False):1452 """Add a spec to a mock. `spec` can either be an object or a1453 list of strings. Only attributes on the `spec` can be fetched as1454 attributes from the mock.1455 If `spec_set` is True then only attributes on the spec can be set."""1456 self._mock_add_spec(spec, spec_set)1457 self._mock_set_magics()1458class MagicMock(MagicMixin, Mock):1459 """1460 MagicMock is a subclass of Mock with default implementations1461 of most of the magic methods. You can use MagicMock without having to1462 configure the magic methods yourself.1463 If you use the `spec` or `spec_set` arguments then *only* magic1464 methods that exist in the spec will be created.1465 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.1466 """1467 def mock_add_spec(self, spec, spec_set=False):1468 """Add a spec to a mock. `spec` can either be an object or a1469 list of strings. Only attributes on the `spec` can be fetched as1470 attributes from the mock.1471 If `spec_set` is True then only attributes on the spec can be set."""1472 self._mock_add_spec(spec, spec_set)1473 self._mock_set_magics()1474class MagicProxy(object):1475 def __init__(self, name, parent):1476 self.name = name1477 self.parent = parent1478 def __call__(self, *args, **kwargs):1479 m = self.create_mock()1480 return m(*args, **kwargs)1481 def create_mock(self):1482 entry = self.name1483 parent = self.parent1484 m = parent._get_child_mock(name=entry, _new_name=entry,1485 _new_parent=parent)1486 setattr(parent, entry, m)1487 _set_return_value(parent, m, entry)1488 return m1489 def __get__(self, obj, _type=None):1490 return self.create_mock()1491class _ANY(object):1492 "A helper object that compares equal to everything."1493 __hash__ = object.__hash__1494 def __eq__(self, other):1495 return True1496 def __ne__(self, other):1497 return False1498 def __repr__(self):1499 return '<ANY>'1500ANY = _ANY()1501def _format_call_signature(name, args, kwargs):1502 message = '%s(%%s)' % name1503 formatted_args = ''1504 args_string = ', '.join([repr(arg) for arg in args])1505 kwargs_string = ', '.join([1506 '%s=%r' % (key, value) for key, value in sorted(kwargs.items())1507 ])1508 if args_string:1509 formatted_args = args_string1510 if kwargs_string:1511 if formatted_args:1512 formatted_args += ', '1513 formatted_args += kwargs_string1514 return message % formatted_args1515class _Call(tuple):1516 """1517 A tuple for holding the results of a call to a mock, either in the form1518 `(args, kwargs)` or `(name, args, kwargs)`.1519 If args or kwargs are empty then a call tuple will compare equal to1520 a tuple without those values. This makes comparisons less verbose::1521 _Call(('name', (), {})) == ('name',)1522 _Call(('name', (1,), {})) == ('name', (1,))1523 _Call(((), {'a': 'b'})) == ({'a': 'b'},)1524 The `_Call` object provides a useful shortcut for comparing with call::1525 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)1526 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)1527 If the _Call has no name then it will match any name.1528 """1529 __hash__ = object.__hash__1530 def __new__(cls, value=(), name=None, parent=None, two=False,1531 from_kall=True):1532 name = ''1533 args = ()1534 kwargs = {}1535 _len = len(value)1536 if _len == 3:1537 name, args, kwargs = value1538 elif _len == 2:1539 first, second = value1540 if isinstance(first, str):1541 name = first1542 if isinstance(second, tuple):1543 args = second1544 else:1545 kwargs = second1546 else:1547 args, kwargs = first, second1548 elif _len == 1:1549 value, = value1550 if isinstance(value, str):1551 name = value1552 elif isinstance(value, tuple):1553 args = value1554 else:1555 kwargs = value1556 if two:1557 return tuple.__new__(cls, (args, kwargs))1558 return tuple.__new__(cls, (name, args, kwargs))1559 def __init__(self, value=(), name=None, parent=None, two=False,1560 from_kall=True):1561 self.name = name1562 self.parent = parent1563 self.from_kall = from_kall1564 def __eq__(self, other):1565 if other is ANY:1566 return True1567 try:1568 len_other = len(other)1569 except TypeError:1570 return False1571 self_name = ''1572 if len(self) == 2:1573 self_args, self_kwargs = self1574 else:1575 self_name, self_args, self_kwargs = self1576 other_name = ''1577 if len_other == 0:1578 other_args, other_kwargs = (), {}1579 elif len_other == 3:1580 other_name, other_args, other_kwargs = other1581 elif len_other == 1:1582 value, = other1583 if isinstance(value, tuple):1584 other_args = value1585 other_kwargs = {}1586 elif isinstance(value, str):1587 other_name = value1588 other_args, other_kwargs = (), {}1589 else:1590 other_args = ()1591 other_kwargs = value1592 else:1593 # len 21594 # could be (name, args) or (name, kwargs) or (args, kwargs)1595 first, second = other1596 if isinstance(first, str):1597 other_name = first1598 if isinstance(second, tuple):1599 other_args, other_kwargs = second, {}1600 else:1601 other_args, other_kwargs = (), second1602 else:1603 other_args, other_kwargs = first, second1604 if self_name and other_name != self_name:1605 return False1606 # this order is important for ANY to work!1607 return (other_args, other_kwargs) == (self_args, self_kwargs)1608 def __ne__(self, other):1609 return not self.__eq__(other)1610 def __call__(self, *args, **kwargs):1611 if self.name is None:1612 return _Call(('', args, kwargs), name='()')1613 name = self.name + '()'1614 return _Call((self.name, args, kwargs), name=name, parent=self)1615 def __getattr__(self, attr):1616 if self.name is None:1617 return _Call(name=attr, from_kall=False)1618 name = '%s.%s' % (self.name, attr)1619 return _Call(name=name, parent=self, from_kall=False)1620 def count(self, *args, **kwargs):1621 return self.__getattr__('count')(*args, **kwargs)1622 def index(self, *args, **kwargs):1623 return self.__getattr__('index')(*args, **kwargs)1624 def __repr__(self):1625 if not self.from_kall:1626 name = self.name or 'call'1627 if name.startswith('()'):1628 name = 'call%s' % name1629 return name1630 if len(self) == 2:1631 name = 'call'1632 args, kwargs = self1633 else:1634 name, args, kwargs = self1635 if not name:1636 name = 'call'1637 elif not name.startswith('()'):1638 name = 'call.%s' % name1639 else:1640 name = 'call%s' % name1641 return _format_call_signature(name, args, kwargs)1642 def call_list(self):1643 """For a call object that represents multiple calls, `call_list`1644 returns a list of all the intermediate calls as well as the1645 final call."""1646 vals = []1647 thing = self1648 while thing is not None:1649 if thing.from_kall:1650 vals.append(thing)1651 thing = thing.parent1652 return _CallList(reversed(vals))1653call = _Call(from_kall=False)1654def create_autospec(spec, spec_set=False, instance=False, _parent=None,1655 _name=None, **kwargs):...

Full Screen

Full Screen

mock.py

Source:mock.py Github

copy

Full Screen

...510 del self._mock_children[name]511 self._mock_children[name] = _deleted512 def _format_mock_call_signature(self, args, kwargs):513 name = self._mock_name or 'mock'514 return _format_call_signature(name, args, kwargs)515 def _format_mock_failure_message(self, args, kwargs):516 message = 'Expected call: %s\nActual call: %s'517 expected_string = self._format_mock_call_signature(args, kwargs)518 call_args = self.call_args519 if len(call_args) == 3:520 call_args = call_args[1:]521 actual_string = self._format_mock_call_signature(*call_args)522 return message % (expected_string, actual_string)523 def assert_called_with(_mock_self, *args, **kwargs):524 self = _mock_self525 if self.call_args is None:526 expected = self._format_mock_call_signature(args, kwargs)527 raise AssertionError('Expected call: %s\nNot called' % (expected,))528 if self.call_args != (args, kwargs):529 msg = self._format_mock_failure_message(args, kwargs)530 raise AssertionError(msg)531 def assert_called_once_with(_mock_self, *args, **kwargs):532 self = _mock_self533 if not self.call_count == 1:534 msg = 'Expected to be called once. Called %s times.' % self.call_count535 raise AssertionError(msg)536 return self.assert_called_with(*args, **kwargs)537 def assert_has_calls(self, calls, any_order = False):538 if not any_order:539 if calls not in self.mock_calls:540 raise AssertionError('Calls not found.\nExpected: %r\nActual: %r' % (calls, self.mock_calls))541 return542 all_calls = list(self.mock_calls)543 not_found = []544 for kall in calls:545 try:546 all_calls.remove(kall)547 except ValueError:548 not_found.append(kall)549 if not_found:550 raise AssertionError('%r not all found in call list' % (tuple(not_found),))551 def assert_any_call(self, *args, **kwargs):552 kall = call(*args, **kwargs)553 if kall not in self.call_args_list:554 expected_string = self._format_mock_call_signature(args, kwargs)555 raise AssertionError('%s call not found' % expected_string)556 def _get_child_mock(self, **kw):557 _type = type(self)558 if not issubclass(_type, CallableMixin):559 if issubclass(_type, NonCallableMagicMock):560 klass = MagicMock561 elif issubclass(_type, NonCallableMock):562 klass = Mock563 else:564 klass = _type.__mro__[1]565 return klass(**kw)566def _try_iter(obj):567 if obj is None:568 return obj569 if _is_exception(obj):570 return obj571 if _callable(obj):572 return obj573 try:574 return iter(obj)575 except TypeError:576 return obj577class CallableMixin(Base):578 def __init__(self, spec = None, side_effect = None, return_value = DEFAULT, wraps = None, name = None, spec_set = None, parent = None, _spec_state = None, _new_name = '', _new_parent = None, **kwargs):579 self.__dict__['_mock_return_value'] = return_value580 _super(CallableMixin, self).__init__(spec, wraps, name, spec_set, parent, _spec_state, _new_name, _new_parent, **kwargs)581 self.side_effect = side_effect582 def _mock_check_sig(self, *args, **kwargs):583 pass584 def __call__(_mock_self, *args, **kwargs):585 _mock_self._mock_check_sig(*args, **kwargs)586 return _mock_self._mock_call(*args, **kwargs)587 def _mock_call(_mock_self, *args, **kwargs):588 self = _mock_self589 self.called = True590 self.call_count += 1591 self.call_args = _Call((args, kwargs), two=True)592 self.call_args_list.append(_Call((args, kwargs), two=True))593 _new_name = self._mock_new_name594 _new_parent = self._mock_new_parent595 self.mock_calls.append(_Call(('', args, kwargs)))596 seen = set()597 skip_next_dot = _new_name == '()'598 do_method_calls = self._mock_parent is not None599 name = self._mock_name600 while _new_parent is not None:601 this_mock_call = _Call((_new_name, args, kwargs))602 if _new_parent._mock_new_name:603 dot = '.'604 if skip_next_dot:605 dot = ''606 skip_next_dot = False607 if _new_parent._mock_new_name == '()':608 skip_next_dot = True609 _new_name = _new_parent._mock_new_name + dot + _new_name610 if do_method_calls:611 if _new_name == name:612 this_method_call = this_mock_call613 else:614 this_method_call = _Call((name, args, kwargs))615 _new_parent.method_calls.append(this_method_call)616 do_method_calls = _new_parent._mock_parent is not None617 if do_method_calls:618 name = _new_parent._mock_name + '.' + name619 _new_parent.mock_calls.append(this_mock_call)620 _new_parent = _new_parent._mock_new_parent621 _new_parent_id = id(_new_parent)622 if _new_parent_id in seen:623 break624 seen.add(_new_parent_id)625 ret_val = DEFAULT626 effect = self.side_effect627 if effect is not None:628 if _is_exception(effect):629 raise effect630 if not _callable(effect):631 result = next(effect)632 if _is_exception(result):633 raise result634 return result635 ret_val = effect(*args, **kwargs)636 if ret_val is DEFAULT:637 ret_val = self.return_value638 if self._mock_wraps is not None and self._mock_return_value is DEFAULT:639 return self._mock_wraps(*args, **kwargs)640 if ret_val is DEFAULT:641 ret_val = self.return_value642 return ret_val643class Mock(CallableMixin, NonCallableMock):644 pass645def _dot_lookup(thing, comp, import_path):646 try:647 return getattr(thing, comp)648 except AttributeError:649 __import__(import_path)650 return getattr(thing, comp)651def _importer(target):652 components = target.split('.')653 import_path = components.pop(0)654 thing = __import__(import_path)655 for comp in components:656 import_path += '.%s' % comp657 thing = _dot_lookup(thing, comp, import_path)658 return thing659def _is_started(patcher):660 return hasattr(patcher, 'is_local')661class _patch(object):662 attribute_name = None663 _active_patches = set()664 def __init__(self, getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs):665 if new_callable is not None:666 if new is not DEFAULT:667 raise ValueError("Cannot use 'new' and 'new_callable' together")668 if autospec is not None:669 raise ValueError("Cannot use 'autospec' and 'new_callable' together")670 self.getter = getter671 self.attribute = attribute672 self.new = new673 self.new_callable = new_callable674 self.spec = spec675 self.create = create676 self.has_local = False677 self.spec_set = spec_set678 self.autospec = autospec679 self.kwargs = kwargs680 self.additional_patchers = []681 def copy(self):682 patcher = _patch(self.getter, self.attribute, self.new, self.spec, self.create, self.spec_set, self.autospec, self.new_callable, self.kwargs)683 patcher.attribute_name = self.attribute_name684 patcher.additional_patchers = [ p.copy() for p in self.additional_patchers ]685 return patcher686 def __call__(self, func):687 if isinstance(func, ClassTypes):688 return self.decorate_class(func)689 return self.decorate_callable(func)690 def decorate_class(self, klass):691 for attr in dir(klass):692 if not attr.startswith(patch.TEST_PREFIX):693 continue694 attr_value = getattr(klass, attr)695 if not hasattr(attr_value, '__call__'):696 continue697 patcher = self.copy()698 setattr(klass, attr, patcher(attr_value))699 return klass700 def decorate_callable(self, func):701 if hasattr(func, 'patchings'):702 func.patchings.append(self)703 return func704 @wraps(func)705 def patched(*args, **keywargs):706 extra_args = []707 entered_patchers = []708 exc_info = tuple()709 try:710 for patching in patched.patchings:711 arg = patching.__enter__()712 entered_patchers.append(patching)713 if patching.attribute_name is not None:714 keywargs.update(arg)715 elif patching.new is DEFAULT:716 extra_args.append(arg)717 args += tuple(extra_args)718 return func(*args, **keywargs)719 except:720 if patching not in entered_patchers and _is_started(patching):721 entered_patchers.append(patching)722 exc_info = sys.exc_info()723 raise724 finally:725 for patching in reversed(entered_patchers):726 patching.__exit__(*exc_info)727 patched.patchings = [self]728 if hasattr(func, 'func_code'):729 patched.compat_co_firstlineno = getattr(func, 'compat_co_firstlineno', func.func_code.co_firstlineno)730 return patched731 def get_original(self):732 target = self.getter()733 name = self.attribute734 original = DEFAULT735 local = False736 try:737 original = target.__dict__[name]738 except (AttributeError, KeyError):739 original = getattr(target, name, DEFAULT)740 else:741 local = True742 if not self.create and original is DEFAULT:743 raise AttributeError('%s does not have the attribute %r' % (target, name))744 return (original, local)745 def __enter__(self):746 new, spec, spec_set = self.new, self.spec, self.spec_set747 autospec, kwargs = self.autospec, self.kwargs748 new_callable = self.new_callable749 self.target = self.getter()750 if spec is False:751 spec = None752 if spec_set is False:753 spec_set = None754 if autospec is False:755 autospec = None756 if spec is not None and autospec is not None:757 raise TypeError("Can't specify spec and autospec")758 if (spec is not None or autospec is not None) and spec_set not in (True, None):759 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")760 original, local = self.get_original()761 if new is DEFAULT and autospec is None:762 inherit = False763 if spec is True:764 spec = original765 if spec_set is True:766 spec_set = original767 spec = None768 elif spec is not None:769 if spec_set is True:770 spec_set = spec771 spec = None772 elif spec_set is True:773 spec_set = original774 if spec is not None or spec_set is not None:775 if original is DEFAULT:776 raise TypeError("Can't use 'spec' with create=True")777 if isinstance(original, ClassTypes):778 inherit = True779 Klass = MagicMock780 _kwargs = {}781 if new_callable is not None:782 Klass = new_callable783 elif spec is not None or spec_set is not None:784 this_spec = spec785 if spec_set is not None:786 this_spec = spec_set787 if _is_list(this_spec):788 not_callable = '__call__' not in this_spec789 else:790 not_callable = not _callable(this_spec)791 if not_callable:792 Klass = NonCallableMagicMock793 if spec is not None:794 _kwargs['spec'] = spec795 if spec_set is not None:796 _kwargs['spec_set'] = spec_set797 if isinstance(Klass, type) and issubclass(Klass, NonCallableMock) and self.attribute:798 _kwargs['name'] = self.attribute799 _kwargs.update(kwargs)800 new = Klass(**_kwargs)801 if inherit and _is_instance_mock(new):802 this_spec = spec803 if spec_set is not None:804 this_spec = spec_set805 if not _is_list(this_spec) and not _instance_callable(this_spec):806 Klass = NonCallableMagicMock807 _kwargs.pop('name')808 new.return_value = Klass(_new_parent=new, _new_name='()', **_kwargs)809 elif autospec is not None:810 if new is not DEFAULT:811 raise TypeError("autospec creates the mock for you. Can't specify autospec and new.")812 if original is DEFAULT:813 raise TypeError("Can't use 'autospec' with create=True")814 spec_set = bool(spec_set)815 if autospec is True:816 autospec = original817 new = create_autospec(autospec, spec_set=spec_set, _name=self.attribute, **kwargs)818 elif kwargs:819 raise TypeError("Can't pass kwargs to a mock we aren't creating")820 new_attr = new821 self.temp_original = original822 self.is_local = local823 setattr(self.target, self.attribute, new_attr)824 if self.attribute_name is not None:825 extra_args = {}826 if self.new is DEFAULT:827 extra_args[self.attribute_name] = new828 for patching in self.additional_patchers:829 arg = patching.__enter__()830 if patching.new is DEFAULT:831 extra_args.update(arg)832 return extra_args833 return new834 def __exit__(self, *exc_info):835 if not _is_started(self):836 raise RuntimeError('stop called on unstarted patcher')837 if self.is_local and self.temp_original is not DEFAULT:838 setattr(self.target, self.attribute, self.temp_original)839 else:840 delattr(self.target, self.attribute)841 if not self.create and not hasattr(self.target, self.attribute):842 setattr(self.target, self.attribute, self.temp_original)843 del self.temp_original844 del self.is_local845 del self.target846 for patcher in reversed(self.additional_patchers):847 if _is_started(patcher):848 patcher.__exit__(*exc_info)849 def start(self):850 result = self.__enter__()851 self._active_patches.add(self)852 return result853 def stop(self):854 self._active_patches.discard(self)855 return self.__exit__()856def _get_target(target):857 try:858 target, attribute = target.rsplit('.', 1)859 except (TypeError, ValueError):860 raise TypeError('Need a valid target to patch. You supplied: %r' % (target,))861 getter = lambda : _importer(target)862 return (getter, attribute)863def _patch_object(target, attribute, new = DEFAULT, spec = None, create = False, spec_set = None, autospec = None, new_callable = None, **kwargs):864 getter = lambda : target865 return _patch(getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs)866def _patch_multiple(target, spec = None, create = False, spec_set = None, autospec = None, new_callable = None, **kwargs):867 if type(target) in (unicode, str):868 getter = lambda : _importer(target)869 else:870 getter = lambda : target871 if not kwargs:872 raise ValueError('Must supply at least one keyword argument with patch.multiple')873 items = list(kwargs.items())874 attribute, new = items[0]875 patcher = _patch(getter, attribute, new, spec, create, spec_set, autospec, new_callable, {})876 patcher.attribute_name = attribute877 for attribute, new in items[1:]:878 this_patcher = _patch(getter, attribute, new, spec, create, spec_set, autospec, new_callable, {})879 this_patcher.attribute_name = attribute880 patcher.additional_patchers.append(this_patcher)881 return patcher882def patch(target, new = DEFAULT, spec = None, create = False, spec_set = None, autospec = None, new_callable = None, **kwargs):883 getter, attribute = _get_target(target)884 return _patch(getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs)885class _patch_dict(object):886 def __init__(self, in_dict, values = (), clear = False, **kwargs):887 if isinstance(in_dict, basestring):888 in_dict = _importer(in_dict)889 self.in_dict = in_dict890 self.values = dict(values)891 self.values.update(kwargs)892 self.clear = clear893 self._original = None894 def __call__(self, f):895 if isinstance(f, ClassTypes):896 return self.decorate_class(f)897 @wraps(f)898 def _inner(*args, **kw):899 self._patch_dict()900 try:901 return f(*args, **kw)902 finally:903 self._unpatch_dict()904 return _inner905 def decorate_class(self, klass):906 for attr in dir(klass):907 attr_value = getattr(klass, attr)908 if attr.startswith(patch.TEST_PREFIX) and hasattr(attr_value, '__call__'):909 decorator = _patch_dict(self.in_dict, self.values, self.clear)910 decorated = decorator(attr_value)911 setattr(klass, attr, decorated)912 return klass913 def __enter__(self):914 self._patch_dict()915 def _patch_dict(self):916 values = self.values917 in_dict = self.in_dict918 clear = self.clear919 try:920 original = in_dict.copy()921 except AttributeError:922 original = {}923 for key in in_dict:924 original[key] = in_dict[key]925 self._original = original926 if clear:927 _clear_dict(in_dict)928 try:929 in_dict.update(values)930 except AttributeError:931 for key in values:932 in_dict[key] = values[key]933 def _unpatch_dict(self):934 in_dict = self.in_dict935 original = self._original936 _clear_dict(in_dict)937 try:938 in_dict.update(original)939 except AttributeError:940 for key in original:941 in_dict[key] = original[key]942 def __exit__(self, *args):943 self._unpatch_dict()944 return False945 start = __enter__946 stop = __exit__947def _clear_dict(in_dict):948 try:949 in_dict.clear()950 except AttributeError:951 keys = list(in_dict)952 for key in keys:953 del in_dict[key]954def _patch_stopall():955 for patch in list(_patch._active_patches):956 patch.stop()957patch.object = _patch_object958patch.dict = _patch_dict959patch.multiple = _patch_multiple960patch.stopall = _patch_stopall961patch.TEST_PREFIX = 'test'962magic_methods = 'lt le gt ge eq ne getitem setitem delitem len contains iter hash str sizeof enter exit divmod neg pos abs invert complex int float index trunc floor ceil '963numerics = 'add sub mul div floordiv mod lshift rshift and xor or pow '964inplace = ' '.join(('i%s' % n for n in numerics.split()))965right = ' '.join(('r%s' % n for n in numerics.split()))966extra = ''967if inPy3k:968 extra = 'bool next '969else:970 extra = 'unicode long nonzero oct hex truediv rtruediv '971_non_defaults = set(('__%s__' % method for method in ['cmp',972 'getslice',973 'setslice',974 'coerce',975 'subclasses',976 'format',977 'get',978 'set',979 'delete',980 'reversed',981 'missing',982 'reduce',983 'reduce_ex',984 'getinitargs',985 'getnewargs',986 'getstate',987 'setstate',988 'getformat',989 'setformat',990 'repr',991 'dir']))992def _get_method(name, func):993 def method(self, *args, **kw):994 return func(self, *args, **kw)995 method.__name__ = name996 return method997_magics = set(('__%s__' % method for method in ' '.join([magic_methods,998 numerics,999 inplace,1000 right,1001 extra]).split()))1002_all_magics = _magics | _non_defaults1003_unsupported_magics = set(['__getattr__',1004 '__setattr__',1005 '__init__',1006 '__new__',1007 '__prepare____instancecheck__',1008 '__subclasscheck__',1009 '__del__'])1010_calculate_return_value = {'__hash__': lambda self: object.__hash__(self),1011 '__str__': lambda self: object.__str__(self),1012 '__sizeof__': lambda self: object.__sizeof__(self),1013 '__unicode__': lambda self: unicode(object.__str__(self))}1014_return_values = {'__lt__': NotImplemented,1015 '__gt__': NotImplemented,1016 '__le__': NotImplemented,1017 '__ge__': NotImplemented,1018 '__int__': 1,1019 '__contains__': False,1020 '__len__': 0,1021 '__exit__': False,1022 '__complex__': 1j,1023 '__float__': 1.0,1024 '__bool__': True,1025 '__nonzero__': True,1026 '__oct__': '1',1027 '__hex__': '0x1',1028 '__long__': long(1),1029 '__index__': 1}1030def _get_eq(self):1031 def __eq__(other):1032 ret_val = self.__eq__._mock_return_value1033 if ret_val is not DEFAULT:1034 return ret_val1035 return self is other1036 return __eq__1037def _get_ne(self):1038 def __ne__(other):1039 if self.__ne__._mock_return_value is not DEFAULT:1040 return DEFAULT1041 return self is not other1042 return __ne__1043def _get_iter(self):1044 def __iter__():1045 ret_val = self.__iter__._mock_return_value1046 if ret_val is DEFAULT:1047 return iter([])1048 return iter(ret_val)1049 return __iter__1050_side_effect_methods = {'__eq__': _get_eq,1051 '__ne__': _get_ne,1052 '__iter__': _get_iter}1053def _set_return_value(mock, method, name):1054 fixed = _return_values.get(name, DEFAULT)1055 if fixed is not DEFAULT:1056 method.return_value = fixed1057 return1058 return_calulator = _calculate_return_value.get(name)1059 if return_calulator is not None:1060 try:1061 return_value = return_calulator(mock)1062 except AttributeError:1063 return_value = AttributeError(name)1064 method.return_value = return_value1065 return1066 side_effector = _side_effect_methods.get(name)1067 if side_effector is not None:1068 method.side_effect = side_effector(mock)1069class MagicMixin(object):1070 def __init__(self, *args, **kw):1071 _super(MagicMixin, self).__init__(*args, **kw)1072 self._mock_set_magics()1073 def _mock_set_magics(self):1074 these_magics = _magics1075 if self._mock_methods is not None:1076 these_magics = _magics.intersection(self._mock_methods)1077 remove_magics = set()1078 remove_magics = _magics - these_magics1079 for entry in remove_magics:1080 if entry in type(self).__dict__:1081 delattr(self, entry)1082 these_magics = these_magics - set(type(self).__dict__)1083 _type = type(self)1084 for entry in these_magics:1085 setattr(_type, entry, MagicProxy(entry, self))1086class NonCallableMagicMock(MagicMixin, NonCallableMock):1087 def mock_add_spec(self, spec, spec_set = False):1088 self._mock_add_spec(spec, spec_set)1089 self._mock_set_magics()1090class MagicMock(MagicMixin, Mock):1091 def mock_add_spec(self, spec, spec_set = False):1092 self._mock_add_spec(spec, spec_set)1093 self._mock_set_magics()1094class MagicProxy(object):1095 def __init__(self, name, parent):1096 self.name = name1097 self.parent = parent1098 def __call__(self, *args, **kwargs):1099 m = self.create_mock()1100 return m(*args, **kwargs)1101 def create_mock(self):1102 entry = self.name1103 parent = self.parent1104 m = parent._get_child_mock(name=entry, _new_name=entry, _new_parent=parent)1105 setattr(parent, entry, m)1106 _set_return_value(parent, m, entry)1107 return m1108 def __get__(self, obj, _type = None):1109 return self.create_mock()1110class _ANY(object):1111 def __eq__(self, other):1112 return True1113 def __ne__(self, other):1114 return False1115 def __repr__(self):1116 return '<ANY>'1117ANY = _ANY()1118def _format_call_signature(name, args, kwargs):1119 message = '%s(%%s)' % name1120 formatted_args = ''1121 args_string = ', '.join([ repr(arg) for arg in args ])1122 kwargs_string = ', '.join([ '%s=%r' % (key, value) for key, value in kwargs.items() ])1123 if args_string:1124 formatted_args = args_string1125 if kwargs_string:1126 if formatted_args:1127 formatted_args += ', '1128 formatted_args += kwargs_string1129 return message % formatted_args1130class _Call(tuple):1131 def __new__(cls, value = (), name = None, parent = None, two = False, from_kall = True):1132 name = ''1133 args = ()1134 kwargs = {}1135 _len = len(value)1136 if _len == 3:1137 name, args, kwargs = value1138 elif _len == 2:1139 first, second = value1140 if isinstance(first, basestring):1141 name = first1142 if isinstance(second, tuple):1143 args = second1144 else:1145 kwargs = second1146 else:1147 args, kwargs = first, second1148 elif _len == 1:1149 value, = value1150 if isinstance(value, basestring):1151 name = value1152 elif isinstance(value, tuple):1153 args = value1154 else:1155 kwargs = value1156 if two:1157 return tuple.__new__(cls, (args, kwargs))1158 return tuple.__new__(cls, (name, args, kwargs))1159 def __init__(self, value = (), name = None, parent = None, two = False, from_kall = True):1160 self.name = name1161 self.parent = parent1162 self.from_kall = from_kall1163 def __eq__(self, other):1164 if other is ANY:1165 return True1166 try:1167 len_other = len(other)1168 except TypeError:1169 return False1170 self_name = ''1171 if len(self) == 2:1172 self_args, self_kwargs = self1173 else:1174 self_name, self_args, self_kwargs = self1175 other_name = ''1176 if len_other == 0:1177 other_args, other_kwargs = (), {}1178 elif len_other == 3:1179 other_name, other_args, other_kwargs = other1180 elif len_other == 1:1181 value, = other1182 if isinstance(value, tuple):1183 other_args = value1184 other_kwargs = {}1185 elif isinstance(value, basestring):1186 other_name = value1187 other_args, other_kwargs = (), {}1188 else:1189 other_args = ()1190 other_kwargs = value1191 else:1192 first, second = other1193 if isinstance(first, basestring):1194 other_name = first1195 if isinstance(second, tuple):1196 other_args, other_kwargs = second, {}1197 else:1198 other_args, other_kwargs = (), second1199 else:1200 other_args, other_kwargs = first, second1201 if self_name and other_name != self_name:1202 return False1203 return (other_args, other_kwargs) == (self_args, self_kwargs)1204 def __ne__(self, other):1205 return not self.__eq__(other)1206 def __call__(self, *args, **kwargs):1207 if self.name is None:1208 return _Call(('', args, kwargs), name='()')1209 name = self.name + '()'1210 return _Call((self.name, args, kwargs), name=name, parent=self)1211 def __getattr__(self, attr):1212 if self.name is None:1213 return _Call(name=attr, from_kall=False)1214 name = '%s.%s' % (self.name, attr)1215 return _Call(name=name, parent=self, from_kall=False)1216 def __repr__(self):1217 if not self.from_kall:1218 name = self.name or 'call'1219 if name.startswith('()'):1220 name = 'call%s' % name1221 return name1222 if len(self) == 2:1223 name = 'call'1224 args, kwargs = self1225 else:1226 name, args, kwargs = self1227 if not name:1228 name = 'call'1229 elif not name.startswith('()'):1230 name = 'call.%s' % name1231 else:1232 name = 'call%s' % name1233 return _format_call_signature(name, args, kwargs)1234 def call_list(self):1235 vals = []1236 thing = self1237 while thing is not None:1238 if thing.from_kall:1239 vals.append(thing)1240 thing = thing.parent1241 return _CallList(reversed(vals))1242call = _Call(from_kall=False)1243def create_autospec(spec, spec_set = False, instance = False, _parent = None, _name = None, **kwargs):1244 if _is_list(spec):1245 spec = type(spec)1246 is_type = isinstance(spec, ClassTypes)1247 _kwargs = {'spec': spec}...

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