1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
|
================
The Mock Class
================
.. currentmodule:: mock
.. testsetup::
import os, sys
if not os.getcwd() in sys.path:
sys.path.append(os.getcwd())
from mock import Mock, sentinel, DEFAULT
``Mock`` is a flexible mock object intended to replace the use of stubs and
test doubles throughout your code. Mocks are callable and create attributes as
new mocks when you access them [#]_. Accessing the same attribute will always
return the same mock. Mocks record how you use them, allowing you to make
assertions about what your code has done to them.
The :func:`mock.patch` decorators makes it easy to temporarily replace classes
in a particular module with a Mock object.
.. index:: __init__
.. class:: Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None)
Create a new ``Mock`` object. ``Mock`` takes several optional arguments
that specify the behaviour of the Mock object:
* ``spec``: This can be either a list of strings or an existing object (a
class or instance) that acts as the specification for the mock object. If
you pass in an object then a list of strings is formed by calling dir on
the object (excluding unsupported magic attributes and methods). Accessing
any attribute not in this list will raise an ``AttributeError``.
* ``side_effect``: A function to be called whenever the Mock is called. See
the :attr:`Mock.side_effect` attribute. Useful for raising exceptions or
dynamically changing return values. The function is called with the same
arguments as the mock, and unless it returns :data:`DEFAULT`, the return
value of this function is used as the return value.
Alternatively ``side_effect`` can be an exception class or instance. In
this case the exception will be raised when the mock is called.
* ``return_value``: The value returned when the mock is called. By default
this is a new Mock (created on first access). See the
:attr:`Mock.return_value` attribute.
* ``wraps``: Item for the mock object to wrap. If ``wraps`` is not None
then calling the Mock will pass the call through to the wrapped object
(returning the real result and ignoring ``return_value``). Attribute
access on the mock will return a Mock object that wraps the corresponding
attribute of the wrapped object (so attempting to access an attribute that
doesn't exist will raise an ``AttributeError``).
If the mock has an explicit ``return_value`` set then calls are not passed
to the wrapped object and the ``return_value`` is returned instead.
Methods
=======
.. method:: Mock.assert_called_with(*args, **kwargs)
This method is a convenient way of asserting that calls are made in a particular way:
.. doctest::
>>> mock = Mock()
>>> mock.method(1, 2, 3, test='wow')
<mock.Mock object at 0x...>
>>> mock.method.assert_called_with(1, 2, 3, test='wow')
.. method:: Mock.reset_mock()
The reset_mock method resets all the call attributes on a mock object:
.. doctest::
>>> mock = Mock()
>>> mock('hello')
<mock.Mock object at 0x...>
>>> mock.called
True
>>> mock.reset_mock()
>>> mock.called
False
This can be useful where you want to make a series of assertions that reuse the same object. Note that ``reset`` *doesn't* clear the return value, ``side_effect`` or any child attributes. Attributes you have set using normal assignment are also left in place. Child mocks and the return value mock (if any) are reset as well.
.. index:: __call__
Calling
=======
Mock objects are callable. The call will return the value set as the :attr:`Mock.return_value` attribute. The default return value is a new Mock object; it is created the first time the return value is accessed (either explicitly or by calling the Mock) - but it is stored and the same one returned each time.
Calls made to the object will be recorded in the attributes_.
If :attr:`Mock.side_effect` is set then it will be called after the call has been recorded but before any value is returned.
Attributes
==========
.. attribute:: Mock.called
A boolean representing whether or not the mock object has been called:
.. doctest::
>>> mock = Mock(return_value=None)
>>> mock.called
False
>>> mock()
>>> mock.called
True
.. attribute:: Mock.call_count
An integer telling you how many times the mock object has been called:
.. doctest::
>>> mock = Mock(return_value=None)
>>> mock.call_count
0
>>> mock()
>>> mock()
>>> mock.call_count
2
.. attribute:: Mock.return_value
Set this to configure the value returned by calling the mock:
.. doctest::
>>> mock = Mock()
>>> mock.return_value = 'fish'
>>> mock()
'fish'
The default return value is a mock object and you can configure it in the normal way:
.. doctest::
>>> mock = Mock()
>>> mock.return_value.attribute = sentinel.Attribute
>>> mock.return_value()
<mock.Mock object at 0x...>
>>> mock.return_value.assert_called_with()
.. attribute:: Mock.side_effect
This can either be a function to be called when the mock is called, or an
exception (class or instance) to raised.
If you pass in a function it will be called with same arguments as the mock
and unless the mock returns the DEFAULT singleton the mock will return
whatever the function returns. If the function returns default then the
mock will return its normal value (from the :attr:`Mock.return_value`.
An example of a mock that raises an exception (to test exception handling of
an API):
.. doctest::
>>> mock = Mock()
>>> mock.side_effect = Exception('Boom!')
>>> mock()
Traceback (most recent call last):
...
Exception: Boom!
Using ``side_effect`` to return a sequence of values:
.. doctest::
>>> mock = Mock()
>>> results = [1, 2, 3]
>>> def side_effect(*args, **kwargs):
... return results.pop()
...
>>> mock.side_effect = side_effect
>>> mock(), mock(), mock()
(3, 2, 1)
The side_effect function is called with the same arguments as the mock (so it is wise for it to take arbitrary args and keyword arguments) and whatever it returns is used
as the return value for the call. The exception is if it returns :data:`DEFAULT`, in which case the normal :attr:`Mock.return_value` is used.
.. doctest::
>>> mock = Mock(return_value=3)
>>> def side_effect(*args, **kwargs):
... return DEFAULT
...
>>> mock.side_effect = side_effect
>>> mock()
3
.. attribute:: Mock.call_args
This is either ``None`` (if the mock hasn't been called), or the arguments that the mock was last called with. This will be in the form of a tuple: the first member is any ordered arguments the mock was called with (or an empty tuple) and the second member is any keyword arguments (or an empty dictionary):
.. doctest::
>>> mock = Mock(return_value=None)
>>> print mock.call_args
None
>>> mock()
>>> mock.call_args
((), {})
>>>
>>> mock(3, 4, 5, key='fish', next='w00t!')
>>> mock.call_args
((3, 4, 5), {'key': 'fish', 'next': 'w00t!'})
.. attribute:: Mock.call_args_list
This is a list of all the calls made to the mock object in sequence (so the length of the list is the number of times it has been called). Before any calls have been made it is an empty list:
.. doctest::
>>> mock = Mock()
>>> mock()
<mock.Mock object at 0x...>
>>> mock(3, 4, 5, key='fish', next='w00t!')
<mock.Mock object at 0x...>
>>> mock.call_args_list
[((), {}), ((3, 4, 5), {'key': 'fish', 'next': 'w00t!'})]
.. attribute:: Mock.method_calls
As well as tracking calls to themselves, mocks also track calls to methods and attributes, and *their* methods and attributes:
.. doctest::
>>> mock = Mock()
>>> mock.method()
<mock.Mock object at 0x...>
>>> mock.property.method.attribute()
<mock.Mock object at 0x...>
>>> mock.method_calls
[('method', (), {}), ('property.method.attribute', (), {})]
-----
.. [#] The only exceptions are magic methods and attributes (those that have leading and trailing double underscores). Mock doesn't create these but instead of raises an ``AttributeError``. This is because the interpreter will often implicitly request these methods, and gets *very* confused to get a new Mock object when it expects a magic method.
|