1 2:mod:`unittest.mock` --- mock object library 3============================================ 4 5.. module:: unittest.mock 6 :synopsis: Mock object library. 7 8.. moduleauthor:: Michael Foord <michael@python.org> 9.. currentmodule:: unittest.mock 10 11.. versionadded:: 3.3 12 13**Source code:** :source:`Lib/unittest/mock.py` 14 15-------------- 16 17:mod:`unittest.mock` is a library for testing in Python. It allows you to 18replace parts of your system under test with mock objects and make assertions 19about how they have been used. 20 21:mod:`unittest.mock` provides a core :class:`Mock` class removing the need to 22create a host of stubs throughout your test suite. After performing an 23action, you can make assertions about which methods / attributes were used 24and arguments they were called with. You can also specify return values and 25set needed attributes in the normal way. 26 27Additionally, mock provides a :func:`patch` decorator that handles patching 28module and class level attributes within the scope of a test, along with 29:const:`sentinel` for creating unique objects. See the `quick guide`_ for 30some examples of how to use :class:`Mock`, :class:`MagicMock` and 31:func:`patch`. 32 33Mock is very easy to use and is designed for use with :mod:`unittest`. Mock 34is based on the 'action -> assertion' pattern instead of 'record -> replay' 35used by many mocking frameworks. 36 37There is a backport of :mod:`unittest.mock` for earlier versions of Python, 38available as `mock on PyPI <https://pypi.org/project/mock>`_. 39 40 41Quick Guide 42----------- 43 44:class:`Mock` and :class:`MagicMock` objects create all attributes and 45methods as you access them and store details of how they have been used. You 46can configure them, to specify return values or limit what attributes are 47available, and then make assertions about how they have been used: 48 49 >>> from unittest.mock import MagicMock 50 >>> thing = ProductionClass() 51 >>> thing.method = MagicMock(return_value=3) 52 >>> thing.method(3, 4, 5, key='value') 53 3 54 >>> thing.method.assert_called_with(3, 4, 5, key='value') 55 56:attr:`side_effect` allows you to perform side effects, including raising an 57exception when a mock is called: 58 59 >>> mock = Mock(side_effect=KeyError('foo')) 60 >>> mock() 61 Traceback (most recent call last): 62 ... 63 KeyError: 'foo' 64 65 >>> values = {'a': 1, 'b': 2, 'c': 3} 66 >>> def side_effect(arg): 67 ... return values[arg] 68 ... 69 >>> mock.side_effect = side_effect 70 >>> mock('a'), mock('b'), mock('c') 71 (1, 2, 3) 72 >>> mock.side_effect = [5, 4, 3, 2, 1] 73 >>> mock(), mock(), mock() 74 (5, 4, 3) 75 76Mock has many other ways you can configure it and control its behaviour. For 77example the *spec* argument configures the mock to take its specification 78from another object. Attempting to access attributes or methods on the mock 79that don't exist on the spec will fail with an :exc:`AttributeError`. 80 81The :func:`patch` decorator / context manager makes it easy to mock classes or 82objects in a module under test. The object you specify will be replaced with a 83mock (or other object) during the test and restored when the test ends: 84 85 >>> from unittest.mock import patch 86 >>> @patch('module.ClassName2') 87 ... @patch('module.ClassName1') 88 ... def test(MockClass1, MockClass2): 89 ... module.ClassName1() 90 ... module.ClassName2() 91 ... assert MockClass1 is module.ClassName1 92 ... assert MockClass2 is module.ClassName2 93 ... assert MockClass1.called 94 ... assert MockClass2.called 95 ... 96 >>> test() 97 98.. note:: 99 100 When you nest patch decorators the mocks are passed in to the decorated 101 function in the same order they applied (the normal *Python* order that 102 decorators are applied). This means from the bottom up, so in the example 103 above the mock for ``module.ClassName1`` is passed in first. 104 105 With :func:`patch` it matters that you patch objects in the namespace where they 106 are looked up. This is normally straightforward, but for a quick guide 107 read :ref:`where to patch <where-to-patch>`. 108 109As well as a decorator :func:`patch` can be used as a context manager in a with 110statement: 111 112 >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method: 113 ... thing = ProductionClass() 114 ... thing.method(1, 2, 3) 115 ... 116 >>> mock_method.assert_called_once_with(1, 2, 3) 117 118 119There is also :func:`patch.dict` for setting values in a dictionary just 120during a scope and restoring the dictionary to its original state when the test 121ends: 122 123 >>> foo = {'key': 'value'} 124 >>> original = foo.copy() 125 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True): 126 ... assert foo == {'newkey': 'newvalue'} 127 ... 128 >>> assert foo == original 129 130Mock supports the mocking of Python :ref:`magic methods <magic-methods>`. The 131easiest way of using magic methods is with the :class:`MagicMock` class. It 132allows you to do things like: 133 134 >>> mock = MagicMock() 135 >>> mock.__str__.return_value = 'foobarbaz' 136 >>> str(mock) 137 'foobarbaz' 138 >>> mock.__str__.assert_called_with() 139 140Mock allows you to assign functions (or other Mock instances) to magic methods 141and they will be called appropriately. The :class:`MagicMock` class is just a Mock 142variant that has all of the magic methods pre-created for you (well, all the 143useful ones anyway). 144 145The following is an example of using magic methods with the ordinary Mock 146class: 147 148 >>> mock = Mock() 149 >>> mock.__str__ = Mock(return_value='wheeeeee') 150 >>> str(mock) 151 'wheeeeee' 152 153For ensuring that the mock objects in your tests have the same api as the 154objects they are replacing, you can use :ref:`auto-speccing <auto-speccing>`. 155Auto-speccing can be done through the *autospec* argument to patch, or the 156:func:`create_autospec` function. Auto-speccing creates mock objects that 157have the same attributes and methods as the objects they are replacing, and 158any functions and methods (including constructors) have the same call 159signature as the real object. 160 161This ensures that your mocks will fail in the same way as your production 162code if they are used incorrectly: 163 164 >>> from unittest.mock import create_autospec 165 >>> def function(a, b, c): 166 ... pass 167 ... 168 >>> mock_function = create_autospec(function, return_value='fishy') 169 >>> mock_function(1, 2, 3) 170 'fishy' 171 >>> mock_function.assert_called_once_with(1, 2, 3) 172 >>> mock_function('wrong arguments') 173 Traceback (most recent call last): 174 ... 175 TypeError: <lambda>() takes exactly 3 arguments (1 given) 176 177:func:`create_autospec` can also be used on classes, where it copies the signature of 178the ``__init__`` method, and on callable objects where it copies the signature of 179the ``__call__`` method. 180 181 182 183The Mock Class 184-------------- 185 186 187:class:`Mock` is a flexible mock object intended to replace the use of stubs and 188test doubles throughout your code. Mocks are callable and create attributes as 189new mocks when you access them [#]_. Accessing the same attribute will always 190return the same mock. Mocks record how you use them, allowing you to make 191assertions about what your code has done to them. 192 193:class:`MagicMock` is a subclass of :class:`Mock` with all the magic methods 194pre-created and ready to use. There are also non-callable variants, useful 195when you are mocking out objects that aren't callable: 196:class:`NonCallableMock` and :class:`NonCallableMagicMock` 197 198The :func:`patch` decorators makes it easy to temporarily replace classes 199in a particular module with a :class:`Mock` object. By default :func:`patch` will create 200a :class:`MagicMock` for you. You can specify an alternative class of :class:`Mock` using 201the *new_callable* argument to :func:`patch`. 202 203 204.. class:: Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs) 205 206 Create a new :class:`Mock` object. :class:`Mock` takes several optional arguments 207 that specify the behaviour of the Mock object: 208 209 * *spec*: This can be either a list of strings or an existing object (a 210 class or instance) that acts as the specification for the mock object. If 211 you pass in an object then a list of strings is formed by calling dir on 212 the object (excluding unsupported magic attributes and methods). 213 Accessing any attribute not in this list will raise an :exc:`AttributeError`. 214 215 If *spec* is an object (rather than a list of strings) then 216 :attr:`~instance.__class__` returns the class of the spec object. This 217 allows mocks to pass :func:`isinstance` tests. 218 219 * *spec_set*: A stricter variant of *spec*. If used, attempting to *set* 220 or get an attribute on the mock that isn't on the object passed as 221 *spec_set* will raise an :exc:`AttributeError`. 222 223 * *side_effect*: A function to be called whenever the Mock is called. See 224 the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or 225 dynamically changing return values. The function is called with the same 226 arguments as the mock, and unless it returns :data:`DEFAULT`, the return 227 value of this function is used as the return value. 228 229 Alternatively *side_effect* can be an exception class or instance. In 230 this case the exception will be raised when the mock is called. 231 232 If *side_effect* is an iterable then each call to the mock will return 233 the next value from the iterable. 234 235 A *side_effect* can be cleared by setting it to ``None``. 236 237 * *return_value*: The value returned when the mock is called. By default 238 this is a new Mock (created on first access). See the 239 :attr:`return_value` attribute. 240 241 * *unsafe*: By default if any attribute starts with *assert* or 242 *assret* will raise an :exc:`AttributeError`. Passing ``unsafe=True`` 243 will allow access to these attributes. 244 245 .. versionadded:: 3.5 246 247 * *wraps*: Item for the mock object to wrap. If *wraps* is not ``None`` then 248 calling the Mock will pass the call through to the wrapped object 249 (returning the real result). Attribute access on the mock will return a 250 Mock object that wraps the corresponding attribute of the wrapped 251 object (so attempting to access an attribute that doesn't exist will 252 raise an :exc:`AttributeError`). 253 254 If the mock has an explicit *return_value* set then calls are not passed 255 to the wrapped object and the *return_value* is returned instead. 256 257 * *name*: If the mock has a name then it will be used in the repr of the 258 mock. This can be useful for debugging. The name is propagated to child 259 mocks. 260 261 Mocks can also be called with arbitrary keyword arguments. These will be 262 used to set attributes on the mock after it is created. See the 263 :meth:`configure_mock` method for details. 264 265 .. method:: assert_called(*args, **kwargs) 266 267 Assert that the mock was called at least once. 268 269 >>> mock = Mock() 270 >>> mock.method() 271 <Mock name='mock.method()' id='...'> 272 >>> mock.method.assert_called() 273 274 .. versionadded:: 3.6 275 276 .. method:: assert_called_once(*args, **kwargs) 277 278 Assert that the mock was called exactly once. 279 280 >>> mock = Mock() 281 >>> mock.method() 282 <Mock name='mock.method()' id='...'> 283 >>> mock.method.assert_called_once() 284 >>> mock.method() 285 <Mock name='mock.method()' id='...'> 286 >>> mock.method.assert_called_once() 287 Traceback (most recent call last): 288 ... 289 AssertionError: Expected 'method' to have been called once. Called 2 times. 290 291 .. versionadded:: 3.6 292 293 294 .. method:: assert_called_with(*args, **kwargs) 295 296 This method is a convenient way of asserting that calls are made in a 297 particular way: 298 299 >>> mock = Mock() 300 >>> mock.method(1, 2, 3, test='wow') 301 <Mock name='mock.method()' id='...'> 302 >>> mock.method.assert_called_with(1, 2, 3, test='wow') 303 304 .. method:: assert_called_once_with(*args, **kwargs) 305 306 Assert that the mock was called exactly once and that that call was 307 with the specified arguments. 308 309 >>> mock = Mock(return_value=None) 310 >>> mock('foo', bar='baz') 311 >>> mock.assert_called_once_with('foo', bar='baz') 312 >>> mock('other', bar='values') 313 >>> mock.assert_called_once_with('other', bar='values') 314 Traceback (most recent call last): 315 ... 316 AssertionError: Expected 'mock' to be called once. Called 2 times. 317 318 319 .. method:: assert_any_call(*args, **kwargs) 320 321 assert the mock has been called with the specified arguments. 322 323 The assert passes if the mock has *ever* been called, unlike 324 :meth:`assert_called_with` and :meth:`assert_called_once_with` that 325 only pass if the call is the most recent one, and in the case of 326 :meth:`assert_called_once_with` it must also be the only call. 327 328 >>> mock = Mock(return_value=None) 329 >>> mock(1, 2, arg='thing') 330 >>> mock('some', 'thing', 'else') 331 >>> mock.assert_any_call(1, 2, arg='thing') 332 333 334 .. method:: assert_has_calls(calls, any_order=False) 335 336 assert the mock has been called with the specified calls. 337 The :attr:`mock_calls` list is checked for the calls. 338 339 If *any_order* is false (the default) then the calls must be 340 sequential. There can be extra calls before or after the 341 specified calls. 342 343 If *any_order* is true then the calls can be in any order, but 344 they must all appear in :attr:`mock_calls`. 345 346 >>> mock = Mock(return_value=None) 347 >>> mock(1) 348 >>> mock(2) 349 >>> mock(3) 350 >>> mock(4) 351 >>> calls = [call(2), call(3)] 352 >>> mock.assert_has_calls(calls) 353 >>> calls = [call(4), call(2), call(3)] 354 >>> mock.assert_has_calls(calls, any_order=True) 355 356 .. method:: assert_not_called() 357 358 Assert the mock was never called. 359 360 >>> m = Mock() 361 >>> m.hello.assert_not_called() 362 >>> obj = m.hello() 363 >>> m.hello.assert_not_called() 364 Traceback (most recent call last): 365 ... 366 AssertionError: Expected 'hello' to not have been called. Called 1 times. 367 368 .. versionadded:: 3.5 369 370 371 .. method:: reset_mock(*, return_value=False, side_effect=False) 372 373 The reset_mock method resets all the call attributes on a mock object: 374 375 >>> mock = Mock(return_value=None) 376 >>> mock('hello') 377 >>> mock.called 378 True 379 >>> mock.reset_mock() 380 >>> mock.called 381 False 382 383 .. versionchanged:: 3.6 384 Added two keyword only argument to the reset_mock function. 385 386 This can be useful where you want to make a series of assertions that 387 reuse the same object. Note that :meth:`reset_mock` *doesn't* clear the 388 return value, :attr:`side_effect` or any child attributes you have 389 set using normal assignment by default. In case you want to reset 390 *return_value* or :attr:`side_effect`, then pass the corresponding 391 parameter as ``True``. Child mocks and the return value mock 392 (if any) are reset as well. 393 394 .. note:: *return_value*, and :attr:`side_effect` are keyword only 395 argument. 396 397 398 .. method:: mock_add_spec(spec, spec_set=False) 399 400 Add a spec to a mock. *spec* can either be an object or a 401 list of strings. Only attributes on the *spec* can be fetched as 402 attributes from the mock. 403 404 If *spec_set* is true then only attributes on the spec can be set. 405 406 407 .. method:: attach_mock(mock, attribute) 408 409 Attach a mock as an attribute of this one, replacing its name and 410 parent. Calls to the attached mock will be recorded in the 411 :attr:`method_calls` and :attr:`mock_calls` attributes of this one. 412 413 414 .. method:: configure_mock(**kwargs) 415 416 Set attributes on the mock through keyword arguments. 417 418 Attributes plus return values and side effects can be set on child 419 mocks using standard dot notation and unpacking a dictionary in the 420 method call: 421 422 >>> mock = Mock() 423 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} 424 >>> mock.configure_mock(**attrs) 425 >>> mock.method() 426 3 427 >>> mock.other() 428 Traceback (most recent call last): 429 ... 430 KeyError 431 432 The same thing can be achieved in the constructor call to mocks: 433 434 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} 435 >>> mock = Mock(some_attribute='eggs', **attrs) 436 >>> mock.some_attribute 437 'eggs' 438 >>> mock.method() 439 3 440 >>> mock.other() 441 Traceback (most recent call last): 442 ... 443 KeyError 444 445 :meth:`configure_mock` exists to make it easier to do configuration 446 after the mock has been created. 447 448 449 .. method:: __dir__() 450 451 :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results. 452 For mocks with a *spec* this includes all the permitted attributes 453 for the mock. 454 455 See :data:`FILTER_DIR` for what this filtering does, and how to 456 switch it off. 457 458 459 .. method:: _get_child_mock(**kw) 460 461 Create the child mocks for attributes and return value. 462 By default child mocks will be the same type as the parent. 463 Subclasses of Mock may want to override this to customize the way 464 child mocks are made. 465 466 For non-callable mocks the callable variant will be used (rather than 467 any custom subclass). 468 469 470 .. attribute:: called 471 472 A boolean representing whether or not the mock object has been called: 473 474 >>> mock = Mock(return_value=None) 475 >>> mock.called 476 False 477 >>> mock() 478 >>> mock.called 479 True 480 481 .. attribute:: call_count 482 483 An integer telling you how many times the mock object has been called: 484 485 >>> mock = Mock(return_value=None) 486 >>> mock.call_count 487 0 488 >>> mock() 489 >>> mock() 490 >>> mock.call_count 491 2 492 493 494 .. attribute:: return_value 495 496 Set this to configure the value returned by calling the mock: 497 498 >>> mock = Mock() 499 >>> mock.return_value = 'fish' 500 >>> mock() 501 'fish' 502 503 The default return value is a mock object and you can configure it in 504 the normal way: 505 506 >>> mock = Mock() 507 >>> mock.return_value.attribute = sentinel.Attribute 508 >>> mock.return_value() 509 <Mock name='mock()()' id='...'> 510 >>> mock.return_value.assert_called_with() 511 512 :attr:`return_value` can also be set in the constructor: 513 514 >>> mock = Mock(return_value=3) 515 >>> mock.return_value 516 3 517 >>> mock() 518 3 519 520 521 .. attribute:: side_effect 522 523 This can either be a function to be called when the mock is called, 524 an iterable or an exception (class or instance) to be raised. 525 526 If you pass in a function it will be called with same arguments as the 527 mock and unless the function returns the :data:`DEFAULT` singleton the 528 call to the mock will then return whatever the function returns. If the 529 function returns :data:`DEFAULT` then the mock will return its normal 530 value (from the :attr:`return_value`). 531 532 If you pass in an iterable, it is used to retrieve an iterator which 533 must yield a value on every call. This value can either be an exception 534 instance to be raised, or a value to be returned from the call to the 535 mock (:data:`DEFAULT` handling is identical to the function case). 536 537 An example of a mock that raises an exception (to test exception 538 handling of an API): 539 540 >>> mock = Mock() 541 >>> mock.side_effect = Exception('Boom!') 542 >>> mock() 543 Traceback (most recent call last): 544 ... 545 Exception: Boom! 546 547 Using :attr:`side_effect` to return a sequence of values: 548 549 >>> mock = Mock() 550 >>> mock.side_effect = [3, 2, 1] 551 >>> mock(), mock(), mock() 552 (3, 2, 1) 553 554 Using a callable: 555 556 >>> mock = Mock(return_value=3) 557 >>> def side_effect(*args, **kwargs): 558 ... return DEFAULT 559 ... 560 >>> mock.side_effect = side_effect 561 >>> mock() 562 3 563 564 :attr:`side_effect` can be set in the constructor. Here's an example that 565 adds one to the value the mock is called with and returns it: 566 567 >>> side_effect = lambda value: value + 1 568 >>> mock = Mock(side_effect=side_effect) 569 >>> mock(3) 570 4 571 >>> mock(-8) 572 -7 573 574 Setting :attr:`side_effect` to ``None`` clears it: 575 576 >>> m = Mock(side_effect=KeyError, return_value=3) 577 >>> m() 578 Traceback (most recent call last): 579 ... 580 KeyError 581 >>> m.side_effect = None 582 >>> m() 583 3 584 585 586 .. attribute:: call_args 587 588 This is either ``None`` (if the mock hasn't been called), or the 589 arguments that the mock was last called with. This will be in the 590 form of a tuple: the first member is any ordered arguments the mock 591 was called with (or an empty tuple) and the second member is any 592 keyword arguments (or an empty dictionary). 593 594 >>> mock = Mock(return_value=None) 595 >>> print(mock.call_args) 596 None 597 >>> mock() 598 >>> mock.call_args 599 call() 600 >>> mock.call_args == () 601 True 602 >>> mock(3, 4) 603 >>> mock.call_args 604 call(3, 4) 605 >>> mock.call_args == ((3, 4),) 606 True 607 >>> mock(3, 4, 5, key='fish', next='w00t!') 608 >>> mock.call_args 609 call(3, 4, 5, key='fish', next='w00t!') 610 611 :attr:`call_args`, along with members of the lists :attr:`call_args_list`, 612 :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects. 613 These are tuples, so they can be unpacked to get at the individual 614 arguments and make more complex assertions. See 615 :ref:`calls as tuples <calls-as-tuples>`. 616 617 618 .. attribute:: call_args_list 619 620 This is a list of all the calls made to the mock object in sequence 621 (so the length of the list is the number of times it has been 622 called). Before any calls have been made it is an empty list. The 623 :data:`call` object can be used for conveniently constructing lists of 624 calls to compare with :attr:`call_args_list`. 625 626 >>> mock = Mock(return_value=None) 627 >>> mock() 628 >>> mock(3, 4) 629 >>> mock(key='fish', next='w00t!') 630 >>> mock.call_args_list 631 [call(), call(3, 4), call(key='fish', next='w00t!')] 632 >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)] 633 >>> mock.call_args_list == expected 634 True 635 636 Members of :attr:`call_args_list` are :data:`call` objects. These can be 637 unpacked as tuples to get at the individual arguments. See 638 :ref:`calls as tuples <calls-as-tuples>`. 639 640 641 .. attribute:: method_calls 642 643 As well as tracking calls to themselves, mocks also track calls to 644 methods and attributes, and *their* methods and attributes: 645 646 >>> mock = Mock() 647 >>> mock.method() 648 <Mock name='mock.method()' id='...'> 649 >>> mock.property.method.attribute() 650 <Mock name='mock.property.method.attribute()' id='...'> 651 >>> mock.method_calls 652 [call.method(), call.property.method.attribute()] 653 654 Members of :attr:`method_calls` are :data:`call` objects. These can be 655 unpacked as tuples to get at the individual arguments. See 656 :ref:`calls as tuples <calls-as-tuples>`. 657 658 659 .. attribute:: mock_calls 660 661 :attr:`mock_calls` records *all* calls to the mock object, its methods, 662 magic methods *and* return value mocks. 663 664 >>> mock = MagicMock() 665 >>> result = mock(1, 2, 3) 666 >>> mock.first(a=3) 667 <MagicMock name='mock.first()' id='...'> 668 >>> mock.second() 669 <MagicMock name='mock.second()' id='...'> 670 >>> int(mock) 671 1 672 >>> result(1) 673 <MagicMock name='mock()()' id='...'> 674 >>> expected = [call(1, 2, 3), call.first(a=3), call.second(), 675 ... call.__int__(), call()(1)] 676 >>> mock.mock_calls == expected 677 True 678 679 Members of :attr:`mock_calls` are :data:`call` objects. These can be 680 unpacked as tuples to get at the individual arguments. See 681 :ref:`calls as tuples <calls-as-tuples>`. 682 683 .. note:: 684 685 The way :attr:`mock_calls` are recorded means that where nested 686 calls are made, the parameters of ancestor calls are not recorded 687 and so will always compare equal: 688 689 >>> mock = MagicMock() 690 >>> mock.top(a=3).bottom() 691 <MagicMock name='mock.top().bottom()' id='...'> 692 >>> mock.mock_calls 693 [call.top(a=3), call.top().bottom()] 694 >>> mock.mock_calls[-1] == call.top(a=-1).bottom() 695 True 696 697 .. attribute:: __class__ 698 699 Normally the :attr:`__class__` attribute of an object will return its type. 700 For a mock object with a :attr:`spec`, ``__class__`` returns the spec class 701 instead. This allows mock objects to pass :func:`isinstance` tests for the 702 object they are replacing / masquerading as: 703 704 >>> mock = Mock(spec=3) 705 >>> isinstance(mock, int) 706 True 707 708 :attr:`__class__` is assignable to, this allows a mock to pass an 709 :func:`isinstance` check without forcing you to use a spec: 710 711 >>> mock = Mock() 712 >>> mock.__class__ = dict 713 >>> isinstance(mock, dict) 714 True 715 716.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs) 717 718 A non-callable version of :class:`Mock`. The constructor parameters have the same 719 meaning of :class:`Mock`, with the exception of *return_value* and *side_effect* 720 which have no meaning on a non-callable mock. 721 722Mock objects that use a class or an instance as a :attr:`spec` or 723:attr:`spec_set` are able to pass :func:`isinstance` tests: 724 725 >>> mock = Mock(spec=SomeClass) 726 >>> isinstance(mock, SomeClass) 727 True 728 >>> mock = Mock(spec_set=SomeClass()) 729 >>> isinstance(mock, SomeClass) 730 True 731 732The :class:`Mock` classes have support for mocking magic methods. See :ref:`magic 733methods <magic-methods>` for the full details. 734 735The mock classes and the :func:`patch` decorators all take arbitrary keyword 736arguments for configuration. For the :func:`patch` decorators the keywords are 737passed to the constructor of the mock being created. The keyword arguments 738are for configuring attributes of the mock: 739 740 >>> m = MagicMock(attribute=3, other='fish') 741 >>> m.attribute 742 3 743 >>> m.other 744 'fish' 745 746The return value and side effect of child mocks can be set in the same way, 747using dotted notation. As you can't use dotted names directly in a call you 748have to create a dictionary and unpack it using ``**``: 749 750 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} 751 >>> mock = Mock(some_attribute='eggs', **attrs) 752 >>> mock.some_attribute 753 'eggs' 754 >>> mock.method() 755 3 756 >>> mock.other() 757 Traceback (most recent call last): 758 ... 759 KeyError 760 761A callable mock which was created with a *spec* (or a *spec_set*) will 762introspect the specification object's signature when matching calls to 763the mock. Therefore, it can match the actual call's arguments regardless 764of whether they were passed positionally or by name:: 765 766 >>> def f(a, b, c): pass 767 ... 768 >>> mock = Mock(spec=f) 769 >>> mock(1, 2, c=3) 770 <Mock name='mock()' id='140161580456576'> 771 >>> mock.assert_called_with(1, 2, 3) 772 >>> mock.assert_called_with(a=1, b=2, c=3) 773 774This applies to :meth:`~Mock.assert_called_with`, 775:meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and 776:meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also 777apply to method calls on the mock object. 778 779 .. versionchanged:: 3.4 780 Added signature introspection on specced and autospecced mock objects. 781 782 783.. class:: PropertyMock(*args, **kwargs) 784 785 A mock intended to be used as a property, or other descriptor, on a class. 786 :class:`PropertyMock` provides :meth:`__get__` and :meth:`__set__` methods 787 so you can specify a return value when it is fetched. 788 789 Fetching a :class:`PropertyMock` instance from an object calls the mock, with 790 no args. Setting it calls the mock with the value being set. 791 792 >>> class Foo: 793 ... @property 794 ... def foo(self): 795 ... return 'something' 796 ... @foo.setter 797 ... def foo(self, value): 798 ... pass 799 ... 800 >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo: 801 ... mock_foo.return_value = 'mockity-mock' 802 ... this_foo = Foo() 803 ... print(this_foo.foo) 804 ... this_foo.foo = 6 805 ... 806 mockity-mock 807 >>> mock_foo.mock_calls 808 [call(), call(6)] 809 810Because of the way mock attributes are stored you can't directly attach a 811:class:`PropertyMock` to a mock object. Instead you can attach it to the mock type 812object:: 813 814 >>> m = MagicMock() 815 >>> p = PropertyMock(return_value=3) 816 >>> type(m).foo = p 817 >>> m.foo 818 3 819 >>> p.assert_called_once_with() 820 821 822Calling 823~~~~~~~ 824 825Mock objects are callable. The call will return the value set as the 826:attr:`~Mock.return_value` attribute. The default return value is a new Mock 827object; it is created the first time the return value is accessed (either 828explicitly or by calling the Mock) - but it is stored and the same one 829returned each time. 830 831Calls made to the object will be recorded in the attributes 832like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`. 833 834If :attr:`~Mock.side_effect` is set then it will be called after the call has 835been recorded, so if :attr:`side_effect` raises an exception the call is still 836recorded. 837 838The simplest way to make a mock raise an exception when called is to make 839:attr:`~Mock.side_effect` an exception class or instance: 840 841 >>> m = MagicMock(side_effect=IndexError) 842 >>> m(1, 2, 3) 843 Traceback (most recent call last): 844 ... 845 IndexError 846 >>> m.mock_calls 847 [call(1, 2, 3)] 848 >>> m.side_effect = KeyError('Bang!') 849 >>> m('two', 'three', 'four') 850 Traceback (most recent call last): 851 ... 852 KeyError: 'Bang!' 853 >>> m.mock_calls 854 [call(1, 2, 3), call('two', 'three', 'four')] 855 856If :attr:`side_effect` is a function then whatever that function returns is what 857calls to the mock return. The :attr:`side_effect` function is called with the 858same arguments as the mock. This allows you to vary the return value of the 859call dynamically, based on the input: 860 861 >>> def side_effect(value): 862 ... return value + 1 863 ... 864 >>> m = MagicMock(side_effect=side_effect) 865 >>> m(1) 866 2 867 >>> m(2) 868 3 869 >>> m.mock_calls 870 [call(1), call(2)] 871 872If you want the mock to still return the default return value (a new mock), or 873any set return value, then there are two ways of doing this. Either return 874:attr:`mock.return_value` from inside :attr:`side_effect`, or return :data:`DEFAULT`: 875 876 >>> m = MagicMock() 877 >>> def side_effect(*args, **kwargs): 878 ... return m.return_value 879 ... 880 >>> m.side_effect = side_effect 881 >>> m.return_value = 3 882 >>> m() 883 3 884 >>> def side_effect(*args, **kwargs): 885 ... return DEFAULT 886 ... 887 >>> m.side_effect = side_effect 888 >>> m() 889 3 890 891To remove a :attr:`side_effect`, and return to the default behaviour, set the 892:attr:`side_effect` to ``None``: 893 894 >>> m = MagicMock(return_value=6) 895 >>> def side_effect(*args, **kwargs): 896 ... return 3 897 ... 898 >>> m.side_effect = side_effect 899 >>> m() 900 3 901 >>> m.side_effect = None 902 >>> m() 903 6 904 905The :attr:`side_effect` can also be any iterable object. Repeated calls to the mock 906will return values from the iterable (until the iterable is exhausted and 907a :exc:`StopIteration` is raised): 908 909 >>> m = MagicMock(side_effect=[1, 2, 3]) 910 >>> m() 911 1 912 >>> m() 913 2 914 >>> m() 915 3 916 >>> m() 917 Traceback (most recent call last): 918 ... 919 StopIteration 920 921If any members of the iterable are exceptions they will be raised instead of 922returned:: 923 924 >>> iterable = (33, ValueError, 66) 925 >>> m = MagicMock(side_effect=iterable) 926 >>> m() 927 33 928 >>> m() 929 Traceback (most recent call last): 930 ... 931 ValueError 932 >>> m() 933 66 934 935 936.. _deleting-attributes: 937 938Deleting Attributes 939~~~~~~~~~~~~~~~~~~~ 940 941Mock objects create attributes on demand. This allows them to pretend to be 942objects of any type. 943 944You may want a mock object to return ``False`` to a :func:`hasattr` call, or raise an 945:exc:`AttributeError` when an attribute is fetched. You can do this by providing 946an object as a :attr:`spec` for a mock, but that isn't always convenient. 947 948You "block" attributes by deleting them. Once deleted, accessing an attribute 949will raise an :exc:`AttributeError`. 950 951 >>> mock = MagicMock() 952 >>> hasattr(mock, 'm') 953 True 954 >>> del mock.m 955 >>> hasattr(mock, 'm') 956 False 957 >>> del mock.f 958 >>> mock.f 959 Traceback (most recent call last): 960 ... 961 AttributeError: f 962 963 964Mock names and the name attribute 965~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 966 967Since "name" is an argument to the :class:`Mock` constructor, if you want your 968mock object to have a "name" attribute you can't just pass it in at creation 969time. There are two alternatives. One option is to use 970:meth:`~Mock.configure_mock`:: 971 972 >>> mock = MagicMock() 973 >>> mock.configure_mock(name='my_name') 974 >>> mock.name 975 'my_name' 976 977A simpler option is to simply set the "name" attribute after mock creation:: 978 979 >>> mock = MagicMock() 980 >>> mock.name = "foo" 981 982 983Attaching Mocks as Attributes 984~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 985 986When you attach a mock as an attribute of another mock (or as the return 987value) it becomes a "child" of that mock. Calls to the child are recorded in 988the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the 989parent. This is useful for configuring child mocks and then attaching them to 990the parent, or for attaching mocks to a parent that records all calls to the 991children and allows you to make assertions about the order of calls between 992mocks: 993 994 >>> parent = MagicMock() 995 >>> child1 = MagicMock(return_value=None) 996 >>> child2 = MagicMock(return_value=None) 997 >>> parent.child1 = child1 998 >>> parent.child2 = child2 999 >>> child1(1) 1000 >>> child2(2) 1001 >>> parent.mock_calls 1002 [call.child1(1), call.child2(2)] 1003 1004The exception to this is if the mock has a name. This allows you to prevent 1005the "parenting" if for some reason you don't want it to happen. 1006 1007 >>> mock = MagicMock() 1008 >>> not_a_child = MagicMock(name='not-a-child') 1009 >>> mock.attribute = not_a_child 1010 >>> mock.attribute() 1011 <MagicMock name='not-a-child()' id='...'> 1012 >>> mock.mock_calls 1013 [] 1014 1015Mocks created for you by :func:`patch` are automatically given names. To 1016attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock` 1017method: 1018 1019 >>> thing1 = object() 1020 >>> thing2 = object() 1021 >>> parent = MagicMock() 1022 >>> with patch('__main__.thing1', return_value=None) as child1: 1023 ... with patch('__main__.thing2', return_value=None) as child2: 1024 ... parent.attach_mock(child1, 'child1') 1025 ... parent.attach_mock(child2, 'child2') 1026 ... child1('one') 1027 ... child2('two') 1028 ... 1029 >>> parent.mock_calls 1030 [call.child1('one'), call.child2('two')] 1031 1032 1033.. [#] The only exceptions are magic methods and attributes (those that have 1034 leading and trailing double underscores). Mock doesn't create these but 1035 instead raises an :exc:`AttributeError`. This is because the interpreter 1036 will often implicitly request these methods, and gets *very* confused to 1037 get a new Mock object when it expects a magic method. If you need magic 1038 method support see :ref:`magic methods <magic-methods>`. 1039 1040 1041The patchers 1042------------ 1043 1044The patch decorators are used for patching objects only within the scope of 1045the function they decorate. They automatically handle the unpatching for you, 1046even if exceptions are raised. All of these functions can also be used in with 1047statements or as class decorators. 1048 1049 1050patch 1051~~~~~ 1052 1053.. note:: 1054 1055 :func:`patch` is straightforward to use. The key is to do the patching in the 1056 right namespace. See the section `where to patch`_. 1057 1058.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) 1059 1060 :func:`patch` acts as a function decorator, class decorator or a context 1061 manager. Inside the body of the function or with statement, the *target* 1062 is patched with a *new* object. When the function/with statement exits 1063 the patch is undone. 1064 1065 If *new* is omitted, then the target is replaced with a 1066 :class:`MagicMock`. If :func:`patch` is used as a decorator and *new* is 1067 omitted, the created mock is passed in as an extra argument to the 1068 decorated function. If :func:`patch` is used as a context manager the created 1069 mock is returned by the context manager. 1070 1071 *target* should be a string in the form ``'package.module.ClassName'``. The 1072 *target* is imported and the specified object replaced with the *new* 1073 object, so the *target* must be importable from the environment you are 1074 calling :func:`patch` from. The target is imported when the decorated function 1075 is executed, not at decoration time. 1076 1077 The *spec* and *spec_set* keyword arguments are passed to the :class:`MagicMock` 1078 if patch is creating one for you. 1079 1080 In addition you can pass ``spec=True`` or ``spec_set=True``, which causes 1081 patch to pass in the object being mocked as the spec/spec_set object. 1082 1083 *new_callable* allows you to specify a different class, or callable object, 1084 that will be called to create the *new* object. By default :class:`MagicMock` is 1085 used. 1086 1087 A more powerful form of *spec* is *autospec*. If you set ``autospec=True`` 1088 then the mock will be created with a spec from the object being replaced. 1089 All attributes of the mock will also have the spec of the corresponding 1090 attribute of the object being replaced. Methods and functions being mocked 1091 will have their arguments checked and will raise a :exc:`TypeError` if they are 1092 called with the wrong signature. For mocks 1093 replacing a class, their return value (the 'instance') will have the same 1094 spec as the class. See the :func:`create_autospec` function and 1095 :ref:`auto-speccing`. 1096 1097 Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an 1098 arbitrary object as the spec instead of the one being replaced. 1099 1100 By default :func:`patch` will fail to replace attributes that don't exist. 1101 If you pass in ``create=True``, and the attribute doesn't exist, patch will 1102 create the attribute for you when the patched function is called, and delete 1103 it again after the patched function has exited. This is useful for writing 1104 tests against attributes that your production code creates at runtime. It is 1105 off by default because it can be dangerous. With it switched on you can 1106 write passing tests against APIs that don't actually exist! 1107 1108 .. note:: 1109 1110 .. versionchanged:: 3.5 1111 If you are patching builtins in a module then you don't 1112 need to pass ``create=True``, it will be added by default. 1113 1114 Patch can be used as a :class:`TestCase` class decorator. It works by 1115 decorating each test method in the class. This reduces the boilerplate 1116 code when your test methods share a common patchings set. :func:`patch` finds 1117 tests by looking for method names that start with ``patch.TEST_PREFIX``. 1118 By default this is ``'test'``, which matches the way :mod:`unittest` finds tests. 1119 You can specify an alternative prefix by setting ``patch.TEST_PREFIX``. 1120 1121 Patch can be used as a context manager, with the with statement. Here the 1122 patching applies to the indented block after the with statement. If you 1123 use "as" then the patched object will be bound to the name after the 1124 "as"; very useful if :func:`patch` is creating a mock object for you. 1125 1126 :func:`patch` takes arbitrary keyword arguments. These will be passed to 1127 the :class:`Mock` (or *new_callable*) on construction. 1128 1129 ``patch.dict(...)``, ``patch.multiple(...)`` and ``patch.object(...)`` are 1130 available for alternate use-cases. 1131 1132:func:`patch` as function decorator, creating the mock for you and passing it into 1133the decorated function: 1134 1135 >>> @patch('__main__.SomeClass') 1136 ... def function(normal_argument, mock_class): 1137 ... print(mock_class is SomeClass) 1138 ... 1139 >>> function(None) 1140 True 1141 1142Patching a class replaces the class with a :class:`MagicMock` *instance*. If the 1143class is instantiated in the code under test then it will be the 1144:attr:`~Mock.return_value` of the mock that will be used. 1145 1146If the class is instantiated multiple times you could use 1147:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you 1148can set the *return_value* to be anything you want. 1149 1150To configure return values on methods of *instances* on the patched class 1151you must do this on the :attr:`return_value`. For example: 1152 1153 >>> class Class: 1154 ... def method(self): 1155 ... pass 1156 ... 1157 >>> with patch('__main__.Class') as MockClass: 1158 ... instance = MockClass.return_value 1159 ... instance.method.return_value = 'foo' 1160 ... assert Class() is instance 1161 ... assert Class().method() == 'foo' 1162 ... 1163 1164If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the 1165return value of the created mock will have the same spec. 1166 1167 >>> Original = Class 1168 >>> patcher = patch('__main__.Class', spec=True) 1169 >>> MockClass = patcher.start() 1170 >>> instance = MockClass() 1171 >>> assert isinstance(instance, Original) 1172 >>> patcher.stop() 1173 1174The *new_callable* argument is useful where you want to use an alternative 1175class to the default :class:`MagicMock` for the created mock. For example, if 1176you wanted a :class:`NonCallableMock` to be used: 1177 1178 >>> thing = object() 1179 >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing: 1180 ... assert thing is mock_thing 1181 ... thing() 1182 ... 1183 Traceback (most recent call last): 1184 ... 1185 TypeError: 'NonCallableMock' object is not callable 1186 1187Another use case might be to replace an object with an :class:`io.StringIO` instance: 1188 1189 >>> from io import StringIO 1190 >>> def foo(): 1191 ... print('Something') 1192 ... 1193 >>> @patch('sys.stdout', new_callable=StringIO) 1194 ... def test(mock_stdout): 1195 ... foo() 1196 ... assert mock_stdout.getvalue() == 'Something\n' 1197 ... 1198 >>> test() 1199 1200When :func:`patch` is creating a mock for you, it is common that the first thing 1201you need to do is to configure the mock. Some of that configuration can be done 1202in the call to patch. Any arbitrary keywords you pass into the call will be 1203used to set attributes on the created mock: 1204 1205 >>> patcher = patch('__main__.thing', first='one', second='two') 1206 >>> mock_thing = patcher.start() 1207 >>> mock_thing.first 1208 'one' 1209 >>> mock_thing.second 1210 'two' 1211 1212As well as attributes on the created mock attributes, like the 1213:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can 1214also be configured. These aren't syntactically valid to pass in directly as 1215keyword arguments, but a dictionary with these as keys can still be expanded 1216into a :func:`patch` call using ``**``: 1217 1218 >>> config = {'method.return_value': 3, 'other.side_effect': KeyError} 1219 >>> patcher = patch('__main__.thing', **config) 1220 >>> mock_thing = patcher.start() 1221 >>> mock_thing.method() 1222 3 1223 >>> mock_thing.other() 1224 Traceback (most recent call last): 1225 ... 1226 KeyError 1227 1228By default, attempting to patch a function in a module (or a method or an 1229attribute in a class) that does not exist will fail with :exc:`AttributeError`:: 1230 1231 >>> @patch('sys.non_existing_attribute', 42) 1232 ... def test(): 1233 ... assert sys.non_existing_attribute == 42 1234 ... 1235 >>> test() 1236 Traceback (most recent call last): 1237 ... 1238 AttributeError: <module 'sys' (built-in)> does not have the attribute 'non_existing' 1239 1240but adding ``create=True`` in the call to :func:`patch` will make the previous example 1241work as expected:: 1242 1243 >>> @patch('sys.non_existing_attribute', 42, create=True) 1244 ... def test(mock_stdout): 1245 ... assert sys.non_existing_attribute == 42 1246 ... 1247 >>> test() 1248 1249 1250patch.object 1251~~~~~~~~~~~~ 1252 1253.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) 1254 1255 patch the named member (*attribute*) on an object (*target*) with a mock 1256 object. 1257 1258 :func:`patch.object` can be used as a decorator, class decorator or a context 1259 manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* and 1260 *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`, 1261 :func:`patch.object` takes arbitrary keyword arguments for configuring the mock 1262 object it creates. 1263 1264 When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX`` 1265 for choosing which methods to wrap. 1266 1267You can either call :func:`patch.object` with three arguments or two arguments. The 1268three argument form takes the object to be patched, the attribute name and the 1269object to replace the attribute with. 1270 1271When calling with the two argument form you omit the replacement object, and a 1272mock is created for you and passed in as an extra argument to the decorated 1273function: 1274 1275 >>> @patch.object(SomeClass, 'class_method') 1276 ... def test(mock_method): 1277 ... SomeClass.class_method(3) 1278 ... mock_method.assert_called_with(3) 1279 ... 1280 >>> test() 1281 1282*spec*, *create* and the other arguments to :func:`patch.object` have the same 1283meaning as they do for :func:`patch`. 1284 1285 1286patch.dict 1287~~~~~~~~~~ 1288 1289.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs) 1290 1291 Patch a dictionary, or dictionary like object, and restore the dictionary 1292 to its original state after the test. 1293 1294 *in_dict* can be a dictionary or a mapping like container. If it is a 1295 mapping then it must at least support getting, setting and deleting items 1296 plus iterating over keys. 1297 1298 *in_dict* can also be a string specifying the name of the dictionary, which 1299 will then be fetched by importing it. 1300 1301 *values* can be a dictionary of values to set in the dictionary. *values* 1302 can also be an iterable of ``(key, value)`` pairs. 1303 1304 If *clear* is true then the dictionary will be cleared before the new 1305 values are set. 1306 1307 :func:`patch.dict` can also be called with arbitrary keyword arguments to set 1308 values in the dictionary. 1309 1310 :func:`patch.dict` can be used as a context manager, decorator or class 1311 decorator. When used as a class decorator :func:`patch.dict` honours 1312 ``patch.TEST_PREFIX`` for choosing which methods to wrap. 1313 1314:func:`patch.dict` can be used to add members to a dictionary, or simply let a test 1315change a dictionary, and ensure the dictionary is restored when the test 1316ends. 1317 1318 >>> foo = {} 1319 >>> with patch.dict(foo, {'newkey': 'newvalue'}): 1320 ... assert foo == {'newkey': 'newvalue'} 1321 ... 1322 >>> assert foo == {} 1323 1324 >>> import os 1325 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}): 1326 ... print(os.environ['newkey']) 1327 ... 1328 newvalue 1329 >>> assert 'newkey' not in os.environ 1330 1331Keywords can be used in the :func:`patch.dict` call to set values in the dictionary: 1332 1333 >>> mymodule = MagicMock() 1334 >>> mymodule.function.return_value = 'fish' 1335 >>> with patch.dict('sys.modules', mymodule=mymodule): 1336 ... import mymodule 1337 ... mymodule.function('some', 'args') 1338 ... 1339 'fish' 1340 1341:func:`patch.dict` can be used with dictionary like objects that aren't actually 1342dictionaries. At the very minimum they must support item getting, setting, 1343deleting and either iteration or membership test. This corresponds to the 1344magic methods :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__` and either 1345:meth:`__iter__` or :meth:`__contains__`. 1346 1347 >>> class Container: 1348 ... def __init__(self): 1349 ... self.values = {} 1350 ... def __getitem__(self, name): 1351 ... return self.values[name] 1352 ... def __setitem__(self, name, value): 1353 ... self.values[name] = value 1354 ... def __delitem__(self, name): 1355 ... del self.values[name] 1356 ... def __iter__(self): 1357 ... return iter(self.values) 1358 ... 1359 >>> thing = Container() 1360 >>> thing['one'] = 1 1361 >>> with patch.dict(thing, one=2, two=3): 1362 ... assert thing['one'] == 2 1363 ... assert thing['two'] == 3 1364 ... 1365 >>> assert thing['one'] == 1 1366 >>> assert list(thing) == ['one'] 1367 1368 1369patch.multiple 1370~~~~~~~~~~~~~~ 1371 1372.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) 1373 1374 Perform multiple patches in a single call. It takes the object to be 1375 patched (either as an object or a string to fetch the object by importing) 1376 and keyword arguments for the patches:: 1377 1378 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'): 1379 ... 1380 1381 Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create 1382 mocks for you. In this case the created mocks are passed into a decorated 1383 function by keyword, and a dictionary is returned when :func:`patch.multiple` is 1384 used as a context manager. 1385 1386 :func:`patch.multiple` can be used as a decorator, class decorator or a context 1387 manager. The arguments *spec*, *spec_set*, *create*, *autospec* and 1388 *new_callable* have the same meaning as for :func:`patch`. These arguments will 1389 be applied to *all* patches done by :func:`patch.multiple`. 1390 1391 When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX`` 1392 for choosing which methods to wrap. 1393 1394If you want :func:`patch.multiple` to create mocks for you, then you can use 1395:data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator 1396then the created mocks are passed into the decorated function by keyword. 1397 1398 >>> thing = object() 1399 >>> other = object() 1400 1401 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) 1402 ... def test_function(thing, other): 1403 ... assert isinstance(thing, MagicMock) 1404 ... assert isinstance(other, MagicMock) 1405 ... 1406 >>> test_function() 1407 1408:func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments 1409passed by keyword *after* any of the standard arguments created by :func:`patch`: 1410 1411 >>> @patch('sys.exit') 1412 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) 1413 ... def test_function(mock_exit, other, thing): 1414 ... assert 'other' in repr(other) 1415 ... assert 'thing' in repr(thing) 1416 ... assert 'exit' in repr(mock_exit) 1417 ... 1418 >>> test_function() 1419 1420If :func:`patch.multiple` is used as a context manager, the value returned by the 1421context manger is a dictionary where created mocks are keyed by name: 1422 1423 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values: 1424 ... assert 'other' in repr(values['other']) 1425 ... assert 'thing' in repr(values['thing']) 1426 ... assert values['thing'] is thing 1427 ... assert values['other'] is other 1428 ... 1429 1430 1431.. _start-and-stop: 1432 1433patch methods: start and stop 1434~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1435 1436All the patchers have :meth:`start` and :meth:`stop` methods. These make it simpler to do 1437patching in ``setUp`` methods or where you want to do multiple patches without 1438nesting decorators or with statements. 1439 1440To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as 1441normal and keep a reference to the returned ``patcher`` object. You can then 1442call :meth:`start` to put the patch in place and :meth:`stop` to undo it. 1443 1444If you are using :func:`patch` to create a mock for you then it will be returned by 1445the call to ``patcher.start``. 1446 1447 >>> patcher = patch('package.module.ClassName') 1448 >>> from package import module 1449 >>> original = module.ClassName 1450 >>> new_mock = patcher.start() 1451 >>> assert module.ClassName is not original 1452 >>> assert module.ClassName is new_mock 1453 >>> patcher.stop() 1454 >>> assert module.ClassName is original 1455 >>> assert module.ClassName is not new_mock 1456 1457 1458A typical use case for this might be for doing multiple patches in the ``setUp`` 1459method of a :class:`TestCase`: 1460 1461 >>> class MyTest(TestCase): 1462 ... def setUp(self): 1463 ... self.patcher1 = patch('package.module.Class1') 1464 ... self.patcher2 = patch('package.module.Class2') 1465 ... self.MockClass1 = self.patcher1.start() 1466 ... self.MockClass2 = self.patcher2.start() 1467 ... 1468 ... def tearDown(self): 1469 ... self.patcher1.stop() 1470 ... self.patcher2.stop() 1471 ... 1472 ... def test_something(self): 1473 ... assert package.module.Class1 is self.MockClass1 1474 ... assert package.module.Class2 is self.MockClass2 1475 ... 1476 >>> MyTest('test_something').run() 1477 1478.. caution:: 1479 1480 If you use this technique you must ensure that the patching is "undone" by 1481 calling ``stop``. This can be fiddlier than you might think, because if an 1482 exception is raised in the ``setUp`` then ``tearDown`` is not called. 1483 :meth:`unittest.TestCase.addCleanup` makes this easier: 1484 1485 >>> class MyTest(TestCase): 1486 ... def setUp(self): 1487 ... patcher = patch('package.module.Class') 1488 ... self.MockClass = patcher.start() 1489 ... self.addCleanup(patcher.stop) 1490 ... 1491 ... def test_something(self): 1492 ... assert package.module.Class is self.MockClass 1493 ... 1494 1495 As an added bonus you no longer need to keep a reference to the ``patcher`` 1496 object. 1497 1498It is also possible to stop all patches which have been started by using 1499:func:`patch.stopall`. 1500 1501.. function:: patch.stopall 1502 1503 Stop all active patches. Only stops patches started with ``start``. 1504 1505 1506.. _patch-builtins: 1507 1508patch builtins 1509~~~~~~~~~~~~~~ 1510You can patch any builtins within a module. The following example patches 1511builtin :func:`ord`: 1512 1513 >>> @patch('__main__.ord') 1514 ... def test(mock_ord): 1515 ... mock_ord.return_value = 101 1516 ... print(ord('c')) 1517 ... 1518 >>> test() 1519 101 1520 1521 1522TEST_PREFIX 1523~~~~~~~~~~~ 1524 1525All of the patchers can be used as class decorators. When used in this way 1526they wrap every test method on the class. The patchers recognise methods that 1527start with ``'test'`` as being test methods. This is the same way that the 1528:class:`unittest.TestLoader` finds test methods by default. 1529 1530It is possible that you want to use a different prefix for your tests. You can 1531inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``: 1532 1533 >>> patch.TEST_PREFIX = 'foo' 1534 >>> value = 3 1535 >>> 1536 >>> @patch('__main__.value', 'not three') 1537 ... class Thing: 1538 ... def foo_one(self): 1539 ... print(value) 1540 ... def foo_two(self): 1541 ... print(value) 1542 ... 1543 >>> 1544 >>> Thing().foo_one() 1545 not three 1546 >>> Thing().foo_two() 1547 not three 1548 >>> value 1549 3 1550 1551 1552Nesting Patch Decorators 1553~~~~~~~~~~~~~~~~~~~~~~~~ 1554 1555If you want to perform multiple patches then you can simply stack up the 1556decorators. 1557 1558You can stack up multiple patch decorators using this pattern: 1559 1560 >>> @patch.object(SomeClass, 'class_method') 1561 ... @patch.object(SomeClass, 'static_method') 1562 ... def test(mock1, mock2): 1563 ... assert SomeClass.static_method is mock1 1564 ... assert SomeClass.class_method is mock2 1565 ... SomeClass.static_method('foo') 1566 ... SomeClass.class_method('bar') 1567 ... return mock1, mock2 1568 ... 1569 >>> mock1, mock2 = test() 1570 >>> mock1.assert_called_once_with('foo') 1571 >>> mock2.assert_called_once_with('bar') 1572 1573 1574Note that the decorators are applied from the bottom upwards. This is the 1575standard way that Python applies decorators. The order of the created mocks 1576passed into your test function matches this order. 1577 1578 1579.. _where-to-patch: 1580 1581Where to patch 1582~~~~~~~~~~~~~~ 1583 1584:func:`patch` works by (temporarily) changing the object that a *name* points to with 1585another one. There can be many names pointing to any individual object, so 1586for patching to work you must ensure that you patch the name used by the system 1587under test. 1588 1589The basic principle is that you patch where an object is *looked up*, which 1590is not necessarily the same place as where it is defined. A couple of 1591examples will help to clarify this. 1592 1593Imagine we have a project that we want to test with the following structure:: 1594 1595 a.py 1596 -> Defines SomeClass 1597 1598 b.py 1599 -> from a import SomeClass 1600 -> some_function instantiates SomeClass 1601 1602Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using 1603:func:`patch`. The problem is that when we import module b, which we will have to 1604do then it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out 1605``a.SomeClass`` then it will have no effect on our test; module b already has a 1606reference to the *real* ``SomeClass`` and it looks like our patching had no 1607effect. 1608 1609The key is to patch out ``SomeClass`` where it is used (or where it is looked up). 1610In this case ``some_function`` will actually look up ``SomeClass`` in module b, 1611where we have imported it. The patching should look like:: 1612 1613 @patch('b.SomeClass') 1614 1615However, consider the alternative scenario where instead of ``from a import 1616SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both 1617of these import forms are common. In this case the class we want to patch is 1618being looked up in the module and so we have to patch ``a.SomeClass`` instead:: 1619 1620 @patch('a.SomeClass') 1621 1622 1623Patching Descriptors and Proxy Objects 1624~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1625 1626Both patch_ and patch.object_ correctly patch and restore descriptors: class 1627methods, static methods and properties. You should patch these on the *class* 1628rather than an instance. They also work with *some* objects 1629that proxy attribute access, like the `django settings object 1630<http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_. 1631 1632 1633MagicMock and magic method support 1634---------------------------------- 1635 1636.. _magic-methods: 1637 1638Mocking Magic Methods 1639~~~~~~~~~~~~~~~~~~~~~ 1640 1641:class:`Mock` supports mocking the Python protocol methods, also known as 1642"magic methods". This allows mock objects to replace containers or other 1643objects that implement Python protocols. 1644 1645Because magic methods are looked up differently from normal methods [#]_, this 1646support has been specially implemented. This means that only specific magic 1647methods are supported. The supported list includes *almost* all of them. If 1648there are any missing that you need please let us know. 1649 1650You mock magic methods by setting the method you are interested in to a function 1651or a mock instance. If you are using a function then it *must* take ``self`` as 1652the first argument [#]_. 1653 1654 >>> def __str__(self): 1655 ... return 'fooble' 1656 ... 1657 >>> mock = Mock() 1658 >>> mock.__str__ = __str__ 1659 >>> str(mock) 1660 'fooble' 1661 1662 >>> mock = Mock() 1663 >>> mock.__str__ = Mock() 1664 >>> mock.__str__.return_value = 'fooble' 1665 >>> str(mock) 1666 'fooble' 1667 1668 >>> mock = Mock() 1669 >>> mock.__iter__ = Mock(return_value=iter([])) 1670 >>> list(mock) 1671 [] 1672 1673One use case for this is for mocking objects used as context managers in a 1674:keyword:`with` statement: 1675 1676 >>> mock = Mock() 1677 >>> mock.__enter__ = Mock(return_value='foo') 1678 >>> mock.__exit__ = Mock(return_value=False) 1679 >>> with mock as m: 1680 ... assert m == 'foo' 1681 ... 1682 >>> mock.__enter__.assert_called_with() 1683 >>> mock.__exit__.assert_called_with(None, None, None) 1684 1685Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they 1686are recorded in :attr:`~Mock.mock_calls`. 1687 1688.. note:: 1689 1690 If you use the *spec* keyword argument to create a mock then attempting to 1691 set a magic method that isn't in the spec will raise an :exc:`AttributeError`. 1692 1693The full list of supported magic methods is: 1694 1695* ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__`` 1696* ``__dir__``, ``__format__`` and ``__subclasses__`` 1697* ``__floor__``, ``__trunc__`` and ``__ceil__`` 1698* Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``, 1699 ``__eq__`` and ``__ne__`` 1700* Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``, 1701 ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__`` 1702 and ``__missing__`` 1703* Context manager: ``__enter__`` and ``__exit__`` 1704* Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__`` 1705* The numeric methods (including right hand and in-place variants): 1706 ``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__div__``, ``__truediv__``, 1707 ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``, 1708 ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__`` 1709* Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__`` 1710 and ``__index__`` 1711* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__`` 1712* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, 1713 ``__getnewargs__``, ``__getstate__`` and ``__setstate__`` 1714 1715 1716The following methods exist but are *not* supported as they are either in use 1717by mock, can't be set dynamically, or can cause problems: 1718 1719* ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__`` 1720* ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__`` 1721 1722 1723 1724Magic Mock 1725~~~~~~~~~~ 1726 1727There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`. 1728 1729 1730.. class:: MagicMock(*args, **kw) 1731 1732 ``MagicMock`` is a subclass of :class:`Mock` with default implementations 1733 of most of the magic methods. You can use ``MagicMock`` without having to 1734 configure the magic methods yourself. 1735 1736 The constructor parameters have the same meaning as for :class:`Mock`. 1737 1738 If you use the *spec* or *spec_set* arguments then *only* magic methods 1739 that exist in the spec will be created. 1740 1741 1742.. class:: NonCallableMagicMock(*args, **kw) 1743 1744 A non-callable version of :class:`MagicMock`. 1745 1746 The constructor parameters have the same meaning as for 1747 :class:`MagicMock`, with the exception of *return_value* and 1748 *side_effect* which have no meaning on a non-callable mock. 1749 1750The magic methods are setup with :class:`MagicMock` objects, so you can configure them 1751and use them in the usual way: 1752 1753 >>> mock = MagicMock() 1754 >>> mock[3] = 'fish' 1755 >>> mock.__setitem__.assert_called_with(3, 'fish') 1756 >>> mock.__getitem__.return_value = 'result' 1757 >>> mock[2] 1758 'result' 1759 1760By default many of the protocol methods are required to return objects of a 1761specific type. These methods are preconfigured with a default return value, so 1762that they can be used without you having to do anything if you aren't interested 1763in the return value. You can still *set* the return value manually if you want 1764to change the default. 1765 1766Methods and their defaults: 1767 1768* ``__lt__``: NotImplemented 1769* ``__gt__``: NotImplemented 1770* ``__le__``: NotImplemented 1771* ``__ge__``: NotImplemented 1772* ``__int__``: 1 1773* ``__contains__``: False 1774* ``__len__``: 0 1775* ``__iter__``: iter([]) 1776* ``__exit__``: False 1777* ``__complex__``: 1j 1778* ``__float__``: 1.0 1779* ``__bool__``: True 1780* ``__index__``: 1 1781* ``__hash__``: default hash for the mock 1782* ``__str__``: default str for the mock 1783* ``__sizeof__``: default sizeof for the mock 1784 1785For example: 1786 1787 >>> mock = MagicMock() 1788 >>> int(mock) 1789 1 1790 >>> len(mock) 1791 0 1792 >>> list(mock) 1793 [] 1794 >>> object() in mock 1795 False 1796 1797The two equality methods, :meth:`__eq__` and :meth:`__ne__`, are special. 1798They do the default equality comparison on identity, using the 1799:attr:`~Mock.side_effect` attribute, unless you change their return value to 1800return something else:: 1801 1802 >>> MagicMock() == 3 1803 False 1804 >>> MagicMock() != 3 1805 True 1806 >>> mock = MagicMock() 1807 >>> mock.__eq__.return_value = True 1808 >>> mock == 3 1809 True 1810 1811The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't 1812required to be an iterator: 1813 1814 >>> mock = MagicMock() 1815 >>> mock.__iter__.return_value = ['a', 'b', 'c'] 1816 >>> list(mock) 1817 ['a', 'b', 'c'] 1818 >>> list(mock) 1819 ['a', 'b', 'c'] 1820 1821If the return value *is* an iterator, then iterating over it once will consume 1822it and subsequent iterations will result in an empty list: 1823 1824 >>> mock.__iter__.return_value = iter(['a', 'b', 'c']) 1825 >>> list(mock) 1826 ['a', 'b', 'c'] 1827 >>> list(mock) 1828 [] 1829 1830``MagicMock`` has all of the supported magic methods configured except for some 1831of the obscure and obsolete ones. You can still set these up if you want. 1832 1833Magic methods that are supported but not setup by default in ``MagicMock`` are: 1834 1835* ``__subclasses__`` 1836* ``__dir__`` 1837* ``__format__`` 1838* ``__get__``, ``__set__`` and ``__delete__`` 1839* ``__reversed__`` and ``__missing__`` 1840* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``, 1841 ``__getstate__`` and ``__setstate__`` 1842* ``__getformat__`` and ``__setformat__`` 1843 1844 1845 1846.. [#] Magic methods *should* be looked up on the class rather than the 1847 instance. Different versions of Python are inconsistent about applying this 1848 rule. The supported protocol methods should work with all supported versions 1849 of Python. 1850.. [#] The function is basically hooked up to the class, but each ``Mock`` 1851 instance is kept isolated from the others. 1852 1853 1854Helpers 1855------- 1856 1857sentinel 1858~~~~~~~~ 1859 1860.. data:: sentinel 1861 1862 The ``sentinel`` object provides a convenient way of providing unique 1863 objects for your tests. 1864 1865 Attributes are created on demand when you access them by name. Accessing 1866 the same attribute will always return the same object. The objects 1867 returned have a sensible repr so that test failure messages are readable. 1868 1869 .. versionchanged:: 3.7 1870 The ``sentinel`` attributes now preserve their identity when they are 1871 :mod:`copied <copy>` or :mod:`pickled <pickle>`. 1872 1873Sometimes when testing you need to test that a specific object is passed as an 1874argument to another method, or returned. It can be common to create named 1875sentinel objects to test this. :data:`sentinel` provides a convenient way of 1876creating and testing the identity of objects like this. 1877 1878In this example we monkey patch ``method`` to return ``sentinel.some_object``: 1879 1880 >>> real = ProductionClass() 1881 >>> real.method = Mock(name="method") 1882 >>> real.method.return_value = sentinel.some_object 1883 >>> result = real.method() 1884 >>> assert result is sentinel.some_object 1885 >>> sentinel.some_object 1886 sentinel.some_object 1887 1888 1889DEFAULT 1890~~~~~~~ 1891 1892 1893.. data:: DEFAULT 1894 1895 The :data:`DEFAULT` object is a pre-created sentinel (actually 1896 ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect` 1897 functions to indicate that the normal return value should be used. 1898 1899 1900call 1901~~~~ 1902 1903.. function:: call(*args, **kwargs) 1904 1905 :func:`call` is a helper object for making simpler assertions, for comparing with 1906 :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`, 1907 :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be 1908 used with :meth:`~Mock.assert_has_calls`. 1909 1910 >>> m = MagicMock(return_value=None) 1911 >>> m(1, 2, a='foo', b='bar') 1912 >>> m() 1913 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()] 1914 True 1915 1916.. method:: call.call_list() 1917 1918 For a call object that represents multiple calls, :meth:`call_list` 1919 returns a list of all the intermediate calls as well as the 1920 final call. 1921 1922``call_list`` is particularly useful for making assertions on "chained calls". A 1923chained call is multiple calls on a single line of code. This results in 1924multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing 1925the sequence of calls can be tedious. 1926 1927:meth:`~call.call_list` can construct the sequence of calls from the same 1928chained call: 1929 1930 >>> m = MagicMock() 1931 >>> m(1).method(arg='foo').other('bar')(2.0) 1932 <MagicMock name='mock().method().other()()' id='...'> 1933 >>> kall = call(1).method(arg='foo').other('bar')(2.0) 1934 >>> kall.call_list() 1935 [call(1), 1936 call().method(arg='foo'), 1937 call().method().other('bar'), 1938 call().method().other()(2.0)] 1939 >>> m.mock_calls == kall.call_list() 1940 True 1941 1942.. _calls-as-tuples: 1943 1944A ``call`` object is either a tuple of (positional args, keyword args) or 1945(name, positional args, keyword args) depending on how it was constructed. When 1946you construct them yourself this isn't particularly interesting, but the ``call`` 1947objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and 1948:attr:`Mock.mock_calls` attributes can be introspected to get at the individual 1949arguments they contain. 1950 1951The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list` 1952are two-tuples of (positional args, keyword args) whereas the ``call`` objects 1953in :attr:`Mock.mock_calls`, along with ones you construct yourself, are 1954three-tuples of (name, positional args, keyword args). 1955 1956You can use their "tupleness" to pull out the individual arguments for more 1957complex introspection and assertions. The positional arguments are a tuple 1958(an empty tuple if there are no positional arguments) and the keyword 1959arguments are a dictionary: 1960 1961 >>> m = MagicMock(return_value=None) 1962 >>> m(1, 2, 3, arg='one', arg2='two') 1963 >>> kall = m.call_args 1964 >>> args, kwargs = kall 1965 >>> args 1966 (1, 2, 3) 1967 >>> kwargs 1968 {'arg2': 'two', 'arg': 'one'} 1969 >>> args is kall[0] 1970 True 1971 >>> kwargs is kall[1] 1972 True 1973 1974 >>> m = MagicMock() 1975 >>> m.foo(4, 5, 6, arg='two', arg2='three') 1976 <MagicMock name='mock.foo()' id='...'> 1977 >>> kall = m.mock_calls[0] 1978 >>> name, args, kwargs = kall 1979 >>> name 1980 'foo' 1981 >>> args 1982 (4, 5, 6) 1983 >>> kwargs 1984 {'arg2': 'three', 'arg': 'two'} 1985 >>> name is m.mock_calls[0][0] 1986 True 1987 1988 1989create_autospec 1990~~~~~~~~~~~~~~~ 1991 1992.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs) 1993 1994 Create a mock object using another object as a spec. Attributes on the 1995 mock will use the corresponding attribute on the *spec* object as their 1996 spec. 1997 1998 Functions or methods being mocked will have their arguments checked to 1999 ensure that they are called with the correct signature. 2000 2001 If *spec_set* is ``True`` then attempting to set attributes that don't exist 2002 on the spec object will raise an :exc:`AttributeError`. 2003 2004 If a class is used as a spec then the return value of the mock (the 2005 instance of the class) will have the same spec. You can use a class as the 2006 spec for an instance object by passing ``instance=True``. The returned mock 2007 will only be callable if instances of the mock are callable. 2008 2009 :func:`create_autospec` also takes arbitrary keyword arguments that are passed to 2010 the constructor of the created mock. 2011 2012See :ref:`auto-speccing` for examples of how to use auto-speccing with 2013:func:`create_autospec` and the *autospec* argument to :func:`patch`. 2014 2015 2016ANY 2017~~~ 2018 2019.. data:: ANY 2020 2021Sometimes you may need to make assertions about *some* of the arguments in a 2022call to mock, but either not care about some of the arguments or want to pull 2023them individually out of :attr:`~Mock.call_args` and make more complex 2024assertions on them. 2025 2026To ignore certain arguments you can pass in objects that compare equal to 2027*everything*. Calls to :meth:`~Mock.assert_called_with` and 2028:meth:`~Mock.assert_called_once_with` will then succeed no matter what was 2029passed in. 2030 2031 >>> mock = Mock(return_value=None) 2032 >>> mock('foo', bar=object()) 2033 >>> mock.assert_called_once_with('foo', bar=ANY) 2034 2035:data:`ANY` can also be used in comparisons with call lists like 2036:attr:`~Mock.mock_calls`: 2037 2038 >>> m = MagicMock(return_value=None) 2039 >>> m(1) 2040 >>> m(1, 2) 2041 >>> m(object()) 2042 >>> m.mock_calls == [call(1), call(1, 2), ANY] 2043 True 2044 2045 2046 2047FILTER_DIR 2048~~~~~~~~~~ 2049 2050.. data:: FILTER_DIR 2051 2052:data:`FILTER_DIR` is a module level variable that controls the way mock objects 2053respond to :func:`dir` (only for Python 2.6 or more recent). The default is ``True``, 2054which uses the filtering described below, to only show useful members. If you 2055dislike this filtering, or need to switch it off for diagnostic purposes, then 2056set ``mock.FILTER_DIR = False``. 2057 2058With filtering on, ``dir(some_mock)`` shows only useful attributes and will 2059include any dynamically created attributes that wouldn't normally be shown. 2060If the mock was created with a *spec* (or *autospec* of course) then all the 2061attributes from the original are shown, even if they haven't been accessed 2062yet: 2063 2064 >>> dir(Mock()) 2065 ['assert_any_call', 2066 'assert_called_once_with', 2067 'assert_called_with', 2068 'assert_has_calls', 2069 'attach_mock', 2070 ... 2071 >>> from urllib import request 2072 >>> dir(Mock(spec=request)) 2073 ['AbstractBasicAuthHandler', 2074 'AbstractDigestAuthHandler', 2075 'AbstractHTTPHandler', 2076 'BaseHandler', 2077 ... 2078 2079Many of the not-very-useful (private to :class:`Mock` rather than the thing being 2080mocked) underscore and double underscore prefixed attributes have been 2081filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this 2082behaviour you can switch it off by setting the module level switch 2083:data:`FILTER_DIR`: 2084 2085 >>> from unittest import mock 2086 >>> mock.FILTER_DIR = False 2087 >>> dir(mock.Mock()) 2088 ['_NonCallableMock__get_return_value', 2089 '_NonCallableMock__get_side_effect', 2090 '_NonCallableMock__return_value_doc', 2091 '_NonCallableMock__set_return_value', 2092 '_NonCallableMock__set_side_effect', 2093 '__call__', 2094 '__class__', 2095 ... 2096 2097Alternatively you can just use ``vars(my_mock)`` (instance members) and 2098``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of 2099:data:`mock.FILTER_DIR`. 2100 2101 2102mock_open 2103~~~~~~~~~ 2104 2105.. function:: mock_open(mock=None, read_data=None) 2106 2107 A helper function to create a mock to replace the use of :func:`open`. It works 2108 for :func:`open` called directly or used as a context manager. 2109 2110 The *mock* argument is the mock object to configure. If ``None`` (the 2111 default) then a :class:`MagicMock` will be created for you, with the API limited 2112 to methods or attributes available on standard file handles. 2113 2114 *read_data* is a string for the :meth:`~io.IOBase.read`, 2115 :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods 2116 of the file handle to return. Calls to those methods will take data from 2117 *read_data* until it is depleted. The mock of these methods is pretty 2118 simplistic: every time the *mock* is called, the *read_data* is rewound to 2119 the start. If you need more control over the data that you are feeding to 2120 the tested code you will need to customize this mock for yourself. When that 2121 is insufficient, one of the in-memory filesystem packages on `PyPI 2122 <https://pypi.org>`_ can offer a realistic filesystem for testing. 2123 2124 .. versionchanged:: 3.4 2125 Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support. 2126 The mock of :meth:`~io.IOBase.read` changed to consume *read_data* rather 2127 than returning it on each call. 2128 2129 .. versionchanged:: 3.5 2130 *read_data* is now reset on each call to the *mock*. 2131 2132 .. versionchanged:: 3.7.1 2133 Added :meth:`__iter__` to implementation so that iteration (such as in for 2134 loops) correctly consumes *read_data*. 2135 2136Using :func:`open` as a context manager is a great way to ensure your file handles 2137are closed properly and is becoming common:: 2138 2139 with open('/some/path', 'w') as f: 2140 f.write('something') 2141 2142The issue is that even if you mock out the call to :func:`open` it is the 2143*returned object* that is used as a context manager (and has :meth:`__enter__` and 2144:meth:`__exit__` called). 2145 2146Mocking context managers with a :class:`MagicMock` is common enough and fiddly 2147enough that a helper function is useful. 2148 2149 >>> m = mock_open() 2150 >>> with patch('__main__.open', m): 2151 ... with open('foo', 'w') as h: 2152 ... h.write('some stuff') 2153 ... 2154 >>> m.mock_calls 2155 [call('foo', 'w'), 2156 call().__enter__(), 2157 call().write('some stuff'), 2158 call().__exit__(None, None, None)] 2159 >>> m.assert_called_once_with('foo', 'w') 2160 >>> handle = m() 2161 >>> handle.write.assert_called_once_with('some stuff') 2162 2163And for reading files: 2164 2165 >>> with patch('__main__.open', mock_open(read_data='bibble')) as m: 2166 ... with open('foo') as h: 2167 ... result = h.read() 2168 ... 2169 >>> m.assert_called_once_with('foo') 2170 >>> assert result == 'bibble' 2171 2172 2173.. _auto-speccing: 2174 2175Autospeccing 2176~~~~~~~~~~~~ 2177 2178Autospeccing is based on the existing :attr:`spec` feature of mock. It limits the 2179api of mocks to the api of an original object (the spec), but it is recursive 2180(implemented lazily) so that attributes of mocks only have the same api as 2181the attributes of the spec. In addition mocked functions / methods have the 2182same call signature as the original so they raise a :exc:`TypeError` if they are 2183called incorrectly. 2184 2185Before I explain how auto-speccing works, here's why it is needed. 2186 2187:class:`Mock` is a very powerful and flexible object, but it suffers from two flaws 2188when used to mock out objects from a system under test. One of these flaws is 2189specific to the :class:`Mock` api and the other is a more general problem with using 2190mock objects. 2191 2192First the problem specific to :class:`Mock`. :class:`Mock` has two assert methods that are 2193extremely handy: :meth:`~Mock.assert_called_with` and 2194:meth:`~Mock.assert_called_once_with`. 2195 2196 >>> mock = Mock(name='Thing', return_value=None) 2197 >>> mock(1, 2, 3) 2198 >>> mock.assert_called_once_with(1, 2, 3) 2199 >>> mock(1, 2, 3) 2200 >>> mock.assert_called_once_with(1, 2, 3) 2201 Traceback (most recent call last): 2202 ... 2203 AssertionError: Expected 'mock' to be called once. Called 2 times. 2204 2205Because mocks auto-create attributes on demand, and allow you to call them 2206with arbitrary arguments, if you misspell one of these assert methods then 2207your assertion is gone: 2208 2209.. code-block:: pycon 2210 2211 >>> mock = Mock(name='Thing', return_value=None) 2212 >>> mock(1, 2, 3) 2213 >>> mock.assret_called_once_with(4, 5, 6) 2214 2215Your tests can pass silently and incorrectly because of the typo. 2216 2217The second issue is more general to mocking. If you refactor some of your 2218code, rename members and so on, any tests for code that is still using the 2219*old api* but uses mocks instead of the real objects will still pass. This 2220means your tests can all pass even though your code is broken. 2221 2222Note that this is another reason why you need integration tests as well as 2223unit tests. Testing everything in isolation is all fine and dandy, but if you 2224don't test how your units are "wired together" there is still lots of room 2225for bugs that tests might have caught. 2226 2227:mod:`mock` already provides a feature to help with this, called speccing. If you 2228use a class or instance as the :attr:`spec` for a mock then you can only access 2229attributes on the mock that exist on the real class: 2230 2231 >>> from urllib import request 2232 >>> mock = Mock(spec=request.Request) 2233 >>> mock.assret_called_with 2234 Traceback (most recent call last): 2235 ... 2236 AttributeError: Mock object has no attribute 'assret_called_with' 2237 2238The spec only applies to the mock itself, so we still have the same issue 2239with any methods on the mock: 2240 2241.. code-block:: pycon 2242 2243 >>> mock.has_data() 2244 <mock.Mock object at 0x...> 2245 >>> mock.has_data.assret_called_with() 2246 2247Auto-speccing solves this problem. You can either pass ``autospec=True`` to 2248:func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a 2249mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the 2250object that is being replaced will be used as the spec object. Because the 2251speccing is done "lazily" (the spec is created as attributes on the mock are 2252accessed) you can use it with very complex or deeply nested objects (like 2253modules that import modules that import modules) without a big performance 2254hit. 2255 2256Here's an example of it in use: 2257 2258 >>> from urllib import request 2259 >>> patcher = patch('__main__.request', autospec=True) 2260 >>> mock_request = patcher.start() 2261 >>> request is mock_request 2262 True 2263 >>> mock_request.Request 2264 <MagicMock name='request.Request' spec='Request' id='...'> 2265 2266You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two 2267arguments in the constructor (one of which is *self*). Here's what happens if 2268we try to call it incorrectly: 2269 2270 >>> req = request.Request() 2271 Traceback (most recent call last): 2272 ... 2273 TypeError: <lambda>() takes at least 2 arguments (1 given) 2274 2275The spec also applies to instantiated classes (i.e. the return value of 2276specced mocks): 2277 2278 >>> req = request.Request('foo') 2279 >>> req 2280 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'> 2281 2282:class:`Request` objects are not callable, so the return value of instantiating our 2283mocked out :class:`request.Request` is a non-callable mock. With the spec in place 2284any typos in our asserts will raise the correct error: 2285 2286 >>> req.add_header('spam', 'eggs') 2287 <MagicMock name='request.Request().add_header()' id='...'> 2288 >>> req.add_header.assret_called_with 2289 Traceback (most recent call last): 2290 ... 2291 AttributeError: Mock object has no attribute 'assret_called_with' 2292 >>> req.add_header.assert_called_with('spam', 'eggs') 2293 2294In many cases you will just be able to add ``autospec=True`` to your existing 2295:func:`patch` calls and then be protected against bugs due to typos and api 2296changes. 2297 2298As well as using *autospec* through :func:`patch` there is a 2299:func:`create_autospec` for creating autospecced mocks directly: 2300 2301 >>> from urllib import request 2302 >>> mock_request = create_autospec(request) 2303 >>> mock_request.Request('foo', 'bar') 2304 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'> 2305 2306This isn't without caveats and limitations however, which is why it is not 2307the default behaviour. In order to know what attributes are available on the 2308spec object, autospec has to introspect (access attributes) the spec. As you 2309traverse attributes on the mock a corresponding traversal of the original 2310object is happening under the hood. If any of your specced objects have 2311properties or descriptors that can trigger code execution then you may not be 2312able to use autospec. On the other hand it is much better to design your 2313objects so that introspection is safe [#]_. 2314 2315A more serious problem is that it is common for instance attributes to be 2316created in the :meth:`__init__` method and not to exist on the class at all. 2317*autospec* can't know about any dynamically created attributes and restricts 2318the api to visible attributes. 2319 2320 >>> class Something: 2321 ... def __init__(self): 2322 ... self.a = 33 2323 ... 2324 >>> with patch('__main__.Something', autospec=True): 2325 ... thing = Something() 2326 ... thing.a 2327 ... 2328 Traceback (most recent call last): 2329 ... 2330 AttributeError: Mock object has no attribute 'a' 2331 2332There are a few different ways of resolving this problem. The easiest, but 2333not necessarily the least annoying, way is to simply set the required 2334attributes on the mock after creation. Just because *autospec* doesn't allow 2335you to fetch attributes that don't exist on the spec it doesn't prevent you 2336setting them: 2337 2338 >>> with patch('__main__.Something', autospec=True): 2339 ... thing = Something() 2340 ... thing.a = 33 2341 ... 2342 2343There is a more aggressive version of both *spec* and *autospec* that *does* 2344prevent you setting non-existent attributes. This is useful if you want to 2345ensure your code only *sets* valid attributes too, but obviously it prevents 2346this particular scenario: 2347 2348 >>> with patch('__main__.Something', autospec=True, spec_set=True): 2349 ... thing = Something() 2350 ... thing.a = 33 2351 ... 2352 Traceback (most recent call last): 2353 ... 2354 AttributeError: Mock object has no attribute 'a' 2355 2356Probably the best way of solving the problem is to add class attributes as 2357default values for instance members initialised in :meth:`__init__`. Note that if 2358you are only setting default attributes in :meth:`__init__` then providing them via 2359class attributes (shared between instances of course) is faster too. e.g. 2360 2361.. code-block:: python 2362 2363 class Something: 2364 a = 33 2365 2366This brings up another issue. It is relatively common to provide a default 2367value of ``None`` for members that will later be an object of a different type. 2368``None`` would be useless as a spec because it wouldn't let you access *any* 2369attributes or methods on it. As ``None`` is *never* going to be useful as a 2370spec, and probably indicates a member that will normally of some other type, 2371autospec doesn't use a spec for members that are set to ``None``. These will 2372just be ordinary mocks (well - MagicMocks): 2373 2374 >>> class Something: 2375 ... member = None 2376 ... 2377 >>> mock = create_autospec(Something) 2378 >>> mock.member.foo.bar.baz() 2379 <MagicMock name='mock.member.foo.bar.baz()' id='...'> 2380 2381If modifying your production classes to add defaults isn't to your liking 2382then there are more options. One of these is simply to use an instance as the 2383spec rather than the class. The other is to create a subclass of the 2384production class and add the defaults to the subclass without affecting the 2385production class. Both of these require you to use an alternative object as 2386the spec. Thankfully :func:`patch` supports this - you can simply pass the 2387alternative object as the *autospec* argument: 2388 2389 >>> class Something: 2390 ... def __init__(self): 2391 ... self.a = 33 2392 ... 2393 >>> class SomethingForTest(Something): 2394 ... a = 33 2395 ... 2396 >>> p = patch('__main__.Something', autospec=SomethingForTest) 2397 >>> mock = p.start() 2398 >>> mock.a 2399 <NonCallableMagicMock name='Something.a' spec='int' id='...'> 2400 2401 2402.. [#] This only applies to classes or already instantiated objects. Calling 2403 a mocked class to create a mock instance *does not* create a real instance. 2404 It is only attribute lookups - along with calls to :func:`dir` - that are done. 2405 2406Sealing mocks 2407~~~~~~~~~~~~~ 2408 2409.. function:: seal(mock) 2410 2411 Seal will disable the automatic creation of mocks when accessing an attribute of 2412 the mock being sealed or any of its attributes that are already mocks recursively. 2413 2414 If a mock instance with a name or a spec is assigned to an attribute 2415 it won't be considered in the sealing chain. This allows one to prevent seal from 2416 fixing part of the mock object. 2417 2418 >>> mock = Mock() 2419 >>> mock.submock.attribute1 = 2 2420 >>> mock.not_submock = mock.Mock(name="sample_name") 2421 >>> seal(mock) 2422 >>> mock.new_attribute # This will raise AttributeError. 2423 >>> mock.submock.attribute2 # This will raise AttributeError. 2424 >>> mock.not_submock.attribute2 # This won't raise. 2425 2426 .. versionadded:: 3.7 2427