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