Debian Codegraph @

Doc/library/unittest.mock.rst

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