2 # Test tools for mocking and patching.
3 # Copyright (C) 2007-2012 Michael Foord & the mock team
4 # E-mail: fuzzyman AT voidspace DOT org DOT uk
7 # http://www.voidspace.org.uk/python/mock/
9 # Released subject to the BSD License
10 # Please see http://www.voidspace.org.uk/python/license.shtml
12 # Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
13 # Comments, suggestions and bug reports welcome.
27 'NonCallableMagicMock',
42 # for alternative platforms that
43 # may not have inspect
47 from functools
import wraps
as original_wraps
49 # Python 2.4 compatibility
52 f
.__name
__ = original
.__name
__
53 f
.__doc
__ = original
.__doc
__
54 f
.__module
__ = original
.__module
__
55 f
.__wrapped
__ = original
59 if sys
.version_info
[:2] >= (3, 3):
60 wraps
= original_wraps
64 f
= original_wraps(func
)(f
)
73 basestring
= unicode = str
84 # Python 2.4 compatibility
85 BaseException
= Exception
94 BaseExceptions
= (BaseException
,)
95 if 'java' in sys
.platform
:
98 BaseExceptions
= (BaseException
, java
.lang
.Throwable
)
101 _isidentifier
= str.isidentifier
102 except AttributeError:
106 regex
= re
.compile(r
'^[a-z_][a-z0-9_]*$', re
.I
)
107 def _isidentifier(string
):
108 if string
in keyword
.kwlist
:
110 return regex
.match(string
)
113 inPy3k
= sys
.version_info
[0] == 3
115 # Needed to work around Python 3 bug where use of "super" interferes with
116 # defining __class__ as a descriptor
120 builtin
= '__builtin__'
128 def _is_instance_mock(obj
):
129 # can't use isinstance on Mock objects because they override __class__
130 # The base class for all mocks is NonCallableMock
131 return issubclass(type(obj
), NonCallableMock
)
134 def _is_exception(obj
):
136 isinstance(obj
, BaseExceptions
) or
137 isinstance(obj
, ClassTypes
) and issubclass(obj
, BaseExceptions
)
141 class _slotted(object):
151 def _getsignature(func
, skipfirst
, instance
=False):
153 raise ImportError('inspect module not available')
155 if isinstance(func
, ClassTypes
) and not instance
:
158 except AttributeError:
161 elif not isinstance(func
, FunctionTypes
):
162 # for classes where instance is True we end up here too
165 except AttributeError:
170 argspec
= inspect
.getfullargspec(func
)
172 # C function / method, possibly inherited object().__init__
174 regargs
, varargs
, varkw
, defaults
, kwonly
, kwonlydef
, ann
= argspec
177 regargs
, varargs
, varkwargs
, defaults
= inspect
.getargspec(func
)
179 # C function / method, possibly inherited object().__init__
182 # instance methods and classmethods need to lose the self argument
183 if getattr(func
, self
, None) is not None:
184 regargs
= regargs
[1:]
186 # this condition and the above one are never both True - why?
187 regargs
= regargs
[1:]
190 signature
= inspect
.formatargspec(
191 regargs
, varargs
, varkw
, defaults
,
192 kwonly
, kwonlydef
, ann
, formatvalue
=lambda value
: "")
194 signature
= inspect
.formatargspec(
195 regargs
, varargs
, varkwargs
, defaults
,
196 formatvalue
=lambda value
: "")
197 return signature
[1:-1], func
200 def _check_signature(func
, mock
, skipfirst
, instance
=False):
201 if not _callable(func
):
204 result
= _getsignature(func
, skipfirst
, instance
)
207 signature
, func
= result
209 # can't use self because "self" is common as an argument name
210 # unfortunately even not in the first place
211 src
= "lambda _mock_self, %s: None" % signature
212 checksig
= eval(src
, {})
213 _copy_func_details(func
, checksig
)
214 type(mock
)._mock
_check
_sig
= checksig
217 def _copy_func_details(func
, funcopy
):
218 funcopy
.__name
__ = func
.__name
__
219 funcopy
.__doc
__ = func
.__doc
__
220 #funcopy.__dict__.update(func.__dict__)
221 funcopy
.__module
__ = func
.__module
__
223 funcopy
.func_defaults
= func
.func_defaults
225 funcopy
.__defaults
__ = func
.__defaults
__
226 funcopy
.__kwdefaults
__ = func
.__kwdefaults
__
230 if isinstance(obj
, ClassTypes
):
232 if getattr(obj
, '__call__', None) is not None:
238 # checks for list or tuples
240 return type(obj
) in (list, tuple)
243 def _instance_callable(obj
):
244 """Given an object, return True if the object is callable.
245 For classes, return True if instances would be callable."""
246 if not isinstance(obj
, ClassTypes
):
247 # already an instance
248 return getattr(obj
, '__call__', None) is not None
251 # uses __bases__ instead of __mro__ so that we work with old style classes
252 if klass
.__dict
__.get('__call__') is not None:
255 for base
in klass
.__bases
__:
256 if _instance_callable(base
):
261 def _set_signature(mock
, original
, instance
=False):
262 # creates a function with signature (*args, **kwargs) that delegates to a
263 # mock. It still does signature checking by calling a lambda with the same
264 # signature as the original.
265 if not _callable(original
):
268 skipfirst
= isinstance(original
, ClassTypes
)
269 result
= _getsignature(original
, skipfirst
, instance
)
271 # was a C function (e.g. object().__init__ ) that can't be mocked
274 signature
, func
= result
276 src
= "lambda %s: None" % signature
277 checksig
= eval(src
, {})
278 _copy_func_details(func
, checksig
)
280 name
= original
.__name
__
281 if not _isidentifier(name
):
283 context
= {'_checksig_': checksig
, 'mock': mock
}
284 src
= """def %s(*args, **kwargs):
285 _checksig_(*args, **kwargs)
286 return mock(*args, **kwargs)""" % name
288 funcopy
= context
[name
]
289 _setup_func(funcopy
, mock
)
293 def _setup_func(funcopy
, mock
):
296 # can't use isinstance with mocks
297 if not _is_instance_mock(mock
):
300 def assert_called_with(*args
, **kwargs
):
301 return mock
.assert_called_with(*args
, **kwargs
)
302 def assert_called_once_with(*args
, **kwargs
):
303 return mock
.assert_called_once_with(*args
, **kwargs
)
304 def assert_has_calls(*args
, **kwargs
):
305 return mock
.assert_has_calls(*args
, **kwargs
)
306 def assert_any_call(*args
, **kwargs
):
307 return mock
.assert_any_call(*args
, **kwargs
)
309 funcopy
.method_calls
= _CallList()
310 funcopy
.mock_calls
= _CallList()
312 ret
= funcopy
.return_value
313 if _is_instance_mock(ret
) and not ret
is mock
:
316 funcopy
.called
= False
317 funcopy
.call_count
= 0
318 funcopy
.call_args
= None
319 funcopy
.call_args_list
= _CallList()
320 funcopy
.method_calls
= _CallList()
321 funcopy
.mock_calls
= _CallList()
323 funcopy
.return_value
= mock
.return_value
324 funcopy
.side_effect
= mock
.side_effect
325 funcopy
._mock
_children
= mock
._mock
_children
327 funcopy
.assert_called_with
= assert_called_with
328 funcopy
.assert_called_once_with
= assert_called_once_with
329 funcopy
.assert_has_calls
= assert_has_calls
330 funcopy
.assert_any_call
= assert_any_call
331 funcopy
.reset_mock
= reset_mock
333 mock
._mock
_delegate
= funcopy
337 return '__%s__' % name
[2:-2] == name
340 class _SentinelObject(object):
341 "A unique, named, sentinel object."
342 def __init__(self
, name
):
346 return 'sentinel.%s' % self
.name
349 class _Sentinel(object):
350 """Access attributes to return a named object, usable as a sentinel."""
354 def __getattr__(self
, name
):
355 if name
== '__bases__':
356 # Without this help(mock) raises an exception
358 return self
._sentinels
.setdefault(name
, _SentinelObject(name
))
361 sentinel
= _Sentinel()
363 DEFAULT
= sentinel
.DEFAULT
364 _missing
= sentinel
.MISSING
365 _deleted
= sentinel
.DELETED
370 ClassType
= type(OldStyleClass
)
374 if type(value
) in (dict, list, tuple, set):
375 return type(value
)(value
)
381 ClassTypes
= (type, ClassType
)
383 _allowed_names
= set(
385 'return_value', '_mock_return_value', 'side_effect',
386 '_mock_side_effect', '_mock_parent', '_mock_new_parent',
387 '_mock_name', '_mock_new_name'
392 def _delegating_property(name
):
393 _allowed_names
.add(name
)
394 _the_name
= '_mock_' + name
395 def _get(self
, name
=name
, _the_name
=_the_name
):
396 sig
= self
._mock
_delegate
398 return getattr(self
, _the_name
)
399 return getattr(sig
, name
)
400 def _set(self
, value
, name
=name
, _the_name
=_the_name
):
401 sig
= self
._mock
_delegate
403 self
.__dict
__[_the_name
] = value
405 setattr(sig
, name
, value
)
407 return property(_get
, _set
)
411 class _CallList(list):
413 def __contains__(self
, value
):
414 if not isinstance(value
, list):
415 return list.__contains
__(self
, value
)
416 len_value
= len(value
)
418 if len_value
> len_self
:
421 for i
in range(0, len_self
- len_value
+ 1):
422 sub_list
= self
[i
:i
+len_value
]
423 if sub_list
== value
:
428 return pprint
.pformat(list(self
))
431 def _check_and_set_parent(parent
, value
, name
, new_name
):
432 if not _is_instance_mock(value
):
434 if ((value
._mock
_name
or value
._mock
_new
_name
) or
435 (value
._mock
_parent
is not None) or
436 (value
._mock
_new
_parent
is not None)):
440 while _parent
is not None:
441 # setting a mock (value) as a child or return value of itself
442 # should not modify the mock
445 _parent
= _parent
._mock
_new
_parent
448 value
._mock
_new
_parent
= parent
449 value
._mock
_new
_name
= new_name
451 value
._mock
_parent
= parent
452 value
._mock
_name
= name
458 _mock_return_value
= DEFAULT
459 _mock_side_effect
= None
460 def __init__(self
, *args
, **kwargs
):
465 class NonCallableMock(Base
):
466 """A non-callable version of `Mock`"""
468 def __new__(cls
, *args
, **kw
):
469 # every instance has its own class
470 # so we can create magic methods on the
471 # class without stomping on other mocks
472 new
= type(cls
.__name
__, (cls
,), {'__doc__': cls
.__doc
__})
473 instance
= object.__new
__(new
)
478 self
, spec
=None, wraps
=None, name
=None, spec_set
=None,
479 parent
=None, _spec_state
=None, _new_name
='', _new_parent
=None,
482 if _new_parent
is None:
485 __dict__
= self
.__dict
__
486 __dict__
['_mock_parent'] = parent
487 __dict__
['_mock_name'] = name
488 __dict__
['_mock_new_name'] = _new_name
489 __dict__
['_mock_new_parent'] = _new_parent
491 if spec_set
is not None:
495 self
._mock
_add
_spec
(spec
, spec_set
)
497 __dict__
['_mock_children'] = {}
498 __dict__
['_mock_wraps'] = wraps
499 __dict__
['_mock_delegate'] = None
501 __dict__
['_mock_called'] = False
502 __dict__
['_mock_call_args'] = None
503 __dict__
['_mock_call_count'] = 0
504 __dict__
['_mock_call_args_list'] = _CallList()
505 __dict__
['_mock_mock_calls'] = _CallList()
507 __dict__
['method_calls'] = _CallList()
510 self
.configure_mock(**kwargs
)
512 _super(NonCallableMock
, self
).__init
__(
513 spec
, wraps
, name
, spec_set
, parent
,
518 def attach_mock(self
, mock
, attribute
):
520 Attach a mock as an attribute of this one, replacing its name and
521 parent. Calls to the attached mock will be recorded in the
522 `method_calls` and `mock_calls` attributes of this one."""
523 mock
._mock
_parent
= None
524 mock
._mock
_new
_parent
= None
526 mock
._mock
_new
_name
= None
528 setattr(self
, attribute
, mock
)
531 def mock_add_spec(self
, spec
, spec_set
=False):
532 """Add a spec to a mock. `spec` can either be an object or a
533 list of strings. Only attributes on the `spec` can be fetched as
534 attributes from the mock.
536 If `spec_set` is True then only attributes on the spec can be set."""
537 self
._mock
_add
_spec
(spec
, spec_set
)
540 def _mock_add_spec(self
, spec
, spec_set
):
543 if spec
is not None and not _is_list(spec
):
544 if isinstance(spec
, ClassTypes
):
547 _spec_class
= _get_class(spec
)
551 __dict__
= self
.__dict
__
552 __dict__
['_spec_class'] = _spec_class
553 __dict__
['_spec_set'] = spec_set
554 __dict__
['_mock_methods'] = spec
557 def __get_return_value(self
):
558 ret
= self
._mock
_return
_value
559 if self
._mock
_delegate
is not None:
560 ret
= self
._mock
_delegate
.return_value
563 ret
= self
._get
_child
_mock
(
564 _new_parent
=self
, _new_name
='()'
566 self
.return_value
= ret
570 def __set_return_value(self
, value
):
571 if self
._mock
_delegate
is not None:
572 self
._mock
_delegate
.return_value
= value
574 self
._mock
_return
_value
= value
575 _check_and_set_parent(self
, value
, None, '()')
577 __return_value_doc
= "The value to be returned when the mock is called."
578 return_value
= property(__get_return_value
, __set_return_value
,
584 if self
._spec
_class
is None:
586 return self
._spec
_class
588 called
= _delegating_property('called')
589 call_count
= _delegating_property('call_count')
590 call_args
= _delegating_property('call_args')
591 call_args_list
= _delegating_property('call_args_list')
592 mock_calls
= _delegating_property('mock_calls')
595 def __get_side_effect(self
):
596 sig
= self
._mock
_delegate
598 return self
._mock
_side
_effect
599 return sig
.side_effect
601 def __set_side_effect(self
, value
):
602 value
= _try_iter(value
)
603 sig
= self
._mock
_delegate
605 self
._mock
_side
_effect
= value
607 sig
.side_effect
= value
609 side_effect
= property(__get_side_effect
, __set_side_effect
)
612 def reset_mock(self
):
613 "Restore the mock object to its initial state."
615 self
.call_args
= None
617 self
.mock_calls
= _CallList()
618 self
.call_args_list
= _CallList()
619 self
.method_calls
= _CallList()
621 for child
in self
._mock
_children
.values():
622 if isinstance(child
, _SpecState
):
626 ret
= self
._mock
_return
_value
627 if _is_instance_mock(ret
) and ret
is not self
:
631 def configure_mock(self
, **kwargs
):
632 """Set attributes on the mock through keyword arguments.
634 Attributes plus return values and side effects can be set on child
635 mocks using standard dot notation and unpacking a dictionary in the
638 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
639 >>> mock.configure_mock(**attrs)"""
640 for arg
, val
in sorted(kwargs
.items(),
641 # we sort on the number of dots so that
642 # attributes are set before we set attributes on
644 key
=lambda entry
: entry
[0].count('.')):
645 args
= arg
.split('.')
649 obj
= getattr(obj
, entry
)
650 setattr(obj
, final
, val
)
653 def __getattr__(self
, name
):
654 if name
== '_mock_methods':
655 raise AttributeError(name
)
656 elif self
._mock
_methods
is not None:
657 if name
not in self
._mock
_methods
or name
in _all_magics
:
658 raise AttributeError("Mock object has no attribute %r" % name
)
659 elif _is_magic(name
):
660 raise AttributeError(name
)
662 result
= self
._mock
_children
.get(name
)
663 if result
is _deleted
:
664 raise AttributeError(name
)
667 if self
._mock
_wraps
is not None:
668 # XXXX should we get the attribute without triggering code
670 wraps
= getattr(self
._mock
_wraps
, name
)
672 result
= self
._get
_child
_mock
(
673 parent
=self
, name
=name
, wraps
=wraps
, _new_name
=name
,
676 self
._mock
_children
[name
] = result
678 elif isinstance(result
, _SpecState
):
679 result
= create_autospec(
680 result
.spec
, result
.spec_set
, result
.instance
,
681 result
.parent
, result
.name
683 self
._mock
_children
[name
] = result
689 _name_list
= [self
._mock
_new
_name
]
690 _parent
= self
._mock
_new
_parent
694 if _name_list
== ['()']:
697 while _parent
is not None:
700 _name_list
.append(_parent
._mock
_new
_name
+ dot
)
702 if _parent
._mock
_new
_name
== '()':
705 _parent
= _parent
._mock
_new
_parent
707 # use ids here so as not to call __hash__ on the mocks
708 if id(_parent
) in seen
:
710 seen
.add(id(_parent
))
712 _name_list
= list(reversed(_name_list
))
713 _first
= last
._mock
_name
or 'mock'
714 if len(_name_list
) > 1:
715 if _name_list
[1] not in ('()', '().'):
717 _name_list
[0] = _first
718 name
= ''.join(_name_list
)
721 if name
not in ('mock', 'mock.'):
722 name_string
= ' name=%r' % name
725 if self
._spec
_class
is not None:
726 spec_string
= ' spec=%r'
728 spec_string
= ' spec_set=%r'
729 spec_string
= spec_string
% self
._spec
_class
.__name
__
730 return "<%s%s%s id='%s'>" % (
739 """Filter the output of `dir(mock)` to only useful members.
742 extras
= self
._mock
_methods
or []
743 from_type
= dir(type(self
))
744 from_dict
= list(self
.__dict
__)
747 from_type
= [e
for e
in from_type
if not e
.startswith('_')]
748 from_dict
= [e
for e
in from_dict
if not e
.startswith('_') or
750 return sorted(set(extras
+ from_type
+ from_dict
+
751 list(self
._mock
_children
)))
754 def __setattr__(self
, name
, value
):
755 if name
in _allowed_names
:
756 # property setters go through here
757 return object.__setattr
__(self
, name
, value
)
758 elif (self
._spec
_set
and self
._mock
_methods
is not None and
759 name
not in self
._mock
_methods
and
760 name
not in self
.__dict
__):
761 raise AttributeError("Mock object has no attribute '%s'" % name
)
762 elif name
in _unsupported_magics
:
763 msg
= 'Attempting to set unsupported magic method %r.' % name
764 raise AttributeError(msg
)
765 elif name
in _all_magics
:
766 if self
._mock
_methods
is not None and name
not in self
._mock
_methods
:
767 raise AttributeError("Mock object has no attribute '%s'" % name
)
769 if not _is_instance_mock(value
):
770 setattr(type(self
), name
, _get_method(name
, value
))
772 value
= lambda *args
, **kw
: original(self
, *args
, **kw
)
774 # only set _new_name and not name so that mock_calls is tracked
775 # but not method calls
776 _check_and_set_parent(self
, value
, None, name
)
777 setattr(type(self
), name
, value
)
778 self
._mock
_children
[name
] = value
779 elif name
== '__class__':
780 self
._spec
_class
= value
783 if _check_and_set_parent(self
, value
, name
, name
):
784 self
._mock
_children
[name
] = value
785 return object.__setattr
__(self
, name
, value
)
788 def __delattr__(self
, name
):
789 if name
in _all_magics
and name
in type(self
).__dict
__:
790 delattr(type(self
), name
)
791 if name
not in self
.__dict
__:
792 # for magic methods that are still MagicProxy objects and
793 # not set on the instance itself
796 if name
in self
.__dict
__:
797 object.__delattr
__(self
, name
)
799 obj
= self
._mock
_children
.get(name
, _missing
)
801 raise AttributeError(name
)
802 if obj
is not _missing
:
803 del self
._mock
_children
[name
]
804 self
._mock
_children
[name
] = _deleted
808 def _format_mock_call_signature(self
, args
, kwargs
):
809 name
= self
._mock
_name
or 'mock'
810 return _format_call_signature(name
, args
, kwargs
)
813 def _format_mock_failure_message(self
, args
, kwargs
):
814 message
= 'Expected call: %s\nActual call: %s'
815 expected_string
= self
._format
_mock
_call
_signature
(args
, kwargs
)
816 call_args
= self
.call_args
817 if len(call_args
) == 3:
818 call_args
= call_args
[1:]
819 actual_string
= self
._format
_mock
_call
_signature
(*call_args
)
820 return message
% (expected_string
, actual_string
)
823 def assert_called_with(_mock_self
, *args
, **kwargs
):
824 """assert that the mock was called with the specified arguments.
826 Raises an AssertionError if the args and keyword args passed in are
827 different to the last call to the mock."""
829 if self
.call_args
is None:
830 expected
= self
._format
_mock
_call
_signature
(args
, kwargs
)
831 raise AssertionError('Expected call: %s\nNot called' % (expected
,))
833 if self
.call_args
!= (args
, kwargs
):
834 msg
= self
._format
_mock
_failure
_message
(args
, kwargs
)
835 raise AssertionError(msg
)
838 def assert_called_once_with(_mock_self
, *args
, **kwargs
):
839 """assert that the mock was called exactly once and with the specified
842 if not self
.call_count
== 1:
843 msg
= ("Expected to be called once. Called %s times." %
845 raise AssertionError(msg
)
846 return self
.assert_called_with(*args
, **kwargs
)
849 def assert_has_calls(self
, calls
, any_order
=False):
850 """assert the mock has been called with the specified calls.
851 The `mock_calls` list is checked for the calls.
853 If `any_order` is False (the default) then the calls must be
854 sequential. There can be extra calls before or after the
857 If `any_order` is True then the calls can be in any order, but
858 they must all appear in `mock_calls`."""
860 if calls
not in self
.mock_calls
:
861 raise AssertionError(
862 'Calls not found.\nExpected: %r\n'
863 'Actual: %r' % (calls
, self
.mock_calls
)
867 all_calls
= list(self
.mock_calls
)
872 all_calls
.remove(kall
)
874 not_found
.append(kall
)
876 raise AssertionError(
877 '%r not all found in call list' % (tuple(not_found
),)
881 def assert_any_call(self
, *args
, **kwargs
):
882 """assert the mock has been called with the specified arguments.
884 The assert passes if the mock has *ever* been called, unlike
885 `assert_called_with` and `assert_called_once_with` that only pass if
886 the call is the most recent one."""
887 kall
= call(*args
, **kwargs
)
888 if kall
not in self
.call_args_list
:
889 expected_string
= self
._format
_mock
_call
_signature
(args
, kwargs
)
890 raise AssertionError(
891 '%s call not found' % expected_string
895 def _get_child_mock(self
, **kw
):
896 """Create the child mocks for attributes and return value.
897 By default child mocks will be the same type as the parent.
898 Subclasses of Mock may want to override this to customize the way
899 child mocks are made.
901 For non-callable mocks the callable variant will be used (rather than
902 any custom subclass)."""
904 if not issubclass(_type
, CallableMixin
):
905 if issubclass(_type
, NonCallableMagicMock
):
907 elif issubclass(_type
, NonCallableMock
) :
910 klass
= _type
.__mro
__[1]
918 if _is_exception(obj
):
925 # XXXX backwards compatibility
926 # but this will blow up on first call - so maybe we should fail early?
931 class CallableMixin(Base
):
933 def __init__(self
, spec
=None, side_effect
=None, return_value
=DEFAULT
,
934 wraps
=None, name
=None, spec_set
=None, parent
=None,
935 _spec_state
=None, _new_name
='', _new_parent
=None, **kwargs
):
936 self
.__dict
__['_mock_return_value'] = return_value
938 _super(CallableMixin
, self
).__init
__(
939 spec
, wraps
, name
, spec_set
, parent
,
940 _spec_state
, _new_name
, _new_parent
, **kwargs
943 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
951 def __call__(_mock_self
, *args
, **kwargs
):
952 # can't use self in-case a function / method we are mocking uses self
954 _mock_self
._mock
_check
_sig
(*args
, **kwargs
)
955 return _mock_self
._mock
_call
(*args
, **kwargs
)
958 def _mock_call(_mock_self
, *args
, **kwargs
):
962 self
.call_args
= _Call((args
, kwargs
), two
=True)
963 self
.call_args_list
.append(_Call((args
, kwargs
), two
=True))
965 _new_name
= self
._mock
_new
_name
966 _new_parent
= self
._mock
_new
_parent
967 self
.mock_calls
.append(_Call(('', args
, kwargs
)))
970 skip_next_dot
= _new_name
== '()'
971 do_method_calls
= self
._mock
_parent
is not None
972 name
= self
._mock
_name
973 while _new_parent
is not None:
974 this_mock_call
= _Call((_new_name
, args
, kwargs
))
975 if _new_parent
._mock
_new
_name
:
980 skip_next_dot
= False
981 if _new_parent
._mock
_new
_name
== '()':
984 _new_name
= _new_parent
._mock
_new
_name
+ dot
+ _new_name
987 if _new_name
== name
:
988 this_method_call
= this_mock_call
990 this_method_call
= _Call((name
, args
, kwargs
))
991 _new_parent
.method_calls
.append(this_method_call
)
993 do_method_calls
= _new_parent
._mock
_parent
is not None
995 name
= _new_parent
._mock
_name
+ '.' + name
997 _new_parent
.mock_calls
.append(this_mock_call
)
998 _new_parent
= _new_parent
._mock
_new
_parent
1000 # use ids here so as not to call __hash__ on the mocks
1001 _new_parent_id
= id(_new_parent
)
1002 if _new_parent_id
in seen
:
1004 seen
.add(_new_parent_id
)
1007 effect
= self
.side_effect
1008 if effect
is not None:
1009 if _is_exception(effect
):
1012 if not _callable(effect
):
1013 result
= next(effect
)
1014 if _is_exception(result
):
1018 ret_val
= effect(*args
, **kwargs
)
1019 if ret_val
is DEFAULT
:
1020 ret_val
= self
.return_value
1022 if (self
._mock
_wraps
is not None and
1023 self
._mock
_return
_value
is DEFAULT
):
1024 return self
._mock
_wraps
(*args
, **kwargs
)
1025 if ret_val
is DEFAULT
:
1026 ret_val
= self
.return_value
1031 class Mock(CallableMixin
, NonCallableMock
):
1033 Create a new `Mock` object. `Mock` takes several optional arguments
1034 that specify the behaviour of the Mock object:
1036 * `spec`: This can be either a list of strings or an existing object (a
1037 class or instance) that acts as the specification for the mock object. If
1038 you pass in an object then a list of strings is formed by calling dir on
1039 the object (excluding unsupported magic attributes and methods). Accessing
1040 any attribute not in this list will raise an `AttributeError`.
1042 If `spec` is an object (rather than a list of strings) then
1043 `mock.__class__` returns the class of the spec object. This allows mocks
1044 to pass `isinstance` tests.
1046 * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1047 or get an attribute on the mock that isn't on the object passed as
1048 `spec_set` will raise an `AttributeError`.
1050 * `side_effect`: A function to be called whenever the Mock is called. See
1051 the `side_effect` attribute. Useful for raising exceptions or
1052 dynamically changing return values. The function is called with the same
1053 arguments as the mock, and unless it returns `DEFAULT`, the return
1054 value of this function is used as the return value.
1056 Alternatively `side_effect` can be an exception class or instance. In
1057 this case the exception will be raised when the mock is called.
1059 If `side_effect` is an iterable then each call to the mock will return
1060 the next value from the iterable. If any of the members of the iterable
1061 are exceptions they will be raised instead of returned.
1063 * `return_value`: The value returned when the mock is called. By default
1064 this is a new Mock (created on first access). See the
1065 `return_value` attribute.
1067 * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1068 calling the Mock will pass the call through to the wrapped object
1069 (returning the real result). Attribute access on the mock will return a
1070 Mock object that wraps the corresponding attribute of the wrapped object
1071 (so attempting to access an attribute that doesn't exist will raise an
1074 If the mock has an explicit `return_value` set then calls are not passed
1075 to the wrapped object and the `return_value` is returned instead.
1077 * `name`: If the mock has a name then it will be used in the repr of the
1078 mock. This can be useful for debugging. The name is propagated to child
1081 Mocks can also be called with arbitrary keyword arguments. These will be
1082 used to set attributes on the mock after it is created.
1087 def _dot_lookup(thing
, comp
, import_path
):
1089 return getattr(thing
, comp
)
1090 except AttributeError:
1091 __import__(import_path
)
1092 return getattr(thing
, comp
)
1095 def _importer(target
):
1096 components
= target
.split('.')
1097 import_path
= components
.pop(0)
1098 thing
= __import__(import_path
)
1100 for comp
in components
:
1101 import_path
+= ".%s" % comp
1102 thing
= _dot_lookup(thing
, comp
, import_path
)
1106 def _is_started(patcher
):
1108 return hasattr(patcher
, 'is_local')
1111 class _patch(object):
1113 attribute_name
= None
1114 _active_patches
= set()
1117 self
, getter
, attribute
, new
, spec
, create
,
1118 spec_set
, autospec
, new_callable
, kwargs
1120 if new_callable
is not None:
1121 if new
is not DEFAULT
:
1123 "Cannot use 'new' and 'new_callable' together"
1125 if autospec
is not None:
1127 "Cannot use 'autospec' and 'new_callable' together"
1130 self
.getter
= getter
1131 self
.attribute
= attribute
1133 self
.new_callable
= new_callable
1135 self
.create
= create
1136 self
.has_local
= False
1137 self
.spec_set
= spec_set
1138 self
.autospec
= autospec
1139 self
.kwargs
= kwargs
1140 self
.additional_patchers
= []
1145 self
.getter
, self
.attribute
, self
.new
, self
.spec
,
1146 self
.create
, self
.spec_set
,
1147 self
.autospec
, self
.new_callable
, self
.kwargs
1149 patcher
.attribute_name
= self
.attribute_name
1150 patcher
.additional_patchers
= [
1151 p
.copy() for p
in self
.additional_patchers
1156 def __call__(self
, func
):
1157 if isinstance(func
, ClassTypes
):
1158 return self
.decorate_class(func
)
1159 return self
.decorate_callable(func
)
1162 def decorate_class(self
, klass
):
1163 for attr
in dir(klass
):
1164 if not attr
.startswith(patch
.TEST_PREFIX
):
1167 attr_value
= getattr(klass
, attr
)
1168 if not hasattr(attr_value
, "__call__"):
1171 patcher
= self
.copy()
1172 setattr(klass
, attr
, patcher(attr_value
))
1176 def decorate_callable(self
, func
):
1177 if hasattr(func
, 'patchings'):
1178 func
.patchings
.append(self
)
1182 def patched(*args
, **keywargs
):
1183 # don't use a with here (backwards compatability with Python 2.4)
1185 entered_patchers
= []
1187 # can't use try...except...finally because of Python 2.4
1192 for patching
in patched
.patchings
:
1193 arg
= patching
.__enter
__()
1194 entered_patchers
.append(patching
)
1195 if patching
.attribute_name
is not None:
1196 keywargs
.update(arg
)
1197 elif patching
.new
is DEFAULT
:
1198 extra_args
.append(arg
)
1200 args
+= tuple(extra_args
)
1201 return func(*args
, **keywargs
)
1203 if (patching
not in entered_patchers
and
1204 _is_started(patching
)):
1205 # the patcher may have been started, but an exception
1206 # raised whilst entering one of its additional_patchers
1207 entered_patchers
.append(patching
)
1208 # Pass the exception to __exit__
1209 exc_info
= sys
.exc_info()
1210 # re-raise the exception
1213 for patching
in reversed(entered_patchers
):
1214 patching
.__exit
__(*exc_info
)
1216 patched
.patchings
= [self
]
1217 if hasattr(func
, 'func_code'):
1219 patched
.compat_co_firstlineno
= getattr(
1220 func
, "compat_co_firstlineno",
1221 func
.func_code
.co_firstlineno
1226 def get_original(self
):
1227 target
= self
.getter()
1228 name
= self
.attribute
1234 original
= target
.__dict
__[name
]
1235 except (AttributeError, KeyError):
1236 original
= getattr(target
, name
, DEFAULT
)
1240 if not self
.create
and original
is DEFAULT
:
1241 raise AttributeError(
1242 "%s does not have the attribute %r" % (target
, name
)
1244 return original
, local
1247 def __enter__(self
):
1248 """Perform the patch."""
1249 new
, spec
, spec_set
= self
.new
, self
.spec
, self
.spec_set
1250 autospec
, kwargs
= self
.autospec
, self
.kwargs
1251 new_callable
= self
.new_callable
1252 self
.target
= self
.getter()
1254 # normalise False to None
1257 if spec_set
is False:
1259 if autospec
is False:
1262 if spec
is not None and autospec
is not None:
1263 raise TypeError("Can't specify spec and autospec")
1264 if ((spec
is not None or autospec
is not None) and
1265 spec_set
not in (True, None)):
1266 raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1268 original
, local
= self
.get_original()
1270 if new
is DEFAULT
and autospec
is None:
1273 # set spec to the object we are replacing
1275 if spec_set
is True:
1278 elif spec
is not None:
1279 if spec_set
is True:
1282 elif spec_set
is True:
1285 if spec
is not None or spec_set
is not None:
1286 if original
is DEFAULT
:
1287 raise TypeError("Can't use 'spec' with create=True")
1288 if isinstance(original
, ClassTypes
):
1289 # If we're patching out a class and there is a spec
1294 if new_callable
is not None:
1295 Klass
= new_callable
1296 elif spec
is not None or spec_set
is not None:
1298 if spec_set
is not None:
1299 this_spec
= spec_set
1300 if _is_list(this_spec
):
1301 not_callable
= '__call__' not in this_spec
1303 not_callable
= not _callable(this_spec
)
1305 Klass
= NonCallableMagicMock
1307 if spec
is not None:
1308 _kwargs
['spec'] = spec
1309 if spec_set
is not None:
1310 _kwargs
['spec_set'] = spec_set
1312 # add a name to mocks
1313 if (isinstance(Klass
, type) and
1314 issubclass(Klass
, NonCallableMock
) and self
.attribute
):
1315 _kwargs
['name'] = self
.attribute
1317 _kwargs
.update(kwargs
)
1318 new
= Klass(**_kwargs
)
1320 if inherit
and _is_instance_mock(new
):
1321 # we can only tell if the instance should be callable if the
1322 # spec is not a list
1324 if spec_set
is not None:
1325 this_spec
= spec_set
1326 if (not _is_list(this_spec
) and not
1327 _instance_callable(this_spec
)):
1328 Klass
= NonCallableMagicMock
1331 new
.return_value
= Klass(_new_parent
=new
, _new_name
='()',
1333 elif autospec
is not None:
1334 # spec is ignored, new *must* be default, spec_set is treated
1335 # as a boolean. Should we check spec is not None and that spec_set
1337 if new
is not DEFAULT
:
1339 "autospec creates the mock for you. Can't specify "
1342 if original
is DEFAULT
:
1343 raise TypeError("Can't use 'autospec' with create=True")
1344 spec_set
= bool(spec_set
)
1345 if autospec
is True:
1348 new
= create_autospec(autospec
, spec_set
=spec_set
,
1349 _name
=self
.attribute
, **kwargs
)
1351 # can't set keyword args when we aren't creating the mock
1352 # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1353 raise TypeError("Can't pass kwargs to a mock we aren't creating")
1357 self
.temp_original
= original
1358 self
.is_local
= local
1359 setattr(self
.target
, self
.attribute
, new_attr
)
1360 if self
.attribute_name
is not None:
1362 if self
.new
is DEFAULT
:
1363 extra_args
[self
.attribute_name
] = new
1364 for patching
in self
.additional_patchers
:
1365 arg
= patching
.__enter
__()
1366 if patching
.new
is DEFAULT
:
1367 extra_args
.update(arg
)
1373 def __exit__(self
, *exc_info
):
1374 """Undo the patch."""
1375 if not _is_started(self
):
1376 raise RuntimeError('stop called on unstarted patcher')
1378 if self
.is_local
and self
.temp_original
is not DEFAULT
:
1379 setattr(self
.target
, self
.attribute
, self
.temp_original
)
1381 delattr(self
.target
, self
.attribute
)
1382 if not self
.create
and not hasattr(self
.target
, self
.attribute
):
1383 # needed for proxy objects like django settings
1384 setattr(self
.target
, self
.attribute
, self
.temp_original
)
1386 del self
.temp_original
1389 for patcher
in reversed(self
.additional_patchers
):
1390 if _is_started(patcher
):
1391 patcher
.__exit
__(*exc_info
)
1395 """Activate a patch, returning any created mock."""
1396 result
= self
.__enter
__()
1397 self
._active
_patches
.add(self
)
1402 """Stop an active patch."""
1403 self
._active
_patches
.discard(self
)
1404 return self
.__exit
__()
1408 def _get_target(target
):
1410 target
, attribute
= target
.rsplit('.', 1)
1411 except (TypeError, ValueError):
1412 raise TypeError("Need a valid target to patch. You supplied: %r" %
1414 getter
= lambda: _importer(target
)
1415 return getter
, attribute
1419 target
, attribute
, new
=DEFAULT
, spec
=None,
1420 create
=False, spec_set
=None, autospec
=None,
1421 new_callable
=None, **kwargs
1424 patch.object(target, attribute, new=DEFAULT, spec=None, create=False,
1425 spec_set=None, autospec=None, new_callable=None, **kwargs)
1427 patch the named member (`attribute`) on an object (`target`) with a mock
1430 `patch.object` can be used as a decorator, class decorator or a context
1431 manager. Arguments `new`, `spec`, `create`, `spec_set`,
1432 `autospec` and `new_callable` have the same meaning as for `patch`. Like
1433 `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1434 the mock object it creates.
1436 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1437 for choosing which methods to wrap.
1439 getter
= lambda: target
1441 getter
, attribute
, new
, spec
, create
,
1442 spec_set
, autospec
, new_callable
, kwargs
1446 def _patch_multiple(target
, spec
=None, create
=False, spec_set
=None,
1447 autospec
=None, new_callable
=None, **kwargs
):
1448 """Perform multiple patches in a single call. It takes the object to be
1449 patched (either as an object or a string to fetch the object by importing)
1450 and keyword arguments for the patches::
1452 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1455 Use `DEFAULT` as the value if you want `patch.multiple` to create
1456 mocks for you. In this case the created mocks are passed into a decorated
1457 function by keyword, and a dictionary is returned when `patch.multiple` is
1458 used as a context manager.
1460 `patch.multiple` can be used as a decorator, class decorator or a context
1461 manager. The arguments `spec`, `spec_set`, `create`,
1462 `autospec` and `new_callable` have the same meaning as for `patch`. These
1463 arguments will be applied to *all* patches done by `patch.multiple`.
1465 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1466 for choosing which methods to wrap.
1468 if type(target
) in (unicode, str):
1469 getter
= lambda: _importer(target
)
1471 getter
= lambda: target
1475 'Must supply at least one keyword argument with patch.multiple'
1477 # need to wrap in a list for python 3, where items is a view
1478 items
= list(kwargs
.items())
1479 attribute
, new
= items
[0]
1481 getter
, attribute
, new
, spec
, create
, spec_set
,
1482 autospec
, new_callable
, {}
1484 patcher
.attribute_name
= attribute
1485 for attribute
, new
in items
[1:]:
1486 this_patcher
= _patch(
1487 getter
, attribute
, new
, spec
, create
, spec_set
,
1488 autospec
, new_callable
, {}
1490 this_patcher
.attribute_name
= attribute
1491 patcher
.additional_patchers
.append(this_patcher
)
1496 target
, new
=DEFAULT
, spec
=None, create
=False,
1497 spec_set
=None, autospec
=None, new_callable
=None, **kwargs
1500 `patch` acts as a function decorator, class decorator or a context
1501 manager. Inside the body of the function or with statement, the `target`
1502 is patched with a `new` object. When the function/with statement exits
1503 the patch is undone.
1505 If `new` is omitted, then the target is replaced with a
1506 `MagicMock`. If `patch` is used as a decorator and `new` is
1507 omitted, the created mock is passed in as an extra argument to the
1508 decorated function. If `patch` is used as a context manager the created
1509 mock is returned by the context manager.
1511 `target` should be a string in the form `'package.module.ClassName'`. The
1512 `target` is imported and the specified object replaced with the `new`
1513 object, so the `target` must be importable from the environment you are
1514 calling `patch` from. The target is imported when the decorated function
1515 is executed, not at decoration time.
1517 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1518 if patch is creating one for you.
1520 In addition you can pass `spec=True` or `spec_set=True`, which causes
1521 patch to pass in the object being mocked as the spec/spec_set object.
1523 `new_callable` allows you to specify a different class, or callable object,
1524 that will be called to create the `new` object. By default `MagicMock` is
1527 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1528 then the mock with be created with a spec from the object being replaced.
1529 All attributes of the mock will also have the spec of the corresponding
1530 attribute of the object being replaced. Methods and functions being
1531 mocked will have their arguments checked and will raise a `TypeError` if
1532 they are called with the wrong signature. For mocks replacing a class,
1533 their return value (the 'instance') will have the same spec as the class.
1535 Instead of `autospec=True` you can pass `autospec=some_object` to use an
1536 arbitrary object as the spec instead of the one being replaced.
1538 By default `patch` will fail to replace attributes that don't exist. If
1539 you pass in `create=True`, and the attribute doesn't exist, patch will
1540 create the attribute for you when the patched function is called, and
1541 delete it again afterwards. This is useful for writing tests against
1542 attributes that your production code creates at runtime. It is off by by
1543 default because it can be dangerous. With it switched on you can write
1544 passing tests against APIs that don't actually exist!
1546 Patch can be used as a `TestCase` class decorator. It works by
1547 decorating each test method in the class. This reduces the boilerplate
1548 code when your test methods share a common patchings set. `patch` finds
1549 tests by looking for method names that start with `patch.TEST_PREFIX`.
1550 By default this is `test`, which matches the way `unittest` finds tests.
1551 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1553 Patch can be used as a context manager, with the with statement. Here the
1554 patching applies to the indented block after the with statement. If you
1555 use "as" then the patched object will be bound to the name after the
1556 "as"; very useful if `patch` is creating a mock object for you.
1558 `patch` takes arbitrary keyword arguments. These will be passed to
1559 the `Mock` (or `new_callable`) on construction.
1561 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1562 available for alternate use-cases.
1564 getter
, attribute
= _get_target(target
)
1566 getter
, attribute
, new
, spec
, create
,
1567 spec_set
, autospec
, new_callable
, kwargs
1571 class _patch_dict(object):
1573 Patch a dictionary, or dictionary like object, and restore the dictionary
1574 to its original state after the test.
1576 `in_dict` can be a dictionary or a mapping like container. If it is a
1577 mapping then it must at least support getting, setting and deleting items
1578 plus iterating over keys.
1580 `in_dict` can also be a string specifying the name of the dictionary, which
1581 will then be fetched by importing it.
1583 `values` can be a dictionary of values to set in the dictionary. `values`
1584 can also be an iterable of `(key, value)` pairs.
1586 If `clear` is True then the dictionary will be cleared before the new
1589 `patch.dict` can also be called with arbitrary keyword arguments to set
1590 values in the dictionary::
1592 with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1595 `patch.dict` can be used as a context manager, decorator or class
1596 decorator. When used as a class decorator `patch.dict` honours
1597 `patch.TEST_PREFIX` for choosing which methods to wrap.
1600 def __init__(self
, in_dict
, values
=(), clear
=False, **kwargs
):
1601 if isinstance(in_dict
, basestring
):
1602 in_dict
= _importer(in_dict
)
1603 self
.in_dict
= in_dict
1604 # support any argument supported by dict(...) constructor
1605 self
.values
= dict(values
)
1606 self
.values
.update(kwargs
)
1608 self
._original
= None
1611 def __call__(self
, f
):
1612 if isinstance(f
, ClassTypes
):
1613 return self
.decorate_class(f
)
1615 def _inner(*args
, **kw
):
1618 return f(*args
, **kw
)
1620 self
._unpatch
_dict
()
1625 def decorate_class(self
, klass
):
1626 for attr
in dir(klass
):
1627 attr_value
= getattr(klass
, attr
)
1628 if (attr
.startswith(patch
.TEST_PREFIX
) and
1629 hasattr(attr_value
, "__call__")):
1630 decorator
= _patch_dict(self
.in_dict
, self
.values
, self
.clear
)
1631 decorated
= decorator(attr_value
)
1632 setattr(klass
, attr
, decorated
)
1636 def __enter__(self
):
1637 """Patch the dict."""
1641 def _patch_dict(self
):
1642 values
= self
.values
1643 in_dict
= self
.in_dict
1647 original
= in_dict
.copy()
1648 except AttributeError:
1649 # dict like object with no copy method
1650 # must support iteration over keys
1653 original
[key
] = in_dict
[key
]
1654 self
._original
= original
1657 _clear_dict(in_dict
)
1660 in_dict
.update(values
)
1661 except AttributeError:
1662 # dict like object with no update method
1664 in_dict
[key
] = values
[key
]
1667 def _unpatch_dict(self
):
1668 in_dict
= self
.in_dict
1669 original
= self
._original
1671 _clear_dict(in_dict
)
1674 in_dict
.update(original
)
1675 except AttributeError:
1676 for key
in original
:
1677 in_dict
[key
] = original
[key
]
1680 def __exit__(self
, *args
):
1681 """Unpatch the dict."""
1682 self
._unpatch
_dict
()
1689 def _clear_dict(in_dict
):
1692 except AttributeError:
1693 keys
= list(in_dict
)
1698 def _patch_stopall():
1699 """Stop all active patches."""
1700 for patch
in list(_patch
._active
_patches
):
1704 patch
.object = _patch_object
1705 patch
.dict = _patch_dict
1706 patch
.multiple
= _patch_multiple
1707 patch
.stopall
= _patch_stopall
1708 patch
.TEST_PREFIX
= 'test'
1711 "lt le gt ge eq ne "
1712 "getitem setitem delitem "
1713 "len contains iter "
1716 "divmod neg pos abs invert "
1717 "complex int float index "
1721 numerics
= "add sub mul div floordiv mod lshift rshift and xor or pow "
1722 inplace
= ' '.join('i%s' % n
for n
in numerics
.split())
1723 right
= ' '.join('r%s' % n
for n
in numerics
.split())
1726 extra
= 'bool next '
1728 extra
= 'unicode long nonzero oct hex truediv rtruediv '
1730 # not including __prepare__, __instancecheck__, __subclasscheck__
1731 # (as they are metaclass methods)
1732 # __del__ is not supported at all as it causes problems if it exists
1734 _non_defaults
= set('__%s__' % method
for method
in [
1735 'cmp', 'getslice', 'setslice', 'coerce', 'subclasses',
1736 'format', 'get', 'set', 'delete', 'reversed',
1737 'missing', 'reduce', 'reduce_ex', 'getinitargs',
1738 'getnewargs', 'getstate', 'setstate', 'getformat',
1739 'setformat', 'repr', 'dir'
1743 def _get_method(name
, func
):
1744 "Turns a callable object (like a mock) into a real function"
1745 def method(self
, *args
, **kw
):
1746 return func(self
, *args
, **kw
)
1747 method
.__name
__ = name
1752 '__%s__' % method
for method
in
1753 ' '.join([magic_methods
, numerics
, inplace
, right
, extra
]).split()
1756 _all_magics
= _magics | _non_defaults
1758 _unsupported_magics
= set([
1759 '__getattr__', '__setattr__',
1760 '__init__', '__new__', '__prepare__'
1761 '__instancecheck__', '__subclasscheck__',
1765 _calculate_return_value
= {
1766 '__hash__': lambda self
: object.__hash
__(self
),
1767 '__str__': lambda self
: object.__str
__(self
),
1768 '__sizeof__': lambda self
: object.__sizeof
__(self
),
1769 '__unicode__': lambda self
: unicode(object.__str
__(self
)),
1773 '__lt__': NotImplemented,
1774 '__gt__': NotImplemented,
1775 '__le__': NotImplemented,
1776 '__ge__': NotImplemented,
1778 '__contains__': False,
1784 '__nonzero__': True,
1787 '__long__': long(1),
1794 ret_val
= self
.__eq
__._mock
_return
_value
1795 if ret_val
is not DEFAULT
:
1797 return self
is other
1802 if self
.__ne
__._mock
_return
_value
is not DEFAULT
:
1804 return self
is not other
1807 def _get_iter(self
):
1809 ret_val
= self
.__iter
__._mock
_return
_value
1810 if ret_val
is DEFAULT
:
1812 # if ret_val was already an iterator, then calling iter on it should
1813 # return the iterator unchanged
1814 return iter(ret_val
)
1817 _side_effect_methods
= {
1820 '__iter__': _get_iter
,
1825 def _set_return_value(mock
, method
, name
):
1826 fixed
= _return_values
.get(name
, DEFAULT
)
1827 if fixed
is not DEFAULT
:
1828 method
.return_value
= fixed
1831 return_calulator
= _calculate_return_value
.get(name
)
1832 if return_calulator
is not None:
1834 return_value
= return_calulator(mock
)
1835 except AttributeError:
1836 # XXXX why do we return AttributeError here?
1837 # set it as a side_effect instead?
1838 return_value
= AttributeError(name
)
1839 method
.return_value
= return_value
1842 side_effector
= _side_effect_methods
.get(name
)
1843 if side_effector
is not None:
1844 method
.side_effect
= side_effector(mock
)
1848 class MagicMixin(object):
1849 def __init__(self
, *args
, **kw
):
1850 _super(MagicMixin
, self
).__init
__(*args
, **kw
)
1851 self
._mock
_set
_magics
()
1854 def _mock_set_magics(self
):
1855 these_magics
= _magics
1857 if self
._mock
_methods
is not None:
1858 these_magics
= _magics
.intersection(self
._mock
_methods
)
1860 remove_magics
= set()
1861 remove_magics
= _magics
- these_magics
1863 for entry
in remove_magics
:
1864 if entry
in type(self
).__dict
__:
1865 # remove unneeded magic methods
1866 delattr(self
, entry
)
1868 # don't overwrite existing attributes if called a second time
1869 these_magics
= these_magics
- set(type(self
).__dict
__)
1872 for entry
in these_magics
:
1873 setattr(_type
, entry
, MagicProxy(entry
, self
))
1877 class NonCallableMagicMock(MagicMixin
, NonCallableMock
):
1878 """A version of `MagicMock` that isn't callable."""
1879 def mock_add_spec(self
, spec
, spec_set
=False):
1880 """Add a spec to a mock. `spec` can either be an object or a
1881 list of strings. Only attributes on the `spec` can be fetched as
1882 attributes from the mock.
1884 If `spec_set` is True then only attributes on the spec can be set."""
1885 self
._mock
_add
_spec
(spec
, spec_set
)
1886 self
._mock
_set
_magics
()
1890 class MagicMock(MagicMixin
, Mock
):
1892 MagicMock is a subclass of Mock with default implementations
1893 of most of the magic methods. You can use MagicMock without having to
1894 configure the magic methods yourself.
1896 If you use the `spec` or `spec_set` arguments then *only* magic
1897 methods that exist in the spec will be created.
1899 Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1901 def mock_add_spec(self
, spec
, spec_set
=False):
1902 """Add a spec to a mock. `spec` can either be an object or a
1903 list of strings. Only attributes on the `spec` can be fetched as
1904 attributes from the mock.
1906 If `spec_set` is True then only attributes on the spec can be set."""
1907 self
._mock
_add
_spec
(spec
, spec_set
)
1908 self
._mock
_set
_magics
()
1912 class MagicProxy(object):
1913 def __init__(self
, name
, parent
):
1915 self
.parent
= parent
1917 def __call__(self
, *args
, **kwargs
):
1918 m
= self
.create_mock()
1919 return m(*args
, **kwargs
)
1921 def create_mock(self
):
1923 parent
= self
.parent
1924 m
= parent
._get
_child
_mock
(name
=entry
, _new_name
=entry
,
1926 setattr(parent
, entry
, m
)
1927 _set_return_value(parent
, m
, entry
)
1930 def __get__(self
, obj
, _type
=None):
1931 return self
.create_mock()
1936 "A helper object that compares equal to everything."
1938 def __eq__(self
, other
):
1941 def __ne__(self
, other
):
1951 def _format_call_signature(name
, args
, kwargs
):
1952 message
= '%s(%%s)' % name
1954 args_string
= ', '.join([repr(arg
) for arg
in args
])
1955 kwargs_string
= ', '.join([
1956 '%s=%r' % (key
, value
) for key
, value
in kwargs
.items()
1959 formatted_args
= args_string
1962 formatted_args
+= ', '
1963 formatted_args
+= kwargs_string
1965 return message
% formatted_args
1971 A tuple for holding the results of a call to a mock, either in the form
1972 `(args, kwargs)` or `(name, args, kwargs)`.
1974 If args or kwargs are empty then a call tuple will compare equal to
1975 a tuple without those values. This makes comparisons less verbose::
1977 _Call(('name', (), {})) == ('name',)
1978 _Call(('name', (1,), {})) == ('name', (1,))
1979 _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1981 The `_Call` object provides a useful shortcut for comparing with call::
1983 _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1984 _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1986 If the _Call has no name then it will match any name.
1988 def __new__(cls
, value
=(), name
=None, parent
=None, two
=False,
1995 name
, args
, kwargs
= value
1997 first
, second
= value
1998 if isinstance(first
, basestring
):
2000 if isinstance(second
, tuple):
2005 args
, kwargs
= first
, second
2008 if isinstance(value
, basestring
):
2010 elif isinstance(value
, tuple):
2016 return tuple.__new
__(cls
, (args
, kwargs
))
2018 return tuple.__new
__(cls
, (name
, args
, kwargs
))
2021 def __init__(self
, value
=(), name
=None, parent
=None, two
=False,
2024 self
.parent
= parent
2025 self
.from_kall
= from_kall
2028 def __eq__(self
, other
):
2032 len_other
= len(other
)
2038 self_args
, self_kwargs
= self
2040 self_name
, self_args
, self_kwargs
= self
2044 other_args
, other_kwargs
= (), {}
2045 elif len_other
== 3:
2046 other_name
, other_args
, other_kwargs
= other
2047 elif len_other
== 1:
2049 if isinstance(value
, tuple):
2052 elif isinstance(value
, basestring
):
2054 other_args
, other_kwargs
= (), {}
2057 other_kwargs
= value
2060 # could be (name, args) or (name, kwargs) or (args, kwargs)
2061 first
, second
= other
2062 if isinstance(first
, basestring
):
2064 if isinstance(second
, tuple):
2065 other_args
, other_kwargs
= second
, {}
2067 other_args
, other_kwargs
= (), second
2069 other_args
, other_kwargs
= first
, second
2071 if self_name
and other_name
!= self_name
:
2074 # this order is important for ANY to work!
2075 return (other_args
, other_kwargs
) == (self_args
, self_kwargs
)
2078 def __ne__(self
, other
):
2079 return not self
.__eq
__(other
)
2082 def __call__(self
, *args
, **kwargs
):
2083 if self
.name
is None:
2084 return _Call(('', args
, kwargs
), name
='()')
2086 name
= self
.name
+ '()'
2087 return _Call((self
.name
, args
, kwargs
), name
=name
, parent
=self
)
2090 def __getattr__(self
, attr
):
2091 if self
.name
is None:
2092 return _Call(name
=attr
, from_kall
=False)
2093 name
= '%s.%s' % (self
.name
, attr
)
2094 return _Call(name
=name
, parent
=self
, from_kall
=False)
2098 if not self
.from_kall
:
2099 name
= self
.name
or 'call'
2100 if name
.startswith('()'):
2101 name
= 'call%s' % name
2108 name
, args
, kwargs
= self
2111 elif not name
.startswith('()'):
2112 name
= 'call.%s' % name
2114 name
= 'call%s' % name
2115 return _format_call_signature(name
, args
, kwargs
)
2118 def call_list(self
):
2119 """For a call object that represents multiple calls, `call_list`
2120 returns a list of all the intermediate calls as well as the
2124 while thing
is not None:
2127 thing
= thing
.parent
2128 return _CallList(reversed(vals
))
2131 call
= _Call(from_kall
=False)
2135 def create_autospec(spec
, spec_set
=False, instance
=False, _parent
=None,
2136 _name
=None, **kwargs
):
2137 """Create a mock object using another object as a spec. Attributes on the
2138 mock will use the corresponding attribute on the `spec` object as their
2141 Functions or methods being mocked will have their arguments checked
2142 to check that they are called with the correct signature.
2144 If `spec_set` is True then attempting to set attributes that don't exist
2145 on the spec object will raise an `AttributeError`.
2147 If a class is used as a spec then the return value of the mock (the
2148 instance of the class) will have the same spec. You can use a class as the
2149 spec for an instance object by passing `instance=True`. The returned mock
2150 will only be callable if instances of the mock are callable.
2152 `create_autospec` also takes arbitrary keyword arguments that are passed to
2153 the constructor of the created mock."""
2155 # can't pass a list instance to the mock constructor as it will be
2156 # interpreted as a list of strings
2159 is_type
= isinstance(spec
, ClassTypes
)
2161 _kwargs
= {'spec': spec
}
2163 _kwargs
= {'spec_set': spec
}
2165 # None we mock with a normal mock without a spec
2168 _kwargs
.update(kwargs
)
2171 if type(spec
) in DescriptorTypes
:
2172 # descriptors don't have a spec
2173 # because we don't know what type they return
2175 elif not _callable(spec
):
2176 Klass
= NonCallableMagicMock
2177 elif is_type
and instance
and not _instance_callable(spec
):
2178 Klass
= NonCallableMagicMock
2182 # for a top level object no _new_name should be set
2185 mock
= Klass(parent
=_parent
, _new_parent
=_parent
, _new_name
=_new_name
,
2186 name
=_name
, **_kwargs
)
2188 if isinstance(spec
, FunctionTypes
):
2189 # should only happen at the top level because we don't
2190 # recurse for functions
2191 mock
= _set_signature(mock
, spec
)
2193 _check_signature(spec
, mock
, is_type
, instance
)
2195 if _parent
is not None and not instance
:
2196 _parent
._mock
_children
[_name
] = mock
2198 if is_type
and not instance
and 'return_value' not in kwargs
:
2199 mock
.return_value
= create_autospec(spec
, spec_set
, instance
=True,
2200 _name
='()', _parent
=mock
)
2202 for entry
in dir(spec
):
2203 if _is_magic(entry
):
2204 # MagicMock already does the useful magic methods for us
2207 if isinstance(spec
, FunctionTypes
) and entry
in FunctionAttributes
:
2208 # allow a mock to actually be a function
2211 # XXXX do we need a better way of getting attributes without
2212 # triggering code execution (?) Probably not - we need the actual
2213 # object to mock it so we would rather trigger a property than mock
2214 # the property descriptor. Likewise we want to mock out dynamically
2215 # provided attributes.
2216 # XXXX what about attributes that raise exceptions other than
2217 # AttributeError on being fetched?
2218 # we could be resilient against it, or catch and propagate the
2219 # exception when the attribute is fetched from the mock
2221 original
= getattr(spec
, entry
)
2222 except AttributeError:
2225 kwargs
= {'spec': original
}
2227 kwargs
= {'spec_set': original
}
2229 if not isinstance(original
, FunctionTypes
):
2230 new
= _SpecState(original
, spec_set
, mock
, entry
, instance
)
2231 mock
._mock
_children
[entry
] = new
2234 if isinstance(spec
, FunctionTypes
):
2237 new
= MagicMock(parent
=parent
, name
=entry
, _new_name
=entry
,
2238 _new_parent
=parent
, **kwargs
)
2239 mock
._mock
_children
[entry
] = new
2240 skipfirst
= _must_skip(spec
, entry
, is_type
)
2241 _check_signature(original
, new
, skipfirst
=skipfirst
)
2243 # so functions created with _set_signature become instance attributes,
2244 # *plus* their underlying mock exists in _mock_children of the parent
2245 # mock. Adding to _mock_children may be unnecessary where we are also
2246 # setting as an instance attribute?
2247 if isinstance(new
, FunctionTypes
):
2248 setattr(mock
, entry
, new
)
2253 def _must_skip(spec
, entry
, is_type
):
2254 if not isinstance(spec
, ClassTypes
):
2255 if entry
in getattr(spec
, '__dict__', {}):
2256 # instance attribute - shouldn't skip
2258 spec
= spec
.__class
__
2259 if not hasattr(spec
, '__mro__'):
2260 # old style class: can't have descriptors anyway
2263 for klass
in spec
.__mro
__:
2264 result
= klass
.__dict
__.get(entry
, DEFAULT
)
2265 if result
is DEFAULT
:
2267 if isinstance(result
, (staticmethod, classmethod)):
2271 # shouldn't get here unless function is a dynamically provided attribute
2272 # XXXX untested behaviour
2276 def _get_class(obj
):
2278 return obj
.__class
__
2279 except AttributeError:
2280 # in Python 2, _sre.SRE_Pattern objects have no __class__
2284 class _SpecState(object):
2286 def __init__(self
, spec
, spec_set
=False, parent
=None,
2287 name
=None, ids
=None, instance
=False):
2290 self
.spec_set
= spec_set
2291 self
.parent
= parent
2292 self
.instance
= instance
2298 type(create_autospec
),
2305 FunctionAttributes
= set([
2319 def mock_open(mock
=None, read_data
=''):
2321 A helper function to create a mock to replace the use of `open`. It works
2322 for `open` called directly or used as a context manager.
2324 The `mock` argument is the mock object to configure. If `None` (the
2325 default) then a `MagicMock` will be created for you, with the API limited
2326 to methods or attributes available on standard file handles.
2328 `read_data` is a string for the `read` method of the file handle to return.
2329 This is an empty string by default.
2332 if file_spec
is None:
2336 file_spec
= list(set(dir(_io
.TextIOWrapper
)).union(set(dir(_io
.BytesIO
))))
2341 mock
= MagicMock(name
='open', spec
=open)
2343 handle
= MagicMock(spec
=file_spec
)
2344 handle
.write
.return_value
= None
2345 handle
.__enter
__.return_value
= handle
2346 handle
.read
.return_value
= read_data
2348 mock
.return_value
= handle
2352 class PropertyMock(Mock
):
2354 A mock intended to be used as a property, or other descriptor, on a class.
2355 `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2356 a return value when it is fetched.
2358 Fetching a `PropertyMock` instance from an object calls the mock, with
2359 no args. Setting it calls the mock with the value being set.
2361 def _get_child_mock(self
, **kwargs
):
2362 return MagicMock(**kwargs
)
2364 def __get__(self
, obj
, obj_type
):
2366 def __set__(self
, obj
, val
):