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