python/mock-1.0.0/mock.py

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/python/mock-1.0.0/mock.py	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,2356 @@
     1.4 +# mock.py
     1.5 +# Test tools for mocking and patching.
     1.6 +# Copyright (C) 2007-2012 Michael Foord & the mock team
     1.7 +# E-mail: fuzzyman AT voidspace DOT org DOT uk
     1.8 +
     1.9 +# mock 1.0
    1.10 +# http://www.voidspace.org.uk/python/mock/
    1.11 +
    1.12 +# Released subject to the BSD License
    1.13 +# Please see http://www.voidspace.org.uk/python/license.shtml
    1.14 +
    1.15 +# Scripts maintained at http://www.voidspace.org.uk/python/index.shtml
    1.16 +# Comments, suggestions and bug reports welcome.
    1.17 +
    1.18 +
    1.19 +__all__ = (
    1.20 +    'Mock',
    1.21 +    'MagicMock',
    1.22 +    'patch',
    1.23 +    'sentinel',
    1.24 +    'DEFAULT',
    1.25 +    'ANY',
    1.26 +    'call',
    1.27 +    'create_autospec',
    1.28 +    'FILTER_DIR',
    1.29 +    'NonCallableMock',
    1.30 +    'NonCallableMagicMock',
    1.31 +    'mock_open',
    1.32 +    'PropertyMock',
    1.33 +)
    1.34 +
    1.35 +
    1.36 +__version__ = '1.0.0'
    1.37 +
    1.38 +
    1.39 +import pprint
    1.40 +import sys
    1.41 +
    1.42 +try:
    1.43 +    import inspect
    1.44 +except ImportError:
    1.45 +    # for alternative platforms that
    1.46 +    # may not have inspect
    1.47 +    inspect = None
    1.48 +
    1.49 +try:
    1.50 +    from functools import wraps
    1.51 +except ImportError:
    1.52 +    # Python 2.4 compatibility
    1.53 +    def wraps(original):
    1.54 +        def inner(f):
    1.55 +            f.__name__ = original.__name__
    1.56 +            f.__doc__ = original.__doc__
    1.57 +            f.__module__ = original.__module__
    1.58 +            return f
    1.59 +        return inner
    1.60 +
    1.61 +try:
    1.62 +    unicode
    1.63 +except NameError:
    1.64 +    # Python 3
    1.65 +    basestring = unicode = str
    1.66 +
    1.67 +try:
    1.68 +    long
    1.69 +except NameError:
    1.70 +    # Python 3
    1.71 +    long = int
    1.72 +
    1.73 +try:
    1.74 +    BaseException
    1.75 +except NameError:
    1.76 +    # Python 2.4 compatibility
    1.77 +    BaseException = Exception
    1.78 +
    1.79 +try:
    1.80 +    next
    1.81 +except NameError:
    1.82 +    def next(obj):
    1.83 +        return obj.next()
    1.84 +
    1.85 +
    1.86 +BaseExceptions = (BaseException,)
    1.87 +if 'java' in sys.platform:
    1.88 +    # jython
    1.89 +    import java
    1.90 +    BaseExceptions = (BaseException, java.lang.Throwable)
    1.91 +
    1.92 +try:
    1.93 +    _isidentifier = str.isidentifier
    1.94 +except AttributeError:
    1.95 +    # Python 2.X
    1.96 +    import keyword
    1.97 +    import re
    1.98 +    regex = re.compile(r'^[a-z_][a-z0-9_]*$', re.I)
    1.99 +    def _isidentifier(string):
   1.100 +        if string in keyword.kwlist:
   1.101 +            return False
   1.102 +        return regex.match(string)
   1.103 +
   1.104 +
   1.105 +inPy3k = sys.version_info[0] == 3
   1.106 +
   1.107 +# Needed to work around Python 3 bug where use of "super" interferes with
   1.108 +# defining __class__ as a descriptor
   1.109 +_super = super
   1.110 +
   1.111 +self = 'im_self'
   1.112 +builtin = '__builtin__'
   1.113 +if inPy3k:
   1.114 +    self = '__self__'
   1.115 +    builtin = 'builtins'
   1.116 +
   1.117 +FILTER_DIR = True
   1.118 +
   1.119 +
   1.120 +def _is_instance_mock(obj):
   1.121 +    # can't use isinstance on Mock objects because they override __class__
   1.122 +    # The base class for all mocks is NonCallableMock
   1.123 +    return issubclass(type(obj), NonCallableMock)
   1.124 +
   1.125 +
   1.126 +def _is_exception(obj):
   1.127 +    return (
   1.128 +        isinstance(obj, BaseExceptions) or
   1.129 +        isinstance(obj, ClassTypes) and issubclass(obj, BaseExceptions)
   1.130 +    )
   1.131 +
   1.132 +
   1.133 +class _slotted(object):
   1.134 +    __slots__ = ['a']
   1.135 +
   1.136 +
   1.137 +DescriptorTypes = (
   1.138 +    type(_slotted.a),
   1.139 +    property,
   1.140 +)
   1.141 +
   1.142 +
   1.143 +def _getsignature(func, skipfirst, instance=False):
   1.144 +    if inspect is None:
   1.145 +        raise ImportError('inspect module not available')
   1.146 +
   1.147 +    if isinstance(func, ClassTypes) and not instance:
   1.148 +        try:
   1.149 +            func = func.__init__
   1.150 +        except AttributeError:
   1.151 +            return
   1.152 +        skipfirst = True
   1.153 +    elif not isinstance(func, FunctionTypes):
   1.154 +        # for classes where instance is True we end up here too
   1.155 +        try:
   1.156 +            func = func.__call__
   1.157 +        except AttributeError:
   1.158 +            return
   1.159 +
   1.160 +    if inPy3k:
   1.161 +        try:
   1.162 +            argspec = inspect.getfullargspec(func)
   1.163 +        except TypeError:
   1.164 +            # C function / method, possibly inherited object().__init__
   1.165 +            return
   1.166 +        regargs, varargs, varkw, defaults, kwonly, kwonlydef, ann = argspec
   1.167 +    else:
   1.168 +        try:
   1.169 +            regargs, varargs, varkwargs, defaults = inspect.getargspec(func)
   1.170 +        except TypeError:
   1.171 +            # C function / method, possibly inherited object().__init__
   1.172 +            return
   1.173 +
   1.174 +    # instance methods and classmethods need to lose the self argument
   1.175 +    if getattr(func, self, None) is not None:
   1.176 +        regargs = regargs[1:]
   1.177 +    if skipfirst:
   1.178 +        # this condition and the above one are never both True - why?
   1.179 +        regargs = regargs[1:]
   1.180 +
   1.181 +    if inPy3k:
   1.182 +        signature = inspect.formatargspec(
   1.183 +            regargs, varargs, varkw, defaults,
   1.184 +            kwonly, kwonlydef, ann, formatvalue=lambda value: "")
   1.185 +    else:
   1.186 +        signature = inspect.formatargspec(
   1.187 +            regargs, varargs, varkwargs, defaults,
   1.188 +            formatvalue=lambda value: "")
   1.189 +    return signature[1:-1], func
   1.190 +
   1.191 +
   1.192 +def _check_signature(func, mock, skipfirst, instance=False):
   1.193 +    if not _callable(func):
   1.194 +        return
   1.195 +
   1.196 +    result = _getsignature(func, skipfirst, instance)
   1.197 +    if result is None:
   1.198 +        return
   1.199 +    signature, func = result
   1.200 +
   1.201 +    # can't use self because "self" is common as an argument name
   1.202 +    # unfortunately even not in the first place
   1.203 +    src = "lambda _mock_self, %s: None" % signature
   1.204 +    checksig = eval(src, {})
   1.205 +    _copy_func_details(func, checksig)
   1.206 +    type(mock)._mock_check_sig = checksig
   1.207 +
   1.208 +
   1.209 +def _copy_func_details(func, funcopy):
   1.210 +    funcopy.__name__ = func.__name__
   1.211 +    funcopy.__doc__ = func.__doc__
   1.212 +    #funcopy.__dict__.update(func.__dict__)
   1.213 +    funcopy.__module__ = func.__module__
   1.214 +    if not inPy3k:
   1.215 +        funcopy.func_defaults = func.func_defaults
   1.216 +        return
   1.217 +    funcopy.__defaults__ = func.__defaults__
   1.218 +    funcopy.__kwdefaults__ = func.__kwdefaults__
   1.219 +
   1.220 +
   1.221 +def _callable(obj):
   1.222 +    if isinstance(obj, ClassTypes):
   1.223 +        return True
   1.224 +    if getattr(obj, '__call__', None) is not None:
   1.225 +        return True
   1.226 +    return False
   1.227 +
   1.228 +
   1.229 +def _is_list(obj):
   1.230 +    # checks for list or tuples
   1.231 +    # XXXX badly named!
   1.232 +    return type(obj) in (list, tuple)
   1.233 +
   1.234 +
   1.235 +def _instance_callable(obj):
   1.236 +    """Given an object, return True if the object is callable.
   1.237 +    For classes, return True if instances would be callable."""
   1.238 +    if not isinstance(obj, ClassTypes):
   1.239 +        # already an instance
   1.240 +        return getattr(obj, '__call__', None) is not None
   1.241 +
   1.242 +    klass = obj
   1.243 +    # uses __bases__ instead of __mro__ so that we work with old style classes
   1.244 +    if klass.__dict__.get('__call__') is not None:
   1.245 +        return True
   1.246 +
   1.247 +    for base in klass.__bases__:
   1.248 +        if _instance_callable(base):
   1.249 +            return True
   1.250 +    return False
   1.251 +
   1.252 +
   1.253 +def _set_signature(mock, original, instance=False):
   1.254 +    # creates a function with signature (*args, **kwargs) that delegates to a
   1.255 +    # mock. It still does signature checking by calling a lambda with the same
   1.256 +    # signature as the original.
   1.257 +    if not _callable(original):
   1.258 +        return
   1.259 +
   1.260 +    skipfirst = isinstance(original, ClassTypes)
   1.261 +    result = _getsignature(original, skipfirst, instance)
   1.262 +    if result is None:
   1.263 +        # was a C function (e.g. object().__init__ ) that can't be mocked
   1.264 +        return
   1.265 +
   1.266 +    signature, func = result
   1.267 +
   1.268 +    src = "lambda %s: None" % signature
   1.269 +    checksig = eval(src, {})
   1.270 +    _copy_func_details(func, checksig)
   1.271 +
   1.272 +    name = original.__name__
   1.273 +    if not _isidentifier(name):
   1.274 +        name = 'funcopy'
   1.275 +    context = {'_checksig_': checksig, 'mock': mock}
   1.276 +    src = """def %s(*args, **kwargs):
   1.277 +    _checksig_(*args, **kwargs)
   1.278 +    return mock(*args, **kwargs)""" % name
   1.279 +    exec (src, context)
   1.280 +    funcopy = context[name]
   1.281 +    _setup_func(funcopy, mock)
   1.282 +    return funcopy
   1.283 +
   1.284 +
   1.285 +def _setup_func(funcopy, mock):
   1.286 +    funcopy.mock = mock
   1.287 +
   1.288 +    # can't use isinstance with mocks
   1.289 +    if not _is_instance_mock(mock):
   1.290 +        return
   1.291 +
   1.292 +    def assert_called_with(*args, **kwargs):
   1.293 +        return mock.assert_called_with(*args, **kwargs)
   1.294 +    def assert_called_once_with(*args, **kwargs):
   1.295 +        return mock.assert_called_once_with(*args, **kwargs)
   1.296 +    def assert_has_calls(*args, **kwargs):
   1.297 +        return mock.assert_has_calls(*args, **kwargs)
   1.298 +    def assert_any_call(*args, **kwargs):
   1.299 +        return mock.assert_any_call(*args, **kwargs)
   1.300 +    def reset_mock():
   1.301 +        funcopy.method_calls = _CallList()
   1.302 +        funcopy.mock_calls = _CallList()
   1.303 +        mock.reset_mock()
   1.304 +        ret = funcopy.return_value
   1.305 +        if _is_instance_mock(ret) and not ret is mock:
   1.306 +            ret.reset_mock()
   1.307 +
   1.308 +    funcopy.called = False
   1.309 +    funcopy.call_count = 0
   1.310 +    funcopy.call_args = None
   1.311 +    funcopy.call_args_list = _CallList()
   1.312 +    funcopy.method_calls = _CallList()
   1.313 +    funcopy.mock_calls = _CallList()
   1.314 +
   1.315 +    funcopy.return_value = mock.return_value
   1.316 +    funcopy.side_effect = mock.side_effect
   1.317 +    funcopy._mock_children = mock._mock_children
   1.318 +
   1.319 +    funcopy.assert_called_with = assert_called_with
   1.320 +    funcopy.assert_called_once_with = assert_called_once_with
   1.321 +    funcopy.assert_has_calls = assert_has_calls
   1.322 +    funcopy.assert_any_call = assert_any_call
   1.323 +    funcopy.reset_mock = reset_mock
   1.324 +
   1.325 +    mock._mock_delegate = funcopy
   1.326 +
   1.327 +
   1.328 +def _is_magic(name):
   1.329 +    return '__%s__' % name[2:-2] == name
   1.330 +
   1.331 +
   1.332 +class _SentinelObject(object):
   1.333 +    "A unique, named, sentinel object."
   1.334 +    def __init__(self, name):
   1.335 +        self.name = name
   1.336 +
   1.337 +    def __repr__(self):
   1.338 +        return 'sentinel.%s' % self.name
   1.339 +
   1.340 +
   1.341 +class _Sentinel(object):
   1.342 +    """Access attributes to return a named object, usable as a sentinel."""
   1.343 +    def __init__(self):
   1.344 +        self._sentinels = {}
   1.345 +
   1.346 +    def __getattr__(self, name):
   1.347 +        if name == '__bases__':
   1.348 +            # Without this help(mock) raises an exception
   1.349 +            raise AttributeError
   1.350 +        return self._sentinels.setdefault(name, _SentinelObject(name))
   1.351 +
   1.352 +
   1.353 +sentinel = _Sentinel()
   1.354 +
   1.355 +DEFAULT = sentinel.DEFAULT
   1.356 +_missing = sentinel.MISSING
   1.357 +_deleted = sentinel.DELETED
   1.358 +
   1.359 +
   1.360 +class OldStyleClass:
   1.361 +    pass
   1.362 +ClassType = type(OldStyleClass)
   1.363 +
   1.364 +
   1.365 +def _copy(value):
   1.366 +    if type(value) in (dict, list, tuple, set):
   1.367 +        return type(value)(value)
   1.368 +    return value
   1.369 +
   1.370 +
   1.371 +ClassTypes = (type,)
   1.372 +if not inPy3k:
   1.373 +    ClassTypes = (type, ClassType)
   1.374 +
   1.375 +_allowed_names = set(
   1.376 +    [
   1.377 +        'return_value', '_mock_return_value', 'side_effect',
   1.378 +        '_mock_side_effect', '_mock_parent', '_mock_new_parent',
   1.379 +        '_mock_name', '_mock_new_name'
   1.380 +    ]
   1.381 +)
   1.382 +
   1.383 +
   1.384 +def _delegating_property(name):
   1.385 +    _allowed_names.add(name)
   1.386 +    _the_name = '_mock_' + name
   1.387 +    def _get(self, name=name, _the_name=_the_name):
   1.388 +        sig = self._mock_delegate
   1.389 +        if sig is None:
   1.390 +            return getattr(self, _the_name)
   1.391 +        return getattr(sig, name)
   1.392 +    def _set(self, value, name=name, _the_name=_the_name):
   1.393 +        sig = self._mock_delegate
   1.394 +        if sig is None:
   1.395 +            self.__dict__[_the_name] = value
   1.396 +        else:
   1.397 +            setattr(sig, name, value)
   1.398 +
   1.399 +    return property(_get, _set)
   1.400 +
   1.401 +
   1.402 +
   1.403 +class _CallList(list):
   1.404 +
   1.405 +    def __contains__(self, value):
   1.406 +        if not isinstance(value, list):
   1.407 +            return list.__contains__(self, value)
   1.408 +        len_value = len(value)
   1.409 +        len_self = len(self)
   1.410 +        if len_value > len_self:
   1.411 +            return False
   1.412 +
   1.413 +        for i in range(0, len_self - len_value + 1):
   1.414 +            sub_list = self[i:i+len_value]
   1.415 +            if sub_list == value:
   1.416 +                return True
   1.417 +        return False
   1.418 +
   1.419 +    def __repr__(self):
   1.420 +        return pprint.pformat(list(self))
   1.421 +
   1.422 +
   1.423 +def _check_and_set_parent(parent, value, name, new_name):
   1.424 +    if not _is_instance_mock(value):
   1.425 +        return False
   1.426 +    if ((value._mock_name or value._mock_new_name) or
   1.427 +        (value._mock_parent is not None) or
   1.428 +        (value._mock_new_parent is not None)):
   1.429 +        return False
   1.430 +
   1.431 +    _parent = parent
   1.432 +    while _parent is not None:
   1.433 +        # setting a mock (value) as a child or return value of itself
   1.434 +        # should not modify the mock
   1.435 +        if _parent is value:
   1.436 +            return False
   1.437 +        _parent = _parent._mock_new_parent
   1.438 +
   1.439 +    if new_name:
   1.440 +        value._mock_new_parent = parent
   1.441 +        value._mock_new_name = new_name
   1.442 +    if name:
   1.443 +        value._mock_parent = parent
   1.444 +        value._mock_name = name
   1.445 +    return True
   1.446 +
   1.447 +
   1.448 +
   1.449 +class Base(object):
   1.450 +    _mock_return_value = DEFAULT
   1.451 +    _mock_side_effect = None
   1.452 +    def __init__(self, *args, **kwargs):
   1.453 +        pass
   1.454 +
   1.455 +
   1.456 +
   1.457 +class NonCallableMock(Base):
   1.458 +    """A non-callable version of `Mock`"""
   1.459 +
   1.460 +    def __new__(cls, *args, **kw):
   1.461 +        # every instance has its own class
   1.462 +        # so we can create magic methods on the
   1.463 +        # class without stomping on other mocks
   1.464 +        new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
   1.465 +        instance = object.__new__(new)
   1.466 +        return instance
   1.467 +
   1.468 +
   1.469 +    def __init__(
   1.470 +            self, spec=None, wraps=None, name=None, spec_set=None,
   1.471 +            parent=None, _spec_state=None, _new_name='', _new_parent=None,
   1.472 +            **kwargs
   1.473 +        ):
   1.474 +        if _new_parent is None:
   1.475 +            _new_parent = parent
   1.476 +
   1.477 +        __dict__ = self.__dict__
   1.478 +        __dict__['_mock_parent'] = parent
   1.479 +        __dict__['_mock_name'] = name
   1.480 +        __dict__['_mock_new_name'] = _new_name
   1.481 +        __dict__['_mock_new_parent'] = _new_parent
   1.482 +
   1.483 +        if spec_set is not None:
   1.484 +            spec = spec_set
   1.485 +            spec_set = True
   1.486 +
   1.487 +        self._mock_add_spec(spec, spec_set)
   1.488 +
   1.489 +        __dict__['_mock_children'] = {}
   1.490 +        __dict__['_mock_wraps'] = wraps
   1.491 +        __dict__['_mock_delegate'] = None
   1.492 +
   1.493 +        __dict__['_mock_called'] = False
   1.494 +        __dict__['_mock_call_args'] = None
   1.495 +        __dict__['_mock_call_count'] = 0
   1.496 +        __dict__['_mock_call_args_list'] = _CallList()
   1.497 +        __dict__['_mock_mock_calls'] = _CallList()
   1.498 +
   1.499 +        __dict__['method_calls'] = _CallList()
   1.500 +
   1.501 +        if kwargs:
   1.502 +            self.configure_mock(**kwargs)
   1.503 +
   1.504 +        _super(NonCallableMock, self).__init__(
   1.505 +            spec, wraps, name, spec_set, parent,
   1.506 +            _spec_state
   1.507 +        )
   1.508 +
   1.509 +
   1.510 +    def attach_mock(self, mock, attribute):
   1.511 +        """
   1.512 +        Attach a mock as an attribute of this one, replacing its name and
   1.513 +        parent. Calls to the attached mock will be recorded in the
   1.514 +        `method_calls` and `mock_calls` attributes of this one."""
   1.515 +        mock._mock_parent = None
   1.516 +        mock._mock_new_parent = None
   1.517 +        mock._mock_name = ''
   1.518 +        mock._mock_new_name = None
   1.519 +
   1.520 +        setattr(self, attribute, mock)
   1.521 +
   1.522 +
   1.523 +    def mock_add_spec(self, spec, spec_set=False):
   1.524 +        """Add a spec to a mock. `spec` can either be an object or a
   1.525 +        list of strings. Only attributes on the `spec` can be fetched as
   1.526 +        attributes from the mock.
   1.527 +
   1.528 +        If `spec_set` is True then only attributes on the spec can be set."""
   1.529 +        self._mock_add_spec(spec, spec_set)
   1.530 +
   1.531 +
   1.532 +    def _mock_add_spec(self, spec, spec_set):
   1.533 +        _spec_class = None
   1.534 +
   1.535 +        if spec is not None and not _is_list(spec):
   1.536 +            if isinstance(spec, ClassTypes):
   1.537 +                _spec_class = spec
   1.538 +            else:
   1.539 +                _spec_class = _get_class(spec)
   1.540 +
   1.541 +            spec = dir(spec)
   1.542 +
   1.543 +        __dict__ = self.__dict__
   1.544 +        __dict__['_spec_class'] = _spec_class
   1.545 +        __dict__['_spec_set'] = spec_set
   1.546 +        __dict__['_mock_methods'] = spec
   1.547 +
   1.548 +
   1.549 +    def __get_return_value(self):
   1.550 +        ret = self._mock_return_value
   1.551 +        if self._mock_delegate is not None:
   1.552 +            ret = self._mock_delegate.return_value
   1.553 +
   1.554 +        if ret is DEFAULT:
   1.555 +            ret = self._get_child_mock(
   1.556 +                _new_parent=self, _new_name='()'
   1.557 +            )
   1.558 +            self.return_value = ret
   1.559 +        return ret
   1.560 +
   1.561 +
   1.562 +    def __set_return_value(self, value):
   1.563 +        if self._mock_delegate is not None:
   1.564 +            self._mock_delegate.return_value = value
   1.565 +        else:
   1.566 +            self._mock_return_value = value
   1.567 +            _check_and_set_parent(self, value, None, '()')
   1.568 +
   1.569 +    __return_value_doc = "The value to be returned when the mock is called."
   1.570 +    return_value = property(__get_return_value, __set_return_value,
   1.571 +                            __return_value_doc)
   1.572 +
   1.573 +
   1.574 +    @property
   1.575 +    def __class__(self):
   1.576 +        if self._spec_class is None:
   1.577 +            return type(self)
   1.578 +        return self._spec_class
   1.579 +
   1.580 +    called = _delegating_property('called')
   1.581 +    call_count = _delegating_property('call_count')
   1.582 +    call_args = _delegating_property('call_args')
   1.583 +    call_args_list = _delegating_property('call_args_list')
   1.584 +    mock_calls = _delegating_property('mock_calls')
   1.585 +
   1.586 +
   1.587 +    def __get_side_effect(self):
   1.588 +        sig = self._mock_delegate
   1.589 +        if sig is None:
   1.590 +            return self._mock_side_effect
   1.591 +        return sig.side_effect
   1.592 +
   1.593 +    def __set_side_effect(self, value):
   1.594 +        value = _try_iter(value)
   1.595 +        sig = self._mock_delegate
   1.596 +        if sig is None:
   1.597 +            self._mock_side_effect = value
   1.598 +        else:
   1.599 +            sig.side_effect = value
   1.600 +
   1.601 +    side_effect = property(__get_side_effect, __set_side_effect)
   1.602 +
   1.603 +
   1.604 +    def reset_mock(self):
   1.605 +        "Restore the mock object to its initial state."
   1.606 +        self.called = False
   1.607 +        self.call_args = None
   1.608 +        self.call_count = 0
   1.609 +        self.mock_calls = _CallList()
   1.610 +        self.call_args_list = _CallList()
   1.611 +        self.method_calls = _CallList()
   1.612 +
   1.613 +        for child in self._mock_children.values():
   1.614 +            if isinstance(child, _SpecState):
   1.615 +                continue
   1.616 +            child.reset_mock()
   1.617 +
   1.618 +        ret = self._mock_return_value
   1.619 +        if _is_instance_mock(ret) and ret is not self:
   1.620 +            ret.reset_mock()
   1.621 +
   1.622 +
   1.623 +    def configure_mock(self, **kwargs):
   1.624 +        """Set attributes on the mock through keyword arguments.
   1.625 +
   1.626 +        Attributes plus return values and side effects can be set on child
   1.627 +        mocks using standard dot notation and unpacking a dictionary in the
   1.628 +        method call:
   1.629 +
   1.630 +        >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
   1.631 +        >>> mock.configure_mock(**attrs)"""
   1.632 +        for arg, val in sorted(kwargs.items(),
   1.633 +                               # we sort on the number of dots so that
   1.634 +                               # attributes are set before we set attributes on
   1.635 +                               # attributes
   1.636 +                               key=lambda entry: entry[0].count('.')):
   1.637 +            args = arg.split('.')
   1.638 +            final = args.pop()
   1.639 +            obj = self
   1.640 +            for entry in args:
   1.641 +                obj = getattr(obj, entry)
   1.642 +            setattr(obj, final, val)
   1.643 +
   1.644 +
   1.645 +    def __getattr__(self, name):
   1.646 +        if name == '_mock_methods':
   1.647 +            raise AttributeError(name)
   1.648 +        elif self._mock_methods is not None:
   1.649 +            if name not in self._mock_methods or name in _all_magics:
   1.650 +                raise AttributeError("Mock object has no attribute %r" % name)
   1.651 +        elif _is_magic(name):
   1.652 +            raise AttributeError(name)
   1.653 +
   1.654 +        result = self._mock_children.get(name)
   1.655 +        if result is _deleted:
   1.656 +            raise AttributeError(name)
   1.657 +        elif result is None:
   1.658 +            wraps = None
   1.659 +            if self._mock_wraps is not None:
   1.660 +                # XXXX should we get the attribute without triggering code
   1.661 +                # execution?
   1.662 +                wraps = getattr(self._mock_wraps, name)
   1.663 +
   1.664 +            result = self._get_child_mock(
   1.665 +                parent=self, name=name, wraps=wraps, _new_name=name,
   1.666 +                _new_parent=self
   1.667 +            )
   1.668 +            self._mock_children[name]  = result
   1.669 +
   1.670 +        elif isinstance(result, _SpecState):
   1.671 +            result = create_autospec(
   1.672 +                result.spec, result.spec_set, result.instance,
   1.673 +                result.parent, result.name
   1.674 +            )
   1.675 +            self._mock_children[name]  = result
   1.676 +
   1.677 +        return result
   1.678 +
   1.679 +
   1.680 +    def __repr__(self):
   1.681 +        _name_list = [self._mock_new_name]
   1.682 +        _parent = self._mock_new_parent
   1.683 +        last = self
   1.684 +
   1.685 +        dot = '.'
   1.686 +        if _name_list == ['()']:
   1.687 +            dot = ''
   1.688 +        seen = set()
   1.689 +        while _parent is not None:
   1.690 +            last = _parent
   1.691 +
   1.692 +            _name_list.append(_parent._mock_new_name + dot)
   1.693 +            dot = '.'
   1.694 +            if _parent._mock_new_name == '()':
   1.695 +                dot = ''
   1.696 +
   1.697 +            _parent = _parent._mock_new_parent
   1.698 +
   1.699 +            # use ids here so as not to call __hash__ on the mocks
   1.700 +            if id(_parent) in seen:
   1.701 +                break
   1.702 +            seen.add(id(_parent))
   1.703 +
   1.704 +        _name_list = list(reversed(_name_list))
   1.705 +        _first = last._mock_name or 'mock'
   1.706 +        if len(_name_list) > 1:
   1.707 +            if _name_list[1] not in ('()', '().'):
   1.708 +                _first += '.'
   1.709 +        _name_list[0] = _first
   1.710 +        name = ''.join(_name_list)
   1.711 +
   1.712 +        name_string = ''
   1.713 +        if name not in ('mock', 'mock.'):
   1.714 +            name_string = ' name=%r' % name
   1.715 +
   1.716 +        spec_string = ''
   1.717 +        if self._spec_class is not None:
   1.718 +            spec_string = ' spec=%r'
   1.719 +            if self._spec_set:
   1.720 +                spec_string = ' spec_set=%r'
   1.721 +            spec_string = spec_string % self._spec_class.__name__
   1.722 +        return "<%s%s%s id='%s'>" % (
   1.723 +            type(self).__name__,
   1.724 +            name_string,
   1.725 +            spec_string,
   1.726 +            id(self)
   1.727 +        )
   1.728 +
   1.729 +
   1.730 +    def __dir__(self):
   1.731 +        """Filter the output of `dir(mock)` to only useful members.
   1.732 +        XXXX
   1.733 +        """
   1.734 +        extras = self._mock_methods or []
   1.735 +        from_type = dir(type(self))
   1.736 +        from_dict = list(self.__dict__)
   1.737 +
   1.738 +        if FILTER_DIR:
   1.739 +            from_type = [e for e in from_type if not e.startswith('_')]
   1.740 +            from_dict = [e for e in from_dict if not e.startswith('_') or
   1.741 +                         _is_magic(e)]
   1.742 +        return sorted(set(extras + from_type + from_dict +
   1.743 +                          list(self._mock_children)))
   1.744 +
   1.745 +
   1.746 +    def __setattr__(self, name, value):
   1.747 +        if name in _allowed_names:
   1.748 +            # property setters go through here
   1.749 +            return object.__setattr__(self, name, value)
   1.750 +        elif (self._spec_set and self._mock_methods is not None and
   1.751 +            name not in self._mock_methods and
   1.752 +            name not in self.__dict__):
   1.753 +            raise AttributeError("Mock object has no attribute '%s'" % name)
   1.754 +        elif name in _unsupported_magics:
   1.755 +            msg = 'Attempting to set unsupported magic method %r.' % name
   1.756 +            raise AttributeError(msg)
   1.757 +        elif name in _all_magics:
   1.758 +            if self._mock_methods is not None and name not in self._mock_methods:
   1.759 +                raise AttributeError("Mock object has no attribute '%s'" % name)
   1.760 +
   1.761 +            if not _is_instance_mock(value):
   1.762 +                setattr(type(self), name, _get_method(name, value))
   1.763 +                original = value
   1.764 +                value = lambda *args, **kw: original(self, *args, **kw)
   1.765 +            else:
   1.766 +                # only set _new_name and not name so that mock_calls is tracked
   1.767 +                # but not method calls
   1.768 +                _check_and_set_parent(self, value, None, name)
   1.769 +                setattr(type(self), name, value)
   1.770 +                self._mock_children[name] = value
   1.771 +        elif name == '__class__':
   1.772 +            self._spec_class = value
   1.773 +            return
   1.774 +        else:
   1.775 +            if _check_and_set_parent(self, value, name, name):
   1.776 +                self._mock_children[name] = value
   1.777 +        return object.__setattr__(self, name, value)
   1.778 +
   1.779 +
   1.780 +    def __delattr__(self, name):
   1.781 +        if name in _all_magics and name in type(self).__dict__:
   1.782 +            delattr(type(self), name)
   1.783 +            if name not in self.__dict__:
   1.784 +                # for magic methods that are still MagicProxy objects and
   1.785 +                # not set on the instance itself
   1.786 +                return
   1.787 +
   1.788 +        if name in self.__dict__:
   1.789 +            object.__delattr__(self, name)
   1.790 +
   1.791 +        obj = self._mock_children.get(name, _missing)
   1.792 +        if obj is _deleted:
   1.793 +            raise AttributeError(name)
   1.794 +        if obj is not _missing:
   1.795 +            del self._mock_children[name]
   1.796 +        self._mock_children[name] = _deleted
   1.797 +
   1.798 +
   1.799 +
   1.800 +    def _format_mock_call_signature(self, args, kwargs):
   1.801 +        name = self._mock_name or 'mock'
   1.802 +        return _format_call_signature(name, args, kwargs)
   1.803 +
   1.804 +
   1.805 +    def _format_mock_failure_message(self, args, kwargs):
   1.806 +        message = 'Expected call: %s\nActual call: %s'
   1.807 +        expected_string = self._format_mock_call_signature(args, kwargs)
   1.808 +        call_args = self.call_args
   1.809 +        if len(call_args) == 3:
   1.810 +            call_args = call_args[1:]
   1.811 +        actual_string = self._format_mock_call_signature(*call_args)
   1.812 +        return message % (expected_string, actual_string)
   1.813 +
   1.814 +
   1.815 +    def assert_called_with(_mock_self, *args, **kwargs):
   1.816 +        """assert that the mock was called with the specified arguments.
   1.817 +
   1.818 +        Raises an AssertionError if the args and keyword args passed in are
   1.819 +        different to the last call to the mock."""
   1.820 +        self = _mock_self
   1.821 +        if self.call_args is None:
   1.822 +            expected = self._format_mock_call_signature(args, kwargs)
   1.823 +            raise AssertionError('Expected call: %s\nNot called' % (expected,))
   1.824 +
   1.825 +        if self.call_args != (args, kwargs):
   1.826 +            msg = self._format_mock_failure_message(args, kwargs)
   1.827 +            raise AssertionError(msg)
   1.828 +
   1.829 +
   1.830 +    def assert_called_once_with(_mock_self, *args, **kwargs):
   1.831 +        """assert that the mock was called exactly once and with the specified
   1.832 +        arguments."""
   1.833 +        self = _mock_self
   1.834 +        if not self.call_count == 1:
   1.835 +            msg = ("Expected to be called once. Called %s times." %
   1.836 +                   self.call_count)
   1.837 +            raise AssertionError(msg)
   1.838 +        return self.assert_called_with(*args, **kwargs)
   1.839 +
   1.840 +
   1.841 +    def assert_has_calls(self, calls, any_order=False):
   1.842 +        """assert the mock has been called with the specified calls.
   1.843 +        The `mock_calls` list is checked for the calls.
   1.844 +
   1.845 +        If `any_order` is False (the default) then the calls must be
   1.846 +        sequential. There can be extra calls before or after the
   1.847 +        specified calls.
   1.848 +
   1.849 +        If `any_order` is True then the calls can be in any order, but
   1.850 +        they must all appear in `mock_calls`."""
   1.851 +        if not any_order:
   1.852 +            if calls not in self.mock_calls:
   1.853 +                raise AssertionError(
   1.854 +                    'Calls not found.\nExpected: %r\n'
   1.855 +                    'Actual: %r' % (calls, self.mock_calls)
   1.856 +                )
   1.857 +            return
   1.858 +
   1.859 +        all_calls = list(self.mock_calls)
   1.860 +
   1.861 +        not_found = []
   1.862 +        for kall in calls:
   1.863 +            try:
   1.864 +                all_calls.remove(kall)
   1.865 +            except ValueError:
   1.866 +                not_found.append(kall)
   1.867 +        if not_found:
   1.868 +            raise AssertionError(
   1.869 +                '%r not all found in call list' % (tuple(not_found),)
   1.870 +            )
   1.871 +
   1.872 +
   1.873 +    def assert_any_call(self, *args, **kwargs):
   1.874 +        """assert the mock has been called with the specified arguments.
   1.875 +
   1.876 +        The assert passes if the mock has *ever* been called, unlike
   1.877 +        `assert_called_with` and `assert_called_once_with` that only pass if
   1.878 +        the call is the most recent one."""
   1.879 +        kall = call(*args, **kwargs)
   1.880 +        if kall not in self.call_args_list:
   1.881 +            expected_string = self._format_mock_call_signature(args, kwargs)
   1.882 +            raise AssertionError(
   1.883 +                '%s call not found' % expected_string
   1.884 +            )
   1.885 +
   1.886 +
   1.887 +    def _get_child_mock(self, **kw):
   1.888 +        """Create the child mocks for attributes and return value.
   1.889 +        By default child mocks will be the same type as the parent.
   1.890 +        Subclasses of Mock may want to override this to customize the way
   1.891 +        child mocks are made.
   1.892 +
   1.893 +        For non-callable mocks the callable variant will be used (rather than
   1.894 +        any custom subclass)."""
   1.895 +        _type = type(self)
   1.896 +        if not issubclass(_type, CallableMixin):
   1.897 +            if issubclass(_type, NonCallableMagicMock):
   1.898 +                klass = MagicMock
   1.899 +            elif issubclass(_type, NonCallableMock) :
   1.900 +                klass = Mock
   1.901 +        else:
   1.902 +            klass = _type.__mro__[1]
   1.903 +        return klass(**kw)
   1.904 +
   1.905 +
   1.906 +
   1.907 +def _try_iter(obj):
   1.908 +    if obj is None:
   1.909 +        return obj
   1.910 +    if _is_exception(obj):
   1.911 +        return obj
   1.912 +    if _callable(obj):
   1.913 +        return obj
   1.914 +    try:
   1.915 +        return iter(obj)
   1.916 +    except TypeError:
   1.917 +        # XXXX backwards compatibility
   1.918 +        # but this will blow up on first call - so maybe we should fail early?
   1.919 +        return obj
   1.920 +
   1.921 +
   1.922 +
   1.923 +class CallableMixin(Base):
   1.924 +
   1.925 +    def __init__(self, spec=None, side_effect=None, return_value=DEFAULT,
   1.926 +                 wraps=None, name=None, spec_set=None, parent=None,
   1.927 +                 _spec_state=None, _new_name='', _new_parent=None, **kwargs):
   1.928 +        self.__dict__['_mock_return_value'] = return_value
   1.929 +
   1.930 +        _super(CallableMixin, self).__init__(
   1.931 +            spec, wraps, name, spec_set, parent,
   1.932 +            _spec_state, _new_name, _new_parent, **kwargs
   1.933 +        )
   1.934 +
   1.935 +        self.side_effect = side_effect
   1.936 +
   1.937 +
   1.938 +    def _mock_check_sig(self, *args, **kwargs):
   1.939 +        # stub method that can be replaced with one with a specific signature
   1.940 +        pass
   1.941 +
   1.942 +
   1.943 +    def __call__(_mock_self, *args, **kwargs):
   1.944 +        # can't use self in-case a function / method we are mocking uses self
   1.945 +        # in the signature
   1.946 +        _mock_self._mock_check_sig(*args, **kwargs)
   1.947 +        return _mock_self._mock_call(*args, **kwargs)
   1.948 +
   1.949 +
   1.950 +    def _mock_call(_mock_self, *args, **kwargs):
   1.951 +        self = _mock_self
   1.952 +        self.called = True
   1.953 +        self.call_count += 1
   1.954 +        self.call_args = _Call((args, kwargs), two=True)
   1.955 +        self.call_args_list.append(_Call((args, kwargs), two=True))
   1.956 +
   1.957 +        _new_name = self._mock_new_name
   1.958 +        _new_parent = self._mock_new_parent
   1.959 +        self.mock_calls.append(_Call(('', args, kwargs)))
   1.960 +
   1.961 +        seen = set()
   1.962 +        skip_next_dot = _new_name == '()'
   1.963 +        do_method_calls = self._mock_parent is not None
   1.964 +        name = self._mock_name
   1.965 +        while _new_parent is not None:
   1.966 +            this_mock_call = _Call((_new_name, args, kwargs))
   1.967 +            if _new_parent._mock_new_name:
   1.968 +                dot = '.'
   1.969 +                if skip_next_dot:
   1.970 +                    dot = ''
   1.971 +
   1.972 +                skip_next_dot = False
   1.973 +                if _new_parent._mock_new_name == '()':
   1.974 +                    skip_next_dot = True
   1.975 +
   1.976 +                _new_name = _new_parent._mock_new_name + dot + _new_name
   1.977 +
   1.978 +            if do_method_calls:
   1.979 +                if _new_name == name:
   1.980 +                    this_method_call = this_mock_call
   1.981 +                else:
   1.982 +                    this_method_call = _Call((name, args, kwargs))
   1.983 +                _new_parent.method_calls.append(this_method_call)
   1.984 +
   1.985 +                do_method_calls = _new_parent._mock_parent is not None
   1.986 +                if do_method_calls:
   1.987 +                    name = _new_parent._mock_name + '.' + name
   1.988 +
   1.989 +            _new_parent.mock_calls.append(this_mock_call)
   1.990 +            _new_parent = _new_parent._mock_new_parent
   1.991 +
   1.992 +            # use ids here so as not to call __hash__ on the mocks
   1.993 +            _new_parent_id = id(_new_parent)
   1.994 +            if _new_parent_id in seen:
   1.995 +                break
   1.996 +            seen.add(_new_parent_id)
   1.997 +
   1.998 +        ret_val = DEFAULT
   1.999 +        effect = self.side_effect
  1.1000 +        if effect is not None:
  1.1001 +            if _is_exception(effect):
  1.1002 +                raise effect
  1.1003 +
  1.1004 +            if not _callable(effect):
  1.1005 +                result = next(effect)
  1.1006 +                if _is_exception(result):
  1.1007 +                    raise result
  1.1008 +                return result
  1.1009 +
  1.1010 +            ret_val = effect(*args, **kwargs)
  1.1011 +            if ret_val is DEFAULT:
  1.1012 +                ret_val = self.return_value
  1.1013 +
  1.1014 +        if (self._mock_wraps is not None and
  1.1015 +             self._mock_return_value is DEFAULT):
  1.1016 +            return self._mock_wraps(*args, **kwargs)
  1.1017 +        if ret_val is DEFAULT:
  1.1018 +            ret_val = self.return_value
  1.1019 +        return ret_val
  1.1020 +
  1.1021 +
  1.1022 +
  1.1023 +class Mock(CallableMixin, NonCallableMock):
  1.1024 +    """
  1.1025 +    Create a new `Mock` object. `Mock` takes several optional arguments
  1.1026 +    that specify the behaviour of the Mock object:
  1.1027 +
  1.1028 +    * `spec`: This can be either a list of strings or an existing object (a
  1.1029 +      class or instance) that acts as the specification for the mock object. If
  1.1030 +      you pass in an object then a list of strings is formed by calling dir on
  1.1031 +      the object (excluding unsupported magic attributes and methods). Accessing
  1.1032 +      any attribute not in this list will raise an `AttributeError`.
  1.1033 +
  1.1034 +      If `spec` is an object (rather than a list of strings) then
  1.1035 +      `mock.__class__` returns the class of the spec object. This allows mocks
  1.1036 +      to pass `isinstance` tests.
  1.1037 +
  1.1038 +    * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
  1.1039 +      or get an attribute on the mock that isn't on the object passed as
  1.1040 +      `spec_set` will raise an `AttributeError`.
  1.1041 +
  1.1042 +    * `side_effect`: A function to be called whenever the Mock is called. See
  1.1043 +      the `side_effect` attribute. Useful for raising exceptions or
  1.1044 +      dynamically changing return values. The function is called with the same
  1.1045 +      arguments as the mock, and unless it returns `DEFAULT`, the return
  1.1046 +      value of this function is used as the return value.
  1.1047 +
  1.1048 +      Alternatively `side_effect` can be an exception class or instance. In
  1.1049 +      this case the exception will be raised when the mock is called.
  1.1050 +
  1.1051 +      If `side_effect` is an iterable then each call to the mock will return
  1.1052 +      the next value from the iterable. If any of the members of the iterable
  1.1053 +      are exceptions they will be raised instead of returned.
  1.1054 +
  1.1055 +    * `return_value`: The value returned when the mock is called. By default
  1.1056 +      this is a new Mock (created on first access). See the
  1.1057 +      `return_value` attribute.
  1.1058 +
  1.1059 +    * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
  1.1060 +      calling the Mock will pass the call through to the wrapped object
  1.1061 +      (returning the real result). Attribute access on the mock will return a
  1.1062 +      Mock object that wraps the corresponding attribute of the wrapped object
  1.1063 +      (so attempting to access an attribute that doesn't exist will raise an
  1.1064 +      `AttributeError`).
  1.1065 +
  1.1066 +      If the mock has an explicit `return_value` set then calls are not passed
  1.1067 +      to the wrapped object and the `return_value` is returned instead.
  1.1068 +
  1.1069 +    * `name`: If the mock has a name then it will be used in the repr of the
  1.1070 +      mock. This can be useful for debugging. The name is propagated to child
  1.1071 +      mocks.
  1.1072 +
  1.1073 +    Mocks can also be called with arbitrary keyword arguments. These will be
  1.1074 +    used to set attributes on the mock after it is created.
  1.1075 +    """
  1.1076 +
  1.1077 +
  1.1078 +
  1.1079 +def _dot_lookup(thing, comp, import_path):
  1.1080 +    try:
  1.1081 +        return getattr(thing, comp)
  1.1082 +    except AttributeError:
  1.1083 +        __import__(import_path)
  1.1084 +        return getattr(thing, comp)
  1.1085 +
  1.1086 +
  1.1087 +def _importer(target):
  1.1088 +    components = target.split('.')
  1.1089 +    import_path = components.pop(0)
  1.1090 +    thing = __import__(import_path)
  1.1091 +
  1.1092 +    for comp in components:
  1.1093 +        import_path += ".%s" % comp
  1.1094 +        thing = _dot_lookup(thing, comp, import_path)
  1.1095 +    return thing
  1.1096 +
  1.1097 +
  1.1098 +def _is_started(patcher):
  1.1099 +    # XXXX horrible
  1.1100 +    return hasattr(patcher, 'is_local')
  1.1101 +
  1.1102 +
  1.1103 +class _patch(object):
  1.1104 +
  1.1105 +    attribute_name = None
  1.1106 +    _active_patches = set()
  1.1107 +
  1.1108 +    def __init__(
  1.1109 +            self, getter, attribute, new, spec, create,
  1.1110 +            spec_set, autospec, new_callable, kwargs
  1.1111 +        ):
  1.1112 +        if new_callable is not None:
  1.1113 +            if new is not DEFAULT:
  1.1114 +                raise ValueError(
  1.1115 +                    "Cannot use 'new' and 'new_callable' together"
  1.1116 +                )
  1.1117 +            if autospec is not None:
  1.1118 +                raise ValueError(
  1.1119 +                    "Cannot use 'autospec' and 'new_callable' together"
  1.1120 +                )
  1.1121 +
  1.1122 +        self.getter = getter
  1.1123 +        self.attribute = attribute
  1.1124 +        self.new = new
  1.1125 +        self.new_callable = new_callable
  1.1126 +        self.spec = spec
  1.1127 +        self.create = create
  1.1128 +        self.has_local = False
  1.1129 +        self.spec_set = spec_set
  1.1130 +        self.autospec = autospec
  1.1131 +        self.kwargs = kwargs
  1.1132 +        self.additional_patchers = []
  1.1133 +
  1.1134 +
  1.1135 +    def copy(self):
  1.1136 +        patcher = _patch(
  1.1137 +            self.getter, self.attribute, self.new, self.spec,
  1.1138 +            self.create, self.spec_set,
  1.1139 +            self.autospec, self.new_callable, self.kwargs
  1.1140 +        )
  1.1141 +        patcher.attribute_name = self.attribute_name
  1.1142 +        patcher.additional_patchers = [
  1.1143 +            p.copy() for p in self.additional_patchers
  1.1144 +        ]
  1.1145 +        return patcher
  1.1146 +
  1.1147 +
  1.1148 +    def __call__(self, func):
  1.1149 +        if isinstance(func, ClassTypes):
  1.1150 +            return self.decorate_class(func)
  1.1151 +        return self.decorate_callable(func)
  1.1152 +
  1.1153 +
  1.1154 +    def decorate_class(self, klass):
  1.1155 +        for attr in dir(klass):
  1.1156 +            if not attr.startswith(patch.TEST_PREFIX):
  1.1157 +                continue
  1.1158 +
  1.1159 +            attr_value = getattr(klass, attr)
  1.1160 +            if not hasattr(attr_value, "__call__"):
  1.1161 +                continue
  1.1162 +
  1.1163 +            patcher = self.copy()
  1.1164 +            setattr(klass, attr, patcher(attr_value))
  1.1165 +        return klass
  1.1166 +
  1.1167 +
  1.1168 +    def decorate_callable(self, func):
  1.1169 +        if hasattr(func, 'patchings'):
  1.1170 +            func.patchings.append(self)
  1.1171 +            return func
  1.1172 +
  1.1173 +        @wraps(func)
  1.1174 +        def patched(*args, **keywargs):
  1.1175 +            # don't use a with here (backwards compatability with Python 2.4)
  1.1176 +            extra_args = []
  1.1177 +            entered_patchers = []
  1.1178 +
  1.1179 +            # can't use try...except...finally because of Python 2.4
  1.1180 +            # compatibility
  1.1181 +            exc_info = tuple()
  1.1182 +            try:
  1.1183 +                try:
  1.1184 +                    for patching in patched.patchings:
  1.1185 +                        arg = patching.__enter__()
  1.1186 +                        entered_patchers.append(patching)
  1.1187 +                        if patching.attribute_name is not None:
  1.1188 +                            keywargs.update(arg)
  1.1189 +                        elif patching.new is DEFAULT:
  1.1190 +                            extra_args.append(arg)
  1.1191 +
  1.1192 +                    args += tuple(extra_args)
  1.1193 +                    return func(*args, **keywargs)
  1.1194 +                except:
  1.1195 +                    if (patching not in entered_patchers and
  1.1196 +                        _is_started(patching)):
  1.1197 +                        # the patcher may have been started, but an exception
  1.1198 +                        # raised whilst entering one of its additional_patchers
  1.1199 +                        entered_patchers.append(patching)
  1.1200 +                    # Pass the exception to __exit__
  1.1201 +                    exc_info = sys.exc_info()
  1.1202 +                    # re-raise the exception
  1.1203 +                    raise
  1.1204 +            finally:
  1.1205 +                for patching in reversed(entered_patchers):
  1.1206 +                    patching.__exit__(*exc_info)
  1.1207 +
  1.1208 +        patched.patchings = [self]
  1.1209 +        if hasattr(func, 'func_code'):
  1.1210 +            # not in Python 3
  1.1211 +            patched.compat_co_firstlineno = getattr(
  1.1212 +                func, "compat_co_firstlineno",
  1.1213 +                func.func_code.co_firstlineno
  1.1214 +            )
  1.1215 +        return patched
  1.1216 +
  1.1217 +
  1.1218 +    def get_original(self):
  1.1219 +        target = self.getter()
  1.1220 +        name = self.attribute
  1.1221 +
  1.1222 +        original = DEFAULT
  1.1223 +        local = False
  1.1224 +
  1.1225 +        try:
  1.1226 +            original = target.__dict__[name]
  1.1227 +        except (AttributeError, KeyError):
  1.1228 +            original = getattr(target, name, DEFAULT)
  1.1229 +        else:
  1.1230 +            local = True
  1.1231 +
  1.1232 +        if not self.create and original is DEFAULT:
  1.1233 +            raise AttributeError(
  1.1234 +                "%s does not have the attribute %r" % (target, name)
  1.1235 +            )
  1.1236 +        return original, local
  1.1237 +
  1.1238 +
  1.1239 +    def __enter__(self):
  1.1240 +        """Perform the patch."""
  1.1241 +        new, spec, spec_set = self.new, self.spec, self.spec_set
  1.1242 +        autospec, kwargs = self.autospec, self.kwargs
  1.1243 +        new_callable = self.new_callable
  1.1244 +        self.target = self.getter()
  1.1245 +
  1.1246 +        # normalise False to None
  1.1247 +        if spec is False:
  1.1248 +            spec = None
  1.1249 +        if spec_set is False:
  1.1250 +            spec_set = None
  1.1251 +        if autospec is False:
  1.1252 +            autospec = None
  1.1253 +
  1.1254 +        if spec is not None and autospec is not None:
  1.1255 +            raise TypeError("Can't specify spec and autospec")
  1.1256 +        if ((spec is not None or autospec is not None) and
  1.1257 +            spec_set not in (True, None)):
  1.1258 +            raise TypeError("Can't provide explicit spec_set *and* spec or autospec")
  1.1259 +
  1.1260 +        original, local = self.get_original()
  1.1261 +
  1.1262 +        if new is DEFAULT and autospec is None:
  1.1263 +            inherit = False
  1.1264 +            if spec is True:
  1.1265 +                # set spec to the object we are replacing
  1.1266 +                spec = original
  1.1267 +                if spec_set is True:
  1.1268 +                    spec_set = original
  1.1269 +                    spec = None
  1.1270 +            elif spec is not None:
  1.1271 +                if spec_set is True:
  1.1272 +                    spec_set = spec
  1.1273 +                    spec = None
  1.1274 +            elif spec_set is True:
  1.1275 +                spec_set = original
  1.1276 +
  1.1277 +            if spec is not None or spec_set is not None:
  1.1278 +                if original is DEFAULT:
  1.1279 +                    raise TypeError("Can't use 'spec' with create=True")
  1.1280 +                if isinstance(original, ClassTypes):
  1.1281 +                    # If we're patching out a class and there is a spec
  1.1282 +                    inherit = True
  1.1283 +
  1.1284 +            Klass = MagicMock
  1.1285 +            _kwargs = {}
  1.1286 +            if new_callable is not None:
  1.1287 +                Klass = new_callable
  1.1288 +            elif spec is not None or spec_set is not None:
  1.1289 +                this_spec = spec
  1.1290 +                if spec_set is not None:
  1.1291 +                    this_spec = spec_set
  1.1292 +                if _is_list(this_spec):
  1.1293 +                    not_callable = '__call__' not in this_spec
  1.1294 +                else:
  1.1295 +                    not_callable = not _callable(this_spec)
  1.1296 +                if not_callable:
  1.1297 +                    Klass = NonCallableMagicMock
  1.1298 +
  1.1299 +            if spec is not None:
  1.1300 +                _kwargs['spec'] = spec
  1.1301 +            if spec_set is not None:
  1.1302 +                _kwargs['spec_set'] = spec_set
  1.1303 +
  1.1304 +            # add a name to mocks
  1.1305 +            if (isinstance(Klass, type) and
  1.1306 +                issubclass(Klass, NonCallableMock) and self.attribute):
  1.1307 +                _kwargs['name'] = self.attribute
  1.1308 +
  1.1309 +            _kwargs.update(kwargs)
  1.1310 +            new = Klass(**_kwargs)
  1.1311 +
  1.1312 +            if inherit and _is_instance_mock(new):
  1.1313 +                # we can only tell if the instance should be callable if the
  1.1314 +                # spec is not a list
  1.1315 +                this_spec = spec
  1.1316 +                if spec_set is not None:
  1.1317 +                    this_spec = spec_set
  1.1318 +                if (not _is_list(this_spec) and not
  1.1319 +                    _instance_callable(this_spec)):
  1.1320 +                    Klass = NonCallableMagicMock
  1.1321 +
  1.1322 +                _kwargs.pop('name')
  1.1323 +                new.return_value = Klass(_new_parent=new, _new_name='()',
  1.1324 +                                         **_kwargs)
  1.1325 +        elif autospec is not None:
  1.1326 +            # spec is ignored, new *must* be default, spec_set is treated
  1.1327 +            # as a boolean. Should we check spec is not None and that spec_set
  1.1328 +            # is a bool?
  1.1329 +            if new is not DEFAULT:
  1.1330 +                raise TypeError(
  1.1331 +                    "autospec creates the mock for you. Can't specify "
  1.1332 +                    "autospec and new."
  1.1333 +                )
  1.1334 +            if original is DEFAULT:
  1.1335 +                raise TypeError("Can't use 'autospec' with create=True")
  1.1336 +            spec_set = bool(spec_set)
  1.1337 +            if autospec is True:
  1.1338 +                autospec = original
  1.1339 +
  1.1340 +            new = create_autospec(autospec, spec_set=spec_set,
  1.1341 +                                  _name=self.attribute, **kwargs)
  1.1342 +        elif kwargs:
  1.1343 +            # can't set keyword args when we aren't creating the mock
  1.1344 +            # XXXX If new is a Mock we could call new.configure_mock(**kwargs)
  1.1345 +            raise TypeError("Can't pass kwargs to a mock we aren't creating")
  1.1346 +
  1.1347 +        new_attr = new
  1.1348 +
  1.1349 +        self.temp_original = original
  1.1350 +        self.is_local = local
  1.1351 +        setattr(self.target, self.attribute, new_attr)
  1.1352 +        if self.attribute_name is not None:
  1.1353 +            extra_args = {}
  1.1354 +            if self.new is DEFAULT:
  1.1355 +                extra_args[self.attribute_name] =  new
  1.1356 +            for patching in self.additional_patchers:
  1.1357 +                arg = patching.__enter__()
  1.1358 +                if patching.new is DEFAULT:
  1.1359 +                    extra_args.update(arg)
  1.1360 +            return extra_args
  1.1361 +
  1.1362 +        return new
  1.1363 +
  1.1364 +
  1.1365 +    def __exit__(self, *exc_info):
  1.1366 +        """Undo the patch."""
  1.1367 +        if not _is_started(self):
  1.1368 +            raise RuntimeError('stop called on unstarted patcher')
  1.1369 +
  1.1370 +        if self.is_local and self.temp_original is not DEFAULT:
  1.1371 +            setattr(self.target, self.attribute, self.temp_original)
  1.1372 +        else:
  1.1373 +            delattr(self.target, self.attribute)
  1.1374 +            if not self.create and not hasattr(self.target, self.attribute):
  1.1375 +                # needed for proxy objects like django settings
  1.1376 +                setattr(self.target, self.attribute, self.temp_original)
  1.1377 +
  1.1378 +        del self.temp_original
  1.1379 +        del self.is_local
  1.1380 +        del self.target
  1.1381 +        for patcher in reversed(self.additional_patchers):
  1.1382 +            if _is_started(patcher):
  1.1383 +                patcher.__exit__(*exc_info)
  1.1384 +
  1.1385 +
  1.1386 +    def start(self):
  1.1387 +        """Activate a patch, returning any created mock."""
  1.1388 +        result = self.__enter__()
  1.1389 +        self._active_patches.add(self)
  1.1390 +        return result
  1.1391 +
  1.1392 +
  1.1393 +    def stop(self):
  1.1394 +        """Stop an active patch."""
  1.1395 +        self._active_patches.discard(self)
  1.1396 +        return self.__exit__()
  1.1397 +
  1.1398 +
  1.1399 +
  1.1400 +def _get_target(target):
  1.1401 +    try:
  1.1402 +        target, attribute = target.rsplit('.', 1)
  1.1403 +    except (TypeError, ValueError):
  1.1404 +        raise TypeError("Need a valid target to patch. You supplied: %r" %
  1.1405 +                        (target,))
  1.1406 +    getter = lambda: _importer(target)
  1.1407 +    return getter, attribute
  1.1408 +
  1.1409 +
  1.1410 +def _patch_object(
  1.1411 +        target, attribute, new=DEFAULT, spec=None,
  1.1412 +        create=False, spec_set=None, autospec=None,
  1.1413 +        new_callable=None, **kwargs
  1.1414 +    ):
  1.1415 +    """
  1.1416 +    patch.object(target, attribute, new=DEFAULT, spec=None, create=False,
  1.1417 +                 spec_set=None, autospec=None, new_callable=None, **kwargs)
  1.1418 +
  1.1419 +    patch the named member (`attribute`) on an object (`target`) with a mock
  1.1420 +    object.
  1.1421 +
  1.1422 +    `patch.object` can be used as a decorator, class decorator or a context
  1.1423 +    manager. Arguments `new`, `spec`, `create`, `spec_set`,
  1.1424 +    `autospec` and `new_callable` have the same meaning as for `patch`. Like
  1.1425 +    `patch`, `patch.object` takes arbitrary keyword arguments for configuring
  1.1426 +    the mock object it creates.
  1.1427 +
  1.1428 +    When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
  1.1429 +    for choosing which methods to wrap.
  1.1430 +    """
  1.1431 +    getter = lambda: target
  1.1432 +    return _patch(
  1.1433 +        getter, attribute, new, spec, create,
  1.1434 +        spec_set, autospec, new_callable, kwargs
  1.1435 +    )
  1.1436 +
  1.1437 +
  1.1438 +def _patch_multiple(target, spec=None, create=False, spec_set=None,
  1.1439 +                    autospec=None, new_callable=None, **kwargs):
  1.1440 +    """Perform multiple patches in a single call. It takes the object to be
  1.1441 +    patched (either as an object or a string to fetch the object by importing)
  1.1442 +    and keyword arguments for the patches::
  1.1443 +
  1.1444 +        with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
  1.1445 +            ...
  1.1446 +
  1.1447 +    Use `DEFAULT` as the value if you want `patch.multiple` to create
  1.1448 +    mocks for you. In this case the created mocks are passed into a decorated
  1.1449 +    function by keyword, and a dictionary is returned when `patch.multiple` is
  1.1450 +    used as a context manager.
  1.1451 +
  1.1452 +    `patch.multiple` can be used as a decorator, class decorator or a context
  1.1453 +    manager. The arguments `spec`, `spec_set`, `create`,
  1.1454 +    `autospec` and `new_callable` have the same meaning as for `patch`. These
  1.1455 +    arguments will be applied to *all* patches done by `patch.multiple`.
  1.1456 +
  1.1457 +    When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
  1.1458 +    for choosing which methods to wrap.
  1.1459 +    """
  1.1460 +    if type(target) in (unicode, str):
  1.1461 +        getter = lambda: _importer(target)
  1.1462 +    else:
  1.1463 +        getter = lambda: target
  1.1464 +
  1.1465 +    if not kwargs:
  1.1466 +        raise ValueError(
  1.1467 +            'Must supply at least one keyword argument with patch.multiple'
  1.1468 +        )
  1.1469 +    # need to wrap in a list for python 3, where items is a view
  1.1470 +    items = list(kwargs.items())
  1.1471 +    attribute, new = items[0]
  1.1472 +    patcher = _patch(
  1.1473 +        getter, attribute, new, spec, create, spec_set,
  1.1474 +        autospec, new_callable, {}
  1.1475 +    )
  1.1476 +    patcher.attribute_name = attribute
  1.1477 +    for attribute, new in items[1:]:
  1.1478 +        this_patcher = _patch(
  1.1479 +            getter, attribute, new, spec, create, spec_set,
  1.1480 +            autospec, new_callable, {}
  1.1481 +        )
  1.1482 +        this_patcher.attribute_name = attribute
  1.1483 +        patcher.additional_patchers.append(this_patcher)
  1.1484 +    return patcher
  1.1485 +
  1.1486 +
  1.1487 +def patch(
  1.1488 +        target, new=DEFAULT, spec=None, create=False,
  1.1489 +        spec_set=None, autospec=None, new_callable=None, **kwargs
  1.1490 +    ):
  1.1491 +    """
  1.1492 +    `patch` acts as a function decorator, class decorator or a context
  1.1493 +    manager. Inside the body of the function or with statement, the `target`
  1.1494 +    is patched with a `new` object. When the function/with statement exits
  1.1495 +    the patch is undone.
  1.1496 +
  1.1497 +    If `new` is omitted, then the target is replaced with a
  1.1498 +    `MagicMock`. If `patch` is used as a decorator and `new` is
  1.1499 +    omitted, the created mock is passed in as an extra argument to the
  1.1500 +    decorated function. If `patch` is used as a context manager the created
  1.1501 +    mock is returned by the context manager.
  1.1502 +
  1.1503 +    `target` should be a string in the form `'package.module.ClassName'`. The
  1.1504 +    `target` is imported and the specified object replaced with the `new`
  1.1505 +    object, so the `target` must be importable from the environment you are
  1.1506 +    calling `patch` from. The target is imported when the decorated function
  1.1507 +    is executed, not at decoration time.
  1.1508 +
  1.1509 +    The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
  1.1510 +    if patch is creating one for you.
  1.1511 +
  1.1512 +    In addition you can pass `spec=True` or `spec_set=True`, which causes
  1.1513 +    patch to pass in the object being mocked as the spec/spec_set object.
  1.1514 +
  1.1515 +    `new_callable` allows you to specify a different class, or callable object,
  1.1516 +    that will be called to create the `new` object. By default `MagicMock` is
  1.1517 +    used.
  1.1518 +
  1.1519 +    A more powerful form of `spec` is `autospec`. If you set `autospec=True`
  1.1520 +    then the mock with be created with a spec from the object being replaced.
  1.1521 +    All attributes of the mock will also have the spec of the corresponding
  1.1522 +    attribute of the object being replaced. Methods and functions being
  1.1523 +    mocked will have their arguments checked and will raise a `TypeError` if
  1.1524 +    they are called with the wrong signature. For mocks replacing a class,
  1.1525 +    their return value (the 'instance') will have the same spec as the class.
  1.1526 +
  1.1527 +    Instead of `autospec=True` you can pass `autospec=some_object` to use an
  1.1528 +    arbitrary object as the spec instead of the one being replaced.
  1.1529 +
  1.1530 +    By default `patch` will fail to replace attributes that don't exist. If
  1.1531 +    you pass in `create=True`, and the attribute doesn't exist, patch will
  1.1532 +    create the attribute for you when the patched function is called, and
  1.1533 +    delete it again afterwards. This is useful for writing tests against
  1.1534 +    attributes that your production code creates at runtime. It is off by by
  1.1535 +    default because it can be dangerous. With it switched on you can write
  1.1536 +    passing tests against APIs that don't actually exist!
  1.1537 +
  1.1538 +    Patch can be used as a `TestCase` class decorator. It works by
  1.1539 +    decorating each test method in the class. This reduces the boilerplate
  1.1540 +    code when your test methods share a common patchings set. `patch` finds
  1.1541 +    tests by looking for method names that start with `patch.TEST_PREFIX`.
  1.1542 +    By default this is `test`, which matches the way `unittest` finds tests.
  1.1543 +    You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
  1.1544 +
  1.1545 +    Patch can be used as a context manager, with the with statement. Here the
  1.1546 +    patching applies to the indented block after the with statement. If you
  1.1547 +    use "as" then the patched object will be bound to the name after the
  1.1548 +    "as"; very useful if `patch` is creating a mock object for you.
  1.1549 +
  1.1550 +    `patch` takes arbitrary keyword arguments. These will be passed to
  1.1551 +    the `Mock` (or `new_callable`) on construction.
  1.1552 +
  1.1553 +    `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
  1.1554 +    available for alternate use-cases.
  1.1555 +    """
  1.1556 +    getter, attribute = _get_target(target)
  1.1557 +    return _patch(
  1.1558 +        getter, attribute, new, spec, create,
  1.1559 +        spec_set, autospec, new_callable, kwargs
  1.1560 +    )
  1.1561 +
  1.1562 +
  1.1563 +class _patch_dict(object):
  1.1564 +    """
  1.1565 +    Patch a dictionary, or dictionary like object, and restore the dictionary
  1.1566 +    to its original state after the test.
  1.1567 +
  1.1568 +    `in_dict` can be a dictionary or a mapping like container. If it is a
  1.1569 +    mapping then it must at least support getting, setting and deleting items
  1.1570 +    plus iterating over keys.
  1.1571 +
  1.1572 +    `in_dict` can also be a string specifying the name of the dictionary, which
  1.1573 +    will then be fetched by importing it.
  1.1574 +
  1.1575 +    `values` can be a dictionary of values to set in the dictionary. `values`
  1.1576 +    can also be an iterable of `(key, value)` pairs.
  1.1577 +
  1.1578 +    If `clear` is True then the dictionary will be cleared before the new
  1.1579 +    values are set.
  1.1580 +
  1.1581 +    `patch.dict` can also be called with arbitrary keyword arguments to set
  1.1582 +    values in the dictionary::
  1.1583 +
  1.1584 +        with patch.dict('sys.modules', mymodule=Mock(), other_module=Mock()):
  1.1585 +            ...
  1.1586 +
  1.1587 +    `patch.dict` can be used as a context manager, decorator or class
  1.1588 +    decorator. When used as a class decorator `patch.dict` honours
  1.1589 +    `patch.TEST_PREFIX` for choosing which methods to wrap.
  1.1590 +    """
  1.1591 +
  1.1592 +    def __init__(self, in_dict, values=(), clear=False, **kwargs):
  1.1593 +        if isinstance(in_dict, basestring):
  1.1594 +            in_dict = _importer(in_dict)
  1.1595 +        self.in_dict = in_dict
  1.1596 +        # support any argument supported by dict(...) constructor
  1.1597 +        self.values = dict(values)
  1.1598 +        self.values.update(kwargs)
  1.1599 +        self.clear = clear
  1.1600 +        self._original = None
  1.1601 +
  1.1602 +
  1.1603 +    def __call__(self, f):
  1.1604 +        if isinstance(f, ClassTypes):
  1.1605 +            return self.decorate_class(f)
  1.1606 +        @wraps(f)
  1.1607 +        def _inner(*args, **kw):
  1.1608 +            self._patch_dict()
  1.1609 +            try:
  1.1610 +                return f(*args, **kw)
  1.1611 +            finally:
  1.1612 +                self._unpatch_dict()
  1.1613 +
  1.1614 +        return _inner
  1.1615 +
  1.1616 +
  1.1617 +    def decorate_class(self, klass):
  1.1618 +        for attr in dir(klass):
  1.1619 +            attr_value = getattr(klass, attr)
  1.1620 +            if (attr.startswith(patch.TEST_PREFIX) and
  1.1621 +                 hasattr(attr_value, "__call__")):
  1.1622 +                decorator = _patch_dict(self.in_dict, self.values, self.clear)
  1.1623 +                decorated = decorator(attr_value)
  1.1624 +                setattr(klass, attr, decorated)
  1.1625 +        return klass
  1.1626 +
  1.1627 +
  1.1628 +    def __enter__(self):
  1.1629 +        """Patch the dict."""
  1.1630 +        self._patch_dict()
  1.1631 +
  1.1632 +
  1.1633 +    def _patch_dict(self):
  1.1634 +        values = self.values
  1.1635 +        in_dict = self.in_dict
  1.1636 +        clear = self.clear
  1.1637 +
  1.1638 +        try:
  1.1639 +            original = in_dict.copy()
  1.1640 +        except AttributeError:
  1.1641 +            # dict like object with no copy method
  1.1642 +            # must support iteration over keys
  1.1643 +            original = {}
  1.1644 +            for key in in_dict:
  1.1645 +                original[key] = in_dict[key]
  1.1646 +        self._original = original
  1.1647 +
  1.1648 +        if clear:
  1.1649 +            _clear_dict(in_dict)
  1.1650 +
  1.1651 +        try:
  1.1652 +            in_dict.update(values)
  1.1653 +        except AttributeError:
  1.1654 +            # dict like object with no update method
  1.1655 +            for key in values:
  1.1656 +                in_dict[key] = values[key]
  1.1657 +
  1.1658 +
  1.1659 +    def _unpatch_dict(self):
  1.1660 +        in_dict = self.in_dict
  1.1661 +        original = self._original
  1.1662 +
  1.1663 +        _clear_dict(in_dict)
  1.1664 +
  1.1665 +        try:
  1.1666 +            in_dict.update(original)
  1.1667 +        except AttributeError:
  1.1668 +            for key in original:
  1.1669 +                in_dict[key] = original[key]
  1.1670 +
  1.1671 +
  1.1672 +    def __exit__(self, *args):
  1.1673 +        """Unpatch the dict."""
  1.1674 +        self._unpatch_dict()
  1.1675 +        return False
  1.1676 +
  1.1677 +    start = __enter__
  1.1678 +    stop = __exit__
  1.1679 +
  1.1680 +
  1.1681 +def _clear_dict(in_dict):
  1.1682 +    try:
  1.1683 +        in_dict.clear()
  1.1684 +    except AttributeError:
  1.1685 +        keys = list(in_dict)
  1.1686 +        for key in keys:
  1.1687 +            del in_dict[key]
  1.1688 +
  1.1689 +
  1.1690 +def _patch_stopall():
  1.1691 +    """Stop all active patches."""
  1.1692 +    for patch in list(_patch._active_patches):
  1.1693 +        patch.stop()
  1.1694 +
  1.1695 +
  1.1696 +patch.object = _patch_object
  1.1697 +patch.dict = _patch_dict
  1.1698 +patch.multiple = _patch_multiple
  1.1699 +patch.stopall = _patch_stopall
  1.1700 +patch.TEST_PREFIX = 'test'
  1.1701 +
  1.1702 +magic_methods = (
  1.1703 +    "lt le gt ge eq ne "
  1.1704 +    "getitem setitem delitem "
  1.1705 +    "len contains iter "
  1.1706 +    "hash str sizeof "
  1.1707 +    "enter exit "
  1.1708 +    "divmod neg pos abs invert "
  1.1709 +    "complex int float index "
  1.1710 +    "trunc floor ceil "
  1.1711 +)
  1.1712 +
  1.1713 +numerics = "add sub mul div floordiv mod lshift rshift and xor or pow "
  1.1714 +inplace = ' '.join('i%s' % n for n in numerics.split())
  1.1715 +right = ' '.join('r%s' % n for n in numerics.split())
  1.1716 +extra = ''
  1.1717 +if inPy3k:
  1.1718 +    extra = 'bool next '
  1.1719 +else:
  1.1720 +    extra = 'unicode long nonzero oct hex truediv rtruediv '
  1.1721 +
  1.1722 +# not including __prepare__, __instancecheck__, __subclasscheck__
  1.1723 +# (as they are metaclass methods)
  1.1724 +# __del__ is not supported at all as it causes problems if it exists
  1.1725 +
  1.1726 +_non_defaults = set('__%s__' % method for method in [
  1.1727 +    'cmp', 'getslice', 'setslice', 'coerce', 'subclasses',
  1.1728 +    'format', 'get', 'set', 'delete', 'reversed',
  1.1729 +    'missing', 'reduce', 'reduce_ex', 'getinitargs',
  1.1730 +    'getnewargs', 'getstate', 'setstate', 'getformat',
  1.1731 +    'setformat', 'repr', 'dir'
  1.1732 +])
  1.1733 +
  1.1734 +
  1.1735 +def _get_method(name, func):
  1.1736 +    "Turns a callable object (like a mock) into a real function"
  1.1737 +    def method(self, *args, **kw):
  1.1738 +        return func(self, *args, **kw)
  1.1739 +    method.__name__ = name
  1.1740 +    return method
  1.1741 +
  1.1742 +
  1.1743 +_magics = set(
  1.1744 +    '__%s__' % method for method in
  1.1745 +    ' '.join([magic_methods, numerics, inplace, right, extra]).split()
  1.1746 +)
  1.1747 +
  1.1748 +_all_magics = _magics | _non_defaults
  1.1749 +
  1.1750 +_unsupported_magics = set([
  1.1751 +    '__getattr__', '__setattr__',
  1.1752 +    '__init__', '__new__', '__prepare__'
  1.1753 +    '__instancecheck__', '__subclasscheck__',
  1.1754 +    '__del__'
  1.1755 +])
  1.1756 +
  1.1757 +_calculate_return_value = {
  1.1758 +    '__hash__': lambda self: object.__hash__(self),
  1.1759 +    '__str__': lambda self: object.__str__(self),
  1.1760 +    '__sizeof__': lambda self: object.__sizeof__(self),
  1.1761 +    '__unicode__': lambda self: unicode(object.__str__(self)),
  1.1762 +}
  1.1763 +
  1.1764 +_return_values = {
  1.1765 +    '__lt__': NotImplemented,
  1.1766 +    '__gt__': NotImplemented,
  1.1767 +    '__le__': NotImplemented,
  1.1768 +    '__ge__': NotImplemented,
  1.1769 +    '__int__': 1,
  1.1770 +    '__contains__': False,
  1.1771 +    '__len__': 0,
  1.1772 +    '__exit__': False,
  1.1773 +    '__complex__': 1j,
  1.1774 +    '__float__': 1.0,
  1.1775 +    '__bool__': True,
  1.1776 +    '__nonzero__': True,
  1.1777 +    '__oct__': '1',
  1.1778 +    '__hex__': '0x1',
  1.1779 +    '__long__': long(1),
  1.1780 +    '__index__': 1,
  1.1781 +}
  1.1782 +
  1.1783 +
  1.1784 +def _get_eq(self):
  1.1785 +    def __eq__(other):
  1.1786 +        ret_val = self.__eq__._mock_return_value
  1.1787 +        if ret_val is not DEFAULT:
  1.1788 +            return ret_val
  1.1789 +        return self is other
  1.1790 +    return __eq__
  1.1791 +
  1.1792 +def _get_ne(self):
  1.1793 +    def __ne__(other):
  1.1794 +        if self.__ne__._mock_return_value is not DEFAULT:
  1.1795 +            return DEFAULT
  1.1796 +        return self is not other
  1.1797 +    return __ne__
  1.1798 +
  1.1799 +def _get_iter(self):
  1.1800 +    def __iter__():
  1.1801 +        ret_val = self.__iter__._mock_return_value
  1.1802 +        if ret_val is DEFAULT:
  1.1803 +            return iter([])
  1.1804 +        # if ret_val was already an iterator, then calling iter on it should
  1.1805 +        # return the iterator unchanged
  1.1806 +        return iter(ret_val)
  1.1807 +    return __iter__
  1.1808 +
  1.1809 +_side_effect_methods = {
  1.1810 +    '__eq__': _get_eq,
  1.1811 +    '__ne__': _get_ne,
  1.1812 +    '__iter__': _get_iter,
  1.1813 +}
  1.1814 +
  1.1815 +
  1.1816 +
  1.1817 +def _set_return_value(mock, method, name):
  1.1818 +    fixed = _return_values.get(name, DEFAULT)
  1.1819 +    if fixed is not DEFAULT:
  1.1820 +        method.return_value = fixed
  1.1821 +        return
  1.1822 +
  1.1823 +    return_calulator = _calculate_return_value.get(name)
  1.1824 +    if return_calulator is not None:
  1.1825 +        try:
  1.1826 +            return_value = return_calulator(mock)
  1.1827 +        except AttributeError:
  1.1828 +            # XXXX why do we return AttributeError here?
  1.1829 +            #      set it as a side_effect instead?
  1.1830 +            return_value = AttributeError(name)
  1.1831 +        method.return_value = return_value
  1.1832 +        return
  1.1833 +
  1.1834 +    side_effector = _side_effect_methods.get(name)
  1.1835 +    if side_effector is not None:
  1.1836 +        method.side_effect = side_effector(mock)
  1.1837 +
  1.1838 +
  1.1839 +
  1.1840 +class MagicMixin(object):
  1.1841 +    def __init__(self, *args, **kw):
  1.1842 +        _super(MagicMixin, self).__init__(*args, **kw)
  1.1843 +        self._mock_set_magics()
  1.1844 +
  1.1845 +
  1.1846 +    def _mock_set_magics(self):
  1.1847 +        these_magics = _magics
  1.1848 +
  1.1849 +        if self._mock_methods is not None:
  1.1850 +            these_magics = _magics.intersection(self._mock_methods)
  1.1851 +
  1.1852 +            remove_magics = set()
  1.1853 +            remove_magics = _magics - these_magics
  1.1854 +
  1.1855 +            for entry in remove_magics:
  1.1856 +                if entry in type(self).__dict__:
  1.1857 +                    # remove unneeded magic methods
  1.1858 +                    delattr(self, entry)
  1.1859 +
  1.1860 +        # don't overwrite existing attributes if called a second time
  1.1861 +        these_magics = these_magics - set(type(self).__dict__)
  1.1862 +
  1.1863 +        _type = type(self)
  1.1864 +        for entry in these_magics:
  1.1865 +            setattr(_type, entry, MagicProxy(entry, self))
  1.1866 +
  1.1867 +
  1.1868 +
  1.1869 +class NonCallableMagicMock(MagicMixin, NonCallableMock):
  1.1870 +    """A version of `MagicMock` that isn't callable."""
  1.1871 +    def mock_add_spec(self, spec, spec_set=False):
  1.1872 +        """Add a spec to a mock. `spec` can either be an object or a
  1.1873 +        list of strings. Only attributes on the `spec` can be fetched as
  1.1874 +        attributes from the mock.
  1.1875 +
  1.1876 +        If `spec_set` is True then only attributes on the spec can be set."""
  1.1877 +        self._mock_add_spec(spec, spec_set)
  1.1878 +        self._mock_set_magics()
  1.1879 +
  1.1880 +
  1.1881 +
  1.1882 +class MagicMock(MagicMixin, Mock):
  1.1883 +    """
  1.1884 +    MagicMock is a subclass of Mock with default implementations
  1.1885 +    of most of the magic methods. You can use MagicMock without having to
  1.1886 +    configure the magic methods yourself.
  1.1887 +
  1.1888 +    If you use the `spec` or `spec_set` arguments then *only* magic
  1.1889 +    methods that exist in the spec will be created.
  1.1890 +
  1.1891 +    Attributes and the return value of a `MagicMock` will also be `MagicMocks`.
  1.1892 +    """
  1.1893 +    def mock_add_spec(self, spec, spec_set=False):
  1.1894 +        """Add a spec to a mock. `spec` can either be an object or a
  1.1895 +        list of strings. Only attributes on the `spec` can be fetched as
  1.1896 +        attributes from the mock.
  1.1897 +
  1.1898 +        If `spec_set` is True then only attributes on the spec can be set."""
  1.1899 +        self._mock_add_spec(spec, spec_set)
  1.1900 +        self._mock_set_magics()
  1.1901 +
  1.1902 +
  1.1903 +
  1.1904 +class MagicProxy(object):
  1.1905 +    def __init__(self, name, parent):
  1.1906 +        self.name = name
  1.1907 +        self.parent = parent
  1.1908 +
  1.1909 +    def __call__(self, *args, **kwargs):
  1.1910 +        m = self.create_mock()
  1.1911 +        return m(*args, **kwargs)
  1.1912 +
  1.1913 +    def create_mock(self):
  1.1914 +        entry = self.name
  1.1915 +        parent = self.parent
  1.1916 +        m = parent._get_child_mock(name=entry, _new_name=entry,
  1.1917 +                                   _new_parent=parent)
  1.1918 +        setattr(parent, entry, m)
  1.1919 +        _set_return_value(parent, m, entry)
  1.1920 +        return m
  1.1921 +
  1.1922 +    def __get__(self, obj, _type=None):
  1.1923 +        return self.create_mock()
  1.1924 +
  1.1925 +
  1.1926 +
  1.1927 +class _ANY(object):
  1.1928 +    "A helper object that compares equal to everything."
  1.1929 +
  1.1930 +    def __eq__(self, other):
  1.1931 +        return True
  1.1932 +
  1.1933 +    def __ne__(self, other):
  1.1934 +        return False
  1.1935 +
  1.1936 +    def __repr__(self):
  1.1937 +        return '<ANY>'
  1.1938 +
  1.1939 +ANY = _ANY()
  1.1940 +
  1.1941 +
  1.1942 +
  1.1943 +def _format_call_signature(name, args, kwargs):
  1.1944 +    message = '%s(%%s)' % name
  1.1945 +    formatted_args = ''
  1.1946 +    args_string = ', '.join([repr(arg) for arg in args])
  1.1947 +    kwargs_string = ', '.join([
  1.1948 +        '%s=%r' % (key, value) for key, value in kwargs.items()
  1.1949 +    ])
  1.1950 +    if args_string:
  1.1951 +        formatted_args = args_string
  1.1952 +    if kwargs_string:
  1.1953 +        if formatted_args:
  1.1954 +            formatted_args += ', '
  1.1955 +        formatted_args += kwargs_string
  1.1956 +
  1.1957 +    return message % formatted_args
  1.1958 +
  1.1959 +
  1.1960 +
  1.1961 +class _Call(tuple):
  1.1962 +    """
  1.1963 +    A tuple for holding the results of a call to a mock, either in the form
  1.1964 +    `(args, kwargs)` or `(name, args, kwargs)`.
  1.1965 +
  1.1966 +    If args or kwargs are empty then a call tuple will compare equal to
  1.1967 +    a tuple without those values. This makes comparisons less verbose::
  1.1968 +
  1.1969 +        _Call(('name', (), {})) == ('name',)
  1.1970 +        _Call(('name', (1,), {})) == ('name', (1,))
  1.1971 +        _Call(((), {'a': 'b'})) == ({'a': 'b'},)
  1.1972 +
  1.1973 +    The `_Call` object provides a useful shortcut for comparing with call::
  1.1974 +
  1.1975 +        _Call(((1, 2), {'a': 3})) == call(1, 2, a=3)
  1.1976 +        _Call(('foo', (1, 2), {'a': 3})) == call.foo(1, 2, a=3)
  1.1977 +
  1.1978 +    If the _Call has no name then it will match any name.
  1.1979 +    """
  1.1980 +    def __new__(cls, value=(), name=None, parent=None, two=False,
  1.1981 +                from_kall=True):
  1.1982 +        name = ''
  1.1983 +        args = ()
  1.1984 +        kwargs = {}
  1.1985 +        _len = len(value)
  1.1986 +        if _len == 3:
  1.1987 +            name, args, kwargs = value
  1.1988 +        elif _len == 2:
  1.1989 +            first, second = value
  1.1990 +            if isinstance(first, basestring):
  1.1991 +                name = first
  1.1992 +                if isinstance(second, tuple):
  1.1993 +                    args = second
  1.1994 +                else:
  1.1995 +                    kwargs = second
  1.1996 +            else:
  1.1997 +                args, kwargs = first, second
  1.1998 +        elif _len == 1:
  1.1999 +            value, = value
  1.2000 +            if isinstance(value, basestring):
  1.2001 +                name = value
  1.2002 +            elif isinstance(value, tuple):
  1.2003 +                args = value
  1.2004 +            else:
  1.2005 +                kwargs = value
  1.2006 +
  1.2007 +        if two:
  1.2008 +            return tuple.__new__(cls, (args, kwargs))
  1.2009 +
  1.2010 +        return tuple.__new__(cls, (name, args, kwargs))
  1.2011 +
  1.2012 +
  1.2013 +    def __init__(self, value=(), name=None, parent=None, two=False,
  1.2014 +                 from_kall=True):
  1.2015 +        self.name = name
  1.2016 +        self.parent = parent
  1.2017 +        self.from_kall = from_kall
  1.2018 +
  1.2019 +
  1.2020 +    def __eq__(self, other):
  1.2021 +        if other is ANY:
  1.2022 +            return True
  1.2023 +        try:
  1.2024 +            len_other = len(other)
  1.2025 +        except TypeError:
  1.2026 +            return False
  1.2027 +
  1.2028 +        self_name = ''
  1.2029 +        if len(self) == 2:
  1.2030 +            self_args, self_kwargs = self
  1.2031 +        else:
  1.2032 +            self_name, self_args, self_kwargs = self
  1.2033 +
  1.2034 +        other_name = ''
  1.2035 +        if len_other == 0:
  1.2036 +            other_args, other_kwargs = (), {}
  1.2037 +        elif len_other == 3:
  1.2038 +            other_name, other_args, other_kwargs = other
  1.2039 +        elif len_other == 1:
  1.2040 +            value, = other
  1.2041 +            if isinstance(value, tuple):
  1.2042 +                other_args = value
  1.2043 +                other_kwargs = {}
  1.2044 +            elif isinstance(value, basestring):
  1.2045 +                other_name = value
  1.2046 +                other_args, other_kwargs = (), {}
  1.2047 +            else:
  1.2048 +                other_args = ()
  1.2049 +                other_kwargs = value
  1.2050 +        else:
  1.2051 +            # len 2
  1.2052 +            # could be (name, args) or (name, kwargs) or (args, kwargs)
  1.2053 +            first, second = other
  1.2054 +            if isinstance(first, basestring):
  1.2055 +                other_name = first
  1.2056 +                if isinstance(second, tuple):
  1.2057 +                    other_args, other_kwargs = second, {}
  1.2058 +                else:
  1.2059 +                    other_args, other_kwargs = (), second
  1.2060 +            else:
  1.2061 +                other_args, other_kwargs = first, second
  1.2062 +
  1.2063 +        if self_name and other_name != self_name:
  1.2064 +            return False
  1.2065 +
  1.2066 +        # this order is important for ANY to work!
  1.2067 +        return (other_args, other_kwargs) == (self_args, self_kwargs)
  1.2068 +
  1.2069 +
  1.2070 +    def __ne__(self, other):
  1.2071 +        return not self.__eq__(other)
  1.2072 +
  1.2073 +
  1.2074 +    def __call__(self, *args, **kwargs):
  1.2075 +        if self.name is None:
  1.2076 +            return _Call(('', args, kwargs), name='()')
  1.2077 +
  1.2078 +        name = self.name + '()'
  1.2079 +        return _Call((self.name, args, kwargs), name=name, parent=self)
  1.2080 +
  1.2081 +
  1.2082 +    def __getattr__(self, attr):
  1.2083 +        if self.name is None:
  1.2084 +            return _Call(name=attr, from_kall=False)
  1.2085 +        name = '%s.%s' % (self.name, attr)
  1.2086 +        return _Call(name=name, parent=self, from_kall=False)
  1.2087 +
  1.2088 +
  1.2089 +    def __repr__(self):
  1.2090 +        if not self.from_kall:
  1.2091 +            name = self.name or 'call'
  1.2092 +            if name.startswith('()'):
  1.2093 +                name = 'call%s' % name
  1.2094 +            return name
  1.2095 +
  1.2096 +        if len(self) == 2:
  1.2097 +            name = 'call'
  1.2098 +            args, kwargs = self
  1.2099 +        else:
  1.2100 +            name, args, kwargs = self
  1.2101 +            if not name:
  1.2102 +                name = 'call'
  1.2103 +            elif not name.startswith('()'):
  1.2104 +                name = 'call.%s' % name
  1.2105 +            else:
  1.2106 +                name = 'call%s' % name
  1.2107 +        return _format_call_signature(name, args, kwargs)
  1.2108 +
  1.2109 +
  1.2110 +    def call_list(self):
  1.2111 +        """For a call object that represents multiple calls, `call_list`
  1.2112 +        returns a list of all the intermediate calls as well as the
  1.2113 +        final call."""
  1.2114 +        vals = []
  1.2115 +        thing = self
  1.2116 +        while thing is not None:
  1.2117 +            if thing.from_kall:
  1.2118 +                vals.append(thing)
  1.2119 +            thing = thing.parent
  1.2120 +        return _CallList(reversed(vals))
  1.2121 +
  1.2122 +
  1.2123 +call = _Call(from_kall=False)
  1.2124 +
  1.2125 +
  1.2126 +
  1.2127 +def create_autospec(spec, spec_set=False, instance=False, _parent=None,
  1.2128 +                    _name=None, **kwargs):
  1.2129 +    """Create a mock object using another object as a spec. Attributes on the
  1.2130 +    mock will use the corresponding attribute on the `spec` object as their
  1.2131 +    spec.
  1.2132 +
  1.2133 +    Functions or methods being mocked will have their arguments checked
  1.2134 +    to check that they are called with the correct signature.
  1.2135 +
  1.2136 +    If `spec_set` is True then attempting to set attributes that don't exist
  1.2137 +    on the spec object will raise an `AttributeError`.
  1.2138 +
  1.2139 +    If a class is used as a spec then the return value of the mock (the
  1.2140 +    instance of the class) will have the same spec. You can use a class as the
  1.2141 +    spec for an instance object by passing `instance=True`. The returned mock
  1.2142 +    will only be callable if instances of the mock are callable.
  1.2143 +
  1.2144 +    `create_autospec` also takes arbitrary keyword arguments that are passed to
  1.2145 +    the constructor of the created mock."""
  1.2146 +    if _is_list(spec):
  1.2147 +        # can't pass a list instance to the mock constructor as it will be
  1.2148 +        # interpreted as a list of strings
  1.2149 +        spec = type(spec)
  1.2150 +
  1.2151 +    is_type = isinstance(spec, ClassTypes)
  1.2152 +
  1.2153 +    _kwargs = {'spec': spec}
  1.2154 +    if spec_set:
  1.2155 +        _kwargs = {'spec_set': spec}
  1.2156 +    elif spec is None:
  1.2157 +        # None we mock with a normal mock without a spec
  1.2158 +        _kwargs = {}
  1.2159 +
  1.2160 +    _kwargs.update(kwargs)
  1.2161 +
  1.2162 +    Klass = MagicMock
  1.2163 +    if type(spec) in DescriptorTypes:
  1.2164 +        # descriptors don't have a spec
  1.2165 +        # because we don't know what type they return
  1.2166 +        _kwargs = {}
  1.2167 +    elif not _callable(spec):
  1.2168 +        Klass = NonCallableMagicMock
  1.2169 +    elif is_type and instance and not _instance_callable(spec):
  1.2170 +        Klass = NonCallableMagicMock
  1.2171 +
  1.2172 +    _new_name = _name
  1.2173 +    if _parent is None:
  1.2174 +        # for a top level object no _new_name should be set
  1.2175 +        _new_name = ''
  1.2176 +
  1.2177 +    mock = Klass(parent=_parent, _new_parent=_parent, _new_name=_new_name,
  1.2178 +                 name=_name, **_kwargs)
  1.2179 +
  1.2180 +    if isinstance(spec, FunctionTypes):
  1.2181 +        # should only happen at the top level because we don't
  1.2182 +        # recurse for functions
  1.2183 +        mock = _set_signature(mock, spec)
  1.2184 +    else:
  1.2185 +        _check_signature(spec, mock, is_type, instance)
  1.2186 +
  1.2187 +    if _parent is not None and not instance:
  1.2188 +        _parent._mock_children[_name] = mock
  1.2189 +
  1.2190 +    if is_type and not instance and 'return_value' not in kwargs:
  1.2191 +        mock.return_value = create_autospec(spec, spec_set, instance=True,
  1.2192 +                                            _name='()', _parent=mock)
  1.2193 +
  1.2194 +    for entry in dir(spec):
  1.2195 +        if _is_magic(entry):
  1.2196 +            # MagicMock already does the useful magic methods for us
  1.2197 +            continue
  1.2198 +
  1.2199 +        if isinstance(spec, FunctionTypes) and entry in FunctionAttributes:
  1.2200 +            # allow a mock to actually be a function
  1.2201 +            continue
  1.2202 +
  1.2203 +        # XXXX do we need a better way of getting attributes without
  1.2204 +        # triggering code execution (?) Probably not - we need the actual
  1.2205 +        # object to mock it so we would rather trigger a property than mock
  1.2206 +        # the property descriptor. Likewise we want to mock out dynamically
  1.2207 +        # provided attributes.
  1.2208 +        # XXXX what about attributes that raise exceptions other than
  1.2209 +        # AttributeError on being fetched?
  1.2210 +        # we could be resilient against it, or catch and propagate the
  1.2211 +        # exception when the attribute is fetched from the mock
  1.2212 +        try:
  1.2213 +            original = getattr(spec, entry)
  1.2214 +        except AttributeError:
  1.2215 +            continue
  1.2216 +
  1.2217 +        kwargs = {'spec': original}
  1.2218 +        if spec_set:
  1.2219 +            kwargs = {'spec_set': original}
  1.2220 +
  1.2221 +        if not isinstance(original, FunctionTypes):
  1.2222 +            new = _SpecState(original, spec_set, mock, entry, instance)
  1.2223 +            mock._mock_children[entry] = new
  1.2224 +        else:
  1.2225 +            parent = mock
  1.2226 +            if isinstance(spec, FunctionTypes):
  1.2227 +                parent = mock.mock
  1.2228 +
  1.2229 +            new = MagicMock(parent=parent, name=entry, _new_name=entry,
  1.2230 +                            _new_parent=parent, **kwargs)
  1.2231 +            mock._mock_children[entry] = new
  1.2232 +            skipfirst = _must_skip(spec, entry, is_type)
  1.2233 +            _check_signature(original, new, skipfirst=skipfirst)
  1.2234 +
  1.2235 +        # so functions created with _set_signature become instance attributes,
  1.2236 +        # *plus* their underlying mock exists in _mock_children of the parent
  1.2237 +        # mock. Adding to _mock_children may be unnecessary where we are also
  1.2238 +        # setting as an instance attribute?
  1.2239 +        if isinstance(new, FunctionTypes):
  1.2240 +            setattr(mock, entry, new)
  1.2241 +
  1.2242 +    return mock
  1.2243 +
  1.2244 +
  1.2245 +def _must_skip(spec, entry, is_type):
  1.2246 +    if not isinstance(spec, ClassTypes):
  1.2247 +        if entry in getattr(spec, '__dict__', {}):
  1.2248 +            # instance attribute - shouldn't skip
  1.2249 +            return False
  1.2250 +        spec = spec.__class__
  1.2251 +    if not hasattr(spec, '__mro__'):
  1.2252 +        # old style class: can't have descriptors anyway
  1.2253 +        return is_type
  1.2254 +
  1.2255 +    for klass in spec.__mro__:
  1.2256 +        result = klass.__dict__.get(entry, DEFAULT)
  1.2257 +        if result is DEFAULT:
  1.2258 +            continue
  1.2259 +        if isinstance(result, (staticmethod, classmethod)):
  1.2260 +            return False
  1.2261 +        return is_type
  1.2262 +
  1.2263 +    # shouldn't get here unless function is a dynamically provided attribute
  1.2264 +    # XXXX untested behaviour
  1.2265 +    return is_type
  1.2266 +
  1.2267 +
  1.2268 +def _get_class(obj):
  1.2269 +    try:
  1.2270 +        return obj.__class__
  1.2271 +    except AttributeError:
  1.2272 +        # in Python 2, _sre.SRE_Pattern objects have no __class__
  1.2273 +        return type(obj)
  1.2274 +
  1.2275 +
  1.2276 +class _SpecState(object):
  1.2277 +
  1.2278 +    def __init__(self, spec, spec_set=False, parent=None,
  1.2279 +                 name=None, ids=None, instance=False):
  1.2280 +        self.spec = spec
  1.2281 +        self.ids = ids
  1.2282 +        self.spec_set = spec_set
  1.2283 +        self.parent = parent
  1.2284 +        self.instance = instance
  1.2285 +        self.name = name
  1.2286 +
  1.2287 +
  1.2288 +FunctionTypes = (
  1.2289 +    # python function
  1.2290 +    type(create_autospec),
  1.2291 +    # instance method
  1.2292 +    type(ANY.__eq__),
  1.2293 +    # unbound method
  1.2294 +    type(_ANY.__eq__),
  1.2295 +)
  1.2296 +
  1.2297 +FunctionAttributes = set([
  1.2298 +    'func_closure',
  1.2299 +    'func_code',
  1.2300 +    'func_defaults',
  1.2301 +    'func_dict',
  1.2302 +    'func_doc',
  1.2303 +    'func_globals',
  1.2304 +    'func_name',
  1.2305 +])
  1.2306 +
  1.2307 +
  1.2308 +file_spec = None
  1.2309 +
  1.2310 +
  1.2311 +def mock_open(mock=None, read_data=''):
  1.2312 +    """
  1.2313 +    A helper function to create a mock to replace the use of `open`. It works
  1.2314 +    for `open` called directly or used as a context manager.
  1.2315 +
  1.2316 +    The `mock` argument is the mock object to configure. If `None` (the
  1.2317 +    default) then a `MagicMock` will be created for you, with the API limited
  1.2318 +    to methods or attributes available on standard file handles.
  1.2319 +
  1.2320 +    `read_data` is a string for the `read` method of the file handle to return.
  1.2321 +    This is an empty string by default.
  1.2322 +    """
  1.2323 +    global file_spec
  1.2324 +    if file_spec is None:
  1.2325 +        # set on first use
  1.2326 +        if inPy3k:
  1.2327 +            import _io
  1.2328 +            file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO))))
  1.2329 +        else:
  1.2330 +            file_spec = file
  1.2331 +
  1.2332 +    if mock is None:
  1.2333 +        mock = MagicMock(name='open', spec=open)
  1.2334 +
  1.2335 +    handle = MagicMock(spec=file_spec)
  1.2336 +    handle.write.return_value = None
  1.2337 +    handle.__enter__.return_value = handle
  1.2338 +    handle.read.return_value = read_data
  1.2339 +
  1.2340 +    mock.return_value = handle
  1.2341 +    return mock
  1.2342 +
  1.2343 +
  1.2344 +class PropertyMock(Mock):
  1.2345 +    """
  1.2346 +    A mock intended to be used as a property, or other descriptor, on a class.
  1.2347 +    `PropertyMock` provides `__get__` and `__set__` methods so you can specify
  1.2348 +    a return value when it is fetched.
  1.2349 +
  1.2350 +    Fetching a `PropertyMock` instance from an object calls the mock, with
  1.2351 +    no args. Setting it calls the mock with the value being set.
  1.2352 +    """
  1.2353 +    def _get_child_mock(self, **kwargs):
  1.2354 +        return MagicMock(**kwargs)
  1.2355 +
  1.2356 +    def __get__(self, obj, obj_type):
  1.2357 +        return self()
  1.2358 +    def __set__(self, obj, val):
  1.2359 +        self(val)

mercurial