blob: ed00ee6d0c2d8335f1b964353f2fb21073d69c99 [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
204 import unittest
205 from unittest.mock import sentinel, DEFAULT, ANY
206 from unittest.mock import patch, call, Mock, MagicMock, PropertyMock
207 from unittest.mock import mock_open
Michael Foord944e02d2012-03-25 23:12:55 +0100208
Georg Brandl7ad3df62014-10-31 07:59:37 +0100209:class:`Mock` is a flexible mock object intended to replace the use of stubs and
Michael Foord944e02d2012-03-25 23:12:55 +0100210test doubles throughout your code. Mocks are callable and create attributes as
211new mocks when you access them [#]_. Accessing the same attribute will always
212return the same mock. Mocks record how you use them, allowing you to make
213assertions about what your code has done to them.
214
Georg Brandl7ad3df62014-10-31 07:59:37 +0100215:class:`MagicMock` is a subclass of :class:`Mock` with all the magic methods
Michael Foord944e02d2012-03-25 23:12:55 +0100216pre-created and ready to use. There are also non-callable variants, useful
217when you are mocking out objects that aren't callable:
218:class:`NonCallableMock` and :class:`NonCallableMagicMock`
219
220The :func:`patch` decorators makes it easy to temporarily replace classes
Georg Brandl7ad3df62014-10-31 07:59:37 +0100221in a particular module with a :class:`Mock` object. By default :func:`patch` will create
222a :class:`MagicMock` for you. You can specify an alternative class of :class:`Mock` using
223the *new_callable* argument to :func:`patch`.
Michael Foord944e02d2012-03-25 23:12:55 +0100224
225
Kushal Das8c145342014-04-16 23:32:21 +0530226.. 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 +0100227
Georg Brandl7ad3df62014-10-31 07:59:37 +0100228 Create a new :class:`Mock` object. :class:`Mock` takes several optional arguments
Michael Foord944e02d2012-03-25 23:12:55 +0100229 that specify the behaviour of the Mock object:
230
Georg Brandl7ad3df62014-10-31 07:59:37 +0100231 * *spec*: This can be either a list of strings or an existing object (a
Michael Foord944e02d2012-03-25 23:12:55 +0100232 class or instance) that acts as the specification for the mock object. If
233 you pass in an object then a list of strings is formed by calling dir on
234 the object (excluding unsupported magic attributes and methods).
Georg Brandl7ad3df62014-10-31 07:59:37 +0100235 Accessing any attribute not in this list will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100236
Georg Brandl7ad3df62014-10-31 07:59:37 +0100237 If *spec* is an object (rather than a list of strings) then
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300238 :attr:`~instance.__class__` returns the class of the spec object. This
Georg Brandl7ad3df62014-10-31 07:59:37 +0100239 allows mocks to pass :func:`isinstance` tests.
Michael Foord944e02d2012-03-25 23:12:55 +0100240
Georg Brandl7ad3df62014-10-31 07:59:37 +0100241 * *spec_set*: A stricter variant of *spec*. If used, attempting to *set*
Michael Foord944e02d2012-03-25 23:12:55 +0100242 or get an attribute on the mock that isn't on the object passed as
Georg Brandl7ad3df62014-10-31 07:59:37 +0100243 *spec_set* will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100244
Georg Brandl7ad3df62014-10-31 07:59:37 +0100245 * *side_effect*: A function to be called whenever the Mock is called. See
Michael Foord944e02d2012-03-25 23:12:55 +0100246 the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or
247 dynamically changing return values. The function is called with the same
248 arguments as the mock, and unless it returns :data:`DEFAULT`, the return
249 value of this function is used as the return value.
250
Georg Brandl7ad3df62014-10-31 07:59:37 +0100251 Alternatively *side_effect* can be an exception class or instance. In
Michael Foord944e02d2012-03-25 23:12:55 +0100252 this case the exception will be raised when the mock is called.
253
Georg Brandl7ad3df62014-10-31 07:59:37 +0100254 If *side_effect* is an iterable then each call to the mock will return
Michael Foord944e02d2012-03-25 23:12:55 +0100255 the next value from the iterable.
256
Georg Brandl7ad3df62014-10-31 07:59:37 +0100257 A *side_effect* can be cleared by setting it to ``None``.
Michael Foord944e02d2012-03-25 23:12:55 +0100258
Georg Brandl7ad3df62014-10-31 07:59:37 +0100259 * *return_value*: The value returned when the mock is called. By default
Michael Foord944e02d2012-03-25 23:12:55 +0100260 this is a new Mock (created on first access). See the
261 :attr:`return_value` attribute.
262
Georg Brandl7ad3df62014-10-31 07:59:37 +0100263 * *unsafe*: By default if any attribute starts with *assert* or
264 *assret* will raise an :exc:`AttributeError`. Passing ``unsafe=True``
265 will allow access to these attributes.
Kushal Das8c145342014-04-16 23:32:21 +0530266
267 .. versionadded:: 3.5
268
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300269 * *wraps*: Item for the mock object to wrap. If *wraps* is not ``None`` then
Michael Foord944e02d2012-03-25 23:12:55 +0100270 calling the Mock will pass the call through to the wrapped object
Michael Foord0682a0c2012-04-13 20:51:20 +0100271 (returning the real result). Attribute access on the mock will return a
272 Mock object that wraps the corresponding attribute of the wrapped
273 object (so attempting to access an attribute that doesn't exist will
Georg Brandl7ad3df62014-10-31 07:59:37 +0100274 raise an :exc:`AttributeError`).
Michael Foord944e02d2012-03-25 23:12:55 +0100275
Georg Brandl7ad3df62014-10-31 07:59:37 +0100276 If the mock has an explicit *return_value* set then calls are not passed
277 to the wrapped object and the *return_value* is returned instead.
Michael Foord944e02d2012-03-25 23:12:55 +0100278
Georg Brandl7ad3df62014-10-31 07:59:37 +0100279 * *name*: If the mock has a name then it will be used in the repr of the
Michael Foord944e02d2012-03-25 23:12:55 +0100280 mock. This can be useful for debugging. The name is propagated to child
281 mocks.
282
283 Mocks can also be called with arbitrary keyword arguments. These will be
284 used to set attributes on the mock after it is created. See the
285 :meth:`configure_mock` method for details.
286
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100287 .. method:: assert_called(*args, **kwargs)
288
289 Assert that the mock was called at least once.
290
291 >>> mock = Mock()
292 >>> mock.method()
293 <Mock name='mock.method()' id='...'>
294 >>> mock.method.assert_called()
295
296 .. versionadded:: 3.6
297
298 .. method:: assert_called_once(*args, **kwargs)
299
300 Assert that the mock was called exactly once.
301
302 >>> mock = Mock()
303 >>> mock.method()
304 <Mock name='mock.method()' id='...'>
305 >>> mock.method.assert_called_once()
306 >>> mock.method()
307 <Mock name='mock.method()' id='...'>
308 >>> mock.method.assert_called_once()
309 Traceback (most recent call last):
310 ...
311 AssertionError: Expected 'method' to have been called once. Called 2 times.
312
313 .. versionadded:: 3.6
314
Michael Foord944e02d2012-03-25 23:12:55 +0100315
316 .. method:: assert_called_with(*args, **kwargs)
317
318 This method is a convenient way of asserting that calls are made in a
319 particular way:
320
321 >>> mock = Mock()
322 >>> mock.method(1, 2, 3, test='wow')
323 <Mock name='mock.method()' id='...'>
324 >>> mock.method.assert_called_with(1, 2, 3, test='wow')
325
Michael Foord944e02d2012-03-25 23:12:55 +0100326 .. method:: assert_called_once_with(*args, **kwargs)
327
Arne de Laat324c5d82017-02-23 15:57:25 +0100328 Assert that the mock was called exactly once and that that call was
329 with the specified arguments.
Michael Foord944e02d2012-03-25 23:12:55 +0100330
331 >>> mock = Mock(return_value=None)
332 >>> mock('foo', bar='baz')
333 >>> mock.assert_called_once_with('foo', bar='baz')
Arne de Laat324c5d82017-02-23 15:57:25 +0100334 >>> mock('other', bar='values')
335 >>> mock.assert_called_once_with('other', bar='values')
Michael Foord944e02d2012-03-25 23:12:55 +0100336 Traceback (most recent call last):
337 ...
Michael Foord28d591c2012-09-28 16:15:22 +0100338 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foord944e02d2012-03-25 23:12:55 +0100339
340
341 .. method:: assert_any_call(*args, **kwargs)
342
343 assert the mock has been called with the specified arguments.
344
345 The assert passes if the mock has *ever* been called, unlike
346 :meth:`assert_called_with` and :meth:`assert_called_once_with` that
Arne de Laat324c5d82017-02-23 15:57:25 +0100347 only pass if the call is the most recent one, and in the case of
348 :meth:`assert_called_once_with` it must also be the only call.
Michael Foord944e02d2012-03-25 23:12:55 +0100349
350 >>> mock = Mock(return_value=None)
351 >>> mock(1, 2, arg='thing')
352 >>> mock('some', 'thing', 'else')
353 >>> mock.assert_any_call(1, 2, arg='thing')
354
355
356 .. method:: assert_has_calls(calls, any_order=False)
357
358 assert the mock has been called with the specified calls.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100359 The :attr:`mock_calls` list is checked for the calls.
Michael Foord944e02d2012-03-25 23:12:55 +0100360
Georg Brandl7ad3df62014-10-31 07:59:37 +0100361 If *any_order* is false (the default) then the calls must be
Michael Foord944e02d2012-03-25 23:12:55 +0100362 sequential. There can be extra calls before or after the
363 specified calls.
364
Georg Brandl7ad3df62014-10-31 07:59:37 +0100365 If *any_order* is true then the calls can be in any order, but
Michael Foord944e02d2012-03-25 23:12:55 +0100366 they must all appear in :attr:`mock_calls`.
367
368 >>> mock = Mock(return_value=None)
369 >>> mock(1)
370 >>> mock(2)
371 >>> mock(3)
372 >>> mock(4)
373 >>> calls = [call(2), call(3)]
374 >>> mock.assert_has_calls(calls)
375 >>> calls = [call(4), call(2), call(3)]
376 >>> mock.assert_has_calls(calls, any_order=True)
377
Berker Peksagebf9fd32016-07-17 15:26:46 +0300378 .. method:: assert_not_called()
Kushal Das8af9db32014-04-17 01:36:14 +0530379
380 Assert the mock was never called.
381
382 >>> m = Mock()
383 >>> m.hello.assert_not_called()
384 >>> obj = m.hello()
385 >>> m.hello.assert_not_called()
386 Traceback (most recent call last):
387 ...
388 AssertionError: Expected 'hello' to not have been called. Called 1 times.
389
390 .. versionadded:: 3.5
391
Michael Foord944e02d2012-03-25 23:12:55 +0100392
Kushal Das9cd39a12016-06-02 10:20:16 -0700393 .. method:: reset_mock(*, return_value=False, side_effect=False)
Michael Foord944e02d2012-03-25 23:12:55 +0100394
395 The reset_mock method resets all the call attributes on a mock object:
396
397 >>> mock = Mock(return_value=None)
398 >>> mock('hello')
399 >>> mock.called
400 True
401 >>> mock.reset_mock()
402 >>> mock.called
403 False
404
Kushal Das9cd39a12016-06-02 10:20:16 -0700405 .. versionchanged:: 3.6
406 Added two keyword only argument to the reset_mock function.
407
Michael Foord944e02d2012-03-25 23:12:55 +0100408 This can be useful where you want to make a series of assertions that
Georg Brandl7ad3df62014-10-31 07:59:37 +0100409 reuse the same object. Note that :meth:`reset_mock` *doesn't* clear the
Michael Foord944e02d2012-03-25 23:12:55 +0100410 return value, :attr:`side_effect` or any child attributes you have
Kushal Das9cd39a12016-06-02 10:20:16 -0700411 set using normal assignment by default. In case you want to reset
412 *return_value* or :attr:`side_effect`, then pass the corresponding
413 parameter as ``True``. Child mocks and the return value mock
Michael Foord944e02d2012-03-25 23:12:55 +0100414 (if any) are reset as well.
415
Kushal Das9cd39a12016-06-02 10:20:16 -0700416 .. note:: *return_value*, and :attr:`side_effect` are keyword only
417 argument.
418
Michael Foord944e02d2012-03-25 23:12:55 +0100419
420 .. method:: mock_add_spec(spec, spec_set=False)
421
Georg Brandl7ad3df62014-10-31 07:59:37 +0100422 Add a spec to a mock. *spec* can either be an object or a
423 list of strings. Only attributes on the *spec* can be fetched as
Michael Foord944e02d2012-03-25 23:12:55 +0100424 attributes from the mock.
425
Georg Brandl7ad3df62014-10-31 07:59:37 +0100426 If *spec_set* is true then only attributes on the spec can be set.
Michael Foord944e02d2012-03-25 23:12:55 +0100427
428
429 .. method:: attach_mock(mock, attribute)
430
431 Attach a mock as an attribute of this one, replacing its name and
432 parent. Calls to the attached mock will be recorded in the
433 :attr:`method_calls` and :attr:`mock_calls` attributes of this one.
434
435
436 .. method:: configure_mock(**kwargs)
437
438 Set attributes on the mock through keyword arguments.
439
440 Attributes plus return values and side effects can be set on child
441 mocks using standard dot notation and unpacking a dictionary in the
442 method call:
443
444 >>> mock = Mock()
445 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
446 >>> mock.configure_mock(**attrs)
447 >>> mock.method()
448 3
449 >>> mock.other()
450 Traceback (most recent call last):
451 ...
452 KeyError
453
454 The same thing can be achieved in the constructor call to mocks:
455
456 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
457 >>> mock = Mock(some_attribute='eggs', **attrs)
458 >>> mock.some_attribute
459 'eggs'
460 >>> mock.method()
461 3
462 >>> mock.other()
463 Traceback (most recent call last):
464 ...
465 KeyError
466
Georg Brandl7ad3df62014-10-31 07:59:37 +0100467 :meth:`configure_mock` exists to make it easier to do configuration
Michael Foord944e02d2012-03-25 23:12:55 +0100468 after the mock has been created.
469
470
471 .. method:: __dir__()
472
Georg Brandl7ad3df62014-10-31 07:59:37 +0100473 :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results.
474 For mocks with a *spec* this includes all the permitted attributes
Michael Foord944e02d2012-03-25 23:12:55 +0100475 for the mock.
476
477 See :data:`FILTER_DIR` for what this filtering does, and how to
478 switch it off.
479
480
481 .. method:: _get_child_mock(**kw)
482
483 Create the child mocks for attributes and return value.
484 By default child mocks will be the same type as the parent.
485 Subclasses of Mock may want to override this to customize the way
486 child mocks are made.
487
488 For non-callable mocks the callable variant will be used (rather than
489 any custom subclass).
490
491
492 .. attribute:: called
493
494 A boolean representing whether or not the mock object has been called:
495
496 >>> mock = Mock(return_value=None)
497 >>> mock.called
498 False
499 >>> mock()
500 >>> mock.called
501 True
502
503 .. attribute:: call_count
504
505 An integer telling you how many times the mock object has been called:
506
507 >>> mock = Mock(return_value=None)
508 >>> mock.call_count
509 0
510 >>> mock()
511 >>> mock()
512 >>> mock.call_count
513 2
514
515
516 .. attribute:: return_value
517
518 Set this to configure the value returned by calling the mock:
519
520 >>> mock = Mock()
521 >>> mock.return_value = 'fish'
522 >>> mock()
523 'fish'
524
525 The default return value is a mock object and you can configure it in
526 the normal way:
527
528 >>> mock = Mock()
529 >>> mock.return_value.attribute = sentinel.Attribute
530 >>> mock.return_value()
531 <Mock name='mock()()' id='...'>
532 >>> mock.return_value.assert_called_with()
533
Georg Brandl7ad3df62014-10-31 07:59:37 +0100534 :attr:`return_value` can also be set in the constructor:
Michael Foord944e02d2012-03-25 23:12:55 +0100535
536 >>> mock = Mock(return_value=3)
537 >>> mock.return_value
538 3
539 >>> mock()
540 3
541
542
543 .. attribute:: side_effect
544
545 This can either be a function to be called when the mock is called,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100546 an iterable or an exception (class or instance) to be raised.
Michael Foord944e02d2012-03-25 23:12:55 +0100547
548 If you pass in a function it will be called with same arguments as the
549 mock and unless the function returns the :data:`DEFAULT` singleton the
550 call to the mock will then return whatever the function returns. If the
551 function returns :data:`DEFAULT` then the mock will return its normal
Brett Cannon533f1ed2013-05-25 11:28:20 -0400552 value (from the :attr:`return_value`).
Michael Foord944e02d2012-03-25 23:12:55 +0100553
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100554 If you pass in an iterable, it is used to retrieve an iterator which
555 must yield a value on every call. This value can either be an exception
556 instance to be raised, or a value to be returned from the call to the
557 mock (:data:`DEFAULT` handling is identical to the function case).
558
Michael Foord944e02d2012-03-25 23:12:55 +0100559 An example of a mock that raises an exception (to test exception
560 handling of an API):
561
562 >>> mock = Mock()
563 >>> mock.side_effect = Exception('Boom!')
564 >>> mock()
565 Traceback (most recent call last):
566 ...
567 Exception: Boom!
568
Georg Brandl7ad3df62014-10-31 07:59:37 +0100569 Using :attr:`side_effect` to return a sequence of values:
Michael Foord944e02d2012-03-25 23:12:55 +0100570
571 >>> mock = Mock()
572 >>> mock.side_effect = [3, 2, 1]
573 >>> mock(), mock(), mock()
574 (3, 2, 1)
575
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100576 Using a callable:
Michael Foord944e02d2012-03-25 23:12:55 +0100577
578 >>> mock = Mock(return_value=3)
579 >>> def side_effect(*args, **kwargs):
580 ... return DEFAULT
581 ...
582 >>> mock.side_effect = side_effect
583 >>> mock()
584 3
585
Georg Brandl7ad3df62014-10-31 07:59:37 +0100586 :attr:`side_effect` can be set in the constructor. Here's an example that
Michael Foord944e02d2012-03-25 23:12:55 +0100587 adds one to the value the mock is called with and returns it:
588
589 >>> side_effect = lambda value: value + 1
590 >>> mock = Mock(side_effect=side_effect)
591 >>> mock(3)
592 4
593 >>> mock(-8)
594 -7
595
Georg Brandl7ad3df62014-10-31 07:59:37 +0100596 Setting :attr:`side_effect` to ``None`` clears it:
Michael Foord944e02d2012-03-25 23:12:55 +0100597
598 >>> m = Mock(side_effect=KeyError, return_value=3)
599 >>> m()
600 Traceback (most recent call last):
601 ...
602 KeyError
603 >>> m.side_effect = None
604 >>> m()
605 3
606
607
608 .. attribute:: call_args
609
Georg Brandl7ad3df62014-10-31 07:59:37 +0100610 This is either ``None`` (if the mock hasn't been called), or the
Michael Foord944e02d2012-03-25 23:12:55 +0100611 arguments that the mock was last called with. This will be in the
Kumar Akshayb0df45e2019-03-22 13:40:40 +0530612 form of a tuple: the first member, which can also be accessed through
613 the ``args`` property, is any ordered arguments the mock was
614 called with (or an empty tuple) and the second member, which can
615 also be accessed through the ``kwargs`` property, is any keyword
616 arguments (or an empty dictionary).
Michael Foord944e02d2012-03-25 23:12:55 +0100617
618 >>> mock = Mock(return_value=None)
Berker Peksag920f6db2015-09-10 21:41:15 +0300619 >>> print(mock.call_args)
Michael Foord944e02d2012-03-25 23:12:55 +0100620 None
621 >>> mock()
622 >>> mock.call_args
623 call()
624 >>> mock.call_args == ()
625 True
626 >>> mock(3, 4)
627 >>> mock.call_args
628 call(3, 4)
629 >>> mock.call_args == ((3, 4),)
630 True
Kumar Akshayb0df45e2019-03-22 13:40:40 +0530631 >>> mock.call_args.args
632 (3, 4)
633 >>> mock.call_args.kwargs
634 {}
Michael Foord944e02d2012-03-25 23:12:55 +0100635 >>> mock(3, 4, 5, key='fish', next='w00t!')
636 >>> mock.call_args
637 call(3, 4, 5, key='fish', next='w00t!')
Kumar Akshayb0df45e2019-03-22 13:40:40 +0530638 >>> mock.call_args.args
639 (3, 4, 5)
640 >>> mock.call_args.kwargs
641 {'key': 'fish', 'next': 'w00t!'}
Michael Foord944e02d2012-03-25 23:12:55 +0100642
Georg Brandl7ad3df62014-10-31 07:59:37 +0100643 :attr:`call_args`, along with members of the lists :attr:`call_args_list`,
Michael Foord944e02d2012-03-25 23:12:55 +0100644 :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects.
645 These are tuples, so they can be unpacked to get at the individual
646 arguments and make more complex assertions. See
647 :ref:`calls as tuples <calls-as-tuples>`.
648
649
650 .. attribute:: call_args_list
651
652 This is a list of all the calls made to the mock object in sequence
653 (so the length of the list is the number of times it has been
654 called). Before any calls have been made it is an empty list. The
655 :data:`call` object can be used for conveniently constructing lists of
Georg Brandl7ad3df62014-10-31 07:59:37 +0100656 calls to compare with :attr:`call_args_list`.
Michael Foord944e02d2012-03-25 23:12:55 +0100657
658 >>> mock = Mock(return_value=None)
659 >>> mock()
660 >>> mock(3, 4)
661 >>> mock(key='fish', next='w00t!')
662 >>> mock.call_args_list
663 [call(), call(3, 4), call(key='fish', next='w00t!')]
664 >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
665 >>> mock.call_args_list == expected
666 True
667
Georg Brandl7ad3df62014-10-31 07:59:37 +0100668 Members of :attr:`call_args_list` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100669 unpacked as tuples to get at the individual arguments. See
670 :ref:`calls as tuples <calls-as-tuples>`.
671
672
673 .. attribute:: method_calls
674
675 As well as tracking calls to themselves, mocks also track calls to
676 methods and attributes, and *their* methods and attributes:
677
678 >>> mock = Mock()
679 >>> mock.method()
680 <Mock name='mock.method()' id='...'>
681 >>> mock.property.method.attribute()
682 <Mock name='mock.property.method.attribute()' id='...'>
683 >>> mock.method_calls
684 [call.method(), call.property.method.attribute()]
685
Georg Brandl7ad3df62014-10-31 07:59:37 +0100686 Members of :attr:`method_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100687 unpacked as tuples to get at the individual arguments. See
688 :ref:`calls as tuples <calls-as-tuples>`.
689
690
691 .. attribute:: mock_calls
692
Georg Brandl7ad3df62014-10-31 07:59:37 +0100693 :attr:`mock_calls` records *all* calls to the mock object, its methods,
694 magic methods *and* return value mocks.
Michael Foord944e02d2012-03-25 23:12:55 +0100695
696 >>> mock = MagicMock()
697 >>> result = mock(1, 2, 3)
698 >>> mock.first(a=3)
699 <MagicMock name='mock.first()' id='...'>
700 >>> mock.second()
701 <MagicMock name='mock.second()' id='...'>
702 >>> int(mock)
703 1
704 >>> result(1)
705 <MagicMock name='mock()()' id='...'>
706 >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
707 ... call.__int__(), call()(1)]
708 >>> mock.mock_calls == expected
709 True
710
Georg Brandl7ad3df62014-10-31 07:59:37 +0100711 Members of :attr:`mock_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100712 unpacked as tuples to get at the individual arguments. See
713 :ref:`calls as tuples <calls-as-tuples>`.
714
Chris Withers8ca0fa92018-12-03 21:31:37 +0000715 .. note::
716
717 The way :attr:`mock_calls` are recorded means that where nested
718 calls are made, the parameters of ancestor calls are not recorded
719 and so will always compare equal:
720
721 >>> mock = MagicMock()
722 >>> mock.top(a=3).bottom()
723 <MagicMock name='mock.top().bottom()' id='...'>
724 >>> mock.mock_calls
725 [call.top(a=3), call.top().bottom()]
726 >>> mock.mock_calls[-1] == call.top(a=-1).bottom()
727 True
Michael Foord944e02d2012-03-25 23:12:55 +0100728
729 .. attribute:: __class__
730
Georg Brandl7ad3df62014-10-31 07:59:37 +0100731 Normally the :attr:`__class__` attribute of an object will return its type.
732 For a mock object with a :attr:`spec`, ``__class__`` returns the spec class
733 instead. This allows mock objects to pass :func:`isinstance` tests for the
Michael Foord944e02d2012-03-25 23:12:55 +0100734 object they are replacing / masquerading as:
735
736 >>> mock = Mock(spec=3)
737 >>> isinstance(mock, int)
738 True
739
Georg Brandl7ad3df62014-10-31 07:59:37 +0100740 :attr:`__class__` is assignable to, this allows a mock to pass an
741 :func:`isinstance` check without forcing you to use a spec:
Michael Foord944e02d2012-03-25 23:12:55 +0100742
743 >>> mock = Mock()
744 >>> mock.__class__ = dict
745 >>> isinstance(mock, dict)
746 True
747
748.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
749
Georg Brandl7ad3df62014-10-31 07:59:37 +0100750 A non-callable version of :class:`Mock`. The constructor parameters have the same
751 meaning of :class:`Mock`, with the exception of *return_value* and *side_effect*
Michael Foord944e02d2012-03-25 23:12:55 +0100752 which have no meaning on a non-callable mock.
753
Georg Brandl7ad3df62014-10-31 07:59:37 +0100754Mock objects that use a class or an instance as a :attr:`spec` or
755:attr:`spec_set` are able to pass :func:`isinstance` tests:
Michael Foord944e02d2012-03-25 23:12:55 +0100756
757 >>> mock = Mock(spec=SomeClass)
758 >>> isinstance(mock, SomeClass)
759 True
760 >>> mock = Mock(spec_set=SomeClass())
761 >>> isinstance(mock, SomeClass)
762 True
763
Georg Brandl7ad3df62014-10-31 07:59:37 +0100764The :class:`Mock` classes have support for mocking magic methods. See :ref:`magic
Michael Foord944e02d2012-03-25 23:12:55 +0100765methods <magic-methods>` for the full details.
766
767The mock classes and the :func:`patch` decorators all take arbitrary keyword
Georg Brandl7ad3df62014-10-31 07:59:37 +0100768arguments for configuration. For the :func:`patch` decorators the keywords are
Michael Foord944e02d2012-03-25 23:12:55 +0100769passed to the constructor of the mock being created. The keyword arguments
770are for configuring attributes of the mock:
771
772 >>> m = MagicMock(attribute=3, other='fish')
773 >>> m.attribute
774 3
775 >>> m.other
776 'fish'
777
778The return value and side effect of child mocks can be set in the same way,
779using dotted notation. As you can't use dotted names directly in a call you
Georg Brandl7ad3df62014-10-31 07:59:37 +0100780have to create a dictionary and unpack it using ``**``:
Michael Foord944e02d2012-03-25 23:12:55 +0100781
782 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
783 >>> mock = Mock(some_attribute='eggs', **attrs)
784 >>> mock.some_attribute
785 'eggs'
786 >>> mock.method()
787 3
788 >>> mock.other()
789 Traceback (most recent call last):
790 ...
791 KeyError
792
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100793A callable mock which was created with a *spec* (or a *spec_set*) will
794introspect the specification object's signature when matching calls to
795the mock. Therefore, it can match the actual call's arguments regardless
796of whether they were passed positionally or by name::
797
798 >>> def f(a, b, c): pass
799 ...
800 >>> mock = Mock(spec=f)
801 >>> mock(1, 2, c=3)
802 <Mock name='mock()' id='140161580456576'>
803 >>> mock.assert_called_with(1, 2, 3)
804 >>> mock.assert_called_with(a=1, b=2, c=3)
805
806This applies to :meth:`~Mock.assert_called_with`,
807:meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and
808:meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also
809apply to method calls on the mock object.
810
811 .. versionchanged:: 3.4
812 Added signature introspection on specced and autospecced mock objects.
813
Michael Foord944e02d2012-03-25 23:12:55 +0100814
815.. class:: PropertyMock(*args, **kwargs)
816
817 A mock intended to be used as a property, or other descriptor, on a class.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100818 :class:`PropertyMock` provides :meth:`__get__` and :meth:`__set__` methods
819 so you can specify a return value when it is fetched.
Michael Foord944e02d2012-03-25 23:12:55 +0100820
Georg Brandl7ad3df62014-10-31 07:59:37 +0100821 Fetching a :class:`PropertyMock` instance from an object calls the mock, with
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200822 no args. Setting it calls the mock with the value being set. ::
Michael Foord944e02d2012-03-25 23:12:55 +0100823
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200824 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100825 ... @property
826 ... def foo(self):
827 ... return 'something'
828 ... @foo.setter
829 ... def foo(self, value):
830 ... pass
831 ...
832 >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
833 ... mock_foo.return_value = 'mockity-mock'
834 ... this_foo = Foo()
Berker Peksag920f6db2015-09-10 21:41:15 +0300835 ... print(this_foo.foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100836 ... this_foo.foo = 6
837 ...
838 mockity-mock
839 >>> mock_foo.mock_calls
840 [call(), call(6)]
841
Michael Foordc2870622012-04-13 16:57:22 +0100842Because of the way mock attributes are stored you can't directly attach a
Georg Brandl7ad3df62014-10-31 07:59:37 +0100843:class:`PropertyMock` to a mock object. Instead you can attach it to the mock type
Michael Foordc2870622012-04-13 16:57:22 +0100844object::
845
846 >>> m = MagicMock()
847 >>> p = PropertyMock(return_value=3)
848 >>> type(m).foo = p
849 >>> m.foo
850 3
851 >>> p.assert_called_once_with()
852
Michael Foord944e02d2012-03-25 23:12:55 +0100853
854Calling
855~~~~~~~
856
857Mock objects are callable. The call will return the value set as the
858:attr:`~Mock.return_value` attribute. The default return value is a new Mock
859object; it is created the first time the return value is accessed (either
860explicitly or by calling the Mock) - but it is stored and the same one
861returned each time.
862
863Calls made to the object will be recorded in the attributes
864like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
865
866If :attr:`~Mock.side_effect` is set then it will be called after the call has
Georg Brandl7ad3df62014-10-31 07:59:37 +0100867been recorded, so if :attr:`side_effect` raises an exception the call is still
Michael Foord944e02d2012-03-25 23:12:55 +0100868recorded.
869
870The simplest way to make a mock raise an exception when called is to make
871:attr:`~Mock.side_effect` an exception class or instance:
872
873 >>> m = MagicMock(side_effect=IndexError)
874 >>> m(1, 2, 3)
875 Traceback (most recent call last):
876 ...
877 IndexError
878 >>> m.mock_calls
879 [call(1, 2, 3)]
880 >>> m.side_effect = KeyError('Bang!')
881 >>> m('two', 'three', 'four')
882 Traceback (most recent call last):
883 ...
884 KeyError: 'Bang!'
885 >>> m.mock_calls
886 [call(1, 2, 3), call('two', 'three', 'four')]
887
Georg Brandl7ad3df62014-10-31 07:59:37 +0100888If :attr:`side_effect` is a function then whatever that function returns is what
889calls to the mock return. The :attr:`side_effect` function is called with the
Michael Foord944e02d2012-03-25 23:12:55 +0100890same arguments as the mock. This allows you to vary the return value of the
891call dynamically, based on the input:
892
893 >>> def side_effect(value):
894 ... return value + 1
895 ...
896 >>> m = MagicMock(side_effect=side_effect)
897 >>> m(1)
898 2
899 >>> m(2)
900 3
901 >>> m.mock_calls
902 [call(1), call(2)]
903
904If you want the mock to still return the default return value (a new mock), or
905any set return value, then there are two ways of doing this. Either return
Georg Brandl7ad3df62014-10-31 07:59:37 +0100906:attr:`mock.return_value` from inside :attr:`side_effect`, or return :data:`DEFAULT`:
Michael Foord944e02d2012-03-25 23:12:55 +0100907
908 >>> m = MagicMock()
909 >>> def side_effect(*args, **kwargs):
910 ... return m.return_value
911 ...
912 >>> m.side_effect = side_effect
913 >>> m.return_value = 3
914 >>> m()
915 3
916 >>> def side_effect(*args, **kwargs):
917 ... return DEFAULT
918 ...
919 >>> m.side_effect = side_effect
920 >>> m()
921 3
922
Georg Brandl7ad3df62014-10-31 07:59:37 +0100923To remove a :attr:`side_effect`, and return to the default behaviour, set the
924:attr:`side_effect` to ``None``:
Michael Foord944e02d2012-03-25 23:12:55 +0100925
926 >>> m = MagicMock(return_value=6)
927 >>> def side_effect(*args, **kwargs):
928 ... return 3
929 ...
930 >>> m.side_effect = side_effect
931 >>> m()
932 3
933 >>> m.side_effect = None
934 >>> m()
935 6
936
Georg Brandl7ad3df62014-10-31 07:59:37 +0100937The :attr:`side_effect` can also be any iterable object. Repeated calls to the mock
Michael Foord944e02d2012-03-25 23:12:55 +0100938will return values from the iterable (until the iterable is exhausted and
Georg Brandl7ad3df62014-10-31 07:59:37 +0100939a :exc:`StopIteration` is raised):
Michael Foord944e02d2012-03-25 23:12:55 +0100940
941 >>> m = MagicMock(side_effect=[1, 2, 3])
942 >>> m()
943 1
944 >>> m()
945 2
946 >>> m()
947 3
948 >>> m()
949 Traceback (most recent call last):
950 ...
951 StopIteration
952
Michael Foord2cd48732012-04-21 15:52:11 +0100953If any members of the iterable are exceptions they will be raised instead of
954returned::
955
956 >>> iterable = (33, ValueError, 66)
957 >>> m = MagicMock(side_effect=iterable)
958 >>> m()
959 33
960 >>> m()
961 Traceback (most recent call last):
962 ...
963 ValueError
964 >>> m()
965 66
966
Michael Foord944e02d2012-03-25 23:12:55 +0100967
968.. _deleting-attributes:
969
970Deleting Attributes
971~~~~~~~~~~~~~~~~~~~
972
973Mock objects create attributes on demand. This allows them to pretend to be
974objects of any type.
975
Georg Brandl7ad3df62014-10-31 07:59:37 +0100976You may want a mock object to return ``False`` to a :func:`hasattr` call, or raise an
977:exc:`AttributeError` when an attribute is fetched. You can do this by providing
978an object as a :attr:`spec` for a mock, but that isn't always convenient.
Michael Foord944e02d2012-03-25 23:12:55 +0100979
980You "block" attributes by deleting them. Once deleted, accessing an attribute
Georg Brandl7ad3df62014-10-31 07:59:37 +0100981will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100982
983 >>> mock = MagicMock()
984 >>> hasattr(mock, 'm')
985 True
986 >>> del mock.m
987 >>> hasattr(mock, 'm')
988 False
989 >>> del mock.f
990 >>> mock.f
991 Traceback (most recent call last):
992 ...
993 AttributeError: f
994
995
Michael Foordf5752302013-03-18 15:04:03 -0700996Mock names and the name attribute
997~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
998
999Since "name" is an argument to the :class:`Mock` constructor, if you want your
1000mock object to have a "name" attribute you can't just pass it in at creation
1001time. There are two alternatives. One option is to use
1002:meth:`~Mock.configure_mock`::
1003
1004 >>> mock = MagicMock()
1005 >>> mock.configure_mock(name='my_name')
1006 >>> mock.name
1007 'my_name'
1008
1009A simpler option is to simply set the "name" attribute after mock creation::
1010
1011 >>> mock = MagicMock()
1012 >>> mock.name = "foo"
1013
1014
Michael Foord944e02d2012-03-25 23:12:55 +01001015Attaching Mocks as Attributes
1016~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1017
1018When you attach a mock as an attribute of another mock (or as the return
1019value) it becomes a "child" of that mock. Calls to the child are recorded in
1020the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
1021parent. This is useful for configuring child mocks and then attaching them to
1022the parent, or for attaching mocks to a parent that records all calls to the
1023children and allows you to make assertions about the order of calls between
1024mocks:
1025
1026 >>> parent = MagicMock()
1027 >>> child1 = MagicMock(return_value=None)
1028 >>> child2 = MagicMock(return_value=None)
1029 >>> parent.child1 = child1
1030 >>> parent.child2 = child2
1031 >>> child1(1)
1032 >>> child2(2)
1033 >>> parent.mock_calls
1034 [call.child1(1), call.child2(2)]
1035
1036The exception to this is if the mock has a name. This allows you to prevent
1037the "parenting" if for some reason you don't want it to happen.
1038
1039 >>> mock = MagicMock()
1040 >>> not_a_child = MagicMock(name='not-a-child')
1041 >>> mock.attribute = not_a_child
1042 >>> mock.attribute()
1043 <MagicMock name='not-a-child()' id='...'>
1044 >>> mock.mock_calls
1045 []
1046
1047Mocks created for you by :func:`patch` are automatically given names. To
1048attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001049method::
Michael Foord944e02d2012-03-25 23:12:55 +01001050
1051 >>> thing1 = object()
1052 >>> thing2 = object()
1053 >>> parent = MagicMock()
1054 >>> with patch('__main__.thing1', return_value=None) as child1:
1055 ... with patch('__main__.thing2', return_value=None) as child2:
1056 ... parent.attach_mock(child1, 'child1')
1057 ... parent.attach_mock(child2, 'child2')
1058 ... child1('one')
1059 ... child2('two')
1060 ...
1061 >>> parent.mock_calls
1062 [call.child1('one'), call.child2('two')]
1063
1064
1065.. [#] The only exceptions are magic methods and attributes (those that have
1066 leading and trailing double underscores). Mock doesn't create these but
Georg Brandl7ad3df62014-10-31 07:59:37 +01001067 instead raises an :exc:`AttributeError`. This is because the interpreter
Michael Foord944e02d2012-03-25 23:12:55 +01001068 will often implicitly request these methods, and gets *very* confused to
1069 get a new Mock object when it expects a magic method. If you need magic
1070 method support see :ref:`magic methods <magic-methods>`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001071
1072
1073The patchers
Georg Brandlfb134382013-02-03 11:47:49 +01001074------------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001075
1076The patch decorators are used for patching objects only within the scope of
1077the function they decorate. They automatically handle the unpatching for you,
1078even if exceptions are raised. All of these functions can also be used in with
1079statements or as class decorators.
1080
1081
1082patch
Georg Brandlfb134382013-02-03 11:47:49 +01001083~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001084
1085.. note::
1086
Georg Brandl7ad3df62014-10-31 07:59:37 +01001087 :func:`patch` is straightforward to use. The key is to do the patching in the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001088 right namespace. See the section `where to patch`_.
1089
1090.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1091
Georg Brandl7ad3df62014-10-31 07:59:37 +01001092 :func:`patch` acts as a function decorator, class decorator or a context
1093 manager. Inside the body of the function or with statement, the *target*
1094 is patched with a *new* object. When the function/with statement exits
Michael Foord54b3db82012-03-28 15:08:08 +01001095 the patch is undone.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001096
Georg Brandl7ad3df62014-10-31 07:59:37 +01001097 If *new* is omitted, then the target is replaced with a
1098 :class:`MagicMock`. If :func:`patch` is used as a decorator and *new* is
Michael Foord54b3db82012-03-28 15:08:08 +01001099 omitted, the created mock is passed in as an extra argument to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001100 decorated function. If :func:`patch` is used as a context manager the created
Michael Foord54b3db82012-03-28 15:08:08 +01001101 mock is returned by the context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001102
Georg Brandl7ad3df62014-10-31 07:59:37 +01001103 *target* should be a string in the form ``'package.module.ClassName'``. The
1104 *target* is imported and the specified object replaced with the *new*
1105 object, so the *target* must be importable from the environment you are
1106 calling :func:`patch` from. The target is imported when the decorated function
Michael Foord54b3db82012-03-28 15:08:08 +01001107 is executed, not at decoration time.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001108
Georg Brandl7ad3df62014-10-31 07:59:37 +01001109 The *spec* and *spec_set* keyword arguments are passed to the :class:`MagicMock`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001110 if patch is creating one for you.
1111
Georg Brandl7ad3df62014-10-31 07:59:37 +01001112 In addition you can pass ``spec=True`` or ``spec_set=True``, which causes
Michael Foorda9e6fb22012-03-28 14:36:02 +01001113 patch to pass in the object being mocked as the spec/spec_set object.
1114
Georg Brandl7ad3df62014-10-31 07:59:37 +01001115 *new_callable* allows you to specify a different class, or callable object,
1116 that will be called to create the *new* object. By default :class:`MagicMock` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001117 used.
1118
Georg Brandl7ad3df62014-10-31 07:59:37 +01001119 A more powerful form of *spec* is *autospec*. If you set ``autospec=True``
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001120 then the mock will be created with a spec from the object being replaced.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001121 All attributes of the mock will also have the spec of the corresponding
1122 attribute of the object being replaced. Methods and functions being mocked
Georg Brandl7ad3df62014-10-31 07:59:37 +01001123 will have their arguments checked and will raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001124 called with the wrong signature. For mocks
1125 replacing a class, their return value (the 'instance') will have the same
1126 spec as the class. See the :func:`create_autospec` function and
1127 :ref:`auto-speccing`.
1128
Georg Brandl7ad3df62014-10-31 07:59:37 +01001129 Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001130 arbitrary object as the spec instead of the one being replaced.
1131
Pablo Galindod6acf172019-01-09 21:43:24 +00001132 By default :func:`patch` will fail to replace attributes that don't exist.
1133 If you pass in ``create=True``, and the attribute doesn't exist, patch will
1134 create the attribute for you when the patched function is called, and delete
1135 it again after the patched function has exited. This is useful for writing
1136 tests against attributes that your production code creates at runtime. It is
1137 off by default because it can be dangerous. With it switched on you can
1138 write passing tests against APIs that don't actually exist!
Michael Foorda9e6fb22012-03-28 14:36:02 +01001139
Michael Foordfddcfa22014-04-14 16:25:20 -04001140 .. note::
1141
1142 .. versionchanged:: 3.5
1143 If you are patching builtins in a module then you don't
Georg Brandl7ad3df62014-10-31 07:59:37 +01001144 need to pass ``create=True``, it will be added by default.
Michael Foordfddcfa22014-04-14 16:25:20 -04001145
Georg Brandl7ad3df62014-10-31 07:59:37 +01001146 Patch can be used as a :class:`TestCase` class decorator. It works by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001147 decorating each test method in the class. This reduces the boilerplate
Georg Brandl7ad3df62014-10-31 07:59:37 +01001148 code when your test methods share a common patchings set. :func:`patch` finds
1149 tests by looking for method names that start with ``patch.TEST_PREFIX``.
1150 By default this is ``'test'``, which matches the way :mod:`unittest` finds tests.
1151 You can specify an alternative prefix by setting ``patch.TEST_PREFIX``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001152
1153 Patch can be used as a context manager, with the with statement. Here the
1154 patching applies to the indented block after the with statement. If you
1155 use "as" then the patched object will be bound to the name after the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001156 "as"; very useful if :func:`patch` is creating a mock object for you.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001157
Georg Brandl7ad3df62014-10-31 07:59:37 +01001158 :func:`patch` takes arbitrary keyword arguments. These will be passed to
1159 the :class:`Mock` (or *new_callable*) on construction.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001160
Georg Brandl7ad3df62014-10-31 07:59:37 +01001161 ``patch.dict(...)``, ``patch.multiple(...)`` and ``patch.object(...)`` are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001162 available for alternate use-cases.
1163
Georg Brandl7ad3df62014-10-31 07:59:37 +01001164:func:`patch` as function decorator, creating the mock for you and passing it into
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001165the decorated function::
Michael Foord90155362012-03-28 15:32:08 +01001166
1167 >>> @patch('__main__.SomeClass')
Michael Foord324b58b2012-03-28 15:49:08 +01001168 ... def function(normal_argument, mock_class):
Michael Foord90155362012-03-28 15:32:08 +01001169 ... print(mock_class is SomeClass)
1170 ...
Michael Foord324b58b2012-03-28 15:49:08 +01001171 >>> function(None)
Michael Foord90155362012-03-28 15:32:08 +01001172 True
Michael Foorda9e6fb22012-03-28 14:36:02 +01001173
Georg Brandl7ad3df62014-10-31 07:59:37 +01001174Patching a class replaces the class with a :class:`MagicMock` *instance*. If the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001175class is instantiated in the code under test then it will be the
1176:attr:`~Mock.return_value` of the mock that will be used.
1177
1178If the class is instantiated multiple times you could use
1179:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
Georg Brandl7ad3df62014-10-31 07:59:37 +01001180can set the *return_value* to be anything you want.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001181
1182To configure return values on methods of *instances* on the patched class
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001183you must do this on the :attr:`return_value`. For example::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001184
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001185 >>> class Class:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001186 ... def method(self):
1187 ... pass
1188 ...
1189 >>> with patch('__main__.Class') as MockClass:
1190 ... instance = MockClass.return_value
1191 ... instance.method.return_value = 'foo'
1192 ... assert Class() is instance
1193 ... assert Class().method() == 'foo'
1194 ...
1195
Georg Brandl7ad3df62014-10-31 07:59:37 +01001196If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001197return value of the created mock will have the same spec. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001198
1199 >>> Original = Class
1200 >>> patcher = patch('__main__.Class', spec=True)
1201 >>> MockClass = patcher.start()
1202 >>> instance = MockClass()
1203 >>> assert isinstance(instance, Original)
1204 >>> patcher.stop()
1205
Georg Brandl7ad3df62014-10-31 07:59:37 +01001206The *new_callable* argument is useful where you want to use an alternative
Michael Foorda9e6fb22012-03-28 14:36:02 +01001207class to the default :class:`MagicMock` for the created mock. For example, if
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001208you wanted a :class:`NonCallableMock` to be used::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001209
1210 >>> thing = object()
1211 >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
1212 ... assert thing is mock_thing
1213 ... thing()
1214 ...
1215 Traceback (most recent call last):
1216 ...
1217 TypeError: 'NonCallableMock' object is not callable
1218
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001219Another use case might be to replace an object with an :class:`io.StringIO` instance::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001220
Serhiy Storchakae79be872013-08-17 00:09:55 +03001221 >>> from io import StringIO
Michael Foorda9e6fb22012-03-28 14:36:02 +01001222 >>> def foo():
Berker Peksag920f6db2015-09-10 21:41:15 +03001223 ... print('Something')
Michael Foorda9e6fb22012-03-28 14:36:02 +01001224 ...
1225 >>> @patch('sys.stdout', new_callable=StringIO)
1226 ... def test(mock_stdout):
1227 ... foo()
1228 ... assert mock_stdout.getvalue() == 'Something\n'
1229 ...
1230 >>> test()
1231
Georg Brandl7ad3df62014-10-31 07:59:37 +01001232When :func:`patch` is creating a mock for you, it is common that the first thing
Michael Foorda9e6fb22012-03-28 14:36:02 +01001233you need to do is to configure the mock. Some of that configuration can be done
1234in the call to patch. Any arbitrary keywords you pass into the call will be
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001235used to set attributes on the created mock::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001236
1237 >>> patcher = patch('__main__.thing', first='one', second='two')
1238 >>> mock_thing = patcher.start()
1239 >>> mock_thing.first
1240 'one'
1241 >>> mock_thing.second
1242 'two'
1243
1244As well as attributes on the created mock attributes, like the
1245:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
1246also be configured. These aren't syntactically valid to pass in directly as
1247keyword arguments, but a dictionary with these as keys can still be expanded
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001248into a :func:`patch` call using ``**``::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001249
1250 >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
1251 >>> patcher = patch('__main__.thing', **config)
1252 >>> mock_thing = patcher.start()
1253 >>> mock_thing.method()
1254 3
1255 >>> mock_thing.other()
1256 Traceback (most recent call last):
1257 ...
1258 KeyError
1259
Pablo Galindod6acf172019-01-09 21:43:24 +00001260By default, attempting to patch a function in a module (or a method or an
1261attribute in a class) that does not exist will fail with :exc:`AttributeError`::
1262
1263 >>> @patch('sys.non_existing_attribute', 42)
1264 ... def test():
1265 ... assert sys.non_existing_attribute == 42
1266 ...
1267 >>> test()
1268 Traceback (most recent call last):
1269 ...
1270 AttributeError: <module 'sys' (built-in)> does not have the attribute 'non_existing'
1271
1272but adding ``create=True`` in the call to :func:`patch` will make the previous example
1273work as expected::
1274
1275 >>> @patch('sys.non_existing_attribute', 42, create=True)
1276 ... def test(mock_stdout):
1277 ... assert sys.non_existing_attribute == 42
1278 ...
1279 >>> test()
1280
Michael Foorda9e6fb22012-03-28 14:36:02 +01001281
1282patch.object
Georg Brandlfb134382013-02-03 11:47:49 +01001283~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001284
1285.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1286
Georg Brandl7ad3df62014-10-31 07:59:37 +01001287 patch the named member (*attribute*) on an object (*target*) with a mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001288 object.
1289
Georg Brandl7ad3df62014-10-31 07:59:37 +01001290 :func:`patch.object` can be used as a decorator, class decorator or a context
1291 manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* and
1292 *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`,
1293 :func:`patch.object` takes arbitrary keyword arguments for configuring the mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001294 object it creates.
1295
Georg Brandl7ad3df62014-10-31 07:59:37 +01001296 When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001297 for choosing which methods to wrap.
1298
Georg Brandl7ad3df62014-10-31 07:59:37 +01001299You can either call :func:`patch.object` with three arguments or two arguments. The
Michael Foorda9e6fb22012-03-28 14:36:02 +01001300three argument form takes the object to be patched, the attribute name and the
1301object to replace the attribute with.
1302
1303When calling with the two argument form you omit the replacement object, and a
1304mock is created for you and passed in as an extra argument to the decorated
1305function:
1306
1307 >>> @patch.object(SomeClass, 'class_method')
1308 ... def test(mock_method):
1309 ... SomeClass.class_method(3)
1310 ... mock_method.assert_called_with(3)
1311 ...
1312 >>> test()
1313
Georg Brandl7ad3df62014-10-31 07:59:37 +01001314*spec*, *create* and the other arguments to :func:`patch.object` have the same
1315meaning as they do for :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001316
1317
1318patch.dict
Georg Brandlfb134382013-02-03 11:47:49 +01001319~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001320
1321.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs)
1322
1323 Patch a dictionary, or dictionary like object, and restore the dictionary
1324 to its original state after the test.
1325
Georg Brandl7ad3df62014-10-31 07:59:37 +01001326 *in_dict* can be a dictionary or a mapping like container. If it is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01001327 mapping then it must at least support getting, setting and deleting items
1328 plus iterating over keys.
1329
Georg Brandl7ad3df62014-10-31 07:59:37 +01001330 *in_dict* can also be a string specifying the name of the dictionary, which
Michael Foorda9e6fb22012-03-28 14:36:02 +01001331 will then be fetched by importing it.
1332
Georg Brandl7ad3df62014-10-31 07:59:37 +01001333 *values* can be a dictionary of values to set in the dictionary. *values*
1334 can also be an iterable of ``(key, value)`` pairs.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001335
Georg Brandl7ad3df62014-10-31 07:59:37 +01001336 If *clear* is true then the dictionary will be cleared before the new
Michael Foorda9e6fb22012-03-28 14:36:02 +01001337 values are set.
1338
Georg Brandl7ad3df62014-10-31 07:59:37 +01001339 :func:`patch.dict` can also be called with arbitrary keyword arguments to set
Michael Foorda9e6fb22012-03-28 14:36:02 +01001340 values in the dictionary.
1341
Georg Brandl7ad3df62014-10-31 07:59:37 +01001342 :func:`patch.dict` can be used as a context manager, decorator or class
1343 decorator. When used as a class decorator :func:`patch.dict` honours
1344 ``patch.TEST_PREFIX`` for choosing which methods to wrap.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001345
Georg Brandl7ad3df62014-10-31 07:59:37 +01001346:func:`patch.dict` can be used to add members to a dictionary, or simply let a test
Michael Foorda9e6fb22012-03-28 14:36:02 +01001347change a dictionary, and ensure the dictionary is restored when the test
1348ends.
1349
1350 >>> foo = {}
1351 >>> with patch.dict(foo, {'newkey': 'newvalue'}):
1352 ... assert foo == {'newkey': 'newvalue'}
1353 ...
1354 >>> assert foo == {}
1355
1356 >>> import os
1357 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
Berker Peksag920f6db2015-09-10 21:41:15 +03001358 ... print(os.environ['newkey'])
Michael Foorda9e6fb22012-03-28 14:36:02 +01001359 ...
1360 newvalue
1361 >>> assert 'newkey' not in os.environ
1362
Georg Brandl7ad3df62014-10-31 07:59:37 +01001363Keywords can be used in the :func:`patch.dict` call to set values in the dictionary:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001364
1365 >>> mymodule = MagicMock()
1366 >>> mymodule.function.return_value = 'fish'
1367 >>> with patch.dict('sys.modules', mymodule=mymodule):
1368 ... import mymodule
1369 ... mymodule.function('some', 'args')
1370 ...
1371 'fish'
1372
Georg Brandl7ad3df62014-10-31 07:59:37 +01001373:func:`patch.dict` can be used with dictionary like objects that aren't actually
Michael Foorda9e6fb22012-03-28 14:36:02 +01001374dictionaries. At the very minimum they must support item getting, setting,
1375deleting and either iteration or membership test. This corresponds to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001376magic methods :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__` and either
1377:meth:`__iter__` or :meth:`__contains__`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001378
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001379 >>> class Container:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001380 ... def __init__(self):
1381 ... self.values = {}
1382 ... def __getitem__(self, name):
1383 ... return self.values[name]
1384 ... def __setitem__(self, name, value):
1385 ... self.values[name] = value
1386 ... def __delitem__(self, name):
1387 ... del self.values[name]
1388 ... def __iter__(self):
1389 ... return iter(self.values)
1390 ...
1391 >>> thing = Container()
1392 >>> thing['one'] = 1
1393 >>> with patch.dict(thing, one=2, two=3):
1394 ... assert thing['one'] == 2
1395 ... assert thing['two'] == 3
1396 ...
1397 >>> assert thing['one'] == 1
1398 >>> assert list(thing) == ['one']
1399
1400
1401patch.multiple
Georg Brandlfb134382013-02-03 11:47:49 +01001402~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001403
1404.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1405
1406 Perform multiple patches in a single call. It takes the object to be
1407 patched (either as an object or a string to fetch the object by importing)
1408 and keyword arguments for the patches::
1409
1410 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1411 ...
1412
Georg Brandl7ad3df62014-10-31 07:59:37 +01001413 Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create
Michael Foorda9e6fb22012-03-28 14:36:02 +01001414 mocks for you. In this case the created mocks are passed into a decorated
Georg Brandl7ad3df62014-10-31 07:59:37 +01001415 function by keyword, and a dictionary is returned when :func:`patch.multiple` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001416 used as a context manager.
1417
Georg Brandl7ad3df62014-10-31 07:59:37 +01001418 :func:`patch.multiple` can be used as a decorator, class decorator or a context
1419 manager. The arguments *spec*, *spec_set*, *create*, *autospec* and
1420 *new_callable* have the same meaning as for :func:`patch`. These arguments will
1421 be applied to *all* patches done by :func:`patch.multiple`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001422
Georg Brandl7ad3df62014-10-31 07:59:37 +01001423 When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001424 for choosing which methods to wrap.
1425
Georg Brandl7ad3df62014-10-31 07:59:37 +01001426If you want :func:`patch.multiple` to create mocks for you, then you can use
1427:data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001428then the created mocks are passed into the decorated function by keyword. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001429
1430 >>> thing = object()
1431 >>> other = object()
1432
1433 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1434 ... def test_function(thing, other):
1435 ... assert isinstance(thing, MagicMock)
1436 ... assert isinstance(other, MagicMock)
1437 ...
1438 >>> test_function()
1439
Georg Brandl7ad3df62014-10-31 07:59:37 +01001440:func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001441passed by keyword *after* any of the standard arguments created by :func:`patch`::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001442
1443 >>> @patch('sys.exit')
1444 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1445 ... def test_function(mock_exit, other, thing):
1446 ... assert 'other' in repr(other)
1447 ... assert 'thing' in repr(thing)
1448 ... assert 'exit' in repr(mock_exit)
1449 ...
1450 >>> test_function()
1451
Georg Brandl7ad3df62014-10-31 07:59:37 +01001452If :func:`patch.multiple` is used as a context manager, the value returned by the
Joan Massichdc69f692019-03-18 00:34:22 +01001453context manager is a dictionary where created mocks are keyed by name::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001454
1455 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
1456 ... assert 'other' in repr(values['other'])
1457 ... assert 'thing' in repr(values['thing'])
1458 ... assert values['thing'] is thing
1459 ... assert values['other'] is other
1460 ...
1461
1462
1463.. _start-and-stop:
1464
1465patch methods: start and stop
Georg Brandlfb134382013-02-03 11:47:49 +01001466~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001467
Georg Brandl7ad3df62014-10-31 07:59:37 +01001468All the patchers have :meth:`start` and :meth:`stop` methods. These make it simpler to do
1469patching in ``setUp`` methods or where you want to do multiple patches without
Michael Foorda9e6fb22012-03-28 14:36:02 +01001470nesting decorators or with statements.
1471
Georg Brandl7ad3df62014-10-31 07:59:37 +01001472To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as
1473normal and keep a reference to the returned ``patcher`` object. You can then
1474call :meth:`start` to put the patch in place and :meth:`stop` to undo it.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001475
Georg Brandl7ad3df62014-10-31 07:59:37 +01001476If 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 +02001477the call to ``patcher.start``. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001478
1479 >>> patcher = patch('package.module.ClassName')
1480 >>> from package import module
1481 >>> original = module.ClassName
1482 >>> new_mock = patcher.start()
1483 >>> assert module.ClassName is not original
1484 >>> assert module.ClassName is new_mock
1485 >>> patcher.stop()
1486 >>> assert module.ClassName is original
1487 >>> assert module.ClassName is not new_mock
1488
1489
Georg Brandl7ad3df62014-10-31 07:59:37 +01001490A typical use case for this might be for doing multiple patches in the ``setUp``
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001491method of a :class:`TestCase`::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001492
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001493 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +01001494 ... def setUp(self):
1495 ... self.patcher1 = patch('package.module.Class1')
1496 ... self.patcher2 = patch('package.module.Class2')
1497 ... self.MockClass1 = self.patcher1.start()
1498 ... self.MockClass2 = self.patcher2.start()
1499 ...
1500 ... def tearDown(self):
1501 ... self.patcher1.stop()
1502 ... self.patcher2.stop()
1503 ...
1504 ... def test_something(self):
1505 ... assert package.module.Class1 is self.MockClass1
1506 ... assert package.module.Class2 is self.MockClass2
1507 ...
1508 >>> MyTest('test_something').run()
1509
1510.. caution::
1511
1512 If you use this technique you must ensure that the patching is "undone" by
Georg Brandl7ad3df62014-10-31 07:59:37 +01001513 calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001514 exception is raised in the ``setUp`` then ``tearDown`` is not called.
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001515 :meth:`unittest.TestCase.addCleanup` makes this easier::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001516
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001517 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +01001518 ... def setUp(self):
1519 ... patcher = patch('package.module.Class')
1520 ... self.MockClass = patcher.start()
1521 ... self.addCleanup(patcher.stop)
1522 ...
1523 ... def test_something(self):
1524 ... assert package.module.Class is self.MockClass
1525 ...
1526
Georg Brandl7ad3df62014-10-31 07:59:37 +01001527 As an added bonus you no longer need to keep a reference to the ``patcher``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001528 object.
1529
Michael Foordf7c41582012-06-10 20:36:32 +01001530It is also possible to stop all patches which have been started by using
Georg Brandl7ad3df62014-10-31 07:59:37 +01001531:func:`patch.stopall`.
Michael Foordf7c41582012-06-10 20:36:32 +01001532
1533.. function:: patch.stopall
1534
Georg Brandl7ad3df62014-10-31 07:59:37 +01001535 Stop all active patches. Only stops patches started with ``start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001536
Georg Brandl7ad3df62014-10-31 07:59:37 +01001537
1538.. _patch-builtins:
Michael Foordfddcfa22014-04-14 16:25:20 -04001539
1540patch builtins
Georg Brandl7ad3df62014-10-31 07:59:37 +01001541~~~~~~~~~~~~~~
Michael Foordfddcfa22014-04-14 16:25:20 -04001542You can patch any builtins within a module. The following example patches
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001543builtin :func:`ord`::
Michael Foordfddcfa22014-04-14 16:25:20 -04001544
1545 >>> @patch('__main__.ord')
1546 ... def test(mock_ord):
1547 ... mock_ord.return_value = 101
1548 ... print(ord('c'))
1549 ...
1550 >>> test()
1551 101
1552
Michael Foorda9e6fb22012-03-28 14:36:02 +01001553
1554TEST_PREFIX
Georg Brandlfb134382013-02-03 11:47:49 +01001555~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001556
1557All of the patchers can be used as class decorators. When used in this way
1558they wrap every test method on the class. The patchers recognise methods that
Georg Brandl7ad3df62014-10-31 07:59:37 +01001559start with ``'test'`` as being test methods. This is the same way that the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001560:class:`unittest.TestLoader` finds test methods by default.
1561
1562It is possible that you want to use a different prefix for your tests. You can
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001563inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001564
1565 >>> patch.TEST_PREFIX = 'foo'
1566 >>> value = 3
1567 >>>
1568 >>> @patch('__main__.value', 'not three')
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001569 ... class Thing:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001570 ... def foo_one(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001571 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001572 ... def foo_two(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001573 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001574 ...
1575 >>>
1576 >>> Thing().foo_one()
1577 not three
1578 >>> Thing().foo_two()
1579 not three
1580 >>> value
1581 3
1582
1583
1584Nesting Patch Decorators
Georg Brandlfb134382013-02-03 11:47:49 +01001585~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001586
1587If you want to perform multiple patches then you can simply stack up the
1588decorators.
1589
1590You can stack up multiple patch decorators using this pattern:
1591
1592 >>> @patch.object(SomeClass, 'class_method')
1593 ... @patch.object(SomeClass, 'static_method')
1594 ... def test(mock1, mock2):
1595 ... assert SomeClass.static_method is mock1
1596 ... assert SomeClass.class_method is mock2
1597 ... SomeClass.static_method('foo')
1598 ... SomeClass.class_method('bar')
1599 ... return mock1, mock2
1600 ...
1601 >>> mock1, mock2 = test()
1602 >>> mock1.assert_called_once_with('foo')
1603 >>> mock2.assert_called_once_with('bar')
1604
1605
1606Note that the decorators are applied from the bottom upwards. This is the
1607standard way that Python applies decorators. The order of the created mocks
1608passed into your test function matches this order.
1609
1610
1611.. _where-to-patch:
1612
1613Where to patch
Georg Brandlfb134382013-02-03 11:47:49 +01001614~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001615
Georg Brandl7ad3df62014-10-31 07:59:37 +01001616:func:`patch` works by (temporarily) changing the object that a *name* points to with
Michael Foorda9e6fb22012-03-28 14:36:02 +01001617another one. There can be many names pointing to any individual object, so
1618for patching to work you must ensure that you patch the name used by the system
1619under test.
1620
1621The basic principle is that you patch where an object is *looked up*, which
1622is not necessarily the same place as where it is defined. A couple of
1623examples will help to clarify this.
1624
1625Imagine we have a project that we want to test with the following structure::
1626
1627 a.py
1628 -> Defines SomeClass
1629
1630 b.py
1631 -> from a import SomeClass
1632 -> some_function instantiates SomeClass
1633
Georg Brandl7ad3df62014-10-31 07:59:37 +01001634Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
1635:func:`patch`. The problem is that when we import module b, which we will have to
1636do then it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
1637``a.SomeClass`` then it will have no effect on our test; module b already has a
1638reference to the *real* ``SomeClass`` and it looks like our patching had no
Michael Foorda9e6fb22012-03-28 14:36:02 +01001639effect.
1640
Ben Lloyd15033d12017-05-22 12:06:56 +01001641The key is to patch out ``SomeClass`` where it is used (or where it is looked up).
1642In this case ``some_function`` will actually look up ``SomeClass`` in module b,
Michael Foorda9e6fb22012-03-28 14:36:02 +01001643where we have imported it. The patching should look like::
1644
1645 @patch('b.SomeClass')
1646
Georg Brandl7ad3df62014-10-31 07:59:37 +01001647However, consider the alternative scenario where instead of ``from a import
1648SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both
Michael Foorda9e6fb22012-03-28 14:36:02 +01001649of these import forms are common. In this case the class we want to patch is
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001650being looked up in the module and so we have to patch ``a.SomeClass`` instead::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001651
1652 @patch('a.SomeClass')
1653
1654
1655Patching Descriptors and Proxy Objects
Georg Brandlfb134382013-02-03 11:47:49 +01001656~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001657
1658Both patch_ and patch.object_ correctly patch and restore descriptors: class
1659methods, static methods and properties. You should patch these on the *class*
1660rather than an instance. They also work with *some* objects
Zachary Ware5ea5d2c2014-02-26 09:34:43 -06001661that proxy attribute access, like the `django settings object
Michael Foorda9e6fb22012-03-28 14:36:02 +01001662<http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
1663
1664
Michael Foord2309ed82012-03-28 15:38:36 +01001665MagicMock and magic method support
Georg Brandlfb134382013-02-03 11:47:49 +01001666----------------------------------
Michael Foord2309ed82012-03-28 15:38:36 +01001667
1668.. _magic-methods:
1669
1670Mocking Magic Methods
Georg Brandlfb134382013-02-03 11:47:49 +01001671~~~~~~~~~~~~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001672
1673:class:`Mock` supports mocking the Python protocol methods, also known as
1674"magic methods". This allows mock objects to replace containers or other
1675objects that implement Python protocols.
1676
1677Because magic methods are looked up differently from normal methods [#]_, this
1678support has been specially implemented. This means that only specific magic
1679methods are supported. The supported list includes *almost* all of them. If
1680there are any missing that you need please let us know.
1681
1682You mock magic methods by setting the method you are interested in to a function
1683or a mock instance. If you are using a function then it *must* take ``self`` as
1684the first argument [#]_.
1685
1686 >>> def __str__(self):
1687 ... return 'fooble'
1688 ...
1689 >>> mock = Mock()
1690 >>> mock.__str__ = __str__
1691 >>> str(mock)
1692 'fooble'
1693
1694 >>> mock = Mock()
1695 >>> mock.__str__ = Mock()
1696 >>> mock.__str__.return_value = 'fooble'
1697 >>> str(mock)
1698 'fooble'
1699
1700 >>> mock = Mock()
1701 >>> mock.__iter__ = Mock(return_value=iter([]))
1702 >>> list(mock)
1703 []
1704
1705One use case for this is for mocking objects used as context managers in a
Georg Brandl7ad3df62014-10-31 07:59:37 +01001706:keyword:`with` statement:
Michael Foord2309ed82012-03-28 15:38:36 +01001707
1708 >>> mock = Mock()
1709 >>> mock.__enter__ = Mock(return_value='foo')
1710 >>> mock.__exit__ = Mock(return_value=False)
1711 >>> with mock as m:
1712 ... assert m == 'foo'
1713 ...
1714 >>> mock.__enter__.assert_called_with()
1715 >>> mock.__exit__.assert_called_with(None, None, None)
1716
1717Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they
1718are recorded in :attr:`~Mock.mock_calls`.
1719
1720.. note::
1721
Georg Brandl7ad3df62014-10-31 07:59:37 +01001722 If you use the *spec* keyword argument to create a mock then attempting to
1723 set a magic method that isn't in the spec will raise an :exc:`AttributeError`.
Michael Foord2309ed82012-03-28 15:38:36 +01001724
1725The full list of supported magic methods is:
1726
1727* ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``
1728* ``__dir__``, ``__format__`` and ``__subclasses__``
John Reese6c4fab02018-05-22 13:01:10 -07001729* ``__round__``, ``__floor__``, ``__trunc__`` and ``__ceil__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001730* Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001731 ``__eq__`` and ``__ne__``
1732* Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``,
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001733 ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__``
1734 and ``__missing__``
Michael Foord2309ed82012-03-28 15:38:36 +01001735* Context manager: ``__enter__`` and ``__exit__``
1736* Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``
1737* The numeric methods (including right hand and in-place variants):
Serhiy Storchakac2ccce72015-03-12 22:01:30 +02001738 ``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__div__``, ``__truediv__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001739 ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``,
1740 ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001741* Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__``
1742 and ``__index__``
Michael Foord2309ed82012-03-28 15:38:36 +01001743* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
1744* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
1745 ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001746* File system path representation: ``__fspath__``
1747
1748.. versionchanged:: 3.8
1749 Added support for :func:`os.PathLike.__fspath__`.
Michael Foord2309ed82012-03-28 15:38:36 +01001750
1751
1752The following methods exist but are *not* supported as they are either in use
1753by mock, can't be set dynamically, or can cause problems:
1754
1755* ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``
1756* ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``
1757
1758
1759
1760Magic Mock
Georg Brandlfb134382013-02-03 11:47:49 +01001761~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001762
Georg Brandl7ad3df62014-10-31 07:59:37 +01001763There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001764
1765
1766.. class:: MagicMock(*args, **kw)
1767
1768 ``MagicMock`` is a subclass of :class:`Mock` with default implementations
1769 of most of the magic methods. You can use ``MagicMock`` without having to
1770 configure the magic methods yourself.
1771
1772 The constructor parameters have the same meaning as for :class:`Mock`.
1773
Georg Brandl7ad3df62014-10-31 07:59:37 +01001774 If you use the *spec* or *spec_set* arguments then *only* magic methods
Michael Foord2309ed82012-03-28 15:38:36 +01001775 that exist in the spec will be created.
1776
1777
1778.. class:: NonCallableMagicMock(*args, **kw)
1779
Georg Brandl7ad3df62014-10-31 07:59:37 +01001780 A non-callable version of :class:`MagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001781
1782 The constructor parameters have the same meaning as for
Georg Brandl7ad3df62014-10-31 07:59:37 +01001783 :class:`MagicMock`, with the exception of *return_value* and
1784 *side_effect* which have no meaning on a non-callable mock.
Michael Foord2309ed82012-03-28 15:38:36 +01001785
Georg Brandl7ad3df62014-10-31 07:59:37 +01001786The magic methods are setup with :class:`MagicMock` objects, so you can configure them
Michael Foord2309ed82012-03-28 15:38:36 +01001787and use them in the usual way:
1788
1789 >>> mock = MagicMock()
1790 >>> mock[3] = 'fish'
1791 >>> mock.__setitem__.assert_called_with(3, 'fish')
1792 >>> mock.__getitem__.return_value = 'result'
1793 >>> mock[2]
1794 'result'
1795
1796By default many of the protocol methods are required to return objects of a
1797specific type. These methods are preconfigured with a default return value, so
1798that they can be used without you having to do anything if you aren't interested
1799in the return value. You can still *set* the return value manually if you want
1800to change the default.
1801
1802Methods and their defaults:
1803
1804* ``__lt__``: NotImplemented
1805* ``__gt__``: NotImplemented
1806* ``__le__``: NotImplemented
1807* ``__ge__``: NotImplemented
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001808* ``__int__``: 1
1809* ``__contains__``: False
Berker Peksag8fafc742016-04-11 12:23:04 +03001810* ``__len__``: 0
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001811* ``__iter__``: iter([])
1812* ``__exit__``: False
1813* ``__complex__``: 1j
1814* ``__float__``: 1.0
1815* ``__bool__``: True
1816* ``__index__``: 1
1817* ``__hash__``: default hash for the mock
1818* ``__str__``: default str for the mock
Michael Foord2309ed82012-03-28 15:38:36 +01001819* ``__sizeof__``: default sizeof for the mock
1820
1821For example:
1822
1823 >>> mock = MagicMock()
1824 >>> int(mock)
1825 1
1826 >>> len(mock)
1827 0
1828 >>> list(mock)
1829 []
1830 >>> object() in mock
1831 False
1832
Berker Peksag283f1aa2015-01-07 21:15:02 +02001833The two equality methods, :meth:`__eq__` and :meth:`__ne__`, are special.
1834They do the default equality comparison on identity, using the
1835:attr:`~Mock.side_effect` attribute, unless you change their return value to
1836return something else::
Michael Foord2309ed82012-03-28 15:38:36 +01001837
1838 >>> MagicMock() == 3
1839 False
1840 >>> MagicMock() != 3
1841 True
1842 >>> mock = MagicMock()
1843 >>> mock.__eq__.return_value = True
1844 >>> mock == 3
1845 True
1846
Georg Brandl7ad3df62014-10-31 07:59:37 +01001847The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
Michael Foord2309ed82012-03-28 15:38:36 +01001848required to be an iterator:
1849
1850 >>> mock = MagicMock()
1851 >>> mock.__iter__.return_value = ['a', 'b', 'c']
1852 >>> list(mock)
1853 ['a', 'b', 'c']
1854 >>> list(mock)
1855 ['a', 'b', 'c']
1856
1857If the return value *is* an iterator, then iterating over it once will consume
1858it and subsequent iterations will result in an empty list:
1859
1860 >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
1861 >>> list(mock)
1862 ['a', 'b', 'c']
1863 >>> list(mock)
1864 []
1865
1866``MagicMock`` has all of the supported magic methods configured except for some
1867of the obscure and obsolete ones. You can still set these up if you want.
1868
1869Magic methods that are supported but not setup by default in ``MagicMock`` are:
1870
1871* ``__subclasses__``
1872* ``__dir__``
1873* ``__format__``
1874* ``__get__``, ``__set__`` and ``__delete__``
1875* ``__reversed__`` and ``__missing__``
1876* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
1877 ``__getstate__`` and ``__setstate__``
1878* ``__getformat__`` and ``__setformat__``
1879
1880
1881
1882.. [#] Magic methods *should* be looked up on the class rather than the
1883 instance. Different versions of Python are inconsistent about applying this
1884 rule. The supported protocol methods should work with all supported versions
1885 of Python.
1886.. [#] The function is basically hooked up to the class, but each ``Mock``
1887 instance is kept isolated from the others.
1888
1889
Michael Foorda9e6fb22012-03-28 14:36:02 +01001890Helpers
Georg Brandlfb134382013-02-03 11:47:49 +01001891-------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001892
1893sentinel
Georg Brandlfb134382013-02-03 11:47:49 +01001894~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001895
1896.. data:: sentinel
1897
Andrés Delfinof85af032018-07-08 21:28:51 -03001898 The ``sentinel`` object provides a convenient way of providing unique
1899 objects for your tests.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001900
Andrés Delfinof85af032018-07-08 21:28:51 -03001901 Attributes are created on demand when you access them by name. Accessing
1902 the same attribute will always return the same object. The objects
1903 returned have a sensible repr so that test failure messages are readable.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001904
Serhiy Storchakad9c956f2017-01-11 20:13:03 +02001905 .. versionchanged:: 3.7
1906 The ``sentinel`` attributes now preserve their identity when they are
1907 :mod:`copied <copy>` or :mod:`pickled <pickle>`.
1908
Michael Foorda9e6fb22012-03-28 14:36:02 +01001909Sometimes when testing you need to test that a specific object is passed as an
1910argument to another method, or returned. It can be common to create named
Georg Brandl7ad3df62014-10-31 07:59:37 +01001911sentinel objects to test this. :data:`sentinel` provides a convenient way of
Michael Foorda9e6fb22012-03-28 14:36:02 +01001912creating and testing the identity of objects like this.
1913
Georg Brandl7ad3df62014-10-31 07:59:37 +01001914In this example we monkey patch ``method`` to return ``sentinel.some_object``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001915
1916 >>> real = ProductionClass()
1917 >>> real.method = Mock(name="method")
1918 >>> real.method.return_value = sentinel.some_object
1919 >>> result = real.method()
1920 >>> assert result is sentinel.some_object
1921 >>> sentinel.some_object
1922 sentinel.some_object
1923
1924
1925DEFAULT
Georg Brandlfb134382013-02-03 11:47:49 +01001926~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001927
1928
1929.. data:: DEFAULT
1930
Georg Brandl7ad3df62014-10-31 07:59:37 +01001931 The :data:`DEFAULT` object is a pre-created sentinel (actually
1932 ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001933 functions to indicate that the normal return value should be used.
1934
1935
Michael Foorda9e6fb22012-03-28 14:36:02 +01001936call
Georg Brandlfb134382013-02-03 11:47:49 +01001937~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001938
1939.. function:: call(*args, **kwargs)
1940
Georg Brandl7ad3df62014-10-31 07:59:37 +01001941 :func:`call` is a helper object for making simpler assertions, for comparing with
Georg Brandl24891672012-04-01 13:48:26 +02001942 :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
Georg Brandl7ad3df62014-10-31 07:59:37 +01001943 :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be
Michael Foorda9e6fb22012-03-28 14:36:02 +01001944 used with :meth:`~Mock.assert_has_calls`.
1945
1946 >>> m = MagicMock(return_value=None)
1947 >>> m(1, 2, a='foo', b='bar')
1948 >>> m()
1949 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
1950 True
1951
1952.. method:: call.call_list()
1953
Georg Brandl7ad3df62014-10-31 07:59:37 +01001954 For a call object that represents multiple calls, :meth:`call_list`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001955 returns a list of all the intermediate calls as well as the
1956 final call.
1957
Georg Brandl7ad3df62014-10-31 07:59:37 +01001958``call_list`` is particularly useful for making assertions on "chained calls". A
Michael Foorda9e6fb22012-03-28 14:36:02 +01001959chained call is multiple calls on a single line of code. This results in
1960multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
1961the sequence of calls can be tedious.
1962
1963:meth:`~call.call_list` can construct the sequence of calls from the same
1964chained call:
1965
1966 >>> m = MagicMock()
1967 >>> m(1).method(arg='foo').other('bar')(2.0)
1968 <MagicMock name='mock().method().other()()' id='...'>
1969 >>> kall = call(1).method(arg='foo').other('bar')(2.0)
1970 >>> kall.call_list()
1971 [call(1),
1972 call().method(arg='foo'),
1973 call().method().other('bar'),
1974 call().method().other()(2.0)]
1975 >>> m.mock_calls == kall.call_list()
1976 True
1977
1978.. _calls-as-tuples:
1979
Georg Brandl7ad3df62014-10-31 07:59:37 +01001980A ``call`` object is either a tuple of (positional args, keyword args) or
Michael Foorda9e6fb22012-03-28 14:36:02 +01001981(name, positional args, keyword args) depending on how it was constructed. When
Georg Brandl7ad3df62014-10-31 07:59:37 +01001982you construct them yourself this isn't particularly interesting, but the ``call``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001983objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
1984:attr:`Mock.mock_calls` attributes can be introspected to get at the individual
1985arguments they contain.
1986
Georg Brandl7ad3df62014-10-31 07:59:37 +01001987The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
1988are two-tuples of (positional args, keyword args) whereas the ``call`` objects
Michael Foorda9e6fb22012-03-28 14:36:02 +01001989in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
1990three-tuples of (name, positional args, keyword args).
1991
1992You can use their "tupleness" to pull out the individual arguments for more
1993complex introspection and assertions. The positional arguments are a tuple
1994(an empty tuple if there are no positional arguments) and the keyword
1995arguments are a dictionary:
1996
1997 >>> m = MagicMock(return_value=None)
1998 >>> m(1, 2, 3, arg='one', arg2='two')
1999 >>> kall = m.call_args
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302000 >>> kall.args
Michael Foorda9e6fb22012-03-28 14:36:02 +01002001 (1, 2, 3)
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302002 >>> kall.kwargs
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002003 {'arg': 'one', 'arg2': 'two'}
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302004 >>> kall.args is kall[0]
Michael Foorda9e6fb22012-03-28 14:36:02 +01002005 True
Kumar Akshayb0df45e2019-03-22 13:40:40 +05302006 >>> kall.kwargs is kall[1]
Michael Foorda9e6fb22012-03-28 14:36:02 +01002007 True
2008
2009 >>> m = MagicMock()
2010 >>> m.foo(4, 5, 6, arg='two', arg2='three')
2011 <MagicMock name='mock.foo()' id='...'>
2012 >>> kall = m.mock_calls[0]
2013 >>> name, args, kwargs = kall
2014 >>> name
2015 'foo'
2016 >>> args
2017 (4, 5, 6)
2018 >>> kwargs
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002019 {'arg': 'two', 'arg2': 'three'}
Michael Foorda9e6fb22012-03-28 14:36:02 +01002020 >>> name is m.mock_calls[0][0]
2021 True
2022
2023
2024create_autospec
Georg Brandlfb134382013-02-03 11:47:49 +01002025~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002026
2027.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
2028
2029 Create a mock object using another object as a spec. Attributes on the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002030 mock will use the corresponding attribute on the *spec* object as their
Michael Foorda9e6fb22012-03-28 14:36:02 +01002031 spec.
2032
2033 Functions or methods being mocked will have their arguments checked to
2034 ensure that they are called with the correct signature.
2035
Georg Brandl7ad3df62014-10-31 07:59:37 +01002036 If *spec_set* is ``True`` then attempting to set attributes that don't exist
2037 on the spec object will raise an :exc:`AttributeError`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002038
2039 If a class is used as a spec then the return value of the mock (the
2040 instance of the class) will have the same spec. You can use a class as the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002041 spec for an instance object by passing ``instance=True``. The returned mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01002042 will only be callable if instances of the mock are callable.
2043
Georg Brandl7ad3df62014-10-31 07:59:37 +01002044 :func:`create_autospec` also takes arbitrary keyword arguments that are passed to
Michael Foorda9e6fb22012-03-28 14:36:02 +01002045 the constructor of the created mock.
2046
2047See :ref:`auto-speccing` for examples of how to use auto-speccing with
Georg Brandl7ad3df62014-10-31 07:59:37 +01002048:func:`create_autospec` and the *autospec* argument to :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002049
2050
2051ANY
Georg Brandlfb134382013-02-03 11:47:49 +01002052~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002053
2054.. data:: ANY
2055
2056Sometimes you may need to make assertions about *some* of the arguments in a
2057call to mock, but either not care about some of the arguments or want to pull
2058them individually out of :attr:`~Mock.call_args` and make more complex
2059assertions on them.
2060
2061To ignore certain arguments you can pass in objects that compare equal to
2062*everything*. Calls to :meth:`~Mock.assert_called_with` and
2063:meth:`~Mock.assert_called_once_with` will then succeed no matter what was
2064passed in.
2065
2066 >>> mock = Mock(return_value=None)
2067 >>> mock('foo', bar=object())
2068 >>> mock.assert_called_once_with('foo', bar=ANY)
2069
Georg Brandl7ad3df62014-10-31 07:59:37 +01002070:data:`ANY` can also be used in comparisons with call lists like
Michael Foorda9e6fb22012-03-28 14:36:02 +01002071:attr:`~Mock.mock_calls`:
2072
2073 >>> m = MagicMock(return_value=None)
2074 >>> m(1)
2075 >>> m(1, 2)
2076 >>> m(object())
2077 >>> m.mock_calls == [call(1), call(1, 2), ANY]
2078 True
2079
2080
2081
2082FILTER_DIR
Georg Brandlfb134382013-02-03 11:47:49 +01002083~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002084
2085.. data:: FILTER_DIR
2086
Georg Brandl7ad3df62014-10-31 07:59:37 +01002087:data:`FILTER_DIR` is a module level variable that controls the way mock objects
2088respond to :func:`dir` (only for Python 2.6 or more recent). The default is ``True``,
Michael Foorda9e6fb22012-03-28 14:36:02 +01002089which uses the filtering described below, to only show useful members. If you
2090dislike this filtering, or need to switch it off for diagnostic purposes, then
Georg Brandl7ad3df62014-10-31 07:59:37 +01002091set ``mock.FILTER_DIR = False``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002092
Georg Brandl7ad3df62014-10-31 07:59:37 +01002093With filtering on, ``dir(some_mock)`` shows only useful attributes and will
Michael Foorda9e6fb22012-03-28 14:36:02 +01002094include any dynamically created attributes that wouldn't normally be shown.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002095If the mock was created with a *spec* (or *autospec* of course) then all the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002096attributes from the original are shown, even if they haven't been accessed
2097yet:
2098
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002099.. doctest::
2100 :options: +ELLIPSIS,+NORMALIZE_WHITESPACE
2101
Michael Foorda9e6fb22012-03-28 14:36:02 +01002102 >>> dir(Mock())
2103 ['assert_any_call',
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002104 'assert_called',
2105 'assert_called_once',
Michael Foorda9e6fb22012-03-28 14:36:02 +01002106 'assert_called_once_with',
2107 'assert_called_with',
2108 'assert_has_calls',
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002109 'assert_not_called',
Michael Foorda9e6fb22012-03-28 14:36:02 +01002110 'attach_mock',
2111 ...
2112 >>> from urllib import request
2113 >>> dir(Mock(spec=request))
2114 ['AbstractBasicAuthHandler',
2115 'AbstractDigestAuthHandler',
2116 'AbstractHTTPHandler',
2117 'BaseHandler',
2118 ...
2119
Georg Brandl7ad3df62014-10-31 07:59:37 +01002120Many of the not-very-useful (private to :class:`Mock` rather than the thing being
Michael Foorda9e6fb22012-03-28 14:36:02 +01002121mocked) underscore and double underscore prefixed attributes have been
Georg Brandl7ad3df62014-10-31 07:59:37 +01002122filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this
Michael Foorda9e6fb22012-03-28 14:36:02 +01002123behaviour you can switch it off by setting the module level switch
Georg Brandl7ad3df62014-10-31 07:59:37 +01002124:data:`FILTER_DIR`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002125
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002126.. doctest::
2127 :options: +ELLIPSIS,+NORMALIZE_WHITESPACE
2128
Michael Foorda9e6fb22012-03-28 14:36:02 +01002129 >>> from unittest import mock
2130 >>> mock.FILTER_DIR = False
2131 >>> dir(mock.Mock())
2132 ['_NonCallableMock__get_return_value',
2133 '_NonCallableMock__get_side_effect',
2134 '_NonCallableMock__return_value_doc',
2135 '_NonCallableMock__set_return_value',
2136 '_NonCallableMock__set_side_effect',
2137 '__call__',
2138 '__class__',
2139 ...
2140
Georg Brandl7ad3df62014-10-31 07:59:37 +01002141Alternatively you can just use ``vars(my_mock)`` (instance members) and
2142``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of
2143:data:`mock.FILTER_DIR`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002144
2145
2146mock_open
Georg Brandlfb134382013-02-03 11:47:49 +01002147~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002148
2149.. function:: mock_open(mock=None, read_data=None)
2150
Andrés Delfinof85af032018-07-08 21:28:51 -03002151 A helper function to create a mock to replace the use of :func:`open`. It works
2152 for :func:`open` called directly or used as a context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002153
Andrés Delfinof85af032018-07-08 21:28:51 -03002154 The *mock* argument is the mock object to configure. If ``None`` (the
2155 default) then a :class:`MagicMock` will be created for you, with the API limited
2156 to methods or attributes available on standard file handles.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002157
Andrés Delfinof85af032018-07-08 21:28:51 -03002158 *read_data* is a string for the :meth:`~io.IOBase.read`,
2159 :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods
2160 of the file handle to return. Calls to those methods will take data from
2161 *read_data* until it is depleted. The mock of these methods is pretty
2162 simplistic: every time the *mock* is called, the *read_data* is rewound to
2163 the start. If you need more control over the data that you are feeding to
2164 the tested code you will need to customize this mock for yourself. When that
2165 is insufficient, one of the in-memory filesystem packages on `PyPI
2166 <https://pypi.org>`_ can offer a realistic filesystem for testing.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002167
Robert Collinsf79dfe32015-07-24 04:09:59 +12002168 .. versionchanged:: 3.4
2169 Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support.
2170 The mock of :meth:`~io.IOBase.read` changed to consume *read_data* rather
2171 than returning it on each call.
2172
Robert Collins70398392015-07-24 04:10:27 +12002173 .. versionchanged:: 3.5
Robert Collinsf79dfe32015-07-24 04:09:59 +12002174 *read_data* is now reset on each call to the *mock*.
2175
Tony Flury20870232018-09-12 23:21:16 +01002176 .. versionchanged:: 3.8
2177 Added :meth:`__iter__` to implementation so that iteration (such as in for
2178 loops) correctly consumes *read_data*.
2179
Georg Brandl7ad3df62014-10-31 07:59:37 +01002180Using :func:`open` as a context manager is a great way to ensure your file handles
Michael Foorda9e6fb22012-03-28 14:36:02 +01002181are closed properly and is becoming common::
2182
2183 with open('/some/path', 'w') as f:
2184 f.write('something')
2185
Georg Brandl7ad3df62014-10-31 07:59:37 +01002186The issue is that even if you mock out the call to :func:`open` it is the
2187*returned object* that is used as a context manager (and has :meth:`__enter__` and
2188:meth:`__exit__` called).
Michael Foorda9e6fb22012-03-28 14:36:02 +01002189
2190Mocking context managers with a :class:`MagicMock` is common enough and fiddly
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002191enough that a helper function is useful. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002192
2193 >>> m = mock_open()
Michael Foordfddcfa22014-04-14 16:25:20 -04002194 >>> with patch('__main__.open', m):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002195 ... with open('foo', 'w') as h:
2196 ... h.write('some stuff')
2197 ...
2198 >>> m.mock_calls
2199 [call('foo', 'w'),
2200 call().__enter__(),
2201 call().write('some stuff'),
2202 call().__exit__(None, None, None)]
2203 >>> m.assert_called_once_with('foo', 'w')
2204 >>> handle = m()
2205 >>> handle.write.assert_called_once_with('some stuff')
2206
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002207And for reading files::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002208
Michael Foordfddcfa22014-04-14 16:25:20 -04002209 >>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002210 ... with open('foo') as h:
2211 ... result = h.read()
2212 ...
2213 >>> m.assert_called_once_with('foo')
2214 >>> assert result == 'bibble'
2215
2216
2217.. _auto-speccing:
2218
2219Autospeccing
Georg Brandlfb134382013-02-03 11:47:49 +01002220~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002221
Georg Brandl7ad3df62014-10-31 07:59:37 +01002222Autospeccing is based on the existing :attr:`spec` feature of mock. It limits the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002223api of mocks to the api of an original object (the spec), but it is recursive
2224(implemented lazily) so that attributes of mocks only have the same api as
2225the attributes of the spec. In addition mocked functions / methods have the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002226same call signature as the original so they raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002227called incorrectly.
2228
2229Before I explain how auto-speccing works, here's why it is needed.
2230
Georg Brandl7ad3df62014-10-31 07:59:37 +01002231:class:`Mock` is a very powerful and flexible object, but it suffers from two flaws
Michael Foorda9e6fb22012-03-28 14:36:02 +01002232when used to mock out objects from a system under test. One of these flaws is
Georg Brandl7ad3df62014-10-31 07:59:37 +01002233specific to the :class:`Mock` api and the other is a more general problem with using
Michael Foorda9e6fb22012-03-28 14:36:02 +01002234mock objects.
2235
Georg Brandl7ad3df62014-10-31 07:59:37 +01002236First the problem specific to :class:`Mock`. :class:`Mock` has two assert methods that are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002237extremely handy: :meth:`~Mock.assert_called_with` and
2238:meth:`~Mock.assert_called_once_with`.
2239
2240 >>> mock = Mock(name='Thing', return_value=None)
2241 >>> mock(1, 2, 3)
2242 >>> mock.assert_called_once_with(1, 2, 3)
2243 >>> mock(1, 2, 3)
2244 >>> mock.assert_called_once_with(1, 2, 3)
2245 Traceback (most recent call last):
2246 ...
Michael Foord28d591c2012-09-28 16:15:22 +01002247 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002248
2249Because mocks auto-create attributes on demand, and allow you to call them
2250with arbitrary arguments, if you misspell one of these assert methods then
2251your assertion is gone:
2252
2253.. code-block:: pycon
2254
2255 >>> mock = Mock(name='Thing', return_value=None)
2256 >>> mock(1, 2, 3)
2257 >>> mock.assret_called_once_with(4, 5, 6)
2258
2259Your tests can pass silently and incorrectly because of the typo.
2260
2261The second issue is more general to mocking. If you refactor some of your
2262code, rename members and so on, any tests for code that is still using the
2263*old api* but uses mocks instead of the real objects will still pass. This
2264means your tests can all pass even though your code is broken.
2265
2266Note that this is another reason why you need integration tests as well as
2267unit tests. Testing everything in isolation is all fine and dandy, but if you
2268don't test how your units are "wired together" there is still lots of room
2269for bugs that tests might have caught.
2270
Georg Brandl7ad3df62014-10-31 07:59:37 +01002271:mod:`mock` already provides a feature to help with this, called speccing. If you
2272use a class or instance as the :attr:`spec` for a mock then you can only access
Michael Foorda9e6fb22012-03-28 14:36:02 +01002273attributes on the mock that exist on the real class:
2274
2275 >>> from urllib import request
2276 >>> mock = Mock(spec=request.Request)
2277 >>> mock.assret_called_with
2278 Traceback (most recent call last):
2279 ...
2280 AttributeError: Mock object has no attribute 'assret_called_with'
2281
2282The spec only applies to the mock itself, so we still have the same issue
2283with any methods on the mock:
2284
2285.. code-block:: pycon
2286
2287 >>> mock.has_data()
2288 <mock.Mock object at 0x...>
2289 >>> mock.has_data.assret_called_with()
2290
Georg Brandl7ad3df62014-10-31 07:59:37 +01002291Auto-speccing solves this problem. You can either pass ``autospec=True`` to
2292:func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a
2293mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002294object that is being replaced will be used as the spec object. Because the
2295speccing is done "lazily" (the spec is created as attributes on the mock are
2296accessed) you can use it with very complex or deeply nested objects (like
2297modules that import modules that import modules) without a big performance
2298hit.
2299
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002300Here's an example of it in use::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002301
2302 >>> from urllib import request
2303 >>> patcher = patch('__main__.request', autospec=True)
2304 >>> mock_request = patcher.start()
2305 >>> request is mock_request
2306 True
2307 >>> mock_request.Request
2308 <MagicMock name='request.Request' spec='Request' id='...'>
2309
Georg Brandl7ad3df62014-10-31 07:59:37 +01002310You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two
2311arguments in the constructor (one of which is *self*). Here's what happens if
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002312we try to call it incorrectly::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002313
2314 >>> req = request.Request()
2315 Traceback (most recent call last):
2316 ...
2317 TypeError: <lambda>() takes at least 2 arguments (1 given)
2318
2319The spec also applies to instantiated classes (i.e. the return value of
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002320specced mocks)::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002321
2322 >>> req = request.Request('foo')
2323 >>> req
2324 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
2325
Georg Brandl7ad3df62014-10-31 07:59:37 +01002326:class:`Request` objects are not callable, so the return value of instantiating our
2327mocked out :class:`request.Request` is a non-callable mock. With the spec in place
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002328any typos in our asserts will raise the correct error::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002329
2330 >>> req.add_header('spam', 'eggs')
2331 <MagicMock name='request.Request().add_header()' id='...'>
2332 >>> req.add_header.assret_called_with
2333 Traceback (most recent call last):
2334 ...
2335 AttributeError: Mock object has no attribute 'assret_called_with'
2336 >>> req.add_header.assert_called_with('spam', 'eggs')
2337
Georg Brandl7ad3df62014-10-31 07:59:37 +01002338In many cases you will just be able to add ``autospec=True`` to your existing
2339:func:`patch` calls and then be protected against bugs due to typos and api
Michael Foorda9e6fb22012-03-28 14:36:02 +01002340changes.
2341
Georg Brandl7ad3df62014-10-31 07:59:37 +01002342As well as using *autospec* through :func:`patch` there is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002343:func:`create_autospec` for creating autospecced mocks directly:
2344
2345 >>> from urllib import request
2346 >>> mock_request = create_autospec(request)
2347 >>> mock_request.Request('foo', 'bar')
2348 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
2349
2350This isn't without caveats and limitations however, which is why it is not
2351the default behaviour. In order to know what attributes are available on the
2352spec object, autospec has to introspect (access attributes) the spec. As you
2353traverse attributes on the mock a corresponding traversal of the original
2354object is happening under the hood. If any of your specced objects have
2355properties or descriptors that can trigger code execution then you may not be
2356able to use autospec. On the other hand it is much better to design your
2357objects so that introspection is safe [#]_.
2358
2359A more serious problem is that it is common for instance attributes to be
Georg Brandl7ad3df62014-10-31 07:59:37 +01002360created in the :meth:`__init__` method and not to exist on the class at all.
2361*autospec* can't know about any dynamically created attributes and restricts
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002362the api to visible attributes. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002363
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002364 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002365 ... def __init__(self):
2366 ... self.a = 33
2367 ...
2368 >>> with patch('__main__.Something', autospec=True):
2369 ... thing = Something()
2370 ... thing.a
2371 ...
2372 Traceback (most recent call last):
2373 ...
2374 AttributeError: Mock object has no attribute 'a'
2375
2376There are a few different ways of resolving this problem. The easiest, but
2377not necessarily the least annoying, way is to simply set the required
Georg Brandl7ad3df62014-10-31 07:59:37 +01002378attributes on the mock after creation. Just because *autospec* doesn't allow
Michael Foorda9e6fb22012-03-28 14:36:02 +01002379you to fetch attributes that don't exist on the spec it doesn't prevent you
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002380setting them::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002381
2382 >>> with patch('__main__.Something', autospec=True):
2383 ... thing = Something()
2384 ... thing.a = 33
2385 ...
2386
Georg Brandl7ad3df62014-10-31 07:59:37 +01002387There is a more aggressive version of both *spec* and *autospec* that *does*
Michael Foorda9e6fb22012-03-28 14:36:02 +01002388prevent you setting non-existent attributes. This is useful if you want to
2389ensure your code only *sets* valid attributes too, but obviously it prevents
2390this particular scenario:
2391
2392 >>> with patch('__main__.Something', autospec=True, spec_set=True):
2393 ... thing = Something()
2394 ... thing.a = 33
2395 ...
2396 Traceback (most recent call last):
2397 ...
2398 AttributeError: Mock object has no attribute 'a'
2399
2400Probably the best way of solving the problem is to add class attributes as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002401default values for instance members initialised in :meth:`__init__`. Note that if
2402you are only setting default attributes in :meth:`__init__` then providing them via
Michael Foorda9e6fb22012-03-28 14:36:02 +01002403class attributes (shared between instances of course) is faster too. e.g.
2404
2405.. code-block:: python
2406
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002407 class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002408 a = 33
2409
2410This brings up another issue. It is relatively common to provide a default
Georg Brandl7ad3df62014-10-31 07:59:37 +01002411value of ``None`` for members that will later be an object of a different type.
2412``None`` would be useless as a spec because it wouldn't let you access *any*
2413attributes or methods on it. As ``None`` is *never* going to be useful as a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002414spec, and probably indicates a member that will normally of some other type,
Georg Brandl7ad3df62014-10-31 07:59:37 +01002415autospec doesn't use a spec for members that are set to ``None``. These will
2416just be ordinary mocks (well - MagicMocks):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002417
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002418 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002419 ... member = None
2420 ...
2421 >>> mock = create_autospec(Something)
2422 >>> mock.member.foo.bar.baz()
2423 <MagicMock name='mock.member.foo.bar.baz()' id='...'>
2424
2425If modifying your production classes to add defaults isn't to your liking
2426then there are more options. One of these is simply to use an instance as the
2427spec rather than the class. The other is to create a subclass of the
2428production class and add the defaults to the subclass without affecting the
2429production class. Both of these require you to use an alternative object as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002430the spec. Thankfully :func:`patch` supports this - you can simply pass the
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002431alternative object as the *autospec* argument::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002432
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002433 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002434 ... def __init__(self):
2435 ... self.a = 33
2436 ...
2437 >>> class SomethingForTest(Something):
2438 ... a = 33
2439 ...
2440 >>> p = patch('__main__.Something', autospec=SomethingForTest)
2441 >>> mock = p.start()
2442 >>> mock.a
2443 <NonCallableMagicMock name='Something.a' spec='int' id='...'>
2444
2445
2446.. [#] This only applies to classes or already instantiated objects. Calling
2447 a mocked class to create a mock instance *does not* create a real instance.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002448 It is only attribute lookups - along with calls to :func:`dir` - that are done.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002449
Mario Corchero552be9d2017-10-17 12:35:11 +01002450Sealing mocks
2451~~~~~~~~~~~~~
2452
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002453
2454.. testsetup::
2455
2456 from unittest.mock import seal
2457
Mario Corchero552be9d2017-10-17 12:35:11 +01002458.. function:: seal(mock)
2459
Mario Corchero96200eb2018-10-19 22:57:37 +01002460 Seal will disable the automatic creation of mocks when accessing an attribute of
2461 the mock being sealed or any of its attributes that are already mocks recursively.
Mario Corchero552be9d2017-10-17 12:35:11 +01002462
Mario Corchero96200eb2018-10-19 22:57:37 +01002463 If a mock instance with a name or a spec is assigned to an attribute
Paul Ganssle85ac7262018-01-06 08:25:34 -05002464 it won't be considered in the sealing chain. This allows one to prevent seal from
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002465 fixing part of the mock object. ::
Mario Corchero552be9d2017-10-17 12:35:11 +01002466
2467 >>> mock = Mock()
2468 >>> mock.submock.attribute1 = 2
Mario Corchero96200eb2018-10-19 22:57:37 +01002469 >>> mock.not_submock = mock.Mock(name="sample_name")
Mario Corchero552be9d2017-10-17 12:35:11 +01002470 >>> seal(mock)
Mario Corchero96200eb2018-10-19 22:57:37 +01002471 >>> mock.new_attribute # This will raise AttributeError.
Mario Corchero552be9d2017-10-17 12:35:11 +01002472 >>> mock.submock.attribute2 # This will raise AttributeError.
2473 >>> mock.not_submock.attribute2 # This won't raise.
2474
2475 .. versionadded:: 3.7