2 # Test tools for mocking and patching.
3 # E-mail: fuzzyman AT voidspace DOT org DOT uk
6 # http://www.voidspace.org.uk/python/mock/
8 # Copyright (c) 2007-2013, Michael Foord & the mock team
11 # Redistribution and use in source and binary forms, with or without
12 # modification, are permitted provided that the following conditions are
15 # * Redistributions of source code must retain the above copyright
16 # notice, this list of conditions and the following disclaimer.
18 # * Redistributions in binary form must reproduce the above
19 # copyright notice, this list of conditions and the following
20 # disclaimer in the documentation and/or other materials provided
21 # with the distribution.
23 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46 'NonCallableMagicMock',
61 # for alternative platforms that
62 # may not have inspect
66 from functools import wraps as original_wraps
68 # Python 2.4 compatibility
71 f.__name__ = original.__name__
72 f.__doc__ = original.__doc__
73 f.__module__ = original.__module__
74 wrapped = getattr(original, '__wrapped__', original)
75 f.__wrapped__ = wrapped
79 if sys.version_info[:2] >= (3, 2):
80 wraps = original_wraps
84 f = original_wraps(func)(f)
85 wrapped = getattr(func, '__wrapped__', func)
86 f.__wrapped__ = wrapped
94 basestring = unicode = str
105 # Python 2.4 compatibility
106 BaseException = Exception
115 BaseExceptions = (BaseException,)
116 if 'java' in sys.platform:
119 BaseExceptions = (BaseException, java.lang.Throwable)
122 _isidentifier = str.isidentifier
123 except AttributeError:
127 regex = re.compile(r'^[a-z_][a-z0-9_]*$', re.I)
129 def _isidentifier(string):
130 if string in keyword.kwlist:
132 return regex.match(string)
135 inPy3k = sys.version_info[0] == 3
137 # Needed to work around Python 3 bug where use of "super" interferes with
138 # defining __class__ as a descriptor
142 builtin = '__builtin__'
150 def _is_instance_mock(obj):
151 # can't use isinstance on Mock objects because they override __class__
152 # The base class for all mocks is NonCallableMock
153 return issubclass(type(obj), NonCallableMock)
156 def _is_exception(obj):
158 isinstance(obj, BaseExceptions) or
159 isinstance(obj, ClassTypes) and issubclass(obj, BaseExceptions)
163 class _slotted(object):
173 def _getsignature(func, skipfirst, instance=False):
175 raise ImportError('inspect module not available')
177 if isinstance(func, ClassTypes) and not instance:
180 except AttributeError:
183 elif not isinstance(func, FunctionTypes):
184 # for classes where instance is True we end up here too
187 except AttributeError:
192 argspec = inspect.getfullargspec(func)
194 # C function / method, possibly inherited object().__init__
196 regargs, varargs, varkw, defaults, kwonly, kwonlydef, ann = argspec
199 regargs, varargs, varkwargs, defaults = inspect.getargspec(func)
201 # C function / method, possibly inherited object().__init__
204 # instance methods and classmethods need to lose the self argument
205 if getattr(func, self, None) is not None:
206 regargs = regargs[1:]
208 # this condition and the above one are never both True - why?
209 regargs = regargs[1:]
212 signature = inspect.formatargspec(
213 regargs, varargs, varkw, defaults,
214 kwonly, kwonlydef, ann, formatvalue=lambda value: "")
216 signature = inspect.formatargspec(
217 regargs, varargs, varkwargs, defaults,
218 formatvalue=lambda value: "")
219 return signature[1:-1], func
222 def _check_signature(func, mock, skipfirst, instance=False):
223 if not _callable(func):
226 result = _getsignature(func, skipfirst, instance)
229 signature, func = result
231 # can't use self because "self" is common as an argument name
232 # unfortunately even not in the first place
233 src = "lambda _mock_self, %s: None" % signature
234 checksig = eval(src, {})
235 _copy_func_details(func, checksig)
236 type(mock)._mock_check_sig = checksig
239 def _copy_func_details(func, funcopy):
240 funcopy.__name__ = func.__name__
241 funcopy.__doc__ = func.__doc__
242 # funcopy.__dict__.update(func.__dict__)
243 funcopy.__module__ = func.__module__
245 funcopy.func_defaults = func.func_defaults
247 funcopy.__defaults__ = func.__defaults__
248 funcopy.__kwdefaults__ = func.__kwdefaults__
252 if isinstance(obj, ClassTypes):
254 if getattr(obj, '__call__', None) is not None:
260 # checks for list or tuples
262 return type(obj) in (list, tuple)
265 def _instance_callable(obj):
266 """Given an object, return True if the object is callable.
267 For classes, return True if instances would be callable."""
268 if not isinstance(obj, ClassTypes):
269 # already an instance
270 return getattr(obj, '__call__', None) is not None
273 # uses __bases__ instead of __mro__ so that we work with old style classes
274 if klass.__dict__.get('__call__') is not None:
277 for base in klass.__bases__:
278 if _instance_callable(base):
283 def _set_signature(mock, original, instance=False):
284 # creates a function with signature (*args, **kwargs) that delegates to a
285 # mock. It still does signature checking by calling a lambda with the same
286 # signature as the original.
287 if not _callable(original):
290 skipfirst = isinstance(original, ClassTypes)
291 result = _getsignature(original, skipfirst, instance)
293 # was a C function (e.g. object().__init__ ) that can't be mocked
296 signature, func = result
298 src = "lambda %s: None" % signature
299 checksig = eval(src, {})
300 _copy_func_details(func, checksig)
302 name = original.__name__
303 if not _isidentifier(name):
305 context = {'_checksig_': checksig, 'mock': mock}
306 src = """def %s(*args, **kwargs):
307 _checksig_(*args, **kwargs)
308 return mock(*args, **kwargs)""" % name
310 funcopy = context[name]
311 _setup_func(funcopy, mock)
315 def _setup_func(funcopy, mock):
318 # can't use isinstance with mocks
319 if not _is_instance_mock(mock):
322 def assert_called_with(*args, **kwargs):
323 return mock.assert_called_with(*args, **kwargs)
325 def assert_called_once_with(*args, **kwargs):
326 return mock.assert_called_once_with(*args, **kwargs)
328 def assert_has_calls(*args, **kwargs):
329 return mock.assert_has_calls(*args, **kwargs)
331 def assert_any_call(*args, **kwargs):
332 return mock.assert_any_call(*args, **kwargs)
335 funcopy.method_calls = _CallList()
336 funcopy.mock_calls = _CallList()
338 ret = funcopy.return_value
339 if _is_instance_mock(ret) and ret is not mock:
342 funcopy.called = False
343 funcopy.call_count = 0
344 funcopy.call_args = None
345 funcopy.call_args_list = _CallList()
346 funcopy.method_calls = _CallList()
347 funcopy.mock_calls = _CallList()
349 funcopy.return_value = mock.return_value
350 funcopy.side_effect = mock.side_effect
351 funcopy._mock_children = mock._mock_children
353 funcopy.assert_called_with = assert_called_with
354 funcopy.assert_called_once_with = assert_called_once_with
355 funcopy.assert_has_calls = assert_has_calls
356 funcopy.assert_any_call = assert_any_call
357 funcopy.reset_mock = reset_mock
359 mock._mock_delegate = funcopy
363 return '__%s__' % name[2:-2] == name
366 class _SentinelObject(object):
367 "A unique, named, sentinel object."
369 def __init__(self, name):
373 return 'sentinel.%s' % self.name
376 class _Sentinel(object):
377 """Access attributes to return a named object, usable as a sentinel."""
382 def __getattr__(self, name):
383 if name == '__bases__':
384 # Without this help(mock) raises an exception
386 return self._sentinels.setdefault(name, _SentinelObject(name))
389 sentinel = _Sentinel()
391 DEFAULT = sentinel.DEFAULT
392 _missing = sentinel.MISSING
393 _deleted = sentinel.DELETED
398 ClassType = type(OldStyleClass)
402 if type(value) in (dict, list, tuple, set):
403 return type(value)(value)
409 ClassTypes = (type, ClassType)
411 _allowed_names = set(
413 'return_value', '_mock_return_value', 'side_effect',
414 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
415 '_mock_name', '_mock_new_name'
420 def _delegating_property(name):
421 _allowed_names.add(name)
422 _the_name = '_mock_' + name
424 def _get(self, name=name, _the_name=_the_name):
425 sig = self._mock_delegate
427 return getattr(self, _the_name)
428 return getattr(sig, name)
430 def _set(self, value, name=name, _the_name=_the_name):
431 sig = self._mock_delegate
433 self.__dict__[_the_name] = value
435 setattr(sig, name, value)
437 return property(_get, _set)
440 class _CallList(list):
442 def __contains__(self, value):
443 if not isinstance(value, list):
444 return list.__contains__(self, value)
445 len_value = len(value)
447 if len_value > len_self:
450 for i in range(0, len_self - len_value + 1):
451 sub_list = self[i:i + len_value]
452 if sub_list == value:
457 return pprint.pformat(list(self))
460 def _check_and_set_parent(parent, value, name, new_name):
461 if not _is_instance_mock(value):
463 if ((value._mock_name or value._mock_new_name) or
464 (value._mock_parent is not None) or
465 (value._mock_new_parent is not None)):
469 while _parent is not None:
470 # setting a mock (value) as a child or return value of itself
471 # should not modify the mock
474 _parent = _parent._mock_new_parent
477 value._mock_new_parent = parent
478 value._mock_new_name = new_name
480 value._mock_parent = parent
481 value._mock_name = name
486 _mock_return_value = DEFAULT
487 _mock_side_effect = None
489 def __init__(self, *args, **kwargs):
493 class NonCallableMock(Base):
494 """A non-callable version of `Mock`"""
496 def __new__(cls, *args, **kw):
497 # every instance has its own class
498 # so we can create magic methods on the
499 # class without stomping on other mocks
500 new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
501 instance = object.__new__(new)
505 self, spec=None, wraps=None, name=None, spec_set=None,
506 parent=None, _spec_state=None, _new_name='', _new_parent=None,
509 if _new_parent is None:
512 __dict__ = self.__dict__
513 __dict__['_mock_parent'] = parent
514 __dict__['_mock_name'] = name
515 __dict__['_mock_new_name'] = _new_name
516 __dict__['_mock_new_parent'] = _new_parent
518 if spec_set is not None:
522 self._mock_add_spec(spec, spec_set)
524 __dict__['_mock_children'] = {}
525 __dict__['_mock_wraps'] = wraps
526 __dict__['_mock_delegate'] = None
528 __dict__['_mock_called'] = False
529 __dict__['_mock_call_args'] = None
530 __dict__['_mock_call_count'] = 0
531 __dict__['_mock_call_args_list'] = _CallList()
532 __dict__['_mock_mock_calls'] = _CallList()
534 __dict__['method_calls'] = _CallList()
537 self.configure_mock(**kwargs)
539 _super(NonCallableMock, self).__init__(
540 spec, wraps, name, spec_set, parent,
544 def attach_mock(self, mock, attribute):
546 Attach a mock as an attribute of this one, replacing its name and
547 parent. Calls to the attached mock will be recorded in the
548 `method_calls` and `mock_calls` attributes of this one."""
549 mock._mock_parent = None
550 mock._mock_new_parent = None
552 mock._mock_new_name = None
554 setattr(self, attribute, mock)
556 def mock_add_spec(self, spec, spec_set=False):
557 """Add a spec to a mock. `spec` can either be an object or a
558 list of strings. Only attributes on the `spec` can be fetched as
559 attributes from the mock.
561 If `spec_set` is True then only attributes on the spec can be set."""
562 self._mock_add_spec(spec, spec_set)
564 def _mock_add_spec(self, spec, spec_set):
567 if spec is not None and not _is_list(spec):
568 if isinstance(spec, ClassTypes):
571 _spec_class = _get_class(spec)
575 __dict__ = self.__dict__
576 __dict__['_spec_class'] = _spec_class
577 __dict__['_spec_set'] = spec_set
578 __dict__['_mock_methods'] = spec
580 def __get_return_value(self):
581 ret = self._mock_return_value
582 if self._mock_delegate is not None:
583 ret = self._mock_delegate.return_value
586 ret = self._get_child_mock(
587 _new_parent=self, _new_name='()'
589 self.return_value = ret
592 def __set_return_value(self, value):
593 if self._mock_delegate is not None:
594 self._mock_delegate.return_value = value
596 self._mock_return_value = value
597 _check_and_set_parent(self, value, None, '()')
599 __return_value_doc = "The value to be returned when the mock is called."
600 return_value = property(__get_return_value, __set_return_value,
605 if self._spec_class is None:
607 return self._spec_class
609 called = _delegating_property('called')
610 call_count = _delegating_property('call_count')
611 call_args = _delegating_property('call_args')
612 call_args_list = _delegating_property('call_args_list')
613 mock_calls = _delegating_property('mock_calls')
615 def __get_side_effect(self):
616 sig = self._mock_delegate
618 return self._mock_side_effect
619 return sig.side_effect
621 def __set_side_effect(self, value):
622 value = _try_iter(value)
623 sig = self._mock_delegate
625 self._mock_side_effect = value
627 sig.side_effect = value
629 side_effect = property(__get_side_effect, __set_side_effect)
631 def reset_mock(self):
632 "Restore the mock object to its initial state."
634 self.call_args = None
636 self.mock_calls = _CallList()
637 self.call_args_list = _CallList()
638 self.method_calls = _CallList()
640 for child in self._mock_children.values():
641 if isinstance(child, _SpecState):
645 ret = self._mock_return_value
646 if _is_instance_mock(ret) and ret is not self:
649 def configure_mock(self, **kwargs):
650 """Set attributes on the mock through keyword arguments.
652 Attributes plus return values and side effects can be set on child
653 mocks using standard dot notation and unpacking a dictionary in the
656 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
657 >>> mock.configure_mock(**attrs)"""
658 for arg, val in sorted(kwargs.items(),
659 # we sort on the number of dots so that
660 # attributes are set before we set attributes on
662 key=lambda entry: entry[0].count('.')):
663 args = arg.split('.')
667 obj = getattr(obj, entry)
668 setattr(obj, final, val)
670 def __getattr__(self, name):
671 if name == '_mock_methods':
672 raise AttributeError(name)
673 elif self._mock_methods is not None:
674 if name not in self._mock_methods or name in _all_magics:
675 raise AttributeError("Mock object has no attribute %r" % name)
676 elif _is_magic(name):
677 raise AttributeError(name)
679 result = self._mock_children.get(name)
680 if result is _deleted:
681 raise AttributeError(name)
684 if self._mock_wraps is not None:
685 # XXXX should we get the attribute without triggering code
687 wraps = getattr(self._mock_wraps, name)
689 result = self._get_child_mock(
690 parent=self, name=name, wraps=wraps, _new_name=name,
693 self._mock_children[name] = result
695 elif isinstance(result, _SpecState):
696 result = create_autospec(
697 result.spec, result.spec_set, result.instance,
698 result.parent, result.name
700 self._mock_children[name] = result
705 _name_list = [self._mock_new_name]
706 _parent = self._mock_new_parent
710 if _name_list == ['()']:
713 while _parent is not None:
716 _name_list.append(_parent._mock_new_name + dot)
718 if _parent._mock_new_name == '()':
721 _parent = _parent._mock_new_parent
723 # use ids here so as not to call __hash__ on the mocks
724 if id(_parent) in seen:
726 seen.add(id(_parent))
728 _name_list = list(reversed(_name_list))
729 _first = last._mock_name or 'mock'
730 if len(_name_list) > 1:
731 if _name_list[1] not in ('()', '().'):
733 _name_list[0] = _first
734 name = ''.join(_name_list)
737 if name not in ('mock', 'mock.'):
738 name_string = ' name=%r' % name
741 if self._spec_class is not None:
742 spec_string = ' spec=%r'
744 spec_string = ' spec_set=%r'
745 spec_string = spec_string % self._spec_class.__name__
746 return "<%s%s%s id='%s'>" % (
754 """Filter the output of `dir(mock)` to only useful members."""
755 extras = self._mock_methods or []
756 from_type = dir(type(self))
757 from_dict = list(self.__dict__)
760 from_type = [e for e in from_type if not e.startswith('_')]
761 from_dict = [e for e in from_dict if not e.startswith('_') or
763 return sorted(set(extras + from_type + from_dict +
764 list(self._mock_children)))
766 def __setattr__(self, name, value):
767 if name in _allowed_names:
768 # property setters go through here
769 return object.__setattr__(self, name, value)
770 elif (self._spec_set and self._mock_methods is not None and
771 name not in self._mock_methods and
772 name not in self.__dict__):
773 raise AttributeError("Mock object has no attribute '%s'" % name)
774 elif name in _unsupported_magics:
775 msg = 'Attempting to set unsupported magic method %r.' % name
776 raise AttributeError(msg)
777 elif name in _all_magics:
778 if self._mock_methods is not None and name not in self._mock_methods:
779 raise AttributeError("Mock object has no attribute '%s'" % name)
781 if not _is_instance_mock(value):
782 setattr(type(self), name, _get_method(name, value))
784 value = lambda *args, **kw: original(self, *args, **kw)
786 # only set _new_name and not name so that mock_calls is tracked
787 # but not method calls
788 _check_and_set_parent(self, value, None, name)
789 setattr(type(self), name, value)
790 self._mock_children[name] = value
791 elif name == '__class__':
792 self._spec_class = value
795 if _check_and_set_parent(self, value, name, name):
796 self._mock_children[name] = value
797 return object.__setattr__(self, name, value)
799 def __delattr__(self, name):
800 if name in _all_magics and name in type(self).__dict__:
801 delattr(type(self), name)
802 if name not in self.__dict__:
803 # for magic methods that are still MagicProxy objects and
804 # not set on the instance itself
807 if name in self.__dict__:
808 object.__delattr__(self, name)
810 obj = self._mock_children.get(name, _missing)
812 raise AttributeError(name)
813 if obj is not _missing:
814 del self._mock_children[name]
815 self._mock_children[name] = _deleted
817 def _format_mock_call_signature(self, args, kwargs):
818 name = self._mock_name or 'mock'
819 return _format_call_signature(name, args, kwargs)
821 def _format_mock_failure_message(self, args, kwargs):
822 message = 'Expected call: %s\nActual call: %s'
823 expected_string = self._format_mock_call_signature(args, kwargs)
824 call_args = self.call_args
825 if len(call_args) == 3:
826 call_args = call_args[1:]
827 actual_string = self._format_mock_call_signature(*call_args)
828 return message % (expected_string, actual_string)
830 def assert_called_with(_mock_self, *args, **kwargs):
831 """assert that the mock was called with the specified arguments.
833 Raises an AssertionError if the args and keyword args passed in are
834 different to the last call to the mock."""
836 if self.call_args is None:
837 expected = self._format_mock_call_signature(args, kwargs)
838 raise AssertionError('Expected call: %s\nNot called' % (expected,))
840 if self.call_args != (args, kwargs):
841 msg = self._format_mock_failure_message(args, kwargs)
842 raise AssertionError(msg)
844 def assert_called_once_with(_mock_self, *args, **kwargs):
845 """assert that the mock was called exactly once and with the specified
848 if not self.call_count == 1:
849 msg = ("Expected to be called once. Called %s times." %
851 raise AssertionError(msg)
852 return self.assert_called_with(*args, **kwargs)
854 def assert_has_calls(self, calls, any_order=False):
855 """assert the mock has been called with the specified calls.
856 The `mock_calls` list is checked for the calls.
858 If `any_order` is False (the default) then the calls must be
859 sequential. There can be extra calls before or after the
862 If `any_order` is True then the calls can be in any order, but
863 they must all appear in `mock_calls`."""
865 if calls not in self.mock_calls:
866 raise AssertionError(
867 'Calls not found.\nExpected: %r\n'
868 'Actual: %r' % (calls, self.mock_calls)
872 all_calls = list(self.mock_calls)
877 all_calls.remove(kall)
879 not_found.append(kall)
881 raise AssertionError(
882 '%r not all found in call list' % (tuple(not_found),)
885 def assert_any_call(self, *args, **kwargs):
886 """assert the mock has been called with the specified arguments.
888 The assert passes if the mock has *ever* been called, unlike
889 `assert_called_with` and `assert_called_once_with` that only pass if
890 the call is the most recent one."""
891 kall = call(*args, **kwargs)
892 if kall not in self.call_args_list:
893 expected_string = self._format_mock_call_signature(args, kwargs)
894 raise AssertionError(
895 '%s call not found' % expected_string
898 def _get_child_mock(self, **kw):
899 """Create the child mocks for attributes and return value.
900 By default child mocks will be the same type as the parent.
901 Subclasses of Mock may want to override this to customize the way
902 child mocks are made.
904 For non-callable mocks the callable variant will be used (rather than
905 any custom subclass)."""
907 if not issubclass(_type, CallableMixin):
908 if issubclass(_type, NonCallableMagicMock):
910 elif issubclass(_type, NonCallableMock):
913 klass = _type.__mro__[1]
920 if _is_exception(obj):
927 # XXXX backwards compatibility
928 # but this will blow up on first call - so maybe we should fail early?
932 class CallableMixin(Base):
934 def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
935 wraps=None, name=None, spec_set=None, parent=None,
936 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
937 self.__dict__['_mock_return_value'] = return_value
939 _super(CallableMixin, self).__init__(
940 spec, wraps, name, spec_set, parent,
941 _spec_state, _new_name, _new_parent, **kwargs
944 self.side_effect = side_effect
946 def _mock_check_sig(self, *args, **kwargs):
947 # stub method that can be replaced with one with a specific signature
950 def __call__(_mock_self, *args, **kwargs):
951 # can't use self in-case a function / method we are mocking uses self
953 _mock_self._mock_check_sig(*args, **kwargs)
954 return _mock_self._mock_call(*args, **kwargs)
956 def _mock_call(_mock_self, *args, **kwargs):
960 self.call_args = _Call((args, kwargs), two=True)
961 self.call_args_list.append(_Call((args, kwargs), two=True))
963 _new_name = self._mock_new_name
964 _new_parent = self._mock_new_parent
965 self.mock_calls.append(_Call(('', args, kwargs)))
968 skip_next_dot = _new_name == '()'
969 do_method_calls = self._mock_parent is not None
970 name = self._mock_name
971 while _new_parent is not None:
972 this_mock_call = _Call((_new_name, args, kwargs))
973 if _new_parent._mock_new_name:
978 skip_next_dot = False
979 if _new_parent._mock_new_name == '()':
982 _new_name = _new_parent._mock_new_name + dot + _new_name
985 if _new_name == name:
986 this_method_call = this_mock_call
988 this_method_call = _Call((name, args, kwargs))
989 _new_parent.method_calls.append(this_method_call)
991 do_method_calls = _new_parent._mock_parent is not None
993 name = _new_parent._mock_name + '.' + name
995 _new_parent.mock_calls.append(this_mock_call)
996 _new_parent = _new_parent._mock_new_parent
998 # use ids here so as not to call __hash__ on the mocks
999 _new_parent_id = id(_new_parent)
1000 if _new_parent_id in seen:
1002 seen.add(_new_parent_id)
1005 effect = self.side_effect
1006 if effect is not None:
1007 if _is_exception(effect):
1010 if not _callable(effect):
1011 result = next(effect)
1012 if _is_exception(result):
1016 ret_val = effect(*args, **kwargs)
1017 if ret_val is DEFAULT:
1018 ret_val = self.return_value
1020 if (self._mock_wraps is not None and
1021 self._mock_return_value is DEFAULT):
1022 return self._mock_wraps(*args, **kwargs)
1023 if ret_val is DEFAULT:
1024 ret_val = self.return_value
1028 class Mock(CallableMixin, NonCallableMock):
1030 Create a new `Mock` object. `Mock` takes several optional arguments
1031 that specify the behaviour of the Mock object:
1033 * `spec`: This can be either a list of strings or an existing object (a
1034 class or instance) that acts as the specification for the mock object. If
1035 you pass in an object then a list of strings is formed by calling dir on
1036 the object (excluding unsupported magic attributes and methods). Accessing
1037 any attribute not in this list will raise an `AttributeError`.
1039 If `spec` is an object (rather than a list of strings) then
1040 `mock.__class__` returns the class of the spec object. This allows mocks
1041 to pass `isinstance` tests.
1043 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1044 or get an attribute on the mock that isn't on the object passed as
1045 `spec_set` will raise an `AttributeError`.
1047 * `side_effect`: A function to be called whenever the Mock is called. See
1048 the `side_effect` attribute. Useful for raising exceptions or
1049 dynamically changing return values. The function is called with the same
1050 arguments as the mock, and unless it returns `DEFAULT`, the return
1051 value of this function is used as the return value.
1053 Alternatively `side_effect` can be an exception class or instance. In
1054 this case the exception will be raised when the mock is called.
1056 If `side_effect` is an iterable then each call to the mock will return
1057 the next value from the iterable. If any of the members of the iterable
1058 are exceptions they will be raised instead of returned.
1060 * `return_value`: The value returned when the mock is called. By default
1061 this is a new Mock (created on first access). See the
1062 `return_value` attribute.
1064 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1065 calling the Mock will pass the call through to the wrapped object
1066 (returning the real result). Attribute access on the mock will return a
1067 Mock object that wraps the corresponding attribute of the wrapped object
1068 (so attempting to access an attribute that doesn't exist will raise an
1071 If the mock has an explicit `return_value` set then calls are not passed
1072 to the wrapped object and the `return_value` is returned instead.
1074 * `name`: If the mock has a name then it will be used in the repr of the
1075 mock. This can be useful for debugging. The name is propagated to child
1078 Mocks can also be called with arbitrary keyword arguments. These will be
1079 used to set attributes on the mock after it is created.
1083 def _dot_lookup(thing, comp, import_path):
1085 return getattr(thing, comp)
1086 except AttributeError:
1087 __import__(import_path)
1088 return getattr(thing, comp)
1091 def _importer(target):
1092 components = target.split('.')
1093 import_path = components.pop(0)
1094 thing = __import__(import_path)
1096 for comp in components:
1097 import_path += ".%s" % comp
1098 thing = _dot_lookup(thing, comp, import_path)
1102 def _is_started(patcher):
1104 return hasattr(patcher, 'is_local')
1107 class _patch(object):
1109 attribute_name = None
1110 _active_patches = set()
1113 self, getter, attribute, new, spec, create,
1114 spec_set, autospec, new_callable, kwargs
1116 if new_callable is not None:
1117 if new is not DEFAULT:
1119 "Cannot use 'new' and 'new_callable' together"
1121 if autospec is not None:
1123 "Cannot use 'autospec' and 'new_callable' together"
1126 self.getter = getter
1127 self.attribute = attribute
1129 self.new_callable = new_callable
1131 self.create = create
1132 self.has_local = False
1133 self.spec_set = spec_set
1134 self.autospec = autospec
1135 self.kwargs = kwargs
1136 self.additional_patchers = []
1140 self.getter, self.attribute, self.new, self.spec,
1141 self.create, self.spec_set,
1142 self.autospec, self.new_callable, self.kwargs
1144 patcher.attribute_name = self.attribute_name
1145 patcher.additional_patchers = [
1146 p.copy() for p in self.additional_patchers
1150 def __call__(self, func):
1151 if isinstance(func, ClassTypes):
1152 return self.decorate_class(func)
1153 return self.decorate_callable(func)
1155 def decorate_class(self, klass):
1156 for attr in dir(klass):
1157 if not attr.startswith(patch.TEST_PREFIX):
1160 attr_value = getattr(klass, attr)
1161 if not hasattr(attr_value, "__call__"):
1164 patcher = self.copy()
1165 setattr(klass, attr, patcher(attr_value))
1168 def decorate_callable(self, func):
1169 if hasattr(func, 'patchings'):
1170 func.patchings.append(self)
1174 def patched(*args, **keywargs):
1175 # don't use a with here (backwards compatibility with Python 2.4)
1177 entered_patchers = []
1179 # can't use try...except...finally because of Python 2.4
1184 for patching in patched.patchings:
1185 arg = patching.__enter__()
1186 entered_patchers.append(patching)
1187 if patching.attribute_name is not None:
1188 keywargs.update(arg)
1189 elif patching.new is DEFAULT:
1190 extra_args.append(arg)
1192 args += tuple(extra_args)
1193 return func(*args, **keywargs)
1195 if (patching not in entered_patchers and
1196 _is_started(patching)):
1197 # the patcher may have been started, but an exception
1198 # raised whilst entering one of its additional_patchers
1199 entered_patchers.append(patching)
1200 # Pass the exception to __exit__
1201 exc_info = sys.exc_info()
1202 # re-raise the exception
1205 for patching in reversed(entered_patchers):
1206 patching.__exit__(*exc_info)
1208 patched.patchings = [self]
1209 if hasattr(func, 'func_code'):
1211 patched.compat_co_firstlineno = getattr(
1212 func, "compat_co_firstlineno",
1213 func.func_code.co_firstlineno
1217 def get_original(self):
1218 target = self.getter()
1219 name = self.attribute
1225 original = target.__dict__[name]
1226 except (AttributeError, KeyError):
1227 original = getattr(target, name, DEFAULT)
1231 if not self.create and original is DEFAULT:
1232 raise AttributeError(
1233 "%s does not have the attribute %r" % (target, name)
1235 return original, local
1237 def __enter__(self):
1238 """Perform the patch."""
1239 new, spec, spec_set = self.new, self.spec, self.spec_set
1240 autospec, kwargs = self.autospec, self.kwargs
1241 new_callable = self.new_callable
1242 self.target = self.getter()
1244 # normalise False to None
1247 if spec_set is False:
1249 if autospec is False:
1252 if spec is not None and autospec is not None:
1253 raise TypeError("Can't specify spec and autospec")
1254 if ((spec is not None or autospec is not None) and
1255 spec_set not in (True, None)):
1256 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1258 original, local = self.get_original()
1260 if new is DEFAULT and autospec is None:
1263 # set spec to the object we are replacing
1265 if spec_set is True:
1268 elif spec is not None:
1269 if spec_set is True:
1272 elif spec_set is True:
1275 if spec is not None or spec_set is not None:
1276 if original is DEFAULT:
1277 raise TypeError("Can't use 'spec' with create=True")
1278 if isinstance(original, ClassTypes):
1279 # If we're patching out a class and there is a spec
1284 if new_callable is not None:
1285 Klass = new_callable
1286 elif spec is not None or spec_set is not None:
1288 if spec_set is not None:
1289 this_spec = spec_set
1290 if _is_list(this_spec):
1291 not_callable = '__call__' not in this_spec
1293 not_callable = not _callable(this_spec)
1295 Klass = NonCallableMagicMock
1297 if spec is not None:
1298 _kwargs['spec'] = spec
1299 if spec_set is not None:
1300 _kwargs['spec_set'] = spec_set
1302 # add a name to mocks
1303 if (isinstance(Klass, type) and
1304 issubclass(Klass, NonCallableMock) and self.attribute):
1305 _kwargs['name'] = self.attribute
1307 _kwargs.update(kwargs)
1308 new = Klass(**_kwargs)
1310 if inherit and _is_instance_mock(new):
1311 # we can only tell if the instance should be callable if the
1312 # spec is not a list
1314 if spec_set is not None:
1315 this_spec = spec_set
1316 if (not _is_list(this_spec) and not
1317 _instance_callable(this_spec)):
1318 Klass = NonCallableMagicMock
1321 new.return_value = Klass(_new_parent=new, _new_name='()',
1323 elif autospec is not None:
1324 # spec is ignored, new *must* be default, spec_set is treated
1325 # as a boolean. Should we check spec is not None and that spec_set
1327 if new is not DEFAULT:
1329 "autospec creates the mock for you. Can't specify "
1332 if original is DEFAULT:
1333 raise TypeError("Can't use 'autospec' with create=True")
1334 spec_set = bool(spec_set)
1335 if autospec is True:
1338 new = create_autospec(autospec, spec_set=spec_set,
1339 _name=self.attribute, **kwargs)
1341 # can't set keyword args when we aren't creating the mock
1342 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1343 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1347 self.temp_original = original
1348 self.is_local = local
1349 setattr(self.target, self.attribute, new_attr)
1350 if self.attribute_name is not None:
1352 if self.new is DEFAULT:
1353 extra_args[self.attribute_name] = new
1354 for patching in self.additional_patchers:
1355 arg = patching.__enter__()
1356 if patching.new is DEFAULT:
1357 extra_args.update(arg)
1362 def __exit__(self, *exc_info):
1363 """Undo the patch."""
1364 if not _is_started(self):
1365 raise RuntimeError('stop called on unstarted patcher')
1367 if self.is_local and self.temp_original is not DEFAULT:
1368 setattr(self.target, self.attribute, self.temp_original)
1370 delattr(self.target, self.attribute)
1371 if not self.create and not hasattr(self.target, self.attribute):
1372 # needed for proxy objects like django settings
1373 setattr(self.target, self.attribute, self.temp_original)
1375 del self.temp_original
1378 for patcher in reversed(self.additional_patchers):
1379 if _is_started(patcher):
1380 patcher.__exit__(*exc_info)
1383 """Activate a patch, returning any created mock."""
1384 result = self.__enter__()
1385 self._active_patches.add(self)
1389 """Stop an active patch."""
1390 self._active_patches.discard(self)
1391 return self.__exit__()
1394 def _get_target(target):
1396 target, attribute = target.rsplit('.', 1)
1397 except (TypeError, ValueError):
1398 raise TypeError("Need a valid target to patch. You supplied: %r" %
1400 getter = lambda: _importer(target)
1401 return getter, attribute
1405 target, attribute, new=DEFAULT, spec=None,
1406 create=False, spec_set=None, autospec=None,
1407 new_callable=None, **kwargs
1410 patch.object(target, attribute, new=DEFAULT, spec=None, create=False,
1411 spec_set=None, autospec=None, new_callable=None, **kwargs)
1413 patch the named member (`attribute`) on an object (`target`) with a mock
1416 `patch.object` can be used as a decorator, class decorator or a context
1417 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1418 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1419 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1420 the mock object it creates.
1422 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1423 for choosing which methods to wrap.
1425 getter = lambda: target
1427 getter, attribute, new, spec, create,
1428 spec_set, autospec, new_callable, kwargs
1432 def _patch_multiple(target, spec=None, create=False, spec_set=None,
1433 autospec=None, new_callable=None, **kwargs):
1434 """Perform multiple patches in a single call. It takes the object to be
1435 patched (either as an object or a string to fetch the object by importing)
1436 and keyword arguments for the patches::
1438 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1441 Use `DEFAULT` as the value if you want `patch.multiple` to create
1442 mocks for you. In this case the created mocks are passed into a decorated
1443 function by keyword, and a dictionary is returned when `patch.multiple` is
1444 used as a context manager.
1446 `patch.multiple` can be used as a decorator, class decorator or a context
1447 manager. The arguments `spec`, `spec_set`, `create`,
1448 `autospec` and `new_callable` have the same meaning as for `patch`. These
1449 arguments will be applied to *all* patches done by `patch.multiple`.
1451 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1452 for choosing which methods to wrap.
1454 if type(target) in (unicode, str):
1455 getter = lambda: _importer(target)
1457 getter = lambda: target
1461 'Must supply at least one keyword argument with patch.multiple'
1463 # need to wrap in a list for python 3, where items is a view
1464 items = list(kwargs.items())
1465 attribute, new = items[0]
1467 getter, attribute, new, spec, create, spec_set,
1468 autospec, new_callable, {}
1470 patcher.attribute_name = attribute
1471 for attribute, new in items[1:]:
1472 this_patcher = _patch(
1473 getter, attribute, new, spec, create, spec_set,
1474 autospec, new_callable, {}
1476 this_patcher.attribute_name = attribute
1477 patcher.additional_patchers.append(this_patcher)
1482 target, new=DEFAULT, spec=None, create=False,
1483 spec_set=None, autospec=None, new_callable=None, **kwargs
1486 `patch` acts as a function decorator, class decorator or a context
1487 manager. Inside the body of the function or with statement, the `target`
1488 is patched with a `new` object. When the function/with statement exits
1489 the patch is undone.
1491 If `new` is omitted, then the target is replaced with a
1492 `MagicMock`. If `patch` is used as a decorator and `new` is
1493 omitted, the created mock is passed in as an extra argument to the
1494 decorated function. If `patch` is used as a context manager the created
1495 mock is returned by the context manager.
1497 `target` should be a string in the form `'package.module.ClassName'`. The
1498 `target` is imported and the specified object replaced with the `new`
1499 object, so the `target` must be importable from the environment you are
1500 calling `patch` from. The target is imported when the decorated function
1501 is executed, not at decoration time.
1503 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1504 if patch is creating one for you.
1506 In addition you can pass `spec=True` or `spec_set=True`, which causes
1507 patch to pass in the object being mocked as the spec/spec_set object.
1509 `new_callable` allows you to specify a different class, or callable object,
1510 that will be called to create the `new` object. By default `MagicMock` is
1513 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1514 then the mock with be created with a spec from the object being replaced.
1515 All attributes of the mock will also have the spec of the corresponding
1516 attribute of the object being replaced. Methods and functions being
1517 mocked will have their arguments checked and will raise a `TypeError` if
1518 they are called with the wrong signature. For mocks replacing a class,
1519 their return value (the 'instance') will have the same spec as the class.
1521 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1522 arbitrary object as the spec instead of the one being replaced.
1524 By default `patch` will fail to replace attributes that don't exist. If
1525 you pass in `create=True`, and the attribute doesn't exist, patch will
1526 create the attribute for you when the patched function is called, and
1527 delete it again afterwards. This is useful for writing tests against
1528 attributes that your production code creates at runtime. It is off by by
1529 default because it can be dangerous. With it switched on you can write
1530 passing tests against APIs that don't actually exist!
1532 Patch can be used as a `TestCase` class decorator. It works by
1533 decorating each test method in the class. This reduces the boilerplate
1534 code when your test methods share a common patchings set. `patch` finds
1535 tests by looking for method names that start with `patch.TEST_PREFIX`.
1536 By default this is `test`, which matches the way `unittest` finds tests.
1537 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1539 Patch can be used as a context manager, with the with statement. Here the
1540 patching applies to the indented block after the with statement. If you
1541 use "as" then the patched object will be bound to the name after the
1542 "as"; very useful if `patch` is creating a mock object for you.
1544 `patch` takes arbitrary keyword arguments. These will be passed to
1545 the `Mock` (or `new_callable`) on construction.
1547 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1548 available for alternate use-cases.
1550 getter, attribute = _get_target(target)
1552 getter, attribute, new, spec, create,
1553 spec_set, autospec, new_callable, kwargs
1557 class _patch_dict(object):
1559 Patch a dictionary, or dictionary like object, and restore the dictionary
1560 to its original state after the test.
1562 `in_dict` can be a dictionary or a mapping like container. If it is a
1563 mapping then it must at least support getting, setting and deleting items
1564 plus iterating over keys.
1566 `in_dict` can also be a string specifying the name of the dictionary, which
1567 will then be fetched by importing it.
1569 `values` can be a dictionary of values to set in the dictionary. `values`
1570 can also be an iterable of `(key, value)` pairs.
1572 If `clear` is True then the dictionary will be cleared before the new
1575 `patch.dict` can also be called with arbitrary keyword arguments to set
1576 values in the dictionary::
1578 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1581 `patch.dict` can be used as a context manager, decorator or class
1582 decorator. When used as a class decorator `patch.dict` honours
1583 `patch.TEST_PREFIX` for choosing which methods to wrap.
1586 def __init__(self, in_dict, values=(), clear=False, **kwargs):
1587 if isinstance(in_dict, basestring):
1588 in_dict = _importer(in_dict)
1589 self.in_dict = in_dict
1590 # support any argument supported by dict(...) constructor
1591 self.values = dict(values)
1592 self.values.update(kwargs)
1594 self._original = None
1596 def __call__(self, f):
1597 if isinstance(f, ClassTypes):
1598 return self.decorate_class(f)
1601 def _inner(*args, **kw):
1604 return f(*args, **kw)
1606 self._unpatch_dict()
1610 def decorate_class(self, klass):
1611 for attr in dir(klass):
1612 attr_value = getattr(klass, attr)
1613 if (attr.startswith(patch.TEST_PREFIX) and
1614 hasattr(attr_value, "__call__")):
1615 decorator = _patch_dict(self.in_dict, self.values, self.clear)
1616 decorated = decorator(attr_value)
1617 setattr(klass, attr, decorated)
1620 def __enter__(self):
1621 """Patch the dict."""
1624 def _patch_dict(self):
1625 values = self.values
1626 in_dict = self.in_dict
1630 original = in_dict.copy()
1631 except AttributeError:
1632 # dict like object with no copy method
1633 # must support iteration over keys
1636 original[key] = in_dict[key]
1637 self._original = original
1640 _clear_dict(in_dict)
1643 in_dict.update(values)
1644 except AttributeError:
1645 # dict like object with no update method
1647 in_dict[key] = values[key]
1649 def _unpatch_dict(self):
1650 in_dict = self.in_dict
1651 original = self._original
1653 _clear_dict(in_dict)
1656 in_dict.update(original)
1657 except AttributeError:
1658 for key in original:
1659 in_dict[key] = original[key]
1661 def __exit__(self, *args):
1662 """Unpatch the dict."""
1663 self._unpatch_dict()
1670 def _clear_dict(in_dict):
1673 except AttributeError:
1674 keys = list(in_dict)
1679 def _patch_stopall():
1680 """Stop all active patches."""
1681 for patch in list(_patch._active_patches):
1685 patch.object = _patch_object
1686 patch.dict = _patch_dict
1687 patch.multiple = _patch_multiple
1688 patch.stopall = _patch_stopall
1689 patch.TEST_PREFIX = 'test'
1692 "lt le gt ge eq ne "
1693 "getitem setitem delitem "
1694 "len contains iter "
1697 "divmod neg pos abs invert "
1698 "complex int float index "
1702 numerics = "add sub mul div floordiv mod lshift rshift and xor or pow "
1703 inplace = ' '.join('i%s' % n for n in numerics.split())
1704 right = ' '.join('r%s' % n for n in numerics.split())
1707 extra = 'bool next '
1709 extra = 'unicode long nonzero oct hex truediv rtruediv '
1711 # not including __prepare__, __instancecheck__, __subclasscheck__
1712 # (as they are metaclass methods)
1713 # __del__ is not supported at all as it causes problems if it exists
1715 _non_defaults = set('__%s__' % method for method in [
1716 'cmp', 'getslice', 'setslice', 'coerce', 'subclasses',
1717 'format', 'get', 'set', 'delete', 'reversed',
1718 'missing', 'reduce', 'reduce_ex', 'getinitargs',
1719 'getnewargs', 'getstate', 'setstate', 'getformat',
1720 'setformat', 'repr', 'dir'
1724 def _get_method(name, func):
1725 "Turns a callable object (like a mock) into a real function"
1727 def method(self, *args, **kw):
1728 return func(self, *args, **kw)
1729 method.__name__ = name
1734 '__%s__' % method for method in
1735 ' '.join([magic_methods, numerics, inplace, right, extra]).split()
1738 _all_magics = _magics | _non_defaults
1740 _unsupported_magics = set([
1741 '__getattr__', '__setattr__',
1742 '__init__', '__new__', '__prepare__'
1743 '__instancecheck__', '__subclasscheck__',
1747 _calculate_return_value = {
1748 '__hash__': lambda self: object.__hash__(self),
1749 '__str__': lambda self: object.__str__(self),
1750 '__sizeof__': lambda self: object.__sizeof__(self),
1751 '__unicode__': lambda self: unicode(object.__str__(self)),
1755 '__lt__': NotImplemented,
1756 '__gt__': NotImplemented,
1757 '__le__': NotImplemented,
1758 '__ge__': NotImplemented,
1760 '__contains__': False,
1766 '__nonzero__': True,
1769 '__long__': long(1),
1776 ret_val = self.__eq__._mock_return_value
1777 if ret_val is not DEFAULT:
1779 return self is other
1785 if self.__ne__._mock_return_value is not DEFAULT:
1787 return self is not other
1791 def _get_iter(self):
1793 ret_val = self.__iter__._mock_return_value
1794 if ret_val is DEFAULT:
1796 # if ret_val was already an iterator, then calling iter on it should
1797 # return the iterator unchanged
1798 return iter(ret_val)
1801 _side_effect_methods = {
1804 '__iter__': _get_iter,
1808 def _set_return_value(mock, method, name):
1809 fixed = _return_values.get(name, DEFAULT)
1810 if fixed is not DEFAULT:
1811 method.return_value = fixed
1814 return_calulator = _calculate_return_value.get(name)
1815 if return_calulator is not None:
1817 return_value = return_calulator(mock)
1818 except AttributeError:
1819 # XXXX why do we return AttributeError here?
1820 # set it as a side_effect instead?
1821 return_value = AttributeError(name)
1822 method.return_value = return_value
1825 side_effector = _side_effect_methods.get(name)
1826 if side_effector is not None:
1827 method.side_effect = side_effector(mock)
1830 class MagicMixin(object):
1831 def __init__(self, *args, **kw):
1832 _super(MagicMixin, self).__init__(*args, **kw)
1833 self._mock_set_magics()
1835 def _mock_set_magics(self):
1836 these_magics = _magics
1838 if self._mock_methods is not None:
1839 these_magics = _magics.intersection(self._mock_methods)
1841 remove_magics = set()
1842 remove_magics = _magics - these_magics
1844 for entry in remove_magics:
1845 if entry in type(self).__dict__:
1846 # remove unneeded magic methods
1847 delattr(self, entry)
1849 # don't overwrite existing attributes if called a second time
1850 these_magics = these_magics - set(type(self).__dict__)
1853 for entry in these_magics:
1854 setattr(_type, entry, MagicProxy(entry, self))
1857 class NonCallableMagicMock(MagicMixin, NonCallableMock):
1858 """A version of `MagicMock` that isn't callable."""
1860 def mock_add_spec(self, spec, spec_set=False):
1861 """Add a spec to a mock. `spec` can either be an object or a
1862 list of strings. Only attributes on the `spec` can be fetched as
1863 attributes from the mock.
1865 If `spec_set` is True then only attributes on the spec can be set."""
1866 self._mock_add_spec(spec, spec_set)
1867 self._mock_set_magics()
1870 class MagicMock(MagicMixin, Mock):
1872 MagicMock is a subclass of Mock with default implementations
1873 of most of the magic methods. You can use MagicMock without having to
1874 configure the magic methods yourself.
1876 If you use the `spec` or `spec_set` arguments then *only* magic
1877 methods that exist in the spec will be created.
1879 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1882 def mock_add_spec(self, spec, spec_set=False):
1883 """Add a spec to a mock. `spec` can either be an object or a
1884 list of strings. Only attributes on the `spec` can be fetched as
1885 attributes from the mock.
1887 If `spec_set` is True then only attributes on the spec can be set."""
1888 self._mock_add_spec(spec, spec_set)
1889 self._mock_set_magics()
1892 class MagicProxy(object):
1893 def __init__(self, name, parent):
1895 self.parent = parent
1897 def __call__(self, *args, **kwargs):
1898 m = self.create_mock()
1899 return m(*args, **kwargs)
1901 def create_mock(self):
1903 parent = self.parent
1904 m = parent._get_child_mock(name=entry, _new_name=entry,
1906 setattr(parent, entry, m)
1907 _set_return_value(parent, m, entry)
1910 def __get__(self, obj, _type=None):
1911 return self.create_mock()
1915 "A helper object that compares equal to everything."
1917 def __eq__(self, other):
1920 def __ne__(self, other):
1929 def _format_call_signature(name, args, kwargs):
1930 message = '%s(%%s)' % name
1932 args_string = ', '.join([repr(arg) for arg in args])
1933 kwargs_string = ', '.join([
1934 '%s=%r' % (key, value) for key, value in kwargs.items()
1937 formatted_args = args_string
1940 formatted_args += ', '
1941 formatted_args += kwargs_string
1943 return message % formatted_args
1948 A tuple for holding the results of a call to a mock, either in the form
1949 `(args, kwargs)` or `(name, args, kwargs)`.
1951 If args or kwargs are empty then a call tuple will compare equal to
1952 a tuple without those values. This makes comparisons less verbose::
1954 _Call(('name', (), {})) == ('name',)
1955 _Call(('name', (1,), {})) == ('name', (1,))
1956 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1958 The `_Call` object provides a useful shortcut for comparing with call::
1960 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1961 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1963 If the _Call has no name then it will match any name.
1965 def __new__(cls, value=(), name=None, parent=None, two=False,
1972 name, args, kwargs = value
1974 first, second = value
1975 if isinstance(first, basestring):
1977 if isinstance(second, tuple):
1982 args, kwargs = first, second
1985 if isinstance(value, basestring):
1987 elif isinstance(value, tuple):
1993 return tuple.__new__(cls, (args, kwargs))
1995 return tuple.__new__(cls, (name, args, kwargs))
1997 def __init__(self, value=(), name=None, parent=None, two=False,
2000 self.parent = parent
2001 self.from_kall = from_kall
2003 def __eq__(self, other):
2007 len_other = len(other)
2013 self_args, self_kwargs = self
2015 self_name, self_args, self_kwargs = self
2019 other_args, other_kwargs = (), {}
2020 elif len_other == 3:
2021 other_name, other_args, other_kwargs = other
2022 elif len_other == 1:
2024 if isinstance(value, tuple):
2027 elif isinstance(value, basestring):
2029 other_args, other_kwargs = (), {}
2032 other_kwargs = value
2035 # could be (name, args) or (name, kwargs) or (args, kwargs)
2036 first, second = other
2037 if isinstance(first, basestring):
2039 if isinstance(second, tuple):
2040 other_args, other_kwargs = second, {}
2042 other_args, other_kwargs = (), second
2044 other_args, other_kwargs = first, second
2046 if self_name and other_name != self_name:
2049 # this order is important for ANY to work!
2050 return (other_args, other_kwargs) == (self_args, self_kwargs)
2052 def __ne__(self, other):
2053 return not self.__eq__(other)
2055 def __call__(self, *args, **kwargs):
2056 if self.name is None:
2057 return _Call(('', args, kwargs), name='()')
2059 name = self.name + '()'
2060 return _Call((self.name, args, kwargs), name=name, parent=self)
2062 def __getattr__(self, attr):
2063 if self.name is None:
2064 return _Call(name=attr, from_kall=False)
2065 name = '%s.%s' % (self.name, attr)
2066 return _Call(name=name, parent=self, from_kall=False)
2069 if not self.from_kall:
2070 name = self.name or 'call'
2071 if name.startswith('()'):
2072 name = 'call%s' % name
2079 name, args, kwargs = self
2082 elif not name.startswith('()'):
2083 name = 'call.%s' % name
2085 name = 'call%s' % name
2086 return _format_call_signature(name, args, kwargs)
2088 def call_list(self):
2089 """For a call object that represents multiple calls, `call_list`
2090 returns a list of all the intermediate calls as well as the
2094 while thing is not None:
2097 thing = thing.parent
2098 return _CallList(reversed(vals))
2101 call = _Call(from_kall=False)
2104 def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2105 _name=None, **kwargs):
2106 """Create a mock object using another object as a spec. Attributes on the
2107 mock will use the corresponding attribute on the `spec` object as their
2110 Functions or methods being mocked will have their arguments checked
2111 to check that they are called with the correct signature.
2113 If `spec_set` is True then attempting to set attributes that don't exist
2114 on the spec object will raise an `AttributeError`.
2116 If a class is used as a spec then the return value of the mock (the
2117 instance of the class) will have the same spec. You can use a class as the
2118 spec for an instance object by passing `instance=True`. The returned mock
2119 will only be callable if instances of the mock are callable.
2121 `create_autospec` also takes arbitrary keyword arguments that are passed to
2122 the constructor of the created mock."""
2124 # can't pass a list instance to the mock constructor as it will be
2125 # interpreted as a list of strings
2128 is_type = isinstance(spec, ClassTypes)
2130 _kwargs = {'spec': spec}
2132 _kwargs = {'spec_set': spec}
2134 # None we mock with a normal mock without a spec
2137 _kwargs.update(kwargs)
2140 if type(spec) in DescriptorTypes:
2141 # descriptors don't have a spec
2142 # because we don't know what type they return
2144 elif not _callable(spec):
2145 Klass = NonCallableMagicMock
2146 elif is_type and instance and not _instance_callable(spec):
2147 Klass = NonCallableMagicMock
2151 # for a top level object no _new_name should be set
2154 mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2155 name=_name, **_kwargs)
2157 if isinstance(spec, FunctionTypes):
2158 # should only happen at the top level because we don't
2159 # recurse for functions
2160 mock = _set_signature(mock, spec)
2162 _check_signature(spec, mock, is_type, instance)
2164 if _parent is not None and not instance:
2165 _parent._mock_children[_name] = mock
2167 if is_type and not instance and 'return_value' not in kwargs:
2168 mock.return_value = create_autospec(spec, spec_set, instance=True,
2169 _name='()', _parent=mock)
2171 for entry in dir(spec):
2172 if _is_magic(entry):
2173 # MagicMock already does the useful magic methods for us
2176 if isinstance(spec, FunctionTypes) and entry in FunctionAttributes:
2177 # allow a mock to actually be a function
2180 # XXXX do we need a better way of getting attributes without
2181 # triggering code execution (?) Probably not - we need the actual
2182 # object to mock it so we would rather trigger a property than mock
2183 # the property descriptor. Likewise we want to mock out dynamically
2184 # provided attributes.
2185 # XXXX what about attributes that raise exceptions other than
2186 # AttributeError on being fetched?
2187 # we could be resilient against it, or catch and propagate the
2188 # exception when the attribute is fetched from the mock
2190 original = getattr(spec, entry)
2191 except AttributeError:
2194 kwargs = {'spec': original}
2196 kwargs = {'spec_set': original}
2198 if not isinstance(original, FunctionTypes):
2199 new = _SpecState(original, spec_set, mock, entry, instance)
2200 mock._mock_children[entry] = new
2203 if isinstance(spec, FunctionTypes):
2206 new = MagicMock(parent=parent, name=entry, _new_name=entry,
2207 _new_parent=parent, **kwargs)
2208 mock._mock_children[entry] = new
2209 skipfirst = _must_skip(spec, entry, is_type)
2210 _check_signature(original, new, skipfirst=skipfirst)
2212 # so functions created with _set_signature become instance attributes,
2213 # *plus* their underlying mock exists in _mock_children of the parent
2214 # mock. Adding to _mock_children may be unnecessary where we are also
2215 # setting as an instance attribute?
2216 if isinstance(new, FunctionTypes):
2217 setattr(mock, entry, new)
2222 def _must_skip(spec, entry, is_type):
2223 if not isinstance(spec, ClassTypes):
2224 if entry in getattr(spec, '__dict__', {}):
2225 # instance attribute - shouldn't skip
2227 spec = spec.__class__
2228 if not hasattr(spec, '__mro__'):
2229 # old style class: can't have descriptors anyway
2232 for klass in spec.__mro__:
2233 result = klass.__dict__.get(entry, DEFAULT)
2234 if result is DEFAULT:
2236 if isinstance(result, (staticmethod, classmethod)):
2240 # shouldn't get here unless function is a dynamically provided attribute
2241 # XXXX untested behaviour
2245 def _get_class(obj):
2247 return obj.__class__
2248 except AttributeError:
2249 # in Python 2, _sre.SRE_Pattern objects have no __class__
2253 class _SpecState(object):
2255 def __init__(self, spec, spec_set=False, parent=None,
2256 name=None, ids=None, instance=False):
2259 self.spec_set = spec_set
2260 self.parent = parent
2261 self.instance = instance
2267 type(create_autospec),
2274 FunctionAttributes = set([
2288 def mock_open(mock=None, read_data=''):
2290 A helper function to create a mock to replace the use of `open`. It works
2291 for `open` called directly or used as a context manager.
2293 The `mock` argument is the mock object to configure. If `None` (the
2294 default) then a `MagicMock` will be created for you, with the API limited
2295 to methods or attributes available on standard file handles.
2297 `read_data` is a string for the `read` method of the file handle to return.
2298 This is an empty string by default.
2301 if file_spec is None:
2305 file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2310 mock = MagicMock(name='open', spec=open)
2312 handle = MagicMock(spec=file_spec)
2313 handle.write.return_value = None
2314 handle.__enter__.return_value = handle
2315 handle.read.return_value = read_data
2317 mock.return_value = handle
2321 class PropertyMock(Mock):
2323 A mock intended to be used as a property, or other descriptor, on a class.
2324 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2325 a return value when it is fetched.
2327 Fetching a `PropertyMock` instance from an object calls the mock, with
2328 no args. Setting it calls the mock with the value being set.
2331 def _get_child_mock(self, **kwargs):
2332 return MagicMock(**kwargs)
2334 def __get__(self, obj, obj_type):
2337 def __set__(self, obj, val):