michael@0: # mock.py michael@0: # Test tools for mocking and patching. michael@0: # Copyright (C) 2007-2012 Michael Foord & the mock team michael@0: # E-mail: fuzzyman AT voidspace DOT org DOT uk michael@0: michael@0: # mock 1.0 michael@0: # http://www.voidspace.org.uk/python/mock/ michael@0: michael@0: # Released subject to the BSD License michael@0: # Please see http://www.voidspace.org.uk/python/license.shtml michael@0: michael@0: # Scripts maintained at http://www.voidspace.org.uk/python/index.shtml michael@0: # Comments, suggestions and bug reports welcome. michael@0: michael@0: michael@0: __all__ = ( michael@0: 'Mock', michael@0: 'MagicMock', michael@0: 'patch', michael@0: 'sentinel', michael@0: 'DEFAULT', michael@0: 'ANY', michael@0: 'call', michael@0: 'create_autospec', michael@0: 'FILTER_DIR', michael@0: 'NonCallableMock', michael@0: 'NonCallableMagicMock', michael@0: 'mock_open', michael@0: 'PropertyMock', michael@0: ) michael@0: michael@0: michael@0: __version__ = '1.0.0' michael@0: michael@0: michael@0: import pprint michael@0: import sys michael@0: michael@0: try: michael@0: import inspect michael@0: except ImportError: michael@0: # for alternative platforms that michael@0: # may not have inspect michael@0: inspect = None michael@0: michael@0: try: michael@0: from functools import wraps michael@0: except ImportError: michael@0: # Python 2.4 compatibility michael@0: def wraps(original): michael@0: def inner(f): michael@0: f.__name__ = original.__name__ michael@0: f.__doc__ = original.__doc__ michael@0: f.__module__ = original.__module__ michael@0: return f michael@0: return inner michael@0: michael@0: try: michael@0: unicode michael@0: except NameError: michael@0: # Python 3 michael@0: basestring = unicode = str michael@0: michael@0: try: michael@0: long michael@0: except NameError: michael@0: # Python 3 michael@0: long = int michael@0: michael@0: try: michael@0: BaseException michael@0: except NameError: michael@0: # Python 2.4 compatibility michael@0: BaseException = Exception michael@0: michael@0: try: michael@0: next michael@0: except NameError: michael@0: def next(obj): michael@0: return obj.next() michael@0: michael@0: michael@0: BaseExceptions = (BaseException,) michael@0: if 'java' in sys.platform: michael@0: # jython michael@0: import java michael@0: BaseExceptions = (BaseException, java.lang.Throwable) michael@0: michael@0: try: michael@0: _isidentifier = str.isidentifier michael@0: except AttributeError: michael@0: # Python 2.X michael@0: import keyword michael@0: import re michael@0: regex = re.compile(r'^[a-z_][a-z0-9_]*$', re.I) michael@0: def _isidentifier(string): michael@0: if string in keyword.kwlist: michael@0: return False michael@0: return regex.match(string) michael@0: michael@0: michael@0: inPy3k = sys.version_info[0] == 3 michael@0: michael@0: # Needed to work around Python 3 bug where use of "super" interferes with michael@0: # defining __class__ as a descriptor michael@0: _super = super michael@0: michael@0: self = 'im_self' michael@0: builtin = '__builtin__' michael@0: if inPy3k: michael@0: self = '__self__' michael@0: builtin = 'builtins' michael@0: michael@0: FILTER_DIR = True michael@0: michael@0: michael@0: def _is_instance_mock(obj): michael@0: # can't use isinstance on Mock objects because they override __class__ michael@0: # The base class for all mocks is NonCallableMock michael@0: return issubclass(type(obj), NonCallableMock) michael@0: michael@0: michael@0: def _is_exception(obj): michael@0: return ( michael@0: isinstance(obj, BaseExceptions) or michael@0: isinstance(obj, ClassTypes) and issubclass(obj, BaseExceptions) michael@0: ) michael@0: michael@0: michael@0: class _slotted(object): michael@0: __slots__ = ['a'] michael@0: michael@0: michael@0: DescriptorTypes = ( michael@0: type(_slotted.a), michael@0: property, michael@0: ) michael@0: michael@0: michael@0: def _getsignature(func, skipfirst, instance=False): michael@0: if inspect is None: michael@0: raise ImportError('inspect module not available') michael@0: michael@0: if isinstance(func, ClassTypes) and not instance: michael@0: try: michael@0: func = func.__init__ michael@0: except AttributeError: michael@0: return michael@0: skipfirst = True michael@0: elif not isinstance(func, FunctionTypes): michael@0: # for classes where instance is True we end up here too michael@0: try: michael@0: func = func.__call__ michael@0: except AttributeError: michael@0: return michael@0: michael@0: if inPy3k: michael@0: try: michael@0: argspec = inspect.getfullargspec(func) michael@0: except TypeError: michael@0: # C function / method, possibly inherited object().__init__ michael@0: return michael@0: regargs, varargs, varkw, defaults, kwonly, kwonlydef, ann = argspec michael@0: else: michael@0: try: michael@0: regargs, varargs, varkwargs, defaults = inspect.getargspec(func) michael@0: except TypeError: michael@0: # C function / method, possibly inherited object().__init__ michael@0: return michael@0: michael@0: # instance methods and classmethods need to lose the self argument michael@0: if getattr(func, self, None) is not None: michael@0: regargs = regargs[1:] michael@0: if skipfirst: michael@0: # this condition and the above one are never both True - why? michael@0: regargs = regargs[1:] michael@0: michael@0: if inPy3k: michael@0: signature = inspect.formatargspec( michael@0: regargs, varargs, varkw, defaults, michael@0: kwonly, kwonlydef, ann, formatvalue=lambda value: "") michael@0: else: michael@0: signature = inspect.formatargspec( michael@0: regargs, varargs, varkwargs, defaults, michael@0: formatvalue=lambda value: "") michael@0: return signature[1:-1], func michael@0: michael@0: michael@0: def _check_signature(func, mock, skipfirst, instance=False): michael@0: if not _callable(func): michael@0: return michael@0: michael@0: result = _getsignature(func, skipfirst, instance) michael@0: if result is None: michael@0: return michael@0: signature, func = result michael@0: michael@0: # can't use self because "self" is common as an argument name michael@0: # unfortunately even not in the first place michael@0: src = "lambda _mock_self, %s: None" % signature michael@0: checksig = eval(src, {}) michael@0: _copy_func_details(func, checksig) michael@0: type(mock)._mock_check_sig = checksig michael@0: michael@0: michael@0: def _copy_func_details(func, funcopy): michael@0: funcopy.__name__ = func.__name__ michael@0: funcopy.__doc__ = func.__doc__ michael@0: #funcopy.__dict__.update(func.__dict__) michael@0: funcopy.__module__ = func.__module__ michael@0: if not inPy3k: michael@0: funcopy.func_defaults = func.func_defaults michael@0: return michael@0: funcopy.__defaults__ = func.__defaults__ michael@0: funcopy.__kwdefaults__ = func.__kwdefaults__ michael@0: michael@0: michael@0: def _callable(obj): michael@0: if isinstance(obj, ClassTypes): michael@0: return True michael@0: if getattr(obj, '__call__', None) is not None: michael@0: return True michael@0: return False michael@0: michael@0: michael@0: def _is_list(obj): michael@0: # checks for list or tuples michael@0: # XXXX badly named! michael@0: return type(obj) in (list, tuple) michael@0: michael@0: michael@0: def _instance_callable(obj): michael@0: """Given an object, return True if the object is callable. michael@0: For classes, return True if instances would be callable.""" michael@0: if not isinstance(obj, ClassTypes): michael@0: # already an instance michael@0: return getattr(obj, '__call__', None) is not None michael@0: michael@0: klass = obj michael@0: # uses __bases__ instead of __mro__ so that we work with old style classes michael@0: if klass.__dict__.get('__call__') is not None: michael@0: return True michael@0: michael@0: for base in klass.__bases__: michael@0: if _instance_callable(base): michael@0: return True michael@0: return False michael@0: michael@0: michael@0: def _set_signature(mock, original, instance=False): michael@0: # creates a function with signature (*args, **kwargs) that delegates to a michael@0: # mock. It still does signature checking by calling a lambda with the same michael@0: # signature as the original. michael@0: if not _callable(original): michael@0: return michael@0: michael@0: skipfirst = isinstance(original, ClassTypes) michael@0: result = _getsignature(original, skipfirst, instance) michael@0: if result is None: michael@0: # was a C function (e.g. object().__init__ ) that can't be mocked michael@0: return michael@0: michael@0: signature, func = result michael@0: michael@0: src = "lambda %s: None" % signature michael@0: checksig = eval(src, {}) michael@0: _copy_func_details(func, checksig) michael@0: michael@0: name = original.__name__ michael@0: if not _isidentifier(name): michael@0: name = 'funcopy' michael@0: context = {'_checksig_': checksig, 'mock': mock} michael@0: src = """def %s(*args, **kwargs): michael@0: _checksig_(*args, **kwargs) michael@0: return mock(*args, **kwargs)""" % name michael@0: exec (src, context) michael@0: funcopy = context[name] michael@0: _setup_func(funcopy, mock) michael@0: return funcopy michael@0: michael@0: michael@0: def _setup_func(funcopy, mock): michael@0: funcopy.mock = mock michael@0: michael@0: # can't use isinstance with mocks michael@0: if not _is_instance_mock(mock): michael@0: return michael@0: michael@0: def assert_called_with(*args, **kwargs): michael@0: return mock.assert_called_with(*args, **kwargs) michael@0: def assert_called_once_with(*args, **kwargs): michael@0: return mock.assert_called_once_with(*args, **kwargs) michael@0: def assert_has_calls(*args, **kwargs): michael@0: return mock.assert_has_calls(*args, **kwargs) michael@0: def assert_any_call(*args, **kwargs): michael@0: return mock.assert_any_call(*args, **kwargs) michael@0: def reset_mock(): michael@0: funcopy.method_calls = _CallList() michael@0: funcopy.mock_calls = _CallList() michael@0: mock.reset_mock() michael@0: ret = funcopy.return_value michael@0: if _is_instance_mock(ret) and not ret is mock: michael@0: ret.reset_mock() michael@0: michael@0: funcopy.called = False michael@0: funcopy.call_count = 0 michael@0: funcopy.call_args = None michael@0: funcopy.call_args_list = _CallList() michael@0: funcopy.method_calls = _CallList() michael@0: funcopy.mock_calls = _CallList() michael@0: michael@0: funcopy.return_value = mock.return_value michael@0: funcopy.side_effect = mock.side_effect michael@0: funcopy._mock_children = mock._mock_children michael@0: michael@0: funcopy.assert_called_with = assert_called_with michael@0: funcopy.assert_called_once_with = assert_called_once_with michael@0: funcopy.assert_has_calls = assert_has_calls michael@0: funcopy.assert_any_call = assert_any_call michael@0: funcopy.reset_mock = reset_mock michael@0: michael@0: mock._mock_delegate = funcopy michael@0: michael@0: michael@0: def _is_magic(name): michael@0: return '__%s__' % name[2:-2] == name michael@0: michael@0: michael@0: class _SentinelObject(object): michael@0: "A unique, named, sentinel object." michael@0: def __init__(self, name): michael@0: self.name = name michael@0: michael@0: def __repr__(self): michael@0: return 'sentinel.%s' % self.name michael@0: michael@0: michael@0: class _Sentinel(object): michael@0: """Access attributes to return a named object, usable as a sentinel.""" michael@0: def __init__(self): michael@0: self._sentinels = {} michael@0: michael@0: def __getattr__(self, name): michael@0: if name == '__bases__': michael@0: # Without this help(mock) raises an exception michael@0: raise AttributeError michael@0: return self._sentinels.setdefault(name, _SentinelObject(name)) michael@0: michael@0: michael@0: sentinel = _Sentinel() michael@0: michael@0: DEFAULT = sentinel.DEFAULT michael@0: _missing = sentinel.MISSING michael@0: _deleted = sentinel.DELETED michael@0: michael@0: michael@0: class OldStyleClass: michael@0: pass michael@0: ClassType = type(OldStyleClass) michael@0: michael@0: michael@0: def _copy(value): michael@0: if type(value) in (dict, list, tuple, set): michael@0: return type(value)(value) michael@0: return value michael@0: michael@0: michael@0: ClassTypes = (type,) michael@0: if not inPy3k: michael@0: ClassTypes = (type, ClassType) michael@0: michael@0: _allowed_names = set( michael@0: [ michael@0: 'return_value', '_mock_return_value', 'side_effect', michael@0: '_mock_side_effect', '_mock_parent', '_mock_new_parent', michael@0: '_mock_name', '_mock_new_name' michael@0: ] michael@0: ) michael@0: michael@0: michael@0: def _delegating_property(name): michael@0: _allowed_names.add(name) michael@0: _the_name = '_mock_' + name michael@0: def _get(self, name=name, _the_name=_the_name): michael@0: sig = self._mock_delegate michael@0: if sig is None: michael@0: return getattr(self, _the_name) michael@0: return getattr(sig, name) michael@0: def _set(self, value, name=name, _the_name=_the_name): michael@0: sig = self._mock_delegate michael@0: if sig is None: michael@0: self.__dict__[_the_name] = value michael@0: else: michael@0: setattr(sig, name, value) michael@0: michael@0: return property(_get, _set) michael@0: michael@0: michael@0: michael@0: class _CallList(list): michael@0: michael@0: def __contains__(self, value): michael@0: if not isinstance(value, list): michael@0: return list.__contains__(self, value) michael@0: len_value = len(value) michael@0: len_self = len(self) michael@0: if len_value > len_self: michael@0: return False michael@0: michael@0: for i in range(0, len_self - len_value + 1): michael@0: sub_list = self[i:i+len_value] michael@0: if sub_list == value: michael@0: return True michael@0: return False michael@0: michael@0: def __repr__(self): michael@0: return pprint.pformat(list(self)) michael@0: michael@0: michael@0: def _check_and_set_parent(parent, value, name, new_name): michael@0: if not _is_instance_mock(value): michael@0: return False michael@0: if ((value._mock_name or value._mock_new_name) or michael@0: (value._mock_parent is not None) or michael@0: (value._mock_new_parent is not None)): michael@0: return False michael@0: michael@0: _parent = parent michael@0: while _parent is not None: michael@0: # setting a mock (value) as a child or return value of itself michael@0: # should not modify the mock michael@0: if _parent is value: michael@0: return False michael@0: _parent = _parent._mock_new_parent michael@0: michael@0: if new_name: michael@0: value._mock_new_parent = parent michael@0: value._mock_new_name = new_name michael@0: if name: michael@0: value._mock_parent = parent michael@0: value._mock_name = name michael@0: return True michael@0: michael@0: michael@0: michael@0: class Base(object): michael@0: _mock_return_value = DEFAULT michael@0: _mock_side_effect = None michael@0: def __init__(self, *args, **kwargs): michael@0: pass michael@0: michael@0: michael@0: michael@0: class NonCallableMock(Base): michael@0: """A non-callable version of `Mock`""" michael@0: michael@0: def __new__(cls, *args, **kw): michael@0: # every instance has its own class michael@0: # so we can create magic methods on the michael@0: # class without stomping on other mocks michael@0: new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__}) michael@0: instance = object.__new__(new) michael@0: return instance michael@0: michael@0: michael@0: def __init__( michael@0: self, spec=None, wraps=None, name=None, spec_set=None, michael@0: parent=None, _spec_state=None, _new_name='', _new_parent=None, michael@0: **kwargs michael@0: ): michael@0: if _new_parent is None: michael@0: _new_parent = parent michael@0: michael@0: __dict__ = self.__dict__ michael@0: __dict__['_mock_parent'] = parent michael@0: __dict__['_mock_name'] = name michael@0: __dict__['_mock_new_name'] = _new_name michael@0: __dict__['_mock_new_parent'] = _new_parent michael@0: michael@0: if spec_set is not None: michael@0: spec = spec_set michael@0: spec_set = True michael@0: michael@0: self._mock_add_spec(spec, spec_set) michael@0: michael@0: __dict__['_mock_children'] = {} michael@0: __dict__['_mock_wraps'] = wraps michael@0: __dict__['_mock_delegate'] = None michael@0: michael@0: __dict__['_mock_called'] = False michael@0: __dict__['_mock_call_args'] = None michael@0: __dict__['_mock_call_count'] = 0 michael@0: __dict__['_mock_call_args_list'] = _CallList() michael@0: __dict__['_mock_mock_calls'] = _CallList() michael@0: michael@0: __dict__['method_calls'] = _CallList() michael@0: michael@0: if kwargs: michael@0: self.configure_mock(**kwargs) michael@0: michael@0: _super(NonCallableMock, self).__init__( michael@0: spec, wraps, name, spec_set, parent, michael@0: _spec_state michael@0: ) michael@0: michael@0: michael@0: def attach_mock(self, mock, attribute): michael@0: """ michael@0: Attach a mock as an attribute of this one, replacing its name and michael@0: parent. Calls to the attached mock will be recorded in the michael@0: `method_calls` and `mock_calls` attributes of this one.""" michael@0: mock._mock_parent = None michael@0: mock._mock_new_parent = None michael@0: mock._mock_name = '' michael@0: mock._mock_new_name = None michael@0: michael@0: setattr(self, attribute, mock) michael@0: michael@0: michael@0: def mock_add_spec(self, spec, spec_set=False): michael@0: """Add a spec to a mock. `spec` can either be an object or a michael@0: list of strings. Only attributes on the `spec` can be fetched as michael@0: attributes from the mock. michael@0: michael@0: If `spec_set` is True then only attributes on the spec can be set.""" michael@0: self._mock_add_spec(spec, spec_set) michael@0: michael@0: michael@0: def _mock_add_spec(self, spec, spec_set): michael@0: _spec_class = None michael@0: michael@0: if spec is not None and not _is_list(spec): michael@0: if isinstance(spec, ClassTypes): michael@0: _spec_class = spec michael@0: else: michael@0: _spec_class = _get_class(spec) michael@0: michael@0: spec = dir(spec) michael@0: michael@0: __dict__ = self.__dict__ michael@0: __dict__['_spec_class'] = _spec_class michael@0: __dict__['_spec_set'] = spec_set michael@0: __dict__['_mock_methods'] = spec michael@0: michael@0: michael@0: def __get_return_value(self): michael@0: ret = self._mock_return_value michael@0: if self._mock_delegate is not None: michael@0: ret = self._mock_delegate.return_value michael@0: michael@0: if ret is DEFAULT: michael@0: ret = self._get_child_mock( michael@0: _new_parent=self, _new_name='()' michael@0: ) michael@0: self.return_value = ret michael@0: return ret michael@0: michael@0: michael@0: def __set_return_value(self, value): michael@0: if self._mock_delegate is not None: michael@0: self._mock_delegate.return_value = value michael@0: else: michael@0: self._mock_return_value = value michael@0: _check_and_set_parent(self, value, None, '()') michael@0: michael@0: __return_value_doc = "The value to be returned when the mock is called." michael@0: return_value = property(__get_return_value, __set_return_value, michael@0: __return_value_doc) michael@0: michael@0: michael@0: @property michael@0: def __class__(self): michael@0: if self._spec_class is None: michael@0: return type(self) michael@0: return self._spec_class michael@0: michael@0: called = _delegating_property('called') michael@0: call_count = _delegating_property('call_count') michael@0: call_args = _delegating_property('call_args') michael@0: call_args_list = _delegating_property('call_args_list') michael@0: mock_calls = _delegating_property('mock_calls') michael@0: michael@0: michael@0: def __get_side_effect(self): michael@0: sig = self._mock_delegate michael@0: if sig is None: michael@0: return self._mock_side_effect michael@0: return sig.side_effect michael@0: michael@0: def __set_side_effect(self, value): michael@0: value = _try_iter(value) michael@0: sig = self._mock_delegate michael@0: if sig is None: michael@0: self._mock_side_effect = value michael@0: else: michael@0: sig.side_effect = value michael@0: michael@0: side_effect = property(__get_side_effect, __set_side_effect) michael@0: michael@0: michael@0: def reset_mock(self): michael@0: "Restore the mock object to its initial state." michael@0: self.called = False michael@0: self.call_args = None michael@0: self.call_count = 0 michael@0: self.mock_calls = _CallList() michael@0: self.call_args_list = _CallList() michael@0: self.method_calls = _CallList() michael@0: michael@0: for child in self._mock_children.values(): michael@0: if isinstance(child, _SpecState): michael@0: continue michael@0: child.reset_mock() michael@0: michael@0: ret = self._mock_return_value michael@0: if _is_instance_mock(ret) and ret is not self: michael@0: ret.reset_mock() michael@0: michael@0: michael@0: def configure_mock(self, **kwargs): michael@0: """Set attributes on the mock through keyword arguments. michael@0: michael@0: Attributes plus return values and side effects can be set on child michael@0: mocks using standard dot notation and unpacking a dictionary in the michael@0: method call: michael@0: michael@0: >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} michael@0: >>> mock.configure_mock(**attrs)""" michael@0: for arg, val in sorted(kwargs.items(), michael@0: # we sort on the number of dots so that michael@0: # attributes are set before we set attributes on michael@0: # attributes michael@0: key=lambda entry: entry[0].count('.')): michael@0: args = arg.split('.') michael@0: final = args.pop() michael@0: obj = self michael@0: for entry in args: michael@0: obj = getattr(obj, entry) michael@0: setattr(obj, final, val) michael@0: michael@0: michael@0: def __getattr__(self, name): michael@0: if name == '_mock_methods': michael@0: raise AttributeError(name) michael@0: elif self._mock_methods is not None: michael@0: if name not in self._mock_methods or name in _all_magics: michael@0: raise AttributeError("Mock object has no attribute %r" % name) michael@0: elif _is_magic(name): michael@0: raise AttributeError(name) michael@0: michael@0: result = self._mock_children.get(name) michael@0: if result is _deleted: michael@0: raise AttributeError(name) michael@0: elif result is None: michael@0: wraps = None michael@0: if self._mock_wraps is not None: michael@0: # XXXX should we get the attribute without triggering code michael@0: # execution? michael@0: wraps = getattr(self._mock_wraps, name) michael@0: michael@0: result = self._get_child_mock( michael@0: parent=self, name=name, wraps=wraps, _new_name=name, michael@0: _new_parent=self michael@0: ) michael@0: self._mock_children[name] = result michael@0: michael@0: elif isinstance(result, _SpecState): michael@0: result = create_autospec( michael@0: result.spec, result.spec_set, result.instance, michael@0: result.parent, result.name michael@0: ) michael@0: self._mock_children[name] = result michael@0: michael@0: return result michael@0: michael@0: michael@0: def __repr__(self): michael@0: _name_list = [self._mock_new_name] michael@0: _parent = self._mock_new_parent michael@0: last = self michael@0: michael@0: dot = '.' michael@0: if _name_list == ['()']: michael@0: dot = '' michael@0: seen = set() michael@0: while _parent is not None: michael@0: last = _parent michael@0: michael@0: _name_list.append(_parent._mock_new_name + dot) michael@0: dot = '.' michael@0: if _parent._mock_new_name == '()': michael@0: dot = '' michael@0: michael@0: _parent = _parent._mock_new_parent michael@0: michael@0: # use ids here so as not to call __hash__ on the mocks michael@0: if id(_parent) in seen: michael@0: break michael@0: seen.add(id(_parent)) michael@0: michael@0: _name_list = list(reversed(_name_list)) michael@0: _first = last._mock_name or 'mock' michael@0: if len(_name_list) > 1: michael@0: if _name_list[1] not in ('()', '().'): michael@0: _first += '.' michael@0: _name_list[0] = _first michael@0: name = ''.join(_name_list) michael@0: michael@0: name_string = '' michael@0: if name not in ('mock', 'mock.'): michael@0: name_string = ' name=%r' % name michael@0: michael@0: spec_string = '' michael@0: if self._spec_class is not None: michael@0: spec_string = ' spec=%r' michael@0: if self._spec_set: michael@0: spec_string = ' spec_set=%r' michael@0: spec_string = spec_string % self._spec_class.__name__ michael@0: return "<%s%s%s id='%s'>" % ( michael@0: type(self).__name__, michael@0: name_string, michael@0: spec_string, michael@0: id(self) michael@0: ) michael@0: michael@0: michael@0: def __dir__(self): michael@0: """Filter the output of `dir(mock)` to only useful members. michael@0: XXXX michael@0: """ michael@0: extras = self._mock_methods or [] michael@0: from_type = dir(type(self)) michael@0: from_dict = list(self.__dict__) michael@0: michael@0: if FILTER_DIR: michael@0: from_type = [e for e in from_type if not e.startswith('_')] michael@0: from_dict = [e for e in from_dict if not e.startswith('_') or michael@0: _is_magic(e)] michael@0: return sorted(set(extras + from_type + from_dict + michael@0: list(self._mock_children))) michael@0: michael@0: michael@0: def __setattr__(self, name, value): michael@0: if name in _allowed_names: michael@0: # property setters go through here michael@0: return object.__setattr__(self, name, value) michael@0: elif (self._spec_set and self._mock_methods is not None and michael@0: name not in self._mock_methods and michael@0: name not in self.__dict__): michael@0: raise AttributeError("Mock object has no attribute '%s'" % name) michael@0: elif name in _unsupported_magics: michael@0: msg = 'Attempting to set unsupported magic method %r.' % name michael@0: raise AttributeError(msg) michael@0: elif name in _all_magics: michael@0: if self._mock_methods is not None and name not in self._mock_methods: michael@0: raise AttributeError("Mock object has no attribute '%s'" % name) michael@0: michael@0: if not _is_instance_mock(value): michael@0: setattr(type(self), name, _get_method(name, value)) michael@0: original = value michael@0: value = lambda *args, **kw: original(self, *args, **kw) michael@0: else: michael@0: # only set _new_name and not name so that mock_calls is tracked michael@0: # but not method calls michael@0: _check_and_set_parent(self, value, None, name) michael@0: setattr(type(self), name, value) michael@0: self._mock_children[name] = value michael@0: elif name == '__class__': michael@0: self._spec_class = value michael@0: return michael@0: else: michael@0: if _check_and_set_parent(self, value, name, name): michael@0: self._mock_children[name] = value michael@0: return object.__setattr__(self, name, value) michael@0: michael@0: michael@0: def __delattr__(self, name): michael@0: if name in _all_magics and name in type(self).__dict__: michael@0: delattr(type(self), name) michael@0: if name not in self.__dict__: michael@0: # for magic methods that are still MagicProxy objects and michael@0: # not set on the instance itself michael@0: return michael@0: michael@0: if name in self.__dict__: michael@0: object.__delattr__(self, name) michael@0: michael@0: obj = self._mock_children.get(name, _missing) michael@0: if obj is _deleted: michael@0: raise AttributeError(name) michael@0: if obj is not _missing: michael@0: del self._mock_children[name] michael@0: self._mock_children[name] = _deleted michael@0: michael@0: michael@0: michael@0: def _format_mock_call_signature(self, args, kwargs): michael@0: name = self._mock_name or 'mock' michael@0: return _format_call_signature(name, args, kwargs) michael@0: michael@0: michael@0: def _format_mock_failure_message(self, args, kwargs): michael@0: message = 'Expected call: %s\nActual call: %s' michael@0: expected_string = self._format_mock_call_signature(args, kwargs) michael@0: call_args = self.call_args michael@0: if len(call_args) == 3: michael@0: call_args = call_args[1:] michael@0: actual_string = self._format_mock_call_signature(*call_args) michael@0: return message % (expected_string, actual_string) michael@0: michael@0: michael@0: def assert_called_with(_mock_self, *args, **kwargs): michael@0: """assert that the mock was called with the specified arguments. michael@0: michael@0: Raises an AssertionError if the args and keyword args passed in are michael@0: different to the last call to the mock.""" michael@0: self = _mock_self michael@0: if self.call_args is None: michael@0: expected = self._format_mock_call_signature(args, kwargs) michael@0: raise AssertionError('Expected call: %s\nNot called' % (expected,)) michael@0: michael@0: if self.call_args != (args, kwargs): michael@0: msg = self._format_mock_failure_message(args, kwargs) michael@0: raise AssertionError(msg) michael@0: michael@0: michael@0: def assert_called_once_with(_mock_self, *args, **kwargs): michael@0: """assert that the mock was called exactly once and with the specified michael@0: arguments.""" michael@0: self = _mock_self michael@0: if not self.call_count == 1: michael@0: msg = ("Expected to be called once. Called %s times." % michael@0: self.call_count) michael@0: raise AssertionError(msg) michael@0: return self.assert_called_with(*args, **kwargs) michael@0: michael@0: michael@0: def assert_has_calls(self, calls, any_order=False): michael@0: """assert the mock has been called with the specified calls. michael@0: The `mock_calls` list is checked for the calls. michael@0: michael@0: If `any_order` is False (the default) then the calls must be michael@0: sequential. There can be extra calls before or after the michael@0: specified calls. michael@0: michael@0: If `any_order` is True then the calls can be in any order, but michael@0: they must all appear in `mock_calls`.""" michael@0: if not any_order: michael@0: if calls not in self.mock_calls: michael@0: raise AssertionError( michael@0: 'Calls not found.\nExpected: %r\n' michael@0: 'Actual: %r' % (calls, self.mock_calls) michael@0: ) michael@0: return michael@0: michael@0: all_calls = list(self.mock_calls) michael@0: michael@0: not_found = [] michael@0: for kall in calls: michael@0: try: michael@0: all_calls.remove(kall) michael@0: except ValueError: michael@0: not_found.append(kall) michael@0: if not_found: michael@0: raise AssertionError( michael@0: '%r not all found in call list' % (tuple(not_found),) michael@0: ) michael@0: michael@0: michael@0: def assert_any_call(self, *args, **kwargs): michael@0: """assert the mock has been called with the specified arguments. michael@0: michael@0: The assert passes if the mock has *ever* been called, unlike michael@0: `assert_called_with` and `assert_called_once_with` that only pass if michael@0: the call is the most recent one.""" michael@0: kall = call(*args, **kwargs) michael@0: if kall not in self.call_args_list: michael@0: expected_string = self._format_mock_call_signature(args, kwargs) michael@0: raise AssertionError( michael@0: '%s call not found' % expected_string michael@0: ) michael@0: michael@0: michael@0: def _get_child_mock(self, **kw): michael@0: """Create the child mocks for attributes and return value. michael@0: By default child mocks will be the same type as the parent. michael@0: Subclasses of Mock may want to override this to customize the way michael@0: child mocks are made. michael@0: michael@0: For non-callable mocks the callable variant will be used (rather than michael@0: any custom subclass).""" michael@0: _type = type(self) michael@0: if not issubclass(_type, CallableMixin): michael@0: if issubclass(_type, NonCallableMagicMock): michael@0: klass = MagicMock michael@0: elif issubclass(_type, NonCallableMock) : michael@0: klass = Mock michael@0: else: michael@0: klass = _type.__mro__[1] michael@0: return klass(**kw) michael@0: michael@0: michael@0: michael@0: def _try_iter(obj): michael@0: if obj is None: michael@0: return obj michael@0: if _is_exception(obj): michael@0: return obj michael@0: if _callable(obj): michael@0: return obj michael@0: try: michael@0: return iter(obj) michael@0: except TypeError: michael@0: # XXXX backwards compatibility michael@0: # but this will blow up on first call - so maybe we should fail early? michael@0: return obj michael@0: michael@0: michael@0: michael@0: class CallableMixin(Base): michael@0: michael@0: def __init__(self, spec=None, side_effect=None, return_value=DEFAULT, michael@0: wraps=None, name=None, spec_set=None, parent=None, michael@0: _spec_state=None, _new_name='', _new_parent=None, **kwargs): michael@0: self.__dict__['_mock_return_value'] = return_value michael@0: michael@0: _super(CallableMixin, self).__init__( michael@0: spec, wraps, name, spec_set, parent, michael@0: _spec_state, _new_name, _new_parent, **kwargs michael@0: ) michael@0: michael@0: self.side_effect = side_effect michael@0: michael@0: michael@0: def _mock_check_sig(self, *args, **kwargs): michael@0: # stub method that can be replaced with one with a specific signature michael@0: pass michael@0: michael@0: michael@0: def __call__(_mock_self, *args, **kwargs): michael@0: # can't use self in-case a function / method we are mocking uses self michael@0: # in the signature michael@0: _mock_self._mock_check_sig(*args, **kwargs) michael@0: return _mock_self._mock_call(*args, **kwargs) michael@0: michael@0: michael@0: def _mock_call(_mock_self, *args, **kwargs): michael@0: self = _mock_self michael@0: self.called = True michael@0: self.call_count += 1 michael@0: self.call_args = _Call((args, kwargs), two=True) michael@0: self.call_args_list.append(_Call((args, kwargs), two=True)) michael@0: michael@0: _new_name = self._mock_new_name michael@0: _new_parent = self._mock_new_parent michael@0: self.mock_calls.append(_Call(('', args, kwargs))) michael@0: michael@0: seen = set() michael@0: skip_next_dot = _new_name == '()' michael@0: do_method_calls = self._mock_parent is not None michael@0: name = self._mock_name michael@0: while _new_parent is not None: michael@0: this_mock_call = _Call((_new_name, args, kwargs)) michael@0: if _new_parent._mock_new_name: michael@0: dot = '.' michael@0: if skip_next_dot: michael@0: dot = '' michael@0: michael@0: skip_next_dot = False michael@0: if _new_parent._mock_new_name == '()': michael@0: skip_next_dot = True michael@0: michael@0: _new_name = _new_parent._mock_new_name + dot + _new_name michael@0: michael@0: if do_method_calls: michael@0: if _new_name == name: michael@0: this_method_call = this_mock_call michael@0: else: michael@0: this_method_call = _Call((name, args, kwargs)) michael@0: _new_parent.method_calls.append(this_method_call) michael@0: michael@0: do_method_calls = _new_parent._mock_parent is not None michael@0: if do_method_calls: michael@0: name = _new_parent._mock_name + '.' + name michael@0: michael@0: _new_parent.mock_calls.append(this_mock_call) michael@0: _new_parent = _new_parent._mock_new_parent michael@0: michael@0: # use ids here so as not to call __hash__ on the mocks michael@0: _new_parent_id = id(_new_parent) michael@0: if _new_parent_id in seen: michael@0: break michael@0: seen.add(_new_parent_id) michael@0: michael@0: ret_val = DEFAULT michael@0: effect = self.side_effect michael@0: if effect is not None: michael@0: if _is_exception(effect): michael@0: raise effect michael@0: michael@0: if not _callable(effect): michael@0: result = next(effect) michael@0: if _is_exception(result): michael@0: raise result michael@0: return result michael@0: michael@0: ret_val = effect(*args, **kwargs) michael@0: if ret_val is DEFAULT: michael@0: ret_val = self.return_value michael@0: michael@0: if (self._mock_wraps is not None and michael@0: self._mock_return_value is DEFAULT): michael@0: return self._mock_wraps(*args, **kwargs) michael@0: if ret_val is DEFAULT: michael@0: ret_val = self.return_value michael@0: return ret_val michael@0: michael@0: michael@0: michael@0: class Mock(CallableMixin, NonCallableMock): michael@0: """ michael@0: Create a new `Mock` object. `Mock` takes several optional arguments michael@0: that specify the behaviour of the Mock object: michael@0: michael@0: * `spec`: This can be either a list of strings or an existing object (a michael@0: class or instance) that acts as the specification for the mock object. If michael@0: you pass in an object then a list of strings is formed by calling dir on michael@0: the object (excluding unsupported magic attributes and methods). Accessing michael@0: any attribute not in this list will raise an `AttributeError`. michael@0: michael@0: If `spec` is an object (rather than a list of strings) then michael@0: `mock.__class__` returns the class of the spec object. This allows mocks michael@0: to pass `isinstance` tests. michael@0: michael@0: * `spec_set`: A stricter variant of `spec`. If used, attempting to *set* michael@0: or get an attribute on the mock that isn't on the object passed as michael@0: `spec_set` will raise an `AttributeError`. michael@0: michael@0: * `side_effect`: A function to be called whenever the Mock is called. See michael@0: the `side_effect` attribute. Useful for raising exceptions or michael@0: dynamically changing return values. The function is called with the same michael@0: arguments as the mock, and unless it returns `DEFAULT`, the return michael@0: value of this function is used as the return value. michael@0: michael@0: Alternatively `side_effect` can be an exception class or instance. In michael@0: this case the exception will be raised when the mock is called. michael@0: michael@0: If `side_effect` is an iterable then each call to the mock will return michael@0: the next value from the iterable. If any of the members of the iterable michael@0: are exceptions they will be raised instead of returned. michael@0: michael@0: * `return_value`: The value returned when the mock is called. By default michael@0: this is a new Mock (created on first access). See the michael@0: `return_value` attribute. michael@0: michael@0: * `wraps`: Item for the mock object to wrap. If `wraps` is not None then michael@0: calling the Mock will pass the call through to the wrapped object michael@0: (returning the real result). Attribute access on the mock will return a michael@0: Mock object that wraps the corresponding attribute of the wrapped object michael@0: (so attempting to access an attribute that doesn't exist will raise an michael@0: `AttributeError`). michael@0: michael@0: If the mock has an explicit `return_value` set then calls are not passed michael@0: to the wrapped object and the `return_value` is returned instead. michael@0: michael@0: * `name`: If the mock has a name then it will be used in the repr of the michael@0: mock. This can be useful for debugging. The name is propagated to child michael@0: mocks. michael@0: michael@0: Mocks can also be called with arbitrary keyword arguments. These will be michael@0: used to set attributes on the mock after it is created. michael@0: """ michael@0: michael@0: michael@0: michael@0: def _dot_lookup(thing, comp, import_path): michael@0: try: michael@0: return getattr(thing, comp) michael@0: except AttributeError: michael@0: __import__(import_path) michael@0: return getattr(thing, comp) michael@0: michael@0: michael@0: def _importer(target): michael@0: components = target.split('.') michael@0: import_path = components.pop(0) michael@0: thing = __import__(import_path) michael@0: michael@0: for comp in components: michael@0: import_path += ".%s" % comp michael@0: thing = _dot_lookup(thing, comp, import_path) michael@0: return thing michael@0: michael@0: michael@0: def _is_started(patcher): michael@0: # XXXX horrible michael@0: return hasattr(patcher, 'is_local') michael@0: michael@0: michael@0: class _patch(object): michael@0: michael@0: attribute_name = None michael@0: _active_patches = set() michael@0: michael@0: def __init__( michael@0: self, getter, attribute, new, spec, create, michael@0: spec_set, autospec, new_callable, kwargs michael@0: ): michael@0: if new_callable is not None: michael@0: if new is not DEFAULT: michael@0: raise ValueError( michael@0: "Cannot use 'new' and 'new_callable' together" michael@0: ) michael@0: if autospec is not None: michael@0: raise ValueError( michael@0: "Cannot use 'autospec' and 'new_callable' together" michael@0: ) michael@0: michael@0: self.getter = getter michael@0: self.attribute = attribute michael@0: self.new = new michael@0: self.new_callable = new_callable michael@0: self.spec = spec michael@0: self.create = create michael@0: self.has_local = False michael@0: self.spec_set = spec_set michael@0: self.autospec = autospec michael@0: self.kwargs = kwargs michael@0: self.additional_patchers = [] michael@0: michael@0: michael@0: def copy(self): michael@0: patcher = _patch( michael@0: self.getter, self.attribute, self.new, self.spec, michael@0: self.create, self.spec_set, michael@0: self.autospec, self.new_callable, self.kwargs michael@0: ) michael@0: patcher.attribute_name = self.attribute_name michael@0: patcher.additional_patchers = [ michael@0: p.copy() for p in self.additional_patchers michael@0: ] michael@0: return patcher michael@0: michael@0: michael@0: def __call__(self, func): michael@0: if isinstance(func, ClassTypes): michael@0: return self.decorate_class(func) michael@0: return self.decorate_callable(func) michael@0: michael@0: michael@0: def decorate_class(self, klass): michael@0: for attr in dir(klass): michael@0: if not attr.startswith(patch.TEST_PREFIX): michael@0: continue michael@0: michael@0: attr_value = getattr(klass, attr) michael@0: if not hasattr(attr_value, "__call__"): michael@0: continue michael@0: michael@0: patcher = self.copy() michael@0: setattr(klass, attr, patcher(attr_value)) michael@0: return klass michael@0: michael@0: michael@0: def decorate_callable(self, func): michael@0: if hasattr(func, 'patchings'): michael@0: func.patchings.append(self) michael@0: return func michael@0: michael@0: @wraps(func) michael@0: def patched(*args, **keywargs): michael@0: # don't use a with here (backwards compatability with Python 2.4) michael@0: extra_args = [] michael@0: entered_patchers = [] michael@0: michael@0: # can't use try...except...finally because of Python 2.4 michael@0: # compatibility michael@0: exc_info = tuple() michael@0: try: michael@0: try: michael@0: for patching in patched.patchings: michael@0: arg = patching.__enter__() michael@0: entered_patchers.append(patching) michael@0: if patching.attribute_name is not None: michael@0: keywargs.update(arg) michael@0: elif patching.new is DEFAULT: michael@0: extra_args.append(arg) michael@0: michael@0: args += tuple(extra_args) michael@0: return func(*args, **keywargs) michael@0: except: michael@0: if (patching not in entered_patchers and michael@0: _is_started(patching)): michael@0: # the patcher may have been started, but an exception michael@0: # raised whilst entering one of its additional_patchers michael@0: entered_patchers.append(patching) michael@0: # Pass the exception to __exit__ michael@0: exc_info = sys.exc_info() michael@0: # re-raise the exception michael@0: raise michael@0: finally: michael@0: for patching in reversed(entered_patchers): michael@0: patching.__exit__(*exc_info) michael@0: michael@0: patched.patchings = [self] michael@0: if hasattr(func, 'func_code'): michael@0: # not in Python 3 michael@0: patched.compat_co_firstlineno = getattr( michael@0: func, "compat_co_firstlineno", michael@0: func.func_code.co_firstlineno michael@0: ) michael@0: return patched michael@0: michael@0: michael@0: def get_original(self): michael@0: target = self.getter() michael@0: name = self.attribute michael@0: michael@0: original = DEFAULT michael@0: local = False michael@0: michael@0: try: michael@0: original = target.__dict__[name] michael@0: except (AttributeError, KeyError): michael@0: original = getattr(target, name, DEFAULT) michael@0: else: michael@0: local = True michael@0: michael@0: if not self.create and original is DEFAULT: michael@0: raise AttributeError( michael@0: "%s does not have the attribute %r" % (target, name) michael@0: ) michael@0: return original, local michael@0: michael@0: michael@0: def __enter__(self): michael@0: """Perform the patch.""" michael@0: new, spec, spec_set = self.new, self.spec, self.spec_set michael@0: autospec, kwargs = self.autospec, self.kwargs michael@0: new_callable = self.new_callable michael@0: self.target = self.getter() michael@0: michael@0: # normalise False to None michael@0: if spec is False: michael@0: spec = None michael@0: if spec_set is False: michael@0: spec_set = None michael@0: if autospec is False: michael@0: autospec = None michael@0: michael@0: if spec is not None and autospec is not None: michael@0: raise TypeError("Can't specify spec and autospec") michael@0: if ((spec is not None or autospec is not None) and michael@0: spec_set not in (True, None)): michael@0: raise TypeError("Can't provide explicit spec_set *and* spec or autospec") michael@0: michael@0: original, local = self.get_original() michael@0: michael@0: if new is DEFAULT and autospec is None: michael@0: inherit = False michael@0: if spec is True: michael@0: # set spec to the object we are replacing michael@0: spec = original michael@0: if spec_set is True: michael@0: spec_set = original michael@0: spec = None michael@0: elif spec is not None: michael@0: if spec_set is True: michael@0: spec_set = spec michael@0: spec = None michael@0: elif spec_set is True: michael@0: spec_set = original michael@0: michael@0: if spec is not None or spec_set is not None: michael@0: if original is DEFAULT: michael@0: raise TypeError("Can't use 'spec' with create=True") michael@0: if isinstance(original, ClassTypes): michael@0: # If we're patching out a class and there is a spec michael@0: inherit = True michael@0: michael@0: Klass = MagicMock michael@0: _kwargs = {} michael@0: if new_callable is not None: michael@0: Klass = new_callable michael@0: elif spec is not None or spec_set is not None: michael@0: this_spec = spec michael@0: if spec_set is not None: michael@0: this_spec = spec_set michael@0: if _is_list(this_spec): michael@0: not_callable = '__call__' not in this_spec michael@0: else: michael@0: not_callable = not _callable(this_spec) michael@0: if not_callable: michael@0: Klass = NonCallableMagicMock michael@0: michael@0: if spec is not None: michael@0: _kwargs['spec'] = spec michael@0: if spec_set is not None: michael@0: _kwargs['spec_set'] = spec_set michael@0: michael@0: # add a name to mocks michael@0: if (isinstance(Klass, type) and michael@0: issubclass(Klass, NonCallableMock) and self.attribute): michael@0: _kwargs['name'] = self.attribute michael@0: michael@0: _kwargs.update(kwargs) michael@0: new = Klass(**_kwargs) michael@0: michael@0: if inherit and _is_instance_mock(new): michael@0: # we can only tell if the instance should be callable if the michael@0: # spec is not a list michael@0: this_spec = spec michael@0: if spec_set is not None: michael@0: this_spec = spec_set michael@0: if (not _is_list(this_spec) and not michael@0: _instance_callable(this_spec)): michael@0: Klass = NonCallableMagicMock michael@0: michael@0: _kwargs.pop('name') michael@0: new.return_value = Klass(_new_parent=new, _new_name='()', michael@0: **_kwargs) michael@0: elif autospec is not None: michael@0: # spec is ignored, new *must* be default, spec_set is treated michael@0: # as a boolean. Should we check spec is not None and that spec_set michael@0: # is a bool? michael@0: if new is not DEFAULT: michael@0: raise TypeError( michael@0: "autospec creates the mock for you. Can't specify " michael@0: "autospec and new." michael@0: ) michael@0: if original is DEFAULT: michael@0: raise TypeError("Can't use 'autospec' with create=True") michael@0: spec_set = bool(spec_set) michael@0: if autospec is True: michael@0: autospec = original michael@0: michael@0: new = create_autospec(autospec, spec_set=spec_set, michael@0: _name=self.attribute, **kwargs) michael@0: elif kwargs: michael@0: # can't set keyword args when we aren't creating the mock michael@0: # XXXX If new is a Mock we could call new.configure_mock(**kwargs) michael@0: raise TypeError("Can't pass kwargs to a mock we aren't creating") michael@0: michael@0: new_attr = new michael@0: michael@0: self.temp_original = original michael@0: self.is_local = local michael@0: setattr(self.target, self.attribute, new_attr) michael@0: if self.attribute_name is not None: michael@0: extra_args = {} michael@0: if self.new is DEFAULT: michael@0: extra_args[self.attribute_name] = new michael@0: for patching in self.additional_patchers: michael@0: arg = patching.__enter__() michael@0: if patching.new is DEFAULT: michael@0: extra_args.update(arg) michael@0: return extra_args michael@0: michael@0: return new michael@0: michael@0: michael@0: def __exit__(self, *exc_info): michael@0: """Undo the patch.""" michael@0: if not _is_started(self): michael@0: raise RuntimeError('stop called on unstarted patcher') michael@0: michael@0: if self.is_local and self.temp_original is not DEFAULT: michael@0: setattr(self.target, self.attribute, self.temp_original) michael@0: else: michael@0: delattr(self.target, self.attribute) michael@0: if not self.create and not hasattr(self.target, self.attribute): michael@0: # needed for proxy objects like django settings michael@0: setattr(self.target, self.attribute, self.temp_original) michael@0: michael@0: del self.temp_original michael@0: del self.is_local michael@0: del self.target michael@0: for patcher in reversed(self.additional_patchers): michael@0: if _is_started(patcher): michael@0: patcher.__exit__(*exc_info) michael@0: michael@0: michael@0: def start(self): michael@0: """Activate a patch, returning any created mock.""" michael@0: result = self.__enter__() michael@0: self._active_patches.add(self) michael@0: return result michael@0: michael@0: michael@0: def stop(self): michael@0: """Stop an active patch.""" michael@0: self._active_patches.discard(self) michael@0: return self.__exit__() michael@0: michael@0: michael@0: michael@0: def _get_target(target): michael@0: try: michael@0: target, attribute = target.rsplit('.', 1) michael@0: except (TypeError, ValueError): michael@0: raise TypeError("Need a valid target to patch. You supplied: %r" % michael@0: (target,)) michael@0: getter = lambda: _importer(target) michael@0: return getter, attribute michael@0: michael@0: michael@0: def _patch_object( michael@0: target, attribute, new=DEFAULT, spec=None, michael@0: create=False, spec_set=None, autospec=None, michael@0: new_callable=None, **kwargs michael@0: ): michael@0: """ michael@0: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, michael@0: spec_set=None, autospec=None, new_callable=None, **kwargs) michael@0: michael@0: patch the named member (`attribute`) on an object (`target`) with a mock michael@0: object. michael@0: michael@0: `patch.object` can be used as a decorator, class decorator or a context michael@0: manager. Arguments `new`, `spec`, `create`, `spec_set`, michael@0: `autospec` and `new_callable` have the same meaning as for `patch`. Like michael@0: `patch`, `patch.object` takes arbitrary keyword arguments for configuring michael@0: the mock object it creates. michael@0: michael@0: When used as a class decorator `patch.object` honours `patch.TEST_PREFIX` michael@0: for choosing which methods to wrap. michael@0: """ michael@0: getter = lambda: target michael@0: return _patch( michael@0: getter, attribute, new, spec, create, michael@0: spec_set, autospec, new_callable, kwargs michael@0: ) michael@0: michael@0: michael@0: def _patch_multiple(target, spec=None, create=False, spec_set=None, michael@0: autospec=None, new_callable=None, **kwargs): michael@0: """Perform multiple patches in a single call. It takes the object to be michael@0: patched (either as an object or a string to fetch the object by importing) michael@0: and keyword arguments for the patches:: michael@0: michael@0: with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'): michael@0: ... michael@0: michael@0: Use `DEFAULT` as the value if you want `patch.multiple` to create michael@0: mocks for you. In this case the created mocks are passed into a decorated michael@0: function by keyword, and a dictionary is returned when `patch.multiple` is michael@0: used as a context manager. michael@0: michael@0: `patch.multiple` can be used as a decorator, class decorator or a context michael@0: manager. The arguments `spec`, `spec_set`, `create`, michael@0: `autospec` and `new_callable` have the same meaning as for `patch`. These michael@0: arguments will be applied to *all* patches done by `patch.multiple`. michael@0: michael@0: When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX` michael@0: for choosing which methods to wrap. michael@0: """ michael@0: if type(target) in (unicode, str): michael@0: getter = lambda: _importer(target) michael@0: else: michael@0: getter = lambda: target michael@0: michael@0: if not kwargs: michael@0: raise ValueError( michael@0: 'Must supply at least one keyword argument with patch.multiple' michael@0: ) michael@0: # need to wrap in a list for python 3, where items is a view michael@0: items = list(kwargs.items()) michael@0: attribute, new = items[0] michael@0: patcher = _patch( michael@0: getter, attribute, new, spec, create, spec_set, michael@0: autospec, new_callable, {} michael@0: ) michael@0: patcher.attribute_name = attribute michael@0: for attribute, new in items[1:]: michael@0: this_patcher = _patch( michael@0: getter, attribute, new, spec, create, spec_set, michael@0: autospec, new_callable, {} michael@0: ) michael@0: this_patcher.attribute_name = attribute michael@0: patcher.additional_patchers.append(this_patcher) michael@0: return patcher michael@0: michael@0: michael@0: def patch( michael@0: target, new=DEFAULT, spec=None, create=False, michael@0: spec_set=None, autospec=None, new_callable=None, **kwargs michael@0: ): michael@0: """ michael@0: `patch` acts as a function decorator, class decorator or a context michael@0: manager. Inside the body of the function or with statement, the `target` michael@0: is patched with a `new` object. When the function/with statement exits michael@0: the patch is undone. michael@0: michael@0: If `new` is omitted, then the target is replaced with a michael@0: `MagicMock`. If `patch` is used as a decorator and `new` is michael@0: omitted, the created mock is passed in as an extra argument to the michael@0: decorated function. If `patch` is used as a context manager the created michael@0: mock is returned by the context manager. michael@0: michael@0: `target` should be a string in the form `'package.module.ClassName'`. The michael@0: `target` is imported and the specified object replaced with the `new` michael@0: object, so the `target` must be importable from the environment you are michael@0: calling `patch` from. The target is imported when the decorated function michael@0: is executed, not at decoration time. michael@0: michael@0: The `spec` and `spec_set` keyword arguments are passed to the `MagicMock` michael@0: if patch is creating one for you. michael@0: michael@0: In addition you can pass `spec=True` or `spec_set=True`, which causes michael@0: patch to pass in the object being mocked as the spec/spec_set object. michael@0: michael@0: `new_callable` allows you to specify a different class, or callable object, michael@0: that will be called to create the `new` object. By default `MagicMock` is michael@0: used. michael@0: michael@0: A more powerful form of `spec` is `autospec`. If you set `autospec=True` michael@0: then the mock with be created with a spec from the object being replaced. michael@0: All attributes of the mock will also have the spec of the corresponding michael@0: attribute of the object being replaced. Methods and functions being michael@0: mocked will have their arguments checked and will raise a `TypeError` if michael@0: they are called with the wrong signature. For mocks replacing a class, michael@0: their return value (the 'instance') will have the same spec as the class. michael@0: michael@0: Instead of `autospec=True` you can pass `autospec=some_object` to use an michael@0: arbitrary object as the spec instead of the one being replaced. michael@0: michael@0: By default `patch` will fail to replace attributes that don't exist. If michael@0: you pass in `create=True`, and the attribute doesn't exist, patch will michael@0: create the attribute for you when the patched function is called, and michael@0: delete it again afterwards. This is useful for writing tests against michael@0: attributes that your production code creates at runtime. It is off by by michael@0: default because it can be dangerous. With it switched on you can write michael@0: passing tests against APIs that don't actually exist! michael@0: michael@0: Patch can be used as a `TestCase` class decorator. It works by michael@0: decorating each test method in the class. This reduces the boilerplate michael@0: code when your test methods share a common patchings set. `patch` finds michael@0: tests by looking for method names that start with `patch.TEST_PREFIX`. michael@0: By default this is `test`, which matches the way `unittest` finds tests. michael@0: You can specify an alternative prefix by setting `patch.TEST_PREFIX`. michael@0: michael@0: Patch can be used as a context manager, with the with statement. Here the michael@0: patching applies to the indented block after the with statement. If you michael@0: use "as" then the patched object will be bound to the name after the michael@0: "as"; very useful if `patch` is creating a mock object for you. michael@0: michael@0: `patch` takes arbitrary keyword arguments. These will be passed to michael@0: the `Mock` (or `new_callable`) on construction. michael@0: michael@0: `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are michael@0: available for alternate use-cases. michael@0: """ michael@0: getter, attribute = _get_target(target) michael@0: return _patch( michael@0: getter, attribute, new, spec, create, michael@0: spec_set, autospec, new_callable, kwargs michael@0: ) michael@0: michael@0: michael@0: class _patch_dict(object): michael@0: """ michael@0: Patch a dictionary, or dictionary like object, and restore the dictionary michael@0: to its original state after the test. michael@0: michael@0: `in_dict` can be a dictionary or a mapping like container. If it is a michael@0: mapping then it must at least support getting, setting and deleting items michael@0: plus iterating over keys. michael@0: michael@0: `in_dict` can also be a string specifying the name of the dictionary, which michael@0: will then be fetched by importing it. michael@0: michael@0: `values` can be a dictionary of values to set in the dictionary. `values` michael@0: can also be an iterable of `(key, value)` pairs. michael@0: michael@0: If `clear` is True then the dictionary will be cleared before the new michael@0: values are set. michael@0: michael@0: `patch.dict` can also be called with arbitrary keyword arguments to set michael@0: values in the dictionary:: michael@0: michael@0: with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()): michael@0: ... michael@0: michael@0: `patch.dict` can be used as a context manager, decorator or class michael@0: decorator. When used as a class decorator `patch.dict` honours michael@0: `patch.TEST_PREFIX` for choosing which methods to wrap. michael@0: """ michael@0: michael@0: def __init__(self, in_dict, values=(), clear=False, **kwargs): michael@0: if isinstance(in_dict, basestring): michael@0: in_dict = _importer(in_dict) michael@0: self.in_dict = in_dict michael@0: # support any argument supported by dict(...) constructor michael@0: self.values = dict(values) michael@0: self.values.update(kwargs) michael@0: self.clear = clear michael@0: self._original = None michael@0: michael@0: michael@0: def __call__(self, f): michael@0: if isinstance(f, ClassTypes): michael@0: return self.decorate_class(f) michael@0: @wraps(f) michael@0: def _inner(*args, **kw): michael@0: self._patch_dict() michael@0: try: michael@0: return f(*args, **kw) michael@0: finally: michael@0: self._unpatch_dict() michael@0: michael@0: return _inner michael@0: michael@0: michael@0: def decorate_class(self, klass): michael@0: for attr in dir(klass): michael@0: attr_value = getattr(klass, attr) michael@0: if (attr.startswith(patch.TEST_PREFIX) and michael@0: hasattr(attr_value, "__call__")): michael@0: decorator = _patch_dict(self.in_dict, self.values, self.clear) michael@0: decorated = decorator(attr_value) michael@0: setattr(klass, attr, decorated) michael@0: return klass michael@0: michael@0: michael@0: def __enter__(self): michael@0: """Patch the dict.""" michael@0: self._patch_dict() michael@0: michael@0: michael@0: def _patch_dict(self): michael@0: values = self.values michael@0: in_dict = self.in_dict michael@0: clear = self.clear michael@0: michael@0: try: michael@0: original = in_dict.copy() michael@0: except AttributeError: michael@0: # dict like object with no copy method michael@0: # must support iteration over keys michael@0: original = {} michael@0: for key in in_dict: michael@0: original[key] = in_dict[key] michael@0: self._original = original michael@0: michael@0: if clear: michael@0: _clear_dict(in_dict) michael@0: michael@0: try: michael@0: in_dict.update(values) michael@0: except AttributeError: michael@0: # dict like object with no update method michael@0: for key in values: michael@0: in_dict[key] = values[key] michael@0: michael@0: michael@0: def _unpatch_dict(self): michael@0: in_dict = self.in_dict michael@0: original = self._original michael@0: michael@0: _clear_dict(in_dict) michael@0: michael@0: try: michael@0: in_dict.update(original) michael@0: except AttributeError: michael@0: for key in original: michael@0: in_dict[key] = original[key] michael@0: michael@0: michael@0: def __exit__(self, *args): michael@0: """Unpatch the dict.""" michael@0: self._unpatch_dict() michael@0: return False michael@0: michael@0: start = __enter__ michael@0: stop = __exit__ michael@0: michael@0: michael@0: def _clear_dict(in_dict): michael@0: try: michael@0: in_dict.clear() michael@0: except AttributeError: michael@0: keys = list(in_dict) michael@0: for key in keys: michael@0: del in_dict[key] michael@0: michael@0: michael@0: def _patch_stopall(): michael@0: """Stop all active patches.""" michael@0: for patch in list(_patch._active_patches): michael@0: patch.stop() michael@0: michael@0: michael@0: patch.object = _patch_object michael@0: patch.dict = _patch_dict michael@0: patch.multiple = _patch_multiple michael@0: patch.stopall = _patch_stopall michael@0: patch.TEST_PREFIX = 'test' michael@0: michael@0: magic_methods = ( michael@0: "lt le gt ge eq ne " michael@0: "getitem setitem delitem " michael@0: "len contains iter " michael@0: "hash str sizeof " michael@0: "enter exit " michael@0: "divmod neg pos abs invert " michael@0: "complex int float index " michael@0: "trunc floor ceil " michael@0: ) michael@0: michael@0: numerics = "add sub mul div floordiv mod lshift rshift and xor or pow " michael@0: inplace = ' '.join('i%s' % n for n in numerics.split()) michael@0: right = ' '.join('r%s' % n for n in numerics.split()) michael@0: extra = '' michael@0: if inPy3k: michael@0: extra = 'bool next ' michael@0: else: michael@0: extra = 'unicode long nonzero oct hex truediv rtruediv ' michael@0: michael@0: # not including __prepare__, __instancecheck__, __subclasscheck__ michael@0: # (as they are metaclass methods) michael@0: # __del__ is not supported at all as it causes problems if it exists michael@0: michael@0: _non_defaults = set('__%s__' % method for method in [ michael@0: 'cmp', 'getslice', 'setslice', 'coerce', 'subclasses', michael@0: 'format', 'get', 'set', 'delete', 'reversed', michael@0: 'missing', 'reduce', 'reduce_ex', 'getinitargs', michael@0: 'getnewargs', 'getstate', 'setstate', 'getformat', michael@0: 'setformat', 'repr', 'dir' michael@0: ]) michael@0: michael@0: michael@0: def _get_method(name, func): michael@0: "Turns a callable object (like a mock) into a real function" michael@0: def method(self, *args, **kw): michael@0: return func(self, *args, **kw) michael@0: method.__name__ = name michael@0: return method michael@0: michael@0: michael@0: _magics = set( michael@0: '__%s__' % method for method in michael@0: ' '.join([magic_methods, numerics, inplace, right, extra]).split() michael@0: ) michael@0: michael@0: _all_magics = _magics | _non_defaults michael@0: michael@0: _unsupported_magics = set([ michael@0: '__getattr__', '__setattr__', michael@0: '__init__', '__new__', '__prepare__' michael@0: '__instancecheck__', '__subclasscheck__', michael@0: '__del__' michael@0: ]) michael@0: michael@0: _calculate_return_value = { michael@0: '__hash__': lambda self: object.__hash__(self), michael@0: '__str__': lambda self: object.__str__(self), michael@0: '__sizeof__': lambda self: object.__sizeof__(self), michael@0: '__unicode__': lambda self: unicode(object.__str__(self)), michael@0: } michael@0: michael@0: _return_values = { michael@0: '__lt__': NotImplemented, michael@0: '__gt__': NotImplemented, michael@0: '__le__': NotImplemented, michael@0: '__ge__': NotImplemented, michael@0: '__int__': 1, michael@0: '__contains__': False, michael@0: '__len__': 0, michael@0: '__exit__': False, michael@0: '__complex__': 1j, michael@0: '__float__': 1.0, michael@0: '__bool__': True, michael@0: '__nonzero__': True, michael@0: '__oct__': '1', michael@0: '__hex__': '0x1', michael@0: '__long__': long(1), michael@0: '__index__': 1, michael@0: } michael@0: michael@0: michael@0: def _get_eq(self): michael@0: def __eq__(other): michael@0: ret_val = self.__eq__._mock_return_value michael@0: if ret_val is not DEFAULT: michael@0: return ret_val michael@0: return self is other michael@0: return __eq__ michael@0: michael@0: def _get_ne(self): michael@0: def __ne__(other): michael@0: if self.__ne__._mock_return_value is not DEFAULT: michael@0: return DEFAULT michael@0: return self is not other michael@0: return __ne__ michael@0: michael@0: def _get_iter(self): michael@0: def __iter__(): michael@0: ret_val = self.__iter__._mock_return_value michael@0: if ret_val is DEFAULT: michael@0: return iter([]) michael@0: # if ret_val was already an iterator, then calling iter on it should michael@0: # return the iterator unchanged michael@0: return iter(ret_val) michael@0: return __iter__ michael@0: michael@0: _side_effect_methods = { michael@0: '__eq__': _get_eq, michael@0: '__ne__': _get_ne, michael@0: '__iter__': _get_iter, michael@0: } michael@0: michael@0: michael@0: michael@0: def _set_return_value(mock, method, name): michael@0: fixed = _return_values.get(name, DEFAULT) michael@0: if fixed is not DEFAULT: michael@0: method.return_value = fixed michael@0: return michael@0: michael@0: return_calulator = _calculate_return_value.get(name) michael@0: if return_calulator is not None: michael@0: try: michael@0: return_value = return_calulator(mock) michael@0: except AttributeError: michael@0: # XXXX why do we return AttributeError here? michael@0: # set it as a side_effect instead? michael@0: return_value = AttributeError(name) michael@0: method.return_value = return_value michael@0: return michael@0: michael@0: side_effector = _side_effect_methods.get(name) michael@0: if side_effector is not None: michael@0: method.side_effect = side_effector(mock) michael@0: michael@0: michael@0: michael@0: class MagicMixin(object): michael@0: def __init__(self, *args, **kw): michael@0: _super(MagicMixin, self).__init__(*args, **kw) michael@0: self._mock_set_magics() michael@0: michael@0: michael@0: def _mock_set_magics(self): michael@0: these_magics = _magics michael@0: michael@0: if self._mock_methods is not None: michael@0: these_magics = _magics.intersection(self._mock_methods) michael@0: michael@0: remove_magics = set() michael@0: remove_magics = _magics - these_magics michael@0: michael@0: for entry in remove_magics: michael@0: if entry in type(self).__dict__: michael@0: # remove unneeded magic methods michael@0: delattr(self, entry) michael@0: michael@0: # don't overwrite existing attributes if called a second time michael@0: these_magics = these_magics - set(type(self).__dict__) michael@0: michael@0: _type = type(self) michael@0: for entry in these_magics: michael@0: setattr(_type, entry, MagicProxy(entry, self)) michael@0: michael@0: michael@0: michael@0: class NonCallableMagicMock(MagicMixin, NonCallableMock): michael@0: """A version of `MagicMock` that isn't callable.""" michael@0: def mock_add_spec(self, spec, spec_set=False): michael@0: """Add a spec to a mock. `spec` can either be an object or a michael@0: list of strings. Only attributes on the `spec` can be fetched as michael@0: attributes from the mock. michael@0: michael@0: If `spec_set` is True then only attributes on the spec can be set.""" michael@0: self._mock_add_spec(spec, spec_set) michael@0: self._mock_set_magics() michael@0: michael@0: michael@0: michael@0: class MagicMock(MagicMixin, Mock): michael@0: """ michael@0: MagicMock is a subclass of Mock with default implementations michael@0: of most of the magic methods. You can use MagicMock without having to michael@0: configure the magic methods yourself. michael@0: michael@0: If you use the `spec` or `spec_set` arguments then *only* magic michael@0: methods that exist in the spec will be created. michael@0: michael@0: Attributes and the return value of a `MagicMock` will also be `MagicMocks`. michael@0: """ michael@0: def mock_add_spec(self, spec, spec_set=False): michael@0: """Add a spec to a mock. `spec` can either be an object or a michael@0: list of strings. Only attributes on the `spec` can be fetched as michael@0: attributes from the mock. michael@0: michael@0: If `spec_set` is True then only attributes on the spec can be set.""" michael@0: self._mock_add_spec(spec, spec_set) michael@0: self._mock_set_magics() michael@0: michael@0: michael@0: michael@0: class MagicProxy(object): michael@0: def __init__(self, name, parent): michael@0: self.name = name michael@0: self.parent = parent michael@0: michael@0: def __call__(self, *args, **kwargs): michael@0: m = self.create_mock() michael@0: return m(*args, **kwargs) michael@0: michael@0: def create_mock(self): michael@0: entry = self.name michael@0: parent = self.parent michael@0: m = parent._get_child_mock(name=entry, _new_name=entry, michael@0: _new_parent=parent) michael@0: setattr(parent, entry, m) michael@0: _set_return_value(parent, m, entry) michael@0: return m michael@0: michael@0: def __get__(self, obj, _type=None): michael@0: return self.create_mock() michael@0: michael@0: michael@0: michael@0: class _ANY(object): michael@0: "A helper object that compares equal to everything." michael@0: michael@0: def __eq__(self, other): michael@0: return True michael@0: michael@0: def __ne__(self, other): michael@0: return False michael@0: michael@0: def __repr__(self): michael@0: return '' michael@0: michael@0: ANY = _ANY() michael@0: michael@0: michael@0: michael@0: def _format_call_signature(name, args, kwargs): michael@0: message = '%s(%%s)' % name michael@0: formatted_args = '' michael@0: args_string = ', '.join([repr(arg) for arg in args]) michael@0: kwargs_string = ', '.join([ michael@0: '%s=%r' % (key, value) for key, value in kwargs.items() michael@0: ]) michael@0: if args_string: michael@0: formatted_args = args_string michael@0: if kwargs_string: michael@0: if formatted_args: michael@0: formatted_args += ', ' michael@0: formatted_args += kwargs_string michael@0: michael@0: return message % formatted_args michael@0: michael@0: michael@0: michael@0: class _Call(tuple): michael@0: """ michael@0: A tuple for holding the results of a call to a mock, either in the form michael@0: `(args, kwargs)` or `(name, args, kwargs)`. michael@0: michael@0: If args or kwargs are empty then a call tuple will compare equal to michael@0: a tuple without those values. This makes comparisons less verbose:: michael@0: michael@0: _Call(('name', (), {})) == ('name',) michael@0: _Call(('name', (1,), {})) == ('name', (1,)) michael@0: _Call(((), {'a': 'b'})) == ({'a': 'b'},) michael@0: michael@0: The `_Call` object provides a useful shortcut for comparing with call:: michael@0: michael@0: _Call(((1, 2), {'a': 3})) == call(1, 2, a=3) michael@0: _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3) michael@0: michael@0: If the _Call has no name then it will match any name. michael@0: """ michael@0: def __new__(cls, value=(), name=None, parent=None, two=False, michael@0: from_kall=True): michael@0: name = '' michael@0: args = () michael@0: kwargs = {} michael@0: _len = len(value) michael@0: if _len == 3: michael@0: name, args, kwargs = value michael@0: elif _len == 2: michael@0: first, second = value michael@0: if isinstance(first, basestring): michael@0: name = first michael@0: if isinstance(second, tuple): michael@0: args = second michael@0: else: michael@0: kwargs = second michael@0: else: michael@0: args, kwargs = first, second michael@0: elif _len == 1: michael@0: value, = value michael@0: if isinstance(value, basestring): michael@0: name = value michael@0: elif isinstance(value, tuple): michael@0: args = value michael@0: else: michael@0: kwargs = value michael@0: michael@0: if two: michael@0: return tuple.__new__(cls, (args, kwargs)) michael@0: michael@0: return tuple.__new__(cls, (name, args, kwargs)) michael@0: michael@0: michael@0: def __init__(self, value=(), name=None, parent=None, two=False, michael@0: from_kall=True): michael@0: self.name = name michael@0: self.parent = parent michael@0: self.from_kall = from_kall michael@0: michael@0: michael@0: def __eq__(self, other): michael@0: if other is ANY: michael@0: return True michael@0: try: michael@0: len_other = len(other) michael@0: except TypeError: michael@0: return False michael@0: michael@0: self_name = '' michael@0: if len(self) == 2: michael@0: self_args, self_kwargs = self michael@0: else: michael@0: self_name, self_args, self_kwargs = self michael@0: michael@0: other_name = '' michael@0: if len_other == 0: michael@0: other_args, other_kwargs = (), {} michael@0: elif len_other == 3: michael@0: other_name, other_args, other_kwargs = other michael@0: elif len_other == 1: michael@0: value, = other michael@0: if isinstance(value, tuple): michael@0: other_args = value michael@0: other_kwargs = {} michael@0: elif isinstance(value, basestring): michael@0: other_name = value michael@0: other_args, other_kwargs = (), {} michael@0: else: michael@0: other_args = () michael@0: other_kwargs = value michael@0: else: michael@0: # len 2 michael@0: # could be (name, args) or (name, kwargs) or (args, kwargs) michael@0: first, second = other michael@0: if isinstance(first, basestring): michael@0: other_name = first michael@0: if isinstance(second, tuple): michael@0: other_args, other_kwargs = second, {} michael@0: else: michael@0: other_args, other_kwargs = (), second michael@0: else: michael@0: other_args, other_kwargs = first, second michael@0: michael@0: if self_name and other_name != self_name: michael@0: return False michael@0: michael@0: # this order is important for ANY to work! michael@0: return (other_args, other_kwargs) == (self_args, self_kwargs) michael@0: michael@0: michael@0: def __ne__(self, other): michael@0: return not self.__eq__(other) michael@0: michael@0: michael@0: def __call__(self, *args, **kwargs): michael@0: if self.name is None: michael@0: return _Call(('', args, kwargs), name='()') michael@0: michael@0: name = self.name + '()' michael@0: return _Call((self.name, args, kwargs), name=name, parent=self) michael@0: michael@0: michael@0: def __getattr__(self, attr): michael@0: if self.name is None: michael@0: return _Call(name=attr, from_kall=False) michael@0: name = '%s.%s' % (self.name, attr) michael@0: return _Call(name=name, parent=self, from_kall=False) michael@0: michael@0: michael@0: def __repr__(self): michael@0: if not self.from_kall: michael@0: name = self.name or 'call' michael@0: if name.startswith('()'): michael@0: name = 'call%s' % name michael@0: return name michael@0: michael@0: if len(self) == 2: michael@0: name = 'call' michael@0: args, kwargs = self michael@0: else: michael@0: name, args, kwargs = self michael@0: if not name: michael@0: name = 'call' michael@0: elif not name.startswith('()'): michael@0: name = 'call.%s' % name michael@0: else: michael@0: name = 'call%s' % name michael@0: return _format_call_signature(name, args, kwargs) michael@0: michael@0: michael@0: def call_list(self): michael@0: """For a call object that represents multiple calls, `call_list` michael@0: returns a list of all the intermediate calls as well as the michael@0: final call.""" michael@0: vals = [] michael@0: thing = self michael@0: while thing is not None: michael@0: if thing.from_kall: michael@0: vals.append(thing) michael@0: thing = thing.parent michael@0: return _CallList(reversed(vals)) michael@0: michael@0: michael@0: call = _Call(from_kall=False) michael@0: michael@0: michael@0: michael@0: def create_autospec(spec, spec_set=False, instance=False, _parent=None, michael@0: _name=None, **kwargs): michael@0: """Create a mock object using another object as a spec. Attributes on the michael@0: mock will use the corresponding attribute on the `spec` object as their michael@0: spec. michael@0: michael@0: Functions or methods being mocked will have their arguments checked michael@0: to check that they are called with the correct signature. michael@0: michael@0: If `spec_set` is True then attempting to set attributes that don't exist michael@0: on the spec object will raise an `AttributeError`. michael@0: michael@0: If a class is used as a spec then the return value of the mock (the michael@0: instance of the class) will have the same spec. You can use a class as the michael@0: spec for an instance object by passing `instance=True`. The returned mock michael@0: will only be callable if instances of the mock are callable. michael@0: michael@0: `create_autospec` also takes arbitrary keyword arguments that are passed to michael@0: the constructor of the created mock.""" michael@0: if _is_list(spec): michael@0: # can't pass a list instance to the mock constructor as it will be michael@0: # interpreted as a list of strings michael@0: spec = type(spec) michael@0: michael@0: is_type = isinstance(spec, ClassTypes) michael@0: michael@0: _kwargs = {'spec': spec} michael@0: if spec_set: michael@0: _kwargs = {'spec_set': spec} michael@0: elif spec is None: michael@0: # None we mock with a normal mock without a spec michael@0: _kwargs = {} michael@0: michael@0: _kwargs.update(kwargs) michael@0: michael@0: Klass = MagicMock michael@0: if type(spec) in DescriptorTypes: michael@0: # descriptors don't have a spec michael@0: # because we don't know what type they return michael@0: _kwargs = {} michael@0: elif not _callable(spec): michael@0: Klass = NonCallableMagicMock michael@0: elif is_type and instance and not _instance_callable(spec): michael@0: Klass = NonCallableMagicMock michael@0: michael@0: _new_name = _name michael@0: if _parent is None: michael@0: # for a top level object no _new_name should be set michael@0: _new_name = '' michael@0: michael@0: mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name, michael@0: name=_name, **_kwargs) michael@0: michael@0: if isinstance(spec, FunctionTypes): michael@0: # should only happen at the top level because we don't michael@0: # recurse for functions michael@0: mock = _set_signature(mock, spec) michael@0: else: michael@0: _check_signature(spec, mock, is_type, instance) michael@0: michael@0: if _parent is not None and not instance: michael@0: _parent._mock_children[_name] = mock michael@0: michael@0: if is_type and not instance and 'return_value' not in kwargs: michael@0: mock.return_value = create_autospec(spec, spec_set, instance=True, michael@0: _name='()', _parent=mock) michael@0: michael@0: for entry in dir(spec): michael@0: if _is_magic(entry): michael@0: # MagicMock already does the useful magic methods for us michael@0: continue michael@0: michael@0: if isinstance(spec, FunctionTypes) and entry in FunctionAttributes: michael@0: # allow a mock to actually be a function michael@0: continue michael@0: michael@0: # XXXX do we need a better way of getting attributes without michael@0: # triggering code execution (?) Probably not - we need the actual michael@0: # object to mock it so we would rather trigger a property than mock michael@0: # the property descriptor. Likewise we want to mock out dynamically michael@0: # provided attributes. michael@0: # XXXX what about attributes that raise exceptions other than michael@0: # AttributeError on being fetched? michael@0: # we could be resilient against it, or catch and propagate the michael@0: # exception when the attribute is fetched from the mock michael@0: try: michael@0: original = getattr(spec, entry) michael@0: except AttributeError: michael@0: continue michael@0: michael@0: kwargs = {'spec': original} michael@0: if spec_set: michael@0: kwargs = {'spec_set': original} michael@0: michael@0: if not isinstance(original, FunctionTypes): michael@0: new = _SpecState(original, spec_set, mock, entry, instance) michael@0: mock._mock_children[entry] = new michael@0: else: michael@0: parent = mock michael@0: if isinstance(spec, FunctionTypes): michael@0: parent = mock.mock michael@0: michael@0: new = MagicMock(parent=parent, name=entry, _new_name=entry, michael@0: _new_parent=parent, **kwargs) michael@0: mock._mock_children[entry] = new michael@0: skipfirst = _must_skip(spec, entry, is_type) michael@0: _check_signature(original, new, skipfirst=skipfirst) michael@0: michael@0: # so functions created with _set_signature become instance attributes, michael@0: # *plus* their underlying mock exists in _mock_children of the parent michael@0: # mock. Adding to _mock_children may be unnecessary where we are also michael@0: # setting as an instance attribute? michael@0: if isinstance(new, FunctionTypes): michael@0: setattr(mock, entry, new) michael@0: michael@0: return mock michael@0: michael@0: michael@0: def _must_skip(spec, entry, is_type): michael@0: if not isinstance(spec, ClassTypes): michael@0: if entry in getattr(spec, '__dict__', {}): michael@0: # instance attribute - shouldn't skip michael@0: return False michael@0: spec = spec.__class__ michael@0: if not hasattr(spec, '__mro__'): michael@0: # old style class: can't have descriptors anyway michael@0: return is_type michael@0: michael@0: for klass in spec.__mro__: michael@0: result = klass.__dict__.get(entry, DEFAULT) michael@0: if result is DEFAULT: michael@0: continue michael@0: if isinstance(result, (staticmethod, classmethod)): michael@0: return False michael@0: return is_type michael@0: michael@0: # shouldn't get here unless function is a dynamically provided attribute michael@0: # XXXX untested behaviour michael@0: return is_type michael@0: michael@0: michael@0: def _get_class(obj): michael@0: try: michael@0: return obj.__class__ michael@0: except AttributeError: michael@0: # in Python 2, _sre.SRE_Pattern objects have no __class__ michael@0: return type(obj) michael@0: michael@0: michael@0: class _SpecState(object): michael@0: michael@0: def __init__(self, spec, spec_set=False, parent=None, michael@0: name=None, ids=None, instance=False): michael@0: self.spec = spec michael@0: self.ids = ids michael@0: self.spec_set = spec_set michael@0: self.parent = parent michael@0: self.instance = instance michael@0: self.name = name michael@0: michael@0: michael@0: FunctionTypes = ( michael@0: # python function michael@0: type(create_autospec), michael@0: # instance method michael@0: type(ANY.__eq__), michael@0: # unbound method michael@0: type(_ANY.__eq__), michael@0: ) michael@0: michael@0: FunctionAttributes = set([ michael@0: 'func_closure', michael@0: 'func_code', michael@0: 'func_defaults', michael@0: 'func_dict', michael@0: 'func_doc', michael@0: 'func_globals', michael@0: 'func_name', michael@0: ]) michael@0: michael@0: michael@0: file_spec = None michael@0: michael@0: michael@0: def mock_open(mock=None, read_data=''): michael@0: """ michael@0: A helper function to create a mock to replace the use of `open`. It works michael@0: for `open` called directly or used as a context manager. michael@0: michael@0: The `mock` argument is the mock object to configure. If `None` (the michael@0: default) then a `MagicMock` will be created for you, with the API limited michael@0: to methods or attributes available on standard file handles. michael@0: michael@0: `read_data` is a string for the `read` method of the file handle to return. michael@0: This is an empty string by default. michael@0: """ michael@0: global file_spec michael@0: if file_spec is None: michael@0: # set on first use michael@0: if inPy3k: michael@0: import _io michael@0: file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO)))) michael@0: else: michael@0: file_spec = file michael@0: michael@0: if mock is None: michael@0: mock = MagicMock(name='open', spec=open) michael@0: michael@0: handle = MagicMock(spec=file_spec) michael@0: handle.write.return_value = None michael@0: handle.__enter__.return_value = handle michael@0: handle.read.return_value = read_data michael@0: michael@0: mock.return_value = handle michael@0: return mock michael@0: michael@0: michael@0: class PropertyMock(Mock): michael@0: """ michael@0: A mock intended to be used as a property, or other descriptor, on a class. michael@0: `PropertyMock` provides `__get__` and `__set__` methods so you can specify michael@0: a return value when it is fetched. michael@0: michael@0: Fetching a `PropertyMock` instance from an object calls the mock, with michael@0: no args. Setting it calls the mock with the value being set. michael@0: """ michael@0: def _get_child_mock(self, **kwargs): michael@0: return MagicMock(**kwargs) michael@0: michael@0: def __get__(self, obj, obj_type): michael@0: return self() michael@0: def __set__(self, obj, val): michael@0: self(val)