jpayne@68: # mock.py jpayne@68: # Test tools for mocking and patching. jpayne@68: # Maintained by Michael Foord jpayne@68: # Backport for other versions of Python available from jpayne@68: # https://pypi.org/project/mock jpayne@68: jpayne@68: __all__ = ( jpayne@68: 'Mock', jpayne@68: 'MagicMock', jpayne@68: 'patch', jpayne@68: 'sentinel', jpayne@68: 'DEFAULT', jpayne@68: 'ANY', jpayne@68: 'call', jpayne@68: 'create_autospec', jpayne@68: 'AsyncMock', jpayne@68: 'FILTER_DIR', jpayne@68: 'NonCallableMock', jpayne@68: 'NonCallableMagicMock', jpayne@68: 'mock_open', jpayne@68: 'PropertyMock', jpayne@68: 'seal', jpayne@68: ) jpayne@68: jpayne@68: jpayne@68: __version__ = '1.0' jpayne@68: jpayne@68: import asyncio jpayne@68: import contextlib jpayne@68: import io jpayne@68: import inspect jpayne@68: import pprint jpayne@68: import sys jpayne@68: import builtins jpayne@68: from types import CodeType, ModuleType, MethodType jpayne@68: from unittest.util import safe_repr jpayne@68: from functools import wraps, partial jpayne@68: jpayne@68: jpayne@68: _builtins = {name for name in dir(builtins) if not name.startswith('_')} jpayne@68: jpayne@68: FILTER_DIR = True jpayne@68: jpayne@68: # Workaround for issue #12370 jpayne@68: # Without this, the __class__ properties wouldn't be set correctly jpayne@68: _safe_super = super jpayne@68: jpayne@68: def _is_async_obj(obj): jpayne@68: if _is_instance_mock(obj) and not isinstance(obj, AsyncMock): jpayne@68: return False jpayne@68: return asyncio.iscoroutinefunction(obj) or inspect.isawaitable(obj) jpayne@68: jpayne@68: jpayne@68: def _is_async_func(func): jpayne@68: if getattr(func, '__code__', None): jpayne@68: return asyncio.iscoroutinefunction(func) jpayne@68: else: jpayne@68: return False jpayne@68: jpayne@68: jpayne@68: def _is_instance_mock(obj): jpayne@68: # can't use isinstance on Mock objects because they override __class__ jpayne@68: # The base class for all mocks is NonCallableMock jpayne@68: return issubclass(type(obj), NonCallableMock) jpayne@68: jpayne@68: jpayne@68: def _is_exception(obj): jpayne@68: return ( jpayne@68: isinstance(obj, BaseException) or jpayne@68: isinstance(obj, type) and issubclass(obj, BaseException) jpayne@68: ) jpayne@68: jpayne@68: jpayne@68: def _extract_mock(obj): jpayne@68: # Autospecced functions will return a FunctionType with "mock" attribute jpayne@68: # which is the actual mock object that needs to be used. jpayne@68: if isinstance(obj, FunctionTypes) and hasattr(obj, 'mock'): jpayne@68: return obj.mock jpayne@68: else: jpayne@68: return obj jpayne@68: jpayne@68: jpayne@68: def _get_signature_object(func, as_instance, eat_self): jpayne@68: """ jpayne@68: Given an arbitrary, possibly callable object, try to create a suitable jpayne@68: signature object. jpayne@68: Return a (reduced func, signature) tuple, or None. jpayne@68: """ jpayne@68: if isinstance(func, type) and not as_instance: jpayne@68: # If it's a type and should be modelled as a type, use __init__. jpayne@68: func = func.__init__ jpayne@68: # Skip the `self` argument in __init__ jpayne@68: eat_self = True jpayne@68: elif not isinstance(func, FunctionTypes): jpayne@68: # If we really want to model an instance of the passed type, jpayne@68: # __call__ should be looked up, not __init__. jpayne@68: try: jpayne@68: func = func.__call__ jpayne@68: except AttributeError: jpayne@68: return None jpayne@68: if eat_self: jpayne@68: sig_func = partial(func, None) jpayne@68: else: jpayne@68: sig_func = func jpayne@68: try: jpayne@68: return func, inspect.signature(sig_func) jpayne@68: except ValueError: jpayne@68: # Certain callable types are not supported by inspect.signature() jpayne@68: return None jpayne@68: jpayne@68: jpayne@68: def _check_signature(func, mock, skipfirst, instance=False): jpayne@68: sig = _get_signature_object(func, instance, skipfirst) jpayne@68: if sig is None: jpayne@68: return jpayne@68: func, sig = sig jpayne@68: def checksig(self, /, *args, **kwargs): jpayne@68: sig.bind(*args, **kwargs) jpayne@68: _copy_func_details(func, checksig) jpayne@68: type(mock)._mock_check_sig = checksig jpayne@68: type(mock).__signature__ = sig jpayne@68: jpayne@68: jpayne@68: def _copy_func_details(func, funcopy): jpayne@68: # we explicitly don't copy func.__dict__ into this copy as it would jpayne@68: # expose original attributes that should be mocked jpayne@68: for attribute in ( jpayne@68: '__name__', '__doc__', '__text_signature__', jpayne@68: '__module__', '__defaults__', '__kwdefaults__', jpayne@68: ): jpayne@68: try: jpayne@68: setattr(funcopy, attribute, getattr(func, attribute)) jpayne@68: except AttributeError: jpayne@68: pass jpayne@68: jpayne@68: jpayne@68: def _callable(obj): jpayne@68: if isinstance(obj, type): jpayne@68: return True jpayne@68: if isinstance(obj, (staticmethod, classmethod, MethodType)): jpayne@68: return _callable(obj.__func__) jpayne@68: if getattr(obj, '__call__', None) is not None: jpayne@68: return True jpayne@68: return False jpayne@68: jpayne@68: jpayne@68: def _is_list(obj): jpayne@68: # checks for list or tuples jpayne@68: # XXXX badly named! jpayne@68: return type(obj) in (list, tuple) jpayne@68: jpayne@68: jpayne@68: def _instance_callable(obj): jpayne@68: """Given an object, return True if the object is callable. jpayne@68: For classes, return True if instances would be callable.""" jpayne@68: if not isinstance(obj, type): jpayne@68: # already an instance jpayne@68: return getattr(obj, '__call__', None) is not None jpayne@68: jpayne@68: # *could* be broken by a class overriding __mro__ or __dict__ via jpayne@68: # a metaclass jpayne@68: for base in (obj,) + obj.__mro__: jpayne@68: if base.__dict__.get('__call__') is not None: jpayne@68: return True jpayne@68: return False jpayne@68: jpayne@68: jpayne@68: def _set_signature(mock, original, instance=False): jpayne@68: # creates a function with signature (*args, **kwargs) that delegates to a jpayne@68: # mock. It still does signature checking by calling a lambda with the same jpayne@68: # signature as the original. jpayne@68: jpayne@68: skipfirst = isinstance(original, type) jpayne@68: result = _get_signature_object(original, instance, skipfirst) jpayne@68: if result is None: jpayne@68: return mock jpayne@68: func, sig = result jpayne@68: def checksig(*args, **kwargs): jpayne@68: sig.bind(*args, **kwargs) jpayne@68: _copy_func_details(func, checksig) jpayne@68: jpayne@68: name = original.__name__ jpayne@68: if not name.isidentifier(): jpayne@68: name = 'funcopy' jpayne@68: context = {'_checksig_': checksig, 'mock': mock} jpayne@68: src = """def %s(*args, **kwargs): jpayne@68: _checksig_(*args, **kwargs) jpayne@68: return mock(*args, **kwargs)""" % name jpayne@68: exec (src, context) jpayne@68: funcopy = context[name] jpayne@68: _setup_func(funcopy, mock, sig) jpayne@68: return funcopy jpayne@68: jpayne@68: jpayne@68: def _setup_func(funcopy, mock, sig): jpayne@68: funcopy.mock = mock jpayne@68: jpayne@68: def assert_called_with(*args, **kwargs): jpayne@68: return mock.assert_called_with(*args, **kwargs) jpayne@68: def assert_called(*args, **kwargs): jpayne@68: return mock.assert_called(*args, **kwargs) jpayne@68: def assert_not_called(*args, **kwargs): jpayne@68: return mock.assert_not_called(*args, **kwargs) jpayne@68: def assert_called_once(*args, **kwargs): jpayne@68: return mock.assert_called_once(*args, **kwargs) jpayne@68: def assert_called_once_with(*args, **kwargs): jpayne@68: return mock.assert_called_once_with(*args, **kwargs) jpayne@68: def assert_has_calls(*args, **kwargs): jpayne@68: return mock.assert_has_calls(*args, **kwargs) jpayne@68: def assert_any_call(*args, **kwargs): jpayne@68: return mock.assert_any_call(*args, **kwargs) jpayne@68: def reset_mock(): jpayne@68: funcopy.method_calls = _CallList() jpayne@68: funcopy.mock_calls = _CallList() jpayne@68: mock.reset_mock() jpayne@68: ret = funcopy.return_value jpayne@68: if _is_instance_mock(ret) and not ret is mock: jpayne@68: ret.reset_mock() jpayne@68: jpayne@68: funcopy.called = False jpayne@68: funcopy.call_count = 0 jpayne@68: funcopy.call_args = None jpayne@68: funcopy.call_args_list = _CallList() jpayne@68: funcopy.method_calls = _CallList() jpayne@68: funcopy.mock_calls = _CallList() jpayne@68: jpayne@68: funcopy.return_value = mock.return_value jpayne@68: funcopy.side_effect = mock.side_effect jpayne@68: funcopy._mock_children = mock._mock_children jpayne@68: jpayne@68: funcopy.assert_called_with = assert_called_with jpayne@68: funcopy.assert_called_once_with = assert_called_once_with jpayne@68: funcopy.assert_has_calls = assert_has_calls jpayne@68: funcopy.assert_any_call = assert_any_call jpayne@68: funcopy.reset_mock = reset_mock jpayne@68: funcopy.assert_called = assert_called jpayne@68: funcopy.assert_not_called = assert_not_called jpayne@68: funcopy.assert_called_once = assert_called_once jpayne@68: funcopy.__signature__ = sig jpayne@68: jpayne@68: mock._mock_delegate = funcopy jpayne@68: jpayne@68: jpayne@68: def _setup_async_mock(mock): jpayne@68: mock._is_coroutine = asyncio.coroutines._is_coroutine jpayne@68: mock.await_count = 0 jpayne@68: mock.await_args = None jpayne@68: mock.await_args_list = _CallList() jpayne@68: jpayne@68: # Mock is not configured yet so the attributes are set jpayne@68: # to a function and then the corresponding mock helper function jpayne@68: # is called when the helper is accessed similar to _setup_func. jpayne@68: def wrapper(attr, /, *args, **kwargs): jpayne@68: return getattr(mock.mock, attr)(*args, **kwargs) jpayne@68: jpayne@68: for attribute in ('assert_awaited', jpayne@68: 'assert_awaited_once', jpayne@68: 'assert_awaited_with', jpayne@68: 'assert_awaited_once_with', jpayne@68: 'assert_any_await', jpayne@68: 'assert_has_awaits', jpayne@68: 'assert_not_awaited'): jpayne@68: jpayne@68: # setattr(mock, attribute, wrapper) causes late binding jpayne@68: # hence attribute will always be the last value in the loop jpayne@68: # Use partial(wrapper, attribute) to ensure the attribute is bound jpayne@68: # correctly. jpayne@68: setattr(mock, attribute, partial(wrapper, attribute)) jpayne@68: jpayne@68: jpayne@68: def _is_magic(name): jpayne@68: return '__%s__' % name[2:-2] == name jpayne@68: jpayne@68: jpayne@68: class _SentinelObject(object): jpayne@68: "A unique, named, sentinel object." jpayne@68: def __init__(self, name): jpayne@68: self.name = name jpayne@68: jpayne@68: def __repr__(self): jpayne@68: return 'sentinel.%s' % self.name jpayne@68: jpayne@68: def __reduce__(self): jpayne@68: return 'sentinel.%s' % self.name jpayne@68: jpayne@68: jpayne@68: class _Sentinel(object): jpayne@68: """Access attributes to return a named object, usable as a sentinel.""" jpayne@68: def __init__(self): jpayne@68: self._sentinels = {} jpayne@68: jpayne@68: def __getattr__(self, name): jpayne@68: if name == '__bases__': jpayne@68: # Without this help(unittest.mock) raises an exception jpayne@68: raise AttributeError jpayne@68: return self._sentinels.setdefault(name, _SentinelObject(name)) jpayne@68: jpayne@68: def __reduce__(self): jpayne@68: return 'sentinel' jpayne@68: jpayne@68: jpayne@68: sentinel = _Sentinel() jpayne@68: jpayne@68: DEFAULT = sentinel.DEFAULT jpayne@68: _missing = sentinel.MISSING jpayne@68: _deleted = sentinel.DELETED jpayne@68: jpayne@68: jpayne@68: _allowed_names = { jpayne@68: 'return_value', '_mock_return_value', 'side_effect', jpayne@68: '_mock_side_effect', '_mock_parent', '_mock_new_parent', jpayne@68: '_mock_name', '_mock_new_name' jpayne@68: } jpayne@68: jpayne@68: jpayne@68: def _delegating_property(name): jpayne@68: _allowed_names.add(name) jpayne@68: _the_name = '_mock_' + name jpayne@68: def _get(self, name=name, _the_name=_the_name): jpayne@68: sig = self._mock_delegate jpayne@68: if sig is None: jpayne@68: return getattr(self, _the_name) jpayne@68: return getattr(sig, name) jpayne@68: def _set(self, value, name=name, _the_name=_the_name): jpayne@68: sig = self._mock_delegate jpayne@68: if sig is None: jpayne@68: self.__dict__[_the_name] = value jpayne@68: else: jpayne@68: setattr(sig, name, value) jpayne@68: jpayne@68: return property(_get, _set) jpayne@68: jpayne@68: jpayne@68: jpayne@68: class _CallList(list): jpayne@68: jpayne@68: def __contains__(self, value): jpayne@68: if not isinstance(value, list): jpayne@68: return list.__contains__(self, value) jpayne@68: len_value = len(value) jpayne@68: len_self = len(self) jpayne@68: if len_value > len_self: jpayne@68: return False jpayne@68: jpayne@68: for i in range(0, len_self - len_value + 1): jpayne@68: sub_list = self[i:i+len_value] jpayne@68: if sub_list == value: jpayne@68: return True jpayne@68: return False jpayne@68: jpayne@68: def __repr__(self): jpayne@68: return pprint.pformat(list(self)) jpayne@68: jpayne@68: jpayne@68: def _check_and_set_parent(parent, value, name, new_name): jpayne@68: value = _extract_mock(value) jpayne@68: jpayne@68: if not _is_instance_mock(value): jpayne@68: return False jpayne@68: if ((value._mock_name or value._mock_new_name) or jpayne@68: (value._mock_parent is not None) or jpayne@68: (value._mock_new_parent is not None)): jpayne@68: return False jpayne@68: jpayne@68: _parent = parent jpayne@68: while _parent is not None: jpayne@68: # setting a mock (value) as a child or return value of itself jpayne@68: # should not modify the mock jpayne@68: if _parent is value: jpayne@68: return False jpayne@68: _parent = _parent._mock_new_parent jpayne@68: jpayne@68: if new_name: jpayne@68: value._mock_new_parent = parent jpayne@68: value._mock_new_name = new_name jpayne@68: if name: jpayne@68: value._mock_parent = parent jpayne@68: value._mock_name = name jpayne@68: return True jpayne@68: jpayne@68: # Internal class to identify if we wrapped an iterator object or not. jpayne@68: class _MockIter(object): jpayne@68: def __init__(self, obj): jpayne@68: self.obj = iter(obj) jpayne@68: def __next__(self): jpayne@68: return next(self.obj) jpayne@68: jpayne@68: class Base(object): jpayne@68: _mock_return_value = DEFAULT jpayne@68: _mock_side_effect = None jpayne@68: def __init__(self, /, *args, **kwargs): jpayne@68: pass jpayne@68: jpayne@68: jpayne@68: jpayne@68: class NonCallableMock(Base): jpayne@68: """A non-callable version of `Mock`""" jpayne@68: jpayne@68: def __new__(cls, /, *args, **kw): jpayne@68: # every instance has its own class jpayne@68: # so we can create magic methods on the jpayne@68: # class without stomping on other mocks jpayne@68: bases = (cls,) jpayne@68: if not issubclass(cls, AsyncMock): jpayne@68: # Check if spec is an async object or function jpayne@68: sig = inspect.signature(NonCallableMock.__init__) jpayne@68: bound_args = sig.bind_partial(cls, *args, **kw).arguments jpayne@68: spec_arg = [ jpayne@68: arg for arg in bound_args.keys() jpayne@68: if arg.startswith('spec') jpayne@68: ] jpayne@68: if spec_arg: jpayne@68: # what if spec_set is different than spec? jpayne@68: if _is_async_obj(bound_args[spec_arg[0]]): jpayne@68: bases = (AsyncMockMixin, cls,) jpayne@68: new = type(cls.__name__, bases, {'__doc__': cls.__doc__}) jpayne@68: instance = _safe_super(NonCallableMock, cls).__new__(new) jpayne@68: return instance jpayne@68: jpayne@68: jpayne@68: def __init__( jpayne@68: self, spec=None, wraps=None, name=None, spec_set=None, jpayne@68: parent=None, _spec_state=None, _new_name='', _new_parent=None, jpayne@68: _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs jpayne@68: ): jpayne@68: if _new_parent is None: jpayne@68: _new_parent = parent jpayne@68: jpayne@68: __dict__ = self.__dict__ jpayne@68: __dict__['_mock_parent'] = parent jpayne@68: __dict__['_mock_name'] = name jpayne@68: __dict__['_mock_new_name'] = _new_name jpayne@68: __dict__['_mock_new_parent'] = _new_parent jpayne@68: __dict__['_mock_sealed'] = False jpayne@68: jpayne@68: if spec_set is not None: jpayne@68: spec = spec_set jpayne@68: spec_set = True jpayne@68: if _eat_self is None: jpayne@68: _eat_self = parent is not None jpayne@68: jpayne@68: self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self) jpayne@68: jpayne@68: __dict__['_mock_children'] = {} jpayne@68: __dict__['_mock_wraps'] = wraps jpayne@68: __dict__['_mock_delegate'] = None jpayne@68: jpayne@68: __dict__['_mock_called'] = False jpayne@68: __dict__['_mock_call_args'] = None jpayne@68: __dict__['_mock_call_count'] = 0 jpayne@68: __dict__['_mock_call_args_list'] = _CallList() jpayne@68: __dict__['_mock_mock_calls'] = _CallList() jpayne@68: jpayne@68: __dict__['method_calls'] = _CallList() jpayne@68: __dict__['_mock_unsafe'] = unsafe jpayne@68: jpayne@68: if kwargs: jpayne@68: self.configure_mock(**kwargs) jpayne@68: jpayne@68: _safe_super(NonCallableMock, self).__init__( jpayne@68: spec, wraps, name, spec_set, parent, jpayne@68: _spec_state jpayne@68: ) jpayne@68: jpayne@68: jpayne@68: def attach_mock(self, mock, attribute): jpayne@68: """ jpayne@68: Attach a mock as an attribute of this one, replacing its name and jpayne@68: parent. Calls to the attached mock will be recorded in the jpayne@68: `method_calls` and `mock_calls` attributes of this one.""" jpayne@68: inner_mock = _extract_mock(mock) jpayne@68: jpayne@68: inner_mock._mock_parent = None jpayne@68: inner_mock._mock_new_parent = None jpayne@68: inner_mock._mock_name = '' jpayne@68: inner_mock._mock_new_name = None jpayne@68: jpayne@68: setattr(self, attribute, mock) jpayne@68: jpayne@68: jpayne@68: def mock_add_spec(self, spec, spec_set=False): jpayne@68: """Add a spec to a mock. `spec` can either be an object or a jpayne@68: list of strings. Only attributes on the `spec` can be fetched as jpayne@68: attributes from the mock. jpayne@68: jpayne@68: If `spec_set` is True then only attributes on the spec can be set.""" jpayne@68: self._mock_add_spec(spec, spec_set) jpayne@68: jpayne@68: jpayne@68: def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False, jpayne@68: _eat_self=False): jpayne@68: _spec_class = None jpayne@68: _spec_signature = None jpayne@68: _spec_asyncs = [] jpayne@68: jpayne@68: for attr in dir(spec): jpayne@68: if asyncio.iscoroutinefunction(getattr(spec, attr, None)): jpayne@68: _spec_asyncs.append(attr) jpayne@68: jpayne@68: if spec is not None and not _is_list(spec): jpayne@68: if isinstance(spec, type): jpayne@68: _spec_class = spec jpayne@68: else: jpayne@68: _spec_class = type(spec) jpayne@68: res = _get_signature_object(spec, jpayne@68: _spec_as_instance, _eat_self) jpayne@68: _spec_signature = res and res[1] jpayne@68: jpayne@68: spec = dir(spec) jpayne@68: jpayne@68: __dict__ = self.__dict__ jpayne@68: __dict__['_spec_class'] = _spec_class jpayne@68: __dict__['_spec_set'] = spec_set jpayne@68: __dict__['_spec_signature'] = _spec_signature jpayne@68: __dict__['_mock_methods'] = spec jpayne@68: __dict__['_spec_asyncs'] = _spec_asyncs jpayne@68: jpayne@68: def __get_return_value(self): jpayne@68: ret = self._mock_return_value jpayne@68: if self._mock_delegate is not None: jpayne@68: ret = self._mock_delegate.return_value jpayne@68: jpayne@68: if ret is DEFAULT: jpayne@68: ret = self._get_child_mock( jpayne@68: _new_parent=self, _new_name='()' jpayne@68: ) jpayne@68: self.return_value = ret jpayne@68: return ret jpayne@68: jpayne@68: jpayne@68: def __set_return_value(self, value): jpayne@68: if self._mock_delegate is not None: jpayne@68: self._mock_delegate.return_value = value jpayne@68: else: jpayne@68: self._mock_return_value = value jpayne@68: _check_and_set_parent(self, value, None, '()') jpayne@68: jpayne@68: __return_value_doc = "The value to be returned when the mock is called." jpayne@68: return_value = property(__get_return_value, __set_return_value, jpayne@68: __return_value_doc) jpayne@68: jpayne@68: jpayne@68: @property jpayne@68: def __class__(self): jpayne@68: if self._spec_class is None: jpayne@68: return type(self) jpayne@68: return self._spec_class jpayne@68: jpayne@68: called = _delegating_property('called') jpayne@68: call_count = _delegating_property('call_count') jpayne@68: call_args = _delegating_property('call_args') jpayne@68: call_args_list = _delegating_property('call_args_list') jpayne@68: mock_calls = _delegating_property('mock_calls') jpayne@68: jpayne@68: jpayne@68: def __get_side_effect(self): jpayne@68: delegated = self._mock_delegate jpayne@68: if delegated is None: jpayne@68: return self._mock_side_effect jpayne@68: sf = delegated.side_effect jpayne@68: if (sf is not None and not callable(sf) jpayne@68: and not isinstance(sf, _MockIter) and not _is_exception(sf)): jpayne@68: sf = _MockIter(sf) jpayne@68: delegated.side_effect = sf jpayne@68: return sf jpayne@68: jpayne@68: def __set_side_effect(self, value): jpayne@68: value = _try_iter(value) jpayne@68: delegated = self._mock_delegate jpayne@68: if delegated is None: jpayne@68: self._mock_side_effect = value jpayne@68: else: jpayne@68: delegated.side_effect = value jpayne@68: jpayne@68: side_effect = property(__get_side_effect, __set_side_effect) jpayne@68: jpayne@68: jpayne@68: def reset_mock(self, visited=None,*, return_value=False, side_effect=False): jpayne@68: "Restore the mock object to its initial state." jpayne@68: if visited is None: jpayne@68: visited = [] jpayne@68: if id(self) in visited: jpayne@68: return jpayne@68: visited.append(id(self)) jpayne@68: jpayne@68: self.called = False jpayne@68: self.call_args = None jpayne@68: self.call_count = 0 jpayne@68: self.mock_calls = _CallList() jpayne@68: self.call_args_list = _CallList() jpayne@68: self.method_calls = _CallList() jpayne@68: jpayne@68: if return_value: jpayne@68: self._mock_return_value = DEFAULT jpayne@68: if side_effect: jpayne@68: self._mock_side_effect = None jpayne@68: jpayne@68: for child in self._mock_children.values(): jpayne@68: if isinstance(child, _SpecState) or child is _deleted: jpayne@68: continue jpayne@68: child.reset_mock(visited) jpayne@68: jpayne@68: ret = self._mock_return_value jpayne@68: if _is_instance_mock(ret) and ret is not self: jpayne@68: ret.reset_mock(visited) jpayne@68: jpayne@68: jpayne@68: def configure_mock(self, /, **kwargs): jpayne@68: """Set attributes on the mock through keyword arguments. jpayne@68: jpayne@68: Attributes plus return values and side effects can be set on child jpayne@68: mocks using standard dot notation and unpacking a dictionary in the jpayne@68: method call: jpayne@68: jpayne@68: >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} jpayne@68: >>> mock.configure_mock(**attrs)""" jpayne@68: for arg, val in sorted(kwargs.items(), jpayne@68: # we sort on the number of dots so that jpayne@68: # attributes are set before we set attributes on jpayne@68: # attributes jpayne@68: key=lambda entry: entry[0].count('.')): jpayne@68: args = arg.split('.') jpayne@68: final = args.pop() jpayne@68: obj = self jpayne@68: for entry in args: jpayne@68: obj = getattr(obj, entry) jpayne@68: setattr(obj, final, val) jpayne@68: jpayne@68: jpayne@68: def __getattr__(self, name): jpayne@68: if name in {'_mock_methods', '_mock_unsafe'}: jpayne@68: raise AttributeError(name) jpayne@68: elif self._mock_methods is not None: jpayne@68: if name not in self._mock_methods or name in _all_magics: jpayne@68: raise AttributeError("Mock object has no attribute %r" % name) jpayne@68: elif _is_magic(name): jpayne@68: raise AttributeError(name) jpayne@68: if not self._mock_unsafe: jpayne@68: if name.startswith(('assert', 'assret')): jpayne@68: raise AttributeError("Attributes cannot start with 'assert' " jpayne@68: "or 'assret'") jpayne@68: jpayne@68: result = self._mock_children.get(name) jpayne@68: if result is _deleted: jpayne@68: raise AttributeError(name) jpayne@68: elif result is None: jpayne@68: wraps = None jpayne@68: if self._mock_wraps is not None: jpayne@68: # XXXX should we get the attribute without triggering code jpayne@68: # execution? jpayne@68: wraps = getattr(self._mock_wraps, name) jpayne@68: jpayne@68: result = self._get_child_mock( jpayne@68: parent=self, name=name, wraps=wraps, _new_name=name, jpayne@68: _new_parent=self jpayne@68: ) jpayne@68: self._mock_children[name] = result jpayne@68: jpayne@68: elif isinstance(result, _SpecState): jpayne@68: result = create_autospec( jpayne@68: result.spec, result.spec_set, result.instance, jpayne@68: result.parent, result.name jpayne@68: ) jpayne@68: self._mock_children[name] = result jpayne@68: jpayne@68: return result jpayne@68: jpayne@68: jpayne@68: def _extract_mock_name(self): jpayne@68: _name_list = [self._mock_new_name] jpayne@68: _parent = self._mock_new_parent jpayne@68: last = self jpayne@68: jpayne@68: dot = '.' jpayne@68: if _name_list == ['()']: jpayne@68: dot = '' jpayne@68: jpayne@68: while _parent is not None: jpayne@68: last = _parent jpayne@68: jpayne@68: _name_list.append(_parent._mock_new_name + dot) jpayne@68: dot = '.' jpayne@68: if _parent._mock_new_name == '()': jpayne@68: dot = '' jpayne@68: jpayne@68: _parent = _parent._mock_new_parent jpayne@68: jpayne@68: _name_list = list(reversed(_name_list)) jpayne@68: _first = last._mock_name or 'mock' jpayne@68: if len(_name_list) > 1: jpayne@68: if _name_list[1] not in ('()', '().'): jpayne@68: _first += '.' jpayne@68: _name_list[0] = _first jpayne@68: return ''.join(_name_list) jpayne@68: jpayne@68: def __repr__(self): jpayne@68: name = self._extract_mock_name() jpayne@68: jpayne@68: name_string = '' jpayne@68: if name not in ('mock', 'mock.'): jpayne@68: name_string = ' name=%r' % name jpayne@68: jpayne@68: spec_string = '' jpayne@68: if self._spec_class is not None: jpayne@68: spec_string = ' spec=%r' jpayne@68: if self._spec_set: jpayne@68: spec_string = ' spec_set=%r' jpayne@68: spec_string = spec_string % self._spec_class.__name__ jpayne@68: return "<%s%s%s id='%s'>" % ( jpayne@68: type(self).__name__, jpayne@68: name_string, jpayne@68: spec_string, jpayne@68: id(self) jpayne@68: ) jpayne@68: jpayne@68: jpayne@68: def __dir__(self): jpayne@68: """Filter the output of `dir(mock)` to only useful members.""" jpayne@68: if not FILTER_DIR: jpayne@68: return object.__dir__(self) jpayne@68: jpayne@68: extras = self._mock_methods or [] jpayne@68: from_type = dir(type(self)) jpayne@68: from_dict = list(self.__dict__) jpayne@68: from_child_mocks = [ jpayne@68: m_name for m_name, m_value in self._mock_children.items() jpayne@68: if m_value is not _deleted] jpayne@68: jpayne@68: from_type = [e for e in from_type if not e.startswith('_')] jpayne@68: from_dict = [e for e in from_dict if not e.startswith('_') or jpayne@68: _is_magic(e)] jpayne@68: return sorted(set(extras + from_type + from_dict + from_child_mocks)) jpayne@68: jpayne@68: jpayne@68: def __setattr__(self, name, value): jpayne@68: if name in _allowed_names: jpayne@68: # property setters go through here jpayne@68: return object.__setattr__(self, name, value) jpayne@68: elif (self._spec_set and self._mock_methods is not None and jpayne@68: name not in self._mock_methods and jpayne@68: name not in self.__dict__): jpayne@68: raise AttributeError("Mock object has no attribute '%s'" % name) jpayne@68: elif name in _unsupported_magics: jpayne@68: msg = 'Attempting to set unsupported magic method %r.' % name jpayne@68: raise AttributeError(msg) jpayne@68: elif name in _all_magics: jpayne@68: if self._mock_methods is not None and name not in self._mock_methods: jpayne@68: raise AttributeError("Mock object has no attribute '%s'" % name) jpayne@68: jpayne@68: if not _is_instance_mock(value): jpayne@68: setattr(type(self), name, _get_method(name, value)) jpayne@68: original = value jpayne@68: value = lambda *args, **kw: original(self, *args, **kw) jpayne@68: else: jpayne@68: # only set _new_name and not name so that mock_calls is tracked jpayne@68: # but not method calls jpayne@68: _check_and_set_parent(self, value, None, name) jpayne@68: setattr(type(self), name, value) jpayne@68: self._mock_children[name] = value jpayne@68: elif name == '__class__': jpayne@68: self._spec_class = value jpayne@68: return jpayne@68: else: jpayne@68: if _check_and_set_parent(self, value, name, name): jpayne@68: self._mock_children[name] = value jpayne@68: jpayne@68: if self._mock_sealed and not hasattr(self, name): jpayne@68: mock_name = f'{self._extract_mock_name()}.{name}' jpayne@68: raise AttributeError(f'Cannot set {mock_name}') jpayne@68: jpayne@68: return object.__setattr__(self, name, value) jpayne@68: jpayne@68: jpayne@68: def __delattr__(self, name): jpayne@68: if name in _all_magics and name in type(self).__dict__: jpayne@68: delattr(type(self), name) jpayne@68: if name not in self.__dict__: jpayne@68: # for magic methods that are still MagicProxy objects and jpayne@68: # not set on the instance itself jpayne@68: return jpayne@68: jpayne@68: obj = self._mock_children.get(name, _missing) jpayne@68: if name in self.__dict__: jpayne@68: _safe_super(NonCallableMock, self).__delattr__(name) jpayne@68: elif obj is _deleted: jpayne@68: raise AttributeError(name) jpayne@68: if obj is not _missing: jpayne@68: del self._mock_children[name] jpayne@68: self._mock_children[name] = _deleted jpayne@68: jpayne@68: jpayne@68: def _format_mock_call_signature(self, args, kwargs): jpayne@68: name = self._mock_name or 'mock' jpayne@68: return _format_call_signature(name, args, kwargs) jpayne@68: jpayne@68: jpayne@68: def _format_mock_failure_message(self, args, kwargs, action='call'): jpayne@68: message = 'expected %s not found.\nExpected: %s\nActual: %s' jpayne@68: expected_string = self._format_mock_call_signature(args, kwargs) jpayne@68: call_args = self.call_args jpayne@68: actual_string = self._format_mock_call_signature(*call_args) jpayne@68: return message % (action, expected_string, actual_string) jpayne@68: jpayne@68: jpayne@68: def _get_call_signature_from_name(self, name): jpayne@68: """ jpayne@68: * If call objects are asserted against a method/function like obj.meth1 jpayne@68: then there could be no name for the call object to lookup. Hence just jpayne@68: return the spec_signature of the method/function being asserted against. jpayne@68: * If the name is not empty then remove () and split by '.' to get jpayne@68: list of names to iterate through the children until a potential jpayne@68: match is found. A child mock is created only during attribute access jpayne@68: so if we get a _SpecState then no attributes of the spec were accessed jpayne@68: and can be safely exited. jpayne@68: """ jpayne@68: if not name: jpayne@68: return self._spec_signature jpayne@68: jpayne@68: sig = None jpayne@68: names = name.replace('()', '').split('.') jpayne@68: children = self._mock_children jpayne@68: jpayne@68: for name in names: jpayne@68: child = children.get(name) jpayne@68: if child is None or isinstance(child, _SpecState): jpayne@68: break jpayne@68: else: jpayne@68: children = child._mock_children jpayne@68: sig = child._spec_signature jpayne@68: jpayne@68: return sig jpayne@68: jpayne@68: jpayne@68: def _call_matcher(self, _call): jpayne@68: """ jpayne@68: Given a call (or simply an (args, kwargs) tuple), return a jpayne@68: comparison key suitable for matching with other calls. jpayne@68: This is a best effort method which relies on the spec's signature, jpayne@68: if available, or falls back on the arguments themselves. jpayne@68: """ jpayne@68: jpayne@68: if isinstance(_call, tuple) and len(_call) > 2: jpayne@68: sig = self._get_call_signature_from_name(_call[0]) jpayne@68: else: jpayne@68: sig = self._spec_signature jpayne@68: jpayne@68: if sig is not None: jpayne@68: if len(_call) == 2: jpayne@68: name = '' jpayne@68: args, kwargs = _call jpayne@68: else: jpayne@68: name, args, kwargs = _call jpayne@68: try: jpayne@68: return name, sig.bind(*args, **kwargs) jpayne@68: except TypeError as e: jpayne@68: return e.with_traceback(None) jpayne@68: else: jpayne@68: return _call jpayne@68: jpayne@68: def assert_not_called(self): jpayne@68: """assert that the mock was never called. jpayne@68: """ jpayne@68: if self.call_count != 0: jpayne@68: msg = ("Expected '%s' to not have been called. Called %s times.%s" jpayne@68: % (self._mock_name or 'mock', jpayne@68: self.call_count, jpayne@68: self._calls_repr())) jpayne@68: raise AssertionError(msg) jpayne@68: jpayne@68: def assert_called(self): jpayne@68: """assert that the mock was called at least once jpayne@68: """ jpayne@68: if self.call_count == 0: jpayne@68: msg = ("Expected '%s' to have been called." % jpayne@68: (self._mock_name or 'mock')) jpayne@68: raise AssertionError(msg) jpayne@68: jpayne@68: def assert_called_once(self): jpayne@68: """assert that the mock was called only once. jpayne@68: """ jpayne@68: if not self.call_count == 1: jpayne@68: msg = ("Expected '%s' to have been called once. Called %s times.%s" jpayne@68: % (self._mock_name or 'mock', jpayne@68: self.call_count, jpayne@68: self._calls_repr())) jpayne@68: raise AssertionError(msg) jpayne@68: jpayne@68: def assert_called_with(self, /, *args, **kwargs): jpayne@68: """assert that the last call was made with the specified arguments. jpayne@68: jpayne@68: Raises an AssertionError if the args and keyword args passed in are jpayne@68: different to the last call to the mock.""" jpayne@68: if self.call_args is None: jpayne@68: expected = self._format_mock_call_signature(args, kwargs) jpayne@68: actual = 'not called.' jpayne@68: error_message = ('expected call not found.\nExpected: %s\nActual: %s' jpayne@68: % (expected, actual)) jpayne@68: raise AssertionError(error_message) jpayne@68: jpayne@68: def _error_message(): jpayne@68: msg = self._format_mock_failure_message(args, kwargs) jpayne@68: return msg jpayne@68: expected = self._call_matcher((args, kwargs)) jpayne@68: actual = self._call_matcher(self.call_args) jpayne@68: if expected != actual: jpayne@68: cause = expected if isinstance(expected, Exception) else None jpayne@68: raise AssertionError(_error_message()) from cause jpayne@68: jpayne@68: jpayne@68: def assert_called_once_with(self, /, *args, **kwargs): jpayne@68: """assert that the mock was called exactly once and that that call was jpayne@68: with the specified arguments.""" jpayne@68: if not self.call_count == 1: jpayne@68: msg = ("Expected '%s' to be called once. Called %s times.%s" jpayne@68: % (self._mock_name or 'mock', jpayne@68: self.call_count, jpayne@68: self._calls_repr())) jpayne@68: raise AssertionError(msg) jpayne@68: return self.assert_called_with(*args, **kwargs) jpayne@68: jpayne@68: jpayne@68: def assert_has_calls(self, calls, any_order=False): jpayne@68: """assert the mock has been called with the specified calls. jpayne@68: The `mock_calls` list is checked for the calls. jpayne@68: jpayne@68: If `any_order` is False (the default) then the calls must be jpayne@68: sequential. There can be extra calls before or after the jpayne@68: specified calls. jpayne@68: jpayne@68: If `any_order` is True then the calls can be in any order, but jpayne@68: they must all appear in `mock_calls`.""" jpayne@68: expected = [self._call_matcher(c) for c in calls] jpayne@68: cause = next((e for e in expected if isinstance(e, Exception)), None) jpayne@68: all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls) jpayne@68: if not any_order: jpayne@68: if expected not in all_calls: jpayne@68: if cause is None: jpayne@68: problem = 'Calls not found.' jpayne@68: else: jpayne@68: problem = ('Error processing expected calls.\n' jpayne@68: 'Errors: {}').format( jpayne@68: [e if isinstance(e, Exception) else None jpayne@68: for e in expected]) jpayne@68: raise AssertionError( jpayne@68: f'{problem}\n' jpayne@68: f'Expected: {_CallList(calls)}' jpayne@68: f'{self._calls_repr(prefix="Actual").rstrip(".")}' jpayne@68: ) from cause jpayne@68: return jpayne@68: jpayne@68: all_calls = list(all_calls) jpayne@68: jpayne@68: not_found = [] jpayne@68: for kall in expected: jpayne@68: try: jpayne@68: all_calls.remove(kall) jpayne@68: except ValueError: jpayne@68: not_found.append(kall) jpayne@68: if not_found: jpayne@68: raise AssertionError( jpayne@68: '%r does not contain all of %r in its call list, ' jpayne@68: 'found %r instead' % (self._mock_name or 'mock', jpayne@68: tuple(not_found), all_calls) jpayne@68: ) from cause jpayne@68: jpayne@68: jpayne@68: def assert_any_call(self, /, *args, **kwargs): jpayne@68: """assert the mock has been called with the specified arguments. jpayne@68: jpayne@68: The assert passes if the mock has *ever* been called, unlike jpayne@68: `assert_called_with` and `assert_called_once_with` that only pass if jpayne@68: the call is the most recent one.""" jpayne@68: expected = self._call_matcher((args, kwargs)) jpayne@68: actual = [self._call_matcher(c) for c in self.call_args_list] jpayne@68: if expected not in actual: jpayne@68: cause = expected if isinstance(expected, Exception) else None jpayne@68: expected_string = self._format_mock_call_signature(args, kwargs) jpayne@68: raise AssertionError( jpayne@68: '%s call not found' % expected_string jpayne@68: ) from cause jpayne@68: jpayne@68: jpayne@68: def _get_child_mock(self, /, **kw): jpayne@68: """Create the child mocks for attributes and return value. jpayne@68: By default child mocks will be the same type as the parent. jpayne@68: Subclasses of Mock may want to override this to customize the way jpayne@68: child mocks are made. jpayne@68: jpayne@68: For non-callable mocks the callable variant will be used (rather than jpayne@68: any custom subclass).""" jpayne@68: _new_name = kw.get("_new_name") jpayne@68: if _new_name in self.__dict__['_spec_asyncs']: jpayne@68: return AsyncMock(**kw) jpayne@68: jpayne@68: _type = type(self) jpayne@68: if issubclass(_type, MagicMock) and _new_name in _async_method_magics: jpayne@68: # Any asynchronous magic becomes an AsyncMock jpayne@68: klass = AsyncMock jpayne@68: elif issubclass(_type, AsyncMockMixin): jpayne@68: if (_new_name in _all_sync_magics or jpayne@68: self._mock_methods and _new_name in self._mock_methods): jpayne@68: # Any synchronous method on AsyncMock becomes a MagicMock jpayne@68: klass = MagicMock jpayne@68: else: jpayne@68: klass = AsyncMock jpayne@68: elif not issubclass(_type, CallableMixin): jpayne@68: if issubclass(_type, NonCallableMagicMock): jpayne@68: klass = MagicMock jpayne@68: elif issubclass(_type, NonCallableMock): jpayne@68: klass = Mock jpayne@68: else: jpayne@68: klass = _type.__mro__[1] jpayne@68: jpayne@68: if self._mock_sealed: jpayne@68: attribute = "." + kw["name"] if "name" in kw else "()" jpayne@68: mock_name = self._extract_mock_name() + attribute jpayne@68: raise AttributeError(mock_name) jpayne@68: jpayne@68: return klass(**kw) jpayne@68: jpayne@68: jpayne@68: def _calls_repr(self, prefix="Calls"): jpayne@68: """Renders self.mock_calls as a string. jpayne@68: jpayne@68: Example: "\nCalls: [call(1), call(2)]." jpayne@68: jpayne@68: If self.mock_calls is empty, an empty string is returned. The jpayne@68: output will be truncated if very long. jpayne@68: """ jpayne@68: if not self.mock_calls: jpayne@68: return "" jpayne@68: return f"\n{prefix}: {safe_repr(self.mock_calls)}." jpayne@68: jpayne@68: jpayne@68: jpayne@68: def _try_iter(obj): jpayne@68: if obj is None: jpayne@68: return obj jpayne@68: if _is_exception(obj): jpayne@68: return obj jpayne@68: if _callable(obj): jpayne@68: return obj jpayne@68: try: jpayne@68: return iter(obj) jpayne@68: except TypeError: jpayne@68: # XXXX backwards compatibility jpayne@68: # but this will blow up on first call - so maybe we should fail early? jpayne@68: return obj jpayne@68: jpayne@68: jpayne@68: class CallableMixin(Base): jpayne@68: jpayne@68: def __init__(self, spec=None, side_effect=None, return_value=DEFAULT, jpayne@68: wraps=None, name=None, spec_set=None, parent=None, jpayne@68: _spec_state=None, _new_name='', _new_parent=None, **kwargs): jpayne@68: self.__dict__['_mock_return_value'] = return_value jpayne@68: _safe_super(CallableMixin, self).__init__( jpayne@68: spec, wraps, name, spec_set, parent, jpayne@68: _spec_state, _new_name, _new_parent, **kwargs jpayne@68: ) jpayne@68: jpayne@68: self.side_effect = side_effect jpayne@68: jpayne@68: jpayne@68: def _mock_check_sig(self, /, *args, **kwargs): jpayne@68: # stub method that can be replaced with one with a specific signature jpayne@68: pass jpayne@68: jpayne@68: jpayne@68: def __call__(self, /, *args, **kwargs): jpayne@68: # can't use self in-case a function / method we are mocking uses self jpayne@68: # in the signature jpayne@68: self._mock_check_sig(*args, **kwargs) jpayne@68: self._increment_mock_call(*args, **kwargs) jpayne@68: return self._mock_call(*args, **kwargs) jpayne@68: jpayne@68: jpayne@68: def _mock_call(self, /, *args, **kwargs): jpayne@68: return self._execute_mock_call(*args, **kwargs) jpayne@68: jpayne@68: def _increment_mock_call(self, /, *args, **kwargs): jpayne@68: self.called = True jpayne@68: self.call_count += 1 jpayne@68: jpayne@68: # handle call_args jpayne@68: # needs to be set here so assertions on call arguments pass before jpayne@68: # execution in the case of awaited calls jpayne@68: _call = _Call((args, kwargs), two=True) jpayne@68: self.call_args = _call jpayne@68: self.call_args_list.append(_call) jpayne@68: jpayne@68: # initial stuff for method_calls: jpayne@68: do_method_calls = self._mock_parent is not None jpayne@68: method_call_name = self._mock_name jpayne@68: jpayne@68: # initial stuff for mock_calls: jpayne@68: mock_call_name = self._mock_new_name jpayne@68: is_a_call = mock_call_name == '()' jpayne@68: self.mock_calls.append(_Call(('', args, kwargs))) jpayne@68: jpayne@68: # follow up the chain of mocks: jpayne@68: _new_parent = self._mock_new_parent jpayne@68: while _new_parent is not None: jpayne@68: jpayne@68: # handle method_calls: jpayne@68: if do_method_calls: jpayne@68: _new_parent.method_calls.append(_Call((method_call_name, args, kwargs))) jpayne@68: do_method_calls = _new_parent._mock_parent is not None jpayne@68: if do_method_calls: jpayne@68: method_call_name = _new_parent._mock_name + '.' + method_call_name jpayne@68: jpayne@68: # handle mock_calls: jpayne@68: this_mock_call = _Call((mock_call_name, args, kwargs)) jpayne@68: _new_parent.mock_calls.append(this_mock_call) jpayne@68: jpayne@68: if _new_parent._mock_new_name: jpayne@68: if is_a_call: jpayne@68: dot = '' jpayne@68: else: jpayne@68: dot = '.' jpayne@68: is_a_call = _new_parent._mock_new_name == '()' jpayne@68: mock_call_name = _new_parent._mock_new_name + dot + mock_call_name jpayne@68: jpayne@68: # follow the parental chain: jpayne@68: _new_parent = _new_parent._mock_new_parent jpayne@68: jpayne@68: def _execute_mock_call(self, /, *args, **kwargs): jpayne@68: # separate from _increment_mock_call so that awaited functions are jpayne@68: # executed separately from their call, also AsyncMock overrides this method jpayne@68: jpayne@68: effect = self.side_effect jpayne@68: if effect is not None: jpayne@68: if _is_exception(effect): jpayne@68: raise effect jpayne@68: elif not _callable(effect): jpayne@68: result = next(effect) jpayne@68: if _is_exception(result): jpayne@68: raise result jpayne@68: else: jpayne@68: result = effect(*args, **kwargs) jpayne@68: jpayne@68: if result is not DEFAULT: jpayne@68: return result jpayne@68: jpayne@68: if self._mock_return_value is not DEFAULT: jpayne@68: return self.return_value jpayne@68: jpayne@68: if self._mock_wraps is not None: jpayne@68: return self._mock_wraps(*args, **kwargs) jpayne@68: jpayne@68: return self.return_value jpayne@68: jpayne@68: jpayne@68: jpayne@68: class Mock(CallableMixin, NonCallableMock): jpayne@68: """ jpayne@68: Create a new `Mock` object. `Mock` takes several optional arguments jpayne@68: that specify the behaviour of the Mock object: jpayne@68: jpayne@68: * `spec`: This can be either a list of strings or an existing object (a jpayne@68: class or instance) that acts as the specification for the mock object. If jpayne@68: you pass in an object then a list of strings is formed by calling dir on jpayne@68: the object (excluding unsupported magic attributes and methods). Accessing jpayne@68: any attribute not in this list will raise an `AttributeError`. jpayne@68: jpayne@68: If `spec` is an object (rather than a list of strings) then jpayne@68: `mock.__class__` returns the class of the spec object. This allows mocks jpayne@68: to pass `isinstance` tests. jpayne@68: jpayne@68: * `spec_set`: A stricter variant of `spec`. If used, attempting to *set* jpayne@68: or get an attribute on the mock that isn't on the object passed as jpayne@68: `spec_set` will raise an `AttributeError`. jpayne@68: jpayne@68: * `side_effect`: A function to be called whenever the Mock is called. See jpayne@68: the `side_effect` attribute. Useful for raising exceptions or jpayne@68: dynamically changing return values. The function is called with the same jpayne@68: arguments as the mock, and unless it returns `DEFAULT`, the return jpayne@68: value of this function is used as the return value. jpayne@68: jpayne@68: If `side_effect` is an iterable then each call to the mock will return jpayne@68: the next value from the iterable. If any of the members of the iterable jpayne@68: are exceptions they will be raised instead of returned. jpayne@68: jpayne@68: * `return_value`: The value returned when the mock is called. By default jpayne@68: this is a new Mock (created on first access). See the jpayne@68: `return_value` attribute. jpayne@68: jpayne@68: * `wraps`: Item for the mock object to wrap. If `wraps` is not None then jpayne@68: calling the Mock will pass the call through to the wrapped object jpayne@68: (returning the real result). Attribute access on the mock will return a jpayne@68: Mock object that wraps the corresponding attribute of the wrapped object jpayne@68: (so attempting to access an attribute that doesn't exist will raise an jpayne@68: `AttributeError`). jpayne@68: jpayne@68: If the mock has an explicit `return_value` set then calls are not passed jpayne@68: to the wrapped object and the `return_value` is returned instead. jpayne@68: jpayne@68: * `name`: If the mock has a name then it will be used in the repr of the jpayne@68: mock. This can be useful for debugging. The name is propagated to child jpayne@68: mocks. jpayne@68: jpayne@68: Mocks can also be called with arbitrary keyword arguments. These will be jpayne@68: used to set attributes on the mock after it is created. jpayne@68: """ jpayne@68: jpayne@68: jpayne@68: def _dot_lookup(thing, comp, import_path): jpayne@68: try: jpayne@68: return getattr(thing, comp) jpayne@68: except AttributeError: jpayne@68: __import__(import_path) jpayne@68: return getattr(thing, comp) jpayne@68: jpayne@68: jpayne@68: def _importer(target): jpayne@68: components = target.split('.') jpayne@68: import_path = components.pop(0) jpayne@68: thing = __import__(import_path) jpayne@68: jpayne@68: for comp in components: jpayne@68: import_path += ".%s" % comp jpayne@68: thing = _dot_lookup(thing, comp, import_path) jpayne@68: return thing jpayne@68: jpayne@68: jpayne@68: def _is_started(patcher): jpayne@68: # XXXX horrible jpayne@68: return hasattr(patcher, 'is_local') jpayne@68: jpayne@68: jpayne@68: class _patch(object): jpayne@68: jpayne@68: attribute_name = None jpayne@68: _active_patches = [] jpayne@68: jpayne@68: def __init__( jpayne@68: self, getter, attribute, new, spec, create, jpayne@68: spec_set, autospec, new_callable, kwargs jpayne@68: ): jpayne@68: if new_callable is not None: jpayne@68: if new is not DEFAULT: jpayne@68: raise ValueError( jpayne@68: "Cannot use 'new' and 'new_callable' together" jpayne@68: ) jpayne@68: if autospec is not None: jpayne@68: raise ValueError( jpayne@68: "Cannot use 'autospec' and 'new_callable' together" jpayne@68: ) jpayne@68: jpayne@68: self.getter = getter jpayne@68: self.attribute = attribute jpayne@68: self.new = new jpayne@68: self.new_callable = new_callable jpayne@68: self.spec = spec jpayne@68: self.create = create jpayne@68: self.has_local = False jpayne@68: self.spec_set = spec_set jpayne@68: self.autospec = autospec jpayne@68: self.kwargs = kwargs jpayne@68: self.additional_patchers = [] jpayne@68: jpayne@68: jpayne@68: def copy(self): jpayne@68: patcher = _patch( jpayne@68: self.getter, self.attribute, self.new, self.spec, jpayne@68: self.create, self.spec_set, jpayne@68: self.autospec, self.new_callable, self.kwargs jpayne@68: ) jpayne@68: patcher.attribute_name = self.attribute_name jpayne@68: patcher.additional_patchers = [ jpayne@68: p.copy() for p in self.additional_patchers jpayne@68: ] jpayne@68: return patcher jpayne@68: jpayne@68: jpayne@68: def __call__(self, func): jpayne@68: if isinstance(func, type): jpayne@68: return self.decorate_class(func) jpayne@68: if inspect.iscoroutinefunction(func): jpayne@68: return self.decorate_async_callable(func) jpayne@68: return self.decorate_callable(func) jpayne@68: jpayne@68: jpayne@68: def decorate_class(self, klass): jpayne@68: for attr in dir(klass): jpayne@68: if not attr.startswith(patch.TEST_PREFIX): jpayne@68: continue jpayne@68: jpayne@68: attr_value = getattr(klass, attr) jpayne@68: if not hasattr(attr_value, "__call__"): jpayne@68: continue jpayne@68: jpayne@68: patcher = self.copy() jpayne@68: setattr(klass, attr, patcher(attr_value)) jpayne@68: return klass jpayne@68: jpayne@68: jpayne@68: @contextlib.contextmanager jpayne@68: def decoration_helper(self, patched, args, keywargs): jpayne@68: extra_args = [] jpayne@68: entered_patchers = [] jpayne@68: patching = None jpayne@68: jpayne@68: exc_info = tuple() jpayne@68: try: jpayne@68: for patching in patched.patchings: jpayne@68: arg = patching.__enter__() jpayne@68: entered_patchers.append(patching) jpayne@68: if patching.attribute_name is not None: jpayne@68: keywargs.update(arg) jpayne@68: elif patching.new is DEFAULT: jpayne@68: extra_args.append(arg) jpayne@68: jpayne@68: args += tuple(extra_args) jpayne@68: yield (args, keywargs) jpayne@68: except: jpayne@68: if (patching not in entered_patchers and jpayne@68: _is_started(patching)): jpayne@68: # the patcher may have been started, but an exception jpayne@68: # raised whilst entering one of its additional_patchers jpayne@68: entered_patchers.append(patching) jpayne@68: # Pass the exception to __exit__ jpayne@68: exc_info = sys.exc_info() jpayne@68: # re-raise the exception jpayne@68: raise jpayne@68: finally: jpayne@68: for patching in reversed(entered_patchers): jpayne@68: patching.__exit__(*exc_info) jpayne@68: jpayne@68: jpayne@68: def decorate_callable(self, func): jpayne@68: # NB. Keep the method in sync with decorate_async_callable() jpayne@68: if hasattr(func, 'patchings'): jpayne@68: func.patchings.append(self) jpayne@68: return func jpayne@68: jpayne@68: @wraps(func) jpayne@68: def patched(*args, **keywargs): jpayne@68: with self.decoration_helper(patched, jpayne@68: args, jpayne@68: keywargs) as (newargs, newkeywargs): jpayne@68: return func(*newargs, **newkeywargs) jpayne@68: jpayne@68: patched.patchings = [self] jpayne@68: return patched jpayne@68: jpayne@68: jpayne@68: def decorate_async_callable(self, func): jpayne@68: # NB. Keep the method in sync with decorate_callable() jpayne@68: if hasattr(func, 'patchings'): jpayne@68: func.patchings.append(self) jpayne@68: return func jpayne@68: jpayne@68: @wraps(func) jpayne@68: async def patched(*args, **keywargs): jpayne@68: with self.decoration_helper(patched, jpayne@68: args, jpayne@68: keywargs) as (newargs, newkeywargs): jpayne@68: return await func(*newargs, **newkeywargs) jpayne@68: jpayne@68: patched.patchings = [self] jpayne@68: return patched jpayne@68: jpayne@68: jpayne@68: def get_original(self): jpayne@68: target = self.getter() jpayne@68: name = self.attribute jpayne@68: jpayne@68: original = DEFAULT jpayne@68: local = False jpayne@68: jpayne@68: try: jpayne@68: original = target.__dict__[name] jpayne@68: except (AttributeError, KeyError): jpayne@68: original = getattr(target, name, DEFAULT) jpayne@68: else: jpayne@68: local = True jpayne@68: jpayne@68: if name in _builtins and isinstance(target, ModuleType): jpayne@68: self.create = True jpayne@68: jpayne@68: if not self.create and original is DEFAULT: jpayne@68: raise AttributeError( jpayne@68: "%s does not have the attribute %r" % (target, name) jpayne@68: ) jpayne@68: return original, local jpayne@68: jpayne@68: jpayne@68: def __enter__(self): jpayne@68: """Perform the patch.""" jpayne@68: new, spec, spec_set = self.new, self.spec, self.spec_set jpayne@68: autospec, kwargs = self.autospec, self.kwargs jpayne@68: new_callable = self.new_callable jpayne@68: self.target = self.getter() jpayne@68: jpayne@68: # normalise False to None jpayne@68: if spec is False: jpayne@68: spec = None jpayne@68: if spec_set is False: jpayne@68: spec_set = None jpayne@68: if autospec is False: jpayne@68: autospec = None jpayne@68: jpayne@68: if spec is not None and autospec is not None: jpayne@68: raise TypeError("Can't specify spec and autospec") jpayne@68: if ((spec is not None or autospec is not None) and jpayne@68: spec_set not in (True, None)): jpayne@68: raise TypeError("Can't provide explicit spec_set *and* spec or autospec") jpayne@68: jpayne@68: original, local = self.get_original() jpayne@68: jpayne@68: if new is DEFAULT and autospec is None: jpayne@68: inherit = False jpayne@68: if spec is True: jpayne@68: # set spec to the object we are replacing jpayne@68: spec = original jpayne@68: if spec_set is True: jpayne@68: spec_set = original jpayne@68: spec = None jpayne@68: elif spec is not None: jpayne@68: if spec_set is True: jpayne@68: spec_set = spec jpayne@68: spec = None jpayne@68: elif spec_set is True: jpayne@68: spec_set = original jpayne@68: jpayne@68: if spec is not None or spec_set is not None: jpayne@68: if original is DEFAULT: jpayne@68: raise TypeError("Can't use 'spec' with create=True") jpayne@68: if isinstance(original, type): jpayne@68: # If we're patching out a class and there is a spec jpayne@68: inherit = True jpayne@68: if spec is None and _is_async_obj(original): jpayne@68: Klass = AsyncMock jpayne@68: else: jpayne@68: Klass = MagicMock jpayne@68: _kwargs = {} jpayne@68: if new_callable is not None: jpayne@68: Klass = new_callable jpayne@68: elif spec is not None or spec_set is not None: jpayne@68: this_spec = spec jpayne@68: if spec_set is not None: jpayne@68: this_spec = spec_set jpayne@68: if _is_list(this_spec): jpayne@68: not_callable = '__call__' not in this_spec jpayne@68: else: jpayne@68: not_callable = not callable(this_spec) jpayne@68: if _is_async_obj(this_spec): jpayne@68: Klass = AsyncMock jpayne@68: elif not_callable: jpayne@68: Klass = NonCallableMagicMock jpayne@68: jpayne@68: if spec is not None: jpayne@68: _kwargs['spec'] = spec jpayne@68: if spec_set is not None: jpayne@68: _kwargs['spec_set'] = spec_set jpayne@68: jpayne@68: # add a name to mocks jpayne@68: if (isinstance(Klass, type) and jpayne@68: issubclass(Klass, NonCallableMock) and self.attribute): jpayne@68: _kwargs['name'] = self.attribute jpayne@68: jpayne@68: _kwargs.update(kwargs) jpayne@68: new = Klass(**_kwargs) jpayne@68: jpayne@68: if inherit and _is_instance_mock(new): jpayne@68: # we can only tell if the instance should be callable if the jpayne@68: # spec is not a list jpayne@68: this_spec = spec jpayne@68: if spec_set is not None: jpayne@68: this_spec = spec_set jpayne@68: if (not _is_list(this_spec) and not jpayne@68: _instance_callable(this_spec)): jpayne@68: Klass = NonCallableMagicMock jpayne@68: jpayne@68: _kwargs.pop('name') jpayne@68: new.return_value = Klass(_new_parent=new, _new_name='()', jpayne@68: **_kwargs) jpayne@68: elif autospec is not None: jpayne@68: # spec is ignored, new *must* be default, spec_set is treated jpayne@68: # as a boolean. Should we check spec is not None and that spec_set jpayne@68: # is a bool? jpayne@68: if new is not DEFAULT: jpayne@68: raise TypeError( jpayne@68: "autospec creates the mock for you. Can't specify " jpayne@68: "autospec and new." jpayne@68: ) jpayne@68: if original is DEFAULT: jpayne@68: raise TypeError("Can't use 'autospec' with create=True") jpayne@68: spec_set = bool(spec_set) jpayne@68: if autospec is True: jpayne@68: autospec = original jpayne@68: jpayne@68: new = create_autospec(autospec, spec_set=spec_set, jpayne@68: _name=self.attribute, **kwargs) jpayne@68: elif kwargs: jpayne@68: # can't set keyword args when we aren't creating the mock jpayne@68: # XXXX If new is a Mock we could call new.configure_mock(**kwargs) jpayne@68: raise TypeError("Can't pass kwargs to a mock we aren't creating") jpayne@68: jpayne@68: new_attr = new jpayne@68: jpayne@68: self.temp_original = original jpayne@68: self.is_local = local jpayne@68: setattr(self.target, self.attribute, new_attr) jpayne@68: if self.attribute_name is not None: jpayne@68: extra_args = {} jpayne@68: if self.new is DEFAULT: jpayne@68: extra_args[self.attribute_name] = new jpayne@68: for patching in self.additional_patchers: jpayne@68: arg = patching.__enter__() jpayne@68: if patching.new is DEFAULT: jpayne@68: extra_args.update(arg) jpayne@68: return extra_args jpayne@68: jpayne@68: return new jpayne@68: jpayne@68: jpayne@68: def __exit__(self, *exc_info): jpayne@68: """Undo the patch.""" jpayne@68: if not _is_started(self): jpayne@68: return jpayne@68: jpayne@68: if self.is_local and self.temp_original is not DEFAULT: jpayne@68: setattr(self.target, self.attribute, self.temp_original) jpayne@68: else: jpayne@68: delattr(self.target, self.attribute) jpayne@68: if not self.create and (not hasattr(self.target, self.attribute) or jpayne@68: self.attribute in ('__doc__', '__module__', jpayne@68: '__defaults__', '__annotations__', jpayne@68: '__kwdefaults__')): jpayne@68: # needed for proxy objects like django settings jpayne@68: setattr(self.target, self.attribute, self.temp_original) jpayne@68: jpayne@68: del self.temp_original jpayne@68: del self.is_local jpayne@68: del self.target jpayne@68: for patcher in reversed(self.additional_patchers): jpayne@68: if _is_started(patcher): jpayne@68: patcher.__exit__(*exc_info) jpayne@68: jpayne@68: jpayne@68: def start(self): jpayne@68: """Activate a patch, returning any created mock.""" jpayne@68: result = self.__enter__() jpayne@68: self._active_patches.append(self) jpayne@68: return result jpayne@68: jpayne@68: jpayne@68: def stop(self): jpayne@68: """Stop an active patch.""" jpayne@68: try: jpayne@68: self._active_patches.remove(self) jpayne@68: except ValueError: jpayne@68: # If the patch hasn't been started this will fail jpayne@68: pass jpayne@68: jpayne@68: return self.__exit__() jpayne@68: jpayne@68: jpayne@68: jpayne@68: def _get_target(target): jpayne@68: try: jpayne@68: target, attribute = target.rsplit('.', 1) jpayne@68: except (TypeError, ValueError): jpayne@68: raise TypeError("Need a valid target to patch. You supplied: %r" % jpayne@68: (target,)) jpayne@68: getter = lambda: _importer(target) jpayne@68: return getter, attribute jpayne@68: jpayne@68: jpayne@68: def _patch_object( jpayne@68: target, attribute, new=DEFAULT, spec=None, jpayne@68: create=False, spec_set=None, autospec=None, jpayne@68: new_callable=None, **kwargs jpayne@68: ): jpayne@68: """ jpayne@68: patch the named member (`attribute`) on an object (`target`) with a mock jpayne@68: object. jpayne@68: jpayne@68: `patch.object` can be used as a decorator, class decorator or a context jpayne@68: manager. Arguments `new`, `spec`, `create`, `spec_set`, jpayne@68: `autospec` and `new_callable` have the same meaning as for `patch`. Like jpayne@68: `patch`, `patch.object` takes arbitrary keyword arguments for configuring jpayne@68: the mock object it creates. jpayne@68: jpayne@68: When used as a class decorator `patch.object` honours `patch.TEST_PREFIX` jpayne@68: for choosing which methods to wrap. jpayne@68: """ jpayne@68: if type(target) is str: jpayne@68: raise TypeError( jpayne@68: f"{target!r} must be the actual object to be patched, not a str" jpayne@68: ) jpayne@68: getter = lambda: target jpayne@68: return _patch( jpayne@68: getter, attribute, new, spec, create, jpayne@68: spec_set, autospec, new_callable, kwargs jpayne@68: ) jpayne@68: jpayne@68: jpayne@68: def _patch_multiple(target, spec=None, create=False, spec_set=None, jpayne@68: autospec=None, new_callable=None, **kwargs): jpayne@68: """Perform multiple patches in a single call. It takes the object to be jpayne@68: patched (either as an object or a string to fetch the object by importing) jpayne@68: and keyword arguments for the patches:: jpayne@68: jpayne@68: with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'): jpayne@68: ... jpayne@68: jpayne@68: Use `DEFAULT` as the value if you want `patch.multiple` to create jpayne@68: mocks for you. In this case the created mocks are passed into a decorated jpayne@68: function by keyword, and a dictionary is returned when `patch.multiple` is jpayne@68: used as a context manager. jpayne@68: jpayne@68: `patch.multiple` can be used as a decorator, class decorator or a context jpayne@68: manager. The arguments `spec`, `spec_set`, `create`, jpayne@68: `autospec` and `new_callable` have the same meaning as for `patch`. These jpayne@68: arguments will be applied to *all* patches done by `patch.multiple`. jpayne@68: jpayne@68: When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX` jpayne@68: for choosing which methods to wrap. jpayne@68: """ jpayne@68: if type(target) is str: jpayne@68: getter = lambda: _importer(target) jpayne@68: else: jpayne@68: getter = lambda: target jpayne@68: jpayne@68: if not kwargs: jpayne@68: raise ValueError( jpayne@68: 'Must supply at least one keyword argument with patch.multiple' jpayne@68: ) jpayne@68: # need to wrap in a list for python 3, where items is a view jpayne@68: items = list(kwargs.items()) jpayne@68: attribute, new = items[0] jpayne@68: patcher = _patch( jpayne@68: getter, attribute, new, spec, create, spec_set, jpayne@68: autospec, new_callable, {} jpayne@68: ) jpayne@68: patcher.attribute_name = attribute jpayne@68: for attribute, new in items[1:]: jpayne@68: this_patcher = _patch( jpayne@68: getter, attribute, new, spec, create, spec_set, jpayne@68: autospec, new_callable, {} jpayne@68: ) jpayne@68: this_patcher.attribute_name = attribute jpayne@68: patcher.additional_patchers.append(this_patcher) jpayne@68: return patcher jpayne@68: jpayne@68: jpayne@68: def patch( jpayne@68: target, new=DEFAULT, spec=None, create=False, jpayne@68: spec_set=None, autospec=None, new_callable=None, **kwargs jpayne@68: ): jpayne@68: """ jpayne@68: `patch` acts as a function decorator, class decorator or a context jpayne@68: manager. Inside the body of the function or with statement, the `target` jpayne@68: is patched with a `new` object. When the function/with statement exits jpayne@68: the patch is undone. jpayne@68: jpayne@68: If `new` is omitted, then the target is replaced with an jpayne@68: `AsyncMock if the patched object is an async function or a jpayne@68: `MagicMock` otherwise. If `patch` is used as a decorator and `new` is jpayne@68: omitted, the created mock is passed in as an extra argument to the jpayne@68: decorated function. If `patch` is used as a context manager the created jpayne@68: mock is returned by the context manager. jpayne@68: jpayne@68: `target` should be a string in the form `'package.module.ClassName'`. The jpayne@68: `target` is imported and the specified object replaced with the `new` jpayne@68: object, so the `target` must be importable from the environment you are jpayne@68: calling `patch` from. The target is imported when the decorated function jpayne@68: is executed, not at decoration time. jpayne@68: jpayne@68: The `spec` and `spec_set` keyword arguments are passed to the `MagicMock` jpayne@68: if patch is creating one for you. jpayne@68: jpayne@68: In addition you can pass `spec=True` or `spec_set=True`, which causes jpayne@68: patch to pass in the object being mocked as the spec/spec_set object. jpayne@68: jpayne@68: `new_callable` allows you to specify a different class, or callable object, jpayne@68: that will be called to create the `new` object. By default `AsyncMock` is jpayne@68: used for async functions and `MagicMock` for the rest. jpayne@68: jpayne@68: A more powerful form of `spec` is `autospec`. If you set `autospec=True` jpayne@68: then the mock will be created with a spec from the object being replaced. jpayne@68: All attributes of the mock will also have the spec of the corresponding jpayne@68: attribute of the object being replaced. Methods and functions being jpayne@68: mocked will have their arguments checked and will raise a `TypeError` if jpayne@68: they are called with the wrong signature. For mocks replacing a class, jpayne@68: their return value (the 'instance') will have the same spec as the class. jpayne@68: jpayne@68: Instead of `autospec=True` you can pass `autospec=some_object` to use an jpayne@68: arbitrary object as the spec instead of the one being replaced. jpayne@68: jpayne@68: By default `patch` will fail to replace attributes that don't exist. If jpayne@68: you pass in `create=True`, and the attribute doesn't exist, patch will jpayne@68: create the attribute for you when the patched function is called, and jpayne@68: delete it again afterwards. This is useful for writing tests against jpayne@68: attributes that your production code creates at runtime. It is off by jpayne@68: default because it can be dangerous. With it switched on you can write jpayne@68: passing tests against APIs that don't actually exist! jpayne@68: jpayne@68: Patch can be used as a `TestCase` class decorator. It works by jpayne@68: decorating each test method in the class. This reduces the boilerplate jpayne@68: code when your test methods share a common patchings set. `patch` finds jpayne@68: tests by looking for method names that start with `patch.TEST_PREFIX`. jpayne@68: By default this is `test`, which matches the way `unittest` finds tests. jpayne@68: You can specify an alternative prefix by setting `patch.TEST_PREFIX`. jpayne@68: jpayne@68: Patch can be used as a context manager, with the with statement. Here the jpayne@68: patching applies to the indented block after the with statement. If you jpayne@68: use "as" then the patched object will be bound to the name after the jpayne@68: "as"; very useful if `patch` is creating a mock object for you. jpayne@68: jpayne@68: `patch` takes arbitrary keyword arguments. These will be passed to jpayne@68: the `Mock` (or `new_callable`) on construction. jpayne@68: jpayne@68: `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are jpayne@68: available for alternate use-cases. jpayne@68: """ jpayne@68: getter, attribute = _get_target(target) jpayne@68: return _patch( jpayne@68: getter, attribute, new, spec, create, jpayne@68: spec_set, autospec, new_callable, kwargs jpayne@68: ) jpayne@68: jpayne@68: jpayne@68: class _patch_dict(object): jpayne@68: """ jpayne@68: Patch a dictionary, or dictionary like object, and restore the dictionary jpayne@68: to its original state after the test. jpayne@68: jpayne@68: `in_dict` can be a dictionary or a mapping like container. If it is a jpayne@68: mapping then it must at least support getting, setting and deleting items jpayne@68: plus iterating over keys. jpayne@68: jpayne@68: `in_dict` can also be a string specifying the name of the dictionary, which jpayne@68: will then be fetched by importing it. jpayne@68: jpayne@68: `values` can be a dictionary of values to set in the dictionary. `values` jpayne@68: can also be an iterable of `(key, value)` pairs. jpayne@68: jpayne@68: If `clear` is True then the dictionary will be cleared before the new jpayne@68: values are set. jpayne@68: jpayne@68: `patch.dict` can also be called with arbitrary keyword arguments to set jpayne@68: values in the dictionary:: jpayne@68: jpayne@68: with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()): jpayne@68: ... jpayne@68: jpayne@68: `patch.dict` can be used as a context manager, decorator or class jpayne@68: decorator. When used as a class decorator `patch.dict` honours jpayne@68: `patch.TEST_PREFIX` for choosing which methods to wrap. jpayne@68: """ jpayne@68: jpayne@68: def __init__(self, in_dict, values=(), clear=False, **kwargs): jpayne@68: self.in_dict = in_dict jpayne@68: # support any argument supported by dict(...) constructor jpayne@68: self.values = dict(values) jpayne@68: self.values.update(kwargs) jpayne@68: self.clear = clear jpayne@68: self._original = None jpayne@68: jpayne@68: jpayne@68: def __call__(self, f): jpayne@68: if isinstance(f, type): jpayne@68: return self.decorate_class(f) jpayne@68: @wraps(f) jpayne@68: def _inner(*args, **kw): jpayne@68: self._patch_dict() jpayne@68: try: jpayne@68: return f(*args, **kw) jpayne@68: finally: jpayne@68: self._unpatch_dict() jpayne@68: jpayne@68: return _inner jpayne@68: jpayne@68: jpayne@68: def decorate_class(self, klass): jpayne@68: for attr in dir(klass): jpayne@68: attr_value = getattr(klass, attr) jpayne@68: if (attr.startswith(patch.TEST_PREFIX) and jpayne@68: hasattr(attr_value, "__call__")): jpayne@68: decorator = _patch_dict(self.in_dict, self.values, self.clear) jpayne@68: decorated = decorator(attr_value) jpayne@68: setattr(klass, attr, decorated) jpayne@68: return klass jpayne@68: jpayne@68: jpayne@68: def __enter__(self): jpayne@68: """Patch the dict.""" jpayne@68: self._patch_dict() jpayne@68: return self.in_dict jpayne@68: jpayne@68: jpayne@68: def _patch_dict(self): jpayne@68: values = self.values jpayne@68: if isinstance(self.in_dict, str): jpayne@68: self.in_dict = _importer(self.in_dict) jpayne@68: in_dict = self.in_dict jpayne@68: clear = self.clear jpayne@68: jpayne@68: try: jpayne@68: original = in_dict.copy() jpayne@68: except AttributeError: jpayne@68: # dict like object with no copy method jpayne@68: # must support iteration over keys jpayne@68: original = {} jpayne@68: for key in in_dict: jpayne@68: original[key] = in_dict[key] jpayne@68: self._original = original jpayne@68: jpayne@68: if clear: jpayne@68: _clear_dict(in_dict) jpayne@68: jpayne@68: try: jpayne@68: in_dict.update(values) jpayne@68: except AttributeError: jpayne@68: # dict like object with no update method jpayne@68: for key in values: jpayne@68: in_dict[key] = values[key] jpayne@68: jpayne@68: jpayne@68: def _unpatch_dict(self): jpayne@68: in_dict = self.in_dict jpayne@68: original = self._original jpayne@68: jpayne@68: _clear_dict(in_dict) jpayne@68: jpayne@68: try: jpayne@68: in_dict.update(original) jpayne@68: except AttributeError: jpayne@68: for key in original: jpayne@68: in_dict[key] = original[key] jpayne@68: jpayne@68: jpayne@68: def __exit__(self, *args): jpayne@68: """Unpatch the dict.""" jpayne@68: self._unpatch_dict() jpayne@68: return False jpayne@68: jpayne@68: start = __enter__ jpayne@68: stop = __exit__ jpayne@68: jpayne@68: jpayne@68: def _clear_dict(in_dict): jpayne@68: try: jpayne@68: in_dict.clear() jpayne@68: except AttributeError: jpayne@68: keys = list(in_dict) jpayne@68: for key in keys: jpayne@68: del in_dict[key] jpayne@68: jpayne@68: jpayne@68: def _patch_stopall(): jpayne@68: """Stop all active patches. LIFO to unroll nested patches.""" jpayne@68: for patch in reversed(_patch._active_patches): jpayne@68: patch.stop() jpayne@68: jpayne@68: jpayne@68: patch.object = _patch_object jpayne@68: patch.dict = _patch_dict jpayne@68: patch.multiple = _patch_multiple jpayne@68: patch.stopall = _patch_stopall jpayne@68: patch.TEST_PREFIX = 'test' jpayne@68: jpayne@68: magic_methods = ( jpayne@68: "lt le gt ge eq ne " jpayne@68: "getitem setitem delitem " jpayne@68: "len contains iter " jpayne@68: "hash str sizeof " jpayne@68: "enter exit " jpayne@68: # we added divmod and rdivmod here instead of numerics jpayne@68: # because there is no idivmod jpayne@68: "divmod rdivmod neg pos abs invert " jpayne@68: "complex int float index " jpayne@68: "round trunc floor ceil " jpayne@68: "bool next " jpayne@68: "fspath " jpayne@68: "aiter " jpayne@68: ) jpayne@68: jpayne@68: numerics = ( jpayne@68: "add sub mul matmul div floordiv mod lshift rshift and xor or pow truediv" jpayne@68: ) jpayne@68: inplace = ' '.join('i%s' % n for n in numerics.split()) jpayne@68: right = ' '.join('r%s' % n for n in numerics.split()) jpayne@68: jpayne@68: # not including __prepare__, __instancecheck__, __subclasscheck__ jpayne@68: # (as they are metaclass methods) jpayne@68: # __del__ is not supported at all as it causes problems if it exists jpayne@68: jpayne@68: _non_defaults = { jpayne@68: '__get__', '__set__', '__delete__', '__reversed__', '__missing__', jpayne@68: '__reduce__', '__reduce_ex__', '__getinitargs__', '__getnewargs__', jpayne@68: '__getstate__', '__setstate__', '__getformat__', '__setformat__', jpayne@68: '__repr__', '__dir__', '__subclasses__', '__format__', jpayne@68: '__getnewargs_ex__', jpayne@68: } jpayne@68: jpayne@68: jpayne@68: def _get_method(name, func): jpayne@68: "Turns a callable object (like a mock) into a real function" jpayne@68: def method(self, /, *args, **kw): jpayne@68: return func(self, *args, **kw) jpayne@68: method.__name__ = name jpayne@68: return method jpayne@68: jpayne@68: jpayne@68: _magics = { jpayne@68: '__%s__' % method for method in jpayne@68: ' '.join([magic_methods, numerics, inplace, right]).split() jpayne@68: } jpayne@68: jpayne@68: # Magic methods used for async `with` statements jpayne@68: _async_method_magics = {"__aenter__", "__aexit__", "__anext__"} jpayne@68: # Magic methods that are only used with async calls but are synchronous functions themselves jpayne@68: _sync_async_magics = {"__aiter__"} jpayne@68: _async_magics = _async_method_magics | _sync_async_magics jpayne@68: jpayne@68: _all_sync_magics = _magics | _non_defaults jpayne@68: _all_magics = _all_sync_magics | _async_magics jpayne@68: jpayne@68: _unsupported_magics = { jpayne@68: '__getattr__', '__setattr__', jpayne@68: '__init__', '__new__', '__prepare__', jpayne@68: '__instancecheck__', '__subclasscheck__', jpayne@68: '__del__' jpayne@68: } jpayne@68: jpayne@68: _calculate_return_value = { jpayne@68: '__hash__': lambda self: object.__hash__(self), jpayne@68: '__str__': lambda self: object.__str__(self), jpayne@68: '__sizeof__': lambda self: object.__sizeof__(self), jpayne@68: '__fspath__': lambda self: f"{type(self).__name__}/{self._extract_mock_name()}/{id(self)}", jpayne@68: } jpayne@68: jpayne@68: _return_values = { jpayne@68: '__lt__': NotImplemented, jpayne@68: '__gt__': NotImplemented, jpayne@68: '__le__': NotImplemented, jpayne@68: '__ge__': NotImplemented, jpayne@68: '__int__': 1, jpayne@68: '__contains__': False, jpayne@68: '__len__': 0, jpayne@68: '__exit__': False, jpayne@68: '__complex__': 1j, jpayne@68: '__float__': 1.0, jpayne@68: '__bool__': True, jpayne@68: '__index__': 1, jpayne@68: '__aexit__': False, jpayne@68: } jpayne@68: jpayne@68: jpayne@68: def _get_eq(self): jpayne@68: def __eq__(other): jpayne@68: ret_val = self.__eq__._mock_return_value jpayne@68: if ret_val is not DEFAULT: jpayne@68: return ret_val jpayne@68: if self is other: jpayne@68: return True jpayne@68: return NotImplemented jpayne@68: return __eq__ jpayne@68: jpayne@68: def _get_ne(self): jpayne@68: def __ne__(other): jpayne@68: if self.__ne__._mock_return_value is not DEFAULT: jpayne@68: return DEFAULT jpayne@68: if self is other: jpayne@68: return False jpayne@68: return NotImplemented jpayne@68: return __ne__ jpayne@68: jpayne@68: def _get_iter(self): jpayne@68: def __iter__(): jpayne@68: ret_val = self.__iter__._mock_return_value jpayne@68: if ret_val is DEFAULT: jpayne@68: return iter([]) jpayne@68: # if ret_val was already an iterator, then calling iter on it should jpayne@68: # return the iterator unchanged jpayne@68: return iter(ret_val) jpayne@68: return __iter__ jpayne@68: jpayne@68: def _get_async_iter(self): jpayne@68: def __aiter__(): jpayne@68: ret_val = self.__aiter__._mock_return_value jpayne@68: if ret_val is DEFAULT: jpayne@68: return _AsyncIterator(iter([])) jpayne@68: return _AsyncIterator(iter(ret_val)) jpayne@68: return __aiter__ jpayne@68: jpayne@68: _side_effect_methods = { jpayne@68: '__eq__': _get_eq, jpayne@68: '__ne__': _get_ne, jpayne@68: '__iter__': _get_iter, jpayne@68: '__aiter__': _get_async_iter jpayne@68: } jpayne@68: jpayne@68: jpayne@68: jpayne@68: def _set_return_value(mock, method, name): jpayne@68: fixed = _return_values.get(name, DEFAULT) jpayne@68: if fixed is not DEFAULT: jpayne@68: method.return_value = fixed jpayne@68: return jpayne@68: jpayne@68: return_calculator = _calculate_return_value.get(name) jpayne@68: if return_calculator is not None: jpayne@68: return_value = return_calculator(mock) jpayne@68: method.return_value = return_value jpayne@68: return jpayne@68: jpayne@68: side_effector = _side_effect_methods.get(name) jpayne@68: if side_effector is not None: jpayne@68: method.side_effect = side_effector(mock) jpayne@68: jpayne@68: jpayne@68: jpayne@68: class MagicMixin(Base): jpayne@68: def __init__(self, /, *args, **kw): jpayne@68: self._mock_set_magics() # make magic work for kwargs in init jpayne@68: _safe_super(MagicMixin, self).__init__(*args, **kw) jpayne@68: self._mock_set_magics() # fix magic broken by upper level init jpayne@68: jpayne@68: jpayne@68: def _mock_set_magics(self): jpayne@68: orig_magics = _magics | _async_method_magics jpayne@68: these_magics = orig_magics jpayne@68: jpayne@68: if getattr(self, "_mock_methods", None) is not None: jpayne@68: these_magics = orig_magics.intersection(self._mock_methods) jpayne@68: jpayne@68: remove_magics = set() jpayne@68: remove_magics = orig_magics - these_magics jpayne@68: jpayne@68: for entry in remove_magics: jpayne@68: if entry in type(self).__dict__: jpayne@68: # remove unneeded magic methods jpayne@68: delattr(self, entry) jpayne@68: jpayne@68: # don't overwrite existing attributes if called a second time jpayne@68: these_magics = these_magics - set(type(self).__dict__) jpayne@68: jpayne@68: _type = type(self) jpayne@68: for entry in these_magics: jpayne@68: setattr(_type, entry, MagicProxy(entry, self)) jpayne@68: jpayne@68: jpayne@68: jpayne@68: class NonCallableMagicMock(MagicMixin, NonCallableMock): jpayne@68: """A version of `MagicMock` that isn't callable.""" jpayne@68: def mock_add_spec(self, spec, spec_set=False): jpayne@68: """Add a spec to a mock. `spec` can either be an object or a jpayne@68: list of strings. Only attributes on the `spec` can be fetched as jpayne@68: attributes from the mock. jpayne@68: jpayne@68: If `spec_set` is True then only attributes on the spec can be set.""" jpayne@68: self._mock_add_spec(spec, spec_set) jpayne@68: self._mock_set_magics() jpayne@68: jpayne@68: jpayne@68: class AsyncMagicMixin(MagicMixin): jpayne@68: def __init__(self, /, *args, **kw): jpayne@68: self._mock_set_magics() # make magic work for kwargs in init jpayne@68: _safe_super(AsyncMagicMixin, self).__init__(*args, **kw) jpayne@68: self._mock_set_magics() # fix magic broken by upper level init jpayne@68: jpayne@68: class MagicMock(MagicMixin, Mock): jpayne@68: """ jpayne@68: MagicMock is a subclass of Mock with default implementations jpayne@68: of most of the magic methods. You can use MagicMock without having to jpayne@68: configure the magic methods yourself. jpayne@68: jpayne@68: If you use the `spec` or `spec_set` arguments then *only* magic jpayne@68: methods that exist in the spec will be created. jpayne@68: jpayne@68: Attributes and the return value of a `MagicMock` will also be `MagicMocks`. jpayne@68: """ jpayne@68: def mock_add_spec(self, spec, spec_set=False): jpayne@68: """Add a spec to a mock. `spec` can either be an object or a jpayne@68: list of strings. Only attributes on the `spec` can be fetched as jpayne@68: attributes from the mock. jpayne@68: jpayne@68: If `spec_set` is True then only attributes on the spec can be set.""" jpayne@68: self._mock_add_spec(spec, spec_set) jpayne@68: self._mock_set_magics() jpayne@68: jpayne@68: jpayne@68: jpayne@68: class MagicProxy(Base): jpayne@68: def __init__(self, name, parent): jpayne@68: self.name = name jpayne@68: self.parent = parent jpayne@68: jpayne@68: def create_mock(self): jpayne@68: entry = self.name jpayne@68: parent = self.parent jpayne@68: m = parent._get_child_mock(name=entry, _new_name=entry, jpayne@68: _new_parent=parent) jpayne@68: setattr(parent, entry, m) jpayne@68: _set_return_value(parent, m, entry) jpayne@68: return m jpayne@68: jpayne@68: def __get__(self, obj, _type=None): jpayne@68: return self.create_mock() jpayne@68: jpayne@68: jpayne@68: class AsyncMockMixin(Base): jpayne@68: await_count = _delegating_property('await_count') jpayne@68: await_args = _delegating_property('await_args') jpayne@68: await_args_list = _delegating_property('await_args_list') jpayne@68: jpayne@68: def __init__(self, /, *args, **kwargs): jpayne@68: super().__init__(*args, **kwargs) jpayne@68: # asyncio.iscoroutinefunction() checks _is_coroutine property to say if an jpayne@68: # object is a coroutine. Without this check it looks to see if it is a jpayne@68: # function/method, which in this case it is not (since it is an jpayne@68: # AsyncMock). jpayne@68: # It is set through __dict__ because when spec_set is True, this jpayne@68: # attribute is likely undefined. jpayne@68: self.__dict__['_is_coroutine'] = asyncio.coroutines._is_coroutine jpayne@68: self.__dict__['_mock_await_count'] = 0 jpayne@68: self.__dict__['_mock_await_args'] = None jpayne@68: self.__dict__['_mock_await_args_list'] = _CallList() jpayne@68: code_mock = NonCallableMock(spec_set=CodeType) jpayne@68: code_mock.co_flags = inspect.CO_COROUTINE jpayne@68: self.__dict__['__code__'] = code_mock jpayne@68: jpayne@68: async def _execute_mock_call(self, /, *args, **kwargs): jpayne@68: # This is nearly just like super(), except for sepcial handling jpayne@68: # of coroutines jpayne@68: jpayne@68: _call = self.call_args jpayne@68: self.await_count += 1 jpayne@68: self.await_args = _call jpayne@68: self.await_args_list.append(_call) jpayne@68: jpayne@68: effect = self.side_effect jpayne@68: if effect is not None: jpayne@68: if _is_exception(effect): jpayne@68: raise effect jpayne@68: elif not _callable(effect): jpayne@68: try: jpayne@68: result = next(effect) jpayne@68: except StopIteration: jpayne@68: # It is impossible to propogate a StopIteration jpayne@68: # through coroutines because of PEP 479 jpayne@68: raise StopAsyncIteration jpayne@68: if _is_exception(result): jpayne@68: raise result jpayne@68: elif asyncio.iscoroutinefunction(effect): jpayne@68: result = await effect(*args, **kwargs) jpayne@68: else: jpayne@68: result = effect(*args, **kwargs) jpayne@68: jpayne@68: if result is not DEFAULT: jpayne@68: return result jpayne@68: jpayne@68: if self._mock_return_value is not DEFAULT: jpayne@68: return self.return_value jpayne@68: jpayne@68: if self._mock_wraps is not None: jpayne@68: if asyncio.iscoroutinefunction(self._mock_wraps): jpayne@68: return await self._mock_wraps(*args, **kwargs) jpayne@68: return self._mock_wraps(*args, **kwargs) jpayne@68: jpayne@68: return self.return_value jpayne@68: jpayne@68: def assert_awaited(self): jpayne@68: """ jpayne@68: Assert that the mock was awaited at least once. jpayne@68: """ jpayne@68: if self.await_count == 0: jpayne@68: msg = f"Expected {self._mock_name or 'mock'} to have been awaited." jpayne@68: raise AssertionError(msg) jpayne@68: jpayne@68: def assert_awaited_once(self): jpayne@68: """ jpayne@68: Assert that the mock was awaited exactly once. jpayne@68: """ jpayne@68: if not self.await_count == 1: jpayne@68: msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once." jpayne@68: f" Awaited {self.await_count} times.") jpayne@68: raise AssertionError(msg) jpayne@68: jpayne@68: def assert_awaited_with(self, /, *args, **kwargs): jpayne@68: """ jpayne@68: Assert that the last await was with the specified arguments. jpayne@68: """ jpayne@68: if self.await_args is None: jpayne@68: expected = self._format_mock_call_signature(args, kwargs) jpayne@68: raise AssertionError(f'Expected await: {expected}\nNot awaited') jpayne@68: jpayne@68: def _error_message(): jpayne@68: msg = self._format_mock_failure_message(args, kwargs, action='await') jpayne@68: return msg jpayne@68: jpayne@68: expected = self._call_matcher((args, kwargs)) jpayne@68: actual = self._call_matcher(self.await_args) jpayne@68: if expected != actual: jpayne@68: cause = expected if isinstance(expected, Exception) else None jpayne@68: raise AssertionError(_error_message()) from cause jpayne@68: jpayne@68: def assert_awaited_once_with(self, /, *args, **kwargs): jpayne@68: """ jpayne@68: Assert that the mock was awaited exactly once and with the specified jpayne@68: arguments. jpayne@68: """ jpayne@68: if not self.await_count == 1: jpayne@68: msg = (f"Expected {self._mock_name or 'mock'} to have been awaited once." jpayne@68: f" Awaited {self.await_count} times.") jpayne@68: raise AssertionError(msg) jpayne@68: return self.assert_awaited_with(*args, **kwargs) jpayne@68: jpayne@68: def assert_any_await(self, /, *args, **kwargs): jpayne@68: """ jpayne@68: Assert the mock has ever been awaited with the specified arguments. jpayne@68: """ jpayne@68: expected = self._call_matcher((args, kwargs)) jpayne@68: actual = [self._call_matcher(c) for c in self.await_args_list] jpayne@68: if expected not in actual: jpayne@68: cause = expected if isinstance(expected, Exception) else None jpayne@68: expected_string = self._format_mock_call_signature(args, kwargs) jpayne@68: raise AssertionError( jpayne@68: '%s await not found' % expected_string jpayne@68: ) from cause jpayne@68: jpayne@68: def assert_has_awaits(self, calls, any_order=False): jpayne@68: """ jpayne@68: Assert the mock has been awaited with the specified calls. jpayne@68: The :attr:`await_args_list` list is checked for the awaits. jpayne@68: jpayne@68: If `any_order` is False (the default) then the awaits must be jpayne@68: sequential. There can be extra calls before or after the jpayne@68: specified awaits. jpayne@68: jpayne@68: If `any_order` is True then the awaits can be in any order, but jpayne@68: they must all appear in :attr:`await_args_list`. jpayne@68: """ jpayne@68: expected = [self._call_matcher(c) for c in calls] jpayne@68: cause = next((e for e in expected if isinstance(e, Exception)), None) jpayne@68: all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list) jpayne@68: if not any_order: jpayne@68: if expected not in all_awaits: jpayne@68: if cause is None: jpayne@68: problem = 'Awaits not found.' jpayne@68: else: jpayne@68: problem = ('Error processing expected awaits.\n' jpayne@68: 'Errors: {}').format( jpayne@68: [e if isinstance(e, Exception) else None jpayne@68: for e in expected]) jpayne@68: raise AssertionError( jpayne@68: f'{problem}\n' jpayne@68: f'Expected: {_CallList(calls)}\n' jpayne@68: f'Actual: {self.await_args_list}' jpayne@68: ) from cause jpayne@68: return jpayne@68: jpayne@68: all_awaits = list(all_awaits) jpayne@68: jpayne@68: not_found = [] jpayne@68: for kall in expected: jpayne@68: try: jpayne@68: all_awaits.remove(kall) jpayne@68: except ValueError: jpayne@68: not_found.append(kall) jpayne@68: if not_found: jpayne@68: raise AssertionError( jpayne@68: '%r not all found in await list' % (tuple(not_found),) jpayne@68: ) from cause jpayne@68: jpayne@68: def assert_not_awaited(self): jpayne@68: """ jpayne@68: Assert that the mock was never awaited. jpayne@68: """ jpayne@68: if self.await_count != 0: jpayne@68: msg = (f"Expected {self._mock_name or 'mock'} to not have been awaited." jpayne@68: f" Awaited {self.await_count} times.") jpayne@68: raise AssertionError(msg) jpayne@68: jpayne@68: def reset_mock(self, /, *args, **kwargs): jpayne@68: """ jpayne@68: See :func:`.Mock.reset_mock()` jpayne@68: """ jpayne@68: super().reset_mock(*args, **kwargs) jpayne@68: self.await_count = 0 jpayne@68: self.await_args = None jpayne@68: self.await_args_list = _CallList() jpayne@68: jpayne@68: jpayne@68: class AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock): jpayne@68: """ jpayne@68: Enhance :class:`Mock` with features allowing to mock jpayne@68: an async function. jpayne@68: jpayne@68: The :class:`AsyncMock` object will behave so the object is jpayne@68: recognized as an async function, and the result of a call is an awaitable: jpayne@68: jpayne@68: >>> mock = AsyncMock() jpayne@68: >>> asyncio.iscoroutinefunction(mock) jpayne@68: True jpayne@68: >>> inspect.isawaitable(mock()) jpayne@68: True jpayne@68: jpayne@68: jpayne@68: The result of ``mock()`` is an async function which will have the outcome jpayne@68: of ``side_effect`` or ``return_value``: jpayne@68: jpayne@68: - if ``side_effect`` is a function, the async function will return the jpayne@68: result of that function, jpayne@68: - if ``side_effect`` is an exception, the async function will raise the jpayne@68: exception, jpayne@68: - if ``side_effect`` is an iterable, the async function will return the jpayne@68: next value of the iterable, however, if the sequence of result is jpayne@68: exhausted, ``StopIteration`` is raised immediately, jpayne@68: - if ``side_effect`` is not defined, the async function will return the jpayne@68: value defined by ``return_value``, hence, by default, the async function jpayne@68: returns a new :class:`AsyncMock` object. jpayne@68: jpayne@68: If the outcome of ``side_effect`` or ``return_value`` is an async function, jpayne@68: the mock async function obtained when the mock object is called will be this jpayne@68: async function itself (and not an async function returning an async jpayne@68: function). jpayne@68: jpayne@68: The test author can also specify a wrapped object with ``wraps``. In this jpayne@68: case, the :class:`Mock` object behavior is the same as with an jpayne@68: :class:`.Mock` object: the wrapped object may have methods jpayne@68: defined as async function functions. jpayne@68: jpayne@68: Based on Martin Richard's asynctest project. jpayne@68: """ jpayne@68: jpayne@68: jpayne@68: class _ANY(object): jpayne@68: "A helper object that compares equal to everything." jpayne@68: jpayne@68: def __eq__(self, other): jpayne@68: return True jpayne@68: jpayne@68: def __ne__(self, other): jpayne@68: return False jpayne@68: jpayne@68: def __repr__(self): jpayne@68: return '' jpayne@68: jpayne@68: ANY = _ANY() jpayne@68: jpayne@68: jpayne@68: jpayne@68: def _format_call_signature(name, args, kwargs): jpayne@68: message = '%s(%%s)' % name jpayne@68: formatted_args = '' jpayne@68: args_string = ', '.join([repr(arg) for arg in args]) jpayne@68: kwargs_string = ', '.join([ jpayne@68: '%s=%r' % (key, value) for key, value in kwargs.items() jpayne@68: ]) jpayne@68: if args_string: jpayne@68: formatted_args = args_string jpayne@68: if kwargs_string: jpayne@68: if formatted_args: jpayne@68: formatted_args += ', ' jpayne@68: formatted_args += kwargs_string jpayne@68: jpayne@68: return message % formatted_args jpayne@68: jpayne@68: jpayne@68: jpayne@68: class _Call(tuple): jpayne@68: """ jpayne@68: A tuple for holding the results of a call to a mock, either in the form jpayne@68: `(args, kwargs)` or `(name, args, kwargs)`. jpayne@68: jpayne@68: If args or kwargs are empty then a call tuple will compare equal to jpayne@68: a tuple without those values. This makes comparisons less verbose:: jpayne@68: jpayne@68: _Call(('name', (), {})) == ('name',) jpayne@68: _Call(('name', (1,), {})) == ('name', (1,)) jpayne@68: _Call(((), {'a': 'b'})) == ({'a': 'b'},) jpayne@68: jpayne@68: The `_Call` object provides a useful shortcut for comparing with call:: jpayne@68: jpayne@68: _Call(((1, 2), {'a': 3})) == call(1, 2, a=3) jpayne@68: _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3) jpayne@68: jpayne@68: If the _Call has no name then it will match any name. jpayne@68: """ jpayne@68: def __new__(cls, value=(), name='', parent=None, two=False, jpayne@68: from_kall=True): jpayne@68: args = () jpayne@68: kwargs = {} jpayne@68: _len = len(value) jpayne@68: if _len == 3: jpayne@68: name, args, kwargs = value jpayne@68: elif _len == 2: jpayne@68: first, second = value jpayne@68: if isinstance(first, str): jpayne@68: name = first jpayne@68: if isinstance(second, tuple): jpayne@68: args = second jpayne@68: else: jpayne@68: kwargs = second jpayne@68: else: jpayne@68: args, kwargs = first, second jpayne@68: elif _len == 1: jpayne@68: value, = value jpayne@68: if isinstance(value, str): jpayne@68: name = value jpayne@68: elif isinstance(value, tuple): jpayne@68: args = value jpayne@68: else: jpayne@68: kwargs = value jpayne@68: jpayne@68: if two: jpayne@68: return tuple.__new__(cls, (args, kwargs)) jpayne@68: jpayne@68: return tuple.__new__(cls, (name, args, kwargs)) jpayne@68: jpayne@68: jpayne@68: def __init__(self, value=(), name=None, parent=None, two=False, jpayne@68: from_kall=True): jpayne@68: self._mock_name = name jpayne@68: self._mock_parent = parent jpayne@68: self._mock_from_kall = from_kall jpayne@68: jpayne@68: jpayne@68: def __eq__(self, other): jpayne@68: if other is ANY: jpayne@68: return True jpayne@68: try: jpayne@68: len_other = len(other) jpayne@68: except TypeError: jpayne@68: return False jpayne@68: jpayne@68: self_name = '' jpayne@68: if len(self) == 2: jpayne@68: self_args, self_kwargs = self jpayne@68: else: jpayne@68: self_name, self_args, self_kwargs = self jpayne@68: jpayne@68: if (getattr(self, '_mock_parent', None) and getattr(other, '_mock_parent', None) jpayne@68: and self._mock_parent != other._mock_parent): jpayne@68: return False jpayne@68: jpayne@68: other_name = '' jpayne@68: if len_other == 0: jpayne@68: other_args, other_kwargs = (), {} jpayne@68: elif len_other == 3: jpayne@68: other_name, other_args, other_kwargs = other jpayne@68: elif len_other == 1: jpayne@68: value, = other jpayne@68: if isinstance(value, tuple): jpayne@68: other_args = value jpayne@68: other_kwargs = {} jpayne@68: elif isinstance(value, str): jpayne@68: other_name = value jpayne@68: other_args, other_kwargs = (), {} jpayne@68: else: jpayne@68: other_args = () jpayne@68: other_kwargs = value jpayne@68: elif len_other == 2: jpayne@68: # could be (name, args) or (name, kwargs) or (args, kwargs) jpayne@68: first, second = other jpayne@68: if isinstance(first, str): jpayne@68: other_name = first jpayne@68: if isinstance(second, tuple): jpayne@68: other_args, other_kwargs = second, {} jpayne@68: else: jpayne@68: other_args, other_kwargs = (), second jpayne@68: else: jpayne@68: other_args, other_kwargs = first, second jpayne@68: else: jpayne@68: return False jpayne@68: jpayne@68: if self_name and other_name != self_name: jpayne@68: return False jpayne@68: jpayne@68: # this order is important for ANY to work! jpayne@68: return (other_args, other_kwargs) == (self_args, self_kwargs) jpayne@68: jpayne@68: jpayne@68: __ne__ = object.__ne__ jpayne@68: jpayne@68: jpayne@68: def __call__(self, /, *args, **kwargs): jpayne@68: if self._mock_name is None: jpayne@68: return _Call(('', args, kwargs), name='()') jpayne@68: jpayne@68: name = self._mock_name + '()' jpayne@68: return _Call((self._mock_name, args, kwargs), name=name, parent=self) jpayne@68: jpayne@68: jpayne@68: def __getattr__(self, attr): jpayne@68: if self._mock_name is None: jpayne@68: return _Call(name=attr, from_kall=False) jpayne@68: name = '%s.%s' % (self._mock_name, attr) jpayne@68: return _Call(name=name, parent=self, from_kall=False) jpayne@68: jpayne@68: jpayne@68: def __getattribute__(self, attr): jpayne@68: if attr in tuple.__dict__: jpayne@68: raise AttributeError jpayne@68: return tuple.__getattribute__(self, attr) jpayne@68: jpayne@68: jpayne@68: def count(self, /, *args, **kwargs): jpayne@68: return self.__getattr__('count')(*args, **kwargs) jpayne@68: jpayne@68: def index(self, /, *args, **kwargs): jpayne@68: return self.__getattr__('index')(*args, **kwargs) jpayne@68: jpayne@68: def _get_call_arguments(self): jpayne@68: if len(self) == 2: jpayne@68: args, kwargs = self jpayne@68: else: jpayne@68: name, args, kwargs = self jpayne@68: jpayne@68: return args, kwargs jpayne@68: jpayne@68: @property jpayne@68: def args(self): jpayne@68: return self._get_call_arguments()[0] jpayne@68: jpayne@68: @property jpayne@68: def kwargs(self): jpayne@68: return self._get_call_arguments()[1] jpayne@68: jpayne@68: def __repr__(self): jpayne@68: if not self._mock_from_kall: jpayne@68: name = self._mock_name or 'call' jpayne@68: if name.startswith('()'): jpayne@68: name = 'call%s' % name jpayne@68: return name jpayne@68: jpayne@68: if len(self) == 2: jpayne@68: name = 'call' jpayne@68: args, kwargs = self jpayne@68: else: jpayne@68: name, args, kwargs = self jpayne@68: if not name: jpayne@68: name = 'call' jpayne@68: elif not name.startswith('()'): jpayne@68: name = 'call.%s' % name jpayne@68: else: jpayne@68: name = 'call%s' % name jpayne@68: return _format_call_signature(name, args, kwargs) jpayne@68: jpayne@68: jpayne@68: def call_list(self): jpayne@68: """For a call object that represents multiple calls, `call_list` jpayne@68: returns a list of all the intermediate calls as well as the jpayne@68: final call.""" jpayne@68: vals = [] jpayne@68: thing = self jpayne@68: while thing is not None: jpayne@68: if thing._mock_from_kall: jpayne@68: vals.append(thing) jpayne@68: thing = thing._mock_parent jpayne@68: return _CallList(reversed(vals)) jpayne@68: jpayne@68: jpayne@68: call = _Call(from_kall=False) jpayne@68: jpayne@68: jpayne@68: def create_autospec(spec, spec_set=False, instance=False, _parent=None, jpayne@68: _name=None, **kwargs): jpayne@68: """Create a mock object using another object as a spec. Attributes on the jpayne@68: mock will use the corresponding attribute on the `spec` object as their jpayne@68: spec. jpayne@68: jpayne@68: Functions or methods being mocked will have their arguments checked jpayne@68: to check that they are called with the correct signature. jpayne@68: jpayne@68: If `spec_set` is True then attempting to set attributes that don't exist jpayne@68: on the spec object will raise an `AttributeError`. jpayne@68: jpayne@68: If a class is used as a spec then the return value of the mock (the jpayne@68: instance of the class) will have the same spec. You can use a class as the jpayne@68: spec for an instance object by passing `instance=True`. The returned mock jpayne@68: will only be callable if instances of the mock are callable. jpayne@68: jpayne@68: `create_autospec` also takes arbitrary keyword arguments that are passed to jpayne@68: the constructor of the created mock.""" jpayne@68: if _is_list(spec): jpayne@68: # can't pass a list instance to the mock constructor as it will be jpayne@68: # interpreted as a list of strings jpayne@68: spec = type(spec) jpayne@68: jpayne@68: is_type = isinstance(spec, type) jpayne@68: is_async_func = _is_async_func(spec) jpayne@68: _kwargs = {'spec': spec} jpayne@68: if spec_set: jpayne@68: _kwargs = {'spec_set': spec} jpayne@68: elif spec is None: jpayne@68: # None we mock with a normal mock without a spec jpayne@68: _kwargs = {} jpayne@68: if _kwargs and instance: jpayne@68: _kwargs['_spec_as_instance'] = True jpayne@68: jpayne@68: _kwargs.update(kwargs) jpayne@68: jpayne@68: Klass = MagicMock jpayne@68: if inspect.isdatadescriptor(spec): jpayne@68: # descriptors don't have a spec jpayne@68: # because we don't know what type they return jpayne@68: _kwargs = {} jpayne@68: elif is_async_func: jpayne@68: if instance: jpayne@68: raise RuntimeError("Instance can not be True when create_autospec " jpayne@68: "is mocking an async function") jpayne@68: Klass = AsyncMock jpayne@68: elif not _callable(spec): jpayne@68: Klass = NonCallableMagicMock jpayne@68: elif is_type and instance and not _instance_callable(spec): jpayne@68: Klass = NonCallableMagicMock jpayne@68: jpayne@68: _name = _kwargs.pop('name', _name) jpayne@68: jpayne@68: _new_name = _name jpayne@68: if _parent is None: jpayne@68: # for a top level object no _new_name should be set jpayne@68: _new_name = '' jpayne@68: jpayne@68: mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name, jpayne@68: name=_name, **_kwargs) jpayne@68: jpayne@68: if isinstance(spec, FunctionTypes): jpayne@68: # should only happen at the top level because we don't jpayne@68: # recurse for functions jpayne@68: mock = _set_signature(mock, spec) jpayne@68: if is_async_func: jpayne@68: _setup_async_mock(mock) jpayne@68: else: jpayne@68: _check_signature(spec, mock, is_type, instance) jpayne@68: jpayne@68: if _parent is not None and not instance: jpayne@68: _parent._mock_children[_name] = mock jpayne@68: jpayne@68: if is_type and not instance and 'return_value' not in kwargs: jpayne@68: mock.return_value = create_autospec(spec, spec_set, instance=True, jpayne@68: _name='()', _parent=mock) jpayne@68: jpayne@68: for entry in dir(spec): jpayne@68: if _is_magic(entry): jpayne@68: # MagicMock already does the useful magic methods for us jpayne@68: continue jpayne@68: jpayne@68: # XXXX do we need a better way of getting attributes without jpayne@68: # triggering code execution (?) Probably not - we need the actual jpayne@68: # object to mock it so we would rather trigger a property than mock jpayne@68: # the property descriptor. Likewise we want to mock out dynamically jpayne@68: # provided attributes. jpayne@68: # XXXX what about attributes that raise exceptions other than jpayne@68: # AttributeError on being fetched? jpayne@68: # we could be resilient against it, or catch and propagate the jpayne@68: # exception when the attribute is fetched from the mock jpayne@68: try: jpayne@68: original = getattr(spec, entry) jpayne@68: except AttributeError: jpayne@68: continue jpayne@68: jpayne@68: kwargs = {'spec': original} jpayne@68: if spec_set: jpayne@68: kwargs = {'spec_set': original} jpayne@68: jpayne@68: if not isinstance(original, FunctionTypes): jpayne@68: new = _SpecState(original, spec_set, mock, entry, instance) jpayne@68: mock._mock_children[entry] = new jpayne@68: else: jpayne@68: parent = mock jpayne@68: if isinstance(spec, FunctionTypes): jpayne@68: parent = mock.mock jpayne@68: jpayne@68: skipfirst = _must_skip(spec, entry, is_type) jpayne@68: kwargs['_eat_self'] = skipfirst jpayne@68: if asyncio.iscoroutinefunction(original): jpayne@68: child_klass = AsyncMock jpayne@68: else: jpayne@68: child_klass = MagicMock jpayne@68: new = child_klass(parent=parent, name=entry, _new_name=entry, jpayne@68: _new_parent=parent, jpayne@68: **kwargs) jpayne@68: mock._mock_children[entry] = new jpayne@68: _check_signature(original, new, skipfirst=skipfirst) jpayne@68: jpayne@68: # so functions created with _set_signature become instance attributes, jpayne@68: # *plus* their underlying mock exists in _mock_children of the parent jpayne@68: # mock. Adding to _mock_children may be unnecessary where we are also jpayne@68: # setting as an instance attribute? jpayne@68: if isinstance(new, FunctionTypes): jpayne@68: setattr(mock, entry, new) jpayne@68: jpayne@68: return mock jpayne@68: jpayne@68: jpayne@68: def _must_skip(spec, entry, is_type): jpayne@68: """ jpayne@68: Return whether we should skip the first argument on spec's `entry` jpayne@68: attribute. jpayne@68: """ jpayne@68: if not isinstance(spec, type): jpayne@68: if entry in getattr(spec, '__dict__', {}): jpayne@68: # instance attribute - shouldn't skip jpayne@68: return False jpayne@68: spec = spec.__class__ jpayne@68: jpayne@68: for klass in spec.__mro__: jpayne@68: result = klass.__dict__.get(entry, DEFAULT) jpayne@68: if result is DEFAULT: jpayne@68: continue jpayne@68: if isinstance(result, (staticmethod, classmethod)): jpayne@68: return False jpayne@68: elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes): jpayne@68: # Normal method => skip if looked up on type jpayne@68: # (if looked up on instance, self is already skipped) jpayne@68: return is_type jpayne@68: else: jpayne@68: return False jpayne@68: jpayne@68: # function is a dynamically provided attribute jpayne@68: return is_type jpayne@68: jpayne@68: jpayne@68: class _SpecState(object): jpayne@68: jpayne@68: def __init__(self, spec, spec_set=False, parent=None, jpayne@68: name=None, ids=None, instance=False): jpayne@68: self.spec = spec jpayne@68: self.ids = ids jpayne@68: self.spec_set = spec_set jpayne@68: self.parent = parent jpayne@68: self.instance = instance jpayne@68: self.name = name jpayne@68: jpayne@68: jpayne@68: FunctionTypes = ( jpayne@68: # python function jpayne@68: type(create_autospec), jpayne@68: # instance method jpayne@68: type(ANY.__eq__), jpayne@68: ) jpayne@68: jpayne@68: MethodWrapperTypes = ( jpayne@68: type(ANY.__eq__.__get__), jpayne@68: ) jpayne@68: jpayne@68: jpayne@68: file_spec = None jpayne@68: jpayne@68: jpayne@68: def _to_stream(read_data): jpayne@68: if isinstance(read_data, bytes): jpayne@68: return io.BytesIO(read_data) jpayne@68: else: jpayne@68: return io.StringIO(read_data) jpayne@68: jpayne@68: jpayne@68: def mock_open(mock=None, read_data=''): jpayne@68: """ jpayne@68: A helper function to create a mock to replace the use of `open`. It works jpayne@68: for `open` called directly or used as a context manager. jpayne@68: jpayne@68: The `mock` argument is the mock object to configure. If `None` (the jpayne@68: default) then a `MagicMock` will be created for you, with the API limited jpayne@68: to methods or attributes available on standard file handles. jpayne@68: jpayne@68: `read_data` is a string for the `read`, `readline` and `readlines` of the jpayne@68: file handle to return. This is an empty string by default. jpayne@68: """ jpayne@68: _read_data = _to_stream(read_data) jpayne@68: _state = [_read_data, None] jpayne@68: jpayne@68: def _readlines_side_effect(*args, **kwargs): jpayne@68: if handle.readlines.return_value is not None: jpayne@68: return handle.readlines.return_value jpayne@68: return _state[0].readlines(*args, **kwargs) jpayne@68: jpayne@68: def _read_side_effect(*args, **kwargs): jpayne@68: if handle.read.return_value is not None: jpayne@68: return handle.read.return_value jpayne@68: return _state[0].read(*args, **kwargs) jpayne@68: jpayne@68: def _readline_side_effect(*args, **kwargs): jpayne@68: yield from _iter_side_effect() jpayne@68: while True: jpayne@68: yield _state[0].readline(*args, **kwargs) jpayne@68: jpayne@68: def _iter_side_effect(): jpayne@68: if handle.readline.return_value is not None: jpayne@68: while True: jpayne@68: yield handle.readline.return_value jpayne@68: for line in _state[0]: jpayne@68: yield line jpayne@68: jpayne@68: def _next_side_effect(): jpayne@68: if handle.readline.return_value is not None: jpayne@68: return handle.readline.return_value jpayne@68: return next(_state[0]) jpayne@68: jpayne@68: global file_spec jpayne@68: if file_spec is None: jpayne@68: import _io jpayne@68: file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO)))) jpayne@68: jpayne@68: if mock is None: jpayne@68: mock = MagicMock(name='open', spec=open) jpayne@68: jpayne@68: handle = MagicMock(spec=file_spec) jpayne@68: handle.__enter__.return_value = handle jpayne@68: jpayne@68: handle.write.return_value = None jpayne@68: handle.read.return_value = None jpayne@68: handle.readline.return_value = None jpayne@68: handle.readlines.return_value = None jpayne@68: jpayne@68: handle.read.side_effect = _read_side_effect jpayne@68: _state[1] = _readline_side_effect() jpayne@68: handle.readline.side_effect = _state[1] jpayne@68: handle.readlines.side_effect = _readlines_side_effect jpayne@68: handle.__iter__.side_effect = _iter_side_effect jpayne@68: handle.__next__.side_effect = _next_side_effect jpayne@68: jpayne@68: def reset_data(*args, **kwargs): jpayne@68: _state[0] = _to_stream(read_data) jpayne@68: if handle.readline.side_effect == _state[1]: jpayne@68: # Only reset the side effect if the user hasn't overridden it. jpayne@68: _state[1] = _readline_side_effect() jpayne@68: handle.readline.side_effect = _state[1] jpayne@68: return DEFAULT jpayne@68: jpayne@68: mock.side_effect = reset_data jpayne@68: mock.return_value = handle jpayne@68: return mock jpayne@68: jpayne@68: jpayne@68: class PropertyMock(Mock): jpayne@68: """ jpayne@68: A mock intended to be used as a property, or other descriptor, on a class. jpayne@68: `PropertyMock` provides `__get__` and `__set__` methods so you can specify jpayne@68: a return value when it is fetched. jpayne@68: jpayne@68: Fetching a `PropertyMock` instance from an object calls the mock, with jpayne@68: no args. Setting it calls the mock with the value being set. jpayne@68: """ jpayne@68: def _get_child_mock(self, /, **kwargs): jpayne@68: return MagicMock(**kwargs) jpayne@68: jpayne@68: def __get__(self, obj, obj_type=None): jpayne@68: return self() jpayne@68: def __set__(self, obj, val): jpayne@68: self(val) jpayne@68: jpayne@68: jpayne@68: def seal(mock): jpayne@68: """Disable the automatic generation of child mocks. jpayne@68: jpayne@68: Given an input Mock, seals it to ensure no further mocks will be generated jpayne@68: when accessing an attribute that was not already defined. jpayne@68: jpayne@68: The operation recursively seals the mock passed in, meaning that jpayne@68: the mock itself, any mocks generated by accessing one of its attributes, jpayne@68: and all assigned mocks without a name or spec will be sealed. jpayne@68: """ jpayne@68: mock._mock_sealed = True jpayne@68: for attr in dir(mock): jpayne@68: try: jpayne@68: m = getattr(mock, attr) jpayne@68: except AttributeError: jpayne@68: continue jpayne@68: if not isinstance(m, NonCallableMock): jpayne@68: continue jpayne@68: if m._mock_new_parent is mock: jpayne@68: seal(m) jpayne@68: jpayne@68: jpayne@68: class _AsyncIterator: jpayne@68: """ jpayne@68: Wraps an iterator in an asynchronous iterator. jpayne@68: """ jpayne@68: def __init__(self, iterator): jpayne@68: self.iterator = iterator jpayne@68: code_mock = NonCallableMock(spec_set=CodeType) jpayne@68: code_mock.co_flags = inspect.CO_ITERABLE_COROUTINE jpayne@68: self.__dict__['__code__'] = code_mock jpayne@68: jpayne@68: def __aiter__(self): jpayne@68: return self jpayne@68: jpayne@68: async def __anext__(self): jpayne@68: try: jpayne@68: return next(self.iterator) jpayne@68: except StopIteration: jpayne@68: pass jpayne@68: raise StopAsyncIteration