blob: f795a2e8c1aebff62fce93673e8da714fbd7fa65 [file] [log] [blame]
Andrew Svetlov7ea6f702012-10-31 11:29:52 +02001
Michael Foord944e02d2012-03-25 23:12:55 +01002:mod:`unittest.mock` --- mock object library
3============================================
4
5.. module:: unittest.mock
6 :synopsis: Mock object library.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04007
Michael Foord944e02d2012-03-25 23:12:55 +01008.. moduleauthor:: Michael Foord <michael@python.org>
9.. currentmodule:: unittest.mock
10
11.. versionadded:: 3.3
12
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040013**Source code:** :source:`Lib/unittest/mock.py`
14
15--------------
16
Michael Foord944e02d2012-03-25 23:12:55 +010017:mod:`unittest.mock` is a library for testing in Python. It allows you to
18replace parts of your system under test with mock objects and make assertions
19about how they have been used.
20
Georg Brandl7ad3df62014-10-31 07:59:37 +010021:mod:`unittest.mock` provides a core :class:`Mock` class removing the need to
Michael Foord944e02d2012-03-25 23:12:55 +010022create a host of stubs throughout your test suite. After performing an
23action, you can make assertions about which methods / attributes were used
24and arguments they were called with. You can also specify return values and
25set needed attributes in the normal way.
26
27Additionally, mock provides a :func:`patch` decorator that handles patching
28module and class level attributes within the scope of a test, along with
29:const:`sentinel` for creating unique objects. See the `quick guide`_ for
30some examples of how to use :class:`Mock`, :class:`MagicMock` and
31:func:`patch`.
32
33Mock is very easy to use and is designed for use with :mod:`unittest`. Mock
Georg Brandl7ad3df62014-10-31 07:59:37 +010034is based on the 'action -> assertion' pattern instead of 'record -> replay'
Michael Foord944e02d2012-03-25 23:12:55 +010035used by many mocking frameworks.
36
Georg Brandl7ad3df62014-10-31 07:59:37 +010037There is a backport of :mod:`unittest.mock` for earlier versions of Python,
Stéphane Wirtel19177fb2018-05-15 20:58:35 +020038available as `mock on PyPI <https://pypi.org/project/mock>`_.
Michael Foord944e02d2012-03-25 23:12:55 +010039
Michael Foord944e02d2012-03-25 23:12:55 +010040
41Quick Guide
42-----------
43
Stéphane Wirtel859c0682018-10-12 09:51:05 +020044.. testsetup::
45
46 class ProductionClass:
47 def method(self, a, b, c):
48 pass
49
50 class SomeClass:
51 @staticmethod
52 def static_method(args):
53 return args
54
55 @classmethod
56 def class_method(cls, args):
57 return args
58
59
Michael Foord944e02d2012-03-25 23:12:55 +010060:class:`Mock` and :class:`MagicMock` objects create all attributes and
61methods as you access them and store details of how they have been used. You
62can configure them, to specify return values or limit what attributes are
63available, and then make assertions about how they have been used:
64
65 >>> from unittest.mock import MagicMock
66 >>> thing = ProductionClass()
67 >>> thing.method = MagicMock(return_value=3)
68 >>> thing.method(3, 4, 5, key='value')
69 3
70 >>> thing.method.assert_called_with(3, 4, 5, key='value')
71
72:attr:`side_effect` allows you to perform side effects, including raising an
73exception when a mock is called:
74
75 >>> mock = Mock(side_effect=KeyError('foo'))
76 >>> mock()
77 Traceback (most recent call last):
78 ...
79 KeyError: 'foo'
80
81 >>> values = {'a': 1, 'b': 2, 'c': 3}
82 >>> def side_effect(arg):
83 ... return values[arg]
84 ...
85 >>> mock.side_effect = side_effect
86 >>> mock('a'), mock('b'), mock('c')
87 (1, 2, 3)
88 >>> mock.side_effect = [5, 4, 3, 2, 1]
89 >>> mock(), mock(), mock()
90 (5, 4, 3)
91
92Mock has many other ways you can configure it and control its behaviour. For
Georg Brandl7ad3df62014-10-31 07:59:37 +010093example the *spec* argument configures the mock to take its specification
Michael Foord944e02d2012-03-25 23:12:55 +010094from another object. Attempting to access attributes or methods on the mock
Georg Brandl7ad3df62014-10-31 07:59:37 +010095that don't exist on the spec will fail with an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +010096
97The :func:`patch` decorator / context manager makes it easy to mock classes or
98objects in a module under test. The object you specify will be replaced with a
Stéphane Wirtel859c0682018-10-12 09:51:05 +020099mock (or other object) during the test and restored when the test ends::
Michael Foord944e02d2012-03-25 23:12:55 +0100100
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()
Michael Foord944e02d2012-03-25 23:12:55 +0100107 ... 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
Andrés Delfino271818f2018-09-14 14:13:09 -0300117 function in the same order they applied (the normal *Python* order that
Michael Foord944e02d2012-03-25 23:12:55 +0100118 decorators are applied). This means from the bottom up, so in the example
Georg Brandl7ad3df62014-10-31 07:59:37 +0100119 above the mock for ``module.ClassName1`` is passed in first.
Michael Foord944e02d2012-03-25 23:12:55 +0100120
Georg Brandl7ad3df62014-10-31 07:59:37 +0100121 With :func:`patch` it matters that you patch objects in the namespace where they
Michael Foord944e02d2012-03-25 23:12:55 +0100122 are looked up. This is normally straightforward, but for a quick guide
123 read :ref:`where to patch <where-to-patch>`.
124
Georg Brandl7ad3df62014-10-31 07:59:37 +0100125As well as a decorator :func:`patch` can be used as a context manager in a with
Michael Foord944e02d2012-03-25 23:12:55 +0100126statement:
127
128 >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
129 ... thing = ProductionClass()
130 ... thing.method(1, 2, 3)
131 ...
132 >>> mock_method.assert_called_once_with(1, 2, 3)
133
134
135There is also :func:`patch.dict` for setting values in a dictionary just
136during a scope and restoring the dictionary to its original state when the test
137ends:
138
139 >>> foo = {'key': 'value'}
140 >>> original = foo.copy()
141 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
142 ... assert foo == {'newkey': 'newvalue'}
143 ...
144 >>> assert foo == original
145
146Mock supports the mocking of Python :ref:`magic methods <magic-methods>`. The
147easiest way of using magic methods is with the :class:`MagicMock` class. It
148allows you to do things like:
149
150 >>> mock = MagicMock()
151 >>> mock.__str__.return_value = 'foobarbaz'
152 >>> str(mock)
153 'foobarbaz'
154 >>> mock.__str__.assert_called_with()
155
156Mock allows you to assign functions (or other Mock instances) to magic methods
Georg Brandl7ad3df62014-10-31 07:59:37 +0100157and they will be called appropriately. The :class:`MagicMock` class is just a Mock
Michael Foord944e02d2012-03-25 23:12:55 +0100158variant that has all of the magic methods pre-created for you (well, all the
159useful ones anyway).
160
161The following is an example of using magic methods with the ordinary Mock
162class:
163
164 >>> mock = Mock()
165 >>> mock.__str__ = Mock(return_value='wheeeeee')
166 >>> str(mock)
167 'wheeeeee'
168
169For ensuring that the mock objects in your tests have the same api as the
170objects they are replacing, you can use :ref:`auto-speccing <auto-speccing>`.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100171Auto-speccing can be done through the *autospec* argument to patch, or the
Michael Foord944e02d2012-03-25 23:12:55 +0100172:func:`create_autospec` function. Auto-speccing creates mock objects that
173have the same attributes and methods as the objects they are replacing, and
174any functions and methods (including constructors) have the same call
175signature as the real object.
176
177This ensures that your mocks will fail in the same way as your production
178code if they are used incorrectly:
179
180 >>> from unittest.mock import create_autospec
181 >>> def function(a, b, c):
182 ... pass
183 ...
184 >>> mock_function = create_autospec(function, return_value='fishy')
185 >>> mock_function(1, 2, 3)
186 'fishy'
187 >>> mock_function.assert_called_once_with(1, 2, 3)
188 >>> mock_function('wrong arguments')
189 Traceback (most recent call last):
190 ...
191 TypeError: <lambda>() takes exactly 3 arguments (1 given)
192
Georg Brandl7ad3df62014-10-31 07:59:37 +0100193:func:`create_autospec` can also be used on classes, where it copies the signature of
194the ``__init__`` method, and on callable objects where it copies the signature of
195the ``__call__`` method.
Michael Foord944e02d2012-03-25 23:12:55 +0100196
197
198
199The Mock Class
200--------------
201
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200202.. testsetup::
203
Lisa Roach77b3b772019-05-20 09:19:53 -0700204 import asyncio
205 import inspect
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200206 import unittest
207 from unittest.mock import sentinel, DEFAULT, ANY
Lisa Roach77b3b772019-05-20 09:19:53 -0700208 from unittest.mock import patch, call, Mock, MagicMock, PropertyMock, AsyncMock
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200209 from unittest.mock import mock_open
Michael Foord944e02d2012-03-25 23:12:55 +0100210
Georg Brandl7ad3df62014-10-31 07:59:37 +0100211:class:`Mock` is a flexible mock object intended to replace the use of stubs and
Michael Foord944e02d2012-03-25 23:12:55 +0100212test doubles throughout your code. Mocks are callable and create attributes as
213new mocks when you access them [#]_. Accessing the same attribute will always
214return the same mock. Mocks record how you use them, allowing you to make
215assertions about what your code has done to them.
216
Georg Brandl7ad3df62014-10-31 07:59:37 +0100217:class:`MagicMock` is a subclass of :class:`Mock` with all the magic methods
Michael Foord944e02d2012-03-25 23:12:55 +0100218pre-created and ready to use. There are also non-callable variants, useful
219when you are mocking out objects that aren't callable:
220:class:`NonCallableMock` and :class:`NonCallableMagicMock`
221
222The :func:`patch` decorators makes it easy to temporarily replace classes
Georg Brandl7ad3df62014-10-31 07:59:37 +0100223in a particular module with a :class:`Mock` object. By default :func:`patch` will create
224a :class:`MagicMock` for you. You can specify an alternative class of :class:`Mock` using
225the *new_callable* argument to :func:`patch`.
Michael Foord944e02d2012-03-25 23:12:55 +0100226
227
Kushal Das8c145342014-04-16 23:32:21 +0530228.. class:: Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs)
Michael Foord944e02d2012-03-25 23:12:55 +0100229
Georg Brandl7ad3df62014-10-31 07:59:37 +0100230 Create a new :class:`Mock` object. :class:`Mock` takes several optional arguments
Michael Foord944e02d2012-03-25 23:12:55 +0100231 that specify the behaviour of the Mock object:
232
Georg Brandl7ad3df62014-10-31 07:59:37 +0100233 * *spec*: This can be either a list of strings or an existing object (a
Michael Foord944e02d2012-03-25 23:12:55 +0100234 class or instance) that acts as the specification for the mock object. If
235 you pass in an object then a list of strings is formed by calling dir on
236 the object (excluding unsupported magic attributes and methods).
Georg Brandl7ad3df62014-10-31 07:59:37 +0100237 Accessing any attribute not in this list will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100238
Georg Brandl7ad3df62014-10-31 07:59:37 +0100239 If *spec* is an object (rather than a list of strings) then
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300240 :attr:`~instance.__class__` returns the class of the spec object. This
Georg Brandl7ad3df62014-10-31 07:59:37 +0100241 allows mocks to pass :func:`isinstance` tests.
Michael Foord944e02d2012-03-25 23:12:55 +0100242
Georg Brandl7ad3df62014-10-31 07:59:37 +0100243 * *spec_set*: A stricter variant of *spec*. If used, attempting to *set*
Michael Foord944e02d2012-03-25 23:12:55 +0100244 or get an attribute on the mock that isn't on the object passed as
Georg Brandl7ad3df62014-10-31 07:59:37 +0100245 *spec_set* will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100246
Georg Brandl7ad3df62014-10-31 07:59:37 +0100247 * *side_effect*: A function to be called whenever the Mock is called. See
Michael Foord944e02d2012-03-25 23:12:55 +0100248 the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or
249 dynamically changing return values. The function is called with the same
250 arguments as the mock, and unless it returns :data:`DEFAULT`, the return
251 value of this function is used as the return value.
252
Georg Brandl7ad3df62014-10-31 07:59:37 +0100253 Alternatively *side_effect* can be an exception class or instance. In
Michael Foord944e02d2012-03-25 23:12:55 +0100254 this case the exception will be raised when the mock is called.
255
Georg Brandl7ad3df62014-10-31 07:59:37 +0100256 If *side_effect* is an iterable then each call to the mock will return
Michael Foord944e02d2012-03-25 23:12:55 +0100257 the next value from the iterable.
258
Georg Brandl7ad3df62014-10-31 07:59:37 +0100259 A *side_effect* can be cleared by setting it to ``None``.
Michael Foord944e02d2012-03-25 23:12:55 +0100260
Georg Brandl7ad3df62014-10-31 07:59:37 +0100261 * *return_value*: The value returned when the mock is called. By default
Michael Foord944e02d2012-03-25 23:12:55 +0100262 this is a new Mock (created on first access). See the
263 :attr:`return_value` attribute.
264
vabr-g9fc57132020-12-10 19:35:28 +0100265 * *unsafe*: By default, accessing any attribute with name starting with
266 *assert*, *assret*, *asert*, *aseert* or *assrt* will raise an
267 :exc:`AttributeError`. Passing ``unsafe=True`` will allow access to
268 these attributes.
Kushal Das8c145342014-04-16 23:32:21 +0530269
270 .. versionadded:: 3.5
271
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300272 * *wraps*: Item for the mock object to wrap. If *wraps* is not ``None`` then
Michael Foord944e02d2012-03-25 23:12:55 +0100273 calling the Mock will pass the call through to the wrapped object
Michael Foord0682a0c2012-04-13 20:51:20 +0100274 (returning the real result). Attribute access on the mock will return a
275 Mock object that wraps the corresponding attribute of the wrapped
276 object (so attempting to access an attribute that doesn't exist will
Georg Brandl7ad3df62014-10-31 07:59:37 +0100277 raise an :exc:`AttributeError`).
Michael Foord944e02d2012-03-25 23:12:55 +0100278
Georg Brandl7ad3df62014-10-31 07:59:37 +0100279 If the mock has an explicit *return_value* set then calls are not passed
280 to the wrapped object and the *return_value* is returned instead.
Michael Foord944e02d2012-03-25 23:12:55 +0100281
Georg Brandl7ad3df62014-10-31 07:59:37 +0100282 * *name*: If the mock has a name then it will be used in the repr of the
Michael Foord944e02d2012-03-25 23:12:55 +0100283 mock. This can be useful for debugging. The name is propagated to child
284 mocks.
285
286 Mocks can also be called with arbitrary keyword arguments. These will be
287 used to set attributes on the mock after it is created. See the
288 :meth:`configure_mock` method for details.
289
Ismail Sf9590ed2019-08-12 07:57:03 +0100290 .. method:: assert_called()
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100291
292 Assert that the mock was called at least once.
293
294 >>> mock = Mock()
295 >>> mock.method()
296 <Mock name='mock.method()' id='...'>
297 >>> mock.method.assert_called()
298
299 .. versionadded:: 3.6
300
Ismail Sf9590ed2019-08-12 07:57:03 +0100301 .. method:: assert_called_once()
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100302
303 Assert that the mock was called exactly once.
304
305 >>> mock = Mock()
306 >>> mock.method()
307 <Mock name='mock.method()' id='...'>
308 >>> mock.method.assert_called_once()
309 >>> mock.method()
310 <Mock name='mock.method()' id='...'>
311 >>> mock.method.assert_called_once()
312 Traceback (most recent call last):
313 ...
314 AssertionError: Expected 'method' to have been called once. Called 2 times.
315
316 .. versionadded:: 3.6
317
Michael Foord944e02d2012-03-25 23:12:55 +0100318
319 .. method:: assert_called_with(*args, **kwargs)
320
Rémi Lapeyref5896a02019-08-29 08:15:53 +0200321 This method is a convenient way of asserting that the last call has been
322 made in a particular way:
Michael Foord944e02d2012-03-25 23:12:55 +0100323
324 >>> mock = Mock()
325 >>> mock.method(1, 2, 3, test='wow')
326 <Mock name='mock.method()' id='...'>
327 >>> mock.method.assert_called_with(1, 2, 3, test='wow')
328
Michael Foord944e02d2012-03-25 23:12:55 +0100329 .. method:: assert_called_once_with(*args, **kwargs)
330
Arne de Laat324c5d82017-02-23 15:57:25 +0100331 Assert that the mock was called exactly once and that that call was
332 with the specified arguments.
Michael Foord944e02d2012-03-25 23:12:55 +0100333
334 >>> mock = Mock(return_value=None)
335 >>> mock('foo', bar='baz')
336 >>> mock.assert_called_once_with('foo', bar='baz')
Arne de Laat324c5d82017-02-23 15:57:25 +0100337 >>> mock('other', bar='values')
338 >>> mock.assert_called_once_with('other', bar='values')
Michael Foord944e02d2012-03-25 23:12:55 +0100339 Traceback (most recent call last):
340 ...
Michael Foord28d591c2012-09-28 16:15:22 +0100341 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foord944e02d2012-03-25 23:12:55 +0100342
343
344 .. method:: assert_any_call(*args, **kwargs)
345
346 assert the mock has been called with the specified arguments.
347
348 The assert passes if the mock has *ever* been called, unlike
349 :meth:`assert_called_with` and :meth:`assert_called_once_with` that
Arne de Laat324c5d82017-02-23 15:57:25 +0100350 only pass if the call is the most recent one, and in the case of
351 :meth:`assert_called_once_with` it must also be the only call.
Michael Foord944e02d2012-03-25 23:12:55 +0100352
353 >>> mock = Mock(return_value=None)
354 >>> mock(1, 2, arg='thing')
355 >>> mock('some', 'thing', 'else')
356 >>> mock.assert_any_call(1, 2, arg='thing')
357
358
359 .. method:: assert_has_calls(calls, any_order=False)
360
361 assert the mock has been called with the specified calls.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100362 The :attr:`mock_calls` list is checked for the calls.
Michael Foord944e02d2012-03-25 23:12:55 +0100363
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200364 If *any_order* is false then the calls must be
Michael Foord944e02d2012-03-25 23:12:55 +0100365 sequential. There can be extra calls before or after the
366 specified calls.
367
Georg Brandl7ad3df62014-10-31 07:59:37 +0100368 If *any_order* is true then the calls can be in any order, but
Michael Foord944e02d2012-03-25 23:12:55 +0100369 they must all appear in :attr:`mock_calls`.
370
371 >>> mock = Mock(return_value=None)
372 >>> mock(1)
373 >>> mock(2)
374 >>> mock(3)
375 >>> mock(4)
376 >>> calls = [call(2), call(3)]
377 >>> mock.assert_has_calls(calls)
378 >>> calls = [call(4), call(2), call(3)]
379 >>> mock.assert_has_calls(calls, any_order=True)
380
Berker Peksagebf9fd32016-07-17 15:26:46 +0300381 .. method:: assert_not_called()
Kushal Das8af9db32014-04-17 01:36:14 +0530382
383 Assert the mock was never called.
384
385 >>> m = Mock()
386 >>> m.hello.assert_not_called()
387 >>> obj = m.hello()
388 >>> m.hello.assert_not_called()
389 Traceback (most recent call last):
390 ...
391 AssertionError: Expected 'hello' to not have been called. Called 1 times.
392
393 .. versionadded:: 3.5
394
Michael Foord944e02d2012-03-25 23:12:55 +0100395
Kushal Das9cd39a12016-06-02 10:20:16 -0700396 .. method:: reset_mock(*, return_value=False, side_effect=False)
Michael Foord944e02d2012-03-25 23:12:55 +0100397
398 The reset_mock method resets all the call attributes on a mock object:
399
400 >>> mock = Mock(return_value=None)
401 >>> mock('hello')
402 >>> mock.called
403 True
404 >>> mock.reset_mock()
405 >>> mock.called
406 False
407
Kushal Das9cd39a12016-06-02 10:20:16 -0700408 .. versionchanged:: 3.6
409 Added two keyword only argument to the reset_mock function.
410
Michael Foord944e02d2012-03-25 23:12:55 +0100411 This can be useful where you want to make a series of assertions that
Georg Brandl7ad3df62014-10-31 07:59:37 +0100412 reuse the same object. Note that :meth:`reset_mock` *doesn't* clear the
Michael Foord944e02d2012-03-25 23:12:55 +0100413 return value, :attr:`side_effect` or any child attributes you have
Kushal Das9cd39a12016-06-02 10:20:16 -0700414 set using normal assignment by default. In case you want to reset
415 *return_value* or :attr:`side_effect`, then pass the corresponding
416 parameter as ``True``. Child mocks and the return value mock
Michael Foord944e02d2012-03-25 23:12:55 +0100417 (if any) are reset as well.
418
Kushal Das9cd39a12016-06-02 10:20:16 -0700419 .. note:: *return_value*, and :attr:`side_effect` are keyword only
420 argument.
421
Michael Foord944e02d2012-03-25 23:12:55 +0100422
423 .. method:: mock_add_spec(spec, spec_set=False)
424
Georg Brandl7ad3df62014-10-31 07:59:37 +0100425 Add a spec to a mock. *spec* can either be an object or a
426 list of strings. Only attributes on the *spec* can be fetched as
Michael Foord944e02d2012-03-25 23:12:55 +0100427 attributes from the mock.
428
Georg Brandl7ad3df62014-10-31 07:59:37 +0100429 If *spec_set* is true then only attributes on the spec can be set.
Michael Foord944e02d2012-03-25 23:12:55 +0100430
431
432 .. method:: attach_mock(mock, attribute)
433
434 Attach a mock as an attribute of this one, replacing its name and
435 parent. Calls to the attached mock will be recorded in the
436 :attr:`method_calls` and :attr:`mock_calls` attributes of this one.
437
438
439 .. method:: configure_mock(**kwargs)
440
441 Set attributes on the mock through keyword arguments.
442
443 Attributes plus return values and side effects can be set on child
444 mocks using standard dot notation and unpacking a dictionary in the
445 method call:
446
447 >>> mock = Mock()
448 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
449 >>> mock.configure_mock(**attrs)
450 >>> mock.method()
451 3
452 >>> mock.other()
453 Traceback (most recent call last):
454 ...
455 KeyError
456
457 The same thing can be achieved in the constructor call to mocks:
458
459 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
460 >>> mock = Mock(some_attribute='eggs', **attrs)
461 >>> mock.some_attribute
462 'eggs'
463 >>> mock.method()
464 3
465 >>> mock.other()
466 Traceback (most recent call last):
467 ...
468 KeyError
469
Georg Brandl7ad3df62014-10-31 07:59:37 +0100470 :meth:`configure_mock` exists to make it easier to do configuration
Michael Foord944e02d2012-03-25 23:12:55 +0100471 after the mock has been created.
472
473
474 .. method:: __dir__()
475
Georg Brandl7ad3df62014-10-31 07:59:37 +0100476 :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results.
477 For mocks with a *spec* this includes all the permitted attributes
Michael Foord944e02d2012-03-25 23:12:55 +0100478 for the mock.
479
480 See :data:`FILTER_DIR` for what this filtering does, and how to
481 switch it off.
482
483
484 .. method:: _get_child_mock(**kw)
485
486 Create the child mocks for attributes and return value.
487 By default child mocks will be the same type as the parent.
488 Subclasses of Mock may want to override this to customize the way
489 child mocks are made.
490
491 For non-callable mocks the callable variant will be used (rather than
492 any custom subclass).
493
494
495 .. attribute:: called
496
497 A boolean representing whether or not the mock object has been called:
498
499 >>> mock = Mock(return_value=None)
500 >>> mock.called
501 False
502 >>> mock()
503 >>> mock.called
504 True
505
506 .. attribute:: call_count
507
508 An integer telling you how many times the mock object has been called:
509
510 >>> mock = Mock(return_value=None)
511 >>> mock.call_count
512 0
513 >>> mock()
514 >>> mock()
515 >>> mock.call_count
516 2
517
Michael Foord944e02d2012-03-25 23:12:55 +0100518 .. attribute:: return_value
519
520 Set this to configure the value returned by calling the mock:
521
522 >>> mock = Mock()
523 >>> mock.return_value = 'fish'
524 >>> mock()
525 'fish'
526
527 The default return value is a mock object and you can configure it in
528 the normal way:
529
530 >>> mock = Mock()
531 >>> mock.return_value.attribute = sentinel.Attribute
532 >>> mock.return_value()
533 <Mock name='mock()()' id='...'>
534 >>> mock.return_value.assert_called_with()
535
Georg Brandl7ad3df62014-10-31 07:59:37 +0100536 :attr:`return_value` can also be set in the constructor:
Michael Foord944e02d2012-03-25 23:12:55 +0100537
538 >>> mock = Mock(return_value=3)
539 >>> mock.return_value
540 3
541 >>> mock()
542 3
543
544
545 .. attribute:: side_effect
546
547 This can either be a function to be called when the mock is called,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100548 an iterable or an exception (class or instance) to be raised.
Michael Foord944e02d2012-03-25 23:12:55 +0100549
550 If you pass in a function it will be called with same arguments as the
551 mock and unless the function returns the :data:`DEFAULT` singleton the
552 call to the mock will then return whatever the function returns. If the
553 function returns :data:`DEFAULT` then the mock will return its normal
Brett Cannon533f1ed2013-05-25 11:28:20 -0400554 value (from the :attr:`return_value`).
Michael Foord944e02d2012-03-25 23:12:55 +0100555
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100556 If you pass in an iterable, it is used to retrieve an iterator which
557 must yield a value on every call. This value can either be an exception
558 instance to be raised, or a value to be returned from the call to the
559 mock (:data:`DEFAULT` handling is identical to the function case).
560
Michael Foord944e02d2012-03-25 23:12:55 +0100561 An example of a mock that raises an exception (to test exception
562 handling of an API):
563
564 >>> mock = Mock()
565 >>> mock.side_effect = Exception('Boom!')
566 >>> mock()
567 Traceback (most recent call last):
568 ...
569 Exception: Boom!
570
Georg Brandl7ad3df62014-10-31 07:59:37 +0100571 Using :attr:`side_effect` to return a sequence of values:
Michael Foord944e02d2012-03-25 23:12:55 +0100572
573 >>> mock = Mock()
574 >>> mock.side_effect = [3, 2, 1]
575 >>> mock(), mock(), mock()
576 (3, 2, 1)
577
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100578 Using a callable:
Michael Foord944e02d2012-03-25 23:12:55 +0100579
580 >>> mock = Mock(return_value=3)
581 >>> def side_effect(*args, **kwargs):
582 ... return DEFAULT
583 ...
584 >>> mock.side_effect = side_effect
585 >>> mock()
586 3
587
Georg Brandl7ad3df62014-10-31 07:59:37 +0100588 :attr:`side_effect` can be set in the constructor. Here's an example that
Michael Foord944e02d2012-03-25 23:12:55 +0100589 adds one to the value the mock is called with and returns it:
590
591 >>> side_effect = lambda value: value + 1
592 >>> mock = Mock(side_effect=side_effect)
593 >>> mock(3)
594 4
595 >>> mock(-8)
596 -7
597
Georg Brandl7ad3df62014-10-31 07:59:37 +0100598 Setting :attr:`side_effect` to ``None`` clears it:
Michael Foord944e02d2012-03-25 23:12:55 +0100599
600 >>> m = Mock(side_effect=KeyError, return_value=3)
601 >>> m()
602 Traceback (most recent call last):
603 ...
604 KeyError
605 >>> m.side_effect = None
606 >>> m()
607 3
608
609
610 .. attribute:: call_args
611
Georg Brandl7ad3df62014-10-31 07:59:37 +0100612 This is either ``None`` (if the mock hasn't been called), or the
Michael Foord944e02d2012-03-25 23:12:55 +0100613 arguments that the mock was last called with. This will be in the
Kumar Akshayb0df45e2019-03-22 13:40:40 +0530614 form of a tuple: the first member, which can also be accessed through
615 the ``args`` property, is any ordered arguments the mock was
616 called with (or an empty tuple) and the second member, which can
617 also be accessed through the ``kwargs`` property, is any keyword
618 arguments (or an empty dictionary).
Michael Foord944e02d2012-03-25 23:12:55 +0100619
620 >>> mock = Mock(return_value=None)
Berker Peksag920f6db2015-09-10 21:41:15 +0300621 >>> print(mock.call_args)
Michael Foord944e02d2012-03-25 23:12:55 +0100622 None
623 >>> mock()
624 >>> mock.call_args
625 call()
626 >>> mock.call_args == ()
627 True
628 >>> mock(3, 4)
629 >>> mock.call_args
630 call(3, 4)
631 >>> mock.call_args == ((3, 4),)
632 True
Kumar Akshayb0df45e2019-03-22 13:40:40 +0530633 >>> mock.call_args.args
634 (3, 4)
635 >>> mock.call_args.kwargs
636 {}
Michael Foord944e02d2012-03-25 23:12:55 +0100637 >>> mock(3, 4, 5, key='fish', next='w00t!')
638 >>> mock.call_args
639 call(3, 4, 5, key='fish', next='w00t!')
Kumar Akshayb0df45e2019-03-22 13:40:40 +0530640 >>> mock.call_args.args
641 (3, 4, 5)
642 >>> mock.call_args.kwargs
643 {'key': 'fish', 'next': 'w00t!'}
Michael Foord944e02d2012-03-25 23:12:55 +0100644
Georg Brandl7ad3df62014-10-31 07:59:37 +0100645 :attr:`call_args`, along with members of the lists :attr:`call_args_list`,
Michael Foord944e02d2012-03-25 23:12:55 +0100646 :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects.
647 These are tuples, so they can be unpacked to get at the individual
648 arguments and make more complex assertions. See
649 :ref:`calls as tuples <calls-as-tuples>`.
650
Jordan Speicher9b01c592020-07-18 08:05:44 -0500651 .. versionchanged:: 3.8
652 Added ``args`` and ``kwargs`` properties.
653
Michael Foord944e02d2012-03-25 23:12:55 +0100654
655 .. attribute:: call_args_list
656
657 This is a list of all the calls made to the mock object in sequence
658 (so the length of the list is the number of times it has been
659 called). Before any calls have been made it is an empty list. The
660 :data:`call` object can be used for conveniently constructing lists of
Georg Brandl7ad3df62014-10-31 07:59:37 +0100661 calls to compare with :attr:`call_args_list`.
Michael Foord944e02d2012-03-25 23:12:55 +0100662
663 >>> mock = Mock(return_value=None)
664 >>> mock()
665 >>> mock(3, 4)
666 >>> mock(key='fish', next='w00t!')
667 >>> mock.call_args_list
668 [call(), call(3, 4), call(key='fish', next='w00t!')]
669 >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
670 >>> mock.call_args_list == expected
671 True
672
Georg Brandl7ad3df62014-10-31 07:59:37 +0100673 Members of :attr:`call_args_list` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100674 unpacked as tuples to get at the individual arguments. See
675 :ref:`calls as tuples <calls-as-tuples>`.
676
677
678 .. attribute:: method_calls
679
680 As well as tracking calls to themselves, mocks also track calls to
681 methods and attributes, and *their* methods and attributes:
682
683 >>> mock = Mock()
684 >>> mock.method()
685 <Mock name='mock.method()' id='...'>
686 >>> mock.property.method.attribute()
687 <Mock name='mock.property.method.attribute()' id='...'>
688 >>> mock.method_calls
689 [call.method(), call.property.method.attribute()]
690
Georg Brandl7ad3df62014-10-31 07:59:37 +0100691 Members of :attr:`method_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100692 unpacked as tuples to get at the individual arguments. See
693 :ref:`calls as tuples <calls-as-tuples>`.
694
695
696 .. attribute:: mock_calls
697
Georg Brandl7ad3df62014-10-31 07:59:37 +0100698 :attr:`mock_calls` records *all* calls to the mock object, its methods,
699 magic methods *and* return value mocks.
Michael Foord944e02d2012-03-25 23:12:55 +0100700
701 >>> mock = MagicMock()
702 >>> result = mock(1, 2, 3)
703 >>> mock.first(a=3)
704 <MagicMock name='mock.first()' id='...'>
705 >>> mock.second()
706 <MagicMock name='mock.second()' id='...'>
707 >>> int(mock)
708 1
709 >>> result(1)
710 <MagicMock name='mock()()' id='...'>
711 >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
712 ... call.__int__(), call()(1)]
713 >>> mock.mock_calls == expected
714 True
715
Georg Brandl7ad3df62014-10-31 07:59:37 +0100716 Members of :attr:`mock_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100717 unpacked as tuples to get at the individual arguments. See
718 :ref:`calls as tuples <calls-as-tuples>`.
719
Chris Withers8ca0fa92018-12-03 21:31:37 +0000720 .. note::
721
722 The way :attr:`mock_calls` are recorded means that where nested
723 calls are made, the parameters of ancestor calls are not recorded
724 and so will always compare equal:
725
726 >>> mock = MagicMock()
727 >>> mock.top(a=3).bottom()
728 <MagicMock name='mock.top().bottom()' id='...'>
729 >>> mock.mock_calls
730 [call.top(a=3), call.top().bottom()]
731 >>> mock.mock_calls[-1] == call.top(a=-1).bottom()
732 True
Michael Foord944e02d2012-03-25 23:12:55 +0100733
734 .. attribute:: __class__
735
Georg Brandl7ad3df62014-10-31 07:59:37 +0100736 Normally the :attr:`__class__` attribute of an object will return its type.
737 For a mock object with a :attr:`spec`, ``__class__`` returns the spec class
738 instead. This allows mock objects to pass :func:`isinstance` tests for the
Michael Foord944e02d2012-03-25 23:12:55 +0100739 object they are replacing / masquerading as:
740
741 >>> mock = Mock(spec=3)
742 >>> isinstance(mock, int)
743 True
744
Georg Brandl7ad3df62014-10-31 07:59:37 +0100745 :attr:`__class__` is assignable to, this allows a mock to pass an
746 :func:`isinstance` check without forcing you to use a spec:
Michael Foord944e02d2012-03-25 23:12:55 +0100747
748 >>> mock = Mock()
749 >>> mock.__class__ = dict
750 >>> isinstance(mock, dict)
751 True
752
753.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
754
Georg Brandl7ad3df62014-10-31 07:59:37 +0100755 A non-callable version of :class:`Mock`. The constructor parameters have the same
756 meaning of :class:`Mock`, with the exception of *return_value* and *side_effect*
Michael Foord944e02d2012-03-25 23:12:55 +0100757 which have no meaning on a non-callable mock.
758
Georg Brandl7ad3df62014-10-31 07:59:37 +0100759Mock objects that use a class or an instance as a :attr:`spec` or
760:attr:`spec_set` are able to pass :func:`isinstance` tests:
Michael Foord944e02d2012-03-25 23:12:55 +0100761
762 >>> mock = Mock(spec=SomeClass)
763 >>> isinstance(mock, SomeClass)
764 True
765 >>> mock = Mock(spec_set=SomeClass())
766 >>> isinstance(mock, SomeClass)
767 True
768
Georg Brandl7ad3df62014-10-31 07:59:37 +0100769The :class:`Mock` classes have support for mocking magic methods. See :ref:`magic
Michael Foord944e02d2012-03-25 23:12:55 +0100770methods <magic-methods>` for the full details.
771
772The mock classes and the :func:`patch` decorators all take arbitrary keyword
Georg Brandl7ad3df62014-10-31 07:59:37 +0100773arguments for configuration. For the :func:`patch` decorators the keywords are
Michael Foord944e02d2012-03-25 23:12:55 +0100774passed to the constructor of the mock being created. The keyword arguments
775are for configuring attributes of the mock:
776
777 >>> m = MagicMock(attribute=3, other='fish')
778 >>> m.attribute
779 3
780 >>> m.other
781 'fish'
782
783The return value and side effect of child mocks can be set in the same way,
784using dotted notation. As you can't use dotted names directly in a call you
Georg Brandl7ad3df62014-10-31 07:59:37 +0100785have to create a dictionary and unpack it using ``**``:
Michael Foord944e02d2012-03-25 23:12:55 +0100786
787 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
788 >>> mock = Mock(some_attribute='eggs', **attrs)
789 >>> mock.some_attribute
790 'eggs'
791 >>> mock.method()
792 3
793 >>> mock.other()
794 Traceback (most recent call last):
795 ...
796 KeyError
797
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100798A callable mock which was created with a *spec* (or a *spec_set*) will
799introspect the specification object's signature when matching calls to
800the mock. Therefore, it can match the actual call's arguments regardless
801of whether they were passed positionally or by name::
802
803 >>> def f(a, b, c): pass
804 ...
805 >>> mock = Mock(spec=f)
806 >>> mock(1, 2, c=3)
807 <Mock name='mock()' id='140161580456576'>
808 >>> mock.assert_called_with(1, 2, 3)
809 >>> mock.assert_called_with(a=1, b=2, c=3)
810
811This applies to :meth:`~Mock.assert_called_with`,
812:meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and
813:meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also
814apply to method calls on the mock object.
815
816 .. versionchanged:: 3.4
817 Added signature introspection on specced and autospecced mock objects.
818
Michael Foord944e02d2012-03-25 23:12:55 +0100819
820.. class:: PropertyMock(*args, **kwargs)
821
822 A mock intended to be used as a property, or other descriptor, on a class.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100823 :class:`PropertyMock` provides :meth:`__get__` and :meth:`__set__` methods
824 so you can specify a return value when it is fetched.
Michael Foord944e02d2012-03-25 23:12:55 +0100825
Georg Brandl7ad3df62014-10-31 07:59:37 +0100826 Fetching a :class:`PropertyMock` instance from an object calls the mock, with
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200827 no args. Setting it calls the mock with the value being set. ::
Michael Foord944e02d2012-03-25 23:12:55 +0100828
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200829 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100830 ... @property
831 ... def foo(self):
832 ... return 'something'
833 ... @foo.setter
834 ... def foo(self, value):
835 ... pass
836 ...
837 >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
838 ... mock_foo.return_value = 'mockity-mock'
839 ... this_foo = Foo()
Berker Peksag920f6db2015-09-10 21:41:15 +0300840 ... print(this_foo.foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100841 ... this_foo.foo = 6
842 ...
843 mockity-mock
844 >>> mock_foo.mock_calls
845 [call(), call(6)]
846
Michael Foordc2870622012-04-13 16:57:22 +0100847Because of the way mock attributes are stored you can't directly attach a
Georg Brandl7ad3df62014-10-31 07:59:37 +0100848:class:`PropertyMock` to a mock object. Instead you can attach it to the mock type
Michael Foordc2870622012-04-13 16:57:22 +0100849object::
850
851 >>> m = MagicMock()
852 >>> p = PropertyMock(return_value=3)
853 >>> type(m).foo = p
854 >>> m.foo
855 3
856 >>> p.assert_called_once_with()
857
Michael Foord944e02d2012-03-25 23:12:55 +0100858
Lisa Roach77b3b772019-05-20 09:19:53 -0700859.. class:: AsyncMock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs)
860
Elena Oatcf288b52020-01-15 01:50:57 -0800861 An asynchronous version of :class:`MagicMock`. The :class:`AsyncMock` object will
Lisa Roach77b3b772019-05-20 09:19:53 -0700862 behave so the object is recognized as an async function, and the result of a
863 call is an awaitable.
864
865 >>> mock = AsyncMock()
866 >>> asyncio.iscoroutinefunction(mock)
867 True
Xtreake7cb23b2019-05-21 14:17:17 +0530868 >>> inspect.isawaitable(mock()) # doctest: +SKIP
Lisa Roach77b3b772019-05-20 09:19:53 -0700869 True
870
871 The result of ``mock()`` is an async function which will have the outcome
Lisa Roach3667e1e2019-09-29 21:56:47 -0700872 of ``side_effect`` or ``return_value`` after it has been awaited:
Lisa Roach77b3b772019-05-20 09:19:53 -0700873
874 - if ``side_effect`` is a function, the async function will return the
875 result of that function,
876 - if ``side_effect`` is an exception, the async function will raise the
877 exception,
878 - if ``side_effect`` is an iterable, the async function will return the
879 next value of the iterable, however, if the sequence of result is
Jason Fried046442d2019-11-20 16:27:51 -0800880 exhausted, ``StopAsyncIteration`` is raised immediately,
Lisa Roach77b3b772019-05-20 09:19:53 -0700881 - if ``side_effect`` is not defined, the async function will return the
882 value defined by ``return_value``, hence, by default, the async function
883 returns a new :class:`AsyncMock` object.
884
885
886 Setting the *spec* of a :class:`Mock` or :class:`MagicMock` to an async function
887 will result in a coroutine object being returned after calling.
888
889 >>> async def async_func(): pass
890 ...
891 >>> mock = MagicMock(async_func)
892 >>> mock
893 <MagicMock spec='function' id='...'>
Xtreake7cb23b2019-05-21 14:17:17 +0530894 >>> mock() # doctest: +SKIP
Lisa Roach77b3b772019-05-20 09:19:53 -0700895 <coroutine object AsyncMockMixin._mock_call at ...>
896
Lisa Roach3667e1e2019-09-29 21:56:47 -0700897
898 Setting the *spec* of a :class:`Mock`, :class:`MagicMock`, or :class:`AsyncMock`
899 to a class with asynchronous and synchronous functions will automatically
900 detect the synchronous functions and set them as :class:`MagicMock` (if the
901 parent mock is :class:`AsyncMock` or :class:`MagicMock`) or :class:`Mock` (if
902 the parent mock is :class:`Mock`). All asynchronous functions will be
903 :class:`AsyncMock`.
904
905 >>> class ExampleClass:
906 ... def sync_foo():
907 ... pass
908 ... async def async_foo():
909 ... pass
910 ...
911 >>> a_mock = AsyncMock(ExampleClass)
912 >>> a_mock.sync_foo
913 <MagicMock name='mock.sync_foo' id='...'>
914 >>> a_mock.async_foo
915 <AsyncMock name='mock.async_foo' id='...'>
916 >>> mock = Mock(ExampleClass)
917 >>> mock.sync_foo
918 <Mock name='mock.sync_foo' id='...'>
919 >>> mock.async_foo
920 <AsyncMock name='mock.async_foo' id='...'>
921
John Belmonte279d8df2019-11-20 09:30:43 +0900922 .. versionadded:: 3.8
Lisa Roach3667e1e2019-09-29 21:56:47 -0700923
Lisa Roach77b3b772019-05-20 09:19:53 -0700924 .. method:: assert_awaited()
925
Lisa Roachef048512019-09-23 20:49:40 -0700926 Assert that the mock was awaited at least once. Note that this is separate
927 from the object having been called, the ``await`` keyword must be used:
Lisa Roach77b3b772019-05-20 09:19:53 -0700928
929 >>> mock = AsyncMock()
Lisa Roachef048512019-09-23 20:49:40 -0700930 >>> async def main(coroutine_mock):
931 ... await coroutine_mock
Lisa Roach77b3b772019-05-20 09:19:53 -0700932 ...
Lisa Roachef048512019-09-23 20:49:40 -0700933 >>> coroutine_mock = mock()
934 >>> mock.called
935 True
Lisa Roach77b3b772019-05-20 09:19:53 -0700936 >>> mock.assert_awaited()
Lisa Roach77b3b772019-05-20 09:19:53 -0700937 Traceback (most recent call last):
938 ...
939 AssertionError: Expected mock to have been awaited.
Lisa Roachef048512019-09-23 20:49:40 -0700940 >>> asyncio.run(main(coroutine_mock))
941 >>> mock.assert_awaited()
Lisa Roach77b3b772019-05-20 09:19:53 -0700942
943 .. method:: assert_awaited_once()
944
945 Assert that the mock was awaited exactly once.
946
947 >>> mock = AsyncMock()
948 >>> async def main():
949 ... await mock()
950 ...
951 >>> asyncio.run(main())
952 >>> mock.assert_awaited_once()
953 >>> asyncio.run(main())
954 >>> mock.method.assert_awaited_once()
955 Traceback (most recent call last):
956 ...
957 AssertionError: Expected mock to have been awaited once. Awaited 2 times.
958
959 .. method:: assert_awaited_with(*args, **kwargs)
960
961 Assert that the last await was with the specified arguments.
962
963 >>> mock = AsyncMock()
964 >>> async def main(*args, **kwargs):
965 ... await mock(*args, **kwargs)
966 ...
967 >>> asyncio.run(main('foo', bar='bar'))
968 >>> mock.assert_awaited_with('foo', bar='bar')
969 >>> mock.assert_awaited_with('other')
970 Traceback (most recent call last):
971 ...
972 AssertionError: expected call not found.
973 Expected: mock('other')
974 Actual: mock('foo', bar='bar')
975
976 .. method:: assert_awaited_once_with(*args, **kwargs)
977
978 Assert that the mock was awaited exactly once and with the specified
979 arguments.
980
981 >>> mock = AsyncMock()
982 >>> async def main(*args, **kwargs):
983 ... await mock(*args, **kwargs)
984 ...
985 >>> asyncio.run(main('foo', bar='bar'))
986 >>> mock.assert_awaited_once_with('foo', bar='bar')
987 >>> asyncio.run(main('foo', bar='bar'))
988 >>> mock.assert_awaited_once_with('foo', bar='bar')
989 Traceback (most recent call last):
990 ...
991 AssertionError: Expected mock to have been awaited once. Awaited 2 times.
992
993 .. method:: assert_any_await(*args, **kwargs)
994
995 Assert the mock has ever been awaited with the specified arguments.
996
997 >>> mock = AsyncMock()
998 >>> async def main(*args, **kwargs):
999 ... await mock(*args, **kwargs)
1000 ...
1001 >>> asyncio.run(main('foo', bar='bar'))
1002 >>> asyncio.run(main('hello'))
1003 >>> mock.assert_any_await('foo', bar='bar')
1004 >>> mock.assert_any_await('other')
1005 Traceback (most recent call last):
1006 ...
1007 AssertionError: mock('other') await not found
1008
1009 .. method:: assert_has_awaits(calls, any_order=False)
1010
1011 Assert the mock has been awaited with the specified calls.
1012 The :attr:`await_args_list` list is checked for the awaits.
1013
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +02001014 If *any_order* is false then the awaits must be
Lisa Roach77b3b772019-05-20 09:19:53 -07001015 sequential. There can be extra calls before or after the
1016 specified awaits.
1017
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +02001018 If *any_order* is true then the awaits can be in any order, but
Lisa Roach77b3b772019-05-20 09:19:53 -07001019 they must all appear in :attr:`await_args_list`.
1020
1021 >>> mock = AsyncMock()
1022 >>> async def main(*args, **kwargs):
1023 ... await mock(*args, **kwargs)
1024 ...
1025 >>> calls = [call("foo"), call("bar")]
Lisa Roachef048512019-09-23 20:49:40 -07001026 >>> mock.assert_has_awaits(calls)
Lisa Roach77b3b772019-05-20 09:19:53 -07001027 Traceback (most recent call last):
1028 ...
Lisa Roachef048512019-09-23 20:49:40 -07001029 AssertionError: Awaits not found.
Lisa Roach77b3b772019-05-20 09:19:53 -07001030 Expected: [call('foo'), call('bar')]
Lisa Roachef048512019-09-23 20:49:40 -07001031 Actual: []
Lisa Roach77b3b772019-05-20 09:19:53 -07001032 >>> asyncio.run(main('foo'))
1033 >>> asyncio.run(main('bar'))
Lisa Roachef048512019-09-23 20:49:40 -07001034 >>> mock.assert_has_awaits(calls)
Lisa Roach77b3b772019-05-20 09:19:53 -07001035
1036 .. method:: assert_not_awaited()
1037
1038 Assert that the mock was never awaited.
1039
1040 >>> mock = AsyncMock()
1041 >>> mock.assert_not_awaited()
1042
1043 .. method:: reset_mock(*args, **kwargs)
1044
1045 See :func:`Mock.reset_mock`. Also sets :attr:`await_count` to 0,
1046 :attr:`await_args` to None, and clears the :attr:`await_args_list`.
1047
1048 .. attribute:: await_count
1049
1050 An integer keeping track of how many times the mock object has been awaited.
1051
1052 >>> mock = AsyncMock()
1053 >>> async def main():
1054 ... await mock()
1055 ...
1056 >>> asyncio.run(main())
1057 >>> mock.await_count
1058 1
1059 >>> asyncio.run(main())
1060 >>> mock.await_count
1061 2
1062
1063 .. attribute:: await_args
1064
1065 This is either ``None`` (if the mock hasn’t been awaited), or the arguments that
1066 the mock was last awaited with. Functions the same as :attr:`Mock.call_args`.
1067
1068 >>> mock = AsyncMock()
1069 >>> async def main(*args):
1070 ... await mock(*args)
1071 ...
1072 >>> mock.await_args
1073 >>> asyncio.run(main('foo'))
1074 >>> mock.await_args
1075 call('foo')
1076 >>> asyncio.run(main('bar'))
1077 >>> mock.await_args
1078 call('bar')
1079
1080
1081 .. attribute:: await_args_list
1082
1083 This is a list of all the awaits made to the mock object in sequence (so the
1084 length of the list is the number of times it has been awaited). Before any
1085 awaits have been made it is an empty list.
1086
1087 >>> mock = AsyncMock()
1088 >>> async def main(*args):
1089 ... await mock(*args)
1090 ...
1091 >>> mock.await_args_list
1092 []
1093 >>> asyncio.run(main('foo'))
1094 >>> mock.await_args_list
1095 [call('foo')]
1096 >>> asyncio.run(main('bar'))
1097 >>> mock.await_args_list
1098 [call('foo'), call('bar')]
1099
1100
Michael Foord944e02d2012-03-25 23:12:55 +01001101Calling
1102~~~~~~~
1103
1104Mock objects are callable. The call will return the value set as the
1105:attr:`~Mock.return_value` attribute. The default return value is a new Mock
1106object; it is created the first time the return value is accessed (either
1107explicitly or by calling the Mock) - but it is stored and the same one
1108returned each time.
1109
1110Calls made to the object will be recorded in the attributes
1111like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
1112
1113If :attr:`~Mock.side_effect` is set then it will be called after the call has
Georg Brandl7ad3df62014-10-31 07:59:37 +01001114been recorded, so if :attr:`side_effect` raises an exception the call is still
Michael Foord944e02d2012-03-25 23:12:55 +01001115recorded.
1116
1117The simplest way to make a mock raise an exception when called is to make
1118:attr:`~Mock.side_effect` an exception class or instance:
1119
1120 >>> m = MagicMock(side_effect=IndexError)
1121 >>> m(1, 2, 3)
1122 Traceback (most recent call last):
1123 ...
1124 IndexError
1125 >>> m.mock_calls
1126 [call(1, 2, 3)]
1127 >>> m.side_effect = KeyError('Bang!')
1128 >>> m('two', 'three', 'four')
1129 Traceback (most recent call last):
1130 ...
1131 KeyError: 'Bang!'
1132 >>> m.mock_calls
1133 [call(1, 2, 3), call('two', 'three', 'four')]
1134
Georg Brandl7ad3df62014-10-31 07:59:37 +01001135If :attr:`side_effect` is a function then whatever that function returns is what
1136calls to the mock return. The :attr:`side_effect` function is called with the
Michael Foord944e02d2012-03-25 23:12:55 +01001137same arguments as the mock. This allows you to vary the return value of the
1138call dynamically, based on the input:
1139
1140 >>> def side_effect(value):
1141 ... return value + 1
1142 ...
1143 >>> m = MagicMock(side_effect=side_effect)
1144 >>> m(1)
1145 2
1146 >>> m(2)
1147 3
1148 >>> m.mock_calls
1149 [call(1), call(2)]
1150
1151If you want the mock to still return the default return value (a new mock), or
1152any set return value, then there are two ways of doing this. Either return
Georg Brandl7ad3df62014-10-31 07:59:37 +01001153:attr:`mock.return_value` from inside :attr:`side_effect`, or return :data:`DEFAULT`:
Michael Foord944e02d2012-03-25 23:12:55 +01001154
1155 >>> m = MagicMock()
1156 >>> def side_effect(*args, **kwargs):
1157 ... return m.return_value
1158 ...
1159 >>> m.side_effect = side_effect
1160 >>> m.return_value = 3
1161 >>> m()
1162 3
1163 >>> def side_effect(*args, **kwargs):
1164 ... return DEFAULT
1165 ...
1166 >>> m.side_effect = side_effect
1167 >>> m()
1168 3
1169
Georg Brandl7ad3df62014-10-31 07:59:37 +01001170To remove a :attr:`side_effect`, and return to the default behaviour, set the
1171:attr:`side_effect` to ``None``:
Michael Foord944e02d2012-03-25 23:12:55 +01001172
1173 >>> m = MagicMock(return_value=6)
1174 >>> def side_effect(*args, **kwargs):
1175 ... return 3
1176 ...
1177 >>> m.side_effect = side_effect
1178 >>> m()
1179 3
1180 >>> m.side_effect = None
1181 >>> m()
1182 6
1183
Georg Brandl7ad3df62014-10-31 07:59:37 +01001184The :attr:`side_effect` can also be any iterable object. Repeated calls to the mock
Michael Foord944e02d2012-03-25 23:12:55 +01001185will return values from the iterable (until the iterable is exhausted and
Georg Brandl7ad3df62014-10-31 07:59:37 +01001186a :exc:`StopIteration` is raised):
Michael Foord944e02d2012-03-25 23:12:55 +01001187
1188 >>> m = MagicMock(side_effect=[1, 2, 3])
1189 >>> m()
1190 1
1191 >>> m()
1192 2
1193 >>> m()
1194 3
1195 >>> m()
1196 Traceback (most recent call last):
1197 ...
1198 StopIteration
1199
Michael Foord2cd48732012-04-21 15:52:11 +01001200If any members of the iterable are exceptions they will be raised instead of
1201returned::
1202
1203 >>> iterable = (33, ValueError, 66)
1204 >>> m = MagicMock(side_effect=iterable)
1205 >>> m()
1206 33
1207 >>> m()
1208 Traceback (most recent call last):
1209 ...
1210 ValueError
1211 >>> m()
1212 66
1213
Michael Foord944e02d2012-03-25 23:12:55 +01001214
1215.. _deleting-attributes:
1216
1217Deleting Attributes
1218~~~~~~~~~~~~~~~~~~~
1219
1220Mock objects create attributes on demand. This allows them to pretend to be
1221objects of any type.
1222
Georg Brandl7ad3df62014-10-31 07:59:37 +01001223You may want a mock object to return ``False`` to a :func:`hasattr` call, or raise an
1224:exc:`AttributeError` when an attribute is fetched. You can do this by providing
1225an object as a :attr:`spec` for a mock, but that isn't always convenient.
Michael Foord944e02d2012-03-25 23:12:55 +01001226
1227You "block" attributes by deleting them. Once deleted, accessing an attribute
Georg Brandl7ad3df62014-10-31 07:59:37 +01001228will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +01001229
1230 >>> mock = MagicMock()
1231 >>> hasattr(mock, 'm')
1232 True
1233 >>> del mock.m
1234 >>> hasattr(mock, 'm')
1235 False
1236 >>> del mock.f
1237 >>> mock.f
1238 Traceback (most recent call last):
1239 ...
1240 AttributeError: f
1241
1242
Michael Foordf5752302013-03-18 15:04:03 -07001243Mock names and the name attribute
1244~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1245
1246Since "name" is an argument to the :class:`Mock` constructor, if you want your
1247mock object to have a "name" attribute you can't just pass it in at creation
1248time. There are two alternatives. One option is to use
1249:meth:`~Mock.configure_mock`::
1250
1251 >>> mock = MagicMock()
1252 >>> mock.configure_mock(name='my_name')
1253 >>> mock.name
1254 'my_name'
1255
1256A simpler option is to simply set the "name" attribute after mock creation::
1257
1258 >>> mock = MagicMock()
1259 >>> mock.name = "foo"
1260
1261
Michael Foord944e02d2012-03-25 23:12:55 +01001262Attaching Mocks as Attributes
1263~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1264
1265When you attach a mock as an attribute of another mock (or as the return
1266value) it becomes a "child" of that mock. Calls to the child are recorded in
1267the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
1268parent. This is useful for configuring child mocks and then attaching them to
1269the parent, or for attaching mocks to a parent that records all calls to the
1270children and allows you to make assertions about the order of calls between
1271mocks:
1272
1273 >>> parent = MagicMock()
1274 >>> child1 = MagicMock(return_value=None)
1275 >>> child2 = MagicMock(return_value=None)
1276 >>> parent.child1 = child1
1277 >>> parent.child2 = child2
1278 >>> child1(1)
1279 >>> child2(2)
1280 >>> parent.mock_calls
1281 [call.child1(1), call.child2(2)]
1282
1283The exception to this is if the mock has a name. This allows you to prevent
1284the "parenting" if for some reason you don't want it to happen.
1285
1286 >>> mock = MagicMock()
1287 >>> not_a_child = MagicMock(name='not-a-child')
1288 >>> mock.attribute = not_a_child
1289 >>> mock.attribute()
1290 <MagicMock name='not-a-child()' id='...'>
1291 >>> mock.mock_calls
1292 []
1293
1294Mocks created for you by :func:`patch` are automatically given names. To
1295attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001296method::
Michael Foord944e02d2012-03-25 23:12:55 +01001297
1298 >>> thing1 = object()
1299 >>> thing2 = object()
1300 >>> parent = MagicMock()
1301 >>> with patch('__main__.thing1', return_value=None) as child1:
1302 ... with patch('__main__.thing2', return_value=None) as child2:
1303 ... parent.attach_mock(child1, 'child1')
1304 ... parent.attach_mock(child2, 'child2')
1305 ... child1('one')
1306 ... child2('two')
1307 ...
1308 >>> parent.mock_calls
1309 [call.child1('one'), call.child2('two')]
1310
1311
1312.. [#] The only exceptions are magic methods and attributes (those that have
1313 leading and trailing double underscores). Mock doesn't create these but
Georg Brandl7ad3df62014-10-31 07:59:37 +01001314 instead raises an :exc:`AttributeError`. This is because the interpreter
Michael Foord944e02d2012-03-25 23:12:55 +01001315 will often implicitly request these methods, and gets *very* confused to
1316 get a new Mock object when it expects a magic method. If you need magic
1317 method support see :ref:`magic methods <magic-methods>`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001318
1319
1320The patchers
Georg Brandlfb134382013-02-03 11:47:49 +01001321------------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001322
1323The patch decorators are used for patching objects only within the scope of
1324the function they decorate. They automatically handle the unpatching for you,
1325even if exceptions are raised. All of these functions can also be used in with
1326statements or as class decorators.
1327
1328
1329patch
Georg Brandlfb134382013-02-03 11:47:49 +01001330~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001331
1332.. note::
1333
Brian Curtine00c1d02020-02-10 10:47:17 -07001334 The key is to do the patching in the right namespace. See the section `where to patch`_.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001335
1336.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1337
Georg Brandl7ad3df62014-10-31 07:59:37 +01001338 :func:`patch` acts as a function decorator, class decorator or a context
1339 manager. Inside the body of the function or with statement, the *target*
1340 is patched with a *new* object. When the function/with statement exits
Michael Foord54b3db82012-03-28 15:08:08 +01001341 the patch is undone.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001342
Mario Corcherof5e7f392019-09-09 15:18:06 +01001343 If *new* is omitted, then the target is replaced with an
1344 :class:`AsyncMock` if the patched object is an async function or
1345 a :class:`MagicMock` otherwise.
1346 If :func:`patch` is used as a decorator and *new* is
Michael Foord54b3db82012-03-28 15:08:08 +01001347 omitted, the created mock is passed in as an extra argument to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001348 decorated function. If :func:`patch` is used as a context manager the created
Michael Foord54b3db82012-03-28 15:08:08 +01001349 mock is returned by the context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001350
Georg Brandl7ad3df62014-10-31 07:59:37 +01001351 *target* should be a string in the form ``'package.module.ClassName'``. The
1352 *target* is imported and the specified object replaced with the *new*
1353 object, so the *target* must be importable from the environment you are
1354 calling :func:`patch` from. The target is imported when the decorated function
Michael Foord54b3db82012-03-28 15:08:08 +01001355 is executed, not at decoration time.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001356
Georg Brandl7ad3df62014-10-31 07:59:37 +01001357 The *spec* and *spec_set* keyword arguments are passed to the :class:`MagicMock`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001358 if patch is creating one for you.
1359
Georg Brandl7ad3df62014-10-31 07:59:37 +01001360 In addition you can pass ``spec=True`` or ``spec_set=True``, which causes
Michael Foorda9e6fb22012-03-28 14:36:02 +01001361 patch to pass in the object being mocked as the spec/spec_set object.
1362
Georg Brandl7ad3df62014-10-31 07:59:37 +01001363 *new_callable* allows you to specify a different class, or callable object,
Mario Corcherof5e7f392019-09-09 15:18:06 +01001364 that will be called to create the *new* object. By default :class:`AsyncMock`
1365 is used for async functions and :class:`MagicMock` for the rest.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001366
Georg Brandl7ad3df62014-10-31 07:59:37 +01001367 A more powerful form of *spec* is *autospec*. If you set ``autospec=True``
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001368 then the mock will be created with a spec from the object being replaced.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001369 All attributes of the mock will also have the spec of the corresponding
1370 attribute of the object being replaced. Methods and functions being mocked
Georg Brandl7ad3df62014-10-31 07:59:37 +01001371 will have their arguments checked and will raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001372 called with the wrong signature. For mocks
1373 replacing a class, their return value (the 'instance') will have the same
1374 spec as the class. See the :func:`create_autospec` function and
1375 :ref:`auto-speccing`.
1376
Georg Brandl7ad3df62014-10-31 07:59:37 +01001377 Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001378 arbitrary object as the spec instead of the one being replaced.
1379
Pablo Galindod6acf172019-01-09 21:43:24 +00001380 By default :func:`patch` will fail to replace attributes that don't exist.
1381 If you pass in ``create=True``, and the attribute doesn't exist, patch will
1382 create the attribute for you when the patched function is called, and delete
1383 it again after the patched function has exited. This is useful for writing
1384 tests against attributes that your production code creates at runtime. It is
1385 off by default because it can be dangerous. With it switched on you can
1386 write passing tests against APIs that don't actually exist!
Michael Foorda9e6fb22012-03-28 14:36:02 +01001387
Michael Foordfddcfa22014-04-14 16:25:20 -04001388 .. note::
1389
1390 .. versionchanged:: 3.5
1391 If you are patching builtins in a module then you don't
Georg Brandl7ad3df62014-10-31 07:59:37 +01001392 need to pass ``create=True``, it will be added by default.
Michael Foordfddcfa22014-04-14 16:25:20 -04001393
Georg Brandl7ad3df62014-10-31 07:59:37 +01001394 Patch can be used as a :class:`TestCase` class decorator. It works by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001395 decorating each test method in the class. This reduces the boilerplate
Georg Brandl7ad3df62014-10-31 07:59:37 +01001396 code when your test methods share a common patchings set. :func:`patch` finds
1397 tests by looking for method names that start with ``patch.TEST_PREFIX``.
1398 By default this is ``'test'``, which matches the way :mod:`unittest` finds tests.
1399 You can specify an alternative prefix by setting ``patch.TEST_PREFIX``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001400
1401 Patch can be used as a context manager, with the with statement. Here the
1402 patching applies to the indented block after the with statement. If you
1403 use "as" then the patched object will be bound to the name after the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001404 "as"; very useful if :func:`patch` is creating a mock object for you.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001405
Georg Brandl7ad3df62014-10-31 07:59:37 +01001406 :func:`patch` takes arbitrary keyword arguments. These will be passed to
Paulo Henrique Silva40c08092020-01-25 07:53:54 -03001407 :class:`AsyncMock` if the patched object is asynchronous, to
1408 :class:`MagicMock` otherwise or to *new_callable* if specified.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001409
Georg Brandl7ad3df62014-10-31 07:59:37 +01001410 ``patch.dict(...)``, ``patch.multiple(...)`` and ``patch.object(...)`` are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001411 available for alternate use-cases.
1412
Georg Brandl7ad3df62014-10-31 07:59:37 +01001413:func:`patch` as function decorator, creating the mock for you and passing it into
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001414the decorated function::
Michael Foord90155362012-03-28 15:32:08 +01001415
1416 >>> @patch('__main__.SomeClass')
Michael Foord324b58b2012-03-28 15:49:08 +01001417 ... def function(normal_argument, mock_class):
Michael Foord90155362012-03-28 15:32:08 +01001418 ... print(mock_class is SomeClass)
1419 ...
Michael Foord324b58b2012-03-28 15:49:08 +01001420 >>> function(None)
Michael Foord90155362012-03-28 15:32:08 +01001421 True
Michael Foorda9e6fb22012-03-28 14:36:02 +01001422
Georg Brandl7ad3df62014-10-31 07:59:37 +01001423Patching a class replaces the class with a :class:`MagicMock` *instance*. If the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001424class is instantiated in the code under test then it will be the
1425:attr:`~Mock.return_value` of the mock that will be used.
1426
1427If the class is instantiated multiple times you could use
1428:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
Georg Brandl7ad3df62014-10-31 07:59:37 +01001429can set the *return_value* to be anything you want.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001430
1431To configure return values on methods of *instances* on the patched class
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001432you must do this on the :attr:`return_value`. For example::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001433
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001434 >>> class Class:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001435 ... def method(self):
1436 ... pass
1437 ...
1438 >>> with patch('__main__.Class') as MockClass:
1439 ... instance = MockClass.return_value
1440 ... instance.method.return_value = 'foo'
1441 ... assert Class() is instance
1442 ... assert Class().method() == 'foo'
1443 ...
1444
Georg Brandl7ad3df62014-10-31 07:59:37 +01001445If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001446return value of the created mock will have the same spec. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001447
1448 >>> Original = Class
1449 >>> patcher = patch('__main__.Class', spec=True)
1450 >>> MockClass = patcher.start()
1451 >>> instance = MockClass()
1452 >>> assert isinstance(instance, Original)
1453 >>> patcher.stop()
1454
Georg Brandl7ad3df62014-10-31 07:59:37 +01001455The *new_callable* argument is useful where you want to use an alternative
Michael Foorda9e6fb22012-03-28 14:36:02 +01001456class to the default :class:`MagicMock` for the created mock. For example, if
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001457you wanted a :class:`NonCallableMock` to be used::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001458
1459 >>> thing = object()
1460 >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
1461 ... assert thing is mock_thing
1462 ... thing()
1463 ...
1464 Traceback (most recent call last):
1465 ...
1466 TypeError: 'NonCallableMock' object is not callable
1467
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001468Another use case might be to replace an object with an :class:`io.StringIO` instance::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001469
Serhiy Storchakae79be872013-08-17 00:09:55 +03001470 >>> from io import StringIO
Michael Foorda9e6fb22012-03-28 14:36:02 +01001471 >>> def foo():
Berker Peksag920f6db2015-09-10 21:41:15 +03001472 ... print('Something')
Michael Foorda9e6fb22012-03-28 14:36:02 +01001473 ...
1474 >>> @patch('sys.stdout', new_callable=StringIO)
1475 ... def test(mock_stdout):
1476 ... foo()
1477 ... assert mock_stdout.getvalue() == 'Something\n'
1478 ...
1479 >>> test()
1480
Georg Brandl7ad3df62014-10-31 07:59:37 +01001481When :func:`patch` is creating a mock for you, it is common that the first thing
Michael Foorda9e6fb22012-03-28 14:36:02 +01001482you need to do is to configure the mock. Some of that configuration can be done
1483in the call to patch. Any arbitrary keywords you pass into the call will be
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001484used to set attributes on the created mock::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001485
1486 >>> patcher = patch('__main__.thing', first='one', second='two')
1487 >>> mock_thing = patcher.start()
1488 >>> mock_thing.first
1489 'one'
1490 >>> mock_thing.second
1491 'two'
1492
1493As well as attributes on the created mock attributes, like the
1494:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
1495also be configured. These aren't syntactically valid to pass in directly as
1496keyword arguments, but a dictionary with these as keys can still be expanded
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001497into a :func:`patch` call using ``**``::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001498
1499 >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
1500 >>> patcher = patch('__main__.thing', **config)
1501 >>> mock_thing = patcher.start()
1502 >>> mock_thing.method()
1503 3
1504 >>> mock_thing.other()
1505 Traceback (most recent call last):
1506 ...
1507 KeyError
1508
Pablo Galindod6acf172019-01-09 21:43:24 +00001509By default, attempting to patch a function in a module (or a method or an
1510attribute in a class) that does not exist will fail with :exc:`AttributeError`::
1511
1512 >>> @patch('sys.non_existing_attribute', 42)
1513 ... def test():
1514 ... assert sys.non_existing_attribute == 42
1515 ...
1516 >>> test()
1517 Traceback (most recent call last):
1518 ...
1519 AttributeError: <module 'sys' (built-in)> does not have the attribute 'non_existing'
1520
1521but adding ``create=True`` in the call to :func:`patch` will make the previous example
1522work as expected::
1523
1524 >>> @patch('sys.non_existing_attribute', 42, create=True)
1525 ... def test(mock_stdout):
1526 ... assert sys.non_existing_attribute == 42
1527 ...
1528 >>> test()
1529
Mario Corcherof5e7f392019-09-09 15:18:06 +01001530.. versionchanged:: 3.8
1531
1532 :func:`patch` now returns an :class:`AsyncMock` if the target is an async function.
1533
Michael Foorda9e6fb22012-03-28 14:36:02 +01001534
1535patch.object
Georg Brandlfb134382013-02-03 11:47:49 +01001536~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001537
1538.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1539
Georg Brandl7ad3df62014-10-31 07:59:37 +01001540 patch the named member (*attribute*) on an object (*target*) with a mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001541 object.
1542
Georg Brandl7ad3df62014-10-31 07:59:37 +01001543 :func:`patch.object` can be used as a decorator, class decorator or a context
1544 manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* and
1545 *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`,
1546 :func:`patch.object` takes arbitrary keyword arguments for configuring the mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001547 object it creates.
1548
Georg Brandl7ad3df62014-10-31 07:59:37 +01001549 When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001550 for choosing which methods to wrap.
1551
Georg Brandl7ad3df62014-10-31 07:59:37 +01001552You can either call :func:`patch.object` with three arguments or two arguments. The
Michael Foorda9e6fb22012-03-28 14:36:02 +01001553three argument form takes the object to be patched, the attribute name and the
1554object to replace the attribute with.
1555
1556When calling with the two argument form you omit the replacement object, and a
1557mock is created for you and passed in as an extra argument to the decorated
1558function:
1559
1560 >>> @patch.object(SomeClass, 'class_method')
1561 ... def test(mock_method):
1562 ... SomeClass.class_method(3)
1563 ... mock_method.assert_called_with(3)
1564 ...
1565 >>> test()
1566
Georg Brandl7ad3df62014-10-31 07:59:37 +01001567*spec*, *create* and the other arguments to :func:`patch.object` have the same
1568meaning as they do for :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001569
1570
1571patch.dict
Georg Brandlfb134382013-02-03 11:47:49 +01001572~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001573
1574.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs)
1575
1576 Patch a dictionary, or dictionary like object, and restore the dictionary
1577 to its original state after the test.
1578
Georg Brandl7ad3df62014-10-31 07:59:37 +01001579 *in_dict* can be a dictionary or a mapping like container. If it is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01001580 mapping then it must at least support getting, setting and deleting items
1581 plus iterating over keys.
1582
Georg Brandl7ad3df62014-10-31 07:59:37 +01001583 *in_dict* can also be a string specifying the name of the dictionary, which
Michael Foorda9e6fb22012-03-28 14:36:02 +01001584 will then be fetched by importing it.
1585
Georg Brandl7ad3df62014-10-31 07:59:37 +01001586 *values* can be a dictionary of values to set in the dictionary. *values*
1587 can also be an iterable of ``(key, value)`` pairs.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001588
Georg Brandl7ad3df62014-10-31 07:59:37 +01001589 If *clear* is true then the dictionary will be cleared before the new
Michael Foorda9e6fb22012-03-28 14:36:02 +01001590 values are set.
1591
Georg Brandl7ad3df62014-10-31 07:59:37 +01001592 :func:`patch.dict` can also be called with arbitrary keyword arguments to set
Michael Foorda9e6fb22012-03-28 14:36:02 +01001593 values in the dictionary.
1594
Mario Corchero04530812019-05-28 13:53:31 +01001595 .. versionchanged:: 3.8
1596
1597 :func:`patch.dict` now returns the patched dictionary when used as a context
1598 manager.
1599
Emmanuel Arias31a82e22019-09-12 08:29:54 -03001600:func:`patch.dict` can be used as a context manager, decorator or class
1601decorator:
1602
1603 >>> foo = {}
1604 >>> @patch.dict(foo, {'newkey': 'newvalue'})
1605 ... def test():
1606 ... assert foo == {'newkey': 'newvalue'}
1607 >>> test()
1608 >>> assert foo == {}
1609
1610When used as a class decorator :func:`patch.dict` honours
1611``patch.TEST_PREFIX`` (default to ``'test'``) for choosing which methods to wrap:
1612
1613 >>> import os
1614 >>> import unittest
1615 >>> from unittest.mock import patch
1616 >>> @patch.dict('os.environ', {'newkey': 'newvalue'})
1617 ... class TestSample(unittest.TestCase):
1618 ... def test_sample(self):
1619 ... self.assertEqual(os.environ['newkey'], 'newvalue')
1620
1621If you want to use a different prefix for your test, you can inform the
1622patchers of the different prefix by setting ``patch.TEST_PREFIX``. For
1623more details about how to change the value of see :ref:`test-prefix`.
1624
Georg Brandl7ad3df62014-10-31 07:59:37 +01001625:func:`patch.dict` can be used to add members to a dictionary, or simply let a test
Michael Foorda9e6fb22012-03-28 14:36:02 +01001626change a dictionary, and ensure the dictionary is restored when the test
1627ends.
1628
1629 >>> foo = {}
Mario Corchero04530812019-05-28 13:53:31 +01001630 >>> with patch.dict(foo, {'newkey': 'newvalue'}) as patched_foo:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001631 ... assert foo == {'newkey': 'newvalue'}
Mario Corchero04530812019-05-28 13:53:31 +01001632 ... assert patched_foo == {'newkey': 'newvalue'}
1633 ... # You can add, update or delete keys of foo (or patched_foo, it's the same dict)
1634 ... patched_foo['spam'] = 'eggs'
Michael Foorda9e6fb22012-03-28 14:36:02 +01001635 ...
1636 >>> assert foo == {}
Mario Corchero04530812019-05-28 13:53:31 +01001637 >>> assert patched_foo == {}
Michael Foorda9e6fb22012-03-28 14:36:02 +01001638
1639 >>> import os
1640 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
Berker Peksag920f6db2015-09-10 21:41:15 +03001641 ... print(os.environ['newkey'])
Michael Foorda9e6fb22012-03-28 14:36:02 +01001642 ...
1643 newvalue
1644 >>> assert 'newkey' not in os.environ
1645
Georg Brandl7ad3df62014-10-31 07:59:37 +01001646Keywords can be used in the :func:`patch.dict` call to set values in the dictionary:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001647
1648 >>> mymodule = MagicMock()
1649 >>> mymodule.function.return_value = 'fish'
1650 >>> with patch.dict('sys.modules', mymodule=mymodule):
1651 ... import mymodule
1652 ... mymodule.function('some', 'args')
1653 ...
1654 'fish'
1655
Georg Brandl7ad3df62014-10-31 07:59:37 +01001656:func:`patch.dict` can be used with dictionary like objects that aren't actually
Michael Foorda9e6fb22012-03-28 14:36:02 +01001657dictionaries. At the very minimum they must support item getting, setting,
1658deleting and either iteration or membership test. This corresponds to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001659magic methods :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__` and either
1660:meth:`__iter__` or :meth:`__contains__`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001661
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001662 >>> class Container:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001663 ... def __init__(self):
1664 ... self.values = {}
1665 ... def __getitem__(self, name):
1666 ... return self.values[name]
1667 ... def __setitem__(self, name, value):
1668 ... self.values[name] = value
1669 ... def __delitem__(self, name):
1670 ... del self.values[name]
1671 ... def __iter__(self):
1672 ... return iter(self.values)
1673 ...
1674 >>> thing = Container()
1675 >>> thing['one'] = 1
1676 >>> with patch.dict(thing, one=2, two=3):
1677 ... assert thing['one'] == 2
1678 ... assert thing['two'] == 3
1679 ...
1680 >>> assert thing['one'] == 1
1681 >>> assert list(thing) == ['one']
1682
1683
1684patch.multiple
Georg Brandlfb134382013-02-03 11:47:49 +01001685~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001686
1687.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1688
1689 Perform multiple patches in a single call. It takes the object to be
1690 patched (either as an object or a string to fetch the object by importing)
1691 and keyword arguments for the patches::
1692
1693 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1694 ...
1695
Georg Brandl7ad3df62014-10-31 07:59:37 +01001696 Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create
Michael Foorda9e6fb22012-03-28 14:36:02 +01001697 mocks for you. In this case the created mocks are passed into a decorated
Georg Brandl7ad3df62014-10-31 07:59:37 +01001698 function by keyword, and a dictionary is returned when :func:`patch.multiple` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001699 used as a context manager.
1700
Georg Brandl7ad3df62014-10-31 07:59:37 +01001701 :func:`patch.multiple` can be used as a decorator, class decorator or a context
1702 manager. The arguments *spec*, *spec_set*, *create*, *autospec* and
1703 *new_callable* have the same meaning as for :func:`patch`. These arguments will
1704 be applied to *all* patches done by :func:`patch.multiple`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001705
Georg Brandl7ad3df62014-10-31 07:59:37 +01001706 When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001707 for choosing which methods to wrap.
1708
Georg Brandl7ad3df62014-10-31 07:59:37 +01001709If you want :func:`patch.multiple` to create mocks for you, then you can use
1710:data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001711then the created mocks are passed into the decorated function by keyword. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001712
1713 >>> thing = object()
1714 >>> other = object()
1715
1716 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1717 ... def test_function(thing, other):
1718 ... assert isinstance(thing, MagicMock)
1719 ... assert isinstance(other, MagicMock)
1720 ...
1721 >>> test_function()
1722
Georg Brandl7ad3df62014-10-31 07:59:37 +01001723:func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001724passed by keyword *after* any of the standard arguments created by :func:`patch`::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001725
1726 >>> @patch('sys.exit')
1727 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1728 ... def test_function(mock_exit, other, thing):
1729 ... assert 'other' in repr(other)
1730 ... assert 'thing' in repr(thing)
1731 ... assert 'exit' in repr(mock_exit)
1732 ...
1733 >>> test_function()
1734
Georg Brandl7ad3df62014-10-31 07:59:37 +01001735If :func:`patch.multiple` is used as a context manager, the value returned by the
Joan Massichdc69f692019-03-18 00:34:22 +01001736context manager is a dictionary where created mocks are keyed by name::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001737
1738 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
1739 ... assert 'other' in repr(values['other'])
1740 ... assert 'thing' in repr(values['thing'])
1741 ... assert values['thing'] is thing
1742 ... assert values['other'] is other
1743 ...
1744
1745
1746.. _start-and-stop:
1747
1748patch methods: start and stop
Georg Brandlfb134382013-02-03 11:47:49 +01001749~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001750
Georg Brandl7ad3df62014-10-31 07:59:37 +01001751All the patchers have :meth:`start` and :meth:`stop` methods. These make it simpler to do
1752patching in ``setUp`` methods or where you want to do multiple patches without
Michael Foorda9e6fb22012-03-28 14:36:02 +01001753nesting decorators or with statements.
1754
Georg Brandl7ad3df62014-10-31 07:59:37 +01001755To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as
1756normal and keep a reference to the returned ``patcher`` object. You can then
1757call :meth:`start` to put the patch in place and :meth:`stop` to undo it.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001758
Georg Brandl7ad3df62014-10-31 07:59:37 +01001759If you are using :func:`patch` to create a mock for you then it will be returned by
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001760the call to ``patcher.start``. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001761
1762 >>> patcher = patch('package.module.ClassName')
1763 >>> from package import module
1764 >>> original = module.ClassName
1765 >>> new_mock = patcher.start()
1766 >>> assert module.ClassName is not original
1767 >>> assert module.ClassName is new_mock
1768 >>> patcher.stop()
1769 >>> assert module.ClassName is original
1770 >>> assert module.ClassName is not new_mock
1771
1772
Georg Brandl7ad3df62014-10-31 07:59:37 +01001773A typical use case for this might be for doing multiple patches in the ``setUp``
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001774method of a :class:`TestCase`::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001775
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001776 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +01001777 ... def setUp(self):
1778 ... self.patcher1 = patch('package.module.Class1')
1779 ... self.patcher2 = patch('package.module.Class2')
1780 ... self.MockClass1 = self.patcher1.start()
1781 ... self.MockClass2 = self.patcher2.start()
1782 ...
1783 ... def tearDown(self):
1784 ... self.patcher1.stop()
1785 ... self.patcher2.stop()
1786 ...
1787 ... def test_something(self):
1788 ... assert package.module.Class1 is self.MockClass1
1789 ... assert package.module.Class2 is self.MockClass2
1790 ...
1791 >>> MyTest('test_something').run()
1792
1793.. caution::
1794
1795 If you use this technique you must ensure that the patching is "undone" by
Georg Brandl7ad3df62014-10-31 07:59:37 +01001796 calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001797 exception is raised in the ``setUp`` then ``tearDown`` is not called.
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001798 :meth:`unittest.TestCase.addCleanup` makes this easier::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001799
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001800 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +01001801 ... def setUp(self):
1802 ... patcher = patch('package.module.Class')
1803 ... self.MockClass = patcher.start()
1804 ... self.addCleanup(patcher.stop)
1805 ...
1806 ... def test_something(self):
1807 ... assert package.module.Class is self.MockClass
1808 ...
1809
Georg Brandl7ad3df62014-10-31 07:59:37 +01001810 As an added bonus you no longer need to keep a reference to the ``patcher``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001811 object.
1812
Michael Foordf7c41582012-06-10 20:36:32 +01001813It is also possible to stop all patches which have been started by using
Georg Brandl7ad3df62014-10-31 07:59:37 +01001814:func:`patch.stopall`.
Michael Foordf7c41582012-06-10 20:36:32 +01001815
1816.. function:: patch.stopall
1817
Georg Brandl7ad3df62014-10-31 07:59:37 +01001818 Stop all active patches. Only stops patches started with ``start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001819
Georg Brandl7ad3df62014-10-31 07:59:37 +01001820
1821.. _patch-builtins:
Michael Foordfddcfa22014-04-14 16:25:20 -04001822
1823patch builtins
Georg Brandl7ad3df62014-10-31 07:59:37 +01001824~~~~~~~~~~~~~~
Michael Foordfddcfa22014-04-14 16:25:20 -04001825You can patch any builtins within a module. The following example patches
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001826builtin :func:`ord`::
Michael Foordfddcfa22014-04-14 16:25:20 -04001827
1828 >>> @patch('__main__.ord')
1829 ... def test(mock_ord):
1830 ... mock_ord.return_value = 101
1831 ... print(ord('c'))
1832 ...
1833 >>> test()
1834 101
1835
Michael Foorda9e6fb22012-03-28 14:36:02 +01001836
Emmanuel Arias31a82e22019-09-12 08:29:54 -03001837.. _test-prefix:
1838
Michael Foorda9e6fb22012-03-28 14:36:02 +01001839TEST_PREFIX
Georg Brandlfb134382013-02-03 11:47:49 +01001840~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001841
1842All of the patchers can be used as class decorators. When used in this way
1843they wrap every test method on the class. The patchers recognise methods that
Georg Brandl7ad3df62014-10-31 07:59:37 +01001844start with ``'test'`` as being test methods. This is the same way that the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001845:class:`unittest.TestLoader` finds test methods by default.
1846
1847It is possible that you want to use a different prefix for your tests. You can
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001848inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001849
1850 >>> patch.TEST_PREFIX = 'foo'
1851 >>> value = 3
1852 >>>
1853 >>> @patch('__main__.value', 'not three')
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001854 ... class Thing:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001855 ... def foo_one(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001856 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001857 ... def foo_two(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001858 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001859 ...
1860 >>>
1861 >>> Thing().foo_one()
1862 not three
1863 >>> Thing().foo_two()
1864 not three
1865 >>> value
1866 3
1867
1868
1869Nesting Patch Decorators
Georg Brandlfb134382013-02-03 11:47:49 +01001870~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001871
1872If you want to perform multiple patches then you can simply stack up the
1873decorators.
1874
1875You can stack up multiple patch decorators using this pattern:
1876
1877 >>> @patch.object(SomeClass, 'class_method')
1878 ... @patch.object(SomeClass, 'static_method')
1879 ... def test(mock1, mock2):
1880 ... assert SomeClass.static_method is mock1
1881 ... assert SomeClass.class_method is mock2
1882 ... SomeClass.static_method('foo')
1883 ... SomeClass.class_method('bar')
1884 ... return mock1, mock2
1885 ...
1886 >>> mock1, mock2 = test()
1887 >>> mock1.assert_called_once_with('foo')
1888 >>> mock2.assert_called_once_with('bar')
1889
1890
1891Note that the decorators are applied from the bottom upwards. This is the
1892standard way that Python applies decorators. The order of the created mocks
1893passed into your test function matches this order.
1894
1895
1896.. _where-to-patch:
1897
1898Where to patch
Georg Brandlfb134382013-02-03 11:47:49 +01001899~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001900
Georg Brandl7ad3df62014-10-31 07:59:37 +01001901:func:`patch` works by (temporarily) changing the object that a *name* points to with
Michael Foorda9e6fb22012-03-28 14:36:02 +01001902another one. There can be many names pointing to any individual object, so
1903for patching to work you must ensure that you patch the name used by the system
1904under test.
1905
1906The basic principle is that you patch where an object is *looked up*, which
1907is not necessarily the same place as where it is defined. A couple of
1908examples will help to clarify this.
1909
1910Imagine we have a project that we want to test with the following structure::
1911
1912 a.py
1913 -> Defines SomeClass
1914
1915 b.py
1916 -> from a import SomeClass
1917 -> some_function instantiates SomeClass
1918
Georg Brandl7ad3df62014-10-31 07:59:37 +01001919Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
1920:func:`patch`. The problem is that when we import module b, which we will have to
1921do then it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
1922``a.SomeClass`` then it will have no effect on our test; module b already has a
1923reference to the *real* ``SomeClass`` and it looks like our patching had no
Michael Foorda9e6fb22012-03-28 14:36:02 +01001924effect.
1925
Ben Lloyd15033d12017-05-22 12:06:56 +01001926The key is to patch out ``SomeClass`` where it is used (or where it is looked up).
1927In this case ``some_function`` will actually look up ``SomeClass`` in module b,
Michael Foorda9e6fb22012-03-28 14:36:02 +01001928where we have imported it. The patching should look like::
1929
1930 @patch('b.SomeClass')
1931
Georg Brandl7ad3df62014-10-31 07:59:37 +01001932However, consider the alternative scenario where instead of ``from a import
1933SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both
Michael Foorda9e6fb22012-03-28 14:36:02 +01001934of these import forms are common. In this case the class we want to patch is
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001935being looked up in the module and so we have to patch ``a.SomeClass`` instead::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001936
1937 @patch('a.SomeClass')
1938
1939
1940Patching Descriptors and Proxy Objects
Georg Brandlfb134382013-02-03 11:47:49 +01001941~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001942
1943Both patch_ and patch.object_ correctly patch and restore descriptors: class
1944methods, static methods and properties. You should patch these on the *class*
1945rather than an instance. They also work with *some* objects
Zachary Ware5ea5d2c2014-02-26 09:34:43 -06001946that proxy attribute access, like the `django settings object
Michael Foorda9e6fb22012-03-28 14:36:02 +01001947<http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
1948
1949
Michael Foord2309ed82012-03-28 15:38:36 +01001950MagicMock and magic method support
Georg Brandlfb134382013-02-03 11:47:49 +01001951----------------------------------
Michael Foord2309ed82012-03-28 15:38:36 +01001952
1953.. _magic-methods:
1954
1955Mocking Magic Methods
Georg Brandlfb134382013-02-03 11:47:49 +01001956~~~~~~~~~~~~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001957
1958:class:`Mock` supports mocking the Python protocol methods, also known as
1959"magic methods". This allows mock objects to replace containers or other
1960objects that implement Python protocols.
1961
1962Because magic methods are looked up differently from normal methods [#]_, this
1963support has been specially implemented. This means that only specific magic
1964methods are supported. The supported list includes *almost* all of them. If
1965there are any missing that you need please let us know.
1966
1967You mock magic methods by setting the method you are interested in to a function
1968or a mock instance. If you are using a function then it *must* take ``self`` as
1969the first argument [#]_.
1970
1971 >>> def __str__(self):
1972 ... return 'fooble'
1973 ...
1974 >>> mock = Mock()
1975 >>> mock.__str__ = __str__
1976 >>> str(mock)
1977 'fooble'
1978
1979 >>> mock = Mock()
1980 >>> mock.__str__ = Mock()
1981 >>> mock.__str__.return_value = 'fooble'
1982 >>> str(mock)
1983 'fooble'
1984
1985 >>> mock = Mock()
1986 >>> mock.__iter__ = Mock(return_value=iter([]))
1987 >>> list(mock)
1988 []
1989
1990One use case for this is for mocking objects used as context managers in a
Georg Brandl7ad3df62014-10-31 07:59:37 +01001991:keyword:`with` statement:
Michael Foord2309ed82012-03-28 15:38:36 +01001992
1993 >>> mock = Mock()
1994 >>> mock.__enter__ = Mock(return_value='foo')
1995 >>> mock.__exit__ = Mock(return_value=False)
1996 >>> with mock as m:
1997 ... assert m == 'foo'
1998 ...
1999 >>> mock.__enter__.assert_called_with()
2000 >>> mock.__exit__.assert_called_with(None, None, None)
2001
2002Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they
2003are recorded in :attr:`~Mock.mock_calls`.
2004
2005.. note::
2006
Georg Brandl7ad3df62014-10-31 07:59:37 +01002007 If you use the *spec* keyword argument to create a mock then attempting to
2008 set a magic method that isn't in the spec will raise an :exc:`AttributeError`.
Michael Foord2309ed82012-03-28 15:38:36 +01002009
2010The full list of supported magic methods is:
2011
2012* ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``
2013* ``__dir__``, ``__format__`` and ``__subclasses__``
John Reese6c4fab02018-05-22 13:01:10 -07002014* ``__round__``, ``__floor__``, ``__trunc__`` and ``__ceil__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002015* Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``,
Michael Foord2309ed82012-03-28 15:38:36 +01002016 ``__eq__`` and ``__ne__``
2017* Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``,
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002018 ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__``
2019 and ``__missing__``
Xtreak0ae022c2019-05-29 12:32:26 +05302020* Context manager: ``__enter__``, ``__exit__``, ``__aenter__`` and ``__aexit__``
Michael Foord2309ed82012-03-28 15:38:36 +01002021* Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``
2022* The numeric methods (including right hand and in-place variants):
Serhiy Storchakac2ccce72015-03-12 22:01:30 +02002023 ``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__div__``, ``__truediv__``,
Michael Foord2309ed82012-03-28 15:38:36 +01002024 ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``,
2025 ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002026* Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__``
2027 and ``__index__``
Michael Foord2309ed82012-03-28 15:38:36 +01002028* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
2029* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
2030 ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
Max Bélanger6c83d9f2018-10-25 14:48:58 -07002031* File system path representation: ``__fspath__``
Xtreakff6b2e62019-05-27 18:26:23 +05302032* Asynchronous iteration methods: ``__aiter__`` and ``__anext__``
Max Bélanger6c83d9f2018-10-25 14:48:58 -07002033
2034.. versionchanged:: 3.8
2035 Added support for :func:`os.PathLike.__fspath__`.
Michael Foord2309ed82012-03-28 15:38:36 +01002036
Xtreakff6b2e62019-05-27 18:26:23 +05302037.. versionchanged:: 3.8
2038 Added support for ``__aenter__``, ``__aexit__``, ``__aiter__`` and ``__anext__``.
2039
Michael Foord2309ed82012-03-28 15:38:36 +01002040
2041The following methods exist but are *not* supported as they are either in use
2042by mock, can't be set dynamically, or can cause problems:
2043
2044* ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``
2045* ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``
2046
2047
2048
2049Magic Mock
Georg Brandlfb134382013-02-03 11:47:49 +01002050~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01002051
Georg Brandl7ad3df62014-10-31 07:59:37 +01002052There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01002053
2054
2055.. class:: MagicMock(*args, **kw)
2056
2057 ``MagicMock`` is a subclass of :class:`Mock` with default implementations
2058 of most of the magic methods. You can use ``MagicMock`` without having to
2059 configure the magic methods yourself.
2060
2061 The constructor parameters have the same meaning as for :class:`Mock`.
2062
Georg Brandl7ad3df62014-10-31 07:59:37 +01002063 If you use the *spec* or *spec_set* arguments then *only* magic methods
Michael Foord2309ed82012-03-28 15:38:36 +01002064 that exist in the spec will be created.
2065
2066
2067.. class:: NonCallableMagicMock(*args, **kw)
2068
Georg Brandl7ad3df62014-10-31 07:59:37 +01002069 A non-callable version of :class:`MagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01002070
2071 The constructor parameters have the same meaning as for
Georg Brandl7ad3df62014-10-31 07:59:37 +01002072 :class:`MagicMock`, with the exception of *return_value* and
2073 *side_effect* which have no meaning on a non-callable mock.
Michael Foord2309ed82012-03-28 15:38:36 +01002074
Georg Brandl7ad3df62014-10-31 07:59:37 +01002075The magic methods are setup with :class:`MagicMock` objects, so you can configure them
Michael Foord2309ed82012-03-28 15:38:36 +01002076and use them in the usual way:
2077
2078 >>> mock = MagicMock()
2079 >>> mock[3] = 'fish'
2080 >>> mock.__setitem__.assert_called_with(3, 'fish')
2081 >>> mock.__getitem__.return_value = 'result'
2082 >>> mock[2]
2083 'result'
2084
2085By default many of the protocol methods are required to return objects of a
2086specific type. These methods are preconfigured with a default return value, so
2087that they can be used without you having to do anything if you aren't interested
2088in the return value. You can still *set* the return value manually if you want
2089to change the default.
2090
2091Methods and their defaults:
2092
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +02002093* ``__lt__``: ``NotImplemented``
2094* ``__gt__``: ``NotImplemented``
2095* ``__le__``: ``NotImplemented``
2096* ``__ge__``: ``NotImplemented``
2097* ``__int__``: ``1``
2098* ``__contains__``: ``False``
2099* ``__len__``: ``0``
2100* ``__iter__``: ``iter([])``
2101* ``__exit__``: ``False``
2102* ``__aexit__``: ``False``
2103* ``__complex__``: ``1j``
2104* ``__float__``: ``1.0``
2105* ``__bool__``: ``True``
2106* ``__index__``: ``1``
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02002107* ``__hash__``: default hash for the mock
2108* ``__str__``: default str for the mock
Michael Foord2309ed82012-03-28 15:38:36 +01002109* ``__sizeof__``: default sizeof for the mock
2110
2111For example:
2112
2113 >>> mock = MagicMock()
2114 >>> int(mock)
2115 1
2116 >>> len(mock)
2117 0
2118 >>> list(mock)
2119 []
2120 >>> object() in mock
2121 False
2122
Berker Peksag283f1aa2015-01-07 21:15:02 +02002123The two equality methods, :meth:`__eq__` and :meth:`__ne__`, are special.
2124They do the default equality comparison on identity, using the
2125:attr:`~Mock.side_effect` attribute, unless you change their return value to
2126return something else::
Michael Foord2309ed82012-03-28 15:38:36 +01002127
2128 >>> MagicMock() == 3
2129 False
2130 >>> MagicMock() != 3
2131 True
2132 >>> mock = MagicMock()
2133 >>> mock.__eq__.return_value = True
2134 >>> mock == 3
2135 True
2136
Georg Brandl7ad3df62014-10-31 07:59:37 +01002137The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
Michael Foord2309ed82012-03-28 15:38:36 +01002138required to be an iterator:
2139
2140 >>> mock = MagicMock()
2141 >>> mock.__iter__.return_value = ['a', 'b', 'c']
2142 >>> list(mock)
2143 ['a', 'b', 'c']
2144 >>> list(mock)
2145 ['a', 'b', 'c']
2146
2147If the return value *is* an iterator, then iterating over it once will consume
2148it and subsequent iterations will result in an empty list:
2149
2150 >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
2151 >>> list(mock)
2152 ['a', 'b', 'c']
2153 >>> list(mock)
2154 []
2155
2156``MagicMock`` has all of the supported magic methods configured except for some
2157of the obscure and obsolete ones. You can still set these up if you want.
2158
2159Magic methods that are supported but not setup by default in ``MagicMock`` are:
2160
2161* ``__subclasses__``
2162* ``__dir__``
2163* ``__format__``
2164* ``__get__``, ``__set__`` and ``__delete__``
2165* ``__reversed__`` and ``__missing__``
2166* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
2167 ``__getstate__`` and ``__setstate__``
2168* ``__getformat__`` and ``__setformat__``
2169
2170
2171
2172.. [#] Magic methods *should* be looked up on the class rather than the
2173 instance. Different versions of Python are inconsistent about applying this
2174 rule. The supported protocol methods should work with all supported versions
2175 of Python.
2176.. [#] The function is basically hooked up to the class, but each ``Mock``
2177 instance is kept isolated from the others.
2178
2179
Michael Foorda9e6fb22012-03-28 14:36:02 +01002180Helpers
Georg Brandlfb134382013-02-03 11:47:49 +01002181-------
Michael Foorda9e6fb22012-03-28 14:36:02 +01002182
2183sentinel
Georg Brandlfb134382013-02-03 11:47:49 +01002184~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002185
2186.. data:: sentinel
2187
Andrés Delfinof85af032018-07-08 21:28:51 -03002188 The ``sentinel`` object provides a convenient way of providing unique
2189 objects for your tests.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002190
Andrés Delfinof85af032018-07-08 21:28:51 -03002191 Attributes are created on demand when you access them by name. Accessing
2192 the same attribute will always return the same object. The objects
2193 returned have a sensible repr so that test failure messages are readable.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002194
Serhiy Storchakad9c956f2017-01-11 20:13:03 +02002195 .. versionchanged:: 3.7
2196 The ``sentinel`` attributes now preserve their identity when they are
2197 :mod:`copied <copy>` or :mod:`pickled <pickle>`.
2198
Michael Foorda9e6fb22012-03-28 14:36:02 +01002199Sometimes when testing you need to test that a specific object is passed as an
2200argument to another method, or returned. It can be common to create named
Georg Brandl7ad3df62014-10-31 07:59:37 +01002201sentinel objects to test this. :data:`sentinel` provides a convenient way of
Michael Foorda9e6fb22012-03-28 14:36:02 +01002202creating and testing the identity of objects like this.
2203
Georg Brandl7ad3df62014-10-31 07:59:37 +01002204In this example we monkey patch ``method`` to return ``sentinel.some_object``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002205
2206 >>> real = ProductionClass()
2207 >>> real.method = Mock(name="method")
2208 >>> real.method.return_value = sentinel.some_object
2209 >>> result = real.method()
2210 >>> assert result is sentinel.some_object
2211 >>> sentinel.some_object
2212 sentinel.some_object
2213
2214
2215DEFAULT
Georg Brandlfb134382013-02-03 11:47:49 +01002216~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002217
2218
2219.. data:: DEFAULT
2220
Georg Brandl7ad3df62014-10-31 07:59:37 +01002221 The :data:`DEFAULT` object is a pre-created sentinel (actually
2222 ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect`
Michael Foorda9e6fb22012-03-28 14:36:02 +01002223 functions to indicate that the normal return value should be used.
2224
2225
Michael Foorda9e6fb22012-03-28 14:36:02 +01002226call
Georg Brandlfb134382013-02-03 11:47:49 +01002227~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002228
2229.. function:: call(*args, **kwargs)
2230
Georg Brandl7ad3df62014-10-31 07:59:37 +01002231 :func:`call` is a helper object for making simpler assertions, for comparing with
Georg Brandl24891672012-04-01 13:48:26 +02002232 :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
Georg Brandl7ad3df62014-10-31 07:59:37 +01002233 :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be
Michael Foorda9e6fb22012-03-28 14:36:02 +01002234 used with :meth:`~Mock.assert_has_calls`.
2235
2236 >>> m = MagicMock(return_value=None)
2237 >>> m(1, 2, a='foo', b='bar')
2238 >>> m()
2239 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
2240 True
2241
2242.. method:: call.call_list()
2243
Georg Brandl7ad3df62014-10-31 07:59:37 +01002244 For a call object that represents multiple calls, :meth:`call_list`
Michael Foorda9e6fb22012-03-28 14:36:02 +01002245 returns a list of all the intermediate calls as well as the
2246 final call.
2247
Georg Brandl7ad3df62014-10-31 07:59:37 +01002248``call_list`` is particularly useful for making assertions on "chained calls". A
Michael Foorda9e6fb22012-03-28 14:36:02 +01002249chained call is multiple calls on a single line of code. This results in
2250multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
2251the sequence of calls can be tedious.
2252
2253:meth:`~call.call_list` can construct the sequence of calls from the same
2254chained call:
2255
2256 >>> m = MagicMock()
2257 >>> m(1).method(arg='foo').other('bar')(2.0)
2258 <MagicMock name='mock().method().other()()' id='...'>
2259 >>> kall = call(1).method(arg='foo').other('bar')(2.0)
2260 >>> kall.call_list()
2261 [call(1),
2262 call().method(arg='foo'),
2263 call().method().other('bar'),
2264 call().method().other()(2.0)]
2265 >>> m.mock_calls == kall.call_list()
2266 True
2267
2268.. _calls-as-tuples:
2269
Georg Brandl7ad3df62014-10-31 07:59:37 +01002270A ``call`` object is either a tuple of (positional args, keyword args) or
Michael Foorda9e6fb22012-03-28 14:36:02 +01002271(name, positional args, keyword args) depending on how it was constructed. When
Georg Brandl7ad3df62014-10-31 07:59:37 +01002272you construct them yourself this isn't particularly interesting, but the ``call``
Michael Foorda9e6fb22012-03-28 14:36:02 +01002273objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
2274:attr:`Mock.mock_calls` attributes can be introspected to get at the individual
2275arguments they contain.
2276
Georg Brandl7ad3df62014-10-31 07:59:37 +01002277The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
2278are two-tuples of (positional args, keyword args) whereas the ``call`` objects
Michael Foorda9e6fb22012-03-28 14:36:02 +01002279in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
2280three-tuples of (name, positional args, keyword args).
2281
2282You can use their "tupleness" to pull out the individual arguments for more
2283complex introspection and assertions. The positional arguments are a tuple
2284(an empty tuple if there are no positional arguments) and the keyword
2285arguments are a dictionary:
2286
2287 >>> m = MagicMock(return_value=None)
2288 >>> m(1, 2, 3, arg='one', arg2='two')
2289 >>> kall = m.call_args
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302290 >>> kall.args
Michael Foorda9e6fb22012-03-28 14:36:02 +01002291 (1, 2, 3)
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302292 >>> kall.kwargs
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002293 {'arg': 'one', 'arg2': 'two'}
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302294 >>> kall.args is kall[0]
Michael Foorda9e6fb22012-03-28 14:36:02 +01002295 True
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302296 >>> kall.kwargs is kall[1]
Michael Foorda9e6fb22012-03-28 14:36:02 +01002297 True
2298
2299 >>> m = MagicMock()
2300 >>> m.foo(4, 5, 6, arg='two', arg2='three')
2301 <MagicMock name='mock.foo()' id='...'>
2302 >>> kall = m.mock_calls[0]
2303 >>> name, args, kwargs = kall
2304 >>> name
2305 'foo'
2306 >>> args
2307 (4, 5, 6)
2308 >>> kwargs
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002309 {'arg': 'two', 'arg2': 'three'}
Michael Foorda9e6fb22012-03-28 14:36:02 +01002310 >>> name is m.mock_calls[0][0]
2311 True
2312
2313
2314create_autospec
Georg Brandlfb134382013-02-03 11:47:49 +01002315~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002316
2317.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
2318
2319 Create a mock object using another object as a spec. Attributes on the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002320 mock will use the corresponding attribute on the *spec* object as their
Michael Foorda9e6fb22012-03-28 14:36:02 +01002321 spec.
2322
2323 Functions or methods being mocked will have their arguments checked to
2324 ensure that they are called with the correct signature.
2325
Georg Brandl7ad3df62014-10-31 07:59:37 +01002326 If *spec_set* is ``True`` then attempting to set attributes that don't exist
2327 on the spec object will raise an :exc:`AttributeError`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002328
2329 If a class is used as a spec then the return value of the mock (the
2330 instance of the class) will have the same spec. You can use a class as the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002331 spec for an instance object by passing ``instance=True``. The returned mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01002332 will only be callable if instances of the mock are callable.
2333
Georg Brandl7ad3df62014-10-31 07:59:37 +01002334 :func:`create_autospec` also takes arbitrary keyword arguments that are passed to
Michael Foorda9e6fb22012-03-28 14:36:02 +01002335 the constructor of the created mock.
2336
2337See :ref:`auto-speccing` for examples of how to use auto-speccing with
Georg Brandl7ad3df62014-10-31 07:59:37 +01002338:func:`create_autospec` and the *autospec* argument to :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002339
2340
Mario Corcherof5e7f392019-09-09 15:18:06 +01002341.. versionchanged:: 3.8
2342
2343 :func:`create_autospec` now returns an :class:`AsyncMock` if the target is
2344 an async function.
2345
2346
Michael Foorda9e6fb22012-03-28 14:36:02 +01002347ANY
Georg Brandlfb134382013-02-03 11:47:49 +01002348~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002349
2350.. data:: ANY
2351
2352Sometimes you may need to make assertions about *some* of the arguments in a
2353call to mock, but either not care about some of the arguments or want to pull
2354them individually out of :attr:`~Mock.call_args` and make more complex
2355assertions on them.
2356
2357To ignore certain arguments you can pass in objects that compare equal to
2358*everything*. Calls to :meth:`~Mock.assert_called_with` and
2359:meth:`~Mock.assert_called_once_with` will then succeed no matter what was
2360passed in.
2361
2362 >>> mock = Mock(return_value=None)
2363 >>> mock('foo', bar=object())
2364 >>> mock.assert_called_once_with('foo', bar=ANY)
2365
Georg Brandl7ad3df62014-10-31 07:59:37 +01002366:data:`ANY` can also be used in comparisons with call lists like
Michael Foorda9e6fb22012-03-28 14:36:02 +01002367:attr:`~Mock.mock_calls`:
2368
2369 >>> m = MagicMock(return_value=None)
2370 >>> m(1)
2371 >>> m(1, 2)
2372 >>> m(object())
2373 >>> m.mock_calls == [call(1), call(1, 2), ANY]
2374 True
2375
2376
2377
2378FILTER_DIR
Georg Brandlfb134382013-02-03 11:47:49 +01002379~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002380
2381.. data:: FILTER_DIR
2382
Georg Brandl7ad3df62014-10-31 07:59:37 +01002383:data:`FILTER_DIR` is a module level variable that controls the way mock objects
2384respond to :func:`dir` (only for Python 2.6 or more recent). The default is ``True``,
Michael Foorda9e6fb22012-03-28 14:36:02 +01002385which uses the filtering described below, to only show useful members. If you
2386dislike this filtering, or need to switch it off for diagnostic purposes, then
Georg Brandl7ad3df62014-10-31 07:59:37 +01002387set ``mock.FILTER_DIR = False``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002388
Georg Brandl7ad3df62014-10-31 07:59:37 +01002389With filtering on, ``dir(some_mock)`` shows only useful attributes and will
Michael Foorda9e6fb22012-03-28 14:36:02 +01002390include any dynamically created attributes that wouldn't normally be shown.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002391If the mock was created with a *spec* (or *autospec* of course) then all the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002392attributes from the original are shown, even if they haven't been accessed
2393yet:
2394
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002395.. doctest::
2396 :options: +ELLIPSIS,+NORMALIZE_WHITESPACE
2397
Michael Foorda9e6fb22012-03-28 14:36:02 +01002398 >>> dir(Mock())
2399 ['assert_any_call',
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002400 'assert_called',
2401 'assert_called_once',
Michael Foorda9e6fb22012-03-28 14:36:02 +01002402 'assert_called_once_with',
2403 'assert_called_with',
2404 'assert_has_calls',
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002405 'assert_not_called',
Michael Foorda9e6fb22012-03-28 14:36:02 +01002406 'attach_mock',
2407 ...
2408 >>> from urllib import request
2409 >>> dir(Mock(spec=request))
2410 ['AbstractBasicAuthHandler',
2411 'AbstractDigestAuthHandler',
2412 'AbstractHTTPHandler',
2413 'BaseHandler',
2414 ...
2415
Georg Brandl7ad3df62014-10-31 07:59:37 +01002416Many of the not-very-useful (private to :class:`Mock` rather than the thing being
Michael Foorda9e6fb22012-03-28 14:36:02 +01002417mocked) underscore and double underscore prefixed attributes have been
Georg Brandl7ad3df62014-10-31 07:59:37 +01002418filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this
Michael Foorda9e6fb22012-03-28 14:36:02 +01002419behaviour you can switch it off by setting the module level switch
Georg Brandl7ad3df62014-10-31 07:59:37 +01002420:data:`FILTER_DIR`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002421
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002422.. doctest::
2423 :options: +ELLIPSIS,+NORMALIZE_WHITESPACE
2424
Michael Foorda9e6fb22012-03-28 14:36:02 +01002425 >>> from unittest import mock
2426 >>> mock.FILTER_DIR = False
2427 >>> dir(mock.Mock())
2428 ['_NonCallableMock__get_return_value',
2429 '_NonCallableMock__get_side_effect',
2430 '_NonCallableMock__return_value_doc',
2431 '_NonCallableMock__set_return_value',
2432 '_NonCallableMock__set_side_effect',
2433 '__call__',
2434 '__class__',
2435 ...
2436
Georg Brandl7ad3df62014-10-31 07:59:37 +01002437Alternatively you can just use ``vars(my_mock)`` (instance members) and
2438``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of
2439:data:`mock.FILTER_DIR`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002440
2441
2442mock_open
Georg Brandlfb134382013-02-03 11:47:49 +01002443~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002444
2445.. function:: mock_open(mock=None, read_data=None)
2446
Andrés Delfinof85af032018-07-08 21:28:51 -03002447 A helper function to create a mock to replace the use of :func:`open`. It works
2448 for :func:`open` called directly or used as a context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002449
Andrés Delfinof85af032018-07-08 21:28:51 -03002450 The *mock* argument is the mock object to configure. If ``None`` (the
2451 default) then a :class:`MagicMock` will be created for you, with the API limited
2452 to methods or attributes available on standard file handles.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002453
Andrés Delfinof85af032018-07-08 21:28:51 -03002454 *read_data* is a string for the :meth:`~io.IOBase.read`,
2455 :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods
2456 of the file handle to return. Calls to those methods will take data from
2457 *read_data* until it is depleted. The mock of these methods is pretty
2458 simplistic: every time the *mock* is called, the *read_data* is rewound to
2459 the start. If you need more control over the data that you are feeding to
2460 the tested code you will need to customize this mock for yourself. When that
2461 is insufficient, one of the in-memory filesystem packages on `PyPI
2462 <https://pypi.org>`_ can offer a realistic filesystem for testing.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002463
Robert Collinsf79dfe32015-07-24 04:09:59 +12002464 .. versionchanged:: 3.4
2465 Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support.
2466 The mock of :meth:`~io.IOBase.read` changed to consume *read_data* rather
2467 than returning it on each call.
2468
Robert Collins70398392015-07-24 04:10:27 +12002469 .. versionchanged:: 3.5
Robert Collinsf79dfe32015-07-24 04:09:59 +12002470 *read_data* is now reset on each call to the *mock*.
2471
Tony Flury20870232018-09-12 23:21:16 +01002472 .. versionchanged:: 3.8
2473 Added :meth:`__iter__` to implementation so that iteration (such as in for
2474 loops) correctly consumes *read_data*.
2475
Georg Brandl7ad3df62014-10-31 07:59:37 +01002476Using :func:`open` as a context manager is a great way to ensure your file handles
Michael Foorda9e6fb22012-03-28 14:36:02 +01002477are closed properly and is becoming common::
2478
2479 with open('/some/path', 'w') as f:
2480 f.write('something')
2481
Georg Brandl7ad3df62014-10-31 07:59:37 +01002482The issue is that even if you mock out the call to :func:`open` it is the
2483*returned object* that is used as a context manager (and has :meth:`__enter__` and
2484:meth:`__exit__` called).
Michael Foorda9e6fb22012-03-28 14:36:02 +01002485
2486Mocking context managers with a :class:`MagicMock` is common enough and fiddly
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002487enough that a helper function is useful. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002488
2489 >>> m = mock_open()
Michael Foordfddcfa22014-04-14 16:25:20 -04002490 >>> with patch('__main__.open', m):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002491 ... with open('foo', 'w') as h:
2492 ... h.write('some stuff')
2493 ...
2494 >>> m.mock_calls
2495 [call('foo', 'w'),
2496 call().__enter__(),
2497 call().write('some stuff'),
2498 call().__exit__(None, None, None)]
2499 >>> m.assert_called_once_with('foo', 'w')
2500 >>> handle = m()
2501 >>> handle.write.assert_called_once_with('some stuff')
2502
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002503And for reading files::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002504
Michael Foordfddcfa22014-04-14 16:25:20 -04002505 >>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002506 ... with open('foo') as h:
2507 ... result = h.read()
2508 ...
2509 >>> m.assert_called_once_with('foo')
2510 >>> assert result == 'bibble'
2511
2512
2513.. _auto-speccing:
2514
2515Autospeccing
Georg Brandlfb134382013-02-03 11:47:49 +01002516~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002517
Georg Brandl7ad3df62014-10-31 07:59:37 +01002518Autospeccing is based on the existing :attr:`spec` feature of mock. It limits the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002519api of mocks to the api of an original object (the spec), but it is recursive
2520(implemented lazily) so that attributes of mocks only have the same api as
2521the attributes of the spec. In addition mocked functions / methods have the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002522same call signature as the original so they raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002523called incorrectly.
2524
2525Before I explain how auto-speccing works, here's why it is needed.
2526
Georg Brandl7ad3df62014-10-31 07:59:37 +01002527:class:`Mock` is a very powerful and flexible object, but it suffers from two flaws
Michael Foorda9e6fb22012-03-28 14:36:02 +01002528when used to mock out objects from a system under test. One of these flaws is
Georg Brandl7ad3df62014-10-31 07:59:37 +01002529specific to the :class:`Mock` api and the other is a more general problem with using
Michael Foorda9e6fb22012-03-28 14:36:02 +01002530mock objects.
2531
Georg Brandl7ad3df62014-10-31 07:59:37 +01002532First the problem specific to :class:`Mock`. :class:`Mock` has two assert methods that are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002533extremely handy: :meth:`~Mock.assert_called_with` and
2534:meth:`~Mock.assert_called_once_with`.
2535
2536 >>> mock = Mock(name='Thing', return_value=None)
2537 >>> mock(1, 2, 3)
2538 >>> mock.assert_called_once_with(1, 2, 3)
2539 >>> mock(1, 2, 3)
2540 >>> mock.assert_called_once_with(1, 2, 3)
2541 Traceback (most recent call last):
2542 ...
Michael Foord28d591c2012-09-28 16:15:22 +01002543 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002544
2545Because mocks auto-create attributes on demand, and allow you to call them
2546with arbitrary arguments, if you misspell one of these assert methods then
2547your assertion is gone:
2548
2549.. code-block:: pycon
2550
2551 >>> mock = Mock(name='Thing', return_value=None)
2552 >>> mock(1, 2, 3)
2553 >>> mock.assret_called_once_with(4, 5, 6)
2554
2555Your tests can pass silently and incorrectly because of the typo.
2556
2557The second issue is more general to mocking. If you refactor some of your
2558code, rename members and so on, any tests for code that is still using the
2559*old api* but uses mocks instead of the real objects will still pass. This
2560means your tests can all pass even though your code is broken.
2561
2562Note that this is another reason why you need integration tests as well as
2563unit tests. Testing everything in isolation is all fine and dandy, but if you
2564don't test how your units are "wired together" there is still lots of room
2565for bugs that tests might have caught.
2566
Georg Brandl7ad3df62014-10-31 07:59:37 +01002567:mod:`mock` already provides a feature to help with this, called speccing. If you
2568use a class or instance as the :attr:`spec` for a mock then you can only access
Michael Foorda9e6fb22012-03-28 14:36:02 +01002569attributes on the mock that exist on the real class:
2570
2571 >>> from urllib import request
2572 >>> mock = Mock(spec=request.Request)
2573 >>> mock.assret_called_with
2574 Traceback (most recent call last):
2575 ...
2576 AttributeError: Mock object has no attribute 'assret_called_with'
2577
2578The spec only applies to the mock itself, so we still have the same issue
2579with any methods on the mock:
2580
2581.. code-block:: pycon
2582
2583 >>> mock.has_data()
2584 <mock.Mock object at 0x...>
2585 >>> mock.has_data.assret_called_with()
2586
Georg Brandl7ad3df62014-10-31 07:59:37 +01002587Auto-speccing solves this problem. You can either pass ``autospec=True`` to
2588:func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a
2589mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002590object that is being replaced will be used as the spec object. Because the
2591speccing is done "lazily" (the spec is created as attributes on the mock are
2592accessed) you can use it with very complex or deeply nested objects (like
2593modules that import modules that import modules) without a big performance
2594hit.
2595
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002596Here's an example of it in use::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002597
2598 >>> from urllib import request
2599 >>> patcher = patch('__main__.request', autospec=True)
2600 >>> mock_request = patcher.start()
2601 >>> request is mock_request
2602 True
2603 >>> mock_request.Request
2604 <MagicMock name='request.Request' spec='Request' id='...'>
2605
Georg Brandl7ad3df62014-10-31 07:59:37 +01002606You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two
2607arguments in the constructor (one of which is *self*). Here's what happens if
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002608we try to call it incorrectly::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002609
2610 >>> req = request.Request()
2611 Traceback (most recent call last):
2612 ...
2613 TypeError: <lambda>() takes at least 2 arguments (1 given)
2614
2615The spec also applies to instantiated classes (i.e. the return value of
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002616specced mocks)::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002617
2618 >>> req = request.Request('foo')
2619 >>> req
2620 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
2621
Georg Brandl7ad3df62014-10-31 07:59:37 +01002622:class:`Request` objects are not callable, so the return value of instantiating our
2623mocked out :class:`request.Request` is a non-callable mock. With the spec in place
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002624any typos in our asserts will raise the correct error::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002625
2626 >>> req.add_header('spam', 'eggs')
2627 <MagicMock name='request.Request().add_header()' id='...'>
2628 >>> req.add_header.assret_called_with
2629 Traceback (most recent call last):
2630 ...
2631 AttributeError: Mock object has no attribute 'assret_called_with'
2632 >>> req.add_header.assert_called_with('spam', 'eggs')
2633
Georg Brandl7ad3df62014-10-31 07:59:37 +01002634In many cases you will just be able to add ``autospec=True`` to your existing
2635:func:`patch` calls and then be protected against bugs due to typos and api
Michael Foorda9e6fb22012-03-28 14:36:02 +01002636changes.
2637
Georg Brandl7ad3df62014-10-31 07:59:37 +01002638As well as using *autospec* through :func:`patch` there is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002639:func:`create_autospec` for creating autospecced mocks directly:
2640
2641 >>> from urllib import request
2642 >>> mock_request = create_autospec(request)
2643 >>> mock_request.Request('foo', 'bar')
2644 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
2645
2646This isn't without caveats and limitations however, which is why it is not
2647the default behaviour. In order to know what attributes are available on the
2648spec object, autospec has to introspect (access attributes) the spec. As you
2649traverse attributes on the mock a corresponding traversal of the original
2650object is happening under the hood. If any of your specced objects have
2651properties or descriptors that can trigger code execution then you may not be
2652able to use autospec. On the other hand it is much better to design your
2653objects so that introspection is safe [#]_.
2654
2655A more serious problem is that it is common for instance attributes to be
Georg Brandl7ad3df62014-10-31 07:59:37 +01002656created in the :meth:`__init__` method and not to exist on the class at all.
2657*autospec* can't know about any dynamically created attributes and restricts
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002658the api to visible attributes. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002659
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002660 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002661 ... def __init__(self):
2662 ... self.a = 33
2663 ...
2664 >>> with patch('__main__.Something', autospec=True):
2665 ... thing = Something()
2666 ... thing.a
2667 ...
2668 Traceback (most recent call last):
2669 ...
2670 AttributeError: Mock object has no attribute 'a'
2671
2672There are a few different ways of resolving this problem. The easiest, but
2673not necessarily the least annoying, way is to simply set the required
Georg Brandl7ad3df62014-10-31 07:59:37 +01002674attributes on the mock after creation. Just because *autospec* doesn't allow
Michael Foorda9e6fb22012-03-28 14:36:02 +01002675you to fetch attributes that don't exist on the spec it doesn't prevent you
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002676setting them::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002677
2678 >>> with patch('__main__.Something', autospec=True):
2679 ... thing = Something()
2680 ... thing.a = 33
2681 ...
2682
Georg Brandl7ad3df62014-10-31 07:59:37 +01002683There is a more aggressive version of both *spec* and *autospec* that *does*
Michael Foorda9e6fb22012-03-28 14:36:02 +01002684prevent you setting non-existent attributes. This is useful if you want to
2685ensure your code only *sets* valid attributes too, but obviously it prevents
2686this particular scenario:
2687
2688 >>> with patch('__main__.Something', autospec=True, spec_set=True):
2689 ... thing = Something()
2690 ... thing.a = 33
2691 ...
2692 Traceback (most recent call last):
2693 ...
2694 AttributeError: Mock object has no attribute 'a'
2695
2696Probably the best way of solving the problem is to add class attributes as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002697default values for instance members initialised in :meth:`__init__`. Note that if
2698you are only setting default attributes in :meth:`__init__` then providing them via
Michael Foorda9e6fb22012-03-28 14:36:02 +01002699class attributes (shared between instances of course) is faster too. e.g.
2700
2701.. code-block:: python
2702
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002703 class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002704 a = 33
2705
2706This brings up another issue. It is relatively common to provide a default
Georg Brandl7ad3df62014-10-31 07:59:37 +01002707value of ``None`` for members that will later be an object of a different type.
2708``None`` would be useless as a spec because it wouldn't let you access *any*
2709attributes or methods on it. As ``None`` is *never* going to be useful as a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002710spec, and probably indicates a member that will normally of some other type,
Georg Brandl7ad3df62014-10-31 07:59:37 +01002711autospec doesn't use a spec for members that are set to ``None``. These will
2712just be ordinary mocks (well - MagicMocks):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002713
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002714 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002715 ... member = None
2716 ...
2717 >>> mock = create_autospec(Something)
2718 >>> mock.member.foo.bar.baz()
2719 <MagicMock name='mock.member.foo.bar.baz()' id='...'>
2720
2721If modifying your production classes to add defaults isn't to your liking
2722then there are more options. One of these is simply to use an instance as the
2723spec rather than the class. The other is to create a subclass of the
2724production class and add the defaults to the subclass without affecting the
2725production class. Both of these require you to use an alternative object as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002726the spec. Thankfully :func:`patch` supports this - you can simply pass the
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002727alternative object as the *autospec* argument::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002728
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002729 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002730 ... def __init__(self):
2731 ... self.a = 33
2732 ...
2733 >>> class SomethingForTest(Something):
2734 ... a = 33
2735 ...
2736 >>> p = patch('__main__.Something', autospec=SomethingForTest)
2737 >>> mock = p.start()
2738 >>> mock.a
2739 <NonCallableMagicMock name='Something.a' spec='int' id='...'>
2740
2741
2742.. [#] This only applies to classes or already instantiated objects. Calling
2743 a mocked class to create a mock instance *does not* create a real instance.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002744 It is only attribute lookups - along with calls to :func:`dir` - that are done.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002745
Mario Corchero552be9d2017-10-17 12:35:11 +01002746Sealing mocks
2747~~~~~~~~~~~~~
2748
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002749
2750.. testsetup::
2751
2752 from unittest.mock import seal
2753
Mario Corchero552be9d2017-10-17 12:35:11 +01002754.. function:: seal(mock)
2755
Mario Corchero96200eb2018-10-19 22:57:37 +01002756 Seal will disable the automatic creation of mocks when accessing an attribute of
2757 the mock being sealed or any of its attributes that are already mocks recursively.
Mario Corchero552be9d2017-10-17 12:35:11 +01002758
Mario Corchero96200eb2018-10-19 22:57:37 +01002759 If a mock instance with a name or a spec is assigned to an attribute
Paul Ganssle85ac7262018-01-06 08:25:34 -05002760 it won't be considered in the sealing chain. This allows one to prevent seal from
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002761 fixing part of the mock object. ::
Mario Corchero552be9d2017-10-17 12:35:11 +01002762
2763 >>> mock = Mock()
2764 >>> mock.submock.attribute1 = 2
Mario Corchero96200eb2018-10-19 22:57:37 +01002765 >>> mock.not_submock = mock.Mock(name="sample_name")
Mario Corchero552be9d2017-10-17 12:35:11 +01002766 >>> seal(mock)
Mario Corchero96200eb2018-10-19 22:57:37 +01002767 >>> mock.new_attribute # This will raise AttributeError.
Mario Corchero552be9d2017-10-17 12:35:11 +01002768 >>> mock.submock.attribute2 # This will raise AttributeError.
2769 >>> mock.not_submock.attribute2 # This won't raise.
2770
2771 .. versionadded:: 3.7