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 >>> inspect.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, where the restored dictionary is a
1665 copy of the dictionary as it was before the test.
1666
1667 *in_dict* can be a dictionary or a mapping like container. If it is a
1668 mapping then it must at least support getting, setting and deleting items
1669 plus iterating over keys.
1670
1671 *in_dict* can also be a string specifying the name of the dictionary, which
1672 will then be fetched by importing it.
1673
1674 *values* can be a dictionary of values to set in the dictionary. *values*
1675 can also be an iterable of ``(key, value)`` pairs.
1676
1677 If *clear* is true then the dictionary will be cleared before the new
1678 values are set.
1679
1680 :func:`patch.dict` can also be called with arbitrary keyword arguments to set
1681 values in the dictionary.
1682
1683 .. versionchanged:: 3.8
1684
1685 :func:`patch.dict` now returns the patched dictionary when used as a context
1686 manager.
1687
1688 :func:`patch.dict` can be used as a context manager, decorator or class
1689 decorator:
1690
1691 >>> foo = {}
1692 >>> @patch.dict(foo, {'newkey': 'newvalue'})
1693 ... def test():
1694 ... assert foo == {'newkey': 'newvalue'}
1695 ...
1696 >>> test()
1697 >>> assert foo == {}
1698
1699 When used as a class decorator :func:`patch.dict` honours
1700 ``patch.TEST_PREFIX`` (default to ``'test'``) for choosing which methods to wrap:
1701
1702 >>> import os
1703 >>> import unittest
1704 >>> from unittest.mock import patch
1705 >>> @patch.dict('os.environ', {'newkey': 'newvalue'})
1706 ... class TestSample(unittest.TestCase):
1707 ... def test_sample(self):
1708 ... self.assertEqual(os.environ['newkey'], 'newvalue')
1709
1710 If you want to use a different prefix for your test, you can inform the
1711 patchers of the different prefix by setting ``patch.TEST_PREFIX``. For
1712 more details about how to change the value of see :ref:`test-prefix`.
1713
1714 :func:`patch.dict` can be used to add members to a dictionary, or simply let a test
1715 change a dictionary, and ensure the dictionary is restored when the test
1716 ends.
1717
1718 >>> foo = {}
1719 >>> with patch.dict(foo, {'newkey': 'newvalue'}) as patched_foo:
1720 ... assert foo == {'newkey': 'newvalue'}
1721 ... assert patched_foo == {'newkey': 'newvalue'}
1722 ... # You can add, update or delete keys of foo (or patched_foo, it's the same dict)
1723 ... patched_foo['spam'] = 'eggs'
1724 ...
1725 >>> assert foo == {}
1726 >>> assert patched_foo == {}
1727
1728 >>> import os
1729 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
1730 ... print(os.environ['newkey'])
1731 ...
1732 newvalue
1733 >>> assert 'newkey' not in os.environ
1734
1735 Keywords can be used in the :func:`patch.dict` call to set values in the dictionary:
1736
1737 >>> mymodule = MagicMock()
1738 >>> mymodule.function.return_value = 'fish'
1739 >>> with patch.dict('sys.modules', mymodule=mymodule):
1740 ... import mymodule
1741 ... mymodule.function('some', 'args')
1742 ...
1743 'fish'
1744
1745 :func:`patch.dict` can be used with dictionary like objects that aren't actually
1746 dictionaries. At the very minimum they must support item getting, setting,
1747 deleting and either iteration or membership test. This corresponds to the
1748 magic methods :meth:`~object.__getitem__`, :meth:`~object.__setitem__`,
1749 :meth:`~object.__delitem__` and either :meth:`~container.__iter__` or
1750 :meth:`~object.__contains__`.
1751
1752 >>> class Container:
1753 ... def __init__(self):
1754 ... self.values = {}
1755 ... def __getitem__(self, name):
1756 ... return self.values[name]
1757 ... def __setitem__(self, name, value):
1758 ... self.values[name] = value
1759 ... def __delitem__(self, name):
1760 ... del self.values[name]
1761 ... def __iter__(self):
1762 ... return iter(self.values)
1763 ...
1764 >>> thing = Container()
1765 >>> thing['one'] = 1
1766 >>> with patch.dict(thing, one=2, two=3):
1767 ... assert thing['one'] == 2
1768 ... assert thing['two'] == 3
1769 ...
1770 >>> assert thing['one'] == 1
1771 >>> assert list(thing) == ['one']
1772
1773
1774 patch.multiple
1775 ~~~~~~~~~~~~~~
1776
1777 .. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1778
1779 Perform multiple patches in a single call. It takes the object to be
1780 patched (either as an object or a string to fetch the object by importing)
1781 and keyword arguments for the patches::
1782
1783 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1784 ...
1785
1786 Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create
1787 mocks for you. In this case the created mocks are passed into a decorated
1788 function by keyword, and a dictionary is returned when :func:`patch.multiple` is
1789 used as a context manager.
1790
1791 :func:`patch.multiple` can be used as a decorator, class decorator or a context
1792 manager. The arguments *spec*, *spec_set*, *create*, *autospec* and
1793 *new_callable* have the same meaning as for :func:`patch`. These arguments will
1794 be applied to *all* patches done by :func:`patch.multiple`.
1795
1796 When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX``
1797 for choosing which methods to wrap.
1798
1799 If you want :func:`patch.multiple` to create mocks for you, then you can use
1800 :data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator
1801 then the created mocks are passed into the decorated function by keyword. ::
1802
1803 >>> thing = object()
1804 >>> other = object()
1805
1806 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1807 ... def test_function(thing, other):
1808 ... assert isinstance(thing, MagicMock)
1809 ... assert isinstance(other, MagicMock)
1810 ...
1811 >>> test_function()
1812
1813 :func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments
1814 passed by keyword *after* any of the standard arguments created by :func:`patch`::
1815
1816 >>> @patch('sys.exit')
1817 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1818 ... def test_function(mock_exit, other, thing):
1819 ... assert 'other' in repr(other)
1820 ... assert 'thing' in repr(thing)
1821 ... assert 'exit' in repr(mock_exit)
1822 ...
1823 >>> test_function()
1824
1825 If :func:`patch.multiple` is used as a context manager, the value returned by the
1826 context manager is a dictionary where created mocks are keyed by name::
1827
1828 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
1829 ... assert 'other' in repr(values['other'])
1830 ... assert 'thing' in repr(values['thing'])
1831 ... assert values['thing'] is thing
1832 ... assert values['other'] is other
1833 ...
1834
1835
1836 .. _start-and-stop:
1837
1838 patch methods: start and stop
1839 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1840
1841 All the patchers have :meth:`!start` and :meth:`!stop` methods. These make it simpler to do
1842 patching in ``setUp`` methods or where you want to do multiple patches without
1843 nesting decorators or with statements.
1844
1845 To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as
1846 normal and keep a reference to the returned ``patcher`` object. You can then
1847 call :meth:`!start` to put the patch in place and :meth:`!stop` to undo it.
1848
1849 If you are using :func:`patch` to create a mock for you then it will be returned by
1850 the call to ``patcher.start``. ::
1851
1852 >>> patcher = patch('package.module.ClassName')
1853 >>> from package import module
1854 >>> original = module.ClassName
1855 >>> new_mock = patcher.start()
1856 >>> assert module.ClassName is not original
1857 >>> assert module.ClassName is new_mock
1858 >>> patcher.stop()
1859 >>> assert module.ClassName is original
1860 >>> assert module.ClassName is not new_mock
1861
1862
1863 A typical use case for this might be for doing multiple patches in the ``setUp``
1864 method of a :class:`~unittest.TestCase`::
1865
1866 >>> class MyTest(unittest.TestCase):
1867 ... def setUp(self):
1868 ... self.patcher1 = patch('package.module.Class1')
1869 ... self.patcher2 = patch('package.module.Class2')
1870 ... self.MockClass1 = self.patcher1.start()
1871 ... self.MockClass2 = self.patcher2.start()
1872 ...
1873 ... def tearDown(self):
1874 ... self.patcher1.stop()
1875 ... self.patcher2.stop()
1876 ...
1877 ... def test_something(self):
1878 ... assert package.module.Class1 is self.MockClass1
1879 ... assert package.module.Class2 is self.MockClass2
1880 ...
1881 >>> MyTest('test_something').run()
1882
1883 .. caution::
1884
1885 If you use this technique you must ensure that the patching is "undone" by
1886 calling ``stop``. This can be fiddlier than you might think, because if an
1887 exception is raised in the ``setUp`` then ``tearDown`` is not called.
1888 :meth:`unittest.TestCase.addCleanup` makes this easier::
1889
1890 >>> class MyTest(unittest.TestCase):
1891 ... def setUp(self):
1892 ... patcher = patch('package.module.Class')
1893 ... self.MockClass = patcher.start()
1894 ... self.addCleanup(patcher.stop)
1895 ...
1896 ... def test_something(self):
1897 ... assert package.module.Class is self.MockClass
1898 ...
1899
1900 As an added bonus you no longer need to keep a reference to the ``patcher``
1901 object.
1902
1903 It is also possible to stop all patches which have been started by using
1904 :func:`patch.stopall`.
1905
1906 .. function:: patch.stopall
1907
1908 Stop all active patches. Only stops patches started with ``start``.
1909
1910
1911 .. _patch-builtins:
1912
1913 patch builtins
1914 ~~~~~~~~~~~~~~
1915 You can patch any builtins within a module. The following example patches
1916 builtin :func:`ord`::
1917
1918 >>> @patch('__main__.ord')
1919 ... def test(mock_ord):
1920 ... mock_ord.return_value = 101
1921 ... print(ord('c'))
1922 ...
1923 >>> test()
1924 101
1925
1926
1927 .. _test-prefix:
1928
1929 TEST_PREFIX
1930 ~~~~~~~~~~~
1931
1932 All of the patchers can be used as class decorators. When used in this way
1933 they wrap every test method on the class. The patchers recognise methods that
1934 start with ``'test'`` as being test methods. This is the same way that the
1935 :class:`unittest.TestLoader` finds test methods by default.
1936
1937 It is possible that you want to use a different prefix for your tests. You can
1938 inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``::
1939
1940 >>> patch.TEST_PREFIX = 'foo'
1941 >>> value = 3
1942 >>>
1943 >>> @patch('__main__.value', 'not three')
1944 ... class Thing:
1945 ... def foo_one(self):
1946 ... print(value)
1947 ... def foo_two(self):
1948 ... print(value)
1949 ...
1950 >>>
1951 >>> Thing().foo_one()
1952 not three
1953 >>> Thing().foo_two()
1954 not three
1955 >>> value
1956 3
1957
1958
1959 Nesting Patch Decorators
1960 ~~~~~~~~~~~~~~~~~~~~~~~~
1961
1962 If you want to perform multiple patches then you can simply stack up the
1963 decorators.
1964
1965 You can stack up multiple patch decorators using this pattern:
1966
1967 >>> @patch.object(SomeClass, 'class_method')
1968 ... @patch.object(SomeClass, 'static_method')
1969 ... def test(mock1, mock2):
1970 ... assert SomeClass.static_method is mock1
1971 ... assert SomeClass.class_method is mock2
1972 ... SomeClass.static_method('foo')
1973 ... SomeClass.class_method('bar')
1974 ... return mock1, mock2
1975 ...
1976 >>> mock1, mock2 = test()
1977 >>> mock1.assert_called_once_with('foo')
1978 >>> mock2.assert_called_once_with('bar')
1979
1980
1981 Note that the decorators are applied from the bottom upwards. This is the
1982 standard way that Python applies decorators. The order of the created mocks
1983 passed into your test function matches this order.
1984
1985
1986 .. _where-to-patch:
1987
1988 Where to patch
1989 ~~~~~~~~~~~~~~
1990
1991 :func:`patch` works by (temporarily) changing the object that a *name* points to with
1992 another one. There can be many names pointing to any individual object, so
1993 for patching to work you must ensure that you patch the name used by the system
1994 under test.
1995
1996 The basic principle is that you patch where an object is *looked up*, which
1997 is not necessarily the same place as where it is defined. A couple of
1998 examples will help to clarify this.
1999
2000 Imagine we have a project that we want to test with the following structure::
2001
2002 a.py
2003 -> Defines SomeClass
2004
2005 b.py
2006 -> from a import SomeClass
2007 -> some_function instantiates SomeClass
2008
2009 Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
2010 :func:`patch`. The problem is that when we import module b, which we will have to
2011 do when it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
2012 ``a.SomeClass`` then it will have no effect on our test; module b already has a
2013 reference to the *real* ``SomeClass`` and it looks like our patching had no
2014 effect.
2015
2016 The key is to patch out ``SomeClass`` where it is used (or where it is looked up).
2017 In this case ``some_function`` will actually look up ``SomeClass`` in module b,
2018 where we have imported it. The patching should look like::
2019
2020 @patch('b.SomeClass')
2021
2022 However, consider the alternative scenario where instead of ``from a import
2023 SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both
2024 of these import forms are common. In this case the class we want to patch is
2025 being looked up in the module and so we have to patch ``a.SomeClass`` instead::
2026
2027 @patch('a.SomeClass')
2028
2029
2030 Patching Descriptors and Proxy Objects
2031 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2032
2033 Both patch_ and patch.object_ correctly patch and restore descriptors: class
2034 methods, static methods and properties. You should patch these on the *class*
2035 rather than an instance. They also work with *some* objects
2036 that proxy attribute access, like the `django settings object
2037 <https://web.archive.org/web/20200603181648/http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
2038
2039
2040 MagicMock and magic method support
2041 ----------------------------------
2042
2043 .. _magic-methods:
2044
2045 Mocking Magic Methods
2046 ~~~~~~~~~~~~~~~~~~~~~
2047
2048 :class:`Mock` supports mocking the Python protocol methods, also known as
2049 :term:`"magic methods" <magic method>`. This allows mock objects to replace
2050 containers or other objects that implement Python protocols.
2051
2052 Because magic methods are looked up differently from normal methods [#]_, this
2053 support has been specially implemented. This means that only specific magic
2054 methods are supported. The supported list includes *almost* all of them. If
2055 there are any missing that you need please let us know.
2056
2057 You mock magic methods by setting the method you are interested in to a function
2058 or a mock instance. If you are using a function then it *must* take ``self`` as
2059 the first argument [#]_.
2060
2061 >>> def __str__(self):
2062 ... return 'fooble'
2063 ...
2064 >>> mock = Mock()
2065 >>> mock.__str__ = __str__
2066 >>> str(mock)
2067 'fooble'
2068
2069 >>> mock = Mock()
2070 >>> mock.__str__ = Mock()
2071 >>> mock.__str__.return_value = 'fooble'
2072 >>> str(mock)
2073 'fooble'
2074
2075 >>> mock = Mock()
2076 >>> mock.__iter__ = Mock(return_value=iter([]))
2077 >>> list(mock)
2078 []
2079
2080 One use case for this is for mocking objects used as context managers in a
2081 :keyword:`with` statement:
2082
2083 >>> mock = Mock()
2084 >>> mock.__enter__ = Mock(return_value='foo')
2085 >>> mock.__exit__ = Mock(return_value=False)
2086 >>> with mock as m:
2087 ... assert m == 'foo'
2088 ...
2089 >>> mock.__enter__.assert_called_with()
2090 >>> mock.__exit__.assert_called_with(None, None, None)
2091
2092 Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they
2093 are recorded in :attr:`~Mock.mock_calls`.
2094
2095 .. note::
2096
2097 If you use the *spec* keyword argument to create a mock then attempting to
2098 set a magic method that isn't in the spec will raise an :exc:`AttributeError`.
2099
2100 The full list of supported magic methods is:
2101
2102 * ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``
2103 * ``__dir__``, ``__format__`` and ``__subclasses__``
2104 * ``__round__``, ``__floor__``, ``__trunc__`` and ``__ceil__``
2105 * Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``,
2106 ``__eq__`` and ``__ne__``
2107 * Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``,
2108 ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__``
2109 and ``__missing__``
2110 * Context manager: ``__enter__``, ``__exit__``, ``__aenter__`` and ``__aexit__``
2111 * Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``
2112 * The numeric methods (including right hand and in-place variants):
2113 ``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__truediv__``,
2114 ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``,
2115 ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``
2116 * Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__``
2117 and ``__index__``
2118 * Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
2119 * Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
2120 ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
2121 * File system path representation: ``__fspath__``
2122 * Asynchronous iteration methods: ``__aiter__`` and ``__anext__``
2123
2124 .. versionchanged:: 3.8
2125 Added support for :func:`os.PathLike.__fspath__`.
2126
2127 .. versionchanged:: 3.8
2128 Added support for ``__aenter__``, ``__aexit__``, ``__aiter__`` and ``__anext__``.
2129
2130
2131 The following methods exist but are *not* supported as they are either in use
2132 by mock, can't be set dynamically, or can cause problems:
2133
2134 * ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``
2135 * ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``
2136
2137
2138
2139 Magic Mock
2140 ~~~~~~~~~~
2141
2142 There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`.
2143
2144
2145 .. class:: MagicMock(*args, **kw)
2146
2147 ``MagicMock`` is a subclass of :class:`Mock` with default implementations
2148 of most of the :term:`magic methods <magic method>`. You can use
2149 ``MagicMock`` without having to configure the magic methods yourself.
2150
2151 The constructor parameters have the same meaning as for :class:`Mock`.
2152
2153 If you use the *spec* or *spec_set* arguments then *only* magic methods
2154 that exist in the spec will be created.
2155
2156
2157 .. class:: NonCallableMagicMock(*args, **kw)
2158
2159 A non-callable version of :class:`MagicMock`.
2160
2161 The constructor parameters have the same meaning as for
2162 :class:`MagicMock`, with the exception of *return_value* and
2163 *side_effect* which have no meaning on a non-callable mock.
2164
2165 The magic methods are setup with :class:`MagicMock` objects, so you can configure them
2166 and use them in the usual way:
2167
2168 >>> mock = MagicMock()
2169 >>> mock[3] = 'fish'
2170 >>> mock.__setitem__.assert_called_with(3, 'fish')
2171 >>> mock.__getitem__.return_value = 'result'
2172 >>> mock[2]
2173 'result'
2174
2175 By default many of the protocol methods are required to return objects of a
2176 specific type. These methods are preconfigured with a default return value, so
2177 that they can be used without you having to do anything if you aren't interested
2178 in the return value. You can still *set* the return value manually if you want
2179 to change the default.
2180
2181 Methods and their defaults:
2182
2183 * ``__lt__``: :data:`NotImplemented`
2184 * ``__gt__``: :data:`!NotImplemented`
2185 * ``__le__``: :data:`!NotImplemented`
2186 * ``__ge__``: :data:`!NotImplemented`
2187 * ``__int__``: ``1``
2188 * ``__contains__``: ``False``
2189 * ``__len__``: ``0``
2190 * ``__iter__``: ``iter([])``
2191 * ``__exit__``: ``False``
2192 * ``__aexit__``: ``False``
2193 * ``__complex__``: ``1j``
2194 * ``__float__``: ``1.0``
2195 * ``__bool__``: ``True``
2196 * ``__index__``: ``1``
2197 * ``__hash__``: default hash for the mock
2198 * ``__str__``: default str for the mock
2199 * ``__sizeof__``: default sizeof for the mock
2200
2201 For example:
2202
2203 >>> mock = MagicMock()
2204 >>> int(mock)
2205 1
2206 >>> len(mock)
2207 0
2208 >>> list(mock)
2209 []
2210 >>> object() in mock
2211 False
2212
2213 The two equality methods, :meth:`!__eq__` and :meth:`!__ne__`, are special.
2214 They do the default equality comparison on identity, using the
2215 :attr:`~Mock.side_effect` attribute, unless you change their return value to
2216 return something else::
2217
2218 >>> MagicMock() == 3
2219 False
2220 >>> MagicMock() != 3
2221 True
2222 >>> mock = MagicMock()
2223 >>> mock.__eq__.return_value = True
2224 >>> mock == 3
2225 True
2226
2227 The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
2228 required to be an iterator:
2229
2230 >>> mock = MagicMock()
2231 >>> mock.__iter__.return_value = ['a', 'b', 'c']
2232 >>> list(mock)
2233 ['a', 'b', 'c']
2234 >>> list(mock)
2235 ['a', 'b', 'c']
2236
2237 If the return value *is* an iterator, then iterating over it once will consume
2238 it and subsequent iterations will result in an empty list:
2239
2240 >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
2241 >>> list(mock)
2242 ['a', 'b', 'c']
2243 >>> list(mock)
2244 []
2245
2246 ``MagicMock`` has all of the supported magic methods configured except for some
2247 of the obscure and obsolete ones. You can still set these up if you want.
2248
2249 Magic methods that are supported but not setup by default in ``MagicMock`` are:
2250
2251 * ``__subclasses__``
2252 * ``__dir__``
2253 * ``__format__``
2254 * ``__get__``, ``__set__`` and ``__delete__``
2255 * ``__reversed__`` and ``__missing__``
2256 * ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
2257 ``__getstate__`` and ``__setstate__``
2258 * ``__getformat__``
2259
2260
2261
2262 .. [#] Magic methods *should* be looked up on the class rather than the
2263 instance. Different versions of Python are inconsistent about applying this
2264 rule. The supported protocol methods should work with all supported versions
2265 of Python.
2266 .. [#] The function is basically hooked up to the class, but each ``Mock``
2267 instance is kept isolated from the others.
2268
2269
2270 Helpers
2271 -------
2272
2273 sentinel
2274 ~~~~~~~~
2275
2276 .. data:: sentinel
2277
2278 The ``sentinel`` object provides a convenient way of providing unique
2279 objects for your tests.
2280
2281 Attributes are created on demand when you access them by name. Accessing
2282 the same attribute will always return the same object. The objects
2283 returned have a sensible repr so that test failure messages are readable.
2284
2285 .. versionchanged:: 3.7
2286 The ``sentinel`` attributes now preserve their identity when they are
2287 :mod:`copied <copy>` or :mod:`pickled <pickle>`.
2288
2289 Sometimes when testing you need to test that a specific object is passed as an
2290 argument to another method, or returned. It can be common to create named
2291 sentinel objects to test this. :data:`sentinel` provides a convenient way of
2292 creating and testing the identity of objects like this.
2293
2294 In this example we monkey patch ``method`` to return ``sentinel.some_object``:
2295
2296 >>> real = ProductionClass()
2297 >>> real.method = Mock(name="method")
2298 >>> real.method.return_value = sentinel.some_object
2299 >>> result = real.method()
2300 >>> assert result is sentinel.some_object
2301 >>> result
2302 sentinel.some_object
2303
2304
2305 DEFAULT
2306 ~~~~~~~
2307
2308
2309 .. data:: DEFAULT
2310
2311 The :data:`DEFAULT` object is a pre-created sentinel (actually
2312 ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect`
2313 functions to indicate that the normal return value should be used.
2314
2315
2316 call
2317 ~~~~
2318
2319 .. function:: call(*args, **kwargs)
2320
2321 :func:`call` is a helper object for making simpler assertions, for comparing with
2322 :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
2323 :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be
2324 used with :meth:`~Mock.assert_has_calls`.
2325
2326 >>> m = MagicMock(return_value=None)
2327 >>> m(1, 2, a='foo', b='bar')
2328 >>> m()
2329 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
2330 True
2331
2332 .. method:: call.call_list()
2333
2334 For a call object that represents multiple calls, :meth:`call_list`
2335 returns a list of all the intermediate calls as well as the
2336 final call.
2337
2338 ``call_list`` is particularly useful for making assertions on "chained calls". A
2339 chained call is multiple calls on a single line of code. This results in
2340 multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
2341 the sequence of calls can be tedious.
2342
2343 :meth:`~call.call_list` can construct the sequence of calls from the same
2344 chained call:
2345
2346 >>> m = MagicMock()
2347 >>> m(1).method(arg='foo').other('bar')(2.0)
2348 <MagicMock name='mock().method().other()()' id='...'>
2349 >>> kall = call(1).method(arg='foo').other('bar')(2.0)
2350 >>> kall.call_list()
2351 [call(1),
2352 call().method(arg='foo'),
2353 call().method().other('bar'),
2354 call().method().other()(2.0)]
2355 >>> m.mock_calls == kall.call_list()
2356 True
2357
2358 .. _calls-as-tuples:
2359
2360 A ``call`` object is either a tuple of (positional args, keyword args) or
2361 (name, positional args, keyword args) depending on how it was constructed. When
2362 you construct them yourself this isn't particularly interesting, but the ``call``
2363 objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
2364 :attr:`Mock.mock_calls` attributes can be introspected to get at the individual
2365 arguments they contain.
2366
2367 The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
2368 are two-tuples of (positional args, keyword args) whereas the ``call`` objects
2369 in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
2370 three-tuples of (name, positional args, keyword args).
2371
2372 You can use their "tupleness" to pull out the individual arguments for more
2373 complex introspection and assertions. The positional arguments are a tuple
2374 (an empty tuple if there are no positional arguments) and the keyword
2375 arguments are a dictionary:
2376
2377 >>> m = MagicMock(return_value=None)
2378 >>> m(1, 2, 3, arg='one', arg2='two')
2379 >>> kall = m.call_args
2380 >>> kall.args
2381 (1, 2, 3)
2382 >>> kall.kwargs
2383 {'arg': 'one', 'arg2': 'two'}
2384 >>> kall.args is kall[0]
2385 True
2386 >>> kall.kwargs is kall[1]
2387 True
2388
2389 >>> m = MagicMock()
2390 >>> m.foo(4, 5, 6, arg='two', arg2='three')
2391 <MagicMock name='mock.foo()' id='...'>
2392 >>> kall = m.mock_calls[0]
2393 >>> name, args, kwargs = kall
2394 >>> name
2395 'foo'
2396 >>> args
2397 (4, 5, 6)
2398 >>> kwargs
2399 {'arg': 'two', 'arg2': 'three'}
2400 >>> name is m.mock_calls[0][0]
2401 True
2402
2403
2404 create_autospec
2405 ~~~~~~~~~~~~~~~
2406
2407 .. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
2408
2409 Create a mock object using another object as a spec. Attributes on the
2410 mock will use the corresponding attribute on the *spec* object as their
2411 spec.
2412
2413 Functions or methods being mocked will have their arguments checked to
2414 ensure that they are called with the correct signature.
2415
2416 If *spec_set* is ``True`` then attempting to set attributes that don't exist
2417 on the spec object will raise an :exc:`AttributeError`.
2418
2419 If a class is used as a spec then the return value of the mock (the
2420 instance of the class) will have the same spec. You can use a class as the
2421 spec for an instance object by passing ``instance=True``. The returned mock
2422 will only be callable if instances of the mock are callable.
2423
2424 :func:`create_autospec` also takes arbitrary keyword arguments that are passed to
2425 the constructor of the created mock.
2426
2427 See :ref:`auto-speccing` for examples of how to use auto-speccing with
2428 :func:`create_autospec` and the *autospec* argument to :func:`patch`.
2429
2430
2431 .. versionchanged:: 3.8
2432
2433 :func:`create_autospec` now returns an :class:`AsyncMock` if the target is
2434 an async function.
2435
2436
2437 ANY
2438 ~~~
2439
2440 .. data:: ANY
2441
2442 Sometimes you may need to make assertions about *some* of the arguments in a
2443 call to mock, but either not care about some of the arguments or want to pull
2444 them individually out of :attr:`~Mock.call_args` and make more complex
2445 assertions on them.
2446
2447 To ignore certain arguments you can pass in objects that compare equal to
2448 *everything*. Calls to :meth:`~Mock.assert_called_with` and
2449 :meth:`~Mock.assert_called_once_with` will then succeed no matter what was
2450 passed in.
2451
2452 >>> mock = Mock(return_value=None)
2453 >>> mock('foo', bar=object())
2454 >>> mock.assert_called_once_with('foo', bar=ANY)
2455
2456 :data:`ANY` can also be used in comparisons with call lists like
2457 :attr:`~Mock.mock_calls`:
2458
2459 >>> m = MagicMock(return_value=None)
2460 >>> m(1)
2461 >>> m(1, 2)
2462 >>> m(object())
2463 >>> m.mock_calls == [call(1), call(1, 2), ANY]
2464 True
2465
2466 :data:`ANY` is not limited to comparisons with call objects and so
2467 can also be used in test assertions::
2468
2469 class TestStringMethods(unittest.TestCase):
2470
2471 def test_split(self):
2472 s = 'hello world'
2473 self.assertEqual(s.split(), ['hello', ANY])
2474
2475
2476 FILTER_DIR
2477 ~~~~~~~~~~
2478
2479 .. data:: FILTER_DIR
2480
2481 :data:`FILTER_DIR` is a module level variable that controls the way mock objects
2482 respond to :func:`dir`. The default is ``True``,
2483 which uses the filtering described below, to only show useful members. If you
2484 dislike this filtering, or need to switch it off for diagnostic purposes, then
2485 set ``mock.FILTER_DIR = False``.
2486
2487 With filtering on, ``dir(some_mock)`` shows only useful attributes and will
2488 include any dynamically created attributes that wouldn't normally be shown.
2489 If the mock was created with a *spec* (or *autospec* of course) then all the
2490 attributes from the original are shown, even if they haven't been accessed
2491 yet:
2492
2493 .. doctest::
2494 :options: +ELLIPSIS,+NORMALIZE_WHITESPACE
2495
2496 >>> dir(Mock())
2497 ['assert_any_call',
2498 'assert_called',
2499 'assert_called_once',
2500 'assert_called_once_with',
2501 'assert_called_with',
2502 'assert_has_calls',
2503 'assert_not_called',
2504 'attach_mock',
2505 ...
2506 >>> from urllib import request
2507 >>> dir(Mock(spec=request))
2508 ['AbstractBasicAuthHandler',
2509 'AbstractDigestAuthHandler',
2510 'AbstractHTTPHandler',
2511 'BaseHandler',
2512 ...
2513
2514 Many of the not-very-useful (private to :class:`Mock` rather than the thing being
2515 mocked) underscore and double underscore prefixed attributes have been
2516 filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this
2517 behaviour you can switch it off by setting the module level switch
2518 :data:`FILTER_DIR`:
2519
2520 .. doctest::
2521 :options: +ELLIPSIS,+NORMALIZE_WHITESPACE
2522
2523 >>> from unittest import mock
2524 >>> mock.FILTER_DIR = False
2525 >>> dir(mock.Mock())
2526 ['_NonCallableMock__get_return_value',
2527 '_NonCallableMock__get_side_effect',
2528 '_NonCallableMock__return_value_doc',
2529 '_NonCallableMock__set_return_value',
2530 '_NonCallableMock__set_side_effect',
2531 '__call__',
2532 '__class__',
2533 ...
2534
2535 Alternatively you can just use ``vars(my_mock)`` (instance members) and
2536 ``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of
2537 :const:`FILTER_DIR`.
2538
2539
2540 mock_open
2541 ~~~~~~~~~
2542
2543 .. function:: mock_open(mock=None, read_data=None)
2544
2545 A helper function to create a mock to replace the use of :func:`open`. It works
2546 for :func:`open` called directly or used as a context manager.
2547
2548 The *mock* argument is the mock object to configure. If ``None`` (the
2549 default) then a :class:`MagicMock` will be created for you, with the API limited
2550 to methods or attributes available on standard file handles.
2551
2552 *read_data* is a string for the :meth:`~io.RawIOBase.read`,
2553 :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods
2554 of the file handle to return. Calls to those methods will take data from
2555 *read_data* until it is depleted. The mock of these methods is pretty
2556 simplistic: every time the *mock* is called, the *read_data* is rewound to
2557 the start. If you need more control over the data that you are feeding to
2558 the tested code you will need to customize this mock for yourself. When that
2559 is insufficient, one of the in-memory filesystem packages on `PyPI
2560 <https://pypi.org>`_ can offer a realistic filesystem for testing.
2561
2562 .. versionchanged:: 3.4
2563 Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support.
2564 The mock of :meth:`~io.RawIOBase.read` changed to consume *read_data* rather
2565 than returning it on each call.
2566
2567 .. versionchanged:: 3.5
2568 *read_data* is now reset on each call to the *mock*.
2569
2570 .. versionchanged:: 3.8
2571 Added :meth:`~container.__iter__` to implementation so that iteration
2572 (such as in for loops) correctly consumes *read_data*.
2573
2574 Using :func:`open` as a context manager is a great way to ensure your file handles
2575 are closed properly and is becoming common::
2576
2577 with open('/some/path', 'w') as f:
2578 f.write('something')
2579
2580 The issue is that even if you mock out the call to :func:`open` it is the
2581 *returned object* that is used as a context manager (and has :meth:`~object.__enter__` and
2582 :meth:`~object.__exit__` called).
2583
2584 Mocking context managers with a :class:`MagicMock` is common enough and fiddly
2585 enough that a helper function is useful. ::
2586
2587 >>> m = mock_open()
2588 >>> with patch('__main__.open', m):
2589 ... with open('foo', 'w') as h:
2590 ... h.write('some stuff')
2591 ...
2592 >>> m.mock_calls
2593 [call('foo', 'w'),
2594 call().__enter__(),
2595 call().write('some stuff'),
2596 call().__exit__(None, None, None)]
2597 >>> m.assert_called_once_with('foo', 'w')
2598 >>> handle = m()
2599 >>> handle.write.assert_called_once_with('some stuff')
2600
2601 And for reading files::
2602
2603 >>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
2604 ... with open('foo') as h:
2605 ... result = h.read()
2606 ...
2607 >>> m.assert_called_once_with('foo')
2608 >>> assert result == 'bibble'
2609
2610
2611 .. _auto-speccing:
2612
2613 Autospeccing
2614 ~~~~~~~~~~~~
2615
2616 Autospeccing is based on the existing :attr:`!spec` feature of mock. It limits the
2617 api of mocks to the api of an original object (the spec), but it is recursive
2618 (implemented lazily) so that attributes of mocks only have the same api as
2619 the attributes of the spec. In addition mocked functions / methods have the
2620 same call signature as the original so they raise a :exc:`TypeError` if they are
2621 called incorrectly.
2622
2623 Before I explain how auto-speccing works, here's why it is needed.
2624
2625 :class:`Mock` is a very powerful and flexible object, but it suffers from a flaw which
2626 is general to mocking. If you refactor some of your code, rename members and so on, any
2627 tests for code that is still using the *old api* but uses mocks instead of the real
2628 objects will still pass. This means your tests can all pass even though your code is
2629 broken.
2630
2631 .. versionchanged:: 3.5
2632
2633 Before 3.5, tests with a typo in the word assert would silently pass when they should
2634 raise an error. You can still achieve this behavior by passing ``unsafe=True`` to Mock.
2635
2636 Note that this is another reason why you need integration tests as well as
2637 unit tests. Testing everything in isolation is all fine and dandy, but if you
2638 don't test how your units are "wired together" there is still lots of room
2639 for bugs that tests might have caught.
2640
2641 :mod:`!unittest.mock` already provides a feature to help with this, called speccing. If you
2642 use a class or instance as the :attr:`!spec` for a mock then you can only access
2643 attributes on the mock that exist on the real class:
2644
2645 >>> from urllib import request
2646 >>> mock = Mock(spec=request.Request)
2647 >>> mock.assret_called_with # Intentional typo!
2648 Traceback (most recent call last):
2649 ...
2650 AttributeError: Mock object has no attribute 'assret_called_with'
2651
2652 The spec only applies to the mock itself, so we still have the same issue
2653 with any methods on the mock:
2654
2655 .. code-block:: pycon
2656
2657 >>> mock.header_items()
2658 <mock.Mock object at 0x...>
2659 >>> mock.header_items.assret_called_with() # Intentional typo!
2660
2661 Auto-speccing solves this problem. You can either pass ``autospec=True`` to
2662 :func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a
2663 mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the
2664 object that is being replaced will be used as the spec object. Because the
2665 speccing is done "lazily" (the spec is created as attributes on the mock are
2666 accessed) you can use it with very complex or deeply nested objects (like
2667 modules that import modules that import modules) without a big performance
2668 hit.
2669
2670 Here's an example of it in use::
2671
2672 >>> from urllib import request
2673 >>> patcher = patch('__main__.request', autospec=True)
2674 >>> mock_request = patcher.start()
2675 >>> request is mock_request
2676 True
2677 >>> mock_request.Request
2678 <MagicMock name='request.Request' spec='Request' id='...'>
2679
2680 You can see that :class:`!request.Request` has a spec. :class:`!request.Request` takes two
2681 arguments in the constructor (one of which is *self*). Here's what happens if
2682 we try to call it incorrectly::
2683
2684 >>> req = request.Request()
2685 Traceback (most recent call last):
2686 ...
2687 TypeError: <lambda>() takes at least 2 arguments (1 given)
2688
2689 The spec also applies to instantiated classes (i.e. the return value of
2690 specced mocks)::
2691
2692 >>> req = request.Request('foo')
2693 >>> req
2694 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
2695
2696 :class:`!Request` objects are not callable, so the return value of instantiating our
2697 mocked out :class:`!request.Request` is a non-callable mock. With the spec in place
2698 any typos in our asserts will raise the correct error::
2699
2700 >>> req.add_header('spam', 'eggs')
2701 <MagicMock name='request.Request().add_header()' id='...'>
2702 >>> req.add_header.assret_called_with # Intentional typo!
2703 Traceback (most recent call last):
2704 ...
2705 AttributeError: Mock object has no attribute 'assret_called_with'
2706 >>> req.add_header.assert_called_with('spam', 'eggs')
2707
2708 In many cases you will just be able to add ``autospec=True`` to your existing
2709 :func:`patch` calls and then be protected against bugs due to typos and api
2710 changes.
2711
2712 As well as using *autospec* through :func:`patch` there is a
2713 :func:`create_autospec` for creating autospecced mocks directly:
2714
2715 >>> from urllib import request
2716 >>> mock_request = create_autospec(request)
2717 >>> mock_request.Request('foo', 'bar')
2718 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
2719
2720 This isn't without caveats and limitations however, which is why it is not
2721 the default behaviour. In order to know what attributes are available on the
2722 spec object, autospec has to introspect (access attributes) the spec. As you
2723 traverse attributes on the mock a corresponding traversal of the original
2724 object is happening under the hood. If any of your specced objects have
2725 properties or descriptors that can trigger code execution then you may not be
2726 able to use autospec. On the other hand it is much better to design your
2727 objects so that introspection is safe [#]_.
2728
2729 A more serious problem is that it is common for instance attributes to be
2730 created in the :meth:`~object.__init__` method and not to exist on the class at all.
2731 *autospec* can't know about any dynamically created attributes and restricts
2732 the api to visible attributes. ::
2733
2734 >>> class Something:
2735 ... def __init__(self):
2736 ... self.a = 33
2737 ...
2738 >>> with patch('__main__.Something', autospec=True):
2739 ... thing = Something()
2740 ... thing.a
2741 ...
2742 Traceback (most recent call last):
2743 ...
2744 AttributeError: Mock object has no attribute 'a'
2745
2746 There are a few different ways of resolving this problem. The easiest, but
2747 not necessarily the least annoying, way is to simply set the required
2748 attributes on the mock after creation. Just because *autospec* doesn't allow
2749 you to fetch attributes that don't exist on the spec it doesn't prevent you
2750 setting them::
2751
2752 >>> with patch('__main__.Something', autospec=True):
2753 ... thing = Something()
2754 ... thing.a = 33
2755 ...
2756
2757 There is a more aggressive version of both *spec* and *autospec* that *does*
2758 prevent you setting non-existent attributes. This is useful if you want to
2759 ensure your code only *sets* valid attributes too, but obviously it prevents
2760 this particular scenario:
2761
2762 >>> with patch('__main__.Something', autospec=True, spec_set=True):
2763 ... thing = Something()
2764 ... thing.a = 33
2765 ...
2766 Traceback (most recent call last):
2767 ...
2768 AttributeError: Mock object has no attribute 'a'
2769
2770 Probably the best way of solving the problem is to add class attributes as
2771 default values for instance members initialised in :meth:`~object.__init__`.
2772 Note that if
2773 you are only setting default attributes in :meth:`!__init__` then providing them via
2774 class attributes (shared between instances of course) is faster too. e.g.
2775
2776 .. code-block:: python
2777
2778 class Something:
2779 a = 33
2780
2781 This brings up another issue. It is relatively common to provide a default
2782 value of ``None`` for members that will later be an object of a different type.
2783 ``None`` would be useless as a spec because it wouldn't let you access *any*
2784 attributes or methods on it. As ``None`` is *never* going to be useful as a
2785 spec, and probably indicates a member that will normally of some other type,
2786 autospec doesn't use a spec for members that are set to ``None``. These will
2787 just be ordinary mocks (well - MagicMocks):
2788
2789 >>> class Something:
2790 ... member = None
2791 ...
2792 >>> mock = create_autospec(Something)
2793 >>> mock.member.foo.bar.baz()
2794 <MagicMock name='mock.member.foo.bar.baz()' id='...'>
2795
2796 If modifying your production classes to add defaults isn't to your liking
2797 then there are more options. One of these is simply to use an instance as the
2798 spec rather than the class. The other is to create a subclass of the
2799 production class and add the defaults to the subclass without affecting the
2800 production class. Both of these require you to use an alternative object as
2801 the spec. Thankfully :func:`patch` supports this - you can simply pass the
2802 alternative object as the *autospec* argument::
2803
2804 >>> class Something:
2805 ... def __init__(self):
2806 ... self.a = 33
2807 ...
2808 >>> class SomethingForTest(Something):
2809 ... a = 33
2810 ...
2811 >>> p = patch('__main__.Something', autospec=SomethingForTest)
2812 >>> mock = p.start()
2813 >>> mock.a
2814 <NonCallableMagicMock name='Something.a' spec='int' id='...'>
2815
2816
2817 .. [#] This only applies to classes or already instantiated objects. Calling
2818 a mocked class to create a mock instance *does not* create a real instance.
2819 It is only attribute lookups - along with calls to :func:`dir` - that are done.
2820
2821 Sealing mocks
2822 ~~~~~~~~~~~~~
2823
2824
2825 .. testsetup::
2826
2827 from unittest.mock import seal
2828
2829 .. function:: seal(mock)
2830
2831 Seal will disable the automatic creation of mocks when accessing an attribute of
2832 the mock being sealed or any of its attributes that are already mocks recursively.
2833
2834 If a mock instance with a name or a spec is assigned to an attribute
2835 it won't be considered in the sealing chain. This allows one to prevent seal from
2836 fixing part of the mock object. ::
2837
2838 >>> mock = Mock()
2839 >>> mock.submock.attribute1 = 2
2840 >>> mock.not_submock = mock.Mock(name="sample_name")
2841 >>> seal(mock)
2842 >>> mock.new_attribute # This will raise AttributeError.
2843 >>> mock.submock.attribute2 # This will raise AttributeError.
2844 >>> mock.not_submock.attribute2 # This won't raise.
2845
2846 .. versionadded:: 3.7
2847
2848
2849 Order of precedence of :attr:`!side_effect`, :attr:`!return_value` and *wraps*
2850 ------------------------------------------------------------------------------
2851
2852 The order of their precedence is:
2853
2854 1. :attr:`~Mock.side_effect`
2855 2. :attr:`~Mock.return_value`
2856 3. *wraps*
2857
2858 If all three are set, mock will return the value from :attr:`~Mock.side_effect`,
2859 ignoring :attr:`~Mock.return_value` and the wrapped object altogether. If any
2860 two are set, the one with the higher precedence will return the value.
2861 Regardless of the order of which was set first, the order of precedence
2862 remains unchanged.
2863
2864 >>> from unittest.mock import Mock
2865 >>> class Order:
2866 ... @staticmethod
2867 ... def get_value():
2868 ... return "third"
2869 ...
2870 >>> order_mock = Mock(spec=Order, wraps=Order)
2871 >>> order_mock.get_value.side_effect = ["first"]
2872 >>> order_mock.get_value.return_value = "second"
2873 >>> order_mock.get_value()
2874 'first'
2875
2876 As ``None`` is the default value of :attr:`~Mock.side_effect`, if you reassign
2877 its value back to ``None``, the order of precedence will be checked between
2878 :attr:`~Mock.return_value` and the wrapped object, ignoring
2879 :attr:`~Mock.side_effect`.
2880
2881 >>> order_mock.get_value.side_effect = None
2882 >>> order_mock.get_value()
2883 'second'
2884
2885 If the value being returned by :attr:`~Mock.side_effect` is :data:`DEFAULT`,
2886 it is ignored and the order of precedence moves to the successor to obtain the
2887 value to return.
2888
2889 >>> from unittest.mock import DEFAULT
2890 >>> order_mock.get_value.side_effect = [DEFAULT]
2891 >>> order_mock.get_value()
2892 'second'
2893
2894 When :class:`Mock` wraps an object, the default value of
2895 :attr:`~Mock.return_value` will be :data:`DEFAULT`.
2896
2897 >>> order_mock = Mock(spec=Order, wraps=Order)
2898 >>> order_mock.return_value
2899 sentinel.DEFAULT
2900 >>> order_mock.get_value.return_value
2901 sentinel.DEFAULT
2902
2903 The order of precedence will ignore this value and it will move to the last
2904 successor which is the wrapped object.
2905
2906 As the real call is being made to the wrapped object, creating an instance of
2907 this mock will return the real instance of the class. The positional arguments,
2908 if any, required by the wrapped object must be passed.
2909
2910 >>> order_mock_instance = order_mock()
2911 >>> isinstance(order_mock_instance, Order)
2912 True
2913 >>> order_mock_instance.get_value()
2914 'third'
2915
2916 >>> order_mock.get_value.return_value = DEFAULT
2917 >>> order_mock.get_value()
2918 'third'
2919
2920 >>> order_mock.get_value.return_value = "second"
2921 >>> order_mock.get_value()
2922 'second'
2923
2924 But if you assign ``None`` to it, this will not be ignored as it is an
2925 explicit assignment. So, the order of precedence will not move to the wrapped
2926 object.
2927
2928 >>> order_mock.get_value.return_value = None
2929 >>> order_mock.get_value() is None
2930 True
2931
2932 Even if you set all three at once when initializing the mock, the order of
2933 precedence remains the same:
2934
2935 >>> order_mock = Mock(spec=Order, wraps=Order,
2936 ... **{"get_value.side_effect": ["first"],
2937 ... "get_value.return_value": "second"}
2938 ... )
2939 ...
2940 >>> order_mock.get_value()
2941 'first'
2942 >>> order_mock.get_value.side_effect = None
2943 >>> order_mock.get_value()
2944 'second'
2945 >>> order_mock.get_value.return_value = DEFAULT
2946 >>> order_mock.get_value()
2947 'third'
2948
2949 If :attr:`~Mock.side_effect` is exhausted, the order of precedence will not
2950 cause a value to be obtained from the successors. Instead, ``StopIteration``
2951 exception is raised.
2952
2953 >>> order_mock = Mock(spec=Order, wraps=Order)
2954 >>> order_mock.get_value.side_effect = ["first side effect value",
2955 ... "another side effect value"]
2956 >>> order_mock.get_value.return_value = "second"
2957
2958 >>> order_mock.get_value()
2959 'first side effect value'
2960 >>> order_mock.get_value()
2961 'another side effect value'
2962
2963 >>> order_mock.get_value()
2964 Traceback (most recent call last):
2965 ...
2966 StopIteration