1# mock.py
2# Test tools for mocking and patching.
3# Maintained by Michael Foord
4# Backport for other versions of Python available from
5# http://pypi.python.org/pypi/mock
6
7__all__ = (
8    'Mock',
9    'MagicMock',
10    'patch',
11    'sentinel',
12    'DEFAULT',
13    'ANY',
14    'call',
15    'create_autospec',
16    'FILTER_DIR',
17    'NonCallableMock',
18    'NonCallableMagicMock',
19    'mock_open',
20    'PropertyMock',
21)
22
23
24__version__ = '1.0'
25
26
27import __builtin__
28import inspect
29import pprint
30import sys
31
32from types import ModuleType
33from functools import wraps, partial
34
35
36_builtins = {name for name in dir(__builtin__) if not name.startswith('_')}
37
38BaseExceptions = (BaseException,)
39if 'java' in sys.platform:
40    # jython
41    import java
42    BaseExceptions = (BaseException, java.lang.Throwable)
43
44
45FILTER_DIR = True
46
47# Workaround for issue #12370
48# Without this, the __class__ properties wouldn't be set correctly
49_safe_super = super
50
51def _is_instance_mock(obj):
52    # can't use isinstance on Mock objects because they override __class__
53    # The base class for all mocks is NonCallableMock
54    return issubclass(type(obj), NonCallableMock)
55
56
57def _is_exception(obj):
58    return (
59        isinstance(obj, BaseExceptions) or
60        isinstance(obj, type) and issubclass(obj, BaseExceptions)
61    )
62
63
64class _slotted(object):
65    __slots__ = ['a']
66
67
68DescriptorTypes = (
69    type(_slotted.a),
70    property,
71)
72
73
74def _get_signature_object(func, as_instance, eat_self):
75    """
76    Given an arbitrary, possibly callable object, try to create a suitable
77    signature object.
78    Return a (reduced func, signature) tuple, or None.
79    """
80    if isinstance(func, type) and not as_instance:
81        # If it's a type and should be modelled as a type, use __init__.
82        try:
83            func = func.__init__
84        except AttributeError:
85            return None
86        # Skip the `self` argument in __init__
87        eat_self = True
88    elif not isinstance(func, FunctionTypes):
89        # If we really want to model an instance of the passed type,
90        # __call__ should be looked up, not __init__.
91        try:
92            func = func.__call__
93        except AttributeError:
94            return None
95    if eat_self:
96        sig_func = partial(func, None)
97    else:
98        sig_func = func
99    try:
100        return func, inspect.signature(sig_func)
101    except ValueError:
102        # Certain callable types are not supported by inspect.signature()
103        return None
104
105
106def _check_signature(func, mock, skipfirst, instance=False):
107    sig = _get_signature_object(func, instance, skipfirst)
108    if sig is None:
109        return
110    func, sig = sig
111    def checksig(_mock_self, *args, **kwargs):
112        sig.bind(*args, **kwargs)
113    _copy_func_details(func, checksig)
114    type(mock)._mock_check_sig = checksig
115
116
117def _copy_func_details(func, funcopy):
118    funcopy.__name__ = func.__name__
119    funcopy.__doc__ = func.__doc__
120    try:
121        funcopy.__text_signature__ = func.__text_signature__
122    except AttributeError:
123        pass
124    # we explicitly don't copy func.__dict__ into this copy as it would
125    # expose original attributes that should be mocked
126    try:
127        funcopy.__module__ = func.__module__
128    except AttributeError:
129        pass
130    try:
131        funcopy.__defaults__ = func.__defaults__
132    except AttributeError:
133        pass
134    try:
135        funcopy.__kwdefaults__ = func.__kwdefaults__
136    except AttributeError:
137        pass
138
139
140def _callable(obj):
141    if isinstance(obj, type):
142        return True
143    if getattr(obj, '__call__', None) is not None:
144        return True
145    return False
146
147
148def _is_list(obj):
149    # checks for list or tuples
150    # XXXX badly named!
151    return type(obj) in (list, tuple)
152
153
154def _instance_callable(obj):
155    """Given an object, return True if the object is callable.
156    For classes, return True if instances would be callable."""
157    if not isinstance(obj, type):
158        # already an instance
159        return getattr(obj, '__call__', None) is not None
160
161    # *could* be broken by a class overriding __mro__ or __dict__ via
162    # a metaclass
163    for base in (obj,) + obj.__mro__:
164        if base.__dict__.get('__call__') is not None:
165            return True
166    return False
167
168
169def _set_signature(mock, original, instance=False):
170    # creates a function with signature (*args, **kwargs) that delegates to a
171    # mock. It still does signature checking by calling a lambda with the same
172    # signature as the original.
173    if not _callable(original):
174        return
175
176    skipfirst = isinstance(original, type)
177    result = _get_signature_object(original, instance, skipfirst)
178    if result is None:
179        return
180    func, sig = result
181    def checksig(*args, **kwargs):
182        sig.bind(*args, **kwargs)
183    _copy_func_details(func, checksig)
184
185    name = original.__name__
186    if not name.isidentifier():
187        name = 'funcopy'
188    context = {'_checksig_': checksig, 'mock': mock}
189    src = """def %s(*args, **kwargs):
190    _checksig_(*args, **kwargs)
191    return mock(*args, **kwargs)""" % name
192    exec (src, context)
193    funcopy = context[name]
194    _setup_func(funcopy, mock)
195    return funcopy
196
197
198def _setup_func(funcopy, mock):
199    funcopy.mock = mock
200
201    # can't use isinstance with mocks
202    if not _is_instance_mock(mock):
203        return
204
205    def assert_called_with(*args, **kwargs):
206        return mock.assert_called_with(*args, **kwargs)
207    def assert_called_once_with(*args, **kwargs):
208        return mock.assert_called_once_with(*args, **kwargs)
209    def assert_has_calls(*args, **kwargs):
210        return mock.assert_has_calls(*args, **kwargs)
211    def assert_any_call(*args, **kwargs):
212        return mock.assert_any_call(*args, **kwargs)
213    def reset_mock():
214        funcopy.method_calls = _CallList()
215        funcopy.mock_calls = _CallList()
216        mock.reset_mock()
217        ret = funcopy.return_value
218        if _is_instance_mock(ret) and not ret is mock:
219            ret.reset_mock()
220
221    funcopy.called = False
222    funcopy.call_count = 0
223    funcopy.call_args = None
224    funcopy.call_args_list = _CallList()
225    funcopy.method_calls = _CallList()
226    funcopy.mock_calls = _CallList()
227
228    funcopy.return_value = mock.return_value
229    funcopy.side_effect = mock.side_effect
230    funcopy._mock_children = mock._mock_children
231
232    funcopy.assert_called_with = assert_called_with
233    funcopy.assert_called_once_with = assert_called_once_with
234    funcopy.assert_has_calls = assert_has_calls
235    funcopy.assert_any_call = assert_any_call
236    funcopy.reset_mock = reset_mock
237
238    mock._mock_delegate = funcopy
239
240
241def _is_magic(name):
242    return '__%s__' % name[2:-2] == name
243
244
245class _SentinelObject(object):
246    "A unique, named, sentinel object."
247    def __init__(self, name):
248        self.name = name
249
250    def __repr__(self):
251        return 'sentinel.%s' % self.name
252
253
254class _Sentinel(object):
255    """Access attributes to return a named object, usable as a sentinel."""
256    def __init__(self):
257        self._sentinels = {}
258
259    def __getattr__(self, name):
260        if name == '__bases__':
261            # Without this help(unittest.mock) raises an exception
262            raise AttributeError
263        return self._sentinels.setdefault(name, _SentinelObject(name))
264
265
266sentinel = _Sentinel()
267
268DEFAULT = sentinel.DEFAULT
269_missing = sentinel.MISSING
270_deleted = sentinel.DELETED
271
272
273def _copy(value):
274    if type(value) in (dict, list, tuple, set):
275        return type(value)(value)
276    return value
277
278
279_allowed_names = set(
280    [
281        'return_value', '_mock_return_value', 'side_effect',
282        '_mock_side_effect', '_mock_parent', '_mock_new_parent',
283        '_mock_name', '_mock_new_name'
284    ]
285)
286
287
288def _delegating_property(name):
289    _allowed_names.add(name)
290    _the_name = '_mock_' + name
291    def _get(self, name=name, _the_name=_the_name):
292        sig = self._mock_delegate
293        if sig is None:
294            return getattr(self, _the_name)
295        return getattr(sig, name)
296    def _set(self, value, name=name, _the_name=_the_name):
297        sig = self._mock_delegate
298        if sig is None:
299            self.__dict__[_the_name] = value
300        else:
301            setattr(sig, name, value)
302
303    return property(_get, _set)
304
305
306
307class _CallList(list):
308
309    def __contains__(self, value):
310        if not isinstance(value, list):
311            return list.__contains__(self, value)
312        len_value = len(value)
313        len_self = len(self)
314        if len_value > len_self:
315            return False
316
317        for i in range(0, len_self - len_value + 1):
318            sub_list = self[i:i+len_value]
319            if sub_list == value:
320                return True
321        return False
322
323    def __repr__(self):
324        return pprint.pformat(list(self))
325
326
327def _check_and_set_parent(parent, value, name, new_name):
328    if not _is_instance_mock(value):
329        return False
330    if ((value._mock_name or value._mock_new_name) or
331        (value._mock_parent is not None) or
332        (value._mock_new_parent is not None)):
333        return False
334
335    _parent = parent
336    while _parent is not None:
337        # setting a mock (value) as a child or return value of itself
338        # should not modify the mock
339        if _parent is value:
340            return False
341        _parent = _parent._mock_new_parent
342
343    if new_name:
344        value._mock_new_parent = parent
345        value._mock_new_name = new_name
346    if name:
347        value._mock_parent = parent
348        value._mock_name = name
349    return True
350
351# Internal class to identify if we wrapped an iterator object or not.
352class _MockIter(object):
353    def __init__(self, obj):
354        self.obj = iter(obj)
355    def __iter__(self):
356        return self
357    def __next__(self):
358        return next(self.obj)
359
360class Base(object):
361    _mock_return_value = DEFAULT
362    _mock_side_effect = None
363    def __init__(self, *args, **kwargs):
364        pass
365
366
367
368class NonCallableMock(Base):
369    """A non-callable version of `Mock`"""
370
371    def __new__(cls, *args, **kw):
372        # every instance has its own class
373        # so we can create magic methods on the
374        # class without stomping on other mocks
375        new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
376        instance = object.__new__(new)
377        return instance
378
379
380    def __init__(
381            self, spec=None, wraps=None, name=None, spec_set=None,
382            parent=None, _spec_state=None, _new_name='', _new_parent=None,
383            _spec_as_instance=False, _eat_self=None, unsafe=False, **kwargs
384        ):
385        if _new_parent is None:
386            _new_parent = parent
387
388        __dict__ = self.__dict__
389        __dict__['_mock_parent'] = parent
390        __dict__['_mock_name'] = name
391        __dict__['_mock_new_name'] = _new_name
392        __dict__['_mock_new_parent'] = _new_parent
393
394        if spec_set is not None:
395            spec = spec_set
396            spec_set = True
397        if _eat_self is None:
398            _eat_self = parent is not None
399
400        self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
401
402        __dict__['_mock_children'] = {}
403        __dict__['_mock_wraps'] = wraps
404        __dict__['_mock_delegate'] = None
405
406        __dict__['_mock_called'] = False
407        __dict__['_mock_call_args'] = None
408        __dict__['_mock_call_count'] = 0
409        __dict__['_mock_call_args_list'] = _CallList()
410        __dict__['_mock_mock_calls'] = _CallList()
411
412        __dict__['method_calls'] = _CallList()
413        __dict__['_mock_unsafe'] = unsafe
414
415        if kwargs:
416            self.configure_mock(**kwargs)
417
418        _safe_super(NonCallableMock, self).__init__(
419            spec, wraps, name, spec_set, parent,
420            _spec_state
421        )
422
423
424    def attach_mock(self, mock, attribute):
425        """
426        Attach a mock as an attribute of this one, replacing its name and
427        parent. Calls to the attached mock will be recorded in the
428        `method_calls` and `mock_calls` attributes of this one."""
429        mock._mock_parent = None
430        mock._mock_new_parent = None
431        mock._mock_name = ''
432        mock._mock_new_name = None
433
434        setattr(self, attribute, mock)
435
436
437    def mock_add_spec(self, spec, spec_set=False):
438        """Add a spec to a mock. `spec` can either be an object or a
439        list of strings. Only attributes on the `spec` can be fetched as
440        attributes from the mock.
441
442        If `spec_set` is True then only attributes on the spec can be set."""
443        self._mock_add_spec(spec, spec_set)
444
445
446    def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False,
447                       _eat_self=False):
448        _spec_class = None
449        _spec_signature = None
450
451        if spec is not None and not _is_list(spec):
452            if isinstance(spec, type):
453                _spec_class = spec
454            else:
455                _spec_class = _get_class(spec)
456            res = _get_signature_object(spec,
457                                        _spec_as_instance, _eat_self)
458            _spec_signature = res and res[1]
459
460            spec = dir(spec)
461
462        __dict__ = self.__dict__
463        __dict__['_spec_class'] = _spec_class
464        __dict__['_spec_set'] = spec_set
465        __dict__['_spec_signature'] = _spec_signature
466        __dict__['_mock_methods'] = spec
467
468
469    def __get_return_value(self):
470        ret = self._mock_return_value
471        if self._mock_delegate is not None:
472            ret = self._mock_delegate.return_value
473
474        if ret is DEFAULT:
475            ret = self._get_child_mock(
476                _new_parent=self, _new_name='()'
477            )
478            self.return_value = ret
479        return ret
480
481
482    def __set_return_value(self, value):
483        if self._mock_delegate is not None:
484            self._mock_delegate.return_value = value
485        else:
486            self._mock_return_value = value
487            _check_and_set_parent(self, value, None, '()')
488
489    __return_value_doc = "The value to be returned when the mock is called."
490    return_value = property(__get_return_value, __set_return_value,
491                            __return_value_doc)
492
493
494    @property
495    def __class__(self):
496        if self._spec_class is None:
497            return type(self)
498        return self._spec_class
499
500    called = _delegating_property('called')
501    call_count = _delegating_property('call_count')
502    call_args = _delegating_property('call_args')
503    call_args_list = _delegating_property('call_args_list')
504    mock_calls = _delegating_property('mock_calls')
505
506
507    def __get_side_effect(self):
508        delegated = self._mock_delegate
509        if delegated is None:
510            return self._mock_side_effect
511        sf = delegated.side_effect
512        if sf is not None and not callable(sf) and not isinstance(sf, _MockIter):
513            sf = _MockIter(sf)
514            delegated.side_effect = sf
515        return sf
516
517    def __set_side_effect(self, value):
518        value = _try_iter(value)
519        delegated = self._mock_delegate
520        if delegated is None:
521            self._mock_side_effect = value
522        else:
523            delegated.side_effect = value
524
525    side_effect = property(__get_side_effect, __set_side_effect)
526
527
528    def reset_mock(self):
529        "Restore the mock object to its initial state."
530        self.called = False
531        self.call_args = None
532        self.call_count = 0
533        self.mock_calls = _CallList()
534        self.call_args_list = _CallList()
535        self.method_calls = _CallList()
536
537        for child in self._mock_children.values():
538            if isinstance(child, _SpecState):
539                continue
540            child.reset_mock()
541
542        ret = self._mock_return_value
543        if _is_instance_mock(ret) and ret is not self:
544            ret.reset_mock()
545
546
547    def configure_mock(self, **kwargs):
548        """Set attributes on the mock through keyword arguments.
549
550        Attributes plus return values and side effects can be set on child
551        mocks using standard dot notation and unpacking a dictionary in the
552        method call:
553
554        >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
555        >>> mock.configure_mock(**attrs)"""
556        for arg, val in sorted(kwargs.items(),
557                               # we sort on the number of dots so that
558                               # attributes are set before we set attributes on
559                               # attributes
560                               key=lambda entry: entry[0].count('.')):
561            args = arg.split('.')
562            final = args.pop()
563            obj = self
564            for entry in args:
565                obj = getattr(obj, entry)
566            setattr(obj, final, val)
567
568
569    def __getattr__(self, name):
570        if name in {'_mock_methods', '_mock_unsafe'}:
571            raise AttributeError(name)
572        elif self._mock_methods is not None:
573            if name not in self._mock_methods or name in _all_magics:
574                raise AttributeError("Mock object has no attribute %r" % name)
575        elif _is_magic(name):
576            raise AttributeError(name)
577        if not self._mock_unsafe:
578            if name.startswith(('assert', 'assret')):
579                raise AttributeError(name)
580
581        result = self._mock_children.get(name)
582        if result is _deleted:
583            raise AttributeError(name)
584        elif result is None:
585            wraps = None
586            if self._mock_wraps is not None:
587                # XXXX should we get the attribute without triggering code
588                # execution?
589                wraps = getattr(self._mock_wraps, name)
590
591            result = self._get_child_mock(
592                parent=self, name=name, wraps=wraps, _new_name=name,
593                _new_parent=self
594            )
595            self._mock_children[name]  = result
596
597        elif isinstance(result, _SpecState):
598            result = create_autospec(
599                result.spec, result.spec_set, result.instance,
600                result.parent, result.name
601            )
602            self._mock_children[name]  = result
603
604        return result
605
606
607    def __repr__(self):
608        _name_list = [self._mock_new_name]
609        _parent = self._mock_new_parent
610        last = self
611
612        dot = '.'
613        if _name_list == ['()']:
614            dot = ''
615        seen = set()
616        while _parent is not None:
617            last = _parent
618
619            _name_list.append(_parent._mock_new_name + dot)
620            dot = '.'
621            if _parent._mock_new_name == '()':
622                dot = ''
623
624            _parent = _parent._mock_new_parent
625
626            # use ids here so as not to call __hash__ on the mocks
627            if id(_parent) in seen:
628                break
629            seen.add(id(_parent))
630
631        _name_list = list(reversed(_name_list))
632        _first = last._mock_name or 'mock'
633        if len(_name_list) > 1:
634            if _name_list[1] not in ('()', '().'):
635                _first += '.'
636        _name_list[0] = _first
637        name = ''.join(_name_list)
638
639        name_string = ''
640        if name not in ('mock', 'mock.'):
641            name_string = ' name=%r' % name
642
643        spec_string = ''
644        if self._spec_class is not None:
645            spec_string = ' spec=%r'
646            if self._spec_set:
647                spec_string = ' spec_set=%r'
648            spec_string = spec_string % self._spec_class.__name__
649        return "<%s%s%s id='%s'>" % (
650            type(self).__name__,
651            name_string,
652            spec_string,
653            id(self)
654        )
655
656
657    def __dir__(self):
658        """Filter the output of `dir(mock)` to only useful members."""
659        if not FILTER_DIR:
660            return object.__dir__(self)
661
662        extras = self._mock_methods or []
663        from_type = dir(type(self))
664        from_dict = list(self.__dict__)
665
666        from_type = [e for e in from_type if not e.startswith('_')]
667        from_dict = [e for e in from_dict if not e.startswith('_') or
668                     _is_magic(e)]
669        return sorted(set(extras + from_type + from_dict +
670                          list(self._mock_children)))
671
672
673    def __setattr__(self, name, value):
674        if name in _allowed_names:
675            # property setters go through here
676            return object.__setattr__(self, name, value)
677        elif (self._spec_set and self._mock_methods is not None and
678            name not in self._mock_methods and
679            name not in self.__dict__):
680            raise AttributeError("Mock object has no attribute '%s'" % name)
681        elif name in _unsupported_magics:
682            msg = 'Attempting to set unsupported magic method %r.' % name
683            raise AttributeError(msg)
684        elif name in _all_magics:
685            if self._mock_methods is not None and name not in self._mock_methods:
686                raise AttributeError("Mock object has no attribute '%s'" % name)
687
688            if not _is_instance_mock(value):
689                setattr(type(self), name, _get_method(name, value))
690                original = value
691                value = lambda *args, **kw: original(self, *args, **kw)
692            else:
693                # only set _new_name and not name so that mock_calls is tracked
694                # but not method calls
695                _check_and_set_parent(self, value, None, name)
696                setattr(type(self), name, value)
697                self._mock_children[name] = value
698        elif name == '__class__':
699            self._spec_class = value
700            return
701        else:
702            if _check_and_set_parent(self, value, name, name):
703                self._mock_children[name] = value
704        return object.__setattr__(self, name, value)
705
706
707    def __delattr__(self, name):
708        if name in _all_magics and name in type(self).__dict__:
709            delattr(type(self), name)
710            if name not in self.__dict__:
711                # for magic methods that are still MagicProxy objects and
712                # not set on the instance itself
713                return
714
715        if name in self.__dict__:
716            object.__delattr__(self, name)
717
718        obj = self._mock_children.get(name, _missing)
719        if obj is _deleted:
720            raise AttributeError(name)
721        if obj is not _missing:
722            del self._mock_children[name]
723        self._mock_children[name] = _deleted
724
725
726    def _format_mock_call_signature(self, args, kwargs):
727        name = self._mock_name or 'mock'
728        return _format_call_signature(name, args, kwargs)
729
730
731    def _format_mock_failure_message(self, args, kwargs):
732        message = 'Expected call: %s\nActual call: %s'
733        expected_string = self._format_mock_call_signature(args, kwargs)
734        call_args = self.call_args
735        if len(call_args) == 3:
736            call_args = call_args[1:]
737        actual_string = self._format_mock_call_signature(*call_args)
738        return message % (expected_string, actual_string)
739
740
741    def _call_matcher(self, _call):
742        """
743        Given a call (or simply an (args, kwargs) tuple), return a
744        comparison key suitable for matching with other calls.
745        This is a best effort method which relies on the spec's signature,
746        if available, or falls back on the arguments themselves.
747        """
748        sig = self._spec_signature
749        if sig is not None:
750            if len(_call) == 2:
751                name = ''
752                args, kwargs = _call
753            else:
754                name, args, kwargs = _call
755            try:
756                return name, sig.bind(*args, **kwargs)
757            except TypeError as e:
758                return e.with_traceback(None)
759        else:
760            return _call
761
762    def assert_not_called(_mock_self):
763        """assert that the mock was never called.
764        """
765        self = _mock_self
766        if self.call_count != 0:
767            msg = ("Expected '%s' to not have been called. Called %s times." %
768                   (self._mock_name or 'mock', self.call_count))
769            raise AssertionError(msg)
770
771    def assert_called_with(_mock_self, *args, **kwargs):
772        """assert that the mock was called with the specified arguments.
773
774        Raises an AssertionError if the args and keyword args passed in are
775        different to the last call to the mock."""
776        self = _mock_self
777        if self.call_args is None:
778            expected = self._format_mock_call_signature(args, kwargs)
779            raise AssertionError('Expected call: %s\nNot called' % (expected,))
780
781        def _error_message():
782            msg = self._format_mock_failure_message(args, kwargs)
783            return msg
784        expected = self._call_matcher((args, kwargs))
785        actual = self._call_matcher(self.call_args)
786        if expected != actual:
787            raise AssertionError(_error_message())
788
789
790    def assert_called_once_with(_mock_self, *args, **kwargs):
791        """assert that the mock was called exactly once and with the specified
792        arguments."""
793        self = _mock_self
794        if not self.call_count == 1:
795            msg = ("Expected '%s' to be called once. Called %s times." %
796                   (self._mock_name or 'mock', self.call_count))
797            raise AssertionError(msg)
798        return self.assert_called_with(*args, **kwargs)
799
800
801    def assert_has_calls(self, calls, any_order=False):
802        """assert the mock has been called with the specified calls.
803        The `mock_calls` list is checked for the calls.
804
805        If `any_order` is False (the default) then the calls must be
806        sequential. There can be extra calls before or after the
807        specified calls.
808
809        If `any_order` is True then the calls can be in any order, but
810        they must all appear in `mock_calls`."""
811        expected = [self._call_matcher(c) for c in calls]
812        all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
813        if not any_order:
814            if expected not in all_calls:
815                raise AssertionError(
816                    'Calls not found.\nExpected: %r\n'
817                    'Actual: %r' % (calls, self.mock_calls)
818                )
819            return
820
821        all_calls = list(all_calls)
822
823        not_found = []
824        for kall in expected:
825            try:
826                all_calls.remove(kall)
827            except ValueError:
828                not_found.append(kall)
829        if not_found:
830            raise AssertionError(
831                '%r not all found in call list' % (tuple(not_found),)
832            )
833
834
835    def assert_any_call(self, *args, **kwargs):
836        """assert the mock has been called with the specified arguments.
837
838        The assert passes if the mock has *ever* been called, unlike
839        `assert_called_with` and `assert_called_once_with` that only pass if
840        the call is the most recent one."""
841        expected = self._call_matcher((args, kwargs))
842        actual = [self._call_matcher(c) for c in self.call_args_list]
843        if expected not in actual:
844            expected_string = self._format_mock_call_signature(args, kwargs)
845            raise AssertionError(
846                '%s call not found' % expected_string
847            )
848
849
850    def _get_child_mock(self, **kw):
851        """Create the child mocks for attributes and return value.
852        By default child mocks will be the same type as the parent.
853        Subclasses of Mock may want to override this to customize the way
854        child mocks are made.
855
856        For non-callable mocks the callable variant will be used (rather than
857        any custom subclass)."""
858        _type = type(self)
859        if not issubclass(_type, CallableMixin):
860            if issubclass(_type, NonCallableMagicMock):
861                klass = MagicMock
862            elif issubclass(_type, NonCallableMock) :
863                klass = Mock
864        else:
865            klass = _type.__mro__[1]
866        return klass(**kw)
867
868
869
870def _try_iter(obj):
871    if obj is None:
872        return obj
873    if _is_exception(obj):
874        return obj
875    if _callable(obj):
876        return obj
877    try:
878        return iter(obj)
879    except TypeError:
880        # XXXX backwards compatibility
881        # but this will blow up on first call - so maybe we should fail early?
882        return obj
883
884
885
886class CallableMixin(Base):
887
888    def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
889                 wraps=None, name=None, spec_set=None, parent=None,
890                 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
891        self.__dict__['_mock_return_value'] = return_value
892
893        _safe_super(CallableMixin, self).__init__(
894            spec, wraps, name, spec_set, parent,
895            _spec_state, _new_name, _new_parent, **kwargs
896        )
897
898        self.side_effect = side_effect
899
900
901    def _mock_check_sig(self, *args, **kwargs):
902        # stub method that can be replaced with one with a specific signature
903        pass
904
905
906    def __call__(_mock_self, *args, **kwargs):
907        # can't use self in-case a function / method we are mocking uses self
908        # in the signature
909        _mock_self._mock_check_sig(*args, **kwargs)
910        return _mock_self._mock_call(*args, **kwargs)
911
912
913    def _mock_call(_mock_self, *args, **kwargs):
914        self = _mock_self
915        self.called = True
916        self.call_count += 1
917        _new_name = self._mock_new_name
918        _new_parent = self._mock_new_parent
919
920        _call = _Call((args, kwargs), two=True)
921        self.call_args = _call
922        self.call_args_list.append(_call)
923        self.mock_calls.append(_Call(('', args, kwargs)))
924
925        seen = set()
926        skip_next_dot = _new_name == '()'
927        do_method_calls = self._mock_parent is not None
928        name = self._mock_name
929        while _new_parent is not None:
930            this_mock_call = _Call((_new_name, args, kwargs))
931            if _new_parent._mock_new_name:
932                dot = '.'
933                if skip_next_dot:
934                    dot = ''
935
936                skip_next_dot = False
937                if _new_parent._mock_new_name == '()':
938                    skip_next_dot = True
939
940                _new_name = _new_parent._mock_new_name + dot + _new_name
941
942            if do_method_calls:
943                if _new_name == name:
944                    this_method_call = this_mock_call
945                else:
946                    this_method_call = _Call((name, args, kwargs))
947                _new_parent.method_calls.append(this_method_call)
948
949                do_method_calls = _new_parent._mock_parent is not None
950                if do_method_calls:
951                    name = _new_parent._mock_name + '.' + name
952
953            _new_parent.mock_calls.append(this_mock_call)
954            _new_parent = _new_parent._mock_new_parent
955
956            # use ids here so as not to call __hash__ on the mocks
957            _new_parent_id = id(_new_parent)
958            if _new_parent_id in seen:
959                break
960            seen.add(_new_parent_id)
961
962        ret_val = DEFAULT
963        effect = self.side_effect
964        if effect is not None:
965            if _is_exception(effect):
966                raise effect
967
968            if not _callable(effect):
969                result = next(effect)
970                if _is_exception(result):
971                    raise result
972                if result is DEFAULT:
973                    result = self.return_value
974                return result
975
976            ret_val = effect(*args, **kwargs)
977
978        if (self._mock_wraps is not None and
979             self._mock_return_value is DEFAULT):
980            return self._mock_wraps(*args, **kwargs)
981        if ret_val is DEFAULT:
982            ret_val = self.return_value
983        return ret_val
984
985
986
987class Mock(CallableMixin, NonCallableMock):
988    """
989    Create a new `Mock` object. `Mock` takes several optional arguments
990    that specify the behaviour of the Mock object:
991
992    * `spec`: This can be either a list of strings or an existing object (a
993      class or instance) that acts as the specification for the mock object. If
994      you pass in an object then a list of strings is formed by calling dir on
995      the object (excluding unsupported magic attributes and methods). Accessing
996      any attribute not in this list will raise an `AttributeError`.
997
998      If `spec` is an object (rather than a list of strings) then
999      `mock.__class__` returns the class of the spec object. This allows mocks
1000      to pass `isinstance` tests.
1001
1002    * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
1003      or get an attribute on the mock that isn't on the object passed as
1004      `spec_set` will raise an `AttributeError`.
1005
1006    * `side_effect`: A function to be called whenever the Mock is called. See
1007      the `side_effect` attribute. Useful for raising exceptions or
1008      dynamically changing return values. The function is called with the same
1009      arguments as the mock, and unless it returns `DEFAULT`, the return
1010      value of this function is used as the return value.
1011
1012      If `side_effect` is an iterable then each call to the mock will return
1013      the next value from the iterable. If any of the members of the iterable
1014      are exceptions they will be raised instead of returned.
1015
1016    * `return_value`: The value returned when the mock is called. By default
1017      this is a new Mock (created on first access). See the
1018      `return_value` attribute.
1019
1020    * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
1021      calling the Mock will pass the call through to the wrapped object
1022      (returning the real result). Attribute access on the mock will return a
1023      Mock object that wraps the corresponding attribute of the wrapped object
1024      (so attempting to access an attribute that doesn't exist will raise an
1025      `AttributeError`).
1026
1027      If the mock has an explicit `return_value` set then calls are not passed
1028      to the wrapped object and the `return_value` is returned instead.
1029
1030    * `name`: If the mock has a name then it will be used in the repr of the
1031      mock. This can be useful for debugging. The name is propagated to child
1032      mocks.
1033
1034    Mocks can also be called with arbitrary keyword arguments. These will be
1035    used to set attributes on the mock after it is created.
1036    """
1037
1038
1039
1040def _dot_lookup(thing, comp, import_path):
1041    try:
1042        return getattr(thing, comp)
1043    except AttributeError:
1044        __import__(import_path)
1045        return getattr(thing, comp)
1046
1047
1048def _importer(target):
1049    components = target.split('.')
1050    import_path = components.pop(0)
1051    thing = __import__(import_path)
1052
1053    for comp in components:
1054        import_path += ".%s" % comp
1055        thing = _dot_lookup(thing, comp, import_path)
1056    return thing
1057
1058
1059def _is_started(patcher):
1060    # XXXX horrible
1061    return hasattr(patcher, 'is_local')
1062
1063
1064class _patch(object):
1065
1066    attribute_name = None
1067    _active_patches = []
1068
1069    def __init__(
1070            self, getter, attribute, new, spec, create,
1071            spec_set, autospec, new_callable, kwargs
1072        ):
1073        if new_callable is not None:
1074            if new is not DEFAULT:
1075                raise ValueError(
1076                    "Cannot use 'new' and 'new_callable' together"
1077                )
1078            if autospec is not None:
1079                raise ValueError(
1080                    "Cannot use 'autospec' and 'new_callable' together"
1081                )
1082
1083        self.getter = getter
1084        self.attribute = attribute
1085        self.new = new
1086        self.new_callable = new_callable
1087        self.spec = spec
1088        self.create = create
1089        self.has_local = False
1090        self.spec_set = spec_set
1091        self.autospec = autospec
1092        self.kwargs = kwargs
1093        self.additional_patchers = []
1094
1095
1096    def copy(self):
1097        patcher = _patch(
1098            self.getter, self.attribute, self.new, self.spec,
1099            self.create, self.spec_set,
1100            self.autospec, self.new_callable, self.kwargs
1101        )
1102        patcher.attribute_name = self.attribute_name
1103        patcher.additional_patchers = [
1104            p.copy() for p in self.additional_patchers
1105        ]
1106        return patcher
1107
1108
1109    def __call__(self, func):
1110        if isinstance(func, type):
1111            return self.decorate_class(func)
1112        return self.decorate_callable(func)
1113
1114
1115    def decorate_class(self, klass):
1116        for attr in dir(klass):
1117            if not attr.startswith(patch.TEST_PREFIX):
1118                continue
1119
1120            attr_value = getattr(klass, attr)
1121            if not hasattr(attr_value, "__call__"):
1122                continue
1123
1124            patcher = self.copy()
1125            setattr(klass, attr, patcher(attr_value))
1126        return klass
1127
1128
1129    def decorate_callable(self, func):
1130        if hasattr(func, 'patchings'):
1131            func.patchings.append(self)
1132            return func
1133
1134        @wraps(func)
1135        def patched(*args, **keywargs):
1136            extra_args = []
1137            entered_patchers = []
1138
1139            exc_info = tuple()
1140            try:
1141                for patching in patched.patchings:
1142                    arg = patching.__enter__()
1143                    entered_patchers.append(patching)
1144                    if patching.attribute_name is not None:
1145                        keywargs.update(arg)
1146                    elif patching.new is DEFAULT:
1147                        extra_args.append(arg)
1148
1149                args += tuple(extra_args)
1150                return func(*args, **keywargs)
1151            except:
1152                if (patching not in entered_patchers and
1153                    _is_started(patching)):
1154                    # the patcher may have been started, but an exception
1155                    # raised whilst entering one of its additional_patchers
1156                    entered_patchers.append(patching)
1157                # Pass the exception to __exit__
1158                exc_info = sys.exc_info()
1159                # re-raise the exception
1160                raise
1161            finally:
1162                for patching in reversed(entered_patchers):
1163                    patching.__exit__(*exc_info)
1164
1165        patched.patchings = [self]
1166        return patched
1167
1168
1169    def get_original(self):
1170        target = self.getter()
1171        name = self.attribute
1172
1173        original = DEFAULT
1174        local = False
1175
1176        try:
1177            original = target.__dict__[name]
1178        except (AttributeError, KeyError):
1179            original = getattr(target, name, DEFAULT)
1180        else:
1181            local = True
1182
1183        if name in _builtins and isinstance(target, ModuleType):
1184            self.create = True
1185
1186        if not self.create and original is DEFAULT:
1187            raise AttributeError(
1188                "%s does not have the attribute %r" % (target, name)
1189            )
1190        return original, local
1191
1192
1193    def __enter__(self):
1194        """Perform the patch."""
1195        new, spec, spec_set = self.new, self.spec, self.spec_set
1196        autospec, kwargs = self.autospec, self.kwargs
1197        new_callable = self.new_callable
1198        self.target = self.getter()
1199
1200        # normalise False to None
1201        if spec is False:
1202            spec = None
1203        if spec_set is False:
1204            spec_set = None
1205        if autospec is False:
1206            autospec = None
1207
1208        if spec is not None and autospec is not None:
1209            raise TypeError("Can't specify spec and autospec")
1210        if ((spec is not None or autospec is not None) and
1211            spec_set not in (True, None)):
1212            raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
1213
1214        original, local = self.get_original()
1215
1216        if new is DEFAULT and autospec is None:
1217            inherit = False
1218            if spec is True:
1219                # set spec to the object we are replacing
1220                spec = original
1221                if spec_set is True:
1222                    spec_set = original
1223                    spec = None
1224            elif spec is not None:
1225                if spec_set is True:
1226                    spec_set = spec
1227                    spec = None
1228            elif spec_set is True:
1229                spec_set = original
1230
1231            if spec is not None or spec_set is not None:
1232                if original is DEFAULT:
1233                    raise TypeError("Can't use 'spec' with create=True")
1234                if isinstance(original, type):
1235                    # If we're patching out a class and there is a spec
1236                    inherit = True
1237
1238            Klass = MagicMock
1239            _kwargs = {}
1240            if new_callable is not None:
1241                Klass = new_callable
1242            elif spec is not None or spec_set is not None:
1243                this_spec = spec
1244                if spec_set is not None:
1245                    this_spec = spec_set
1246                if _is_list(this_spec):
1247                    not_callable = '__call__' not in this_spec
1248                else:
1249                    not_callable = not callable(this_spec)
1250                if not_callable:
1251                    Klass = NonCallableMagicMock
1252
1253            if spec is not None:
1254                _kwargs['spec'] = spec
1255            if spec_set is not None:
1256                _kwargs['spec_set'] = spec_set
1257
1258            # add a name to mocks
1259            if (isinstance(Klass, type) and
1260                issubclass(Klass, NonCallableMock) and self.attribute):
1261                _kwargs['name'] = self.attribute
1262
1263            _kwargs.update(kwargs)
1264            new = Klass(**_kwargs)
1265
1266            if inherit and _is_instance_mock(new):
1267                # we can only tell if the instance should be callable if the
1268                # spec is not a list
1269                this_spec = spec
1270                if spec_set is not None:
1271                    this_spec = spec_set
1272                if (not _is_list(this_spec) and not
1273                    _instance_callable(this_spec)):
1274                    Klass = NonCallableMagicMock
1275
1276                _kwargs.pop('name')
1277                new.return_value = Klass(_new_parent=new, _new_name='()',
1278                                         **_kwargs)
1279        elif autospec is not None:
1280            # spec is ignored, new *must* be default, spec_set is treated
1281            # as a boolean. Should we check spec is not None and that spec_set
1282            # is a bool?
1283            if new is not DEFAULT:
1284                raise TypeError(
1285                    "autospec creates the mock for you. Can't specify "
1286                    "autospec and new."
1287                )
1288            if original is DEFAULT:
1289                raise TypeError("Can't use 'autospec' with create=True")
1290            spec_set = bool(spec_set)
1291            if autospec is True:
1292                autospec = original
1293
1294            new = create_autospec(autospec, spec_set=spec_set,
1295                                  _name=self.attribute, **kwargs)
1296        elif kwargs:
1297            # can't set keyword args when we aren't creating the mock
1298            # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
1299            raise TypeError("Can't pass kwargs to a mock we aren't creating")
1300
1301        new_attr = new
1302
1303        self.temp_original = original
1304        self.is_local = local
1305        setattr(self.target, self.attribute, new_attr)
1306        if self.attribute_name is not None:
1307            extra_args = {}
1308            if self.new is DEFAULT:
1309                extra_args[self.attribute_name] =  new
1310            for patching in self.additional_patchers:
1311                arg = patching.__enter__()
1312                if patching.new is DEFAULT:
1313                    extra_args.update(arg)
1314            return extra_args
1315
1316        return new
1317
1318
1319    def __exit__(self, *exc_info):
1320        """Undo the patch."""
1321        if not _is_started(self):
1322            raise RuntimeError('stop called on unstarted patcher')
1323
1324        if self.is_local and self.temp_original is not DEFAULT:
1325            setattr(self.target, self.attribute, self.temp_original)
1326        else:
1327            delattr(self.target, self.attribute)
1328            if not self.create and not hasattr(self.target, self.attribute):
1329                # needed for proxy objects like django settings
1330                setattr(self.target, self.attribute, self.temp_original)
1331
1332        del self.temp_original
1333        del self.is_local
1334        del self.target
1335        for patcher in reversed(self.additional_patchers):
1336            if _is_started(patcher):
1337                patcher.__exit__(*exc_info)
1338
1339
1340    def start(self):
1341        """Activate a patch, returning any created mock."""
1342        result = self.__enter__()
1343        self._active_patches.append(self)
1344        return result
1345
1346
1347    def stop(self):
1348        """Stop an active patch."""
1349        try:
1350            self._active_patches.remove(self)
1351        except ValueError:
1352            # If the patch hasn't been started this will fail
1353            pass
1354
1355        return self.__exit__()
1356
1357
1358
1359def _get_target(target):
1360    try:
1361        target, attribute = target.rsplit('.', 1)
1362    except (TypeError, ValueError):
1363        raise TypeError("Need a valid target to patch. You supplied: %r" %
1364                        (target,))
1365    getter = lambda: _importer(target)
1366    return getter, attribute
1367
1368
1369def _patch_object(
1370        target, attribute, new=DEFAULT, spec=None,
1371        create=False, spec_set=None, autospec=None,
1372        new_callable=None, **kwargs
1373    ):
1374    """
1375    patch the named member (`attribute`) on an object (`target`) with a mock
1376    object.
1377
1378    `patch.object` can be used as a decorator, class decorator or a context
1379    manager. Arguments `new`, `spec`, `create`, `spec_set`,
1380    `autospec` and `new_callable` have the same meaning as for `patch`. Like
1381    `patch`, `patch.object` takes arbitrary keyword arguments for configuring
1382    the mock object it creates.
1383
1384    When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
1385    for choosing which methods to wrap.
1386    """
1387    getter = lambda: target
1388    return _patch(
1389        getter, attribute, new, spec, create,
1390        spec_set, autospec, new_callable, kwargs
1391    )
1392
1393
1394def _patch_multiple(target, spec=None, create=False, spec_set=None,
1395                    autospec=None, new_callable=None, **kwargs):
1396    """Perform multiple patches in a single call. It takes the object to be
1397    patched (either as an object or a string to fetch the object by importing)
1398    and keyword arguments for the patches::
1399
1400        with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1401            ...
1402
1403    Use `DEFAULT` as the value if you want `patch.multiple` to create
1404    mocks for you. In this case the created mocks are passed into a decorated
1405    function by keyword, and a dictionary is returned when `patch.multiple` is
1406    used as a context manager.
1407
1408    `patch.multiple` can be used as a decorator, class decorator or a context
1409    manager. The arguments `spec`, `spec_set`, `create`,
1410    `autospec` and `new_callable` have the same meaning as for `patch`. These
1411    arguments will be applied to *all* patches done by `patch.multiple`.
1412
1413    When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
1414    for choosing which methods to wrap.
1415    """
1416    if type(target) is str:
1417        getter = lambda: _importer(target)
1418    else:
1419        getter = lambda: target
1420
1421    if not kwargs:
1422        raise ValueError(
1423            'Must supply at least one keyword argument with patch.multiple'
1424        )
1425    # need to wrap in a list for python 3, where items is a view
1426    items = list(kwargs.items())
1427    attribute, new = items[0]
1428    patcher = _patch(
1429        getter, attribute, new, spec, create, spec_set,
1430        autospec, new_callable, {}
1431    )
1432    patcher.attribute_name = attribute
1433    for attribute, new in items[1:]:
1434        this_patcher = _patch(
1435            getter, attribute, new, spec, create, spec_set,
1436            autospec, new_callable, {}
1437        )
1438        this_patcher.attribute_name = attribute
1439        patcher.additional_patchers.append(this_patcher)
1440    return patcher
1441
1442
1443def patch(
1444        target, new=DEFAULT, spec=None, create=False,
1445        spec_set=None, autospec=None, new_callable=None, **kwargs
1446    ):
1447    """
1448    `patch` acts as a function decorator, class decorator or a context
1449    manager. Inside the body of the function or with statement, the `target`
1450    is patched with a `new` object. When the function/with statement exits
1451    the patch is undone.
1452
1453    If `new` is omitted, then the target is replaced with a
1454    `MagicMock`. If `patch` is used as a decorator and `new` is
1455    omitted, the created mock is passed in as an extra argument to the
1456    decorated function. If `patch` is used as a context manager the created
1457    mock is returned by the context manager.
1458
1459    `target` should be a string in the form `'package.module.ClassName'`. The
1460    `target` is imported and the specified object replaced with the `new`
1461    object, so the `target` must be importable from the environment you are
1462    calling `patch` from. The target is imported when the decorated function
1463    is executed, not at decoration time.
1464
1465    The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
1466    if patch is creating one for you.
1467
1468    In addition you can pass `spec=True` or `spec_set=True`, which causes
1469    patch to pass in the object being mocked as the spec/spec_set object.
1470
1471    `new_callable` allows you to specify a different class, or callable object,
1472    that will be called to create the `new` object. By default `MagicMock` is
1473    used.
1474
1475    A more powerful form of `spec` is `autospec`. If you set `autospec=True`
1476    then the mock with be created with a spec from the object being replaced.
1477    All attributes of the mock will also have the spec of the corresponding
1478    attribute of the object being replaced. Methods and functions being
1479    mocked will have their arguments checked and will raise a `TypeError` if
1480    they are called with the wrong signature. For mocks replacing a class,
1481    their return value (the 'instance') will have the same spec as the class.
1482
1483    Instead of `autospec=True` you can pass `autospec=some_object` to use an
1484    arbitrary object as the spec instead of the one being replaced.
1485
1486    By default `patch` will fail to replace attributes that don't exist. If
1487    you pass in `create=True`, and the attribute doesn't exist, patch will
1488    create the attribute for you when the patched function is called, and
1489    delete it again afterwards. This is useful for writing tests against
1490    attributes that your production code creates at runtime. It is off by
1491    default because it can be dangerous. With it switched on you can write
1492    passing tests against APIs that don't actually exist!
1493
1494    Patch can be used as a `TestCase` class decorator. It works by
1495    decorating each test method in the class. This reduces the boilerplate
1496    code when your test methods share a common patchings set. `patch` finds
1497    tests by looking for method names that start with `patch.TEST_PREFIX`.
1498    By default this is `test`, which matches the way `unittest` finds tests.
1499    You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
1500
1501    Patch can be used as a context manager, with the with statement. Here the
1502    patching applies to the indented block after the with statement. If you
1503    use "as" then the patched object will be bound to the name after the
1504    "as"; very useful if `patch` is creating a mock object for you.
1505
1506    `patch` takes arbitrary keyword arguments. These will be passed to
1507    the `Mock` (or `new_callable`) on construction.
1508
1509    `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
1510    available for alternate use-cases.
1511    """
1512    getter, attribute = _get_target(target)
1513    return _patch(
1514        getter, attribute, new, spec, create,
1515        spec_set, autospec, new_callable, kwargs
1516    )
1517
1518
1519class _patch_dict(object):
1520    """
1521    Patch a dictionary, or dictionary like object, and restore the dictionary
1522    to its original state after the test.
1523
1524    `in_dict` can be a dictionary or a mapping like container. If it is a
1525    mapping then it must at least support getting, setting and deleting items
1526    plus iterating over keys.
1527
1528    `in_dict` can also be a string specifying the name of the dictionary, which
1529    will then be fetched by importing it.
1530
1531    `values` can be a dictionary of values to set in the dictionary. `values`
1532    can also be an iterable of `(key, value)` pairs.
1533
1534    If `clear` is True then the dictionary will be cleared before the new
1535    values are set.
1536
1537    `patch.dict` can also be called with arbitrary keyword arguments to set
1538    values in the dictionary::
1539
1540        with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
1541            ...
1542
1543    `patch.dict` can be used as a context manager, decorator or class
1544    decorator. When used as a class decorator `patch.dict` honours
1545    `patch.TEST_PREFIX` for choosing which methods to wrap.
1546    """
1547
1548    def __init__(self, in_dict, values=(), clear=False, **kwargs):
1549        if isinstance(in_dict, str):
1550            in_dict = _importer(in_dict)
1551        self.in_dict = in_dict
1552        # support any argument supported by dict(...) constructor
1553        self.values = dict(values)
1554        self.values.update(kwargs)
1555        self.clear = clear
1556        self._original = None
1557
1558
1559    def __call__(self, f):
1560        if isinstance(f, type):
1561            return self.decorate_class(f)
1562        @wraps(f)
1563        def _inner(*args, **kw):
1564            self._patch_dict()
1565            try:
1566                return f(*args, **kw)
1567            finally:
1568                self._unpatch_dict()
1569
1570        return _inner
1571
1572
1573    def decorate_class(self, klass):
1574        for attr in dir(klass):
1575            attr_value = getattr(klass, attr)
1576            if (attr.startswith(patch.TEST_PREFIX) and
1577                 hasattr(attr_value, "__call__")):
1578                decorator = _patch_dict(self.in_dict, self.values, self.clear)
1579                decorated = decorator(attr_value)
1580                setattr(klass, attr, decorated)
1581        return klass
1582
1583
1584    def __enter__(self):
1585        """Patch the dict."""
1586        self._patch_dict()
1587
1588
1589    def _patch_dict(self):
1590        values = self.values
1591        in_dict = self.in_dict
1592        clear = self.clear
1593
1594        try:
1595            original = in_dict.copy()
1596        except AttributeError:
1597            # dict like object with no copy method
1598            # must support iteration over keys
1599            original = {}
1600            for key in in_dict:
1601                original[key] = in_dict[key]
1602        self._original = original
1603
1604        if clear:
1605            _clear_dict(in_dict)
1606
1607        try:
1608            in_dict.update(values)
1609        except AttributeError:
1610            # dict like object with no update method
1611            for key in values:
1612                in_dict[key] = values[key]
1613
1614
1615    def _unpatch_dict(self):
1616        in_dict = self.in_dict
1617        original = self._original
1618
1619        _clear_dict(in_dict)
1620
1621        try:
1622            in_dict.update(original)
1623        except AttributeError:
1624            for key in original:
1625                in_dict[key] = original[key]
1626
1627
1628    def __exit__(self, *args):
1629        """Unpatch the dict."""
1630        self._unpatch_dict()
1631        return False
1632
1633    start = __enter__
1634    stop = __exit__
1635
1636
1637def _clear_dict(in_dict):
1638    try:
1639        in_dict.clear()
1640    except AttributeError:
1641        keys = list(in_dict)
1642        for key in keys:
1643            del in_dict[key]
1644
1645
1646def _patch_stopall():
1647    """Stop all active patches. LIFO to unroll nested patches."""
1648    for patch in reversed(_patch._active_patches):
1649        patch.stop()
1650
1651
1652patch.object = _patch_object
1653patch.dict = _patch_dict
1654patch.multiple = _patch_multiple
1655patch.stopall = _patch_stopall
1656patch.TEST_PREFIX = 'test'
1657
1658magic_methods = (
1659    "lt le gt ge eq ne "
1660    "getitem setitem delitem "
1661    "len contains iter "
1662    "hash str sizeof "
1663    "enter exit "
1664    "divmod neg pos abs invert "
1665    "complex int float index "
1666    "trunc floor ceil "
1667    "bool next "
1668)
1669
1670numerics = (
1671    "add sub mul div floordiv mod lshift rshift and xor or pow truediv"
1672)
1673inplace = ' '.join('i%s' % n for n in numerics.split())
1674right = ' '.join('r%s' % n for n in numerics.split())
1675
1676# not including __prepare__, __instancecheck__, __subclasscheck__
1677# (as they are metaclass methods)
1678# __del__ is not supported at all as it causes problems if it exists
1679
1680_non_defaults = set('__%s__' % method for method in [
1681    'get', 'set', 'delete', 'reversed', 'missing', 'reduce', 'reduce_ex',
1682    'getinitargs', 'getnewargs', 'getstate', 'setstate', 'getformat',
1683    'setformat', 'repr', 'dir', 'subclasses', 'format',
1684])
1685
1686
1687def _get_method(name, func):
1688    "Turns a callable object (like a mock) into a real function"
1689    def method(self, *args, **kw):
1690        return func(self, *args, **kw)
1691    method.__name__ = name
1692    return method
1693
1694
1695_magics = set(
1696    '__%s__' % method for method in
1697    ' '.join([magic_methods, numerics, inplace, right]).split()
1698)
1699
1700_all_magics = _magics | _non_defaults
1701
1702_unsupported_magics = set([
1703    '__getattr__', '__setattr__',
1704    '__init__', '__new__', '__prepare__'
1705    '__instancecheck__', '__subclasscheck__',
1706    '__del__'
1707])
1708
1709_calculate_return_value = {
1710    '__hash__': lambda self: object.__hash__(self),
1711    '__str__': lambda self: object.__str__(self),
1712    '__sizeof__': lambda self: object.__sizeof__(self),
1713}
1714
1715_return_values = {
1716    '__lt__': NotImplemented,
1717    '__gt__': NotImplemented,
1718    '__le__': NotImplemented,
1719    '__ge__': NotImplemented,
1720    '__int__': 1,
1721    '__contains__': False,
1722    '__len__': 0,
1723    '__exit__': False,
1724    '__complex__': 1j,
1725    '__float__': 1.0,
1726    '__bool__': True,
1727    '__index__': 1,
1728}
1729
1730
1731def _get_eq(self):
1732    def __eq__(other):
1733        ret_val = self.__eq__._mock_return_value
1734        if ret_val is not DEFAULT:
1735            return ret_val
1736        return self is other
1737    return __eq__
1738
1739def _get_ne(self):
1740    def __ne__(other):
1741        if self.__ne__._mock_return_value is not DEFAULT:
1742            return DEFAULT
1743        return self is not other
1744    return __ne__
1745
1746def _get_iter(self):
1747    def __iter__():
1748        ret_val = self.__iter__._mock_return_value
1749        if ret_val is DEFAULT:
1750            return iter([])
1751        # if ret_val was already an iterator, then calling iter on it should
1752        # return the iterator unchanged
1753        return iter(ret_val)
1754    return __iter__
1755
1756_side_effect_methods = {
1757    '__eq__': _get_eq,
1758    '__ne__': _get_ne,
1759    '__iter__': _get_iter,
1760}
1761
1762
1763
1764def _set_return_value(mock, method, name):
1765    fixed = _return_values.get(name, DEFAULT)
1766    if fixed is not DEFAULT:
1767        method.return_value = fixed
1768        return
1769
1770    return_calulator = _calculate_return_value.get(name)
1771    if return_calulator is not None:
1772        try:
1773            return_value = return_calulator(mock)
1774        except AttributeError:
1775            # XXXX why do we return AttributeError here?
1776            #      set it as a side_effect instead?
1777            return_value = AttributeError(name)
1778        method.return_value = return_value
1779        return
1780
1781    side_effector = _side_effect_methods.get(name)
1782    if side_effector is not None:
1783        method.side_effect = side_effector(mock)
1784
1785
1786
1787class MagicMixin(object):
1788    def __init__(self, *args, **kw):
1789        _safe_super(MagicMixin, self).__init__(*args, **kw)
1790        self._mock_set_magics()
1791
1792
1793    def _mock_set_magics(self):
1794        these_magics = _magics
1795
1796        if self._mock_methods is not None:
1797            these_magics = _magics.intersection(self._mock_methods)
1798
1799            remove_magics = set()
1800            remove_magics = _magics - these_magics
1801
1802            for entry in remove_magics:
1803                if entry in type(self).__dict__:
1804                    # remove unneeded magic methods
1805                    delattr(self, entry)
1806
1807        # don't overwrite existing attributes if called a second time
1808        these_magics = these_magics - set(type(self).__dict__)
1809
1810        _type = type(self)
1811        for entry in these_magics:
1812            setattr(_type, entry, MagicProxy(entry, self))
1813
1814
1815
1816class NonCallableMagicMock(MagicMixin, NonCallableMock):
1817    """A version of `MagicMock` that isn't callable."""
1818    def mock_add_spec(self, spec, spec_set=False):
1819        """Add a spec to a mock. `spec` can either be an object or a
1820        list of strings. Only attributes on the `spec` can be fetched as
1821        attributes from the mock.
1822
1823        If `spec_set` is True then only attributes on the spec can be set."""
1824        self._mock_add_spec(spec, spec_set)
1825        self._mock_set_magics()
1826
1827
1828
1829class MagicMock(MagicMixin, Mock):
1830    """
1831    MagicMock is a subclass of Mock with default implementations
1832    of most of the magic methods. You can use MagicMock without having to
1833    configure the magic methods yourself.
1834
1835    If you use the `spec` or `spec_set` arguments then *only* magic
1836    methods that exist in the spec will be created.
1837
1838    Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
1839    """
1840    def mock_add_spec(self, spec, spec_set=False):
1841        """Add a spec to a mock. `spec` can either be an object or a
1842        list of strings. Only attributes on the `spec` can be fetched as
1843        attributes from the mock.
1844
1845        If `spec_set` is True then only attributes on the spec can be set."""
1846        self._mock_add_spec(spec, spec_set)
1847        self._mock_set_magics()
1848
1849
1850
1851class MagicProxy(object):
1852    def __init__(self, name, parent):
1853        self.name = name
1854        self.parent = parent
1855
1856    def __call__(self, *args, **kwargs):
1857        m = self.create_mock()
1858        return m(*args, **kwargs)
1859
1860    def create_mock(self):
1861        entry = self.name
1862        parent = self.parent
1863        m = parent._get_child_mock(name=entry, _new_name=entry,
1864                                   _new_parent=parent)
1865        setattr(parent, entry, m)
1866        _set_return_value(parent, m, entry)
1867        return m
1868
1869    def __get__(self, obj, _type=None):
1870        return self.create_mock()
1871
1872
1873
1874class _ANY(object):
1875    "A helper object that compares equal to everything."
1876
1877    __hash__ = object.__hash__
1878
1879    def __eq__(self, other):
1880        return True
1881
1882    def __ne__(self, other):
1883        return False
1884
1885    def __repr__(self):
1886        return '<ANY>'
1887
1888ANY = _ANY()
1889
1890
1891
1892def _format_call_signature(name, args, kwargs):
1893    message = '%s(%%s)' % name
1894    formatted_args = ''
1895    args_string = ', '.join([repr(arg) for arg in args])
1896    kwargs_string = ', '.join([
1897        '%s=%r' % (key, value) for key, value in sorted(kwargs.items())
1898    ])
1899    if args_string:
1900        formatted_args = args_string
1901    if kwargs_string:
1902        if formatted_args:
1903            formatted_args += ', '
1904        formatted_args += kwargs_string
1905
1906    return message % formatted_args
1907
1908
1909
1910class _Call(tuple):
1911    """
1912    A tuple for holding the results of a call to a mock, either in the form
1913    `(args, kwargs)` or `(name, args, kwargs)`.
1914
1915    If args or kwargs are empty then a call tuple will compare equal to
1916    a tuple without those values. This makes comparisons less verbose::
1917
1918        _Call(('name', (), {})) == ('name',)
1919        _Call(('name', (1,), {})) == ('name', (1,))
1920        _Call(((), {'a': 'b'})) == ({'a': 'b'},)
1921
1922    The `_Call` object provides a useful shortcut for comparing with call::
1923
1924        _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
1925        _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
1926
1927    If the _Call has no name then it will match any name.
1928    """
1929
1930    __hash__ = object.__hash__
1931
1932    def __new__(cls, value=(), name=None, parent=None, two=False,
1933                from_kall=True):
1934        name = ''
1935        args = ()
1936        kwargs = {}
1937        _len = len(value)
1938        if _len == 3:
1939            name, args, kwargs = value
1940        elif _len == 2:
1941            first, second = value
1942            if isinstance(first, str):
1943                name = first
1944                if isinstance(second, tuple):
1945                    args = second
1946                else:
1947                    kwargs = second
1948            else:
1949                args, kwargs = first, second
1950        elif _len == 1:
1951            value, = value
1952            if isinstance(value, str):
1953                name = value
1954            elif isinstance(value, tuple):
1955                args = value
1956            else:
1957                kwargs = value
1958
1959        if two:
1960            return tuple.__new__(cls, (args, kwargs))
1961
1962        return tuple.__new__(cls, (name, args, kwargs))
1963
1964
1965    def __init__(self, value=(), name=None, parent=None, two=False,
1966                 from_kall=True):
1967        self.name = name
1968        self.parent = parent
1969        self.from_kall = from_kall
1970
1971
1972    def __eq__(self, other):
1973        if other is ANY:
1974            return True
1975        try:
1976            len_other = len(other)
1977        except TypeError:
1978            return False
1979
1980        self_name = ''
1981        if len(self) == 2:
1982            self_args, self_kwargs = self
1983        else:
1984            self_name, self_args, self_kwargs = self
1985
1986        other_name = ''
1987        if len_other == 0:
1988            other_args, other_kwargs = (), {}
1989        elif len_other == 3:
1990            other_name, other_args, other_kwargs = other
1991        elif len_other == 1:
1992            value, = other
1993            if isinstance(value, tuple):
1994                other_args = value
1995                other_kwargs = {}
1996            elif isinstance(value, str):
1997                other_name = value
1998                other_args, other_kwargs = (), {}
1999            else:
2000                other_args = ()
2001                other_kwargs = value
2002        else:
2003            # len 2
2004            # could be (name, args) or (name, kwargs) or (args, kwargs)
2005            first, second = other
2006            if isinstance(first, str):
2007                other_name = first
2008                if isinstance(second, tuple):
2009                    other_args, other_kwargs = second, {}
2010                else:
2011                    other_args, other_kwargs = (), second
2012            else:
2013                other_args, other_kwargs = first, second
2014
2015        if self_name and other_name != self_name:
2016            return False
2017
2018        # this order is important for ANY to work!
2019        return (other_args, other_kwargs) == (self_args, self_kwargs)
2020
2021
2022    def __ne__(self, other):
2023        return not self.__eq__(other)
2024
2025
2026    def __call__(self, *args, **kwargs):
2027        if self.name is None:
2028            return _Call(('', args, kwargs), name='()')
2029
2030        name = self.name + '()'
2031        return _Call((self.name, args, kwargs), name=name, parent=self)
2032
2033
2034    def __getattr__(self, attr):
2035        if self.name is None:
2036            return _Call(name=attr, from_kall=False)
2037        name = '%s.%s' % (self.name, attr)
2038        return _Call(name=name, parent=self, from_kall=False)
2039
2040
2041    def count(self, *args, **kwargs):
2042        return self.__getattr__('count')(*args, **kwargs)
2043
2044    def index(self, *args, **kwargs):
2045        return self.__getattr__('index')(*args, **kwargs)
2046
2047    def __repr__(self):
2048        if not self.from_kall:
2049            name = self.name or 'call'
2050            if name.startswith('()'):
2051                name = 'call%s' % name
2052            return name
2053
2054        if len(self) == 2:
2055            name = 'call'
2056            args, kwargs = self
2057        else:
2058            name, args, kwargs = self
2059            if not name:
2060                name = 'call'
2061            elif not name.startswith('()'):
2062                name = 'call.%s' % name
2063            else:
2064                name = 'call%s' % name
2065        return _format_call_signature(name, args, kwargs)
2066
2067
2068    def call_list(self):
2069        """For a call object that represents multiple calls, `call_list`
2070        returns a list of all the intermediate calls as well as the
2071        final call."""
2072        vals = []
2073        thing = self
2074        while thing is not None:
2075            if thing.from_kall:
2076                vals.append(thing)
2077            thing = thing.parent
2078        return _CallList(reversed(vals))
2079
2080
2081call = _Call(from_kall=False)
2082
2083
2084
2085def create_autospec(spec, spec_set=False, instance=False, _parent=None,
2086                    _name=None, **kwargs):
2087    """Create a mock object using another object as a spec. Attributes on the
2088    mock will use the corresponding attribute on the `spec` object as their
2089    spec.
2090
2091    Functions or methods being mocked will have their arguments checked
2092    to check that they are called with the correct signature.
2093
2094    If `spec_set` is True then attempting to set attributes that don't exist
2095    on the spec object will raise an `AttributeError`.
2096
2097    If a class is used as a spec then the return value of the mock (the
2098    instance of the class) will have the same spec. You can use a class as the
2099    spec for an instance object by passing `instance=True`. The returned mock
2100    will only be callable if instances of the mock are callable.
2101
2102    `create_autospec` also takes arbitrary keyword arguments that are passed to
2103    the constructor of the created mock."""
2104    if _is_list(spec):
2105        # can't pass a list instance to the mock constructor as it will be
2106        # interpreted as a list of strings
2107        spec = type(spec)
2108
2109    is_type = isinstance(spec, type)
2110
2111    _kwargs = {'spec': spec}
2112    if spec_set:
2113        _kwargs = {'spec_set': spec}
2114    elif spec is None:
2115        # None we mock with a normal mock without a spec
2116        _kwargs = {}
2117    if _kwargs and instance:
2118        _kwargs['_spec_as_instance'] = True
2119
2120    _kwargs.update(kwargs)
2121
2122    Klass = MagicMock
2123    if type(spec) in DescriptorTypes:
2124        # descriptors don't have a spec
2125        # because we don't know what type they return
2126        _kwargs = {}
2127    elif not _callable(spec):
2128        Klass = NonCallableMagicMock
2129    elif is_type and instance and not _instance_callable(spec):
2130        Klass = NonCallableMagicMock
2131
2132    _name = _kwargs.pop('name', _name)
2133
2134    _new_name = _name
2135    if _parent is None:
2136        # for a top level object no _new_name should be set
2137        _new_name = ''
2138
2139    mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
2140                 name=_name, **_kwargs)
2141
2142    if isinstance(spec, FunctionTypes):
2143        # should only happen at the top level because we don't
2144        # recurse for functions
2145        mock = _set_signature(mock, spec)
2146    else:
2147        _check_signature(spec, mock, is_type, instance)
2148
2149    if _parent is not None and not instance:
2150        _parent._mock_children[_name] = mock
2151
2152    if is_type and not instance and 'return_value' not in kwargs:
2153        mock.return_value = create_autospec(spec, spec_set, instance=True,
2154                                            _name='()', _parent=mock)
2155
2156    for entry in dir(spec):
2157        if _is_magic(entry):
2158            # MagicMock already does the useful magic methods for us
2159            continue
2160
2161        # XXXX do we need a better way of getting attributes without
2162        # triggering code execution (?) Probably not - we need the actual
2163        # object to mock it so we would rather trigger a property than mock
2164        # the property descriptor. Likewise we want to mock out dynamically
2165        # provided attributes.
2166        # XXXX what about attributes that raise exceptions other than
2167        # AttributeError on being fetched?
2168        # we could be resilient against it, or catch and propagate the
2169        # exception when the attribute is fetched from the mock
2170        try:
2171            original = getattr(spec, entry)
2172        except AttributeError:
2173            continue
2174
2175        kwargs = {'spec': original}
2176        if spec_set:
2177            kwargs = {'spec_set': original}
2178
2179        if not isinstance(original, FunctionTypes):
2180            new = _SpecState(original, spec_set, mock, entry, instance)
2181            mock._mock_children[entry] = new
2182        else:
2183            parent = mock
2184            if isinstance(spec, FunctionTypes):
2185                parent = mock.mock
2186
2187            skipfirst = _must_skip(spec, entry, is_type)
2188            kwargs['_eat_self'] = skipfirst
2189            new = MagicMock(parent=parent, name=entry, _new_name=entry,
2190                            _new_parent=parent,
2191                            **kwargs)
2192            mock._mock_children[entry] = new
2193            _check_signature(original, new, skipfirst=skipfirst)
2194
2195        # so functions created with _set_signature become instance attributes,
2196        # *plus* their underlying mock exists in _mock_children of the parent
2197        # mock. Adding to _mock_children may be unnecessary where we are also
2198        # setting as an instance attribute?
2199        if isinstance(new, FunctionTypes):
2200            setattr(mock, entry, new)
2201
2202    return mock
2203
2204
2205def _must_skip(spec, entry, is_type):
2206    """
2207    Return whether we should skip the first argument on spec's `entry`
2208    attribute.
2209    """
2210    if not isinstance(spec, type):
2211        if entry in getattr(spec, '__dict__', {}):
2212            # instance attribute - shouldn't skip
2213            return False
2214        spec = spec.__class__
2215
2216    for klass in spec.__mro__:
2217        result = klass.__dict__.get(entry, DEFAULT)
2218        if result is DEFAULT:
2219            continue
2220        if isinstance(result, (staticmethod, classmethod)):
2221            return False
2222        elif isinstance(getattr(result, '__get__', None), MethodWrapperTypes):
2223            # Normal method => skip if looked up on type
2224            # (if looked up on instance, self is already skipped)
2225            return is_type
2226        else:
2227            return False
2228
2229    # shouldn't get here unless function is a dynamically provided attribute
2230    # XXXX untested behaviour
2231    return is_type
2232
2233
2234def _get_class(obj):
2235    try:
2236        return obj.__class__
2237    except AttributeError:
2238        # it is possible for objects to have no __class__
2239        return type(obj)
2240
2241
2242class _SpecState(object):
2243
2244    def __init__(self, spec, spec_set=False, parent=None,
2245                 name=None, ids=None, instance=False):
2246        self.spec = spec
2247        self.ids = ids
2248        self.spec_set = spec_set
2249        self.parent = parent
2250        self.instance = instance
2251        self.name = name
2252
2253
2254FunctionTypes = (
2255    # python function
2256    type(create_autospec),
2257    # instance method
2258    type(ANY.__eq__),
2259)
2260
2261MethodWrapperTypes = (
2262    type(ANY.__eq__.__get__),
2263)
2264
2265
2266file_spec = None
2267
2268def _iterate_read_data(read_data):
2269    # Helper for mock_open:
2270    # Retrieve lines from read_data via a generator so that separate calls to
2271    # readline, read, and readlines are properly interleaved
2272    data_as_list = ['{}\n'.format(l) for l in read_data.split('\n')]
2273
2274    if data_as_list[-1] == '\n':
2275        # If the last line ended in a newline, the list comprehension will have an
2276        # extra entry that's just a newline.  Remove this.
2277        data_as_list = data_as_list[:-1]
2278    else:
2279        # If there wasn't an extra newline by itself, then the file being
2280        # emulated doesn't have a newline to end the last line  remove the
2281        # newline that our naive format() added
2282        data_as_list[-1] = data_as_list[-1][:-1]
2283
2284    for line in data_as_list:
2285        yield line
2286
2287def mock_open(mock=None, read_data=''):
2288    """
2289    A helper function to create a mock to replace the use of `open`. It works
2290    for `open` called directly or used as a context manager.
2291
2292    The `mock` argument is the mock object to configure. If `None` (the
2293    default) then a `MagicMock` will be created for you, with the API limited
2294    to methods or attributes available on standard file handles.
2295
2296    `read_data` is a string for the `read` methoddline`, and `readlines` of the
2297    file handle to return.  This is an empty string by default.
2298    """
2299    def _readlines_side_effect(*args, **kwargs):
2300        if handle.readlines.return_value is not None:
2301            return handle.readlines.return_value
2302        return list(_data)
2303
2304    def _read_side_effect(*args, **kwargs):
2305        if handle.read.return_value is not None:
2306            return handle.read.return_value
2307        return ''.join(_data)
2308
2309    def _readline_side_effect():
2310        if handle.readline.return_value is not None:
2311            while True:
2312                yield handle.readline.return_value
2313        for line in _data:
2314            yield line
2315
2316
2317    global file_spec
2318    if file_spec is None:
2319        import _io
2320        file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
2321
2322    if mock is None:
2323        mock = MagicMock(name='open', spec=open)
2324
2325    handle = MagicMock(spec=file_spec)
2326    handle.__enter__.return_value = handle
2327
2328    _data = _iterate_read_data(read_data)
2329
2330    handle.write.return_value = None
2331    handle.read.return_value = None
2332    handle.readline.return_value = None
2333    handle.readlines.return_value = None
2334
2335    handle.read.side_effect = _read_side_effect
2336    handle.readline.side_effect = _readline_side_effect()
2337    handle.readlines.side_effect = _readlines_side_effect
2338
2339    mock.return_value = handle
2340    return mock
2341
2342
2343class PropertyMock(Mock):
2344    """
2345    A mock intended to be used as a property, or other descriptor, on a class.
2346    `PropertyMock` provides `__get__` and `__set__` methods so you can specify
2347    a return value when it is fetched.
2348
2349    Fetching a `PropertyMock` instance from an object calls the mock, with
2350    no args. Setting it calls the mock with the value being set.
2351    """
2352    def _get_child_mock(self, **kwargs):
2353        return MagicMock(**kwargs)
2354
2355    def __get__(self, obj, obj_type):
2356        return self()
2357    def __set__(self, obj, val):
2358        self(val)
2359