blob: b446ddb3598f2939432c7f2cf462047898fa9bc2 [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
Georg Brandl7ad3df62014-10-31 07:59:37 +0100265 * *unsafe*: By default if any attribute starts with *assert* or
266 *assret* will raise an :exc:`AttributeError`. Passing ``unsafe=True``
267 will allow access to these attributes.
Kushal Das8c145342014-04-16 23:32:21 +0530268
269 .. versionadded:: 3.5
270
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300271 * *wraps*: Item for the mock object to wrap. If *wraps* is not ``None`` then
Michael Foord944e02d2012-03-25 23:12:55 +0100272 calling the Mock will pass the call through to the wrapped object
Michael Foord0682a0c2012-04-13 20:51:20 +0100273 (returning the real result). Attribute access on the mock will return a
274 Mock object that wraps the corresponding attribute of the wrapped
275 object (so attempting to access an attribute that doesn't exist will
Georg Brandl7ad3df62014-10-31 07:59:37 +0100276 raise an :exc:`AttributeError`).
Michael Foord944e02d2012-03-25 23:12:55 +0100277
Georg Brandl7ad3df62014-10-31 07:59:37 +0100278 If the mock has an explicit *return_value* set then calls are not passed
279 to the wrapped object and the *return_value* is returned instead.
Michael Foord944e02d2012-03-25 23:12:55 +0100280
Georg Brandl7ad3df62014-10-31 07:59:37 +0100281 * *name*: If the mock has a name then it will be used in the repr of the
Michael Foord944e02d2012-03-25 23:12:55 +0100282 mock. This can be useful for debugging. The name is propagated to child
283 mocks.
284
285 Mocks can also be called with arbitrary keyword arguments. These will be
286 used to set attributes on the mock after it is created. See the
287 :meth:`configure_mock` method for details.
288
Ismail Sf9590ed2019-08-12 07:57:03 +0100289 .. method:: assert_called()
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100290
291 Assert that the mock was called at least once.
292
293 >>> mock = Mock()
294 >>> mock.method()
295 <Mock name='mock.method()' id='...'>
296 >>> mock.method.assert_called()
297
298 .. versionadded:: 3.6
299
Ismail Sf9590ed2019-08-12 07:57:03 +0100300 .. method:: assert_called_once()
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100301
302 Assert that the mock was called exactly once.
303
304 >>> mock = Mock()
305 >>> mock.method()
306 <Mock name='mock.method()' id='...'>
307 >>> mock.method.assert_called_once()
308 >>> mock.method()
309 <Mock name='mock.method()' id='...'>
310 >>> mock.method.assert_called_once()
311 Traceback (most recent call last):
312 ...
313 AssertionError: Expected 'method' to have been called once. Called 2 times.
314
315 .. versionadded:: 3.6
316
Michael Foord944e02d2012-03-25 23:12:55 +0100317
318 .. method:: assert_called_with(*args, **kwargs)
319
Rémi Lapeyref5896a02019-08-29 08:15:53 +0200320 This method is a convenient way of asserting that the last call has been
321 made in a particular way:
Michael Foord944e02d2012-03-25 23:12:55 +0100322
323 >>> mock = Mock()
324 >>> mock.method(1, 2, 3, test='wow')
325 <Mock name='mock.method()' id='...'>
326 >>> mock.method.assert_called_with(1, 2, 3, test='wow')
327
Michael Foord944e02d2012-03-25 23:12:55 +0100328 .. method:: assert_called_once_with(*args, **kwargs)
329
Arne de Laat324c5d82017-02-23 15:57:25 +0100330 Assert that the mock was called exactly once and that that call was
331 with the specified arguments.
Michael Foord944e02d2012-03-25 23:12:55 +0100332
333 >>> mock = Mock(return_value=None)
334 >>> mock('foo', bar='baz')
335 >>> mock.assert_called_once_with('foo', bar='baz')
Arne de Laat324c5d82017-02-23 15:57:25 +0100336 >>> mock('other', bar='values')
337 >>> mock.assert_called_once_with('other', bar='values')
Michael Foord944e02d2012-03-25 23:12:55 +0100338 Traceback (most recent call last):
339 ...
Michael Foord28d591c2012-09-28 16:15:22 +0100340 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foord944e02d2012-03-25 23:12:55 +0100341
342
343 .. method:: assert_any_call(*args, **kwargs)
344
345 assert the mock has been called with the specified arguments.
346
347 The assert passes if the mock has *ever* been called, unlike
348 :meth:`assert_called_with` and :meth:`assert_called_once_with` that
Arne de Laat324c5d82017-02-23 15:57:25 +0100349 only pass if the call is the most recent one, and in the case of
350 :meth:`assert_called_once_with` it must also be the only call.
Michael Foord944e02d2012-03-25 23:12:55 +0100351
352 >>> mock = Mock(return_value=None)
353 >>> mock(1, 2, arg='thing')
354 >>> mock('some', 'thing', 'else')
355 >>> mock.assert_any_call(1, 2, arg='thing')
356
357
358 .. method:: assert_has_calls(calls, any_order=False)
359
360 assert the mock has been called with the specified calls.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100361 The :attr:`mock_calls` list is checked for the calls.
Michael Foord944e02d2012-03-25 23:12:55 +0100362
Georg Brandl7ad3df62014-10-31 07:59:37 +0100363 If *any_order* is false (the default) then the calls must be
Michael Foord944e02d2012-03-25 23:12:55 +0100364 sequential. There can be extra calls before or after the
365 specified calls.
366
Georg Brandl7ad3df62014-10-31 07:59:37 +0100367 If *any_order* is true then the calls can be in any order, but
Michael Foord944e02d2012-03-25 23:12:55 +0100368 they must all appear in :attr:`mock_calls`.
369
370 >>> mock = Mock(return_value=None)
371 >>> mock(1)
372 >>> mock(2)
373 >>> mock(3)
374 >>> mock(4)
375 >>> calls = [call(2), call(3)]
376 >>> mock.assert_has_calls(calls)
377 >>> calls = [call(4), call(2), call(3)]
378 >>> mock.assert_has_calls(calls, any_order=True)
379
Berker Peksagebf9fd32016-07-17 15:26:46 +0300380 .. method:: assert_not_called()
Kushal Das8af9db32014-04-17 01:36:14 +0530381
382 Assert the mock was never called.
383
384 >>> m = Mock()
385 >>> m.hello.assert_not_called()
386 >>> obj = m.hello()
387 >>> m.hello.assert_not_called()
388 Traceback (most recent call last):
389 ...
390 AssertionError: Expected 'hello' to not have been called. Called 1 times.
391
392 .. versionadded:: 3.5
393
Michael Foord944e02d2012-03-25 23:12:55 +0100394
Kushal Das9cd39a12016-06-02 10:20:16 -0700395 .. method:: reset_mock(*, return_value=False, side_effect=False)
Michael Foord944e02d2012-03-25 23:12:55 +0100396
397 The reset_mock method resets all the call attributes on a mock object:
398
399 >>> mock = Mock(return_value=None)
400 >>> mock('hello')
401 >>> mock.called
402 True
403 >>> mock.reset_mock()
404 >>> mock.called
405 False
406
Kushal Das9cd39a12016-06-02 10:20:16 -0700407 .. versionchanged:: 3.6
408 Added two keyword only argument to the reset_mock function.
409
Michael Foord944e02d2012-03-25 23:12:55 +0100410 This can be useful where you want to make a series of assertions that
Georg Brandl7ad3df62014-10-31 07:59:37 +0100411 reuse the same object. Note that :meth:`reset_mock` *doesn't* clear the
Michael Foord944e02d2012-03-25 23:12:55 +0100412 return value, :attr:`side_effect` or any child attributes you have
Kushal Das9cd39a12016-06-02 10:20:16 -0700413 set using normal assignment by default. In case you want to reset
414 *return_value* or :attr:`side_effect`, then pass the corresponding
415 parameter as ``True``. Child mocks and the return value mock
Michael Foord944e02d2012-03-25 23:12:55 +0100416 (if any) are reset as well.
417
Kushal Das9cd39a12016-06-02 10:20:16 -0700418 .. note:: *return_value*, and :attr:`side_effect` are keyword only
419 argument.
420
Michael Foord944e02d2012-03-25 23:12:55 +0100421
422 .. method:: mock_add_spec(spec, spec_set=False)
423
Georg Brandl7ad3df62014-10-31 07:59:37 +0100424 Add a spec to a mock. *spec* can either be an object or a
425 list of strings. Only attributes on the *spec* can be fetched as
Michael Foord944e02d2012-03-25 23:12:55 +0100426 attributes from the mock.
427
Georg Brandl7ad3df62014-10-31 07:59:37 +0100428 If *spec_set* is true then only attributes on the spec can be set.
Michael Foord944e02d2012-03-25 23:12:55 +0100429
430
431 .. method:: attach_mock(mock, attribute)
432
433 Attach a mock as an attribute of this one, replacing its name and
434 parent. Calls to the attached mock will be recorded in the
435 :attr:`method_calls` and :attr:`mock_calls` attributes of this one.
436
437
438 .. method:: configure_mock(**kwargs)
439
440 Set attributes on the mock through keyword arguments.
441
442 Attributes plus return values and side effects can be set on child
443 mocks using standard dot notation and unpacking a dictionary in the
444 method call:
445
446 >>> mock = Mock()
447 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
448 >>> mock.configure_mock(**attrs)
449 >>> mock.method()
450 3
451 >>> mock.other()
452 Traceback (most recent call last):
453 ...
454 KeyError
455
456 The same thing can be achieved in the constructor call to mocks:
457
458 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
459 >>> mock = Mock(some_attribute='eggs', **attrs)
460 >>> mock.some_attribute
461 'eggs'
462 >>> mock.method()
463 3
464 >>> mock.other()
465 Traceback (most recent call last):
466 ...
467 KeyError
468
Georg Brandl7ad3df62014-10-31 07:59:37 +0100469 :meth:`configure_mock` exists to make it easier to do configuration
Michael Foord944e02d2012-03-25 23:12:55 +0100470 after the mock has been created.
471
472
473 .. method:: __dir__()
474
Georg Brandl7ad3df62014-10-31 07:59:37 +0100475 :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results.
476 For mocks with a *spec* this includes all the permitted attributes
Michael Foord944e02d2012-03-25 23:12:55 +0100477 for the mock.
478
479 See :data:`FILTER_DIR` for what this filtering does, and how to
480 switch it off.
481
482
483 .. method:: _get_child_mock(**kw)
484
485 Create the child mocks for attributes and return value.
486 By default child mocks will be the same type as the parent.
487 Subclasses of Mock may want to override this to customize the way
488 child mocks are made.
489
490 For non-callable mocks the callable variant will be used (rather than
491 any custom subclass).
492
493
494 .. attribute:: called
495
496 A boolean representing whether or not the mock object has been called:
497
498 >>> mock = Mock(return_value=None)
499 >>> mock.called
500 False
501 >>> mock()
502 >>> mock.called
503 True
504
505 .. attribute:: call_count
506
507 An integer telling you how many times the mock object has been called:
508
509 >>> mock = Mock(return_value=None)
510 >>> mock.call_count
511 0
512 >>> mock()
513 >>> mock()
514 >>> mock.call_count
515 2
516
Lisa Roachb9f65f02019-09-09 17:54:13 +0100517 For :class:`AsyncMock` the :attr:`call_count` is only iterated if the function
518 has been awaited:
519
520 >>> mock = AsyncMock()
521 >>> mock() # doctest: +SKIP
522 <coroutine object AsyncMockMixin._mock_call at ...>
523 >>> mock.call_count
524 0
525 >>> async def main():
526 ... await mock()
527 ...
528 >>> asyncio.run(main())
529 >>> mock.call_count
530 1
Michael Foord944e02d2012-03-25 23:12:55 +0100531
532 .. attribute:: return_value
533
534 Set this to configure the value returned by calling the mock:
535
536 >>> mock = Mock()
537 >>> mock.return_value = 'fish'
538 >>> mock()
539 'fish'
540
541 The default return value is a mock object and you can configure it in
542 the normal way:
543
544 >>> mock = Mock()
545 >>> mock.return_value.attribute = sentinel.Attribute
546 >>> mock.return_value()
547 <Mock name='mock()()' id='...'>
548 >>> mock.return_value.assert_called_with()
549
Georg Brandl7ad3df62014-10-31 07:59:37 +0100550 :attr:`return_value` can also be set in the constructor:
Michael Foord944e02d2012-03-25 23:12:55 +0100551
552 >>> mock = Mock(return_value=3)
553 >>> mock.return_value
554 3
555 >>> mock()
556 3
557
558
559 .. attribute:: side_effect
560
561 This can either be a function to be called when the mock is called,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100562 an iterable or an exception (class or instance) to be raised.
Michael Foord944e02d2012-03-25 23:12:55 +0100563
564 If you pass in a function it will be called with same arguments as the
565 mock and unless the function returns the :data:`DEFAULT` singleton the
566 call to the mock will then return whatever the function returns. If the
567 function returns :data:`DEFAULT` then the mock will return its normal
Brett Cannon533f1ed2013-05-25 11:28:20 -0400568 value (from the :attr:`return_value`).
Michael Foord944e02d2012-03-25 23:12:55 +0100569
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100570 If you pass in an iterable, it is used to retrieve an iterator which
571 must yield a value on every call. This value can either be an exception
572 instance to be raised, or a value to be returned from the call to the
573 mock (:data:`DEFAULT` handling is identical to the function case).
574
Michael Foord944e02d2012-03-25 23:12:55 +0100575 An example of a mock that raises an exception (to test exception
576 handling of an API):
577
578 >>> mock = Mock()
579 >>> mock.side_effect = Exception('Boom!')
580 >>> mock()
581 Traceback (most recent call last):
582 ...
583 Exception: Boom!
584
Georg Brandl7ad3df62014-10-31 07:59:37 +0100585 Using :attr:`side_effect` to return a sequence of values:
Michael Foord944e02d2012-03-25 23:12:55 +0100586
587 >>> mock = Mock()
588 >>> mock.side_effect = [3, 2, 1]
589 >>> mock(), mock(), mock()
590 (3, 2, 1)
591
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100592 Using a callable:
Michael Foord944e02d2012-03-25 23:12:55 +0100593
594 >>> mock = Mock(return_value=3)
595 >>> def side_effect(*args, **kwargs):
596 ... return DEFAULT
597 ...
598 >>> mock.side_effect = side_effect
599 >>> mock()
600 3
601
Georg Brandl7ad3df62014-10-31 07:59:37 +0100602 :attr:`side_effect` can be set in the constructor. Here's an example that
Michael Foord944e02d2012-03-25 23:12:55 +0100603 adds one to the value the mock is called with and returns it:
604
605 >>> side_effect = lambda value: value + 1
606 >>> mock = Mock(side_effect=side_effect)
607 >>> mock(3)
608 4
609 >>> mock(-8)
610 -7
611
Georg Brandl7ad3df62014-10-31 07:59:37 +0100612 Setting :attr:`side_effect` to ``None`` clears it:
Michael Foord944e02d2012-03-25 23:12:55 +0100613
614 >>> m = Mock(side_effect=KeyError, return_value=3)
615 >>> m()
616 Traceback (most recent call last):
617 ...
618 KeyError
619 >>> m.side_effect = None
620 >>> m()
621 3
622
623
624 .. attribute:: call_args
625
Georg Brandl7ad3df62014-10-31 07:59:37 +0100626 This is either ``None`` (if the mock hasn't been called), or the
Michael Foord944e02d2012-03-25 23:12:55 +0100627 arguments that the mock was last called with. This will be in the
Kumar Akshayb0df45e2019-03-22 13:40:40 +0530628 form of a tuple: the first member, which can also be accessed through
629 the ``args`` property, is any ordered arguments the mock was
630 called with (or an empty tuple) and the second member, which can
631 also be accessed through the ``kwargs`` property, is any keyword
632 arguments (or an empty dictionary).
Michael Foord944e02d2012-03-25 23:12:55 +0100633
634 >>> mock = Mock(return_value=None)
Berker Peksag920f6db2015-09-10 21:41:15 +0300635 >>> print(mock.call_args)
Michael Foord944e02d2012-03-25 23:12:55 +0100636 None
637 >>> mock()
638 >>> mock.call_args
639 call()
640 >>> mock.call_args == ()
641 True
642 >>> mock(3, 4)
643 >>> mock.call_args
644 call(3, 4)
645 >>> mock.call_args == ((3, 4),)
646 True
Kumar Akshayb0df45e2019-03-22 13:40:40 +0530647 >>> mock.call_args.args
648 (3, 4)
649 >>> mock.call_args.kwargs
650 {}
Michael Foord944e02d2012-03-25 23:12:55 +0100651 >>> mock(3, 4, 5, key='fish', next='w00t!')
652 >>> mock.call_args
653 call(3, 4, 5, key='fish', next='w00t!')
Kumar Akshayb0df45e2019-03-22 13:40:40 +0530654 >>> mock.call_args.args
655 (3, 4, 5)
656 >>> mock.call_args.kwargs
657 {'key': 'fish', 'next': 'w00t!'}
Michael Foord944e02d2012-03-25 23:12:55 +0100658
Georg Brandl7ad3df62014-10-31 07:59:37 +0100659 :attr:`call_args`, along with members of the lists :attr:`call_args_list`,
Michael Foord944e02d2012-03-25 23:12:55 +0100660 :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects.
661 These are tuples, so they can be unpacked to get at the individual
662 arguments and make more complex assertions. See
663 :ref:`calls as tuples <calls-as-tuples>`.
664
665
666 .. attribute:: call_args_list
667
668 This is a list of all the calls made to the mock object in sequence
669 (so the length of the list is the number of times it has been
670 called). Before any calls have been made it is an empty list. The
671 :data:`call` object can be used for conveniently constructing lists of
Georg Brandl7ad3df62014-10-31 07:59:37 +0100672 calls to compare with :attr:`call_args_list`.
Michael Foord944e02d2012-03-25 23:12:55 +0100673
674 >>> mock = Mock(return_value=None)
675 >>> mock()
676 >>> mock(3, 4)
677 >>> mock(key='fish', next='w00t!')
678 >>> mock.call_args_list
679 [call(), call(3, 4), call(key='fish', next='w00t!')]
680 >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
681 >>> mock.call_args_list == expected
682 True
683
Georg Brandl7ad3df62014-10-31 07:59:37 +0100684 Members of :attr:`call_args_list` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100685 unpacked as tuples to get at the individual arguments. See
686 :ref:`calls as tuples <calls-as-tuples>`.
687
688
689 .. attribute:: method_calls
690
691 As well as tracking calls to themselves, mocks also track calls to
692 methods and attributes, and *their* methods and attributes:
693
694 >>> mock = Mock()
695 >>> mock.method()
696 <Mock name='mock.method()' id='...'>
697 >>> mock.property.method.attribute()
698 <Mock name='mock.property.method.attribute()' id='...'>
699 >>> mock.method_calls
700 [call.method(), call.property.method.attribute()]
701
Georg Brandl7ad3df62014-10-31 07:59:37 +0100702 Members of :attr:`method_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100703 unpacked as tuples to get at the individual arguments. See
704 :ref:`calls as tuples <calls-as-tuples>`.
705
706
707 .. attribute:: mock_calls
708
Georg Brandl7ad3df62014-10-31 07:59:37 +0100709 :attr:`mock_calls` records *all* calls to the mock object, its methods,
710 magic methods *and* return value mocks.
Michael Foord944e02d2012-03-25 23:12:55 +0100711
712 >>> mock = MagicMock()
713 >>> result = mock(1, 2, 3)
714 >>> mock.first(a=3)
715 <MagicMock name='mock.first()' id='...'>
716 >>> mock.second()
717 <MagicMock name='mock.second()' id='...'>
718 >>> int(mock)
719 1
720 >>> result(1)
721 <MagicMock name='mock()()' id='...'>
722 >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
723 ... call.__int__(), call()(1)]
724 >>> mock.mock_calls == expected
725 True
726
Georg Brandl7ad3df62014-10-31 07:59:37 +0100727 Members of :attr:`mock_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100728 unpacked as tuples to get at the individual arguments. See
729 :ref:`calls as tuples <calls-as-tuples>`.
730
Chris Withers8ca0fa92018-12-03 21:31:37 +0000731 .. note::
732
733 The way :attr:`mock_calls` are recorded means that where nested
734 calls are made, the parameters of ancestor calls are not recorded
735 and so will always compare equal:
736
737 >>> mock = MagicMock()
738 >>> mock.top(a=3).bottom()
739 <MagicMock name='mock.top().bottom()' id='...'>
740 >>> mock.mock_calls
741 [call.top(a=3), call.top().bottom()]
742 >>> mock.mock_calls[-1] == call.top(a=-1).bottom()
743 True
Michael Foord944e02d2012-03-25 23:12:55 +0100744
745 .. attribute:: __class__
746
Georg Brandl7ad3df62014-10-31 07:59:37 +0100747 Normally the :attr:`__class__` attribute of an object will return its type.
748 For a mock object with a :attr:`spec`, ``__class__`` returns the spec class
749 instead. This allows mock objects to pass :func:`isinstance` tests for the
Michael Foord944e02d2012-03-25 23:12:55 +0100750 object they are replacing / masquerading as:
751
752 >>> mock = Mock(spec=3)
753 >>> isinstance(mock, int)
754 True
755
Georg Brandl7ad3df62014-10-31 07:59:37 +0100756 :attr:`__class__` is assignable to, this allows a mock to pass an
757 :func:`isinstance` check without forcing you to use a spec:
Michael Foord944e02d2012-03-25 23:12:55 +0100758
759 >>> mock = Mock()
760 >>> mock.__class__ = dict
761 >>> isinstance(mock, dict)
762 True
763
764.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
765
Georg Brandl7ad3df62014-10-31 07:59:37 +0100766 A non-callable version of :class:`Mock`. The constructor parameters have the same
767 meaning of :class:`Mock`, with the exception of *return_value* and *side_effect*
Michael Foord944e02d2012-03-25 23:12:55 +0100768 which have no meaning on a non-callable mock.
769
Georg Brandl7ad3df62014-10-31 07:59:37 +0100770Mock objects that use a class or an instance as a :attr:`spec` or
771:attr:`spec_set` are able to pass :func:`isinstance` tests:
Michael Foord944e02d2012-03-25 23:12:55 +0100772
773 >>> mock = Mock(spec=SomeClass)
774 >>> isinstance(mock, SomeClass)
775 True
776 >>> mock = Mock(spec_set=SomeClass())
777 >>> isinstance(mock, SomeClass)
778 True
779
Georg Brandl7ad3df62014-10-31 07:59:37 +0100780The :class:`Mock` classes have support for mocking magic methods. See :ref:`magic
Michael Foord944e02d2012-03-25 23:12:55 +0100781methods <magic-methods>` for the full details.
782
783The mock classes and the :func:`patch` decorators all take arbitrary keyword
Georg Brandl7ad3df62014-10-31 07:59:37 +0100784arguments for configuration. For the :func:`patch` decorators the keywords are
Michael Foord944e02d2012-03-25 23:12:55 +0100785passed to the constructor of the mock being created. The keyword arguments
786are for configuring attributes of the mock:
787
788 >>> m = MagicMock(attribute=3, other='fish')
789 >>> m.attribute
790 3
791 >>> m.other
792 'fish'
793
794The return value and side effect of child mocks can be set in the same way,
795using dotted notation. As you can't use dotted names directly in a call you
Georg Brandl7ad3df62014-10-31 07:59:37 +0100796have to create a dictionary and unpack it using ``**``:
Michael Foord944e02d2012-03-25 23:12:55 +0100797
798 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
799 >>> mock = Mock(some_attribute='eggs', **attrs)
800 >>> mock.some_attribute
801 'eggs'
802 >>> mock.method()
803 3
804 >>> mock.other()
805 Traceback (most recent call last):
806 ...
807 KeyError
808
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100809A callable mock which was created with a *spec* (or a *spec_set*) will
810introspect the specification object's signature when matching calls to
811the mock. Therefore, it can match the actual call's arguments regardless
812of whether they were passed positionally or by name::
813
814 >>> def f(a, b, c): pass
815 ...
816 >>> mock = Mock(spec=f)
817 >>> mock(1, 2, c=3)
818 <Mock name='mock()' id='140161580456576'>
819 >>> mock.assert_called_with(1, 2, 3)
820 >>> mock.assert_called_with(a=1, b=2, c=3)
821
822This applies to :meth:`~Mock.assert_called_with`,
823:meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and
824:meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also
825apply to method calls on the mock object.
826
827 .. versionchanged:: 3.4
828 Added signature introspection on specced and autospecced mock objects.
829
Michael Foord944e02d2012-03-25 23:12:55 +0100830
831.. class:: PropertyMock(*args, **kwargs)
832
833 A mock intended to be used as a property, or other descriptor, on a class.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100834 :class:`PropertyMock` provides :meth:`__get__` and :meth:`__set__` methods
835 so you can specify a return value when it is fetched.
Michael Foord944e02d2012-03-25 23:12:55 +0100836
Georg Brandl7ad3df62014-10-31 07:59:37 +0100837 Fetching a :class:`PropertyMock` instance from an object calls the mock, with
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200838 no args. Setting it calls the mock with the value being set. ::
Michael Foord944e02d2012-03-25 23:12:55 +0100839
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200840 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100841 ... @property
842 ... def foo(self):
843 ... return 'something'
844 ... @foo.setter
845 ... def foo(self, value):
846 ... pass
847 ...
848 >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
849 ... mock_foo.return_value = 'mockity-mock'
850 ... this_foo = Foo()
Berker Peksag920f6db2015-09-10 21:41:15 +0300851 ... print(this_foo.foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100852 ... this_foo.foo = 6
853 ...
854 mockity-mock
855 >>> mock_foo.mock_calls
856 [call(), call(6)]
857
Michael Foordc2870622012-04-13 16:57:22 +0100858Because of the way mock attributes are stored you can't directly attach a
Georg Brandl7ad3df62014-10-31 07:59:37 +0100859:class:`PropertyMock` to a mock object. Instead you can attach it to the mock type
Michael Foordc2870622012-04-13 16:57:22 +0100860object::
861
862 >>> m = MagicMock()
863 >>> p = PropertyMock(return_value=3)
864 >>> type(m).foo = p
865 >>> m.foo
866 3
867 >>> p.assert_called_once_with()
868
Michael Foord944e02d2012-03-25 23:12:55 +0100869
Lisa Roach77b3b772019-05-20 09:19:53 -0700870.. class:: AsyncMock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs)
871
872 An asynchronous version of :class:`Mock`. The :class:`AsyncMock` object will
873 behave so the object is recognized as an async function, and the result of a
874 call is an awaitable.
875
876 >>> mock = AsyncMock()
877 >>> asyncio.iscoroutinefunction(mock)
878 True
Xtreake7cb23b2019-05-21 14:17:17 +0530879 >>> inspect.isawaitable(mock()) # doctest: +SKIP
Lisa Roach77b3b772019-05-20 09:19:53 -0700880 True
881
882 The result of ``mock()`` is an async function which will have the outcome
883 of ``side_effect`` or ``return_value``:
884
885 - if ``side_effect`` is a function, the async function will return the
886 result of that function,
887 - if ``side_effect`` is an exception, the async function will raise the
888 exception,
889 - if ``side_effect`` is an iterable, the async function will return the
890 next value of the iterable, however, if the sequence of result is
891 exhausted, ``StopIteration`` is raised immediately,
892 - if ``side_effect`` is not defined, the async function will return the
893 value defined by ``return_value``, hence, by default, the async function
894 returns a new :class:`AsyncMock` object.
895
896
897 Setting the *spec* of a :class:`Mock` or :class:`MagicMock` to an async function
898 will result in a coroutine object being returned after calling.
899
900 >>> async def async_func(): pass
901 ...
902 >>> mock = MagicMock(async_func)
903 >>> mock
904 <MagicMock spec='function' id='...'>
Xtreake7cb23b2019-05-21 14:17:17 +0530905 >>> mock() # doctest: +SKIP
Lisa Roach77b3b772019-05-20 09:19:53 -0700906 <coroutine object AsyncMockMixin._mock_call at ...>
907
908 .. method:: assert_awaited()
909
910 Assert that the mock was awaited at least once.
911
912 >>> mock = AsyncMock()
913 >>> async def main():
914 ... await mock()
915 ...
916 >>> asyncio.run(main())
917 >>> mock.assert_awaited()
918 >>> mock_2 = AsyncMock()
919 >>> mock_2.assert_awaited()
920 Traceback (most recent call last):
921 ...
922 AssertionError: Expected mock to have been awaited.
923
924 .. method:: assert_awaited_once()
925
926 Assert that the mock was awaited exactly once.
927
928 >>> mock = AsyncMock()
929 >>> async def main():
930 ... await mock()
931 ...
932 >>> asyncio.run(main())
933 >>> mock.assert_awaited_once()
934 >>> asyncio.run(main())
935 >>> mock.method.assert_awaited_once()
936 Traceback (most recent call last):
937 ...
938 AssertionError: Expected mock to have been awaited once. Awaited 2 times.
939
940 .. method:: assert_awaited_with(*args, **kwargs)
941
942 Assert that the last await was with the specified arguments.
943
944 >>> mock = AsyncMock()
945 >>> async def main(*args, **kwargs):
946 ... await mock(*args, **kwargs)
947 ...
948 >>> asyncio.run(main('foo', bar='bar'))
949 >>> mock.assert_awaited_with('foo', bar='bar')
950 >>> mock.assert_awaited_with('other')
951 Traceback (most recent call last):
952 ...
953 AssertionError: expected call not found.
954 Expected: mock('other')
955 Actual: mock('foo', bar='bar')
956
957 .. method:: assert_awaited_once_with(*args, **kwargs)
958
959 Assert that the mock was awaited exactly once and with the specified
960 arguments.
961
962 >>> mock = AsyncMock()
963 >>> async def main(*args, **kwargs):
964 ... await mock(*args, **kwargs)
965 ...
966 >>> asyncio.run(main('foo', bar='bar'))
967 >>> mock.assert_awaited_once_with('foo', bar='bar')
968 >>> asyncio.run(main('foo', bar='bar'))
969 >>> mock.assert_awaited_once_with('foo', bar='bar')
970 Traceback (most recent call last):
971 ...
972 AssertionError: Expected mock to have been awaited once. Awaited 2 times.
973
974 .. method:: assert_any_await(*args, **kwargs)
975
976 Assert the mock has ever been awaited with the specified arguments.
977
978 >>> mock = AsyncMock()
979 >>> async def main(*args, **kwargs):
980 ... await mock(*args, **kwargs)
981 ...
982 >>> asyncio.run(main('foo', bar='bar'))
983 >>> asyncio.run(main('hello'))
984 >>> mock.assert_any_await('foo', bar='bar')
985 >>> mock.assert_any_await('other')
986 Traceback (most recent call last):
987 ...
988 AssertionError: mock('other') await not found
989
990 .. method:: assert_has_awaits(calls, any_order=False)
991
992 Assert the mock has been awaited with the specified calls.
993 The :attr:`await_args_list` list is checked for the awaits.
994
995 If *any_order* is False (the default) then the awaits must be
996 sequential. There can be extra calls before or after the
997 specified awaits.
998
999 If *any_order* is True then the awaits can be in any order, but
1000 they must all appear in :attr:`await_args_list`.
1001
1002 >>> mock = AsyncMock()
1003 >>> async def main(*args, **kwargs):
1004 ... await mock(*args, **kwargs)
1005 ...
1006 >>> calls = [call("foo"), call("bar")]
1007 >>> mock.assert_has_calls(calls)
1008 Traceback (most recent call last):
1009 ...
1010 AssertionError: Calls not found.
1011 Expected: [call('foo'), call('bar')]
1012 >>> asyncio.run(main('foo'))
1013 >>> asyncio.run(main('bar'))
1014 >>> mock.assert_has_calls(calls)
1015
1016 .. method:: assert_not_awaited()
1017
1018 Assert that the mock was never awaited.
1019
1020 >>> mock = AsyncMock()
1021 >>> mock.assert_not_awaited()
1022
1023 .. method:: reset_mock(*args, **kwargs)
1024
1025 See :func:`Mock.reset_mock`. Also sets :attr:`await_count` to 0,
1026 :attr:`await_args` to None, and clears the :attr:`await_args_list`.
1027
1028 .. attribute:: await_count
1029
1030 An integer keeping track of how many times the mock object has been awaited.
1031
1032 >>> mock = AsyncMock()
1033 >>> async def main():
1034 ... await mock()
1035 ...
1036 >>> asyncio.run(main())
1037 >>> mock.await_count
1038 1
1039 >>> asyncio.run(main())
1040 >>> mock.await_count
1041 2
1042
1043 .. attribute:: await_args
1044
1045 This is either ``None`` (if the mock hasn’t been awaited), or the arguments that
1046 the mock was last awaited with. Functions the same as :attr:`Mock.call_args`.
1047
1048 >>> mock = AsyncMock()
1049 >>> async def main(*args):
1050 ... await mock(*args)
1051 ...
1052 >>> mock.await_args
1053 >>> asyncio.run(main('foo'))
1054 >>> mock.await_args
1055 call('foo')
1056 >>> asyncio.run(main('bar'))
1057 >>> mock.await_args
1058 call('bar')
1059
1060
1061 .. attribute:: await_args_list
1062
1063 This is a list of all the awaits made to the mock object in sequence (so the
1064 length of the list is the number of times it has been awaited). Before any
1065 awaits have been made it is an empty list.
1066
1067 >>> mock = AsyncMock()
1068 >>> async def main(*args):
1069 ... await mock(*args)
1070 ...
1071 >>> mock.await_args_list
1072 []
1073 >>> asyncio.run(main('foo'))
1074 >>> mock.await_args_list
1075 [call('foo')]
1076 >>> asyncio.run(main('bar'))
1077 >>> mock.await_args_list
1078 [call('foo'), call('bar')]
1079
1080
Michael Foord944e02d2012-03-25 23:12:55 +01001081Calling
1082~~~~~~~
1083
1084Mock objects are callable. The call will return the value set as the
1085:attr:`~Mock.return_value` attribute. The default return value is a new Mock
1086object; it is created the first time the return value is accessed (either
1087explicitly or by calling the Mock) - but it is stored and the same one
1088returned each time.
1089
1090Calls made to the object will be recorded in the attributes
1091like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
1092
1093If :attr:`~Mock.side_effect` is set then it will be called after the call has
Georg Brandl7ad3df62014-10-31 07:59:37 +01001094been recorded, so if :attr:`side_effect` raises an exception the call is still
Michael Foord944e02d2012-03-25 23:12:55 +01001095recorded.
1096
1097The simplest way to make a mock raise an exception when called is to make
1098:attr:`~Mock.side_effect` an exception class or instance:
1099
1100 >>> m = MagicMock(side_effect=IndexError)
1101 >>> m(1, 2, 3)
1102 Traceback (most recent call last):
1103 ...
1104 IndexError
1105 >>> m.mock_calls
1106 [call(1, 2, 3)]
1107 >>> m.side_effect = KeyError('Bang!')
1108 >>> m('two', 'three', 'four')
1109 Traceback (most recent call last):
1110 ...
1111 KeyError: 'Bang!'
1112 >>> m.mock_calls
1113 [call(1, 2, 3), call('two', 'three', 'four')]
1114
Georg Brandl7ad3df62014-10-31 07:59:37 +01001115If :attr:`side_effect` is a function then whatever that function returns is what
1116calls to the mock return. The :attr:`side_effect` function is called with the
Michael Foord944e02d2012-03-25 23:12:55 +01001117same arguments as the mock. This allows you to vary the return value of the
1118call dynamically, based on the input:
1119
1120 >>> def side_effect(value):
1121 ... return value + 1
1122 ...
1123 >>> m = MagicMock(side_effect=side_effect)
1124 >>> m(1)
1125 2
1126 >>> m(2)
1127 3
1128 >>> m.mock_calls
1129 [call(1), call(2)]
1130
1131If you want the mock to still return the default return value (a new mock), or
1132any set return value, then there are two ways of doing this. Either return
Georg Brandl7ad3df62014-10-31 07:59:37 +01001133:attr:`mock.return_value` from inside :attr:`side_effect`, or return :data:`DEFAULT`:
Michael Foord944e02d2012-03-25 23:12:55 +01001134
1135 >>> m = MagicMock()
1136 >>> def side_effect(*args, **kwargs):
1137 ... return m.return_value
1138 ...
1139 >>> m.side_effect = side_effect
1140 >>> m.return_value = 3
1141 >>> m()
1142 3
1143 >>> def side_effect(*args, **kwargs):
1144 ... return DEFAULT
1145 ...
1146 >>> m.side_effect = side_effect
1147 >>> m()
1148 3
1149
Georg Brandl7ad3df62014-10-31 07:59:37 +01001150To remove a :attr:`side_effect`, and return to the default behaviour, set the
1151:attr:`side_effect` to ``None``:
Michael Foord944e02d2012-03-25 23:12:55 +01001152
1153 >>> m = MagicMock(return_value=6)
1154 >>> def side_effect(*args, **kwargs):
1155 ... return 3
1156 ...
1157 >>> m.side_effect = side_effect
1158 >>> m()
1159 3
1160 >>> m.side_effect = None
1161 >>> m()
1162 6
1163
Georg Brandl7ad3df62014-10-31 07:59:37 +01001164The :attr:`side_effect` can also be any iterable object. Repeated calls to the mock
Michael Foord944e02d2012-03-25 23:12:55 +01001165will return values from the iterable (until the iterable is exhausted and
Georg Brandl7ad3df62014-10-31 07:59:37 +01001166a :exc:`StopIteration` is raised):
Michael Foord944e02d2012-03-25 23:12:55 +01001167
1168 >>> m = MagicMock(side_effect=[1, 2, 3])
1169 >>> m()
1170 1
1171 >>> m()
1172 2
1173 >>> m()
1174 3
1175 >>> m()
1176 Traceback (most recent call last):
1177 ...
1178 StopIteration
1179
Michael Foord2cd48732012-04-21 15:52:11 +01001180If any members of the iterable are exceptions they will be raised instead of
1181returned::
1182
1183 >>> iterable = (33, ValueError, 66)
1184 >>> m = MagicMock(side_effect=iterable)
1185 >>> m()
1186 33
1187 >>> m()
1188 Traceback (most recent call last):
1189 ...
1190 ValueError
1191 >>> m()
1192 66
1193
Michael Foord944e02d2012-03-25 23:12:55 +01001194
1195.. _deleting-attributes:
1196
1197Deleting Attributes
1198~~~~~~~~~~~~~~~~~~~
1199
1200Mock objects create attributes on demand. This allows them to pretend to be
1201objects of any type.
1202
Georg Brandl7ad3df62014-10-31 07:59:37 +01001203You may want a mock object to return ``False`` to a :func:`hasattr` call, or raise an
1204:exc:`AttributeError` when an attribute is fetched. You can do this by providing
1205an object as a :attr:`spec` for a mock, but that isn't always convenient.
Michael Foord944e02d2012-03-25 23:12:55 +01001206
1207You "block" attributes by deleting them. Once deleted, accessing an attribute
Georg Brandl7ad3df62014-10-31 07:59:37 +01001208will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +01001209
1210 >>> mock = MagicMock()
1211 >>> hasattr(mock, 'm')
1212 True
1213 >>> del mock.m
1214 >>> hasattr(mock, 'm')
1215 False
1216 >>> del mock.f
1217 >>> mock.f
1218 Traceback (most recent call last):
1219 ...
1220 AttributeError: f
1221
1222
Michael Foordf5752302013-03-18 15:04:03 -07001223Mock names and the name attribute
1224~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1225
1226Since "name" is an argument to the :class:`Mock` constructor, if you want your
1227mock object to have a "name" attribute you can't just pass it in at creation
1228time. There are two alternatives. One option is to use
1229:meth:`~Mock.configure_mock`::
1230
1231 >>> mock = MagicMock()
1232 >>> mock.configure_mock(name='my_name')
1233 >>> mock.name
1234 'my_name'
1235
1236A simpler option is to simply set the "name" attribute after mock creation::
1237
1238 >>> mock = MagicMock()
1239 >>> mock.name = "foo"
1240
1241
Michael Foord944e02d2012-03-25 23:12:55 +01001242Attaching Mocks as Attributes
1243~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1244
1245When you attach a mock as an attribute of another mock (or as the return
1246value) it becomes a "child" of that mock. Calls to the child are recorded in
1247the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
1248parent. This is useful for configuring child mocks and then attaching them to
1249the parent, or for attaching mocks to a parent that records all calls to the
1250children and allows you to make assertions about the order of calls between
1251mocks:
1252
1253 >>> parent = MagicMock()
1254 >>> child1 = MagicMock(return_value=None)
1255 >>> child2 = MagicMock(return_value=None)
1256 >>> parent.child1 = child1
1257 >>> parent.child2 = child2
1258 >>> child1(1)
1259 >>> child2(2)
1260 >>> parent.mock_calls
1261 [call.child1(1), call.child2(2)]
1262
1263The exception to this is if the mock has a name. This allows you to prevent
1264the "parenting" if for some reason you don't want it to happen.
1265
1266 >>> mock = MagicMock()
1267 >>> not_a_child = MagicMock(name='not-a-child')
1268 >>> mock.attribute = not_a_child
1269 >>> mock.attribute()
1270 <MagicMock name='not-a-child()' id='...'>
1271 >>> mock.mock_calls
1272 []
1273
1274Mocks created for you by :func:`patch` are automatically given names. To
1275attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001276method::
Michael Foord944e02d2012-03-25 23:12:55 +01001277
1278 >>> thing1 = object()
1279 >>> thing2 = object()
1280 >>> parent = MagicMock()
1281 >>> with patch('__main__.thing1', return_value=None) as child1:
1282 ... with patch('__main__.thing2', return_value=None) as child2:
1283 ... parent.attach_mock(child1, 'child1')
1284 ... parent.attach_mock(child2, 'child2')
1285 ... child1('one')
1286 ... child2('two')
1287 ...
1288 >>> parent.mock_calls
1289 [call.child1('one'), call.child2('two')]
1290
1291
1292.. [#] The only exceptions are magic methods and attributes (those that have
1293 leading and trailing double underscores). Mock doesn't create these but
Georg Brandl7ad3df62014-10-31 07:59:37 +01001294 instead raises an :exc:`AttributeError`. This is because the interpreter
Michael Foord944e02d2012-03-25 23:12:55 +01001295 will often implicitly request these methods, and gets *very* confused to
1296 get a new Mock object when it expects a magic method. If you need magic
1297 method support see :ref:`magic methods <magic-methods>`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001298
1299
1300The patchers
Georg Brandlfb134382013-02-03 11:47:49 +01001301------------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001302
1303The patch decorators are used for patching objects only within the scope of
1304the function they decorate. They automatically handle the unpatching for you,
1305even if exceptions are raised. All of these functions can also be used in with
1306statements or as class decorators.
1307
1308
1309patch
Georg Brandlfb134382013-02-03 11:47:49 +01001310~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001311
1312.. note::
1313
Georg Brandl7ad3df62014-10-31 07:59:37 +01001314 :func:`patch` is straightforward to use. The key is to do the patching in the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001315 right namespace. See the section `where to patch`_.
1316
1317.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1318
Georg Brandl7ad3df62014-10-31 07:59:37 +01001319 :func:`patch` acts as a function decorator, class decorator or a context
1320 manager. Inside the body of the function or with statement, the *target*
1321 is patched with a *new* object. When the function/with statement exits
Michael Foord54b3db82012-03-28 15:08:08 +01001322 the patch is undone.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001323
Mario Corcherof5e7f392019-09-09 15:18:06 +01001324 If *new* is omitted, then the target is replaced with an
1325 :class:`AsyncMock` if the patched object is an async function or
1326 a :class:`MagicMock` otherwise.
1327 If :func:`patch` is used as a decorator and *new* is
Michael Foord54b3db82012-03-28 15:08:08 +01001328 omitted, the created mock is passed in as an extra argument to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001329 decorated function. If :func:`patch` is used as a context manager the created
Michael Foord54b3db82012-03-28 15:08:08 +01001330 mock is returned by the context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001331
Georg Brandl7ad3df62014-10-31 07:59:37 +01001332 *target* should be a string in the form ``'package.module.ClassName'``. The
1333 *target* is imported and the specified object replaced with the *new*
1334 object, so the *target* must be importable from the environment you are
1335 calling :func:`patch` from. The target is imported when the decorated function
Michael Foord54b3db82012-03-28 15:08:08 +01001336 is executed, not at decoration time.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001337
Georg Brandl7ad3df62014-10-31 07:59:37 +01001338 The *spec* and *spec_set* keyword arguments are passed to the :class:`MagicMock`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001339 if patch is creating one for you.
1340
Georg Brandl7ad3df62014-10-31 07:59:37 +01001341 In addition you can pass ``spec=True`` or ``spec_set=True``, which causes
Michael Foorda9e6fb22012-03-28 14:36:02 +01001342 patch to pass in the object being mocked as the spec/spec_set object.
1343
Georg Brandl7ad3df62014-10-31 07:59:37 +01001344 *new_callable* allows you to specify a different class, or callable object,
Mario Corcherof5e7f392019-09-09 15:18:06 +01001345 that will be called to create the *new* object. By default :class:`AsyncMock`
1346 is used for async functions and :class:`MagicMock` for the rest.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001347
Georg Brandl7ad3df62014-10-31 07:59:37 +01001348 A more powerful form of *spec* is *autospec*. If you set ``autospec=True``
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001349 then the mock will be created with a spec from the object being replaced.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001350 All attributes of the mock will also have the spec of the corresponding
1351 attribute of the object being replaced. Methods and functions being mocked
Georg Brandl7ad3df62014-10-31 07:59:37 +01001352 will have their arguments checked and will raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001353 called with the wrong signature. For mocks
1354 replacing a class, their return value (the 'instance') will have the same
1355 spec as the class. See the :func:`create_autospec` function and
1356 :ref:`auto-speccing`.
1357
Georg Brandl7ad3df62014-10-31 07:59:37 +01001358 Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001359 arbitrary object as the spec instead of the one being replaced.
1360
Pablo Galindod6acf172019-01-09 21:43:24 +00001361 By default :func:`patch` will fail to replace attributes that don't exist.
1362 If you pass in ``create=True``, and the attribute doesn't exist, patch will
1363 create the attribute for you when the patched function is called, and delete
1364 it again after the patched function has exited. This is useful for writing
1365 tests against attributes that your production code creates at runtime. It is
1366 off by default because it can be dangerous. With it switched on you can
1367 write passing tests against APIs that don't actually exist!
Michael Foorda9e6fb22012-03-28 14:36:02 +01001368
Michael Foordfddcfa22014-04-14 16:25:20 -04001369 .. note::
1370
1371 .. versionchanged:: 3.5
1372 If you are patching builtins in a module then you don't
Georg Brandl7ad3df62014-10-31 07:59:37 +01001373 need to pass ``create=True``, it will be added by default.
Michael Foordfddcfa22014-04-14 16:25:20 -04001374
Georg Brandl7ad3df62014-10-31 07:59:37 +01001375 Patch can be used as a :class:`TestCase` class decorator. It works by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001376 decorating each test method in the class. This reduces the boilerplate
Georg Brandl7ad3df62014-10-31 07:59:37 +01001377 code when your test methods share a common patchings set. :func:`patch` finds
1378 tests by looking for method names that start with ``patch.TEST_PREFIX``.
1379 By default this is ``'test'``, which matches the way :mod:`unittest` finds tests.
1380 You can specify an alternative prefix by setting ``patch.TEST_PREFIX``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001381
1382 Patch can be used as a context manager, with the with statement. Here the
1383 patching applies to the indented block after the with statement. If you
1384 use "as" then the patched object will be bound to the name after the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001385 "as"; very useful if :func:`patch` is creating a mock object for you.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001386
Georg Brandl7ad3df62014-10-31 07:59:37 +01001387 :func:`patch` takes arbitrary keyword arguments. These will be passed to
1388 the :class:`Mock` (or *new_callable*) on construction.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001389
Georg Brandl7ad3df62014-10-31 07:59:37 +01001390 ``patch.dict(...)``, ``patch.multiple(...)`` and ``patch.object(...)`` are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001391 available for alternate use-cases.
1392
Georg Brandl7ad3df62014-10-31 07:59:37 +01001393:func:`patch` as function decorator, creating the mock for you and passing it into
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001394the decorated function::
Michael Foord90155362012-03-28 15:32:08 +01001395
1396 >>> @patch('__main__.SomeClass')
Michael Foord324b58b2012-03-28 15:49:08 +01001397 ... def function(normal_argument, mock_class):
Michael Foord90155362012-03-28 15:32:08 +01001398 ... print(mock_class is SomeClass)
1399 ...
Michael Foord324b58b2012-03-28 15:49:08 +01001400 >>> function(None)
Michael Foord90155362012-03-28 15:32:08 +01001401 True
Michael Foorda9e6fb22012-03-28 14:36:02 +01001402
Georg Brandl7ad3df62014-10-31 07:59:37 +01001403Patching a class replaces the class with a :class:`MagicMock` *instance*. If the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001404class is instantiated in the code under test then it will be the
1405:attr:`~Mock.return_value` of the mock that will be used.
1406
1407If the class is instantiated multiple times you could use
1408:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
Georg Brandl7ad3df62014-10-31 07:59:37 +01001409can set the *return_value* to be anything you want.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001410
1411To configure return values on methods of *instances* on the patched class
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001412you must do this on the :attr:`return_value`. For example::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001413
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001414 >>> class Class:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001415 ... def method(self):
1416 ... pass
1417 ...
1418 >>> with patch('__main__.Class') as MockClass:
1419 ... instance = MockClass.return_value
1420 ... instance.method.return_value = 'foo'
1421 ... assert Class() is instance
1422 ... assert Class().method() == 'foo'
1423 ...
1424
Georg Brandl7ad3df62014-10-31 07:59:37 +01001425If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001426return value of the created mock will have the same spec. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001427
1428 >>> Original = Class
1429 >>> patcher = patch('__main__.Class', spec=True)
1430 >>> MockClass = patcher.start()
1431 >>> instance = MockClass()
1432 >>> assert isinstance(instance, Original)
1433 >>> patcher.stop()
1434
Georg Brandl7ad3df62014-10-31 07:59:37 +01001435The *new_callable* argument is useful where you want to use an alternative
Michael Foorda9e6fb22012-03-28 14:36:02 +01001436class to the default :class:`MagicMock` for the created mock. For example, if
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001437you wanted a :class:`NonCallableMock` to be used::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001438
1439 >>> thing = object()
1440 >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
1441 ... assert thing is mock_thing
1442 ... thing()
1443 ...
1444 Traceback (most recent call last):
1445 ...
1446 TypeError: 'NonCallableMock' object is not callable
1447
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001448Another use case might be to replace an object with an :class:`io.StringIO` instance::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001449
Serhiy Storchakae79be872013-08-17 00:09:55 +03001450 >>> from io import StringIO
Michael Foorda9e6fb22012-03-28 14:36:02 +01001451 >>> def foo():
Berker Peksag920f6db2015-09-10 21:41:15 +03001452 ... print('Something')
Michael Foorda9e6fb22012-03-28 14:36:02 +01001453 ...
1454 >>> @patch('sys.stdout', new_callable=StringIO)
1455 ... def test(mock_stdout):
1456 ... foo()
1457 ... assert mock_stdout.getvalue() == 'Something\n'
1458 ...
1459 >>> test()
1460
Georg Brandl7ad3df62014-10-31 07:59:37 +01001461When :func:`patch` is creating a mock for you, it is common that the first thing
Michael Foorda9e6fb22012-03-28 14:36:02 +01001462you need to do is to configure the mock. Some of that configuration can be done
1463in the call to patch. Any arbitrary keywords you pass into the call will be
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001464used to set attributes on the created mock::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001465
1466 >>> patcher = patch('__main__.thing', first='one', second='two')
1467 >>> mock_thing = patcher.start()
1468 >>> mock_thing.first
1469 'one'
1470 >>> mock_thing.second
1471 'two'
1472
1473As well as attributes on the created mock attributes, like the
1474:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
1475also be configured. These aren't syntactically valid to pass in directly as
1476keyword arguments, but a dictionary with these as keys can still be expanded
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001477into a :func:`patch` call using ``**``::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001478
1479 >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
1480 >>> patcher = patch('__main__.thing', **config)
1481 >>> mock_thing = patcher.start()
1482 >>> mock_thing.method()
1483 3
1484 >>> mock_thing.other()
1485 Traceback (most recent call last):
1486 ...
1487 KeyError
1488
Pablo Galindod6acf172019-01-09 21:43:24 +00001489By default, attempting to patch a function in a module (or a method or an
1490attribute in a class) that does not exist will fail with :exc:`AttributeError`::
1491
1492 >>> @patch('sys.non_existing_attribute', 42)
1493 ... def test():
1494 ... assert sys.non_existing_attribute == 42
1495 ...
1496 >>> test()
1497 Traceback (most recent call last):
1498 ...
1499 AttributeError: <module 'sys' (built-in)> does not have the attribute 'non_existing'
1500
1501but adding ``create=True`` in the call to :func:`patch` will make the previous example
1502work as expected::
1503
1504 >>> @patch('sys.non_existing_attribute', 42, create=True)
1505 ... def test(mock_stdout):
1506 ... assert sys.non_existing_attribute == 42
1507 ...
1508 >>> test()
1509
Mario Corcherof5e7f392019-09-09 15:18:06 +01001510.. versionchanged:: 3.8
1511
1512 :func:`patch` now returns an :class:`AsyncMock` if the target is an async function.
1513
Michael Foorda9e6fb22012-03-28 14:36:02 +01001514
1515patch.object
Georg Brandlfb134382013-02-03 11:47:49 +01001516~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001517
1518.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1519
Georg Brandl7ad3df62014-10-31 07:59:37 +01001520 patch the named member (*attribute*) on an object (*target*) with a mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001521 object.
1522
Georg Brandl7ad3df62014-10-31 07:59:37 +01001523 :func:`patch.object` can be used as a decorator, class decorator or a context
1524 manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* and
1525 *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`,
1526 :func:`patch.object` takes arbitrary keyword arguments for configuring the mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001527 object it creates.
1528
Georg Brandl7ad3df62014-10-31 07:59:37 +01001529 When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001530 for choosing which methods to wrap.
1531
Georg Brandl7ad3df62014-10-31 07:59:37 +01001532You can either call :func:`patch.object` with three arguments or two arguments. The
Michael Foorda9e6fb22012-03-28 14:36:02 +01001533three argument form takes the object to be patched, the attribute name and the
1534object to replace the attribute with.
1535
1536When calling with the two argument form you omit the replacement object, and a
1537mock is created for you and passed in as an extra argument to the decorated
1538function:
1539
1540 >>> @patch.object(SomeClass, 'class_method')
1541 ... def test(mock_method):
1542 ... SomeClass.class_method(3)
1543 ... mock_method.assert_called_with(3)
1544 ...
1545 >>> test()
1546
Georg Brandl7ad3df62014-10-31 07:59:37 +01001547*spec*, *create* and the other arguments to :func:`patch.object` have the same
1548meaning as they do for :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001549
1550
1551patch.dict
Georg Brandlfb134382013-02-03 11:47:49 +01001552~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001553
1554.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs)
1555
1556 Patch a dictionary, or dictionary like object, and restore the dictionary
1557 to its original state after the test.
1558
Georg Brandl7ad3df62014-10-31 07:59:37 +01001559 *in_dict* can be a dictionary or a mapping like container. If it is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01001560 mapping then it must at least support getting, setting and deleting items
1561 plus iterating over keys.
1562
Georg Brandl7ad3df62014-10-31 07:59:37 +01001563 *in_dict* can also be a string specifying the name of the dictionary, which
Michael Foorda9e6fb22012-03-28 14:36:02 +01001564 will then be fetched by importing it.
1565
Georg Brandl7ad3df62014-10-31 07:59:37 +01001566 *values* can be a dictionary of values to set in the dictionary. *values*
1567 can also be an iterable of ``(key, value)`` pairs.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001568
Georg Brandl7ad3df62014-10-31 07:59:37 +01001569 If *clear* is true then the dictionary will be cleared before the new
Michael Foorda9e6fb22012-03-28 14:36:02 +01001570 values are set.
1571
Georg Brandl7ad3df62014-10-31 07:59:37 +01001572 :func:`patch.dict` can also be called with arbitrary keyword arguments to set
Michael Foorda9e6fb22012-03-28 14:36:02 +01001573 values in the dictionary.
1574
Mario Corchero04530812019-05-28 13:53:31 +01001575 .. versionchanged:: 3.8
1576
1577 :func:`patch.dict` now returns the patched dictionary when used as a context
1578 manager.
1579
Emmanuel Arias31a82e22019-09-12 08:29:54 -03001580:func:`patch.dict` can be used as a context manager, decorator or class
1581decorator:
1582
1583 >>> foo = {}
1584 >>> @patch.dict(foo, {'newkey': 'newvalue'})
1585 ... def test():
1586 ... assert foo == {'newkey': 'newvalue'}
1587 >>> test()
1588 >>> assert foo == {}
1589
1590When used as a class decorator :func:`patch.dict` honours
1591``patch.TEST_PREFIX`` (default to ``'test'``) for choosing which methods to wrap:
1592
1593 >>> import os
1594 >>> import unittest
1595 >>> from unittest.mock import patch
1596 >>> @patch.dict('os.environ', {'newkey': 'newvalue'})
1597 ... class TestSample(unittest.TestCase):
1598 ... def test_sample(self):
1599 ... self.assertEqual(os.environ['newkey'], 'newvalue')
1600
1601If you want to use a different prefix for your test, you can inform the
1602patchers of the different prefix by setting ``patch.TEST_PREFIX``. For
1603more details about how to change the value of see :ref:`test-prefix`.
1604
Georg Brandl7ad3df62014-10-31 07:59:37 +01001605:func:`patch.dict` can be used to add members to a dictionary, or simply let a test
Michael Foorda9e6fb22012-03-28 14:36:02 +01001606change a dictionary, and ensure the dictionary is restored when the test
1607ends.
1608
1609 >>> foo = {}
Mario Corchero04530812019-05-28 13:53:31 +01001610 >>> with patch.dict(foo, {'newkey': 'newvalue'}) as patched_foo:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001611 ... assert foo == {'newkey': 'newvalue'}
Mario Corchero04530812019-05-28 13:53:31 +01001612 ... assert patched_foo == {'newkey': 'newvalue'}
1613 ... # You can add, update or delete keys of foo (or patched_foo, it's the same dict)
1614 ... patched_foo['spam'] = 'eggs'
Michael Foorda9e6fb22012-03-28 14:36:02 +01001615 ...
1616 >>> assert foo == {}
Mario Corchero04530812019-05-28 13:53:31 +01001617 >>> assert patched_foo == {}
Michael Foorda9e6fb22012-03-28 14:36:02 +01001618
1619 >>> import os
1620 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
Berker Peksag920f6db2015-09-10 21:41:15 +03001621 ... print(os.environ['newkey'])
Michael Foorda9e6fb22012-03-28 14:36:02 +01001622 ...
1623 newvalue
1624 >>> assert 'newkey' not in os.environ
1625
Georg Brandl7ad3df62014-10-31 07:59:37 +01001626Keywords can be used in the :func:`patch.dict` call to set values in the dictionary:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001627
1628 >>> mymodule = MagicMock()
1629 >>> mymodule.function.return_value = 'fish'
1630 >>> with patch.dict('sys.modules', mymodule=mymodule):
1631 ... import mymodule
1632 ... mymodule.function('some', 'args')
1633 ...
1634 'fish'
1635
Georg Brandl7ad3df62014-10-31 07:59:37 +01001636:func:`patch.dict` can be used with dictionary like objects that aren't actually
Michael Foorda9e6fb22012-03-28 14:36:02 +01001637dictionaries. At the very minimum they must support item getting, setting,
1638deleting and either iteration or membership test. This corresponds to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001639magic methods :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__` and either
1640:meth:`__iter__` or :meth:`__contains__`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001641
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001642 >>> class Container:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001643 ... def __init__(self):
1644 ... self.values = {}
1645 ... def __getitem__(self, name):
1646 ... return self.values[name]
1647 ... def __setitem__(self, name, value):
1648 ... self.values[name] = value
1649 ... def __delitem__(self, name):
1650 ... del self.values[name]
1651 ... def __iter__(self):
1652 ... return iter(self.values)
1653 ...
1654 >>> thing = Container()
1655 >>> thing['one'] = 1
1656 >>> with patch.dict(thing, one=2, two=3):
1657 ... assert thing['one'] == 2
1658 ... assert thing['two'] == 3
1659 ...
1660 >>> assert thing['one'] == 1
1661 >>> assert list(thing) == ['one']
1662
1663
1664patch.multiple
Georg Brandlfb134382013-02-03 11:47:49 +01001665~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001666
1667.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1668
1669 Perform multiple patches in a single call. It takes the object to be
1670 patched (either as an object or a string to fetch the object by importing)
1671 and keyword arguments for the patches::
1672
1673 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1674 ...
1675
Georg Brandl7ad3df62014-10-31 07:59:37 +01001676 Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create
Michael Foorda9e6fb22012-03-28 14:36:02 +01001677 mocks for you. In this case the created mocks are passed into a decorated
Georg Brandl7ad3df62014-10-31 07:59:37 +01001678 function by keyword, and a dictionary is returned when :func:`patch.multiple` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001679 used as a context manager.
1680
Georg Brandl7ad3df62014-10-31 07:59:37 +01001681 :func:`patch.multiple` can be used as a decorator, class decorator or a context
1682 manager. The arguments *spec*, *spec_set*, *create*, *autospec* and
1683 *new_callable* have the same meaning as for :func:`patch`. These arguments will
1684 be applied to *all* patches done by :func:`patch.multiple`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001685
Georg Brandl7ad3df62014-10-31 07:59:37 +01001686 When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001687 for choosing which methods to wrap.
1688
Georg Brandl7ad3df62014-10-31 07:59:37 +01001689If you want :func:`patch.multiple` to create mocks for you, then you can use
1690:data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001691then the created mocks are passed into the decorated function by keyword. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001692
1693 >>> thing = object()
1694 >>> other = object()
1695
1696 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1697 ... def test_function(thing, other):
1698 ... assert isinstance(thing, MagicMock)
1699 ... assert isinstance(other, MagicMock)
1700 ...
1701 >>> test_function()
1702
Georg Brandl7ad3df62014-10-31 07:59:37 +01001703:func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001704passed by keyword *after* any of the standard arguments created by :func:`patch`::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001705
1706 >>> @patch('sys.exit')
1707 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1708 ... def test_function(mock_exit, other, thing):
1709 ... assert 'other' in repr(other)
1710 ... assert 'thing' in repr(thing)
1711 ... assert 'exit' in repr(mock_exit)
1712 ...
1713 >>> test_function()
1714
Georg Brandl7ad3df62014-10-31 07:59:37 +01001715If :func:`patch.multiple` is used as a context manager, the value returned by the
Joan Massichdc69f692019-03-18 00:34:22 +01001716context manager is a dictionary where created mocks are keyed by name::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001717
1718 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
1719 ... assert 'other' in repr(values['other'])
1720 ... assert 'thing' in repr(values['thing'])
1721 ... assert values['thing'] is thing
1722 ... assert values['other'] is other
1723 ...
1724
1725
1726.. _start-and-stop:
1727
1728patch methods: start and stop
Georg Brandlfb134382013-02-03 11:47:49 +01001729~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001730
Georg Brandl7ad3df62014-10-31 07:59:37 +01001731All the patchers have :meth:`start` and :meth:`stop` methods. These make it simpler to do
1732patching in ``setUp`` methods or where you want to do multiple patches without
Michael Foorda9e6fb22012-03-28 14:36:02 +01001733nesting decorators or with statements.
1734
Georg Brandl7ad3df62014-10-31 07:59:37 +01001735To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as
1736normal and keep a reference to the returned ``patcher`` object. You can then
1737call :meth:`start` to put the patch in place and :meth:`stop` to undo it.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001738
Georg Brandl7ad3df62014-10-31 07:59:37 +01001739If 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 +02001740the call to ``patcher.start``. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001741
1742 >>> patcher = patch('package.module.ClassName')
1743 >>> from package import module
1744 >>> original = module.ClassName
1745 >>> new_mock = patcher.start()
1746 >>> assert module.ClassName is not original
1747 >>> assert module.ClassName is new_mock
1748 >>> patcher.stop()
1749 >>> assert module.ClassName is original
1750 >>> assert module.ClassName is not new_mock
1751
1752
Georg Brandl7ad3df62014-10-31 07:59:37 +01001753A typical use case for this might be for doing multiple patches in the ``setUp``
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001754method of a :class:`TestCase`::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001755
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001756 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +01001757 ... def setUp(self):
1758 ... self.patcher1 = patch('package.module.Class1')
1759 ... self.patcher2 = patch('package.module.Class2')
1760 ... self.MockClass1 = self.patcher1.start()
1761 ... self.MockClass2 = self.patcher2.start()
1762 ...
1763 ... def tearDown(self):
1764 ... self.patcher1.stop()
1765 ... self.patcher2.stop()
1766 ...
1767 ... def test_something(self):
1768 ... assert package.module.Class1 is self.MockClass1
1769 ... assert package.module.Class2 is self.MockClass2
1770 ...
1771 >>> MyTest('test_something').run()
1772
1773.. caution::
1774
1775 If you use this technique you must ensure that the patching is "undone" by
Georg Brandl7ad3df62014-10-31 07:59:37 +01001776 calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001777 exception is raised in the ``setUp`` then ``tearDown`` is not called.
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001778 :meth:`unittest.TestCase.addCleanup` makes this easier::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001779
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001780 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +01001781 ... def setUp(self):
1782 ... patcher = patch('package.module.Class')
1783 ... self.MockClass = patcher.start()
1784 ... self.addCleanup(patcher.stop)
1785 ...
1786 ... def test_something(self):
1787 ... assert package.module.Class is self.MockClass
1788 ...
1789
Georg Brandl7ad3df62014-10-31 07:59:37 +01001790 As an added bonus you no longer need to keep a reference to the ``patcher``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001791 object.
1792
Michael Foordf7c41582012-06-10 20:36:32 +01001793It is also possible to stop all patches which have been started by using
Georg Brandl7ad3df62014-10-31 07:59:37 +01001794:func:`patch.stopall`.
Michael Foordf7c41582012-06-10 20:36:32 +01001795
1796.. function:: patch.stopall
1797
Georg Brandl7ad3df62014-10-31 07:59:37 +01001798 Stop all active patches. Only stops patches started with ``start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001799
Georg Brandl7ad3df62014-10-31 07:59:37 +01001800
1801.. _patch-builtins:
Michael Foordfddcfa22014-04-14 16:25:20 -04001802
1803patch builtins
Georg Brandl7ad3df62014-10-31 07:59:37 +01001804~~~~~~~~~~~~~~
Michael Foordfddcfa22014-04-14 16:25:20 -04001805You can patch any builtins within a module. The following example patches
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001806builtin :func:`ord`::
Michael Foordfddcfa22014-04-14 16:25:20 -04001807
1808 >>> @patch('__main__.ord')
1809 ... def test(mock_ord):
1810 ... mock_ord.return_value = 101
1811 ... print(ord('c'))
1812 ...
1813 >>> test()
1814 101
1815
Michael Foorda9e6fb22012-03-28 14:36:02 +01001816
Emmanuel Arias31a82e22019-09-12 08:29:54 -03001817.. _test-prefix:
1818
Michael Foorda9e6fb22012-03-28 14:36:02 +01001819TEST_PREFIX
Georg Brandlfb134382013-02-03 11:47:49 +01001820~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001821
1822All of the patchers can be used as class decorators. When used in this way
1823they wrap every test method on the class. The patchers recognise methods that
Georg Brandl7ad3df62014-10-31 07:59:37 +01001824start with ``'test'`` as being test methods. This is the same way that the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001825:class:`unittest.TestLoader` finds test methods by default.
1826
1827It is possible that you want to use a different prefix for your tests. You can
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001828inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001829
1830 >>> patch.TEST_PREFIX = 'foo'
1831 >>> value = 3
1832 >>>
1833 >>> @patch('__main__.value', 'not three')
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001834 ... class Thing:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001835 ... def foo_one(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001836 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001837 ... def foo_two(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001838 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001839 ...
1840 >>>
1841 >>> Thing().foo_one()
1842 not three
1843 >>> Thing().foo_two()
1844 not three
1845 >>> value
1846 3
1847
1848
1849Nesting Patch Decorators
Georg Brandlfb134382013-02-03 11:47:49 +01001850~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001851
1852If you want to perform multiple patches then you can simply stack up the
1853decorators.
1854
1855You can stack up multiple patch decorators using this pattern:
1856
1857 >>> @patch.object(SomeClass, 'class_method')
1858 ... @patch.object(SomeClass, 'static_method')
1859 ... def test(mock1, mock2):
1860 ... assert SomeClass.static_method is mock1
1861 ... assert SomeClass.class_method is mock2
1862 ... SomeClass.static_method('foo')
1863 ... SomeClass.class_method('bar')
1864 ... return mock1, mock2
1865 ...
1866 >>> mock1, mock2 = test()
1867 >>> mock1.assert_called_once_with('foo')
1868 >>> mock2.assert_called_once_with('bar')
1869
1870
1871Note that the decorators are applied from the bottom upwards. This is the
1872standard way that Python applies decorators. The order of the created mocks
1873passed into your test function matches this order.
1874
1875
1876.. _where-to-patch:
1877
1878Where to patch
Georg Brandlfb134382013-02-03 11:47:49 +01001879~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001880
Georg Brandl7ad3df62014-10-31 07:59:37 +01001881:func:`patch` works by (temporarily) changing the object that a *name* points to with
Michael Foorda9e6fb22012-03-28 14:36:02 +01001882another one. There can be many names pointing to any individual object, so
1883for patching to work you must ensure that you patch the name used by the system
1884under test.
1885
1886The basic principle is that you patch where an object is *looked up*, which
1887is not necessarily the same place as where it is defined. A couple of
1888examples will help to clarify this.
1889
1890Imagine we have a project that we want to test with the following structure::
1891
1892 a.py
1893 -> Defines SomeClass
1894
1895 b.py
1896 -> from a import SomeClass
1897 -> some_function instantiates SomeClass
1898
Georg Brandl7ad3df62014-10-31 07:59:37 +01001899Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
1900:func:`patch`. The problem is that when we import module b, which we will have to
1901do then it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
1902``a.SomeClass`` then it will have no effect on our test; module b already has a
1903reference to the *real* ``SomeClass`` and it looks like our patching had no
Michael Foorda9e6fb22012-03-28 14:36:02 +01001904effect.
1905
Ben Lloyd15033d12017-05-22 12:06:56 +01001906The key is to patch out ``SomeClass`` where it is used (or where it is looked up).
1907In this case ``some_function`` will actually look up ``SomeClass`` in module b,
Michael Foorda9e6fb22012-03-28 14:36:02 +01001908where we have imported it. The patching should look like::
1909
1910 @patch('b.SomeClass')
1911
Georg Brandl7ad3df62014-10-31 07:59:37 +01001912However, consider the alternative scenario where instead of ``from a import
1913SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both
Michael Foorda9e6fb22012-03-28 14:36:02 +01001914of these import forms are common. In this case the class we want to patch is
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001915being looked up in the module and so we have to patch ``a.SomeClass`` instead::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001916
1917 @patch('a.SomeClass')
1918
1919
1920Patching Descriptors and Proxy Objects
Georg Brandlfb134382013-02-03 11:47:49 +01001921~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001922
1923Both patch_ and patch.object_ correctly patch and restore descriptors: class
1924methods, static methods and properties. You should patch these on the *class*
1925rather than an instance. They also work with *some* objects
Zachary Ware5ea5d2c2014-02-26 09:34:43 -06001926that proxy attribute access, like the `django settings object
Michael Foorda9e6fb22012-03-28 14:36:02 +01001927<http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
1928
1929
Michael Foord2309ed82012-03-28 15:38:36 +01001930MagicMock and magic method support
Georg Brandlfb134382013-02-03 11:47:49 +01001931----------------------------------
Michael Foord2309ed82012-03-28 15:38:36 +01001932
1933.. _magic-methods:
1934
1935Mocking Magic Methods
Georg Brandlfb134382013-02-03 11:47:49 +01001936~~~~~~~~~~~~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001937
1938:class:`Mock` supports mocking the Python protocol methods, also known as
1939"magic methods". This allows mock objects to replace containers or other
1940objects that implement Python protocols.
1941
1942Because magic methods are looked up differently from normal methods [#]_, this
1943support has been specially implemented. This means that only specific magic
1944methods are supported. The supported list includes *almost* all of them. If
1945there are any missing that you need please let us know.
1946
1947You mock magic methods by setting the method you are interested in to a function
1948or a mock instance. If you are using a function then it *must* take ``self`` as
1949the first argument [#]_.
1950
1951 >>> def __str__(self):
1952 ... return 'fooble'
1953 ...
1954 >>> mock = Mock()
1955 >>> mock.__str__ = __str__
1956 >>> str(mock)
1957 'fooble'
1958
1959 >>> mock = Mock()
1960 >>> mock.__str__ = Mock()
1961 >>> mock.__str__.return_value = 'fooble'
1962 >>> str(mock)
1963 'fooble'
1964
1965 >>> mock = Mock()
1966 >>> mock.__iter__ = Mock(return_value=iter([]))
1967 >>> list(mock)
1968 []
1969
1970One use case for this is for mocking objects used as context managers in a
Georg Brandl7ad3df62014-10-31 07:59:37 +01001971:keyword:`with` statement:
Michael Foord2309ed82012-03-28 15:38:36 +01001972
1973 >>> mock = Mock()
1974 >>> mock.__enter__ = Mock(return_value='foo')
1975 >>> mock.__exit__ = Mock(return_value=False)
1976 >>> with mock as m:
1977 ... assert m == 'foo'
1978 ...
1979 >>> mock.__enter__.assert_called_with()
1980 >>> mock.__exit__.assert_called_with(None, None, None)
1981
1982Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they
1983are recorded in :attr:`~Mock.mock_calls`.
1984
1985.. note::
1986
Georg Brandl7ad3df62014-10-31 07:59:37 +01001987 If you use the *spec* keyword argument to create a mock then attempting to
1988 set a magic method that isn't in the spec will raise an :exc:`AttributeError`.
Michael Foord2309ed82012-03-28 15:38:36 +01001989
1990The full list of supported magic methods is:
1991
1992* ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``
1993* ``__dir__``, ``__format__`` and ``__subclasses__``
John Reese6c4fab02018-05-22 13:01:10 -07001994* ``__round__``, ``__floor__``, ``__trunc__`` and ``__ceil__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001995* Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001996 ``__eq__`` and ``__ne__``
1997* Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``,
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001998 ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__``
1999 and ``__missing__``
Xtreak0ae022c2019-05-29 12:32:26 +05302000* Context manager: ``__enter__``, ``__exit__``, ``__aenter__`` and ``__aexit__``
Michael Foord2309ed82012-03-28 15:38:36 +01002001* Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``
2002* The numeric methods (including right hand and in-place variants):
Serhiy Storchakac2ccce72015-03-12 22:01:30 +02002003 ``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__div__``, ``__truediv__``,
Michael Foord2309ed82012-03-28 15:38:36 +01002004 ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``,
2005 ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002006* Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__``
2007 and ``__index__``
Michael Foord2309ed82012-03-28 15:38:36 +01002008* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
2009* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
2010 ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
Max Bélanger6c83d9f2018-10-25 14:48:58 -07002011* File system path representation: ``__fspath__``
Xtreakff6b2e62019-05-27 18:26:23 +05302012* Asynchronous iteration methods: ``__aiter__`` and ``__anext__``
Max Bélanger6c83d9f2018-10-25 14:48:58 -07002013
2014.. versionchanged:: 3.8
2015 Added support for :func:`os.PathLike.__fspath__`.
Michael Foord2309ed82012-03-28 15:38:36 +01002016
Xtreakff6b2e62019-05-27 18:26:23 +05302017.. versionchanged:: 3.8
2018 Added support for ``__aenter__``, ``__aexit__``, ``__aiter__`` and ``__anext__``.
2019
Michael Foord2309ed82012-03-28 15:38:36 +01002020
2021The following methods exist but are *not* supported as they are either in use
2022by mock, can't be set dynamically, or can cause problems:
2023
2024* ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``
2025* ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``
2026
2027
2028
2029Magic Mock
Georg Brandlfb134382013-02-03 11:47:49 +01002030~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01002031
Georg Brandl7ad3df62014-10-31 07:59:37 +01002032There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01002033
2034
2035.. class:: MagicMock(*args, **kw)
2036
2037 ``MagicMock`` is a subclass of :class:`Mock` with default implementations
2038 of most of the magic methods. You can use ``MagicMock`` without having to
2039 configure the magic methods yourself.
2040
2041 The constructor parameters have the same meaning as for :class:`Mock`.
2042
Georg Brandl7ad3df62014-10-31 07:59:37 +01002043 If you use the *spec* or *spec_set* arguments then *only* magic methods
Michael Foord2309ed82012-03-28 15:38:36 +01002044 that exist in the spec will be created.
2045
2046
2047.. class:: NonCallableMagicMock(*args, **kw)
2048
Georg Brandl7ad3df62014-10-31 07:59:37 +01002049 A non-callable version of :class:`MagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01002050
2051 The constructor parameters have the same meaning as for
Georg Brandl7ad3df62014-10-31 07:59:37 +01002052 :class:`MagicMock`, with the exception of *return_value* and
2053 *side_effect* which have no meaning on a non-callable mock.
Michael Foord2309ed82012-03-28 15:38:36 +01002054
Georg Brandl7ad3df62014-10-31 07:59:37 +01002055The magic methods are setup with :class:`MagicMock` objects, so you can configure them
Michael Foord2309ed82012-03-28 15:38:36 +01002056and use them in the usual way:
2057
2058 >>> mock = MagicMock()
2059 >>> mock[3] = 'fish'
2060 >>> mock.__setitem__.assert_called_with(3, 'fish')
2061 >>> mock.__getitem__.return_value = 'result'
2062 >>> mock[2]
2063 'result'
2064
2065By default many of the protocol methods are required to return objects of a
2066specific type. These methods are preconfigured with a default return value, so
2067that they can be used without you having to do anything if you aren't interested
2068in the return value. You can still *set* the return value manually if you want
2069to change the default.
2070
2071Methods and their defaults:
2072
2073* ``__lt__``: NotImplemented
2074* ``__gt__``: NotImplemented
2075* ``__le__``: NotImplemented
2076* ``__ge__``: NotImplemented
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02002077* ``__int__``: 1
2078* ``__contains__``: False
Berker Peksag8fafc742016-04-11 12:23:04 +03002079* ``__len__``: 0
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02002080* ``__iter__``: iter([])
2081* ``__exit__``: False
Xtreak0ae022c2019-05-29 12:32:26 +05302082* ``__aexit__``: False
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02002083* ``__complex__``: 1j
2084* ``__float__``: 1.0
2085* ``__bool__``: True
2086* ``__index__``: 1
2087* ``__hash__``: default hash for the mock
2088* ``__str__``: default str for the mock
Michael Foord2309ed82012-03-28 15:38:36 +01002089* ``__sizeof__``: default sizeof for the mock
2090
2091For example:
2092
2093 >>> mock = MagicMock()
2094 >>> int(mock)
2095 1
2096 >>> len(mock)
2097 0
2098 >>> list(mock)
2099 []
2100 >>> object() in mock
2101 False
2102
Berker Peksag283f1aa2015-01-07 21:15:02 +02002103The two equality methods, :meth:`__eq__` and :meth:`__ne__`, are special.
2104They do the default equality comparison on identity, using the
2105:attr:`~Mock.side_effect` attribute, unless you change their return value to
2106return something else::
Michael Foord2309ed82012-03-28 15:38:36 +01002107
2108 >>> MagicMock() == 3
2109 False
2110 >>> MagicMock() != 3
2111 True
2112 >>> mock = MagicMock()
2113 >>> mock.__eq__.return_value = True
2114 >>> mock == 3
2115 True
2116
Georg Brandl7ad3df62014-10-31 07:59:37 +01002117The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
Michael Foord2309ed82012-03-28 15:38:36 +01002118required to be an iterator:
2119
2120 >>> mock = MagicMock()
2121 >>> mock.__iter__.return_value = ['a', 'b', 'c']
2122 >>> list(mock)
2123 ['a', 'b', 'c']
2124 >>> list(mock)
2125 ['a', 'b', 'c']
2126
2127If the return value *is* an iterator, then iterating over it once will consume
2128it and subsequent iterations will result in an empty list:
2129
2130 >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
2131 >>> list(mock)
2132 ['a', 'b', 'c']
2133 >>> list(mock)
2134 []
2135
2136``MagicMock`` has all of the supported magic methods configured except for some
2137of the obscure and obsolete ones. You can still set these up if you want.
2138
2139Magic methods that are supported but not setup by default in ``MagicMock`` are:
2140
2141* ``__subclasses__``
2142* ``__dir__``
2143* ``__format__``
2144* ``__get__``, ``__set__`` and ``__delete__``
2145* ``__reversed__`` and ``__missing__``
2146* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
2147 ``__getstate__`` and ``__setstate__``
2148* ``__getformat__`` and ``__setformat__``
2149
2150
2151
2152.. [#] Magic methods *should* be looked up on the class rather than the
2153 instance. Different versions of Python are inconsistent about applying this
2154 rule. The supported protocol methods should work with all supported versions
2155 of Python.
2156.. [#] The function is basically hooked up to the class, but each ``Mock``
2157 instance is kept isolated from the others.
2158
2159
Michael Foorda9e6fb22012-03-28 14:36:02 +01002160Helpers
Georg Brandlfb134382013-02-03 11:47:49 +01002161-------
Michael Foorda9e6fb22012-03-28 14:36:02 +01002162
2163sentinel
Georg Brandlfb134382013-02-03 11:47:49 +01002164~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002165
2166.. data:: sentinel
2167
Andrés Delfinof85af032018-07-08 21:28:51 -03002168 The ``sentinel`` object provides a convenient way of providing unique
2169 objects for your tests.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002170
Andrés Delfinof85af032018-07-08 21:28:51 -03002171 Attributes are created on demand when you access them by name. Accessing
2172 the same attribute will always return the same object. The objects
2173 returned have a sensible repr so that test failure messages are readable.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002174
Serhiy Storchakad9c956f2017-01-11 20:13:03 +02002175 .. versionchanged:: 3.7
2176 The ``sentinel`` attributes now preserve their identity when they are
2177 :mod:`copied <copy>` or :mod:`pickled <pickle>`.
2178
Michael Foorda9e6fb22012-03-28 14:36:02 +01002179Sometimes when testing you need to test that a specific object is passed as an
2180argument to another method, or returned. It can be common to create named
Georg Brandl7ad3df62014-10-31 07:59:37 +01002181sentinel objects to test this. :data:`sentinel` provides a convenient way of
Michael Foorda9e6fb22012-03-28 14:36:02 +01002182creating and testing the identity of objects like this.
2183
Georg Brandl7ad3df62014-10-31 07:59:37 +01002184In this example we monkey patch ``method`` to return ``sentinel.some_object``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002185
2186 >>> real = ProductionClass()
2187 >>> real.method = Mock(name="method")
2188 >>> real.method.return_value = sentinel.some_object
2189 >>> result = real.method()
2190 >>> assert result is sentinel.some_object
2191 >>> sentinel.some_object
2192 sentinel.some_object
2193
2194
2195DEFAULT
Georg Brandlfb134382013-02-03 11:47:49 +01002196~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002197
2198
2199.. data:: DEFAULT
2200
Georg Brandl7ad3df62014-10-31 07:59:37 +01002201 The :data:`DEFAULT` object is a pre-created sentinel (actually
2202 ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect`
Michael Foorda9e6fb22012-03-28 14:36:02 +01002203 functions to indicate that the normal return value should be used.
2204
2205
Michael Foorda9e6fb22012-03-28 14:36:02 +01002206call
Georg Brandlfb134382013-02-03 11:47:49 +01002207~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002208
2209.. function:: call(*args, **kwargs)
2210
Georg Brandl7ad3df62014-10-31 07:59:37 +01002211 :func:`call` is a helper object for making simpler assertions, for comparing with
Georg Brandl24891672012-04-01 13:48:26 +02002212 :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
Georg Brandl7ad3df62014-10-31 07:59:37 +01002213 :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be
Michael Foorda9e6fb22012-03-28 14:36:02 +01002214 used with :meth:`~Mock.assert_has_calls`.
2215
2216 >>> m = MagicMock(return_value=None)
2217 >>> m(1, 2, a='foo', b='bar')
2218 >>> m()
2219 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
2220 True
2221
2222.. method:: call.call_list()
2223
Georg Brandl7ad3df62014-10-31 07:59:37 +01002224 For a call object that represents multiple calls, :meth:`call_list`
Michael Foorda9e6fb22012-03-28 14:36:02 +01002225 returns a list of all the intermediate calls as well as the
2226 final call.
2227
Georg Brandl7ad3df62014-10-31 07:59:37 +01002228``call_list`` is particularly useful for making assertions on "chained calls". A
Michael Foorda9e6fb22012-03-28 14:36:02 +01002229chained call is multiple calls on a single line of code. This results in
2230multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
2231the sequence of calls can be tedious.
2232
2233:meth:`~call.call_list` can construct the sequence of calls from the same
2234chained call:
2235
2236 >>> m = MagicMock()
2237 >>> m(1).method(arg='foo').other('bar')(2.0)
2238 <MagicMock name='mock().method().other()()' id='...'>
2239 >>> kall = call(1).method(arg='foo').other('bar')(2.0)
2240 >>> kall.call_list()
2241 [call(1),
2242 call().method(arg='foo'),
2243 call().method().other('bar'),
2244 call().method().other()(2.0)]
2245 >>> m.mock_calls == kall.call_list()
2246 True
2247
2248.. _calls-as-tuples:
2249
Georg Brandl7ad3df62014-10-31 07:59:37 +01002250A ``call`` object is either a tuple of (positional args, keyword args) or
Michael Foorda9e6fb22012-03-28 14:36:02 +01002251(name, positional args, keyword args) depending on how it was constructed. When
Georg Brandl7ad3df62014-10-31 07:59:37 +01002252you construct them yourself this isn't particularly interesting, but the ``call``
Michael Foorda9e6fb22012-03-28 14:36:02 +01002253objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
2254:attr:`Mock.mock_calls` attributes can be introspected to get at the individual
2255arguments they contain.
2256
Georg Brandl7ad3df62014-10-31 07:59:37 +01002257The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
2258are two-tuples of (positional args, keyword args) whereas the ``call`` objects
Michael Foorda9e6fb22012-03-28 14:36:02 +01002259in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
2260three-tuples of (name, positional args, keyword args).
2261
2262You can use their "tupleness" to pull out the individual arguments for more
2263complex introspection and assertions. The positional arguments are a tuple
2264(an empty tuple if there are no positional arguments) and the keyword
2265arguments are a dictionary:
2266
2267 >>> m = MagicMock(return_value=None)
2268 >>> m(1, 2, 3, arg='one', arg2='two')
2269 >>> kall = m.call_args
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302270 >>> kall.args
Michael Foorda9e6fb22012-03-28 14:36:02 +01002271 (1, 2, 3)
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302272 >>> kall.kwargs
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002273 {'arg': 'one', 'arg2': 'two'}
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302274 >>> kall.args is kall[0]
Michael Foorda9e6fb22012-03-28 14:36:02 +01002275 True
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302276 >>> kall.kwargs is kall[1]
Michael Foorda9e6fb22012-03-28 14:36:02 +01002277 True
2278
2279 >>> m = MagicMock()
2280 >>> m.foo(4, 5, 6, arg='two', arg2='three')
2281 <MagicMock name='mock.foo()' id='...'>
2282 >>> kall = m.mock_calls[0]
2283 >>> name, args, kwargs = kall
2284 >>> name
2285 'foo'
2286 >>> args
2287 (4, 5, 6)
2288 >>> kwargs
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002289 {'arg': 'two', 'arg2': 'three'}
Michael Foorda9e6fb22012-03-28 14:36:02 +01002290 >>> name is m.mock_calls[0][0]
2291 True
2292
2293
2294create_autospec
Georg Brandlfb134382013-02-03 11:47:49 +01002295~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002296
2297.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
2298
2299 Create a mock object using another object as a spec. Attributes on the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002300 mock will use the corresponding attribute on the *spec* object as their
Michael Foorda9e6fb22012-03-28 14:36:02 +01002301 spec.
2302
2303 Functions or methods being mocked will have their arguments checked to
2304 ensure that they are called with the correct signature.
2305
Georg Brandl7ad3df62014-10-31 07:59:37 +01002306 If *spec_set* is ``True`` then attempting to set attributes that don't exist
2307 on the spec object will raise an :exc:`AttributeError`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002308
2309 If a class is used as a spec then the return value of the mock (the
2310 instance of the class) will have the same spec. You can use a class as the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002311 spec for an instance object by passing ``instance=True``. The returned mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01002312 will only be callable if instances of the mock are callable.
2313
Georg Brandl7ad3df62014-10-31 07:59:37 +01002314 :func:`create_autospec` also takes arbitrary keyword arguments that are passed to
Michael Foorda9e6fb22012-03-28 14:36:02 +01002315 the constructor of the created mock.
2316
2317See :ref:`auto-speccing` for examples of how to use auto-speccing with
Georg Brandl7ad3df62014-10-31 07:59:37 +01002318:func:`create_autospec` and the *autospec* argument to :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002319
2320
Mario Corcherof5e7f392019-09-09 15:18:06 +01002321.. versionchanged:: 3.8
2322
2323 :func:`create_autospec` now returns an :class:`AsyncMock` if the target is
2324 an async function.
2325
2326
Michael Foorda9e6fb22012-03-28 14:36:02 +01002327ANY
Georg Brandlfb134382013-02-03 11:47:49 +01002328~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002329
2330.. data:: ANY
2331
2332Sometimes you may need to make assertions about *some* of the arguments in a
2333call to mock, but either not care about some of the arguments or want to pull
2334them individually out of :attr:`~Mock.call_args` and make more complex
2335assertions on them.
2336
2337To ignore certain arguments you can pass in objects that compare equal to
2338*everything*. Calls to :meth:`~Mock.assert_called_with` and
2339:meth:`~Mock.assert_called_once_with` will then succeed no matter what was
2340passed in.
2341
2342 >>> mock = Mock(return_value=None)
2343 >>> mock('foo', bar=object())
2344 >>> mock.assert_called_once_with('foo', bar=ANY)
2345
Georg Brandl7ad3df62014-10-31 07:59:37 +01002346:data:`ANY` can also be used in comparisons with call lists like
Michael Foorda9e6fb22012-03-28 14:36:02 +01002347:attr:`~Mock.mock_calls`:
2348
2349 >>> m = MagicMock(return_value=None)
2350 >>> m(1)
2351 >>> m(1, 2)
2352 >>> m(object())
2353 >>> m.mock_calls == [call(1), call(1, 2), ANY]
2354 True
2355
2356
2357
2358FILTER_DIR
Georg Brandlfb134382013-02-03 11:47:49 +01002359~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002360
2361.. data:: FILTER_DIR
2362
Georg Brandl7ad3df62014-10-31 07:59:37 +01002363:data:`FILTER_DIR` is a module level variable that controls the way mock objects
2364respond to :func:`dir` (only for Python 2.6 or more recent). The default is ``True``,
Michael Foorda9e6fb22012-03-28 14:36:02 +01002365which uses the filtering described below, to only show useful members. If you
2366dislike this filtering, or need to switch it off for diagnostic purposes, then
Georg Brandl7ad3df62014-10-31 07:59:37 +01002367set ``mock.FILTER_DIR = False``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002368
Georg Brandl7ad3df62014-10-31 07:59:37 +01002369With filtering on, ``dir(some_mock)`` shows only useful attributes and will
Michael Foorda9e6fb22012-03-28 14:36:02 +01002370include any dynamically created attributes that wouldn't normally be shown.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002371If the mock was created with a *spec* (or *autospec* of course) then all the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002372attributes from the original are shown, even if they haven't been accessed
2373yet:
2374
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002375.. doctest::
2376 :options: +ELLIPSIS,+NORMALIZE_WHITESPACE
2377
Michael Foorda9e6fb22012-03-28 14:36:02 +01002378 >>> dir(Mock())
2379 ['assert_any_call',
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002380 'assert_called',
2381 'assert_called_once',
Michael Foorda9e6fb22012-03-28 14:36:02 +01002382 'assert_called_once_with',
2383 'assert_called_with',
2384 'assert_has_calls',
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002385 'assert_not_called',
Michael Foorda9e6fb22012-03-28 14:36:02 +01002386 'attach_mock',
2387 ...
2388 >>> from urllib import request
2389 >>> dir(Mock(spec=request))
2390 ['AbstractBasicAuthHandler',
2391 'AbstractDigestAuthHandler',
2392 'AbstractHTTPHandler',
2393 'BaseHandler',
2394 ...
2395
Georg Brandl7ad3df62014-10-31 07:59:37 +01002396Many of the not-very-useful (private to :class:`Mock` rather than the thing being
Michael Foorda9e6fb22012-03-28 14:36:02 +01002397mocked) underscore and double underscore prefixed attributes have been
Georg Brandl7ad3df62014-10-31 07:59:37 +01002398filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this
Michael Foorda9e6fb22012-03-28 14:36:02 +01002399behaviour you can switch it off by setting the module level switch
Georg Brandl7ad3df62014-10-31 07:59:37 +01002400:data:`FILTER_DIR`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002401
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002402.. doctest::
2403 :options: +ELLIPSIS,+NORMALIZE_WHITESPACE
2404
Michael Foorda9e6fb22012-03-28 14:36:02 +01002405 >>> from unittest import mock
2406 >>> mock.FILTER_DIR = False
2407 >>> dir(mock.Mock())
2408 ['_NonCallableMock__get_return_value',
2409 '_NonCallableMock__get_side_effect',
2410 '_NonCallableMock__return_value_doc',
2411 '_NonCallableMock__set_return_value',
2412 '_NonCallableMock__set_side_effect',
2413 '__call__',
2414 '__class__',
2415 ...
2416
Georg Brandl7ad3df62014-10-31 07:59:37 +01002417Alternatively you can just use ``vars(my_mock)`` (instance members) and
2418``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of
2419:data:`mock.FILTER_DIR`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002420
2421
2422mock_open
Georg Brandlfb134382013-02-03 11:47:49 +01002423~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002424
2425.. function:: mock_open(mock=None, read_data=None)
2426
Andrés Delfinof85af032018-07-08 21:28:51 -03002427 A helper function to create a mock to replace the use of :func:`open`. It works
2428 for :func:`open` called directly or used as a context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002429
Andrés Delfinof85af032018-07-08 21:28:51 -03002430 The *mock* argument is the mock object to configure. If ``None`` (the
2431 default) then a :class:`MagicMock` will be created for you, with the API limited
2432 to methods or attributes available on standard file handles.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002433
Andrés Delfinof85af032018-07-08 21:28:51 -03002434 *read_data* is a string for the :meth:`~io.IOBase.read`,
2435 :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods
2436 of the file handle to return. Calls to those methods will take data from
2437 *read_data* until it is depleted. The mock of these methods is pretty
2438 simplistic: every time the *mock* is called, the *read_data* is rewound to
2439 the start. If you need more control over the data that you are feeding to
2440 the tested code you will need to customize this mock for yourself. When that
2441 is insufficient, one of the in-memory filesystem packages on `PyPI
2442 <https://pypi.org>`_ can offer a realistic filesystem for testing.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002443
Robert Collinsf79dfe32015-07-24 04:09:59 +12002444 .. versionchanged:: 3.4
2445 Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support.
2446 The mock of :meth:`~io.IOBase.read` changed to consume *read_data* rather
2447 than returning it on each call.
2448
Robert Collins70398392015-07-24 04:10:27 +12002449 .. versionchanged:: 3.5
Robert Collinsf79dfe32015-07-24 04:09:59 +12002450 *read_data* is now reset on each call to the *mock*.
2451
Tony Flury20870232018-09-12 23:21:16 +01002452 .. versionchanged:: 3.8
2453 Added :meth:`__iter__` to implementation so that iteration (such as in for
2454 loops) correctly consumes *read_data*.
2455
Georg Brandl7ad3df62014-10-31 07:59:37 +01002456Using :func:`open` as a context manager is a great way to ensure your file handles
Michael Foorda9e6fb22012-03-28 14:36:02 +01002457are closed properly and is becoming common::
2458
2459 with open('/some/path', 'w') as f:
2460 f.write('something')
2461
Georg Brandl7ad3df62014-10-31 07:59:37 +01002462The issue is that even if you mock out the call to :func:`open` it is the
2463*returned object* that is used as a context manager (and has :meth:`__enter__` and
2464:meth:`__exit__` called).
Michael Foorda9e6fb22012-03-28 14:36:02 +01002465
2466Mocking context managers with a :class:`MagicMock` is common enough and fiddly
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002467enough that a helper function is useful. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002468
2469 >>> m = mock_open()
Michael Foordfddcfa22014-04-14 16:25:20 -04002470 >>> with patch('__main__.open', m):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002471 ... with open('foo', 'w') as h:
2472 ... h.write('some stuff')
2473 ...
2474 >>> m.mock_calls
2475 [call('foo', 'w'),
2476 call().__enter__(),
2477 call().write('some stuff'),
2478 call().__exit__(None, None, None)]
2479 >>> m.assert_called_once_with('foo', 'w')
2480 >>> handle = m()
2481 >>> handle.write.assert_called_once_with('some stuff')
2482
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002483And for reading files::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002484
Michael Foordfddcfa22014-04-14 16:25:20 -04002485 >>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002486 ... with open('foo') as h:
2487 ... result = h.read()
2488 ...
2489 >>> m.assert_called_once_with('foo')
2490 >>> assert result == 'bibble'
2491
2492
2493.. _auto-speccing:
2494
2495Autospeccing
Georg Brandlfb134382013-02-03 11:47:49 +01002496~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002497
Georg Brandl7ad3df62014-10-31 07:59:37 +01002498Autospeccing is based on the existing :attr:`spec` feature of mock. It limits the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002499api of mocks to the api of an original object (the spec), but it is recursive
2500(implemented lazily) so that attributes of mocks only have the same api as
2501the attributes of the spec. In addition mocked functions / methods have the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002502same call signature as the original so they raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002503called incorrectly.
2504
2505Before I explain how auto-speccing works, here's why it is needed.
2506
Georg Brandl7ad3df62014-10-31 07:59:37 +01002507:class:`Mock` is a very powerful and flexible object, but it suffers from two flaws
Michael Foorda9e6fb22012-03-28 14:36:02 +01002508when used to mock out objects from a system under test. One of these flaws is
Georg Brandl7ad3df62014-10-31 07:59:37 +01002509specific to the :class:`Mock` api and the other is a more general problem with using
Michael Foorda9e6fb22012-03-28 14:36:02 +01002510mock objects.
2511
Georg Brandl7ad3df62014-10-31 07:59:37 +01002512First the problem specific to :class:`Mock`. :class:`Mock` has two assert methods that are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002513extremely handy: :meth:`~Mock.assert_called_with` and
2514:meth:`~Mock.assert_called_once_with`.
2515
2516 >>> mock = Mock(name='Thing', return_value=None)
2517 >>> mock(1, 2, 3)
2518 >>> mock.assert_called_once_with(1, 2, 3)
2519 >>> mock(1, 2, 3)
2520 >>> mock.assert_called_once_with(1, 2, 3)
2521 Traceback (most recent call last):
2522 ...
Michael Foord28d591c2012-09-28 16:15:22 +01002523 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002524
2525Because mocks auto-create attributes on demand, and allow you to call them
2526with arbitrary arguments, if you misspell one of these assert methods then
2527your assertion is gone:
2528
2529.. code-block:: pycon
2530
2531 >>> mock = Mock(name='Thing', return_value=None)
2532 >>> mock(1, 2, 3)
2533 >>> mock.assret_called_once_with(4, 5, 6)
2534
2535Your tests can pass silently and incorrectly because of the typo.
2536
2537The second issue is more general to mocking. If you refactor some of your
2538code, rename members and so on, any tests for code that is still using the
2539*old api* but uses mocks instead of the real objects will still pass. This
2540means your tests can all pass even though your code is broken.
2541
2542Note that this is another reason why you need integration tests as well as
2543unit tests. Testing everything in isolation is all fine and dandy, but if you
2544don't test how your units are "wired together" there is still lots of room
2545for bugs that tests might have caught.
2546
Georg Brandl7ad3df62014-10-31 07:59:37 +01002547:mod:`mock` already provides a feature to help with this, called speccing. If you
2548use a class or instance as the :attr:`spec` for a mock then you can only access
Michael Foorda9e6fb22012-03-28 14:36:02 +01002549attributes on the mock that exist on the real class:
2550
2551 >>> from urllib import request
2552 >>> mock = Mock(spec=request.Request)
2553 >>> mock.assret_called_with
2554 Traceback (most recent call last):
2555 ...
2556 AttributeError: Mock object has no attribute 'assret_called_with'
2557
2558The spec only applies to the mock itself, so we still have the same issue
2559with any methods on the mock:
2560
2561.. code-block:: pycon
2562
2563 >>> mock.has_data()
2564 <mock.Mock object at 0x...>
2565 >>> mock.has_data.assret_called_with()
2566
Georg Brandl7ad3df62014-10-31 07:59:37 +01002567Auto-speccing solves this problem. You can either pass ``autospec=True`` to
2568:func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a
2569mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002570object that is being replaced will be used as the spec object. Because the
2571speccing is done "lazily" (the spec is created as attributes on the mock are
2572accessed) you can use it with very complex or deeply nested objects (like
2573modules that import modules that import modules) without a big performance
2574hit.
2575
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002576Here's an example of it in use::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002577
2578 >>> from urllib import request
2579 >>> patcher = patch('__main__.request', autospec=True)
2580 >>> mock_request = patcher.start()
2581 >>> request is mock_request
2582 True
2583 >>> mock_request.Request
2584 <MagicMock name='request.Request' spec='Request' id='...'>
2585
Georg Brandl7ad3df62014-10-31 07:59:37 +01002586You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two
2587arguments in the constructor (one of which is *self*). Here's what happens if
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002588we try to call it incorrectly::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002589
2590 >>> req = request.Request()
2591 Traceback (most recent call last):
2592 ...
2593 TypeError: <lambda>() takes at least 2 arguments (1 given)
2594
2595The spec also applies to instantiated classes (i.e. the return value of
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002596specced mocks)::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002597
2598 >>> req = request.Request('foo')
2599 >>> req
2600 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
2601
Georg Brandl7ad3df62014-10-31 07:59:37 +01002602:class:`Request` objects are not callable, so the return value of instantiating our
2603mocked out :class:`request.Request` is a non-callable mock. With the spec in place
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002604any typos in our asserts will raise the correct error::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002605
2606 >>> req.add_header('spam', 'eggs')
2607 <MagicMock name='request.Request().add_header()' id='...'>
2608 >>> req.add_header.assret_called_with
2609 Traceback (most recent call last):
2610 ...
2611 AttributeError: Mock object has no attribute 'assret_called_with'
2612 >>> req.add_header.assert_called_with('spam', 'eggs')
2613
Georg Brandl7ad3df62014-10-31 07:59:37 +01002614In many cases you will just be able to add ``autospec=True`` to your existing
2615:func:`patch` calls and then be protected against bugs due to typos and api
Michael Foorda9e6fb22012-03-28 14:36:02 +01002616changes.
2617
Georg Brandl7ad3df62014-10-31 07:59:37 +01002618As well as using *autospec* through :func:`patch` there is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002619:func:`create_autospec` for creating autospecced mocks directly:
2620
2621 >>> from urllib import request
2622 >>> mock_request = create_autospec(request)
2623 >>> mock_request.Request('foo', 'bar')
2624 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
2625
2626This isn't without caveats and limitations however, which is why it is not
2627the default behaviour. In order to know what attributes are available on the
2628spec object, autospec has to introspect (access attributes) the spec. As you
2629traverse attributes on the mock a corresponding traversal of the original
2630object is happening under the hood. If any of your specced objects have
2631properties or descriptors that can trigger code execution then you may not be
2632able to use autospec. On the other hand it is much better to design your
2633objects so that introspection is safe [#]_.
2634
2635A more serious problem is that it is common for instance attributes to be
Georg Brandl7ad3df62014-10-31 07:59:37 +01002636created in the :meth:`__init__` method and not to exist on the class at all.
2637*autospec* can't know about any dynamically created attributes and restricts
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002638the api to visible attributes. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002639
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002640 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002641 ... def __init__(self):
2642 ... self.a = 33
2643 ...
2644 >>> with patch('__main__.Something', autospec=True):
2645 ... thing = Something()
2646 ... thing.a
2647 ...
2648 Traceback (most recent call last):
2649 ...
2650 AttributeError: Mock object has no attribute 'a'
2651
2652There are a few different ways of resolving this problem. The easiest, but
2653not necessarily the least annoying, way is to simply set the required
Georg Brandl7ad3df62014-10-31 07:59:37 +01002654attributes on the mock after creation. Just because *autospec* doesn't allow
Michael Foorda9e6fb22012-03-28 14:36:02 +01002655you to fetch attributes that don't exist on the spec it doesn't prevent you
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002656setting them::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002657
2658 >>> with patch('__main__.Something', autospec=True):
2659 ... thing = Something()
2660 ... thing.a = 33
2661 ...
2662
Georg Brandl7ad3df62014-10-31 07:59:37 +01002663There is a more aggressive version of both *spec* and *autospec* that *does*
Michael Foorda9e6fb22012-03-28 14:36:02 +01002664prevent you setting non-existent attributes. This is useful if you want to
2665ensure your code only *sets* valid attributes too, but obviously it prevents
2666this particular scenario:
2667
2668 >>> with patch('__main__.Something', autospec=True, spec_set=True):
2669 ... thing = Something()
2670 ... thing.a = 33
2671 ...
2672 Traceback (most recent call last):
2673 ...
2674 AttributeError: Mock object has no attribute 'a'
2675
2676Probably the best way of solving the problem is to add class attributes as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002677default values for instance members initialised in :meth:`__init__`. Note that if
2678you are only setting default attributes in :meth:`__init__` then providing them via
Michael Foorda9e6fb22012-03-28 14:36:02 +01002679class attributes (shared between instances of course) is faster too. e.g.
2680
2681.. code-block:: python
2682
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002683 class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002684 a = 33
2685
2686This brings up another issue. It is relatively common to provide a default
Georg Brandl7ad3df62014-10-31 07:59:37 +01002687value of ``None`` for members that will later be an object of a different type.
2688``None`` would be useless as a spec because it wouldn't let you access *any*
2689attributes or methods on it. As ``None`` is *never* going to be useful as a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002690spec, and probably indicates a member that will normally of some other type,
Georg Brandl7ad3df62014-10-31 07:59:37 +01002691autospec doesn't use a spec for members that are set to ``None``. These will
2692just be ordinary mocks (well - MagicMocks):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002693
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002694 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002695 ... member = None
2696 ...
2697 >>> mock = create_autospec(Something)
2698 >>> mock.member.foo.bar.baz()
2699 <MagicMock name='mock.member.foo.bar.baz()' id='...'>
2700
2701If modifying your production classes to add defaults isn't to your liking
2702then there are more options. One of these is simply to use an instance as the
2703spec rather than the class. The other is to create a subclass of the
2704production class and add the defaults to the subclass without affecting the
2705production class. Both of these require you to use an alternative object as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002706the spec. Thankfully :func:`patch` supports this - you can simply pass the
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002707alternative object as the *autospec* argument::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002708
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002709 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002710 ... def __init__(self):
2711 ... self.a = 33
2712 ...
2713 >>> class SomethingForTest(Something):
2714 ... a = 33
2715 ...
2716 >>> p = patch('__main__.Something', autospec=SomethingForTest)
2717 >>> mock = p.start()
2718 >>> mock.a
2719 <NonCallableMagicMock name='Something.a' spec='int' id='...'>
2720
2721
2722.. [#] This only applies to classes or already instantiated objects. Calling
2723 a mocked class to create a mock instance *does not* create a real instance.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002724 It is only attribute lookups - along with calls to :func:`dir` - that are done.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002725
Mario Corchero552be9d2017-10-17 12:35:11 +01002726Sealing mocks
2727~~~~~~~~~~~~~
2728
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002729
2730.. testsetup::
2731
2732 from unittest.mock import seal
2733
Mario Corchero552be9d2017-10-17 12:35:11 +01002734.. function:: seal(mock)
2735
Mario Corchero96200eb2018-10-19 22:57:37 +01002736 Seal will disable the automatic creation of mocks when accessing an attribute of
2737 the mock being sealed or any of its attributes that are already mocks recursively.
Mario Corchero552be9d2017-10-17 12:35:11 +01002738
Mario Corchero96200eb2018-10-19 22:57:37 +01002739 If a mock instance with a name or a spec is assigned to an attribute
Paul Ganssle85ac7262018-01-06 08:25:34 -05002740 it won't be considered in the sealing chain. This allows one to prevent seal from
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002741 fixing part of the mock object. ::
Mario Corchero552be9d2017-10-17 12:35:11 +01002742
2743 >>> mock = Mock()
2744 >>> mock.submock.attribute1 = 2
Mario Corchero96200eb2018-10-19 22:57:37 +01002745 >>> mock.not_submock = mock.Mock(name="sample_name")
Mario Corchero552be9d2017-10-17 12:35:11 +01002746 >>> seal(mock)
Mario Corchero96200eb2018-10-19 22:57:37 +01002747 >>> mock.new_attribute # This will raise AttributeError.
Mario Corchero552be9d2017-10-17 12:35:11 +01002748 >>> mock.submock.attribute2 # This will raise AttributeError.
2749 >>> mock.not_submock.attribute2 # This won't raise.
2750
2751 .. versionadded:: 3.7