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