blob: fd4e067546e5ea6c53d5dcf834964c8c67b9d51e [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
44:class:`Mock` and :class:`MagicMock` objects create all attributes and
45methods as you access them and store details of how they have been used. You
46can configure them, to specify return values or limit what attributes are
47available, and then make assertions about how they have been used:
48
49 >>> from unittest.mock import MagicMock
50 >>> thing = ProductionClass()
51 >>> thing.method = MagicMock(return_value=3)
52 >>> thing.method(3, 4, 5, key='value')
53 3
54 >>> thing.method.assert_called_with(3, 4, 5, key='value')
55
56:attr:`side_effect` allows you to perform side effects, including raising an
57exception when a mock is called:
58
59 >>> mock = Mock(side_effect=KeyError('foo'))
60 >>> mock()
61 Traceback (most recent call last):
62 ...
63 KeyError: 'foo'
64
65 >>> values = {'a': 1, 'b': 2, 'c': 3}
66 >>> def side_effect(arg):
67 ... return values[arg]
68 ...
69 >>> mock.side_effect = side_effect
70 >>> mock('a'), mock('b'), mock('c')
71 (1, 2, 3)
72 >>> mock.side_effect = [5, 4, 3, 2, 1]
73 >>> mock(), mock(), mock()
74 (5, 4, 3)
75
76Mock has many other ways you can configure it and control its behaviour. For
Georg Brandl7ad3df62014-10-31 07:59:37 +010077example the *spec* argument configures the mock to take its specification
Michael Foord944e02d2012-03-25 23:12:55 +010078from another object. Attempting to access attributes or methods on the mock
Georg Brandl7ad3df62014-10-31 07:59:37 +010079that don't exist on the spec will fail with an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +010080
81The :func:`patch` decorator / context manager makes it easy to mock classes or
82objects in a module under test. The object you specify will be replaced with a
83mock (or other object) during the test and restored when the test ends:
84
85 >>> from unittest.mock import patch
86 >>> @patch('module.ClassName2')
87 ... @patch('module.ClassName1')
88 ... def test(MockClass1, MockClass2):
89 ... module.ClassName1()
90 ... module.ClassName2()
Michael Foord944e02d2012-03-25 23:12:55 +010091 ... assert MockClass1 is module.ClassName1
92 ... assert MockClass2 is module.ClassName2
93 ... assert MockClass1.called
94 ... assert MockClass2.called
95 ...
96 >>> test()
97
98.. note::
99
100 When you nest patch decorators the mocks are passed in to the decorated
101 function in the same order they applied (the normal *python* order that
102 decorators are applied). This means from the bottom up, so in the example
Georg Brandl7ad3df62014-10-31 07:59:37 +0100103 above the mock for ``module.ClassName1`` is passed in first.
Michael Foord944e02d2012-03-25 23:12:55 +0100104
Georg Brandl7ad3df62014-10-31 07:59:37 +0100105 With :func:`patch` it matters that you patch objects in the namespace where they
Michael Foord944e02d2012-03-25 23:12:55 +0100106 are looked up. This is normally straightforward, but for a quick guide
107 read :ref:`where to patch <where-to-patch>`.
108
Georg Brandl7ad3df62014-10-31 07:59:37 +0100109As well as a decorator :func:`patch` can be used as a context manager in a with
Michael Foord944e02d2012-03-25 23:12:55 +0100110statement:
111
112 >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
113 ... thing = ProductionClass()
114 ... thing.method(1, 2, 3)
115 ...
116 >>> mock_method.assert_called_once_with(1, 2, 3)
117
118
119There is also :func:`patch.dict` for setting values in a dictionary just
120during a scope and restoring the dictionary to its original state when the test
121ends:
122
123 >>> foo = {'key': 'value'}
124 >>> original = foo.copy()
125 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
126 ... assert foo == {'newkey': 'newvalue'}
127 ...
128 >>> assert foo == original
129
130Mock supports the mocking of Python :ref:`magic methods <magic-methods>`. The
131easiest way of using magic methods is with the :class:`MagicMock` class. It
132allows you to do things like:
133
134 >>> mock = MagicMock()
135 >>> mock.__str__.return_value = 'foobarbaz'
136 >>> str(mock)
137 'foobarbaz'
138 >>> mock.__str__.assert_called_with()
139
140Mock allows you to assign functions (or other Mock instances) to magic methods
Georg Brandl7ad3df62014-10-31 07:59:37 +0100141and they will be called appropriately. The :class:`MagicMock` class is just a Mock
Michael Foord944e02d2012-03-25 23:12:55 +0100142variant that has all of the magic methods pre-created for you (well, all the
143useful ones anyway).
144
145The following is an example of using magic methods with the ordinary Mock
146class:
147
148 >>> mock = Mock()
149 >>> mock.__str__ = Mock(return_value='wheeeeee')
150 >>> str(mock)
151 'wheeeeee'
152
153For ensuring that the mock objects in your tests have the same api as the
154objects they are replacing, you can use :ref:`auto-speccing <auto-speccing>`.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100155Auto-speccing can be done through the *autospec* argument to patch, or the
Michael Foord944e02d2012-03-25 23:12:55 +0100156:func:`create_autospec` function. Auto-speccing creates mock objects that
157have the same attributes and methods as the objects they are replacing, and
158any functions and methods (including constructors) have the same call
159signature as the real object.
160
161This ensures that your mocks will fail in the same way as your production
162code if they are used incorrectly:
163
164 >>> from unittest.mock import create_autospec
165 >>> def function(a, b, c):
166 ... pass
167 ...
168 >>> mock_function = create_autospec(function, return_value='fishy')
169 >>> mock_function(1, 2, 3)
170 'fishy'
171 >>> mock_function.assert_called_once_with(1, 2, 3)
172 >>> mock_function('wrong arguments')
173 Traceback (most recent call last):
174 ...
175 TypeError: <lambda>() takes exactly 3 arguments (1 given)
176
Georg Brandl7ad3df62014-10-31 07:59:37 +0100177:func:`create_autospec` can also be used on classes, where it copies the signature of
178the ``__init__`` method, and on callable objects where it copies the signature of
179the ``__call__`` method.
Michael Foord944e02d2012-03-25 23:12:55 +0100180
181
182
183The Mock Class
184--------------
185
186
Georg Brandl7ad3df62014-10-31 07:59:37 +0100187:class:`Mock` is a flexible mock object intended to replace the use of stubs and
Michael Foord944e02d2012-03-25 23:12:55 +0100188test doubles throughout your code. Mocks are callable and create attributes as
189new mocks when you access them [#]_. Accessing the same attribute will always
190return the same mock. Mocks record how you use them, allowing you to make
191assertions about what your code has done to them.
192
Georg Brandl7ad3df62014-10-31 07:59:37 +0100193:class:`MagicMock` is a subclass of :class:`Mock` with all the magic methods
Michael Foord944e02d2012-03-25 23:12:55 +0100194pre-created and ready to use. There are also non-callable variants, useful
195when you are mocking out objects that aren't callable:
196:class:`NonCallableMock` and :class:`NonCallableMagicMock`
197
198The :func:`patch` decorators makes it easy to temporarily replace classes
Georg Brandl7ad3df62014-10-31 07:59:37 +0100199in a particular module with a :class:`Mock` object. By default :func:`patch` will create
200a :class:`MagicMock` for you. You can specify an alternative class of :class:`Mock` using
201the *new_callable* argument to :func:`patch`.
Michael Foord944e02d2012-03-25 23:12:55 +0100202
203
Kushal Das8c145342014-04-16 23:32:21 +0530204.. 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 +0100205
Georg Brandl7ad3df62014-10-31 07:59:37 +0100206 Create a new :class:`Mock` object. :class:`Mock` takes several optional arguments
Michael Foord944e02d2012-03-25 23:12:55 +0100207 that specify the behaviour of the Mock object:
208
Georg Brandl7ad3df62014-10-31 07:59:37 +0100209 * *spec*: This can be either a list of strings or an existing object (a
Michael Foord944e02d2012-03-25 23:12:55 +0100210 class or instance) that acts as the specification for the mock object. If
211 you pass in an object then a list of strings is formed by calling dir on
212 the object (excluding unsupported magic attributes and methods).
Georg Brandl7ad3df62014-10-31 07:59:37 +0100213 Accessing any attribute not in this list will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100214
Georg Brandl7ad3df62014-10-31 07:59:37 +0100215 If *spec* is an object (rather than a list of strings) then
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300216 :attr:`~instance.__class__` returns the class of the spec object. This
Georg Brandl7ad3df62014-10-31 07:59:37 +0100217 allows mocks to pass :func:`isinstance` tests.
Michael Foord944e02d2012-03-25 23:12:55 +0100218
Georg Brandl7ad3df62014-10-31 07:59:37 +0100219 * *spec_set*: A stricter variant of *spec*. If used, attempting to *set*
Michael Foord944e02d2012-03-25 23:12:55 +0100220 or get an attribute on the mock that isn't on the object passed as
Georg Brandl7ad3df62014-10-31 07:59:37 +0100221 *spec_set* will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100222
Georg Brandl7ad3df62014-10-31 07:59:37 +0100223 * *side_effect*: A function to be called whenever the Mock is called. See
Michael Foord944e02d2012-03-25 23:12:55 +0100224 the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or
225 dynamically changing return values. The function is called with the same
226 arguments as the mock, and unless it returns :data:`DEFAULT`, the return
227 value of this function is used as the return value.
228
Georg Brandl7ad3df62014-10-31 07:59:37 +0100229 Alternatively *side_effect* can be an exception class or instance. In
Michael Foord944e02d2012-03-25 23:12:55 +0100230 this case the exception will be raised when the mock is called.
231
Georg Brandl7ad3df62014-10-31 07:59:37 +0100232 If *side_effect* is an iterable then each call to the mock will return
Michael Foord944e02d2012-03-25 23:12:55 +0100233 the next value from the iterable.
234
Georg Brandl7ad3df62014-10-31 07:59:37 +0100235 A *side_effect* can be cleared by setting it to ``None``.
Michael Foord944e02d2012-03-25 23:12:55 +0100236
Georg Brandl7ad3df62014-10-31 07:59:37 +0100237 * *return_value*: The value returned when the mock is called. By default
Michael Foord944e02d2012-03-25 23:12:55 +0100238 this is a new Mock (created on first access). See the
239 :attr:`return_value` attribute.
240
Georg Brandl7ad3df62014-10-31 07:59:37 +0100241 * *unsafe*: By default if any attribute starts with *assert* or
242 *assret* will raise an :exc:`AttributeError`. Passing ``unsafe=True``
243 will allow access to these attributes.
Kushal Das8c145342014-04-16 23:32:21 +0530244
245 .. versionadded:: 3.5
246
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300247 * *wraps*: Item for the mock object to wrap. If *wraps* is not ``None`` then
Michael Foord944e02d2012-03-25 23:12:55 +0100248 calling the Mock will pass the call through to the wrapped object
Michael Foord0682a0c2012-04-13 20:51:20 +0100249 (returning the real result). Attribute access on the mock will return a
250 Mock object that wraps the corresponding attribute of the wrapped
251 object (so attempting to access an attribute that doesn't exist will
Georg Brandl7ad3df62014-10-31 07:59:37 +0100252 raise an :exc:`AttributeError`).
Michael Foord944e02d2012-03-25 23:12:55 +0100253
Georg Brandl7ad3df62014-10-31 07:59:37 +0100254 If the mock has an explicit *return_value* set then calls are not passed
255 to the wrapped object and the *return_value* is returned instead.
Michael Foord944e02d2012-03-25 23:12:55 +0100256
Georg Brandl7ad3df62014-10-31 07:59:37 +0100257 * *name*: If the mock has a name then it will be used in the repr of the
Michael Foord944e02d2012-03-25 23:12:55 +0100258 mock. This can be useful for debugging. The name is propagated to child
259 mocks.
260
261 Mocks can also be called with arbitrary keyword arguments. These will be
262 used to set attributes on the mock after it is created. See the
263 :meth:`configure_mock` method for details.
264
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100265 .. method:: assert_called(*args, **kwargs)
266
267 Assert that the mock was called at least once.
268
269 >>> mock = Mock()
270 >>> mock.method()
271 <Mock name='mock.method()' id='...'>
272 >>> mock.method.assert_called()
273
274 .. versionadded:: 3.6
275
276 .. method:: assert_called_once(*args, **kwargs)
277
278 Assert that the mock was called exactly once.
279
280 >>> mock = Mock()
281 >>> mock.method()
282 <Mock name='mock.method()' id='...'>
283 >>> mock.method.assert_called_once()
284 >>> mock.method()
285 <Mock name='mock.method()' id='...'>
286 >>> mock.method.assert_called_once()
287 Traceback (most recent call last):
288 ...
289 AssertionError: Expected 'method' to have been called once. Called 2 times.
290
291 .. versionadded:: 3.6
292
Michael Foord944e02d2012-03-25 23:12:55 +0100293
294 .. method:: assert_called_with(*args, **kwargs)
295
296 This method is a convenient way of asserting that calls are made in a
297 particular way:
298
299 >>> mock = Mock()
300 >>> mock.method(1, 2, 3, test='wow')
301 <Mock name='mock.method()' id='...'>
302 >>> mock.method.assert_called_with(1, 2, 3, test='wow')
303
Michael Foord944e02d2012-03-25 23:12:55 +0100304 .. method:: assert_called_once_with(*args, **kwargs)
305
Arne de Laat324c5d82017-02-23 15:57:25 +0100306 Assert that the mock was called exactly once and that that call was
307 with the specified arguments.
Michael Foord944e02d2012-03-25 23:12:55 +0100308
309 >>> mock = Mock(return_value=None)
310 >>> mock('foo', bar='baz')
311 >>> mock.assert_called_once_with('foo', bar='baz')
Arne de Laat324c5d82017-02-23 15:57:25 +0100312 >>> mock('other', bar='values')
313 >>> mock.assert_called_once_with('other', bar='values')
Michael Foord944e02d2012-03-25 23:12:55 +0100314 Traceback (most recent call last):
315 ...
Michael Foord28d591c2012-09-28 16:15:22 +0100316 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foord944e02d2012-03-25 23:12:55 +0100317
318
319 .. method:: assert_any_call(*args, **kwargs)
320
321 assert the mock has been called with the specified arguments.
322
323 The assert passes if the mock has *ever* been called, unlike
324 :meth:`assert_called_with` and :meth:`assert_called_once_with` that
Arne de Laat324c5d82017-02-23 15:57:25 +0100325 only pass if the call is the most recent one, and in the case of
326 :meth:`assert_called_once_with` it must also be the only call.
Michael Foord944e02d2012-03-25 23:12:55 +0100327
328 >>> mock = Mock(return_value=None)
329 >>> mock(1, 2, arg='thing')
330 >>> mock('some', 'thing', 'else')
331 >>> mock.assert_any_call(1, 2, arg='thing')
332
333
334 .. method:: assert_has_calls(calls, any_order=False)
335
336 assert the mock has been called with the specified calls.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100337 The :attr:`mock_calls` list is checked for the calls.
Michael Foord944e02d2012-03-25 23:12:55 +0100338
Georg Brandl7ad3df62014-10-31 07:59:37 +0100339 If *any_order* is false (the default) then the calls must be
Michael Foord944e02d2012-03-25 23:12:55 +0100340 sequential. There can be extra calls before or after the
341 specified calls.
342
Georg Brandl7ad3df62014-10-31 07:59:37 +0100343 If *any_order* is true then the calls can be in any order, but
Michael Foord944e02d2012-03-25 23:12:55 +0100344 they must all appear in :attr:`mock_calls`.
345
346 >>> mock = Mock(return_value=None)
347 >>> mock(1)
348 >>> mock(2)
349 >>> mock(3)
350 >>> mock(4)
351 >>> calls = [call(2), call(3)]
352 >>> mock.assert_has_calls(calls)
353 >>> calls = [call(4), call(2), call(3)]
354 >>> mock.assert_has_calls(calls, any_order=True)
355
Berker Peksagebf9fd32016-07-17 15:26:46 +0300356 .. method:: assert_not_called()
Kushal Das8af9db32014-04-17 01:36:14 +0530357
358 Assert the mock was never called.
359
360 >>> m = Mock()
361 >>> m.hello.assert_not_called()
362 >>> obj = m.hello()
363 >>> m.hello.assert_not_called()
364 Traceback (most recent call last):
365 ...
366 AssertionError: Expected 'hello' to not have been called. Called 1 times.
367
368 .. versionadded:: 3.5
369
Michael Foord944e02d2012-03-25 23:12:55 +0100370
Kushal Das9cd39a12016-06-02 10:20:16 -0700371 .. method:: reset_mock(*, return_value=False, side_effect=False)
Michael Foord944e02d2012-03-25 23:12:55 +0100372
373 The reset_mock method resets all the call attributes on a mock object:
374
375 >>> mock = Mock(return_value=None)
376 >>> mock('hello')
377 >>> mock.called
378 True
379 >>> mock.reset_mock()
380 >>> mock.called
381 False
382
Kushal Das9cd39a12016-06-02 10:20:16 -0700383 .. versionchanged:: 3.6
384 Added two keyword only argument to the reset_mock function.
385
Michael Foord944e02d2012-03-25 23:12:55 +0100386 This can be useful where you want to make a series of assertions that
Georg Brandl7ad3df62014-10-31 07:59:37 +0100387 reuse the same object. Note that :meth:`reset_mock` *doesn't* clear the
Michael Foord944e02d2012-03-25 23:12:55 +0100388 return value, :attr:`side_effect` or any child attributes you have
Kushal Das9cd39a12016-06-02 10:20:16 -0700389 set using normal assignment by default. In case you want to reset
390 *return_value* or :attr:`side_effect`, then pass the corresponding
391 parameter as ``True``. Child mocks and the return value mock
Michael Foord944e02d2012-03-25 23:12:55 +0100392 (if any) are reset as well.
393
Kushal Das9cd39a12016-06-02 10:20:16 -0700394 .. note:: *return_value*, and :attr:`side_effect` are keyword only
395 argument.
396
Michael Foord944e02d2012-03-25 23:12:55 +0100397
398 .. method:: mock_add_spec(spec, spec_set=False)
399
Georg Brandl7ad3df62014-10-31 07:59:37 +0100400 Add a spec to a mock. *spec* can either be an object or a
401 list of strings. Only attributes on the *spec* can be fetched as
Michael Foord944e02d2012-03-25 23:12:55 +0100402 attributes from the mock.
403
Georg Brandl7ad3df62014-10-31 07:59:37 +0100404 If *spec_set* is true then only attributes on the spec can be set.
Michael Foord944e02d2012-03-25 23:12:55 +0100405
406
407 .. method:: attach_mock(mock, attribute)
408
409 Attach a mock as an attribute of this one, replacing its name and
410 parent. Calls to the attached mock will be recorded in the
411 :attr:`method_calls` and :attr:`mock_calls` attributes of this one.
412
413
414 .. method:: configure_mock(**kwargs)
415
416 Set attributes on the mock through keyword arguments.
417
418 Attributes plus return values and side effects can be set on child
419 mocks using standard dot notation and unpacking a dictionary in the
420 method call:
421
422 >>> mock = Mock()
423 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
424 >>> mock.configure_mock(**attrs)
425 >>> mock.method()
426 3
427 >>> mock.other()
428 Traceback (most recent call last):
429 ...
430 KeyError
431
432 The same thing can be achieved in the constructor call to mocks:
433
434 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
435 >>> mock = Mock(some_attribute='eggs', **attrs)
436 >>> mock.some_attribute
437 'eggs'
438 >>> mock.method()
439 3
440 >>> mock.other()
441 Traceback (most recent call last):
442 ...
443 KeyError
444
Georg Brandl7ad3df62014-10-31 07:59:37 +0100445 :meth:`configure_mock` exists to make it easier to do configuration
Michael Foord944e02d2012-03-25 23:12:55 +0100446 after the mock has been created.
447
448
449 .. method:: __dir__()
450
Georg Brandl7ad3df62014-10-31 07:59:37 +0100451 :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results.
452 For mocks with a *spec* this includes all the permitted attributes
Michael Foord944e02d2012-03-25 23:12:55 +0100453 for the mock.
454
455 See :data:`FILTER_DIR` for what this filtering does, and how to
456 switch it off.
457
458
459 .. method:: _get_child_mock(**kw)
460
461 Create the child mocks for attributes and return value.
462 By default child mocks will be the same type as the parent.
463 Subclasses of Mock may want to override this to customize the way
464 child mocks are made.
465
466 For non-callable mocks the callable variant will be used (rather than
467 any custom subclass).
468
469
470 .. attribute:: called
471
472 A boolean representing whether or not the mock object has been called:
473
474 >>> mock = Mock(return_value=None)
475 >>> mock.called
476 False
477 >>> mock()
478 >>> mock.called
479 True
480
481 .. attribute:: call_count
482
483 An integer telling you how many times the mock object has been called:
484
485 >>> mock = Mock(return_value=None)
486 >>> mock.call_count
487 0
488 >>> mock()
489 >>> mock()
490 >>> mock.call_count
491 2
492
493
494 .. attribute:: return_value
495
496 Set this to configure the value returned by calling the mock:
497
498 >>> mock = Mock()
499 >>> mock.return_value = 'fish'
500 >>> mock()
501 'fish'
502
503 The default return value is a mock object and you can configure it in
504 the normal way:
505
506 >>> mock = Mock()
507 >>> mock.return_value.attribute = sentinel.Attribute
508 >>> mock.return_value()
509 <Mock name='mock()()' id='...'>
510 >>> mock.return_value.assert_called_with()
511
Georg Brandl7ad3df62014-10-31 07:59:37 +0100512 :attr:`return_value` can also be set in the constructor:
Michael Foord944e02d2012-03-25 23:12:55 +0100513
514 >>> mock = Mock(return_value=3)
515 >>> mock.return_value
516 3
517 >>> mock()
518 3
519
520
521 .. attribute:: side_effect
522
523 This can either be a function to be called when the mock is called,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100524 an iterable or an exception (class or instance) to be raised.
Michael Foord944e02d2012-03-25 23:12:55 +0100525
526 If you pass in a function it will be called with same arguments as the
527 mock and unless the function returns the :data:`DEFAULT` singleton the
528 call to the mock will then return whatever the function returns. If the
529 function returns :data:`DEFAULT` then the mock will return its normal
Brett Cannon533f1ed2013-05-25 11:28:20 -0400530 value (from the :attr:`return_value`).
Michael Foord944e02d2012-03-25 23:12:55 +0100531
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100532 If you pass in an iterable, it is used to retrieve an iterator which
533 must yield a value on every call. This value can either be an exception
534 instance to be raised, or a value to be returned from the call to the
535 mock (:data:`DEFAULT` handling is identical to the function case).
536
Michael Foord944e02d2012-03-25 23:12:55 +0100537 An example of a mock that raises an exception (to test exception
538 handling of an API):
539
540 >>> mock = Mock()
541 >>> mock.side_effect = Exception('Boom!')
542 >>> mock()
543 Traceback (most recent call last):
544 ...
545 Exception: Boom!
546
Georg Brandl7ad3df62014-10-31 07:59:37 +0100547 Using :attr:`side_effect` to return a sequence of values:
Michael Foord944e02d2012-03-25 23:12:55 +0100548
549 >>> mock = Mock()
550 >>> mock.side_effect = [3, 2, 1]
551 >>> mock(), mock(), mock()
552 (3, 2, 1)
553
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100554 Using a callable:
Michael Foord944e02d2012-03-25 23:12:55 +0100555
556 >>> mock = Mock(return_value=3)
557 >>> def side_effect(*args, **kwargs):
558 ... return DEFAULT
559 ...
560 >>> mock.side_effect = side_effect
561 >>> mock()
562 3
563
Georg Brandl7ad3df62014-10-31 07:59:37 +0100564 :attr:`side_effect` can be set in the constructor. Here's an example that
Michael Foord944e02d2012-03-25 23:12:55 +0100565 adds one to the value the mock is called with and returns it:
566
567 >>> side_effect = lambda value: value + 1
568 >>> mock = Mock(side_effect=side_effect)
569 >>> mock(3)
570 4
571 >>> mock(-8)
572 -7
573
Georg Brandl7ad3df62014-10-31 07:59:37 +0100574 Setting :attr:`side_effect` to ``None`` clears it:
Michael Foord944e02d2012-03-25 23:12:55 +0100575
576 >>> m = Mock(side_effect=KeyError, return_value=3)
577 >>> m()
578 Traceback (most recent call last):
579 ...
580 KeyError
581 >>> m.side_effect = None
582 >>> m()
583 3
584
585
586 .. attribute:: call_args
587
Georg Brandl7ad3df62014-10-31 07:59:37 +0100588 This is either ``None`` (if the mock hasn't been called), or the
Michael Foord944e02d2012-03-25 23:12:55 +0100589 arguments that the mock was last called with. This will be in the
590 form of a tuple: the first member is any ordered arguments the mock
591 was called with (or an empty tuple) and the second member is any
592 keyword arguments (or an empty dictionary).
593
594 >>> mock = Mock(return_value=None)
Berker Peksag920f6db2015-09-10 21:41:15 +0300595 >>> print(mock.call_args)
Michael Foord944e02d2012-03-25 23:12:55 +0100596 None
597 >>> mock()
598 >>> mock.call_args
599 call()
600 >>> mock.call_args == ()
601 True
602 >>> mock(3, 4)
603 >>> mock.call_args
604 call(3, 4)
605 >>> mock.call_args == ((3, 4),)
606 True
607 >>> mock(3, 4, 5, key='fish', next='w00t!')
608 >>> mock.call_args
609 call(3, 4, 5, key='fish', next='w00t!')
610
Georg Brandl7ad3df62014-10-31 07:59:37 +0100611 :attr:`call_args`, along with members of the lists :attr:`call_args_list`,
Michael Foord944e02d2012-03-25 23:12:55 +0100612 :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects.
613 These are tuples, so they can be unpacked to get at the individual
614 arguments and make more complex assertions. See
615 :ref:`calls as tuples <calls-as-tuples>`.
616
617
618 .. attribute:: call_args_list
619
620 This is a list of all the calls made to the mock object in sequence
621 (so the length of the list is the number of times it has been
622 called). Before any calls have been made it is an empty list. The
623 :data:`call` object can be used for conveniently constructing lists of
Georg Brandl7ad3df62014-10-31 07:59:37 +0100624 calls to compare with :attr:`call_args_list`.
Michael Foord944e02d2012-03-25 23:12:55 +0100625
626 >>> mock = Mock(return_value=None)
627 >>> mock()
628 >>> mock(3, 4)
629 >>> mock(key='fish', next='w00t!')
630 >>> mock.call_args_list
631 [call(), call(3, 4), call(key='fish', next='w00t!')]
632 >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
633 >>> mock.call_args_list == expected
634 True
635
Georg Brandl7ad3df62014-10-31 07:59:37 +0100636 Members of :attr:`call_args_list` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100637 unpacked as tuples to get at the individual arguments. See
638 :ref:`calls as tuples <calls-as-tuples>`.
639
640
641 .. attribute:: method_calls
642
643 As well as tracking calls to themselves, mocks also track calls to
644 methods and attributes, and *their* methods and attributes:
645
646 >>> mock = Mock()
647 >>> mock.method()
648 <Mock name='mock.method()' id='...'>
649 >>> mock.property.method.attribute()
650 <Mock name='mock.property.method.attribute()' id='...'>
651 >>> mock.method_calls
652 [call.method(), call.property.method.attribute()]
653
Georg Brandl7ad3df62014-10-31 07:59:37 +0100654 Members of :attr:`method_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100655 unpacked as tuples to get at the individual arguments. See
656 :ref:`calls as tuples <calls-as-tuples>`.
657
658
659 .. attribute:: mock_calls
660
Georg Brandl7ad3df62014-10-31 07:59:37 +0100661 :attr:`mock_calls` records *all* calls to the mock object, its methods,
662 magic methods *and* return value mocks.
Michael Foord944e02d2012-03-25 23:12:55 +0100663
664 >>> mock = MagicMock()
665 >>> result = mock(1, 2, 3)
666 >>> mock.first(a=3)
667 <MagicMock name='mock.first()' id='...'>
668 >>> mock.second()
669 <MagicMock name='mock.second()' id='...'>
670 >>> int(mock)
671 1
672 >>> result(1)
673 <MagicMock name='mock()()' id='...'>
674 >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
675 ... call.__int__(), call()(1)]
676 >>> mock.mock_calls == expected
677 True
678
Georg Brandl7ad3df62014-10-31 07:59:37 +0100679 Members of :attr:`mock_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100680 unpacked as tuples to get at the individual arguments. See
681 :ref:`calls as tuples <calls-as-tuples>`.
682
683
684 .. attribute:: __class__
685
Georg Brandl7ad3df62014-10-31 07:59:37 +0100686 Normally the :attr:`__class__` attribute of an object will return its type.
687 For a mock object with a :attr:`spec`, ``__class__`` returns the spec class
688 instead. This allows mock objects to pass :func:`isinstance` tests for the
Michael Foord944e02d2012-03-25 23:12:55 +0100689 object they are replacing / masquerading as:
690
691 >>> mock = Mock(spec=3)
692 >>> isinstance(mock, int)
693 True
694
Georg Brandl7ad3df62014-10-31 07:59:37 +0100695 :attr:`__class__` is assignable to, this allows a mock to pass an
696 :func:`isinstance` check without forcing you to use a spec:
Michael Foord944e02d2012-03-25 23:12:55 +0100697
698 >>> mock = Mock()
699 >>> mock.__class__ = dict
700 >>> isinstance(mock, dict)
701 True
702
703.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
704
Georg Brandl7ad3df62014-10-31 07:59:37 +0100705 A non-callable version of :class:`Mock`. The constructor parameters have the same
706 meaning of :class:`Mock`, with the exception of *return_value* and *side_effect*
Michael Foord944e02d2012-03-25 23:12:55 +0100707 which have no meaning on a non-callable mock.
708
Georg Brandl7ad3df62014-10-31 07:59:37 +0100709Mock objects that use a class or an instance as a :attr:`spec` or
710:attr:`spec_set` are able to pass :func:`isinstance` tests:
Michael Foord944e02d2012-03-25 23:12:55 +0100711
712 >>> mock = Mock(spec=SomeClass)
713 >>> isinstance(mock, SomeClass)
714 True
715 >>> mock = Mock(spec_set=SomeClass())
716 >>> isinstance(mock, SomeClass)
717 True
718
Georg Brandl7ad3df62014-10-31 07:59:37 +0100719The :class:`Mock` classes have support for mocking magic methods. See :ref:`magic
Michael Foord944e02d2012-03-25 23:12:55 +0100720methods <magic-methods>` for the full details.
721
722The mock classes and the :func:`patch` decorators all take arbitrary keyword
Georg Brandl7ad3df62014-10-31 07:59:37 +0100723arguments for configuration. For the :func:`patch` decorators the keywords are
Michael Foord944e02d2012-03-25 23:12:55 +0100724passed to the constructor of the mock being created. The keyword arguments
725are for configuring attributes of the mock:
726
727 >>> m = MagicMock(attribute=3, other='fish')
728 >>> m.attribute
729 3
730 >>> m.other
731 'fish'
732
733The return value and side effect of child mocks can be set in the same way,
734using dotted notation. As you can't use dotted names directly in a call you
Georg Brandl7ad3df62014-10-31 07:59:37 +0100735have to create a dictionary and unpack it using ``**``:
Michael Foord944e02d2012-03-25 23:12:55 +0100736
737 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
738 >>> mock = Mock(some_attribute='eggs', **attrs)
739 >>> mock.some_attribute
740 'eggs'
741 >>> mock.method()
742 3
743 >>> mock.other()
744 Traceback (most recent call last):
745 ...
746 KeyError
747
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100748A callable mock which was created with a *spec* (or a *spec_set*) will
749introspect the specification object's signature when matching calls to
750the mock. Therefore, it can match the actual call's arguments regardless
751of whether they were passed positionally or by name::
752
753 >>> def f(a, b, c): pass
754 ...
755 >>> mock = Mock(spec=f)
756 >>> mock(1, 2, c=3)
757 <Mock name='mock()' id='140161580456576'>
758 >>> mock.assert_called_with(1, 2, 3)
759 >>> mock.assert_called_with(a=1, b=2, c=3)
760
761This applies to :meth:`~Mock.assert_called_with`,
762:meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and
763:meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also
764apply to method calls on the mock object.
765
766 .. versionchanged:: 3.4
767 Added signature introspection on specced and autospecced mock objects.
768
Michael Foord944e02d2012-03-25 23:12:55 +0100769
770.. class:: PropertyMock(*args, **kwargs)
771
772 A mock intended to be used as a property, or other descriptor, on a class.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100773 :class:`PropertyMock` provides :meth:`__get__` and :meth:`__set__` methods
774 so you can specify a return value when it is fetched.
Michael Foord944e02d2012-03-25 23:12:55 +0100775
Georg Brandl7ad3df62014-10-31 07:59:37 +0100776 Fetching a :class:`PropertyMock` instance from an object calls the mock, with
Michael Foord944e02d2012-03-25 23:12:55 +0100777 no args. Setting it calls the mock with the value being set.
778
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200779 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100780 ... @property
781 ... def foo(self):
782 ... return 'something'
783 ... @foo.setter
784 ... def foo(self, value):
785 ... pass
786 ...
787 >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
788 ... mock_foo.return_value = 'mockity-mock'
789 ... this_foo = Foo()
Berker Peksag920f6db2015-09-10 21:41:15 +0300790 ... print(this_foo.foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100791 ... this_foo.foo = 6
792 ...
793 mockity-mock
794 >>> mock_foo.mock_calls
795 [call(), call(6)]
796
Michael Foordc2870622012-04-13 16:57:22 +0100797Because of the way mock attributes are stored you can't directly attach a
Georg Brandl7ad3df62014-10-31 07:59:37 +0100798:class:`PropertyMock` to a mock object. Instead you can attach it to the mock type
Michael Foordc2870622012-04-13 16:57:22 +0100799object::
800
801 >>> m = MagicMock()
802 >>> p = PropertyMock(return_value=3)
803 >>> type(m).foo = p
804 >>> m.foo
805 3
806 >>> p.assert_called_once_with()
807
Michael Foord944e02d2012-03-25 23:12:55 +0100808
809Calling
810~~~~~~~
811
812Mock objects are callable. The call will return the value set as the
813:attr:`~Mock.return_value` attribute. The default return value is a new Mock
814object; it is created the first time the return value is accessed (either
815explicitly or by calling the Mock) - but it is stored and the same one
816returned each time.
817
818Calls made to the object will be recorded in the attributes
819like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
820
821If :attr:`~Mock.side_effect` is set then it will be called after the call has
Georg Brandl7ad3df62014-10-31 07:59:37 +0100822been recorded, so if :attr:`side_effect` raises an exception the call is still
Michael Foord944e02d2012-03-25 23:12:55 +0100823recorded.
824
825The simplest way to make a mock raise an exception when called is to make
826:attr:`~Mock.side_effect` an exception class or instance:
827
828 >>> m = MagicMock(side_effect=IndexError)
829 >>> m(1, 2, 3)
830 Traceback (most recent call last):
831 ...
832 IndexError
833 >>> m.mock_calls
834 [call(1, 2, 3)]
835 >>> m.side_effect = KeyError('Bang!')
836 >>> m('two', 'three', 'four')
837 Traceback (most recent call last):
838 ...
839 KeyError: 'Bang!'
840 >>> m.mock_calls
841 [call(1, 2, 3), call('two', 'three', 'four')]
842
Georg Brandl7ad3df62014-10-31 07:59:37 +0100843If :attr:`side_effect` is a function then whatever that function returns is what
844calls to the mock return. The :attr:`side_effect` function is called with the
Michael Foord944e02d2012-03-25 23:12:55 +0100845same arguments as the mock. This allows you to vary the return value of the
846call dynamically, based on the input:
847
848 >>> def side_effect(value):
849 ... return value + 1
850 ...
851 >>> m = MagicMock(side_effect=side_effect)
852 >>> m(1)
853 2
854 >>> m(2)
855 3
856 >>> m.mock_calls
857 [call(1), call(2)]
858
859If you want the mock to still return the default return value (a new mock), or
860any set return value, then there are two ways of doing this. Either return
Georg Brandl7ad3df62014-10-31 07:59:37 +0100861:attr:`mock.return_value` from inside :attr:`side_effect`, or return :data:`DEFAULT`:
Michael Foord944e02d2012-03-25 23:12:55 +0100862
863 >>> m = MagicMock()
864 >>> def side_effect(*args, **kwargs):
865 ... return m.return_value
866 ...
867 >>> m.side_effect = side_effect
868 >>> m.return_value = 3
869 >>> m()
870 3
871 >>> def side_effect(*args, **kwargs):
872 ... return DEFAULT
873 ...
874 >>> m.side_effect = side_effect
875 >>> m()
876 3
877
Georg Brandl7ad3df62014-10-31 07:59:37 +0100878To remove a :attr:`side_effect`, and return to the default behaviour, set the
879:attr:`side_effect` to ``None``:
Michael Foord944e02d2012-03-25 23:12:55 +0100880
881 >>> m = MagicMock(return_value=6)
882 >>> def side_effect(*args, **kwargs):
883 ... return 3
884 ...
885 >>> m.side_effect = side_effect
886 >>> m()
887 3
888 >>> m.side_effect = None
889 >>> m()
890 6
891
Georg Brandl7ad3df62014-10-31 07:59:37 +0100892The :attr:`side_effect` can also be any iterable object. Repeated calls to the mock
Michael Foord944e02d2012-03-25 23:12:55 +0100893will return values from the iterable (until the iterable is exhausted and
Georg Brandl7ad3df62014-10-31 07:59:37 +0100894a :exc:`StopIteration` is raised):
Michael Foord944e02d2012-03-25 23:12:55 +0100895
896 >>> m = MagicMock(side_effect=[1, 2, 3])
897 >>> m()
898 1
899 >>> m()
900 2
901 >>> m()
902 3
903 >>> m()
904 Traceback (most recent call last):
905 ...
906 StopIteration
907
Michael Foord2cd48732012-04-21 15:52:11 +0100908If any members of the iterable are exceptions they will be raised instead of
909returned::
910
911 >>> iterable = (33, ValueError, 66)
912 >>> m = MagicMock(side_effect=iterable)
913 >>> m()
914 33
915 >>> m()
916 Traceback (most recent call last):
917 ...
918 ValueError
919 >>> m()
920 66
921
Michael Foord944e02d2012-03-25 23:12:55 +0100922
923.. _deleting-attributes:
924
925Deleting Attributes
926~~~~~~~~~~~~~~~~~~~
927
928Mock objects create attributes on demand. This allows them to pretend to be
929objects of any type.
930
Georg Brandl7ad3df62014-10-31 07:59:37 +0100931You may want a mock object to return ``False`` to a :func:`hasattr` call, or raise an
932:exc:`AttributeError` when an attribute is fetched. You can do this by providing
933an object as a :attr:`spec` for a mock, but that isn't always convenient.
Michael Foord944e02d2012-03-25 23:12:55 +0100934
935You "block" attributes by deleting them. Once deleted, accessing an attribute
Georg Brandl7ad3df62014-10-31 07:59:37 +0100936will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100937
938 >>> mock = MagicMock()
939 >>> hasattr(mock, 'm')
940 True
941 >>> del mock.m
942 >>> hasattr(mock, 'm')
943 False
944 >>> del mock.f
945 >>> mock.f
946 Traceback (most recent call last):
947 ...
948 AttributeError: f
949
950
Michael Foordf5752302013-03-18 15:04:03 -0700951Mock names and the name attribute
952~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
953
954Since "name" is an argument to the :class:`Mock` constructor, if you want your
955mock object to have a "name" attribute you can't just pass it in at creation
956time. There are two alternatives. One option is to use
957:meth:`~Mock.configure_mock`::
958
959 >>> mock = MagicMock()
960 >>> mock.configure_mock(name='my_name')
961 >>> mock.name
962 'my_name'
963
964A simpler option is to simply set the "name" attribute after mock creation::
965
966 >>> mock = MagicMock()
967 >>> mock.name = "foo"
968
969
Michael Foord944e02d2012-03-25 23:12:55 +0100970Attaching Mocks as Attributes
971~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
972
973When you attach a mock as an attribute of another mock (or as the return
974value) it becomes a "child" of that mock. Calls to the child are recorded in
975the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
976parent. This is useful for configuring child mocks and then attaching them to
977the parent, or for attaching mocks to a parent that records all calls to the
978children and allows you to make assertions about the order of calls between
979mocks:
980
981 >>> parent = MagicMock()
982 >>> child1 = MagicMock(return_value=None)
983 >>> child2 = MagicMock(return_value=None)
984 >>> parent.child1 = child1
985 >>> parent.child2 = child2
986 >>> child1(1)
987 >>> child2(2)
988 >>> parent.mock_calls
989 [call.child1(1), call.child2(2)]
990
991The exception to this is if the mock has a name. This allows you to prevent
992the "parenting" if for some reason you don't want it to happen.
993
994 >>> mock = MagicMock()
995 >>> not_a_child = MagicMock(name='not-a-child')
996 >>> mock.attribute = not_a_child
997 >>> mock.attribute()
998 <MagicMock name='not-a-child()' id='...'>
999 >>> mock.mock_calls
1000 []
1001
1002Mocks created for you by :func:`patch` are automatically given names. To
1003attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
1004method:
1005
1006 >>> thing1 = object()
1007 >>> thing2 = object()
1008 >>> parent = MagicMock()
1009 >>> with patch('__main__.thing1', return_value=None) as child1:
1010 ... with patch('__main__.thing2', return_value=None) as child2:
1011 ... parent.attach_mock(child1, 'child1')
1012 ... parent.attach_mock(child2, 'child2')
1013 ... child1('one')
1014 ... child2('two')
1015 ...
1016 >>> parent.mock_calls
1017 [call.child1('one'), call.child2('two')]
1018
1019
1020.. [#] The only exceptions are magic methods and attributes (those that have
1021 leading and trailing double underscores). Mock doesn't create these but
Georg Brandl7ad3df62014-10-31 07:59:37 +01001022 instead raises an :exc:`AttributeError`. This is because the interpreter
Michael Foord944e02d2012-03-25 23:12:55 +01001023 will often implicitly request these methods, and gets *very* confused to
1024 get a new Mock object when it expects a magic method. If you need magic
1025 method support see :ref:`magic methods <magic-methods>`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001026
1027
1028The patchers
Georg Brandlfb134382013-02-03 11:47:49 +01001029------------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001030
1031The patch decorators are used for patching objects only within the scope of
1032the function they decorate. They automatically handle the unpatching for you,
1033even if exceptions are raised. All of these functions can also be used in with
1034statements or as class decorators.
1035
1036
1037patch
Georg Brandlfb134382013-02-03 11:47:49 +01001038~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001039
1040.. note::
1041
Georg Brandl7ad3df62014-10-31 07:59:37 +01001042 :func:`patch` is straightforward to use. The key is to do the patching in the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001043 right namespace. See the section `where to patch`_.
1044
1045.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1046
Georg Brandl7ad3df62014-10-31 07:59:37 +01001047 :func:`patch` acts as a function decorator, class decorator or a context
1048 manager. Inside the body of the function or with statement, the *target*
1049 is patched with a *new* object. When the function/with statement exits
Michael Foord54b3db82012-03-28 15:08:08 +01001050 the patch is undone.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001051
Georg Brandl7ad3df62014-10-31 07:59:37 +01001052 If *new* is omitted, then the target is replaced with a
1053 :class:`MagicMock`. If :func:`patch` is used as a decorator and *new* is
Michael Foord54b3db82012-03-28 15:08:08 +01001054 omitted, the created mock is passed in as an extra argument to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001055 decorated function. If :func:`patch` is used as a context manager the created
Michael Foord54b3db82012-03-28 15:08:08 +01001056 mock is returned by the context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001057
Georg Brandl7ad3df62014-10-31 07:59:37 +01001058 *target* should be a string in the form ``'package.module.ClassName'``. The
1059 *target* is imported and the specified object replaced with the *new*
1060 object, so the *target* must be importable from the environment you are
1061 calling :func:`patch` from. The target is imported when the decorated function
Michael Foord54b3db82012-03-28 15:08:08 +01001062 is executed, not at decoration time.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001063
Georg Brandl7ad3df62014-10-31 07:59:37 +01001064 The *spec* and *spec_set* keyword arguments are passed to the :class:`MagicMock`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001065 if patch is creating one for you.
1066
Georg Brandl7ad3df62014-10-31 07:59:37 +01001067 In addition you can pass ``spec=True`` or ``spec_set=True``, which causes
Michael Foorda9e6fb22012-03-28 14:36:02 +01001068 patch to pass in the object being mocked as the spec/spec_set object.
1069
Georg Brandl7ad3df62014-10-31 07:59:37 +01001070 *new_callable* allows you to specify a different class, or callable object,
1071 that will be called to create the *new* object. By default :class:`MagicMock` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001072 used.
1073
Georg Brandl7ad3df62014-10-31 07:59:37 +01001074 A more powerful form of *spec* is *autospec*. If you set ``autospec=True``
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001075 then the mock will be created with a spec from the object being replaced.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001076 All attributes of the mock will also have the spec of the corresponding
1077 attribute of the object being replaced. Methods and functions being mocked
Georg Brandl7ad3df62014-10-31 07:59:37 +01001078 will have their arguments checked and will raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001079 called with the wrong signature. For mocks
1080 replacing a class, their return value (the 'instance') will have the same
1081 spec as the class. See the :func:`create_autospec` function and
1082 :ref:`auto-speccing`.
1083
Georg Brandl7ad3df62014-10-31 07:59:37 +01001084 Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001085 arbitrary object as the spec instead of the one being replaced.
1086
Georg Brandl7ad3df62014-10-31 07:59:37 +01001087 By default :func:`patch` will fail to replace attributes that don't exist. If
1088 you pass in ``create=True``, and the attribute doesn't exist, patch will
Michael Foorda9e6fb22012-03-28 14:36:02 +01001089 create the attribute for you when the patched function is called, and
1090 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001091 attributes that your production code creates at runtime. It is off by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001092 default because it can be dangerous. With it switched on you can write
1093 passing tests against APIs that don't actually exist!
1094
Michael Foordfddcfa22014-04-14 16:25:20 -04001095 .. note::
1096
1097 .. versionchanged:: 3.5
1098 If you are patching builtins in a module then you don't
Georg Brandl7ad3df62014-10-31 07:59:37 +01001099 need to pass ``create=True``, it will be added by default.
Michael Foordfddcfa22014-04-14 16:25:20 -04001100
Georg Brandl7ad3df62014-10-31 07:59:37 +01001101 Patch can be used as a :class:`TestCase` class decorator. It works by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001102 decorating each test method in the class. This reduces the boilerplate
Georg Brandl7ad3df62014-10-31 07:59:37 +01001103 code when your test methods share a common patchings set. :func:`patch` finds
1104 tests by looking for method names that start with ``patch.TEST_PREFIX``.
1105 By default this is ``'test'``, which matches the way :mod:`unittest` finds tests.
1106 You can specify an alternative prefix by setting ``patch.TEST_PREFIX``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001107
1108 Patch can be used as a context manager, with the with statement. Here the
1109 patching applies to the indented block after the with statement. If you
1110 use "as" then the patched object will be bound to the name after the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001111 "as"; very useful if :func:`patch` is creating a mock object for you.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001112
Georg Brandl7ad3df62014-10-31 07:59:37 +01001113 :func:`patch` takes arbitrary keyword arguments. These will be passed to
1114 the :class:`Mock` (or *new_callable*) on construction.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001115
Georg Brandl7ad3df62014-10-31 07:59:37 +01001116 ``patch.dict(...)``, ``patch.multiple(...)`` and ``patch.object(...)`` are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001117 available for alternate use-cases.
1118
Georg Brandl7ad3df62014-10-31 07:59:37 +01001119:func:`patch` as function decorator, creating the mock for you and passing it into
Michael Foord90155362012-03-28 15:32:08 +01001120the decorated function:
1121
1122 >>> @patch('__main__.SomeClass')
Michael Foord324b58b2012-03-28 15:49:08 +01001123 ... def function(normal_argument, mock_class):
Michael Foord90155362012-03-28 15:32:08 +01001124 ... print(mock_class is SomeClass)
1125 ...
Michael Foord324b58b2012-03-28 15:49:08 +01001126 >>> function(None)
Michael Foord90155362012-03-28 15:32:08 +01001127 True
Michael Foorda9e6fb22012-03-28 14:36:02 +01001128
Georg Brandl7ad3df62014-10-31 07:59:37 +01001129Patching a class replaces the class with a :class:`MagicMock` *instance*. If the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001130class is instantiated in the code under test then it will be the
1131:attr:`~Mock.return_value` of the mock that will be used.
1132
1133If the class is instantiated multiple times you could use
1134:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
Georg Brandl7ad3df62014-10-31 07:59:37 +01001135can set the *return_value* to be anything you want.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001136
1137To configure return values on methods of *instances* on the patched class
Georg Brandl7ad3df62014-10-31 07:59:37 +01001138you must do this on the :attr:`return_value`. For example:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001139
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001140 >>> class Class:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001141 ... def method(self):
1142 ... pass
1143 ...
1144 >>> with patch('__main__.Class') as MockClass:
1145 ... instance = MockClass.return_value
1146 ... instance.method.return_value = 'foo'
1147 ... assert Class() is instance
1148 ... assert Class().method() == 'foo'
1149 ...
1150
Georg Brandl7ad3df62014-10-31 07:59:37 +01001151If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001152return value of the created mock will have the same spec.
1153
1154 >>> Original = Class
1155 >>> patcher = patch('__main__.Class', spec=True)
1156 >>> MockClass = patcher.start()
1157 >>> instance = MockClass()
1158 >>> assert isinstance(instance, Original)
1159 >>> patcher.stop()
1160
Georg Brandl7ad3df62014-10-31 07:59:37 +01001161The *new_callable* argument is useful where you want to use an alternative
Michael Foorda9e6fb22012-03-28 14:36:02 +01001162class to the default :class:`MagicMock` for the created mock. For example, if
1163you wanted a :class:`NonCallableMock` to be used:
1164
1165 >>> thing = object()
1166 >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
1167 ... assert thing is mock_thing
1168 ... thing()
1169 ...
1170 Traceback (most recent call last):
1171 ...
1172 TypeError: 'NonCallableMock' object is not callable
1173
Martin Panter7462b6492015-11-02 03:37:02 +00001174Another use case might be to replace an object with an :class:`io.StringIO` instance:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001175
Serhiy Storchakae79be872013-08-17 00:09:55 +03001176 >>> from io import StringIO
Michael Foorda9e6fb22012-03-28 14:36:02 +01001177 >>> def foo():
Berker Peksag920f6db2015-09-10 21:41:15 +03001178 ... print('Something')
Michael Foorda9e6fb22012-03-28 14:36:02 +01001179 ...
1180 >>> @patch('sys.stdout', new_callable=StringIO)
1181 ... def test(mock_stdout):
1182 ... foo()
1183 ... assert mock_stdout.getvalue() == 'Something\n'
1184 ...
1185 >>> test()
1186
Georg Brandl7ad3df62014-10-31 07:59:37 +01001187When :func:`patch` is creating a mock for you, it is common that the first thing
Michael Foorda9e6fb22012-03-28 14:36:02 +01001188you need to do is to configure the mock. Some of that configuration can be done
1189in the call to patch. Any arbitrary keywords you pass into the call will be
1190used to set attributes on the created mock:
1191
1192 >>> patcher = patch('__main__.thing', first='one', second='two')
1193 >>> mock_thing = patcher.start()
1194 >>> mock_thing.first
1195 'one'
1196 >>> mock_thing.second
1197 'two'
1198
1199As well as attributes on the created mock attributes, like the
1200:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
1201also be configured. These aren't syntactically valid to pass in directly as
1202keyword arguments, but a dictionary with these as keys can still be expanded
Georg Brandl7ad3df62014-10-31 07:59:37 +01001203into a :func:`patch` call using ``**``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001204
1205 >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
1206 >>> patcher = patch('__main__.thing', **config)
1207 >>> mock_thing = patcher.start()
1208 >>> mock_thing.method()
1209 3
1210 >>> mock_thing.other()
1211 Traceback (most recent call last):
1212 ...
1213 KeyError
1214
1215
1216patch.object
Georg Brandlfb134382013-02-03 11:47:49 +01001217~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001218
1219.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1220
Georg Brandl7ad3df62014-10-31 07:59:37 +01001221 patch the named member (*attribute*) on an object (*target*) with a mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001222 object.
1223
Georg Brandl7ad3df62014-10-31 07:59:37 +01001224 :func:`patch.object` can be used as a decorator, class decorator or a context
1225 manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* and
1226 *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`,
1227 :func:`patch.object` takes arbitrary keyword arguments for configuring the mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001228 object it creates.
1229
Georg Brandl7ad3df62014-10-31 07:59:37 +01001230 When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001231 for choosing which methods to wrap.
1232
Georg Brandl7ad3df62014-10-31 07:59:37 +01001233You can either call :func:`patch.object` with three arguments or two arguments. The
Michael Foorda9e6fb22012-03-28 14:36:02 +01001234three argument form takes the object to be patched, the attribute name and the
1235object to replace the attribute with.
1236
1237When calling with the two argument form you omit the replacement object, and a
1238mock is created for you and passed in as an extra argument to the decorated
1239function:
1240
1241 >>> @patch.object(SomeClass, 'class_method')
1242 ... def test(mock_method):
1243 ... SomeClass.class_method(3)
1244 ... mock_method.assert_called_with(3)
1245 ...
1246 >>> test()
1247
Georg Brandl7ad3df62014-10-31 07:59:37 +01001248*spec*, *create* and the other arguments to :func:`patch.object` have the same
1249meaning as they do for :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001250
1251
1252patch.dict
Georg Brandlfb134382013-02-03 11:47:49 +01001253~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001254
1255.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs)
1256
1257 Patch a dictionary, or dictionary like object, and restore the dictionary
1258 to its original state after the test.
1259
Georg Brandl7ad3df62014-10-31 07:59:37 +01001260 *in_dict* can be a dictionary or a mapping like container. If it is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01001261 mapping then it must at least support getting, setting and deleting items
1262 plus iterating over keys.
1263
Georg Brandl7ad3df62014-10-31 07:59:37 +01001264 *in_dict* can also be a string specifying the name of the dictionary, which
Michael Foorda9e6fb22012-03-28 14:36:02 +01001265 will then be fetched by importing it.
1266
Georg Brandl7ad3df62014-10-31 07:59:37 +01001267 *values* can be a dictionary of values to set in the dictionary. *values*
1268 can also be an iterable of ``(key, value)`` pairs.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001269
Georg Brandl7ad3df62014-10-31 07:59:37 +01001270 If *clear* is true then the dictionary will be cleared before the new
Michael Foorda9e6fb22012-03-28 14:36:02 +01001271 values are set.
1272
Georg Brandl7ad3df62014-10-31 07:59:37 +01001273 :func:`patch.dict` can also be called with arbitrary keyword arguments to set
Michael Foorda9e6fb22012-03-28 14:36:02 +01001274 values in the dictionary.
1275
Georg Brandl7ad3df62014-10-31 07:59:37 +01001276 :func:`patch.dict` can be used as a context manager, decorator or class
1277 decorator. When used as a class decorator :func:`patch.dict` honours
1278 ``patch.TEST_PREFIX`` for choosing which methods to wrap.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001279
Georg Brandl7ad3df62014-10-31 07:59:37 +01001280:func:`patch.dict` can be used to add members to a dictionary, or simply let a test
Michael Foorda9e6fb22012-03-28 14:36:02 +01001281change a dictionary, and ensure the dictionary is restored when the test
1282ends.
1283
1284 >>> foo = {}
1285 >>> with patch.dict(foo, {'newkey': 'newvalue'}):
1286 ... assert foo == {'newkey': 'newvalue'}
1287 ...
1288 >>> assert foo == {}
1289
1290 >>> import os
1291 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
Berker Peksag920f6db2015-09-10 21:41:15 +03001292 ... print(os.environ['newkey'])
Michael Foorda9e6fb22012-03-28 14:36:02 +01001293 ...
1294 newvalue
1295 >>> assert 'newkey' not in os.environ
1296
Georg Brandl7ad3df62014-10-31 07:59:37 +01001297Keywords can be used in the :func:`patch.dict` call to set values in the dictionary:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001298
1299 >>> mymodule = MagicMock()
1300 >>> mymodule.function.return_value = 'fish'
1301 >>> with patch.dict('sys.modules', mymodule=mymodule):
1302 ... import mymodule
1303 ... mymodule.function('some', 'args')
1304 ...
1305 'fish'
1306
Georg Brandl7ad3df62014-10-31 07:59:37 +01001307:func:`patch.dict` can be used with dictionary like objects that aren't actually
Michael Foorda9e6fb22012-03-28 14:36:02 +01001308dictionaries. At the very minimum they must support item getting, setting,
1309deleting and either iteration or membership test. This corresponds to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001310magic methods :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__` and either
1311:meth:`__iter__` or :meth:`__contains__`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001312
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001313 >>> class Container:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001314 ... def __init__(self):
1315 ... self.values = {}
1316 ... def __getitem__(self, name):
1317 ... return self.values[name]
1318 ... def __setitem__(self, name, value):
1319 ... self.values[name] = value
1320 ... def __delitem__(self, name):
1321 ... del self.values[name]
1322 ... def __iter__(self):
1323 ... return iter(self.values)
1324 ...
1325 >>> thing = Container()
1326 >>> thing['one'] = 1
1327 >>> with patch.dict(thing, one=2, two=3):
1328 ... assert thing['one'] == 2
1329 ... assert thing['two'] == 3
1330 ...
1331 >>> assert thing['one'] == 1
1332 >>> assert list(thing) == ['one']
1333
1334
1335patch.multiple
Georg Brandlfb134382013-02-03 11:47:49 +01001336~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001337
1338.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1339
1340 Perform multiple patches in a single call. It takes the object to be
1341 patched (either as an object or a string to fetch the object by importing)
1342 and keyword arguments for the patches::
1343
1344 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1345 ...
1346
Georg Brandl7ad3df62014-10-31 07:59:37 +01001347 Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create
Michael Foorda9e6fb22012-03-28 14:36:02 +01001348 mocks for you. In this case the created mocks are passed into a decorated
Georg Brandl7ad3df62014-10-31 07:59:37 +01001349 function by keyword, and a dictionary is returned when :func:`patch.multiple` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001350 used as a context manager.
1351
Georg Brandl7ad3df62014-10-31 07:59:37 +01001352 :func:`patch.multiple` can be used as a decorator, class decorator or a context
1353 manager. The arguments *spec*, *spec_set*, *create*, *autospec* and
1354 *new_callable* have the same meaning as for :func:`patch`. These arguments will
1355 be applied to *all* patches done by :func:`patch.multiple`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001356
Georg Brandl7ad3df62014-10-31 07:59:37 +01001357 When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001358 for choosing which methods to wrap.
1359
Georg Brandl7ad3df62014-10-31 07:59:37 +01001360If you want :func:`patch.multiple` to create mocks for you, then you can use
1361:data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator
Michael Foorda9e6fb22012-03-28 14:36:02 +01001362then the created mocks are passed into the decorated function by keyword.
1363
1364 >>> thing = object()
1365 >>> other = object()
1366
1367 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1368 ... def test_function(thing, other):
1369 ... assert isinstance(thing, MagicMock)
1370 ... assert isinstance(other, MagicMock)
1371 ...
1372 >>> test_function()
1373
Georg Brandl7ad3df62014-10-31 07:59:37 +01001374:func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments
1375passed by keyword *after* any of the standard arguments created by :func:`patch`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001376
1377 >>> @patch('sys.exit')
1378 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1379 ... def test_function(mock_exit, other, thing):
1380 ... assert 'other' in repr(other)
1381 ... assert 'thing' in repr(thing)
1382 ... assert 'exit' in repr(mock_exit)
1383 ...
1384 >>> test_function()
1385
Georg Brandl7ad3df62014-10-31 07:59:37 +01001386If :func:`patch.multiple` is used as a context manager, the value returned by the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001387context manger is a dictionary where created mocks are keyed by name:
1388
1389 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
1390 ... assert 'other' in repr(values['other'])
1391 ... assert 'thing' in repr(values['thing'])
1392 ... assert values['thing'] is thing
1393 ... assert values['other'] is other
1394 ...
1395
1396
1397.. _start-and-stop:
1398
1399patch methods: start and stop
Georg Brandlfb134382013-02-03 11:47:49 +01001400~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001401
Georg Brandl7ad3df62014-10-31 07:59:37 +01001402All the patchers have :meth:`start` and :meth:`stop` methods. These make it simpler to do
1403patching in ``setUp`` methods or where you want to do multiple patches without
Michael Foorda9e6fb22012-03-28 14:36:02 +01001404nesting decorators or with statements.
1405
Georg Brandl7ad3df62014-10-31 07:59:37 +01001406To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as
1407normal and keep a reference to the returned ``patcher`` object. You can then
1408call :meth:`start` to put the patch in place and :meth:`stop` to undo it.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001409
Georg Brandl7ad3df62014-10-31 07:59:37 +01001410If you are using :func:`patch` to create a mock for you then it will be returned by
1411the call to ``patcher.start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001412
1413 >>> patcher = patch('package.module.ClassName')
1414 >>> from package import module
1415 >>> original = module.ClassName
1416 >>> new_mock = patcher.start()
1417 >>> assert module.ClassName is not original
1418 >>> assert module.ClassName is new_mock
1419 >>> patcher.stop()
1420 >>> assert module.ClassName is original
1421 >>> assert module.ClassName is not new_mock
1422
1423
Georg Brandl7ad3df62014-10-31 07:59:37 +01001424A typical use case for this might be for doing multiple patches in the ``setUp``
1425method of a :class:`TestCase`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001426
1427 >>> class MyTest(TestCase):
1428 ... def setUp(self):
1429 ... self.patcher1 = patch('package.module.Class1')
1430 ... self.patcher2 = patch('package.module.Class2')
1431 ... self.MockClass1 = self.patcher1.start()
1432 ... self.MockClass2 = self.patcher2.start()
1433 ...
1434 ... def tearDown(self):
1435 ... self.patcher1.stop()
1436 ... self.patcher2.stop()
1437 ...
1438 ... def test_something(self):
1439 ... assert package.module.Class1 is self.MockClass1
1440 ... assert package.module.Class2 is self.MockClass2
1441 ...
1442 >>> MyTest('test_something').run()
1443
1444.. caution::
1445
1446 If you use this technique you must ensure that the patching is "undone" by
Georg Brandl7ad3df62014-10-31 07:59:37 +01001447 calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001448 exception is raised in the ``setUp`` then ``tearDown`` is not called.
1449 :meth:`unittest.TestCase.addCleanup` makes this easier:
1450
1451 >>> class MyTest(TestCase):
1452 ... def setUp(self):
1453 ... patcher = patch('package.module.Class')
1454 ... self.MockClass = patcher.start()
1455 ... self.addCleanup(patcher.stop)
1456 ...
1457 ... def test_something(self):
1458 ... assert package.module.Class is self.MockClass
1459 ...
1460
Georg Brandl7ad3df62014-10-31 07:59:37 +01001461 As an added bonus you no longer need to keep a reference to the ``patcher``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001462 object.
1463
Michael Foordf7c41582012-06-10 20:36:32 +01001464It is also possible to stop all patches which have been started by using
Georg Brandl7ad3df62014-10-31 07:59:37 +01001465:func:`patch.stopall`.
Michael Foordf7c41582012-06-10 20:36:32 +01001466
1467.. function:: patch.stopall
1468
Georg Brandl7ad3df62014-10-31 07:59:37 +01001469 Stop all active patches. Only stops patches started with ``start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001470
Georg Brandl7ad3df62014-10-31 07:59:37 +01001471
1472.. _patch-builtins:
Michael Foordfddcfa22014-04-14 16:25:20 -04001473
1474patch builtins
Georg Brandl7ad3df62014-10-31 07:59:37 +01001475~~~~~~~~~~~~~~
Michael Foordfddcfa22014-04-14 16:25:20 -04001476You can patch any builtins within a module. The following example patches
Georg Brandl7ad3df62014-10-31 07:59:37 +01001477builtin :func:`ord`:
Michael Foordfddcfa22014-04-14 16:25:20 -04001478
1479 >>> @patch('__main__.ord')
1480 ... def test(mock_ord):
1481 ... mock_ord.return_value = 101
1482 ... print(ord('c'))
1483 ...
1484 >>> test()
1485 101
1486
Michael Foorda9e6fb22012-03-28 14:36:02 +01001487
1488TEST_PREFIX
Georg Brandlfb134382013-02-03 11:47:49 +01001489~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001490
1491All of the patchers can be used as class decorators. When used in this way
1492they wrap every test method on the class. The patchers recognise methods that
Georg Brandl7ad3df62014-10-31 07:59:37 +01001493start with ``'test'`` as being test methods. This is the same way that the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001494:class:`unittest.TestLoader` finds test methods by default.
1495
1496It is possible that you want to use a different prefix for your tests. You can
Georg Brandl7ad3df62014-10-31 07:59:37 +01001497inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001498
1499 >>> patch.TEST_PREFIX = 'foo'
1500 >>> value = 3
1501 >>>
1502 >>> @patch('__main__.value', 'not three')
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001503 ... class Thing:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001504 ... def foo_one(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001505 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001506 ... def foo_two(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001507 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001508 ...
1509 >>>
1510 >>> Thing().foo_one()
1511 not three
1512 >>> Thing().foo_two()
1513 not three
1514 >>> value
1515 3
1516
1517
1518Nesting Patch Decorators
Georg Brandlfb134382013-02-03 11:47:49 +01001519~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001520
1521If you want to perform multiple patches then you can simply stack up the
1522decorators.
1523
1524You can stack up multiple patch decorators using this pattern:
1525
1526 >>> @patch.object(SomeClass, 'class_method')
1527 ... @patch.object(SomeClass, 'static_method')
1528 ... def test(mock1, mock2):
1529 ... assert SomeClass.static_method is mock1
1530 ... assert SomeClass.class_method is mock2
1531 ... SomeClass.static_method('foo')
1532 ... SomeClass.class_method('bar')
1533 ... return mock1, mock2
1534 ...
1535 >>> mock1, mock2 = test()
1536 >>> mock1.assert_called_once_with('foo')
1537 >>> mock2.assert_called_once_with('bar')
1538
1539
1540Note that the decorators are applied from the bottom upwards. This is the
1541standard way that Python applies decorators. The order of the created mocks
1542passed into your test function matches this order.
1543
1544
1545.. _where-to-patch:
1546
1547Where to patch
Georg Brandlfb134382013-02-03 11:47:49 +01001548~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001549
Georg Brandl7ad3df62014-10-31 07:59:37 +01001550:func:`patch` works by (temporarily) changing the object that a *name* points to with
Michael Foorda9e6fb22012-03-28 14:36:02 +01001551another one. There can be many names pointing to any individual object, so
1552for patching to work you must ensure that you patch the name used by the system
1553under test.
1554
1555The basic principle is that you patch where an object is *looked up*, which
1556is not necessarily the same place as where it is defined. A couple of
1557examples will help to clarify this.
1558
1559Imagine we have a project that we want to test with the following structure::
1560
1561 a.py
1562 -> Defines SomeClass
1563
1564 b.py
1565 -> from a import SomeClass
1566 -> some_function instantiates SomeClass
1567
Georg Brandl7ad3df62014-10-31 07:59:37 +01001568Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
1569:func:`patch`. The problem is that when we import module b, which we will have to
1570do then it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
1571``a.SomeClass`` then it will have no effect on our test; module b already has a
1572reference to the *real* ``SomeClass`` and it looks like our patching had no
Michael Foorda9e6fb22012-03-28 14:36:02 +01001573effect.
1574
Ben Lloyd15033d12017-05-22 12:06:56 +01001575The key is to patch out ``SomeClass`` where it is used (or where it is looked up).
1576In this case ``some_function`` will actually look up ``SomeClass`` in module b,
Michael Foorda9e6fb22012-03-28 14:36:02 +01001577where we have imported it. The patching should look like::
1578
1579 @patch('b.SomeClass')
1580
Georg Brandl7ad3df62014-10-31 07:59:37 +01001581However, consider the alternative scenario where instead of ``from a import
1582SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both
Michael Foorda9e6fb22012-03-28 14:36:02 +01001583of these import forms are common. In this case the class we want to patch is
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001584being looked up in the module and so we have to patch ``a.SomeClass`` instead::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001585
1586 @patch('a.SomeClass')
1587
1588
1589Patching Descriptors and Proxy Objects
Georg Brandlfb134382013-02-03 11:47:49 +01001590~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001591
1592Both patch_ and patch.object_ correctly patch and restore descriptors: class
1593methods, static methods and properties. You should patch these on the *class*
1594rather than an instance. They also work with *some* objects
Zachary Ware5ea5d2c2014-02-26 09:34:43 -06001595that proxy attribute access, like the `django settings object
Michael Foorda9e6fb22012-03-28 14:36:02 +01001596<http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
1597
1598
Michael Foord2309ed82012-03-28 15:38:36 +01001599MagicMock and magic method support
Georg Brandlfb134382013-02-03 11:47:49 +01001600----------------------------------
Michael Foord2309ed82012-03-28 15:38:36 +01001601
1602.. _magic-methods:
1603
1604Mocking Magic Methods
Georg Brandlfb134382013-02-03 11:47:49 +01001605~~~~~~~~~~~~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001606
1607:class:`Mock` supports mocking the Python protocol methods, also known as
1608"magic methods". This allows mock objects to replace containers or other
1609objects that implement Python protocols.
1610
1611Because magic methods are looked up differently from normal methods [#]_, this
1612support has been specially implemented. This means that only specific magic
1613methods are supported. The supported list includes *almost* all of them. If
1614there are any missing that you need please let us know.
1615
1616You mock magic methods by setting the method you are interested in to a function
1617or a mock instance. If you are using a function then it *must* take ``self`` as
1618the first argument [#]_.
1619
1620 >>> def __str__(self):
1621 ... return 'fooble'
1622 ...
1623 >>> mock = Mock()
1624 >>> mock.__str__ = __str__
1625 >>> str(mock)
1626 'fooble'
1627
1628 >>> mock = Mock()
1629 >>> mock.__str__ = Mock()
1630 >>> mock.__str__.return_value = 'fooble'
1631 >>> str(mock)
1632 'fooble'
1633
1634 >>> mock = Mock()
1635 >>> mock.__iter__ = Mock(return_value=iter([]))
1636 >>> list(mock)
1637 []
1638
1639One use case for this is for mocking objects used as context managers in a
Georg Brandl7ad3df62014-10-31 07:59:37 +01001640:keyword:`with` statement:
Michael Foord2309ed82012-03-28 15:38:36 +01001641
1642 >>> mock = Mock()
1643 >>> mock.__enter__ = Mock(return_value='foo')
1644 >>> mock.__exit__ = Mock(return_value=False)
1645 >>> with mock as m:
1646 ... assert m == 'foo'
1647 ...
1648 >>> mock.__enter__.assert_called_with()
1649 >>> mock.__exit__.assert_called_with(None, None, None)
1650
1651Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they
1652are recorded in :attr:`~Mock.mock_calls`.
1653
1654.. note::
1655
Georg Brandl7ad3df62014-10-31 07:59:37 +01001656 If you use the *spec* keyword argument to create a mock then attempting to
1657 set a magic method that isn't in the spec will raise an :exc:`AttributeError`.
Michael Foord2309ed82012-03-28 15:38:36 +01001658
1659The full list of supported magic methods is:
1660
1661* ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``
1662* ``__dir__``, ``__format__`` and ``__subclasses__``
John Reese6c4fab02018-05-22 13:01:10 -07001663* ``__round__``, ``__floor__``, ``__trunc__`` and ``__ceil__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001664* Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001665 ``__eq__`` and ``__ne__``
1666* Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``,
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001667 ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__``
1668 and ``__missing__``
Michael Foord2309ed82012-03-28 15:38:36 +01001669* Context manager: ``__enter__`` and ``__exit__``
1670* Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``
1671* The numeric methods (including right hand and in-place variants):
Serhiy Storchakac2ccce72015-03-12 22:01:30 +02001672 ``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__div__``, ``__truediv__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001673 ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``,
1674 ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001675* Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__``
1676 and ``__index__``
Michael Foord2309ed82012-03-28 15:38:36 +01001677* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
1678* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
1679 ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
1680
1681
1682The following methods exist but are *not* supported as they are either in use
1683by mock, can't be set dynamically, or can cause problems:
1684
1685* ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``
1686* ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``
1687
1688
1689
1690Magic Mock
Georg Brandlfb134382013-02-03 11:47:49 +01001691~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001692
Georg Brandl7ad3df62014-10-31 07:59:37 +01001693There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001694
1695
1696.. class:: MagicMock(*args, **kw)
1697
1698 ``MagicMock`` is a subclass of :class:`Mock` with default implementations
1699 of most of the magic methods. You can use ``MagicMock`` without having to
1700 configure the magic methods yourself.
1701
1702 The constructor parameters have the same meaning as for :class:`Mock`.
1703
Georg Brandl7ad3df62014-10-31 07:59:37 +01001704 If you use the *spec* or *spec_set* arguments then *only* magic methods
Michael Foord2309ed82012-03-28 15:38:36 +01001705 that exist in the spec will be created.
1706
1707
1708.. class:: NonCallableMagicMock(*args, **kw)
1709
Georg Brandl7ad3df62014-10-31 07:59:37 +01001710 A non-callable version of :class:`MagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001711
1712 The constructor parameters have the same meaning as for
Georg Brandl7ad3df62014-10-31 07:59:37 +01001713 :class:`MagicMock`, with the exception of *return_value* and
1714 *side_effect* which have no meaning on a non-callable mock.
Michael Foord2309ed82012-03-28 15:38:36 +01001715
Georg Brandl7ad3df62014-10-31 07:59:37 +01001716The magic methods are setup with :class:`MagicMock` objects, so you can configure them
Michael Foord2309ed82012-03-28 15:38:36 +01001717and use them in the usual way:
1718
1719 >>> mock = MagicMock()
1720 >>> mock[3] = 'fish'
1721 >>> mock.__setitem__.assert_called_with(3, 'fish')
1722 >>> mock.__getitem__.return_value = 'result'
1723 >>> mock[2]
1724 'result'
1725
1726By default many of the protocol methods are required to return objects of a
1727specific type. These methods are preconfigured with a default return value, so
1728that they can be used without you having to do anything if you aren't interested
1729in the return value. You can still *set* the return value manually if you want
1730to change the default.
1731
1732Methods and their defaults:
1733
1734* ``__lt__``: NotImplemented
1735* ``__gt__``: NotImplemented
1736* ``__le__``: NotImplemented
1737* ``__ge__``: NotImplemented
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001738* ``__int__``: 1
1739* ``__contains__``: False
Berker Peksag8fafc742016-04-11 12:23:04 +03001740* ``__len__``: 0
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001741* ``__iter__``: iter([])
1742* ``__exit__``: False
1743* ``__complex__``: 1j
1744* ``__float__``: 1.0
1745* ``__bool__``: True
1746* ``__index__``: 1
1747* ``__hash__``: default hash for the mock
1748* ``__str__``: default str for the mock
Michael Foord2309ed82012-03-28 15:38:36 +01001749* ``__sizeof__``: default sizeof for the mock
1750
1751For example:
1752
1753 >>> mock = MagicMock()
1754 >>> int(mock)
1755 1
1756 >>> len(mock)
1757 0
1758 >>> list(mock)
1759 []
1760 >>> object() in mock
1761 False
1762
Berker Peksag283f1aa2015-01-07 21:15:02 +02001763The two equality methods, :meth:`__eq__` and :meth:`__ne__`, are special.
1764They do the default equality comparison on identity, using the
1765:attr:`~Mock.side_effect` attribute, unless you change their return value to
1766return something else::
Michael Foord2309ed82012-03-28 15:38:36 +01001767
1768 >>> MagicMock() == 3
1769 False
1770 >>> MagicMock() != 3
1771 True
1772 >>> mock = MagicMock()
1773 >>> mock.__eq__.return_value = True
1774 >>> mock == 3
1775 True
1776
Georg Brandl7ad3df62014-10-31 07:59:37 +01001777The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
Michael Foord2309ed82012-03-28 15:38:36 +01001778required to be an iterator:
1779
1780 >>> mock = MagicMock()
1781 >>> mock.__iter__.return_value = ['a', 'b', 'c']
1782 >>> list(mock)
1783 ['a', 'b', 'c']
1784 >>> list(mock)
1785 ['a', 'b', 'c']
1786
1787If the return value *is* an iterator, then iterating over it once will consume
1788it and subsequent iterations will result in an empty list:
1789
1790 >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
1791 >>> list(mock)
1792 ['a', 'b', 'c']
1793 >>> list(mock)
1794 []
1795
1796``MagicMock`` has all of the supported magic methods configured except for some
1797of the obscure and obsolete ones. You can still set these up if you want.
1798
1799Magic methods that are supported but not setup by default in ``MagicMock`` are:
1800
1801* ``__subclasses__``
1802* ``__dir__``
1803* ``__format__``
1804* ``__get__``, ``__set__`` and ``__delete__``
1805* ``__reversed__`` and ``__missing__``
1806* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
1807 ``__getstate__`` and ``__setstate__``
1808* ``__getformat__`` and ``__setformat__``
1809
1810
1811
1812.. [#] Magic methods *should* be looked up on the class rather than the
1813 instance. Different versions of Python are inconsistent about applying this
1814 rule. The supported protocol methods should work with all supported versions
1815 of Python.
1816.. [#] The function is basically hooked up to the class, but each ``Mock``
1817 instance is kept isolated from the others.
1818
1819
Michael Foorda9e6fb22012-03-28 14:36:02 +01001820Helpers
Georg Brandlfb134382013-02-03 11:47:49 +01001821-------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001822
1823sentinel
Georg Brandlfb134382013-02-03 11:47:49 +01001824~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001825
1826.. data:: sentinel
1827
Andrés Delfinof85af032018-07-08 21:28:51 -03001828 The ``sentinel`` object provides a convenient way of providing unique
1829 objects for your tests.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001830
Andrés Delfinof85af032018-07-08 21:28:51 -03001831 Attributes are created on demand when you access them by name. Accessing
1832 the same attribute will always return the same object. The objects
1833 returned have a sensible repr so that test failure messages are readable.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001834
Serhiy Storchakad9c956f2017-01-11 20:13:03 +02001835 .. versionchanged:: 3.7
1836 The ``sentinel`` attributes now preserve their identity when they are
1837 :mod:`copied <copy>` or :mod:`pickled <pickle>`.
1838
Michael Foorda9e6fb22012-03-28 14:36:02 +01001839Sometimes when testing you need to test that a specific object is passed as an
1840argument to another method, or returned. It can be common to create named
Georg Brandl7ad3df62014-10-31 07:59:37 +01001841sentinel objects to test this. :data:`sentinel` provides a convenient way of
Michael Foorda9e6fb22012-03-28 14:36:02 +01001842creating and testing the identity of objects like this.
1843
Georg Brandl7ad3df62014-10-31 07:59:37 +01001844In this example we monkey patch ``method`` to return ``sentinel.some_object``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001845
1846 >>> real = ProductionClass()
1847 >>> real.method = Mock(name="method")
1848 >>> real.method.return_value = sentinel.some_object
1849 >>> result = real.method()
1850 >>> assert result is sentinel.some_object
1851 >>> sentinel.some_object
1852 sentinel.some_object
1853
1854
1855DEFAULT
Georg Brandlfb134382013-02-03 11:47:49 +01001856~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001857
1858
1859.. data:: DEFAULT
1860
Georg Brandl7ad3df62014-10-31 07:59:37 +01001861 The :data:`DEFAULT` object is a pre-created sentinel (actually
1862 ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001863 functions to indicate that the normal return value should be used.
1864
1865
Michael Foorda9e6fb22012-03-28 14:36:02 +01001866call
Georg Brandlfb134382013-02-03 11:47:49 +01001867~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001868
1869.. function:: call(*args, **kwargs)
1870
Georg Brandl7ad3df62014-10-31 07:59:37 +01001871 :func:`call` is a helper object for making simpler assertions, for comparing with
Georg Brandl24891672012-04-01 13:48:26 +02001872 :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
Georg Brandl7ad3df62014-10-31 07:59:37 +01001873 :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be
Michael Foorda9e6fb22012-03-28 14:36:02 +01001874 used with :meth:`~Mock.assert_has_calls`.
1875
1876 >>> m = MagicMock(return_value=None)
1877 >>> m(1, 2, a='foo', b='bar')
1878 >>> m()
1879 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
1880 True
1881
1882.. method:: call.call_list()
1883
Georg Brandl7ad3df62014-10-31 07:59:37 +01001884 For a call object that represents multiple calls, :meth:`call_list`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001885 returns a list of all the intermediate calls as well as the
1886 final call.
1887
Georg Brandl7ad3df62014-10-31 07:59:37 +01001888``call_list`` is particularly useful for making assertions on "chained calls". A
Michael Foorda9e6fb22012-03-28 14:36:02 +01001889chained call is multiple calls on a single line of code. This results in
1890multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
1891the sequence of calls can be tedious.
1892
1893:meth:`~call.call_list` can construct the sequence of calls from the same
1894chained call:
1895
1896 >>> m = MagicMock()
1897 >>> m(1).method(arg='foo').other('bar')(2.0)
1898 <MagicMock name='mock().method().other()()' id='...'>
1899 >>> kall = call(1).method(arg='foo').other('bar')(2.0)
1900 >>> kall.call_list()
1901 [call(1),
1902 call().method(arg='foo'),
1903 call().method().other('bar'),
1904 call().method().other()(2.0)]
1905 >>> m.mock_calls == kall.call_list()
1906 True
1907
1908.. _calls-as-tuples:
1909
Georg Brandl7ad3df62014-10-31 07:59:37 +01001910A ``call`` object is either a tuple of (positional args, keyword args) or
Michael Foorda9e6fb22012-03-28 14:36:02 +01001911(name, positional args, keyword args) depending on how it was constructed. When
Georg Brandl7ad3df62014-10-31 07:59:37 +01001912you construct them yourself this isn't particularly interesting, but the ``call``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001913objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
1914:attr:`Mock.mock_calls` attributes can be introspected to get at the individual
1915arguments they contain.
1916
Georg Brandl7ad3df62014-10-31 07:59:37 +01001917The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
1918are two-tuples of (positional args, keyword args) whereas the ``call`` objects
Michael Foorda9e6fb22012-03-28 14:36:02 +01001919in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
1920three-tuples of (name, positional args, keyword args).
1921
1922You can use their "tupleness" to pull out the individual arguments for more
1923complex introspection and assertions. The positional arguments are a tuple
1924(an empty tuple if there are no positional arguments) and the keyword
1925arguments are a dictionary:
1926
1927 >>> m = MagicMock(return_value=None)
1928 >>> m(1, 2, 3, arg='one', arg2='two')
1929 >>> kall = m.call_args
1930 >>> args, kwargs = kall
1931 >>> args
1932 (1, 2, 3)
1933 >>> kwargs
1934 {'arg2': 'two', 'arg': 'one'}
1935 >>> args is kall[0]
1936 True
1937 >>> kwargs is kall[1]
1938 True
1939
1940 >>> m = MagicMock()
1941 >>> m.foo(4, 5, 6, arg='two', arg2='three')
1942 <MagicMock name='mock.foo()' id='...'>
1943 >>> kall = m.mock_calls[0]
1944 >>> name, args, kwargs = kall
1945 >>> name
1946 'foo'
1947 >>> args
1948 (4, 5, 6)
1949 >>> kwargs
1950 {'arg2': 'three', 'arg': 'two'}
1951 >>> name is m.mock_calls[0][0]
1952 True
1953
1954
1955create_autospec
Georg Brandlfb134382013-02-03 11:47:49 +01001956~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001957
1958.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
1959
1960 Create a mock object using another object as a spec. Attributes on the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001961 mock will use the corresponding attribute on the *spec* object as their
Michael Foorda9e6fb22012-03-28 14:36:02 +01001962 spec.
1963
1964 Functions or methods being mocked will have their arguments checked to
1965 ensure that they are called with the correct signature.
1966
Georg Brandl7ad3df62014-10-31 07:59:37 +01001967 If *spec_set* is ``True`` then attempting to set attributes that don't exist
1968 on the spec object will raise an :exc:`AttributeError`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001969
1970 If a class is used as a spec then the return value of the mock (the
1971 instance of the class) will have the same spec. You can use a class as the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001972 spec for an instance object by passing ``instance=True``. The returned mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001973 will only be callable if instances of the mock are callable.
1974
Georg Brandl7ad3df62014-10-31 07:59:37 +01001975 :func:`create_autospec` also takes arbitrary keyword arguments that are passed to
Michael Foorda9e6fb22012-03-28 14:36:02 +01001976 the constructor of the created mock.
1977
1978See :ref:`auto-speccing` for examples of how to use auto-speccing with
Georg Brandl7ad3df62014-10-31 07:59:37 +01001979:func:`create_autospec` and the *autospec* argument to :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001980
1981
1982ANY
Georg Brandlfb134382013-02-03 11:47:49 +01001983~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001984
1985.. data:: ANY
1986
1987Sometimes you may need to make assertions about *some* of the arguments in a
1988call to mock, but either not care about some of the arguments or want to pull
1989them individually out of :attr:`~Mock.call_args` and make more complex
1990assertions on them.
1991
1992To ignore certain arguments you can pass in objects that compare equal to
1993*everything*. Calls to :meth:`~Mock.assert_called_with` and
1994:meth:`~Mock.assert_called_once_with` will then succeed no matter what was
1995passed in.
1996
1997 >>> mock = Mock(return_value=None)
1998 >>> mock('foo', bar=object())
1999 >>> mock.assert_called_once_with('foo', bar=ANY)
2000
Georg Brandl7ad3df62014-10-31 07:59:37 +01002001:data:`ANY` can also be used in comparisons with call lists like
Michael Foorda9e6fb22012-03-28 14:36:02 +01002002:attr:`~Mock.mock_calls`:
2003
2004 >>> m = MagicMock(return_value=None)
2005 >>> m(1)
2006 >>> m(1, 2)
2007 >>> m(object())
2008 >>> m.mock_calls == [call(1), call(1, 2), ANY]
2009 True
2010
2011
2012
2013FILTER_DIR
Georg Brandlfb134382013-02-03 11:47:49 +01002014~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002015
2016.. data:: FILTER_DIR
2017
Georg Brandl7ad3df62014-10-31 07:59:37 +01002018:data:`FILTER_DIR` is a module level variable that controls the way mock objects
2019respond to :func:`dir` (only for Python 2.6 or more recent). The default is ``True``,
Michael Foorda9e6fb22012-03-28 14:36:02 +01002020which uses the filtering described below, to only show useful members. If you
2021dislike this filtering, or need to switch it off for diagnostic purposes, then
Georg Brandl7ad3df62014-10-31 07:59:37 +01002022set ``mock.FILTER_DIR = False``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002023
Georg Brandl7ad3df62014-10-31 07:59:37 +01002024With filtering on, ``dir(some_mock)`` shows only useful attributes and will
Michael Foorda9e6fb22012-03-28 14:36:02 +01002025include any dynamically created attributes that wouldn't normally be shown.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002026If the mock was created with a *spec* (or *autospec* of course) then all the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002027attributes from the original are shown, even if they haven't been accessed
2028yet:
2029
2030 >>> dir(Mock())
2031 ['assert_any_call',
2032 'assert_called_once_with',
2033 'assert_called_with',
2034 'assert_has_calls',
2035 'attach_mock',
2036 ...
2037 >>> from urllib import request
2038 >>> dir(Mock(spec=request))
2039 ['AbstractBasicAuthHandler',
2040 'AbstractDigestAuthHandler',
2041 'AbstractHTTPHandler',
2042 'BaseHandler',
2043 ...
2044
Georg Brandl7ad3df62014-10-31 07:59:37 +01002045Many of the not-very-useful (private to :class:`Mock` rather than the thing being
Michael Foorda9e6fb22012-03-28 14:36:02 +01002046mocked) underscore and double underscore prefixed attributes have been
Georg Brandl7ad3df62014-10-31 07:59:37 +01002047filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this
Michael Foorda9e6fb22012-03-28 14:36:02 +01002048behaviour you can switch it off by setting the module level switch
Georg Brandl7ad3df62014-10-31 07:59:37 +01002049:data:`FILTER_DIR`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002050
2051 >>> from unittest import mock
2052 >>> mock.FILTER_DIR = False
2053 >>> dir(mock.Mock())
2054 ['_NonCallableMock__get_return_value',
2055 '_NonCallableMock__get_side_effect',
2056 '_NonCallableMock__return_value_doc',
2057 '_NonCallableMock__set_return_value',
2058 '_NonCallableMock__set_side_effect',
2059 '__call__',
2060 '__class__',
2061 ...
2062
Georg Brandl7ad3df62014-10-31 07:59:37 +01002063Alternatively you can just use ``vars(my_mock)`` (instance members) and
2064``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of
2065:data:`mock.FILTER_DIR`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002066
2067
2068mock_open
Georg Brandlfb134382013-02-03 11:47:49 +01002069~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002070
2071.. function:: mock_open(mock=None, read_data=None)
2072
Andrés Delfinof85af032018-07-08 21:28:51 -03002073 A helper function to create a mock to replace the use of :func:`open`. It works
2074 for :func:`open` called directly or used as a context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002075
Andrés Delfinof85af032018-07-08 21:28:51 -03002076 The *mock* argument is the mock object to configure. If ``None`` (the
2077 default) then a :class:`MagicMock` will be created for you, with the API limited
2078 to methods or attributes available on standard file handles.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002079
Andrés Delfinof85af032018-07-08 21:28:51 -03002080 *read_data* is a string for the :meth:`~io.IOBase.read`,
2081 :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods
2082 of the file handle to return. Calls to those methods will take data from
2083 *read_data* until it is depleted. The mock of these methods is pretty
2084 simplistic: every time the *mock* is called, the *read_data* is rewound to
2085 the start. If you need more control over the data that you are feeding to
2086 the tested code you will need to customize this mock for yourself. When that
2087 is insufficient, one of the in-memory filesystem packages on `PyPI
2088 <https://pypi.org>`_ can offer a realistic filesystem for testing.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002089
Robert Collinsf79dfe32015-07-24 04:09:59 +12002090 .. versionchanged:: 3.4
2091 Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support.
2092 The mock of :meth:`~io.IOBase.read` changed to consume *read_data* rather
2093 than returning it on each call.
2094
Robert Collins70398392015-07-24 04:10:27 +12002095 .. versionchanged:: 3.5
Robert Collinsf79dfe32015-07-24 04:09:59 +12002096 *read_data* is now reset on each call to the *mock*.
2097
Georg Brandl7ad3df62014-10-31 07:59:37 +01002098Using :func:`open` as a context manager is a great way to ensure your file handles
Michael Foorda9e6fb22012-03-28 14:36:02 +01002099are closed properly and is becoming common::
2100
2101 with open('/some/path', 'w') as f:
2102 f.write('something')
2103
Georg Brandl7ad3df62014-10-31 07:59:37 +01002104The issue is that even if you mock out the call to :func:`open` it is the
2105*returned object* that is used as a context manager (and has :meth:`__enter__` and
2106:meth:`__exit__` called).
Michael Foorda9e6fb22012-03-28 14:36:02 +01002107
2108Mocking context managers with a :class:`MagicMock` is common enough and fiddly
2109enough that a helper function is useful.
2110
2111 >>> m = mock_open()
Michael Foordfddcfa22014-04-14 16:25:20 -04002112 >>> with patch('__main__.open', m):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002113 ... with open('foo', 'w') as h:
2114 ... h.write('some stuff')
2115 ...
2116 >>> m.mock_calls
2117 [call('foo', 'w'),
2118 call().__enter__(),
2119 call().write('some stuff'),
2120 call().__exit__(None, None, None)]
2121 >>> m.assert_called_once_with('foo', 'w')
2122 >>> handle = m()
2123 >>> handle.write.assert_called_once_with('some stuff')
2124
2125And for reading files:
2126
Michael Foordfddcfa22014-04-14 16:25:20 -04002127 >>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002128 ... with open('foo') as h:
2129 ... result = h.read()
2130 ...
2131 >>> m.assert_called_once_with('foo')
2132 >>> assert result == 'bibble'
2133
2134
2135.. _auto-speccing:
2136
2137Autospeccing
Georg Brandlfb134382013-02-03 11:47:49 +01002138~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002139
Georg Brandl7ad3df62014-10-31 07:59:37 +01002140Autospeccing is based on the existing :attr:`spec` feature of mock. It limits the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002141api of mocks to the api of an original object (the spec), but it is recursive
2142(implemented lazily) so that attributes of mocks only have the same api as
2143the attributes of the spec. In addition mocked functions / methods have the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002144same call signature as the original so they raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002145called incorrectly.
2146
2147Before I explain how auto-speccing works, here's why it is needed.
2148
Georg Brandl7ad3df62014-10-31 07:59:37 +01002149:class:`Mock` is a very powerful and flexible object, but it suffers from two flaws
Michael Foorda9e6fb22012-03-28 14:36:02 +01002150when used to mock out objects from a system under test. One of these flaws is
Georg Brandl7ad3df62014-10-31 07:59:37 +01002151specific to the :class:`Mock` api and the other is a more general problem with using
Michael Foorda9e6fb22012-03-28 14:36:02 +01002152mock objects.
2153
Georg Brandl7ad3df62014-10-31 07:59:37 +01002154First the problem specific to :class:`Mock`. :class:`Mock` has two assert methods that are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002155extremely handy: :meth:`~Mock.assert_called_with` and
2156:meth:`~Mock.assert_called_once_with`.
2157
2158 >>> mock = Mock(name='Thing', return_value=None)
2159 >>> mock(1, 2, 3)
2160 >>> mock.assert_called_once_with(1, 2, 3)
2161 >>> mock(1, 2, 3)
2162 >>> mock.assert_called_once_with(1, 2, 3)
2163 Traceback (most recent call last):
2164 ...
Michael Foord28d591c2012-09-28 16:15:22 +01002165 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002166
2167Because mocks auto-create attributes on demand, and allow you to call them
2168with arbitrary arguments, if you misspell one of these assert methods then
2169your assertion is gone:
2170
2171.. code-block:: pycon
2172
2173 >>> mock = Mock(name='Thing', return_value=None)
2174 >>> mock(1, 2, 3)
2175 >>> mock.assret_called_once_with(4, 5, 6)
2176
2177Your tests can pass silently and incorrectly because of the typo.
2178
2179The second issue is more general to mocking. If you refactor some of your
2180code, rename members and so on, any tests for code that is still using the
2181*old api* but uses mocks instead of the real objects will still pass. This
2182means your tests can all pass even though your code is broken.
2183
2184Note that this is another reason why you need integration tests as well as
2185unit tests. Testing everything in isolation is all fine and dandy, but if you
2186don't test how your units are "wired together" there is still lots of room
2187for bugs that tests might have caught.
2188
Georg Brandl7ad3df62014-10-31 07:59:37 +01002189:mod:`mock` already provides a feature to help with this, called speccing. If you
2190use a class or instance as the :attr:`spec` for a mock then you can only access
Michael Foorda9e6fb22012-03-28 14:36:02 +01002191attributes on the mock that exist on the real class:
2192
2193 >>> from urllib import request
2194 >>> mock = Mock(spec=request.Request)
2195 >>> mock.assret_called_with
2196 Traceback (most recent call last):
2197 ...
2198 AttributeError: Mock object has no attribute 'assret_called_with'
2199
2200The spec only applies to the mock itself, so we still have the same issue
2201with any methods on the mock:
2202
2203.. code-block:: pycon
2204
2205 >>> mock.has_data()
2206 <mock.Mock object at 0x...>
2207 >>> mock.has_data.assret_called_with()
2208
Georg Brandl7ad3df62014-10-31 07:59:37 +01002209Auto-speccing solves this problem. You can either pass ``autospec=True`` to
2210:func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a
2211mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002212object that is being replaced will be used as the spec object. Because the
2213speccing is done "lazily" (the spec is created as attributes on the mock are
2214accessed) you can use it with very complex or deeply nested objects (like
2215modules that import modules that import modules) without a big performance
2216hit.
2217
2218Here's an example of it in use:
2219
2220 >>> from urllib import request
2221 >>> patcher = patch('__main__.request', autospec=True)
2222 >>> mock_request = patcher.start()
2223 >>> request is mock_request
2224 True
2225 >>> mock_request.Request
2226 <MagicMock name='request.Request' spec='Request' id='...'>
2227
Georg Brandl7ad3df62014-10-31 07:59:37 +01002228You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two
2229arguments in the constructor (one of which is *self*). Here's what happens if
Michael Foorda9e6fb22012-03-28 14:36:02 +01002230we try to call it incorrectly:
2231
2232 >>> req = request.Request()
2233 Traceback (most recent call last):
2234 ...
2235 TypeError: <lambda>() takes at least 2 arguments (1 given)
2236
2237The spec also applies to instantiated classes (i.e. the return value of
2238specced mocks):
2239
2240 >>> req = request.Request('foo')
2241 >>> req
2242 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
2243
Georg Brandl7ad3df62014-10-31 07:59:37 +01002244:class:`Request` objects are not callable, so the return value of instantiating our
2245mocked out :class:`request.Request` is a non-callable mock. With the spec in place
Michael Foorda9e6fb22012-03-28 14:36:02 +01002246any typos in our asserts will raise the correct error:
2247
2248 >>> req.add_header('spam', 'eggs')
2249 <MagicMock name='request.Request().add_header()' id='...'>
2250 >>> req.add_header.assret_called_with
2251 Traceback (most recent call last):
2252 ...
2253 AttributeError: Mock object has no attribute 'assret_called_with'
2254 >>> req.add_header.assert_called_with('spam', 'eggs')
2255
Georg Brandl7ad3df62014-10-31 07:59:37 +01002256In many cases you will just be able to add ``autospec=True`` to your existing
2257:func:`patch` calls and then be protected against bugs due to typos and api
Michael Foorda9e6fb22012-03-28 14:36:02 +01002258changes.
2259
Georg Brandl7ad3df62014-10-31 07:59:37 +01002260As well as using *autospec* through :func:`patch` there is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002261:func:`create_autospec` for creating autospecced mocks directly:
2262
2263 >>> from urllib import request
2264 >>> mock_request = create_autospec(request)
2265 >>> mock_request.Request('foo', 'bar')
2266 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
2267
2268This isn't without caveats and limitations however, which is why it is not
2269the default behaviour. In order to know what attributes are available on the
2270spec object, autospec has to introspect (access attributes) the spec. As you
2271traverse attributes on the mock a corresponding traversal of the original
2272object is happening under the hood. If any of your specced objects have
2273properties or descriptors that can trigger code execution then you may not be
2274able to use autospec. On the other hand it is much better to design your
2275objects so that introspection is safe [#]_.
2276
2277A more serious problem is that it is common for instance attributes to be
Georg Brandl7ad3df62014-10-31 07:59:37 +01002278created in the :meth:`__init__` method and not to exist on the class at all.
2279*autospec* can't know about any dynamically created attributes and restricts
Michael Foorda9e6fb22012-03-28 14:36:02 +01002280the api to visible attributes.
2281
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002282 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002283 ... def __init__(self):
2284 ... self.a = 33
2285 ...
2286 >>> with patch('__main__.Something', autospec=True):
2287 ... thing = Something()
2288 ... thing.a
2289 ...
2290 Traceback (most recent call last):
2291 ...
2292 AttributeError: Mock object has no attribute 'a'
2293
2294There are a few different ways of resolving this problem. The easiest, but
2295not necessarily the least annoying, way is to simply set the required
Georg Brandl7ad3df62014-10-31 07:59:37 +01002296attributes on the mock after creation. Just because *autospec* doesn't allow
Michael Foorda9e6fb22012-03-28 14:36:02 +01002297you to fetch attributes that don't exist on the spec it doesn't prevent you
2298setting them:
2299
2300 >>> with patch('__main__.Something', autospec=True):
2301 ... thing = Something()
2302 ... thing.a = 33
2303 ...
2304
Georg Brandl7ad3df62014-10-31 07:59:37 +01002305There is a more aggressive version of both *spec* and *autospec* that *does*
Michael Foorda9e6fb22012-03-28 14:36:02 +01002306prevent you setting non-existent attributes. This is useful if you want to
2307ensure your code only *sets* valid attributes too, but obviously it prevents
2308this particular scenario:
2309
2310 >>> with patch('__main__.Something', autospec=True, spec_set=True):
2311 ... thing = Something()
2312 ... thing.a = 33
2313 ...
2314 Traceback (most recent call last):
2315 ...
2316 AttributeError: Mock object has no attribute 'a'
2317
2318Probably the best way of solving the problem is to add class attributes as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002319default values for instance members initialised in :meth:`__init__`. Note that if
2320you are only setting default attributes in :meth:`__init__` then providing them via
Michael Foorda9e6fb22012-03-28 14:36:02 +01002321class attributes (shared between instances of course) is faster too. e.g.
2322
2323.. code-block:: python
2324
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002325 class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002326 a = 33
2327
2328This brings up another issue. It is relatively common to provide a default
Georg Brandl7ad3df62014-10-31 07:59:37 +01002329value of ``None`` for members that will later be an object of a different type.
2330``None`` would be useless as a spec because it wouldn't let you access *any*
2331attributes or methods on it. As ``None`` is *never* going to be useful as a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002332spec, and probably indicates a member that will normally of some other type,
Georg Brandl7ad3df62014-10-31 07:59:37 +01002333autospec doesn't use a spec for members that are set to ``None``. These will
2334just be ordinary mocks (well - MagicMocks):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002335
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002336 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002337 ... member = None
2338 ...
2339 >>> mock = create_autospec(Something)
2340 >>> mock.member.foo.bar.baz()
2341 <MagicMock name='mock.member.foo.bar.baz()' id='...'>
2342
2343If modifying your production classes to add defaults isn't to your liking
2344then there are more options. One of these is simply to use an instance as the
2345spec rather than the class. The other is to create a subclass of the
2346production class and add the defaults to the subclass without affecting the
2347production class. Both of these require you to use an alternative object as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002348the spec. Thankfully :func:`patch` supports this - you can simply pass the
2349alternative object as the *autospec* argument:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002350
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002351 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002352 ... def __init__(self):
2353 ... self.a = 33
2354 ...
2355 >>> class SomethingForTest(Something):
2356 ... a = 33
2357 ...
2358 >>> p = patch('__main__.Something', autospec=SomethingForTest)
2359 >>> mock = p.start()
2360 >>> mock.a
2361 <NonCallableMagicMock name='Something.a' spec='int' id='...'>
2362
2363
2364.. [#] This only applies to classes or already instantiated objects. Calling
2365 a mocked class to create a mock instance *does not* create a real instance.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002366 It is only attribute lookups - along with calls to :func:`dir` - that are done.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002367
Mario Corchero552be9d2017-10-17 12:35:11 +01002368Sealing mocks
2369~~~~~~~~~~~~~
2370
2371.. function:: seal(mock)
2372
Paul Ganssle85ac7262018-01-06 08:25:34 -05002373 Seal will disable the creation of mock children by preventing getting or setting
2374 of any new attribute on the sealed mock. The sealing process is performed recursively.
Mario Corchero552be9d2017-10-17 12:35:11 +01002375
2376 If a mock instance is assigned to an attribute instead of being dynamically created
Paul Ganssle85ac7262018-01-06 08:25:34 -05002377 it won't be considered in the sealing chain. This allows one to prevent seal from
2378 fixing part of the mock object.
Mario Corchero552be9d2017-10-17 12:35:11 +01002379
2380 >>> mock = Mock()
2381 >>> mock.submock.attribute1 = 2
2382 >>> mock.not_submock = mock.Mock()
2383 >>> seal(mock)
2384 >>> mock.submock.attribute2 # This will raise AttributeError.
2385 >>> mock.not_submock.attribute2 # This won't raise.
2386
2387 .. versionadded:: 3.7