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