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