Thu, 22 Jan 2015 13:21:57 +0100
Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6
michael@0 | 1 | The Mock Class |
michael@0 | 2 | ============== |
michael@0 | 3 | |
michael@0 | 4 | .. currentmodule:: mock |
michael@0 | 5 | |
michael@0 | 6 | .. testsetup:: |
michael@0 | 7 | |
michael@0 | 8 | class SomeClass: |
michael@0 | 9 | pass |
michael@0 | 10 | |
michael@0 | 11 | |
michael@0 | 12 | `Mock` is a flexible mock object intended to replace the use of stubs and |
michael@0 | 13 | test doubles throughout your code. Mocks are callable and create attributes as |
michael@0 | 14 | new mocks when you access them [#]_. Accessing the same attribute will always |
michael@0 | 15 | return the same mock. Mocks record how you use them, allowing you to make |
michael@0 | 16 | assertions about what your code has done to them. |
michael@0 | 17 | |
michael@0 | 18 | :class:`MagicMock` is a subclass of `Mock` with all the magic methods |
michael@0 | 19 | pre-created and ready to use. There are also non-callable variants, useful |
michael@0 | 20 | when you are mocking out objects that aren't callable: |
michael@0 | 21 | :class:`NonCallableMock` and :class:`NonCallableMagicMock` |
michael@0 | 22 | |
michael@0 | 23 | The :func:`patch` decorators makes it easy to temporarily replace classes |
michael@0 | 24 | in a particular module with a `Mock` object. By default `patch` will create |
michael@0 | 25 | a `MagicMock` for you. You can specify an alternative class of `Mock` using |
michael@0 | 26 | the `new_callable` argument to `patch`. |
michael@0 | 27 | |
michael@0 | 28 | |
michael@0 | 29 | .. index:: side_effect |
michael@0 | 30 | .. index:: return_value |
michael@0 | 31 | .. index:: wraps |
michael@0 | 32 | .. index:: name |
michael@0 | 33 | .. index:: spec |
michael@0 | 34 | |
michael@0 | 35 | .. class:: Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, **kwargs) |
michael@0 | 36 | |
michael@0 | 37 | Create a new `Mock` object. `Mock` takes several optional arguments |
michael@0 | 38 | that specify the behaviour of the Mock object: |
michael@0 | 39 | |
michael@0 | 40 | * `spec`: This can be either a list of strings or an existing object (a |
michael@0 | 41 | class or instance) that acts as the specification for the mock object. If |
michael@0 | 42 | you pass in an object then a list of strings is formed by calling dir on |
michael@0 | 43 | the object (excluding unsupported magic attributes and methods). |
michael@0 | 44 | Accessing any attribute not in this list will raise an `AttributeError`. |
michael@0 | 45 | |
michael@0 | 46 | If `spec` is an object (rather than a list of strings) then |
michael@0 | 47 | :attr:`__class__` returns the class of the spec object. This allows mocks |
michael@0 | 48 | to pass `isinstance` tests. |
michael@0 | 49 | |
michael@0 | 50 | * `spec_set`: A stricter variant of `spec`. If used, attempting to *set* |
michael@0 | 51 | or get an attribute on the mock that isn't on the object passed as |
michael@0 | 52 | `spec_set` will raise an `AttributeError`. |
michael@0 | 53 | |
michael@0 | 54 | * `side_effect`: A function to be called whenever the Mock is called. See |
michael@0 | 55 | the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or |
michael@0 | 56 | dynamically changing return values. The function is called with the same |
michael@0 | 57 | arguments as the mock, and unless it returns :data:`DEFAULT`, the return |
michael@0 | 58 | value of this function is used as the return value. |
michael@0 | 59 | |
michael@0 | 60 | Alternatively `side_effect` can be an exception class or instance. In |
michael@0 | 61 | this case the exception will be raised when the mock is called. |
michael@0 | 62 | |
michael@0 | 63 | If `side_effect` is an iterable then each call to the mock will return |
michael@0 | 64 | the next value from the iterable. If any of the members of the iterable |
michael@0 | 65 | are exceptions they will be raised instead of returned. |
michael@0 | 66 | |
michael@0 | 67 | A `side_effect` can be cleared by setting it to `None`. |
michael@0 | 68 | |
michael@0 | 69 | * `return_value`: The value returned when the mock is called. By default |
michael@0 | 70 | this is a new Mock (created on first access). See the |
michael@0 | 71 | :attr:`return_value` attribute. |
michael@0 | 72 | |
michael@0 | 73 | * `wraps`: Item for the mock object to wrap. If `wraps` is not None then |
michael@0 | 74 | calling the Mock will pass the call through to the wrapped object |
michael@0 | 75 | (returning the real result and ignoring `return_value`). Attribute access |
michael@0 | 76 | on the mock will return a Mock object that wraps the corresponding |
michael@0 | 77 | attribute of the wrapped object (so attempting to access an attribute |
michael@0 | 78 | that doesn't exist will raise an `AttributeError`). |
michael@0 | 79 | |
michael@0 | 80 | If the mock has an explicit `return_value` set then calls are not passed |
michael@0 | 81 | to the wrapped object and the `return_value` is returned instead. |
michael@0 | 82 | |
michael@0 | 83 | * `name`: If the mock has a name then it will be used in the repr of the |
michael@0 | 84 | mock. This can be useful for debugging. The name is propagated to child |
michael@0 | 85 | mocks. |
michael@0 | 86 | |
michael@0 | 87 | Mocks can also be called with arbitrary keyword arguments. These will be |
michael@0 | 88 | used to set attributes on the mock after it is created. See the |
michael@0 | 89 | :meth:`configure_mock` method for details. |
michael@0 | 90 | |
michael@0 | 91 | |
michael@0 | 92 | .. method:: assert_called_with(*args, **kwargs) |
michael@0 | 93 | |
michael@0 | 94 | This method is a convenient way of asserting that calls are made in a |
michael@0 | 95 | particular way: |
michael@0 | 96 | |
michael@0 | 97 | .. doctest:: |
michael@0 | 98 | |
michael@0 | 99 | >>> mock = Mock() |
michael@0 | 100 | >>> mock.method(1, 2, 3, test='wow') |
michael@0 | 101 | <Mock name='mock.method()' id='...'> |
michael@0 | 102 | >>> mock.method.assert_called_with(1, 2, 3, test='wow') |
michael@0 | 103 | |
michael@0 | 104 | |
michael@0 | 105 | .. method:: assert_called_once_with(*args, **kwargs) |
michael@0 | 106 | |
michael@0 | 107 | Assert that the mock was called exactly once and with the specified |
michael@0 | 108 | arguments. |
michael@0 | 109 | |
michael@0 | 110 | .. doctest:: |
michael@0 | 111 | |
michael@0 | 112 | >>> mock = Mock(return_value=None) |
michael@0 | 113 | >>> mock('foo', bar='baz') |
michael@0 | 114 | >>> mock.assert_called_once_with('foo', bar='baz') |
michael@0 | 115 | >>> mock('foo', bar='baz') |
michael@0 | 116 | >>> mock.assert_called_once_with('foo', bar='baz') |
michael@0 | 117 | Traceback (most recent call last): |
michael@0 | 118 | ... |
michael@0 | 119 | AssertionError: Expected to be called once. Called 2 times. |
michael@0 | 120 | |
michael@0 | 121 | |
michael@0 | 122 | .. method:: assert_any_call(*args, **kwargs) |
michael@0 | 123 | |
michael@0 | 124 | assert the mock has been called with the specified arguments. |
michael@0 | 125 | |
michael@0 | 126 | The assert passes if the mock has *ever* been called, unlike |
michael@0 | 127 | :meth:`assert_called_with` and :meth:`assert_called_once_with` that |
michael@0 | 128 | only pass if the call is the most recent one. |
michael@0 | 129 | |
michael@0 | 130 | .. doctest:: |
michael@0 | 131 | |
michael@0 | 132 | >>> mock = Mock(return_value=None) |
michael@0 | 133 | >>> mock(1, 2, arg='thing') |
michael@0 | 134 | >>> mock('some', 'thing', 'else') |
michael@0 | 135 | >>> mock.assert_any_call(1, 2, arg='thing') |
michael@0 | 136 | |
michael@0 | 137 | |
michael@0 | 138 | .. method:: assert_has_calls(calls, any_order=False) |
michael@0 | 139 | |
michael@0 | 140 | assert the mock has been called with the specified calls. |
michael@0 | 141 | The `mock_calls` list is checked for the calls. |
michael@0 | 142 | |
michael@0 | 143 | If `any_order` is False (the default) then the calls must be |
michael@0 | 144 | sequential. There can be extra calls before or after the |
michael@0 | 145 | specified calls. |
michael@0 | 146 | |
michael@0 | 147 | If `any_order` is True then the calls can be in any order, but |
michael@0 | 148 | they must all appear in :attr:`mock_calls`. |
michael@0 | 149 | |
michael@0 | 150 | .. doctest:: |
michael@0 | 151 | |
michael@0 | 152 | >>> mock = Mock(return_value=None) |
michael@0 | 153 | >>> mock(1) |
michael@0 | 154 | >>> mock(2) |
michael@0 | 155 | >>> mock(3) |
michael@0 | 156 | >>> mock(4) |
michael@0 | 157 | >>> calls = [call(2), call(3)] |
michael@0 | 158 | >>> mock.assert_has_calls(calls) |
michael@0 | 159 | >>> calls = [call(4), call(2), call(3)] |
michael@0 | 160 | >>> mock.assert_has_calls(calls, any_order=True) |
michael@0 | 161 | |
michael@0 | 162 | |
michael@0 | 163 | .. method:: reset_mock() |
michael@0 | 164 | |
michael@0 | 165 | The reset_mock method resets all the call attributes on a mock object: |
michael@0 | 166 | |
michael@0 | 167 | .. doctest:: |
michael@0 | 168 | |
michael@0 | 169 | >>> mock = Mock(return_value=None) |
michael@0 | 170 | >>> mock('hello') |
michael@0 | 171 | >>> mock.called |
michael@0 | 172 | True |
michael@0 | 173 | >>> mock.reset_mock() |
michael@0 | 174 | >>> mock.called |
michael@0 | 175 | False |
michael@0 | 176 | |
michael@0 | 177 | This can be useful where you want to make a series of assertions that |
michael@0 | 178 | reuse the same object. Note that `reset_mock` *doesn't* clear the |
michael@0 | 179 | return value, :attr:`side_effect` or any child attributes you have |
michael@0 | 180 | set using normal assignment. Child mocks and the return value mock |
michael@0 | 181 | (if any) are reset as well. |
michael@0 | 182 | |
michael@0 | 183 | |
michael@0 | 184 | .. method:: mock_add_spec(spec, spec_set=False) |
michael@0 | 185 | |
michael@0 | 186 | Add a spec to a mock. `spec` can either be an object or a |
michael@0 | 187 | list of strings. Only attributes on the `spec` can be fetched as |
michael@0 | 188 | attributes from the mock. |
michael@0 | 189 | |
michael@0 | 190 | If `spec_set` is `True` then only attributes on the spec can be set. |
michael@0 | 191 | |
michael@0 | 192 | |
michael@0 | 193 | .. method:: attach_mock(mock, attribute) |
michael@0 | 194 | |
michael@0 | 195 | Attach a mock as an attribute of this one, replacing its name and |
michael@0 | 196 | parent. Calls to the attached mock will be recorded in the |
michael@0 | 197 | :attr:`method_calls` and :attr:`mock_calls` attributes of this one. |
michael@0 | 198 | |
michael@0 | 199 | |
michael@0 | 200 | .. method:: configure_mock(**kwargs) |
michael@0 | 201 | |
michael@0 | 202 | Set attributes on the mock through keyword arguments. |
michael@0 | 203 | |
michael@0 | 204 | Attributes plus return values and side effects can be set on child |
michael@0 | 205 | mocks using standard dot notation and unpacking a dictionary in the |
michael@0 | 206 | method call: |
michael@0 | 207 | |
michael@0 | 208 | .. doctest:: |
michael@0 | 209 | |
michael@0 | 210 | >>> mock = Mock() |
michael@0 | 211 | >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} |
michael@0 | 212 | >>> mock.configure_mock(**attrs) |
michael@0 | 213 | >>> mock.method() |
michael@0 | 214 | 3 |
michael@0 | 215 | >>> mock.other() |
michael@0 | 216 | Traceback (most recent call last): |
michael@0 | 217 | ... |
michael@0 | 218 | KeyError |
michael@0 | 219 | |
michael@0 | 220 | The same thing can be achieved in the constructor call to mocks: |
michael@0 | 221 | |
michael@0 | 222 | .. doctest:: |
michael@0 | 223 | |
michael@0 | 224 | >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} |
michael@0 | 225 | >>> mock = Mock(some_attribute='eggs', **attrs) |
michael@0 | 226 | >>> mock.some_attribute |
michael@0 | 227 | 'eggs' |
michael@0 | 228 | >>> mock.method() |
michael@0 | 229 | 3 |
michael@0 | 230 | >>> mock.other() |
michael@0 | 231 | Traceback (most recent call last): |
michael@0 | 232 | ... |
michael@0 | 233 | KeyError |
michael@0 | 234 | |
michael@0 | 235 | `configure_mock` exists to make it easier to do configuration |
michael@0 | 236 | after the mock has been created. |
michael@0 | 237 | |
michael@0 | 238 | |
michael@0 | 239 | .. method:: __dir__() |
michael@0 | 240 | |
michael@0 | 241 | `Mock` objects limit the results of `dir(some_mock)` to useful results. |
michael@0 | 242 | For mocks with a `spec` this includes all the permitted attributes |
michael@0 | 243 | for the mock. |
michael@0 | 244 | |
michael@0 | 245 | See :data:`FILTER_DIR` for what this filtering does, and how to |
michael@0 | 246 | switch it off. |
michael@0 | 247 | |
michael@0 | 248 | |
michael@0 | 249 | .. method:: _get_child_mock(**kw) |
michael@0 | 250 | |
michael@0 | 251 | Create the child mocks for attributes and return value. |
michael@0 | 252 | By default child mocks will be the same type as the parent. |
michael@0 | 253 | Subclasses of Mock may want to override this to customize the way |
michael@0 | 254 | child mocks are made. |
michael@0 | 255 | |
michael@0 | 256 | For non-callable mocks the callable variant will be used (rather than |
michael@0 | 257 | any custom subclass). |
michael@0 | 258 | |
michael@0 | 259 | |
michael@0 | 260 | .. attribute:: called |
michael@0 | 261 | |
michael@0 | 262 | A boolean representing whether or not the mock object has been called: |
michael@0 | 263 | |
michael@0 | 264 | .. doctest:: |
michael@0 | 265 | |
michael@0 | 266 | >>> mock = Mock(return_value=None) |
michael@0 | 267 | >>> mock.called |
michael@0 | 268 | False |
michael@0 | 269 | >>> mock() |
michael@0 | 270 | >>> mock.called |
michael@0 | 271 | True |
michael@0 | 272 | |
michael@0 | 273 | .. attribute:: call_count |
michael@0 | 274 | |
michael@0 | 275 | An integer telling you how many times the mock object has been called: |
michael@0 | 276 | |
michael@0 | 277 | .. doctest:: |
michael@0 | 278 | |
michael@0 | 279 | >>> mock = Mock(return_value=None) |
michael@0 | 280 | >>> mock.call_count |
michael@0 | 281 | 0 |
michael@0 | 282 | >>> mock() |
michael@0 | 283 | >>> mock() |
michael@0 | 284 | >>> mock.call_count |
michael@0 | 285 | 2 |
michael@0 | 286 | |
michael@0 | 287 | |
michael@0 | 288 | .. attribute:: return_value |
michael@0 | 289 | |
michael@0 | 290 | Set this to configure the value returned by calling the mock: |
michael@0 | 291 | |
michael@0 | 292 | .. doctest:: |
michael@0 | 293 | |
michael@0 | 294 | >>> mock = Mock() |
michael@0 | 295 | >>> mock.return_value = 'fish' |
michael@0 | 296 | >>> mock() |
michael@0 | 297 | 'fish' |
michael@0 | 298 | |
michael@0 | 299 | The default return value is a mock object and you can configure it in |
michael@0 | 300 | the normal way: |
michael@0 | 301 | |
michael@0 | 302 | .. doctest:: |
michael@0 | 303 | |
michael@0 | 304 | >>> mock = Mock() |
michael@0 | 305 | >>> mock.return_value.attribute = sentinel.Attribute |
michael@0 | 306 | >>> mock.return_value() |
michael@0 | 307 | <Mock name='mock()()' id='...'> |
michael@0 | 308 | >>> mock.return_value.assert_called_with() |
michael@0 | 309 | |
michael@0 | 310 | `return_value` can also be set in the constructor: |
michael@0 | 311 | |
michael@0 | 312 | .. doctest:: |
michael@0 | 313 | |
michael@0 | 314 | >>> mock = Mock(return_value=3) |
michael@0 | 315 | >>> mock.return_value |
michael@0 | 316 | 3 |
michael@0 | 317 | >>> mock() |
michael@0 | 318 | 3 |
michael@0 | 319 | |
michael@0 | 320 | |
michael@0 | 321 | .. attribute:: side_effect |
michael@0 | 322 | |
michael@0 | 323 | This can either be a function to be called when the mock is called, |
michael@0 | 324 | or an exception (class or instance) to be raised. |
michael@0 | 325 | |
michael@0 | 326 | If you pass in a function it will be called with same arguments as the |
michael@0 | 327 | mock and unless the function returns the :data:`DEFAULT` singleton the |
michael@0 | 328 | call to the mock will then return whatever the function returns. If the |
michael@0 | 329 | function returns :data:`DEFAULT` then the mock will return its normal |
michael@0 | 330 | value (from the :attr:`return_value`. |
michael@0 | 331 | |
michael@0 | 332 | An example of a mock that raises an exception (to test exception |
michael@0 | 333 | handling of an API): |
michael@0 | 334 | |
michael@0 | 335 | .. doctest:: |
michael@0 | 336 | |
michael@0 | 337 | >>> mock = Mock() |
michael@0 | 338 | >>> mock.side_effect = Exception('Boom!') |
michael@0 | 339 | >>> mock() |
michael@0 | 340 | Traceback (most recent call last): |
michael@0 | 341 | ... |
michael@0 | 342 | Exception: Boom! |
michael@0 | 343 | |
michael@0 | 344 | Using `side_effect` to return a sequence of values: |
michael@0 | 345 | |
michael@0 | 346 | .. doctest:: |
michael@0 | 347 | |
michael@0 | 348 | >>> mock = Mock() |
michael@0 | 349 | >>> mock.side_effect = [3, 2, 1] |
michael@0 | 350 | >>> mock(), mock(), mock() |
michael@0 | 351 | (3, 2, 1) |
michael@0 | 352 | |
michael@0 | 353 | The `side_effect` function is called with the same arguments as the |
michael@0 | 354 | mock (so it is wise for it to take arbitrary args and keyword |
michael@0 | 355 | arguments) and whatever it returns is used as the return value for |
michael@0 | 356 | the call. The exception is if `side_effect` returns :data:`DEFAULT`, |
michael@0 | 357 | in which case the normal :attr:`return_value` is used. |
michael@0 | 358 | |
michael@0 | 359 | .. doctest:: |
michael@0 | 360 | |
michael@0 | 361 | >>> mock = Mock(return_value=3) |
michael@0 | 362 | >>> def side_effect(*args, **kwargs): |
michael@0 | 363 | ... return DEFAULT |
michael@0 | 364 | ... |
michael@0 | 365 | >>> mock.side_effect = side_effect |
michael@0 | 366 | >>> mock() |
michael@0 | 367 | 3 |
michael@0 | 368 | |
michael@0 | 369 | `side_effect` can be set in the constructor. Here's an example that |
michael@0 | 370 | adds one to the value the mock is called with and returns it: |
michael@0 | 371 | |
michael@0 | 372 | .. doctest:: |
michael@0 | 373 | |
michael@0 | 374 | >>> side_effect = lambda value: value + 1 |
michael@0 | 375 | >>> mock = Mock(side_effect=side_effect) |
michael@0 | 376 | >>> mock(3) |
michael@0 | 377 | 4 |
michael@0 | 378 | >>> mock(-8) |
michael@0 | 379 | -7 |
michael@0 | 380 | |
michael@0 | 381 | Setting `side_effect` to `None` clears it: |
michael@0 | 382 | |
michael@0 | 383 | .. doctest:: |
michael@0 | 384 | |
michael@0 | 385 | >>> from mock import Mock |
michael@0 | 386 | >>> m = Mock(side_effect=KeyError, return_value=3) |
michael@0 | 387 | >>> m() |
michael@0 | 388 | Traceback (most recent call last): |
michael@0 | 389 | ... |
michael@0 | 390 | KeyError |
michael@0 | 391 | >>> m.side_effect = None |
michael@0 | 392 | >>> m() |
michael@0 | 393 | 3 |
michael@0 | 394 | |
michael@0 | 395 | |
michael@0 | 396 | .. attribute:: call_args |
michael@0 | 397 | |
michael@0 | 398 | This is either `None` (if the mock hasn't been called), or the |
michael@0 | 399 | arguments that the mock was last called with. This will be in the |
michael@0 | 400 | form of a tuple: the first member is any ordered arguments the mock |
michael@0 | 401 | was called with (or an empty tuple) and the second member is any |
michael@0 | 402 | keyword arguments (or an empty dictionary). |
michael@0 | 403 | |
michael@0 | 404 | .. doctest:: |
michael@0 | 405 | |
michael@0 | 406 | >>> mock = Mock(return_value=None) |
michael@0 | 407 | >>> print mock.call_args |
michael@0 | 408 | None |
michael@0 | 409 | >>> mock() |
michael@0 | 410 | >>> mock.call_args |
michael@0 | 411 | call() |
michael@0 | 412 | >>> mock.call_args == () |
michael@0 | 413 | True |
michael@0 | 414 | >>> mock(3, 4) |
michael@0 | 415 | >>> mock.call_args |
michael@0 | 416 | call(3, 4) |
michael@0 | 417 | >>> mock.call_args == ((3, 4),) |
michael@0 | 418 | True |
michael@0 | 419 | >>> mock(3, 4, 5, key='fish', next='w00t!') |
michael@0 | 420 | >>> mock.call_args |
michael@0 | 421 | call(3, 4, 5, key='fish', next='w00t!') |
michael@0 | 422 | |
michael@0 | 423 | `call_args`, along with members of the lists :attr:`call_args_list`, |
michael@0 | 424 | :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects. |
michael@0 | 425 | These are tuples, so they can be unpacked to get at the individual |
michael@0 | 426 | arguments and make more complex assertions. See |
michael@0 | 427 | :ref:`calls as tuples <calls-as-tuples>`. |
michael@0 | 428 | |
michael@0 | 429 | |
michael@0 | 430 | .. attribute:: call_args_list |
michael@0 | 431 | |
michael@0 | 432 | This is a list of all the calls made to the mock object in sequence |
michael@0 | 433 | (so the length of the list is the number of times it has been |
michael@0 | 434 | called). Before any calls have been made it is an empty list. The |
michael@0 | 435 | :data:`call` object can be used for conveniently constructing lists of |
michael@0 | 436 | calls to compare with `call_args_list`. |
michael@0 | 437 | |
michael@0 | 438 | .. doctest:: |
michael@0 | 439 | |
michael@0 | 440 | >>> mock = Mock(return_value=None) |
michael@0 | 441 | >>> mock() |
michael@0 | 442 | >>> mock(3, 4) |
michael@0 | 443 | >>> mock(key='fish', next='w00t!') |
michael@0 | 444 | >>> mock.call_args_list |
michael@0 | 445 | [call(), call(3, 4), call(key='fish', next='w00t!')] |
michael@0 | 446 | >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)] |
michael@0 | 447 | >>> mock.call_args_list == expected |
michael@0 | 448 | True |
michael@0 | 449 | |
michael@0 | 450 | Members of `call_args_list` are :data:`call` objects. These can be |
michael@0 | 451 | unpacked as tuples to get at the individual arguments. See |
michael@0 | 452 | :ref:`calls as tuples <calls-as-tuples>`. |
michael@0 | 453 | |
michael@0 | 454 | |
michael@0 | 455 | .. attribute:: method_calls |
michael@0 | 456 | |
michael@0 | 457 | As well as tracking calls to themselves, mocks also track calls to |
michael@0 | 458 | methods and attributes, and *their* methods and attributes: |
michael@0 | 459 | |
michael@0 | 460 | .. doctest:: |
michael@0 | 461 | |
michael@0 | 462 | >>> mock = Mock() |
michael@0 | 463 | >>> mock.method() |
michael@0 | 464 | <Mock name='mock.method()' id='...'> |
michael@0 | 465 | >>> mock.property.method.attribute() |
michael@0 | 466 | <Mock name='mock.property.method.attribute()' id='...'> |
michael@0 | 467 | >>> mock.method_calls |
michael@0 | 468 | [call.method(), call.property.method.attribute()] |
michael@0 | 469 | |
michael@0 | 470 | Members of `method_calls` are :data:`call` objects. These can be |
michael@0 | 471 | unpacked as tuples to get at the individual arguments. See |
michael@0 | 472 | :ref:`calls as tuples <calls-as-tuples>`. |
michael@0 | 473 | |
michael@0 | 474 | |
michael@0 | 475 | .. attribute:: mock_calls |
michael@0 | 476 | |
michael@0 | 477 | `mock_calls` records *all* calls to the mock object, its methods, magic |
michael@0 | 478 | methods *and* return value mocks. |
michael@0 | 479 | |
michael@0 | 480 | .. doctest:: |
michael@0 | 481 | |
michael@0 | 482 | >>> mock = MagicMock() |
michael@0 | 483 | >>> result = mock(1, 2, 3) |
michael@0 | 484 | >>> mock.first(a=3) |
michael@0 | 485 | <MagicMock name='mock.first()' id='...'> |
michael@0 | 486 | >>> mock.second() |
michael@0 | 487 | <MagicMock name='mock.second()' id='...'> |
michael@0 | 488 | >>> int(mock) |
michael@0 | 489 | 1 |
michael@0 | 490 | >>> result(1) |
michael@0 | 491 | <MagicMock name='mock()()' id='...'> |
michael@0 | 492 | >>> expected = [call(1, 2, 3), call.first(a=3), call.second(), |
michael@0 | 493 | ... call.__int__(), call()(1)] |
michael@0 | 494 | >>> mock.mock_calls == expected |
michael@0 | 495 | True |
michael@0 | 496 | |
michael@0 | 497 | Members of `mock_calls` are :data:`call` objects. These can be |
michael@0 | 498 | unpacked as tuples to get at the individual arguments. See |
michael@0 | 499 | :ref:`calls as tuples <calls-as-tuples>`. |
michael@0 | 500 | |
michael@0 | 501 | |
michael@0 | 502 | .. attribute:: __class__ |
michael@0 | 503 | |
michael@0 | 504 | Normally the `__class__` attribute of an object will return its type. |
michael@0 | 505 | For a mock object with a `spec` `__class__` returns the spec class |
michael@0 | 506 | instead. This allows mock objects to pass `isinstance` tests for the |
michael@0 | 507 | object they are replacing / masquerading as: |
michael@0 | 508 | |
michael@0 | 509 | .. doctest:: |
michael@0 | 510 | |
michael@0 | 511 | >>> mock = Mock(spec=3) |
michael@0 | 512 | >>> isinstance(mock, int) |
michael@0 | 513 | True |
michael@0 | 514 | |
michael@0 | 515 | `__class__` is assignable to, this allows a mock to pass an |
michael@0 | 516 | `isinstance` check without forcing you to use a spec: |
michael@0 | 517 | |
michael@0 | 518 | .. doctest:: |
michael@0 | 519 | |
michael@0 | 520 | >>> mock = Mock() |
michael@0 | 521 | >>> mock.__class__ = dict |
michael@0 | 522 | >>> isinstance(mock, dict) |
michael@0 | 523 | True |
michael@0 | 524 | |
michael@0 | 525 | .. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs) |
michael@0 | 526 | |
michael@0 | 527 | A non-callable version of `Mock`. The constructor parameters have the same |
michael@0 | 528 | meaning of `Mock`, with the exception of `return_value` and `side_effect` |
michael@0 | 529 | which have no meaning on a non-callable mock. |
michael@0 | 530 | |
michael@0 | 531 | Mock objects that use a class or an instance as a `spec` or `spec_set` are able |
michael@0 | 532 | to pass `isintance` tests: |
michael@0 | 533 | |
michael@0 | 534 | .. doctest:: |
michael@0 | 535 | |
michael@0 | 536 | >>> mock = Mock(spec=SomeClass) |
michael@0 | 537 | >>> isinstance(mock, SomeClass) |
michael@0 | 538 | True |
michael@0 | 539 | >>> mock = Mock(spec_set=SomeClass()) |
michael@0 | 540 | >>> isinstance(mock, SomeClass) |
michael@0 | 541 | True |
michael@0 | 542 | |
michael@0 | 543 | The `Mock` classes have support for mocking magic methods. See :ref:`magic |
michael@0 | 544 | methods <magic-methods>` for the full details. |
michael@0 | 545 | |
michael@0 | 546 | The mock classes and the :func:`patch` decorators all take arbitrary keyword |
michael@0 | 547 | arguments for configuration. For the `patch` decorators the keywords are |
michael@0 | 548 | passed to the constructor of the mock being created. The keyword arguments |
michael@0 | 549 | are for configuring attributes of the mock: |
michael@0 | 550 | |
michael@0 | 551 | .. doctest:: |
michael@0 | 552 | |
michael@0 | 553 | >>> m = MagicMock(attribute=3, other='fish') |
michael@0 | 554 | >>> m.attribute |
michael@0 | 555 | 3 |
michael@0 | 556 | >>> m.other |
michael@0 | 557 | 'fish' |
michael@0 | 558 | |
michael@0 | 559 | The return value and side effect of child mocks can be set in the same way, |
michael@0 | 560 | using dotted notation. As you can't use dotted names directly in a call you |
michael@0 | 561 | have to create a dictionary and unpack it using `**`: |
michael@0 | 562 | |
michael@0 | 563 | .. doctest:: |
michael@0 | 564 | |
michael@0 | 565 | >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} |
michael@0 | 566 | >>> mock = Mock(some_attribute='eggs', **attrs) |
michael@0 | 567 | >>> mock.some_attribute |
michael@0 | 568 | 'eggs' |
michael@0 | 569 | >>> mock.method() |
michael@0 | 570 | 3 |
michael@0 | 571 | >>> mock.other() |
michael@0 | 572 | Traceback (most recent call last): |
michael@0 | 573 | ... |
michael@0 | 574 | KeyError |
michael@0 | 575 | |
michael@0 | 576 | |
michael@0 | 577 | .. class:: PropertyMock(*args, **kwargs) |
michael@0 | 578 | |
michael@0 | 579 | A mock intended to be used as a property, or other descriptor, on a class. |
michael@0 | 580 | `PropertyMock` provides `__get__` and `__set__` methods so you can specify |
michael@0 | 581 | a return value when it is fetched. |
michael@0 | 582 | |
michael@0 | 583 | Fetching a `PropertyMock` instance from an object calls the mock, with |
michael@0 | 584 | no args. Setting it calls the mock with the value being set. |
michael@0 | 585 | |
michael@0 | 586 | .. doctest:: |
michael@0 | 587 | |
michael@0 | 588 | >>> class Foo(object): |
michael@0 | 589 | ... @property |
michael@0 | 590 | ... def foo(self): |
michael@0 | 591 | ... return 'something' |
michael@0 | 592 | ... @foo.setter |
michael@0 | 593 | ... def foo(self, value): |
michael@0 | 594 | ... pass |
michael@0 | 595 | ... |
michael@0 | 596 | >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo: |
michael@0 | 597 | ... mock_foo.return_value = 'mockity-mock' |
michael@0 | 598 | ... this_foo = Foo() |
michael@0 | 599 | ... print this_foo.foo |
michael@0 | 600 | ... this_foo.foo = 6 |
michael@0 | 601 | ... |
michael@0 | 602 | mockity-mock |
michael@0 | 603 | >>> mock_foo.mock_calls |
michael@0 | 604 | [call(), call(6)] |
michael@0 | 605 | |
michael@0 | 606 | Because of the way mock attributes are stored you can't directly attach a |
michael@0 | 607 | `PropertyMock` to a mock object. Instead you can attach it to the mock type |
michael@0 | 608 | object: |
michael@0 | 609 | |
michael@0 | 610 | .. doctest:: |
michael@0 | 611 | |
michael@0 | 612 | >>> m = MagicMock() |
michael@0 | 613 | >>> p = PropertyMock(return_value=3) |
michael@0 | 614 | >>> type(m).foo = p |
michael@0 | 615 | >>> m.foo |
michael@0 | 616 | 3 |
michael@0 | 617 | >>> p.assert_called_once_with() |
michael@0 | 618 | |
michael@0 | 619 | |
michael@0 | 620 | .. index:: __call__ |
michael@0 | 621 | .. index:: calling |
michael@0 | 622 | |
michael@0 | 623 | Calling |
michael@0 | 624 | ======= |
michael@0 | 625 | |
michael@0 | 626 | Mock objects are callable. The call will return the value set as the |
michael@0 | 627 | :attr:`~Mock.return_value` attribute. The default return value is a new Mock |
michael@0 | 628 | object; it is created the first time the return value is accessed (either |
michael@0 | 629 | explicitly or by calling the Mock) - but it is stored and the same one |
michael@0 | 630 | returned each time. |
michael@0 | 631 | |
michael@0 | 632 | Calls made to the object will be recorded in the attributes |
michael@0 | 633 | like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`. |
michael@0 | 634 | |
michael@0 | 635 | If :attr:`~Mock.side_effect` is set then it will be called after the call has |
michael@0 | 636 | been recorded, so if `side_effect` raises an exception the call is still |
michael@0 | 637 | recorded. |
michael@0 | 638 | |
michael@0 | 639 | The simplest way to make a mock raise an exception when called is to make |
michael@0 | 640 | :attr:`~Mock.side_effect` an exception class or instance: |
michael@0 | 641 | |
michael@0 | 642 | .. doctest:: |
michael@0 | 643 | |
michael@0 | 644 | >>> m = MagicMock(side_effect=IndexError) |
michael@0 | 645 | >>> m(1, 2, 3) |
michael@0 | 646 | Traceback (most recent call last): |
michael@0 | 647 | ... |
michael@0 | 648 | IndexError |
michael@0 | 649 | >>> m.mock_calls |
michael@0 | 650 | [call(1, 2, 3)] |
michael@0 | 651 | >>> m.side_effect = KeyError('Bang!') |
michael@0 | 652 | >>> m('two', 'three', 'four') |
michael@0 | 653 | Traceback (most recent call last): |
michael@0 | 654 | ... |
michael@0 | 655 | KeyError: 'Bang!' |
michael@0 | 656 | >>> m.mock_calls |
michael@0 | 657 | [call(1, 2, 3), call('two', 'three', 'four')] |
michael@0 | 658 | |
michael@0 | 659 | If `side_effect` is a function then whatever that function returns is what |
michael@0 | 660 | calls to the mock return. The `side_effect` function is called with the |
michael@0 | 661 | same arguments as the mock. This allows you to vary the return value of the |
michael@0 | 662 | call dynamically, based on the input: |
michael@0 | 663 | |
michael@0 | 664 | .. doctest:: |
michael@0 | 665 | |
michael@0 | 666 | >>> def side_effect(value): |
michael@0 | 667 | ... return value + 1 |
michael@0 | 668 | ... |
michael@0 | 669 | >>> m = MagicMock(side_effect=side_effect) |
michael@0 | 670 | >>> m(1) |
michael@0 | 671 | 2 |
michael@0 | 672 | >>> m(2) |
michael@0 | 673 | 3 |
michael@0 | 674 | >>> m.mock_calls |
michael@0 | 675 | [call(1), call(2)] |
michael@0 | 676 | |
michael@0 | 677 | If you want the mock to still return the default return value (a new mock), or |
michael@0 | 678 | any set return value, then there are two ways of doing this. Either return |
michael@0 | 679 | `mock.return_value` from inside `side_effect`, or return :data:`DEFAULT`: |
michael@0 | 680 | |
michael@0 | 681 | .. doctest:: |
michael@0 | 682 | |
michael@0 | 683 | >>> m = MagicMock() |
michael@0 | 684 | >>> def side_effect(*args, **kwargs): |
michael@0 | 685 | ... return m.return_value |
michael@0 | 686 | ... |
michael@0 | 687 | >>> m.side_effect = side_effect |
michael@0 | 688 | >>> m.return_value = 3 |
michael@0 | 689 | >>> m() |
michael@0 | 690 | 3 |
michael@0 | 691 | >>> def side_effect(*args, **kwargs): |
michael@0 | 692 | ... return DEFAULT |
michael@0 | 693 | ... |
michael@0 | 694 | >>> m.side_effect = side_effect |
michael@0 | 695 | >>> m() |
michael@0 | 696 | 3 |
michael@0 | 697 | |
michael@0 | 698 | To remove a `side_effect`, and return to the default behaviour, set the |
michael@0 | 699 | `side_effect` to `None`: |
michael@0 | 700 | |
michael@0 | 701 | .. doctest:: |
michael@0 | 702 | |
michael@0 | 703 | >>> m = MagicMock(return_value=6) |
michael@0 | 704 | >>> def side_effect(*args, **kwargs): |
michael@0 | 705 | ... return 3 |
michael@0 | 706 | ... |
michael@0 | 707 | >>> m.side_effect = side_effect |
michael@0 | 708 | >>> m() |
michael@0 | 709 | 3 |
michael@0 | 710 | >>> m.side_effect = None |
michael@0 | 711 | >>> m() |
michael@0 | 712 | 6 |
michael@0 | 713 | |
michael@0 | 714 | The `side_effect` can also be any iterable object. Repeated calls to the mock |
michael@0 | 715 | will return values from the iterable (until the iterable is exhausted and |
michael@0 | 716 | a `StopIteration` is raised): |
michael@0 | 717 | |
michael@0 | 718 | .. doctest:: |
michael@0 | 719 | |
michael@0 | 720 | >>> m = MagicMock(side_effect=[1, 2, 3]) |
michael@0 | 721 | >>> m() |
michael@0 | 722 | 1 |
michael@0 | 723 | >>> m() |
michael@0 | 724 | 2 |
michael@0 | 725 | >>> m() |
michael@0 | 726 | 3 |
michael@0 | 727 | >>> m() |
michael@0 | 728 | Traceback (most recent call last): |
michael@0 | 729 | ... |
michael@0 | 730 | StopIteration |
michael@0 | 731 | |
michael@0 | 732 | If any members of the iterable are exceptions they will be raised instead of |
michael@0 | 733 | returned: |
michael@0 | 734 | |
michael@0 | 735 | .. doctest:: |
michael@0 | 736 | |
michael@0 | 737 | >>> iterable = (33, ValueError, 66) |
michael@0 | 738 | >>> m = MagicMock(side_effect=iterable) |
michael@0 | 739 | >>> m() |
michael@0 | 740 | 33 |
michael@0 | 741 | >>> m() |
michael@0 | 742 | Traceback (most recent call last): |
michael@0 | 743 | ... |
michael@0 | 744 | ValueError |
michael@0 | 745 | >>> m() |
michael@0 | 746 | 66 |
michael@0 | 747 | |
michael@0 | 748 | |
michael@0 | 749 | .. _deleting-attributes: |
michael@0 | 750 | |
michael@0 | 751 | Deleting Attributes |
michael@0 | 752 | =================== |
michael@0 | 753 | |
michael@0 | 754 | Mock objects create attributes on demand. This allows them to pretend to be |
michael@0 | 755 | objects of any type. |
michael@0 | 756 | |
michael@0 | 757 | You may want a mock object to return `False` to a `hasattr` call, or raise an |
michael@0 | 758 | `AttributeError` when an attribute is fetched. You can do this by providing |
michael@0 | 759 | an object as a `spec` for a mock, but that isn't always convenient. |
michael@0 | 760 | |
michael@0 | 761 | You "block" attributes by deleting them. Once deleted, accessing an attribute |
michael@0 | 762 | will raise an `AttributeError`. |
michael@0 | 763 | |
michael@0 | 764 | .. doctest:: |
michael@0 | 765 | |
michael@0 | 766 | >>> mock = MagicMock() |
michael@0 | 767 | >>> hasattr(mock, 'm') |
michael@0 | 768 | True |
michael@0 | 769 | >>> del mock.m |
michael@0 | 770 | >>> hasattr(mock, 'm') |
michael@0 | 771 | False |
michael@0 | 772 | >>> del mock.f |
michael@0 | 773 | >>> mock.f |
michael@0 | 774 | Traceback (most recent call last): |
michael@0 | 775 | ... |
michael@0 | 776 | AttributeError: f |
michael@0 | 777 | |
michael@0 | 778 | |
michael@0 | 779 | Attaching Mocks as Attributes |
michael@0 | 780 | ============================= |
michael@0 | 781 | |
michael@0 | 782 | When you attach a mock as an attribute of another mock (or as the return |
michael@0 | 783 | value) it becomes a "child" of that mock. Calls to the child are recorded in |
michael@0 | 784 | the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the |
michael@0 | 785 | parent. This is useful for configuring child mocks and then attaching them to |
michael@0 | 786 | the parent, or for attaching mocks to a parent that records all calls to the |
michael@0 | 787 | children and allows you to make assertions about the order of calls between |
michael@0 | 788 | mocks: |
michael@0 | 789 | |
michael@0 | 790 | .. doctest:: |
michael@0 | 791 | |
michael@0 | 792 | >>> parent = MagicMock() |
michael@0 | 793 | >>> child1 = MagicMock(return_value=None) |
michael@0 | 794 | >>> child2 = MagicMock(return_value=None) |
michael@0 | 795 | >>> parent.child1 = child1 |
michael@0 | 796 | >>> parent.child2 = child2 |
michael@0 | 797 | >>> child1(1) |
michael@0 | 798 | >>> child2(2) |
michael@0 | 799 | >>> parent.mock_calls |
michael@0 | 800 | [call.child1(1), call.child2(2)] |
michael@0 | 801 | |
michael@0 | 802 | The exception to this is if the mock has a name. This allows you to prevent |
michael@0 | 803 | the "parenting" if for some reason you don't want it to happen. |
michael@0 | 804 | |
michael@0 | 805 | .. doctest:: |
michael@0 | 806 | |
michael@0 | 807 | >>> mock = MagicMock() |
michael@0 | 808 | >>> not_a_child = MagicMock(name='not-a-child') |
michael@0 | 809 | >>> mock.attribute = not_a_child |
michael@0 | 810 | >>> mock.attribute() |
michael@0 | 811 | <MagicMock name='not-a-child()' id='...'> |
michael@0 | 812 | >>> mock.mock_calls |
michael@0 | 813 | [] |
michael@0 | 814 | |
michael@0 | 815 | Mocks created for you by :func:`patch` are automatically given names. To |
michael@0 | 816 | attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock` |
michael@0 | 817 | method: |
michael@0 | 818 | |
michael@0 | 819 | .. doctest:: |
michael@0 | 820 | |
michael@0 | 821 | >>> thing1 = object() |
michael@0 | 822 | >>> thing2 = object() |
michael@0 | 823 | >>> parent = MagicMock() |
michael@0 | 824 | >>> with patch('__main__.thing1', return_value=None) as child1: |
michael@0 | 825 | ... with patch('__main__.thing2', return_value=None) as child2: |
michael@0 | 826 | ... parent.attach_mock(child1, 'child1') |
michael@0 | 827 | ... parent.attach_mock(child2, 'child2') |
michael@0 | 828 | ... child1('one') |
michael@0 | 829 | ... child2('two') |
michael@0 | 830 | ... |
michael@0 | 831 | >>> parent.mock_calls |
michael@0 | 832 | [call.child1('one'), call.child2('two')] |
michael@0 | 833 | |
michael@0 | 834 | |
michael@0 | 835 | ----- |
michael@0 | 836 | |
michael@0 | 837 | .. [#] The only exceptions are magic methods and attributes (those that have |
michael@0 | 838 | leading and trailing double underscores). Mock doesn't create these but |
michael@0 | 839 | instead of raises an ``AttributeError``. This is because the interpreter |
michael@0 | 840 | will often implicitly request these methods, and gets *very* confused to |
michael@0 | 841 | get a new Mock object when it expects a magic method. If you need magic |
michael@0 | 842 | method support see :ref:`magic methods <magic-methods>`. |