python/mock-1.0.0/html/_sources/mock.txt

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/python/mock-1.0.0/html/_sources/mock.txt	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,842 @@
     1.4 +The Mock Class
     1.5 +==============
     1.6 +
     1.7 +.. currentmodule:: mock
     1.8 +
     1.9 +.. testsetup::
    1.10 +
    1.11 +    class SomeClass:
    1.12 +        pass
    1.13 +
    1.14 +
    1.15 +`Mock` is a flexible mock object intended to replace the use of stubs and
    1.16 +test doubles throughout your code. Mocks are callable and create attributes as
    1.17 +new mocks when you access them [#]_. Accessing the same attribute will always
    1.18 +return the same mock. Mocks record how you use them, allowing you to make
    1.19 +assertions about what your code has done to them.
    1.20 +
    1.21 +:class:`MagicMock` is a subclass of `Mock` with all the magic methods
    1.22 +pre-created and ready to use. There are also non-callable variants, useful
    1.23 +when you are mocking out objects that aren't callable:
    1.24 +:class:`NonCallableMock` and :class:`NonCallableMagicMock`
    1.25 +
    1.26 +The :func:`patch` decorators makes it easy to temporarily replace classes
    1.27 +in a particular module with a `Mock` object. By default `patch` will create
    1.28 +a `MagicMock` for you. You can specify an alternative class of `Mock` using
    1.29 +the `new_callable` argument to `patch`.
    1.30 +
    1.31 +
    1.32 +.. index:: side_effect
    1.33 +.. index:: return_value
    1.34 +.. index:: wraps
    1.35 +.. index:: name
    1.36 +.. index:: spec
    1.37 +
    1.38 +.. class:: Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, **kwargs)
    1.39 +
    1.40 +    Create a new `Mock` object. `Mock` takes several optional arguments
    1.41 +    that specify the behaviour of the Mock object:
    1.42 +
    1.43 +    * `spec`: This can be either a list of strings or an existing object (a
    1.44 +      class or instance) that acts as the specification for the mock object. If
    1.45 +      you pass in an object then a list of strings is formed by calling dir on
    1.46 +      the object (excluding unsupported magic attributes and methods).
    1.47 +      Accessing any attribute not in this list will raise an `AttributeError`.
    1.48 +
    1.49 +      If `spec` is an object (rather than a list of strings) then
    1.50 +      :attr:`__class__` returns the class of the spec object. This allows mocks
    1.51 +      to pass `isinstance` tests.
    1.52 +
    1.53 +    * `spec_set`: A stricter variant of `spec`. If used, attempting to *set*
    1.54 +      or get an attribute on the mock that isn't on the object passed as
    1.55 +      `spec_set` will raise an `AttributeError`.
    1.56 +
    1.57 +    * `side_effect`: A function to be called whenever the Mock is called. See
    1.58 +      the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or
    1.59 +      dynamically changing return values. The function is called with the same
    1.60 +      arguments as the mock, and unless it returns :data:`DEFAULT`, the return
    1.61 +      value of this function is used as the return value.
    1.62 +
    1.63 +      Alternatively `side_effect` can be an exception class or instance. In
    1.64 +      this case the exception will be raised when the mock is called.
    1.65 +
    1.66 +      If `side_effect` is an iterable then each call to the mock will return
    1.67 +      the next value from the iterable. If any of the members of the iterable
    1.68 +      are exceptions they will be raised instead of returned.
    1.69 +
    1.70 +      A `side_effect` can be cleared by setting it to `None`.
    1.71 +
    1.72 +    * `return_value`: The value returned when the mock is called. By default
    1.73 +      this is a new Mock (created on first access). See the
    1.74 +      :attr:`return_value` attribute.
    1.75 +
    1.76 +    * `wraps`: Item for the mock object to wrap. If `wraps` is not None then
    1.77 +      calling the Mock will pass the call through to the wrapped object
    1.78 +      (returning the real result and ignoring `return_value`). Attribute access
    1.79 +      on the mock will return a Mock object that wraps the corresponding
    1.80 +      attribute of the wrapped object (so attempting to access an attribute
    1.81 +      that doesn't exist will raise an `AttributeError`).
    1.82 +
    1.83 +      If the mock has an explicit `return_value` set then calls are not passed
    1.84 +      to the wrapped object and the `return_value` is returned instead.
    1.85 +
    1.86 +    * `name`: If the mock has a name then it will be used in the repr of the
    1.87 +      mock. This can be useful for debugging. The name is propagated to child
    1.88 +      mocks.
    1.89 +
    1.90 +    Mocks can also be called with arbitrary keyword arguments. These will be
    1.91 +    used to set attributes on the mock after it is created. See the
    1.92 +    :meth:`configure_mock` method for details.
    1.93 +
    1.94 +
    1.95 +    .. method:: assert_called_with(*args, **kwargs)
    1.96 +
    1.97 +        This method is a convenient way of asserting that calls are made in a
    1.98 +        particular way:
    1.99 +
   1.100 +        .. doctest::
   1.101 +
   1.102 +            >>> mock = Mock()
   1.103 +            >>> mock.method(1, 2, 3, test='wow')
   1.104 +            <Mock name='mock.method()' id='...'>
   1.105 +            >>> mock.method.assert_called_with(1, 2, 3, test='wow')
   1.106 +
   1.107 +
   1.108 +    .. method:: assert_called_once_with(*args, **kwargs)
   1.109 +
   1.110 +       Assert that the mock was called exactly once and with the specified
   1.111 +       arguments.
   1.112 +
   1.113 +       .. doctest::
   1.114 +
   1.115 +            >>> mock = Mock(return_value=None)
   1.116 +            >>> mock('foo', bar='baz')
   1.117 +            >>> mock.assert_called_once_with('foo', bar='baz')
   1.118 +            >>> mock('foo', bar='baz')
   1.119 +            >>> mock.assert_called_once_with('foo', bar='baz')
   1.120 +            Traceback (most recent call last):
   1.121 +              ...
   1.122 +            AssertionError: Expected to be called once. Called 2 times.
   1.123 +
   1.124 +
   1.125 +    .. method:: assert_any_call(*args, **kwargs)
   1.126 +
   1.127 +        assert the mock has been called with the specified arguments.
   1.128 +
   1.129 +        The assert passes if the mock has *ever* been called, unlike
   1.130 +        :meth:`assert_called_with` and :meth:`assert_called_once_with` that
   1.131 +        only pass if the call is the most recent one.
   1.132 +
   1.133 +        .. doctest::
   1.134 +
   1.135 +            >>> mock = Mock(return_value=None)
   1.136 +            >>> mock(1, 2, arg='thing')
   1.137 +            >>> mock('some', 'thing', 'else')
   1.138 +            >>> mock.assert_any_call(1, 2, arg='thing')
   1.139 +
   1.140 +
   1.141 +    .. method:: assert_has_calls(calls, any_order=False)
   1.142 +
   1.143 +        assert the mock has been called with the specified calls.
   1.144 +        The `mock_calls` list is checked for the calls.
   1.145 +
   1.146 +        If `any_order` is False (the default) then the calls must be
   1.147 +        sequential. There can be extra calls before or after the
   1.148 +        specified calls.
   1.149 +
   1.150 +        If `any_order` is True then the calls can be in any order, but
   1.151 +        they must all appear in :attr:`mock_calls`.
   1.152 +
   1.153 +        .. doctest::
   1.154 +
   1.155 +            >>> mock = Mock(return_value=None)
   1.156 +            >>> mock(1)
   1.157 +            >>> mock(2)
   1.158 +            >>> mock(3)
   1.159 +            >>> mock(4)
   1.160 +            >>> calls = [call(2), call(3)]
   1.161 +            >>> mock.assert_has_calls(calls)
   1.162 +            >>> calls = [call(4), call(2), call(3)]
   1.163 +            >>> mock.assert_has_calls(calls, any_order=True)
   1.164 +
   1.165 +
   1.166 +    .. method:: reset_mock()
   1.167 +
   1.168 +        The reset_mock method resets all the call attributes on a mock object:
   1.169 +
   1.170 +        .. doctest::
   1.171 +
   1.172 +            >>> mock = Mock(return_value=None)
   1.173 +            >>> mock('hello')
   1.174 +            >>> mock.called
   1.175 +            True
   1.176 +            >>> mock.reset_mock()
   1.177 +            >>> mock.called
   1.178 +            False
   1.179 +
   1.180 +        This can be useful where you want to make a series of assertions that
   1.181 +        reuse the same object. Note that `reset_mock` *doesn't* clear the
   1.182 +        return value, :attr:`side_effect` or any child attributes you have
   1.183 +        set using normal assignment. Child mocks and the return value mock
   1.184 +        (if any) are reset as well.
   1.185 +
   1.186 +
   1.187 +    .. method:: mock_add_spec(spec, spec_set=False)
   1.188 +
   1.189 +        Add a spec to a mock. `spec` can either be an object or a
   1.190 +        list of strings. Only attributes on the `spec` can be fetched as
   1.191 +        attributes from the mock.
   1.192 +
   1.193 +        If `spec_set` is `True` then only attributes on the spec can be set.
   1.194 +
   1.195 +
   1.196 +    .. method:: attach_mock(mock, attribute)
   1.197 +
   1.198 +        Attach a mock as an attribute of this one, replacing its name and
   1.199 +        parent. Calls to the attached mock will be recorded in the
   1.200 +        :attr:`method_calls` and :attr:`mock_calls` attributes of this one.
   1.201 +
   1.202 +
   1.203 +    .. method:: configure_mock(**kwargs)
   1.204 +
   1.205 +        Set attributes on the mock through keyword arguments.
   1.206 +
   1.207 +        Attributes plus return values and side effects can be set on child
   1.208 +        mocks using standard dot notation and unpacking a dictionary in the
   1.209 +        method call:
   1.210 +
   1.211 +        .. doctest::
   1.212 +
   1.213 +            >>> mock = Mock()
   1.214 +            >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
   1.215 +            >>> mock.configure_mock(**attrs)
   1.216 +            >>> mock.method()
   1.217 +            3
   1.218 +            >>> mock.other()
   1.219 +            Traceback (most recent call last):
   1.220 +              ...
   1.221 +            KeyError
   1.222 +
   1.223 +        The same thing can be achieved in the constructor call to mocks:
   1.224 +
   1.225 +        .. doctest::
   1.226 +
   1.227 +            >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
   1.228 +            >>> mock = Mock(some_attribute='eggs', **attrs)
   1.229 +            >>> mock.some_attribute
   1.230 +            'eggs'
   1.231 +            >>> mock.method()
   1.232 +            3
   1.233 +            >>> mock.other()
   1.234 +            Traceback (most recent call last):
   1.235 +              ...
   1.236 +            KeyError
   1.237 +
   1.238 +        `configure_mock` exists to make it easier to do configuration
   1.239 +        after the mock has been created.
   1.240 +
   1.241 +
   1.242 +    .. method:: __dir__()
   1.243 +
   1.244 +        `Mock` objects limit the results of `dir(some_mock)` to useful results.
   1.245 +        For mocks with a `spec` this includes all the permitted attributes
   1.246 +        for the mock.
   1.247 +
   1.248 +        See :data:`FILTER_DIR` for what this filtering does, and how to
   1.249 +        switch it off.
   1.250 +
   1.251 +
   1.252 +    .. method:: _get_child_mock(**kw)
   1.253 +
   1.254 +        Create the child mocks for attributes and return value.
   1.255 +        By default child mocks will be the same type as the parent.
   1.256 +        Subclasses of Mock may want to override this to customize the way
   1.257 +        child mocks are made.
   1.258 +
   1.259 +        For non-callable mocks the callable variant will be used (rather than
   1.260 +        any custom subclass).
   1.261 +
   1.262 +
   1.263 +    .. attribute:: called
   1.264 +
   1.265 +        A boolean representing whether or not the mock object has been called:
   1.266 +
   1.267 +        .. doctest::
   1.268 +
   1.269 +            >>> mock = Mock(return_value=None)
   1.270 +            >>> mock.called
   1.271 +            False
   1.272 +            >>> mock()
   1.273 +            >>> mock.called
   1.274 +            True
   1.275 +
   1.276 +    .. attribute:: call_count
   1.277 +
   1.278 +        An integer telling you how many times the mock object has been called:
   1.279 +
   1.280 +        .. doctest::
   1.281 +
   1.282 +            >>> mock = Mock(return_value=None)
   1.283 +            >>> mock.call_count
   1.284 +            0
   1.285 +            >>> mock()
   1.286 +            >>> mock()
   1.287 +            >>> mock.call_count
   1.288 +            2
   1.289 +
   1.290 +
   1.291 +    .. attribute:: return_value
   1.292 +
   1.293 +        Set this to configure the value returned by calling the mock:
   1.294 +
   1.295 +        .. doctest::
   1.296 +
   1.297 +            >>> mock = Mock()
   1.298 +            >>> mock.return_value = 'fish'
   1.299 +            >>> mock()
   1.300 +            'fish'
   1.301 +
   1.302 +        The default return value is a mock object and you can configure it in
   1.303 +        the normal way:
   1.304 +
   1.305 +        .. doctest::
   1.306 +
   1.307 +            >>> mock = Mock()
   1.308 +            >>> mock.return_value.attribute = sentinel.Attribute
   1.309 +            >>> mock.return_value()
   1.310 +            <Mock name='mock()()' id='...'>
   1.311 +            >>> mock.return_value.assert_called_with()
   1.312 +
   1.313 +        `return_value` can also be set in the constructor:
   1.314 +
   1.315 +        .. doctest::
   1.316 +
   1.317 +            >>> mock = Mock(return_value=3)
   1.318 +            >>> mock.return_value
   1.319 +            3
   1.320 +            >>> mock()
   1.321 +            3
   1.322 +
   1.323 +
   1.324 +    .. attribute:: side_effect
   1.325 +
   1.326 +        This can either be a function to be called when the mock is called,
   1.327 +        or an exception (class or instance) to be raised.
   1.328 +
   1.329 +        If you pass in a function it will be called with same arguments as the
   1.330 +        mock and unless the function returns the :data:`DEFAULT` singleton the
   1.331 +        call to the mock will then return whatever the function returns. If the
   1.332 +        function returns :data:`DEFAULT` then the mock will return its normal
   1.333 +        value (from the :attr:`return_value`.
   1.334 +
   1.335 +        An example of a mock that raises an exception (to test exception
   1.336 +        handling of an API):
   1.337 +
   1.338 +        .. doctest::
   1.339 +
   1.340 +            >>> mock = Mock()
   1.341 +            >>> mock.side_effect = Exception('Boom!')
   1.342 +            >>> mock()
   1.343 +            Traceback (most recent call last):
   1.344 +              ...
   1.345 +            Exception: Boom!
   1.346 +
   1.347 +        Using `side_effect` to return a sequence of values:
   1.348 +
   1.349 +        .. doctest::
   1.350 +
   1.351 +            >>> mock = Mock()
   1.352 +            >>> mock.side_effect = [3, 2, 1]
   1.353 +            >>> mock(), mock(), mock()
   1.354 +            (3, 2, 1)
   1.355 +
   1.356 +        The `side_effect` function is called with the same arguments as the
   1.357 +        mock (so it is wise for it to take arbitrary args and keyword
   1.358 +        arguments) and whatever it returns is used as the return value for
   1.359 +        the call. The exception is if `side_effect` returns :data:`DEFAULT`,
   1.360 +        in which case the normal :attr:`return_value` is used.
   1.361 +
   1.362 +        .. doctest::
   1.363 +
   1.364 +            >>> mock = Mock(return_value=3)
   1.365 +            >>> def side_effect(*args, **kwargs):
   1.366 +            ...     return DEFAULT
   1.367 +            ...
   1.368 +            >>> mock.side_effect = side_effect
   1.369 +            >>> mock()
   1.370 +            3
   1.371 +
   1.372 +        `side_effect` can be set in the constructor. Here's an example that
   1.373 +        adds one to the value the mock is called with and returns it:
   1.374 +
   1.375 +        .. doctest::
   1.376 +
   1.377 +            >>> side_effect = lambda value: value + 1
   1.378 +            >>> mock = Mock(side_effect=side_effect)
   1.379 +            >>> mock(3)
   1.380 +            4
   1.381 +            >>> mock(-8)
   1.382 +            -7
   1.383 +
   1.384 +        Setting `side_effect` to `None` clears it:
   1.385 +
   1.386 +        .. doctest::
   1.387 +
   1.388 +            >>> from mock import Mock
   1.389 +            >>> m = Mock(side_effect=KeyError, return_value=3)
   1.390 +            >>> m()
   1.391 +            Traceback (most recent call last):
   1.392 +             ...
   1.393 +            KeyError
   1.394 +            >>> m.side_effect = None
   1.395 +            >>> m()
   1.396 +            3
   1.397 +
   1.398 +
   1.399 +    .. attribute:: call_args
   1.400 +
   1.401 +        This is either `None` (if the mock hasn't been called), or the
   1.402 +        arguments that the mock was last called with. This will be in the
   1.403 +        form of a tuple: the first member is any ordered arguments the mock
   1.404 +        was called with (or an empty tuple) and the second member is any
   1.405 +        keyword arguments (or an empty dictionary).
   1.406 +
   1.407 +        .. doctest::
   1.408 +
   1.409 +            >>> mock = Mock(return_value=None)
   1.410 +            >>> print mock.call_args
   1.411 +            None
   1.412 +            >>> mock()
   1.413 +            >>> mock.call_args
   1.414 +            call()
   1.415 +            >>> mock.call_args == ()
   1.416 +            True
   1.417 +            >>> mock(3, 4)
   1.418 +            >>> mock.call_args
   1.419 +            call(3, 4)
   1.420 +            >>> mock.call_args == ((3, 4),)
   1.421 +            True
   1.422 +            >>> mock(3, 4, 5, key='fish', next='w00t!')
   1.423 +            >>> mock.call_args
   1.424 +            call(3, 4, 5, key='fish', next='w00t!')
   1.425 +
   1.426 +        `call_args`, along with members of the lists :attr:`call_args_list`,
   1.427 +        :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects.
   1.428 +        These are tuples, so they can be unpacked to get at the individual
   1.429 +        arguments and make more complex assertions. See
   1.430 +        :ref:`calls as tuples <calls-as-tuples>`.
   1.431 +
   1.432 +
   1.433 +    .. attribute:: call_args_list
   1.434 +
   1.435 +        This is a list of all the calls made to the mock object in sequence
   1.436 +        (so the length of the list is the number of times it has been
   1.437 +        called). Before any calls have been made it is an empty list. The
   1.438 +        :data:`call` object can be used for conveniently constructing lists of
   1.439 +        calls to compare with `call_args_list`.
   1.440 +
   1.441 +        .. doctest::
   1.442 +
   1.443 +            >>> mock = Mock(return_value=None)
   1.444 +            >>> mock()
   1.445 +            >>> mock(3, 4)
   1.446 +            >>> mock(key='fish', next='w00t!')
   1.447 +            >>> mock.call_args_list
   1.448 +            [call(), call(3, 4), call(key='fish', next='w00t!')]
   1.449 +            >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
   1.450 +            >>> mock.call_args_list == expected
   1.451 +            True
   1.452 +
   1.453 +        Members of `call_args_list` are :data:`call` objects. These can be
   1.454 +        unpacked as tuples to get at the individual arguments. See
   1.455 +        :ref:`calls as tuples <calls-as-tuples>`.
   1.456 +
   1.457 +
   1.458 +    .. attribute:: method_calls
   1.459 +
   1.460 +        As well as tracking calls to themselves, mocks also track calls to
   1.461 +        methods and attributes, and *their* methods and attributes:
   1.462 +
   1.463 +        .. doctest::
   1.464 +
   1.465 +            >>> mock = Mock()
   1.466 +            >>> mock.method()
   1.467 +            <Mock name='mock.method()' id='...'>
   1.468 +            >>> mock.property.method.attribute()
   1.469 +            <Mock name='mock.property.method.attribute()' id='...'>
   1.470 +            >>> mock.method_calls
   1.471 +            [call.method(), call.property.method.attribute()]
   1.472 +
   1.473 +        Members of `method_calls` are :data:`call` objects. These can be
   1.474 +        unpacked as tuples to get at the individual arguments. See
   1.475 +        :ref:`calls as tuples <calls-as-tuples>`.
   1.476 +
   1.477 +
   1.478 +    .. attribute:: mock_calls
   1.479 +
   1.480 +        `mock_calls` records *all* calls to the mock object, its methods, magic
   1.481 +        methods *and* return value mocks.
   1.482 +
   1.483 +        .. doctest::
   1.484 +
   1.485 +            >>> mock = MagicMock()
   1.486 +            >>> result = mock(1, 2, 3)
   1.487 +            >>> mock.first(a=3)
   1.488 +            <MagicMock name='mock.first()' id='...'>
   1.489 +            >>> mock.second()
   1.490 +            <MagicMock name='mock.second()' id='...'>
   1.491 +            >>> int(mock)
   1.492 +            1
   1.493 +            >>> result(1)
   1.494 +            <MagicMock name='mock()()' id='...'>
   1.495 +            >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
   1.496 +            ... call.__int__(), call()(1)]
   1.497 +            >>> mock.mock_calls == expected
   1.498 +            True
   1.499 +
   1.500 +        Members of `mock_calls` are :data:`call` objects. These can be
   1.501 +        unpacked as tuples to get at the individual arguments. See
   1.502 +        :ref:`calls as tuples <calls-as-tuples>`.
   1.503 +
   1.504 +
   1.505 +    .. attribute:: __class__
   1.506 +
   1.507 +        Normally the `__class__` attribute of an object will return its type.
   1.508 +        For a mock object with a `spec` `__class__` returns the spec class
   1.509 +        instead. This allows mock objects to pass `isinstance` tests for the
   1.510 +        object they are replacing / masquerading as:
   1.511 +
   1.512 +        .. doctest::
   1.513 +
   1.514 +            >>> mock = Mock(spec=3)
   1.515 +            >>> isinstance(mock, int)
   1.516 +            True
   1.517 +
   1.518 +        `__class__` is assignable to, this allows a mock to pass an
   1.519 +        `isinstance` check without forcing you to use a spec:
   1.520 +
   1.521 +        .. doctest::
   1.522 +
   1.523 +            >>> mock = Mock()
   1.524 +            >>> mock.__class__ = dict
   1.525 +            >>> isinstance(mock, dict)
   1.526 +            True
   1.527 +
   1.528 +.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
   1.529 +
   1.530 +    A non-callable version of `Mock`. The constructor parameters have the same
   1.531 +    meaning of `Mock`, with the exception of `return_value` and `side_effect`
   1.532 +    which have no meaning on a non-callable mock.
   1.533 +
   1.534 +Mock objects that use a class or an instance as a `spec` or `spec_set` are able
   1.535 +to pass `isintance` tests:
   1.536 +
   1.537 +.. doctest::
   1.538 +
   1.539 +    >>> mock = Mock(spec=SomeClass)
   1.540 +    >>> isinstance(mock, SomeClass)
   1.541 +    True
   1.542 +    >>> mock = Mock(spec_set=SomeClass())
   1.543 +    >>> isinstance(mock, SomeClass)
   1.544 +    True
   1.545 +
   1.546 +The `Mock` classes have support for mocking magic methods. See :ref:`magic
   1.547 +methods <magic-methods>` for the full details.
   1.548 +
   1.549 +The mock classes and the :func:`patch` decorators all take arbitrary keyword
   1.550 +arguments for configuration. For the `patch` decorators the keywords are
   1.551 +passed to the constructor of the mock being created. The keyword arguments
   1.552 +are for configuring attributes of the mock:
   1.553 +
   1.554 +.. doctest::
   1.555 +
   1.556 +        >>> m = MagicMock(attribute=3, other='fish')
   1.557 +        >>> m.attribute
   1.558 +        3
   1.559 +        >>> m.other
   1.560 +        'fish'
   1.561 +
   1.562 +The return value and side effect of child mocks can be set in the same way,
   1.563 +using dotted notation. As you can't use dotted names directly in a call you
   1.564 +have to create a dictionary and unpack it using `**`:
   1.565 +
   1.566 +.. doctest::
   1.567 +
   1.568 +    >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
   1.569 +    >>> mock = Mock(some_attribute='eggs', **attrs)
   1.570 +    >>> mock.some_attribute
   1.571 +    'eggs'
   1.572 +    >>> mock.method()
   1.573 +    3
   1.574 +    >>> mock.other()
   1.575 +    Traceback (most recent call last):
   1.576 +      ...
   1.577 +    KeyError
   1.578 +
   1.579 +
   1.580 +.. class:: PropertyMock(*args, **kwargs)
   1.581 +
   1.582 +   A mock intended to be used as a property, or other descriptor, on a class.
   1.583 +   `PropertyMock` provides `__get__` and `__set__` methods so you can specify
   1.584 +   a return value when it is fetched.
   1.585 +
   1.586 +   Fetching a `PropertyMock` instance from an object calls the mock, with
   1.587 +   no args. Setting it calls the mock with the value being set.
   1.588 +
   1.589 +   .. doctest::
   1.590 +
   1.591 +        >>> class Foo(object):
   1.592 +        ...     @property
   1.593 +        ...     def foo(self):
   1.594 +        ...         return 'something'
   1.595 +        ...     @foo.setter
   1.596 +        ...     def foo(self, value):
   1.597 +        ...         pass
   1.598 +        ...
   1.599 +        >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
   1.600 +        ...     mock_foo.return_value = 'mockity-mock'
   1.601 +        ...     this_foo = Foo()
   1.602 +        ...     print this_foo.foo
   1.603 +        ...     this_foo.foo = 6
   1.604 +        ...
   1.605 +        mockity-mock
   1.606 +        >>> mock_foo.mock_calls
   1.607 +        [call(), call(6)]
   1.608 +
   1.609 +Because of the way mock attributes are stored you can't directly attach a
   1.610 +`PropertyMock` to a mock object. Instead you can attach it to the mock type
   1.611 +object:
   1.612 +
   1.613 +.. doctest::
   1.614 +
   1.615 +    >>> m = MagicMock()
   1.616 +    >>> p = PropertyMock(return_value=3)
   1.617 +    >>> type(m).foo = p
   1.618 +    >>> m.foo
   1.619 +    3
   1.620 +    >>> p.assert_called_once_with()
   1.621 +
   1.622 +
   1.623 +.. index:: __call__
   1.624 +.. index:: calling
   1.625 +
   1.626 +Calling
   1.627 +=======
   1.628 +
   1.629 +Mock objects are callable. The call will return the value set as the
   1.630 +:attr:`~Mock.return_value` attribute. The default return value is a new Mock
   1.631 +object; it is created the first time the return value is accessed (either
   1.632 +explicitly or by calling the Mock) - but it is stored and the same one
   1.633 +returned each time.
   1.634 +
   1.635 +Calls made to the object will be recorded in the attributes
   1.636 +like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
   1.637 +
   1.638 +If :attr:`~Mock.side_effect` is set then it will be called after the call has
   1.639 +been recorded, so if `side_effect` raises an exception the call is still
   1.640 +recorded.
   1.641 +
   1.642 +The simplest way to make a mock raise an exception when called is to make
   1.643 +:attr:`~Mock.side_effect` an exception class or instance:
   1.644 +
   1.645 +.. doctest::
   1.646 +
   1.647 +        >>> m = MagicMock(side_effect=IndexError)
   1.648 +        >>> m(1, 2, 3)
   1.649 +        Traceback (most recent call last):
   1.650 +          ...
   1.651 +        IndexError
   1.652 +        >>> m.mock_calls
   1.653 +        [call(1, 2, 3)]
   1.654 +        >>> m.side_effect = KeyError('Bang!')
   1.655 +        >>> m('two', 'three', 'four')
   1.656 +        Traceback (most recent call last):
   1.657 +          ...
   1.658 +        KeyError: 'Bang!'
   1.659 +        >>> m.mock_calls
   1.660 +        [call(1, 2, 3), call('two', 'three', 'four')]
   1.661 +
   1.662 +If `side_effect` is a function then whatever that function returns is what
   1.663 +calls to the mock return. The `side_effect` function is called with the
   1.664 +same arguments as the mock. This allows you to vary the return value of the
   1.665 +call dynamically, based on the input:
   1.666 +
   1.667 +.. doctest::
   1.668 +
   1.669 +        >>> def side_effect(value):
   1.670 +        ...     return value + 1
   1.671 +        ...
   1.672 +        >>> m = MagicMock(side_effect=side_effect)
   1.673 +        >>> m(1)
   1.674 +        2
   1.675 +        >>> m(2)
   1.676 +        3
   1.677 +        >>> m.mock_calls
   1.678 +        [call(1), call(2)]
   1.679 +
   1.680 +If you want the mock to still return the default return value (a new mock), or
   1.681 +any set return value, then there are two ways of doing this. Either return
   1.682 +`mock.return_value` from inside `side_effect`, or return :data:`DEFAULT`:
   1.683 +
   1.684 +.. doctest::
   1.685 +
   1.686 +        >>> m = MagicMock()
   1.687 +        >>> def side_effect(*args, **kwargs):
   1.688 +        ...     return m.return_value
   1.689 +        ...
   1.690 +        >>> m.side_effect = side_effect
   1.691 +        >>> m.return_value = 3
   1.692 +        >>> m()
   1.693 +        3
   1.694 +        >>> def side_effect(*args, **kwargs):
   1.695 +        ...     return DEFAULT
   1.696 +        ...
   1.697 +        >>> m.side_effect = side_effect
   1.698 +        >>> m()
   1.699 +        3
   1.700 +
   1.701 +To remove a `side_effect`, and return to the default behaviour, set the
   1.702 +`side_effect` to `None`:
   1.703 +
   1.704 +.. doctest::
   1.705 +
   1.706 +        >>> m = MagicMock(return_value=6)
   1.707 +        >>> def side_effect(*args, **kwargs):
   1.708 +        ...     return 3
   1.709 +        ...
   1.710 +        >>> m.side_effect = side_effect
   1.711 +        >>> m()
   1.712 +        3
   1.713 +        >>> m.side_effect = None
   1.714 +        >>> m()
   1.715 +        6
   1.716 +
   1.717 +The `side_effect` can also be any iterable object. Repeated calls to the mock
   1.718 +will return values from the iterable (until the iterable is exhausted and
   1.719 +a `StopIteration` is raised):
   1.720 +
   1.721 +.. doctest::
   1.722 +
   1.723 +        >>> m = MagicMock(side_effect=[1, 2, 3])
   1.724 +        >>> m()
   1.725 +        1
   1.726 +        >>> m()
   1.727 +        2
   1.728 +        >>> m()
   1.729 +        3
   1.730 +        >>> m()
   1.731 +        Traceback (most recent call last):
   1.732 +          ...
   1.733 +        StopIteration
   1.734 +
   1.735 +If any members of the iterable are exceptions they will be raised instead of
   1.736 +returned:
   1.737 +
   1.738 +.. doctest::
   1.739 +
   1.740 +        >>> iterable = (33, ValueError, 66)
   1.741 +        >>> m = MagicMock(side_effect=iterable)
   1.742 +        >>> m()
   1.743 +        33
   1.744 +        >>> m()
   1.745 +        Traceback (most recent call last):
   1.746 +         ...
   1.747 +        ValueError
   1.748 +        >>> m()
   1.749 +        66
   1.750 +
   1.751 +
   1.752 +.. _deleting-attributes:
   1.753 +
   1.754 +Deleting Attributes
   1.755 +===================
   1.756 +
   1.757 +Mock objects create attributes on demand. This allows them to pretend to be
   1.758 +objects of any type.
   1.759 +
   1.760 +You may want a mock object to return `False` to a `hasattr` call, or raise an
   1.761 +`AttributeError` when an attribute is fetched. You can do this by providing
   1.762 +an object as a `spec` for a mock, but that isn't always convenient.
   1.763 +
   1.764 +You "block" attributes by deleting them. Once deleted, accessing an attribute
   1.765 +will raise an `AttributeError`.
   1.766 +
   1.767 +.. doctest::
   1.768 +
   1.769 +    >>> mock = MagicMock()
   1.770 +    >>> hasattr(mock, 'm')
   1.771 +    True
   1.772 +    >>> del mock.m
   1.773 +    >>> hasattr(mock, 'm')
   1.774 +    False
   1.775 +    >>> del mock.f
   1.776 +    >>> mock.f
   1.777 +    Traceback (most recent call last):
   1.778 +        ...
   1.779 +    AttributeError: f
   1.780 +
   1.781 +
   1.782 +Attaching Mocks as Attributes
   1.783 +=============================
   1.784 +
   1.785 +When you attach a mock as an attribute of another mock (or as the return
   1.786 +value) it becomes a "child" of that mock. Calls to the child are recorded in
   1.787 +the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
   1.788 +parent. This is useful for configuring child mocks and then attaching them to
   1.789 +the parent, or for attaching mocks to a parent that records all calls to the
   1.790 +children and allows you to make assertions about the order of calls between
   1.791 +mocks:
   1.792 +
   1.793 +.. doctest::
   1.794 +
   1.795 +    >>> parent = MagicMock()
   1.796 +    >>> child1 = MagicMock(return_value=None)
   1.797 +    >>> child2 = MagicMock(return_value=None)
   1.798 +    >>> parent.child1 = child1
   1.799 +    >>> parent.child2 = child2
   1.800 +    >>> child1(1)
   1.801 +    >>> child2(2)
   1.802 +    >>> parent.mock_calls
   1.803 +    [call.child1(1), call.child2(2)]
   1.804 +
   1.805 +The exception to this is if the mock has a name. This allows you to prevent
   1.806 +the "parenting" if for some reason you don't want it to happen.
   1.807 +
   1.808 +.. doctest::
   1.809 +
   1.810 +    >>> mock = MagicMock()
   1.811 +    >>> not_a_child = MagicMock(name='not-a-child')
   1.812 +    >>> mock.attribute = not_a_child
   1.813 +    >>> mock.attribute()
   1.814 +    <MagicMock name='not-a-child()' id='...'>
   1.815 +    >>> mock.mock_calls
   1.816 +    []
   1.817 +
   1.818 +Mocks created for you by :func:`patch` are automatically given names. To
   1.819 +attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
   1.820 +method:
   1.821 +
   1.822 +.. doctest::
   1.823 +
   1.824 +    >>> thing1 = object()
   1.825 +    >>> thing2 = object()
   1.826 +    >>> parent = MagicMock()
   1.827 +    >>> with patch('__main__.thing1', return_value=None) as child1:
   1.828 +    ...     with patch('__main__.thing2', return_value=None) as child2:
   1.829 +    ...         parent.attach_mock(child1, 'child1')
   1.830 +    ...         parent.attach_mock(child2, 'child2')
   1.831 +    ...         child1('one')
   1.832 +    ...         child2('two')
   1.833 +    ...
   1.834 +    >>> parent.mock_calls
   1.835 +    [call.child1('one'), call.child2('two')]
   1.836 +
   1.837 +
   1.838 +-----
   1.839 +
   1.840 +.. [#] The only exceptions are magic methods and attributes (those that have
   1.841 +       leading and trailing double underscores). Mock doesn't create these but
   1.842 +       instead of raises an ``AttributeError``. This is because the interpreter
   1.843 +       will often implicitly request these methods, and gets *very* confused to
   1.844 +       get a new Mock object when it expects a magic method. If you need magic
   1.845 +       method support see :ref:`magic methods <magic-methods>`.

mercurial