blob: f1b25958a670f4f1554b72484ef9707966141bd6 [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,
Miss Islington (bot)51b2f6d2018-05-16 07:05:46 -070038available 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
Miss Islington (bot)b2ecb8b2018-09-14 12:15:10 -0700101 function in the same order they applied (the normal *Python* order that
Michael Foord944e02d2012-03-25 23:12:55 +0100102 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
Miss Islington (bot)e8f9e472018-12-03 13:54:44 -0800683 .. note::
684
685 The way :attr:`mock_calls` are recorded means that where nested
686 calls are made, the parameters of ancestor calls are not recorded
687 and so will always compare equal:
688
689 >>> mock = MagicMock()
690 >>> mock.top(a=3).bottom()
691 <MagicMock name='mock.top().bottom()' id='...'>
692 >>> mock.mock_calls
693 [call.top(a=3), call.top().bottom()]
694 >>> mock.mock_calls[-1] == call.top(a=-1).bottom()
695 True
Michael Foord944e02d2012-03-25 23:12:55 +0100696
697 .. attribute:: __class__
698
Georg Brandl7ad3df62014-10-31 07:59:37 +0100699 Normally the :attr:`__class__` attribute of an object will return its type.
700 For a mock object with a :attr:`spec`, ``__class__`` returns the spec class
701 instead. This allows mock objects to pass :func:`isinstance` tests for the
Michael Foord944e02d2012-03-25 23:12:55 +0100702 object they are replacing / masquerading as:
703
704 >>> mock = Mock(spec=3)
705 >>> isinstance(mock, int)
706 True
707
Georg Brandl7ad3df62014-10-31 07:59:37 +0100708 :attr:`__class__` is assignable to, this allows a mock to pass an
709 :func:`isinstance` check without forcing you to use a spec:
Michael Foord944e02d2012-03-25 23:12:55 +0100710
711 >>> mock = Mock()
712 >>> mock.__class__ = dict
713 >>> isinstance(mock, dict)
714 True
715
716.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
717
Georg Brandl7ad3df62014-10-31 07:59:37 +0100718 A non-callable version of :class:`Mock`. The constructor parameters have the same
719 meaning of :class:`Mock`, with the exception of *return_value* and *side_effect*
Michael Foord944e02d2012-03-25 23:12:55 +0100720 which have no meaning on a non-callable mock.
721
Georg Brandl7ad3df62014-10-31 07:59:37 +0100722Mock objects that use a class or an instance as a :attr:`spec` or
723:attr:`spec_set` are able to pass :func:`isinstance` tests:
Michael Foord944e02d2012-03-25 23:12:55 +0100724
725 >>> mock = Mock(spec=SomeClass)
726 >>> isinstance(mock, SomeClass)
727 True
728 >>> mock = Mock(spec_set=SomeClass())
729 >>> isinstance(mock, SomeClass)
730 True
731
Georg Brandl7ad3df62014-10-31 07:59:37 +0100732The :class:`Mock` classes have support for mocking magic methods. See :ref:`magic
Michael Foord944e02d2012-03-25 23:12:55 +0100733methods <magic-methods>` for the full details.
734
735The mock classes and the :func:`patch` decorators all take arbitrary keyword
Georg Brandl7ad3df62014-10-31 07:59:37 +0100736arguments for configuration. For the :func:`patch` decorators the keywords are
Michael Foord944e02d2012-03-25 23:12:55 +0100737passed to the constructor of the mock being created. The keyword arguments
738are for configuring attributes of the mock:
739
740 >>> m = MagicMock(attribute=3, other='fish')
741 >>> m.attribute
742 3
743 >>> m.other
744 'fish'
745
746The return value and side effect of child mocks can be set in the same way,
747using dotted notation. As you can't use dotted names directly in a call you
Georg Brandl7ad3df62014-10-31 07:59:37 +0100748have to create a dictionary and unpack it using ``**``:
Michael Foord944e02d2012-03-25 23:12:55 +0100749
750 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
751 >>> mock = Mock(some_attribute='eggs', **attrs)
752 >>> mock.some_attribute
753 'eggs'
754 >>> mock.method()
755 3
756 >>> mock.other()
757 Traceback (most recent call last):
758 ...
759 KeyError
760
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100761A callable mock which was created with a *spec* (or a *spec_set*) will
762introspect the specification object's signature when matching calls to
763the mock. Therefore, it can match the actual call's arguments regardless
764of whether they were passed positionally or by name::
765
766 >>> def f(a, b, c): pass
767 ...
768 >>> mock = Mock(spec=f)
769 >>> mock(1, 2, c=3)
770 <Mock name='mock()' id='140161580456576'>
771 >>> mock.assert_called_with(1, 2, 3)
772 >>> mock.assert_called_with(a=1, b=2, c=3)
773
774This applies to :meth:`~Mock.assert_called_with`,
775:meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and
776:meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also
777apply to method calls on the mock object.
778
779 .. versionchanged:: 3.4
780 Added signature introspection on specced and autospecced mock objects.
781
Michael Foord944e02d2012-03-25 23:12:55 +0100782
783.. class:: PropertyMock(*args, **kwargs)
784
785 A mock intended to be used as a property, or other descriptor, on a class.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100786 :class:`PropertyMock` provides :meth:`__get__` and :meth:`__set__` methods
787 so you can specify a return value when it is fetched.
Michael Foord944e02d2012-03-25 23:12:55 +0100788
Georg Brandl7ad3df62014-10-31 07:59:37 +0100789 Fetching a :class:`PropertyMock` instance from an object calls the mock, with
Michael Foord944e02d2012-03-25 23:12:55 +0100790 no args. Setting it calls the mock with the value being set.
791
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200792 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100793 ... @property
794 ... def foo(self):
795 ... return 'something'
796 ... @foo.setter
797 ... def foo(self, value):
798 ... pass
799 ...
800 >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
801 ... mock_foo.return_value = 'mockity-mock'
802 ... this_foo = Foo()
Berker Peksag920f6db2015-09-10 21:41:15 +0300803 ... print(this_foo.foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100804 ... this_foo.foo = 6
805 ...
806 mockity-mock
807 >>> mock_foo.mock_calls
808 [call(), call(6)]
809
Michael Foordc2870622012-04-13 16:57:22 +0100810Because of the way mock attributes are stored you can't directly attach a
Georg Brandl7ad3df62014-10-31 07:59:37 +0100811:class:`PropertyMock` to a mock object. Instead you can attach it to the mock type
Michael Foordc2870622012-04-13 16:57:22 +0100812object::
813
814 >>> m = MagicMock()
815 >>> p = PropertyMock(return_value=3)
816 >>> type(m).foo = p
817 >>> m.foo
818 3
819 >>> p.assert_called_once_with()
820
Michael Foord944e02d2012-03-25 23:12:55 +0100821
822Calling
823~~~~~~~
824
825Mock objects are callable. The call will return the value set as the
826:attr:`~Mock.return_value` attribute. The default return value is a new Mock
827object; it is created the first time the return value is accessed (either
828explicitly or by calling the Mock) - but it is stored and the same one
829returned each time.
830
831Calls made to the object will be recorded in the attributes
832like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
833
834If :attr:`~Mock.side_effect` is set then it will be called after the call has
Georg Brandl7ad3df62014-10-31 07:59:37 +0100835been recorded, so if :attr:`side_effect` raises an exception the call is still
Michael Foord944e02d2012-03-25 23:12:55 +0100836recorded.
837
838The simplest way to make a mock raise an exception when called is to make
839:attr:`~Mock.side_effect` an exception class or instance:
840
841 >>> m = MagicMock(side_effect=IndexError)
842 >>> m(1, 2, 3)
843 Traceback (most recent call last):
844 ...
845 IndexError
846 >>> m.mock_calls
847 [call(1, 2, 3)]
848 >>> m.side_effect = KeyError('Bang!')
849 >>> m('two', 'three', 'four')
850 Traceback (most recent call last):
851 ...
852 KeyError: 'Bang!'
853 >>> m.mock_calls
854 [call(1, 2, 3), call('two', 'three', 'four')]
855
Georg Brandl7ad3df62014-10-31 07:59:37 +0100856If :attr:`side_effect` is a function then whatever that function returns is what
857calls to the mock return. The :attr:`side_effect` function is called with the
Michael Foord944e02d2012-03-25 23:12:55 +0100858same arguments as the mock. This allows you to vary the return value of the
859call dynamically, based on the input:
860
861 >>> def side_effect(value):
862 ... return value + 1
863 ...
864 >>> m = MagicMock(side_effect=side_effect)
865 >>> m(1)
866 2
867 >>> m(2)
868 3
869 >>> m.mock_calls
870 [call(1), call(2)]
871
872If you want the mock to still return the default return value (a new mock), or
873any set return value, then there are two ways of doing this. Either return
Georg Brandl7ad3df62014-10-31 07:59:37 +0100874:attr:`mock.return_value` from inside :attr:`side_effect`, or return :data:`DEFAULT`:
Michael Foord944e02d2012-03-25 23:12:55 +0100875
876 >>> m = MagicMock()
877 >>> def side_effect(*args, **kwargs):
878 ... return m.return_value
879 ...
880 >>> m.side_effect = side_effect
881 >>> m.return_value = 3
882 >>> m()
883 3
884 >>> def side_effect(*args, **kwargs):
885 ... return DEFAULT
886 ...
887 >>> m.side_effect = side_effect
888 >>> m()
889 3
890
Georg Brandl7ad3df62014-10-31 07:59:37 +0100891To remove a :attr:`side_effect`, and return to the default behaviour, set the
892:attr:`side_effect` to ``None``:
Michael Foord944e02d2012-03-25 23:12:55 +0100893
894 >>> m = MagicMock(return_value=6)
895 >>> def side_effect(*args, **kwargs):
896 ... return 3
897 ...
898 >>> m.side_effect = side_effect
899 >>> m()
900 3
901 >>> m.side_effect = None
902 >>> m()
903 6
904
Georg Brandl7ad3df62014-10-31 07:59:37 +0100905The :attr:`side_effect` can also be any iterable object. Repeated calls to the mock
Michael Foord944e02d2012-03-25 23:12:55 +0100906will return values from the iterable (until the iterable is exhausted and
Georg Brandl7ad3df62014-10-31 07:59:37 +0100907a :exc:`StopIteration` is raised):
Michael Foord944e02d2012-03-25 23:12:55 +0100908
909 >>> m = MagicMock(side_effect=[1, 2, 3])
910 >>> m()
911 1
912 >>> m()
913 2
914 >>> m()
915 3
916 >>> m()
917 Traceback (most recent call last):
918 ...
919 StopIteration
920
Michael Foord2cd48732012-04-21 15:52:11 +0100921If any members of the iterable are exceptions they will be raised instead of
922returned::
923
924 >>> iterable = (33, ValueError, 66)
925 >>> m = MagicMock(side_effect=iterable)
926 >>> m()
927 33
928 >>> m()
929 Traceback (most recent call last):
930 ...
931 ValueError
932 >>> m()
933 66
934
Michael Foord944e02d2012-03-25 23:12:55 +0100935
936.. _deleting-attributes:
937
938Deleting Attributes
939~~~~~~~~~~~~~~~~~~~
940
941Mock objects create attributes on demand. This allows them to pretend to be
942objects of any type.
943
Georg Brandl7ad3df62014-10-31 07:59:37 +0100944You may want a mock object to return ``False`` to a :func:`hasattr` call, or raise an
945:exc:`AttributeError` when an attribute is fetched. You can do this by providing
946an object as a :attr:`spec` for a mock, but that isn't always convenient.
Michael Foord944e02d2012-03-25 23:12:55 +0100947
948You "block" attributes by deleting them. Once deleted, accessing an attribute
Georg Brandl7ad3df62014-10-31 07:59:37 +0100949will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100950
951 >>> mock = MagicMock()
952 >>> hasattr(mock, 'm')
953 True
954 >>> del mock.m
955 >>> hasattr(mock, 'm')
956 False
957 >>> del mock.f
958 >>> mock.f
959 Traceback (most recent call last):
960 ...
961 AttributeError: f
962
963
Michael Foordf5752302013-03-18 15:04:03 -0700964Mock names and the name attribute
965~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
966
967Since "name" is an argument to the :class:`Mock` constructor, if you want your
968mock object to have a "name" attribute you can't just pass it in at creation
969time. There are two alternatives. One option is to use
970:meth:`~Mock.configure_mock`::
971
972 >>> mock = MagicMock()
973 >>> mock.configure_mock(name='my_name')
974 >>> mock.name
975 'my_name'
976
977A simpler option is to simply set the "name" attribute after mock creation::
978
979 >>> mock = MagicMock()
980 >>> mock.name = "foo"
981
982
Michael Foord944e02d2012-03-25 23:12:55 +0100983Attaching Mocks as Attributes
984~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
985
986When you attach a mock as an attribute of another mock (or as the return
987value) it becomes a "child" of that mock. Calls to the child are recorded in
988the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
989parent. This is useful for configuring child mocks and then attaching them to
990the parent, or for attaching mocks to a parent that records all calls to the
991children and allows you to make assertions about the order of calls between
992mocks:
993
994 >>> parent = MagicMock()
995 >>> child1 = MagicMock(return_value=None)
996 >>> child2 = MagicMock(return_value=None)
997 >>> parent.child1 = child1
998 >>> parent.child2 = child2
999 >>> child1(1)
1000 >>> child2(2)
1001 >>> parent.mock_calls
1002 [call.child1(1), call.child2(2)]
1003
1004The exception to this is if the mock has a name. This allows you to prevent
1005the "parenting" if for some reason you don't want it to happen.
1006
1007 >>> mock = MagicMock()
1008 >>> not_a_child = MagicMock(name='not-a-child')
1009 >>> mock.attribute = not_a_child
1010 >>> mock.attribute()
1011 <MagicMock name='not-a-child()' id='...'>
1012 >>> mock.mock_calls
1013 []
1014
1015Mocks created for you by :func:`patch` are automatically given names. To
1016attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
1017method:
1018
1019 >>> thing1 = object()
1020 >>> thing2 = object()
1021 >>> parent = MagicMock()
1022 >>> with patch('__main__.thing1', return_value=None) as child1:
1023 ... with patch('__main__.thing2', return_value=None) as child2:
1024 ... parent.attach_mock(child1, 'child1')
1025 ... parent.attach_mock(child2, 'child2')
1026 ... child1('one')
1027 ... child2('two')
1028 ...
1029 >>> parent.mock_calls
1030 [call.child1('one'), call.child2('two')]
1031
1032
1033.. [#] The only exceptions are magic methods and attributes (those that have
1034 leading and trailing double underscores). Mock doesn't create these but
Georg Brandl7ad3df62014-10-31 07:59:37 +01001035 instead raises an :exc:`AttributeError`. This is because the interpreter
Michael Foord944e02d2012-03-25 23:12:55 +01001036 will often implicitly request these methods, and gets *very* confused to
1037 get a new Mock object when it expects a magic method. If you need magic
1038 method support see :ref:`magic methods <magic-methods>`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001039
1040
1041The patchers
Georg Brandlfb134382013-02-03 11:47:49 +01001042------------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001043
1044The patch decorators are used for patching objects only within the scope of
1045the function they decorate. They automatically handle the unpatching for you,
1046even if exceptions are raised. All of these functions can also be used in with
1047statements or as class decorators.
1048
1049
1050patch
Georg Brandlfb134382013-02-03 11:47:49 +01001051~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001052
1053.. note::
1054
Georg Brandl7ad3df62014-10-31 07:59:37 +01001055 :func:`patch` is straightforward to use. The key is to do the patching in the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001056 right namespace. See the section `where to patch`_.
1057
1058.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1059
Georg Brandl7ad3df62014-10-31 07:59:37 +01001060 :func:`patch` acts as a function decorator, class decorator or a context
1061 manager. Inside the body of the function or with statement, the *target*
1062 is patched with a *new* object. When the function/with statement exits
Michael Foord54b3db82012-03-28 15:08:08 +01001063 the patch is undone.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001064
Georg Brandl7ad3df62014-10-31 07:59:37 +01001065 If *new* is omitted, then the target is replaced with a
1066 :class:`MagicMock`. If :func:`patch` is used as a decorator and *new* is
Michael Foord54b3db82012-03-28 15:08:08 +01001067 omitted, the created mock is passed in as an extra argument to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001068 decorated function. If :func:`patch` is used as a context manager the created
Michael Foord54b3db82012-03-28 15:08:08 +01001069 mock is returned by the context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001070
Georg Brandl7ad3df62014-10-31 07:59:37 +01001071 *target* should be a string in the form ``'package.module.ClassName'``. The
1072 *target* is imported and the specified object replaced with the *new*
1073 object, so the *target* must be importable from the environment you are
1074 calling :func:`patch` from. The target is imported when the decorated function
Michael Foord54b3db82012-03-28 15:08:08 +01001075 is executed, not at decoration time.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001076
Georg Brandl7ad3df62014-10-31 07:59:37 +01001077 The *spec* and *spec_set* keyword arguments are passed to the :class:`MagicMock`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001078 if patch is creating one for you.
1079
Georg Brandl7ad3df62014-10-31 07:59:37 +01001080 In addition you can pass ``spec=True`` or ``spec_set=True``, which causes
Michael Foorda9e6fb22012-03-28 14:36:02 +01001081 patch to pass in the object being mocked as the spec/spec_set object.
1082
Georg Brandl7ad3df62014-10-31 07:59:37 +01001083 *new_callable* allows you to specify a different class, or callable object,
1084 that will be called to create the *new* object. By default :class:`MagicMock` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001085 used.
1086
Georg Brandl7ad3df62014-10-31 07:59:37 +01001087 A more powerful form of *spec* is *autospec*. If you set ``autospec=True``
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001088 then the mock will be created with a spec from the object being replaced.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001089 All attributes of the mock will also have the spec of the corresponding
1090 attribute of the object being replaced. Methods and functions being mocked
Georg Brandl7ad3df62014-10-31 07:59:37 +01001091 will have their arguments checked and will raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001092 called with the wrong signature. For mocks
1093 replacing a class, their return value (the 'instance') will have the same
1094 spec as the class. See the :func:`create_autospec` function and
1095 :ref:`auto-speccing`.
1096
Georg Brandl7ad3df62014-10-31 07:59:37 +01001097 Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001098 arbitrary object as the spec instead of the one being replaced.
1099
Georg Brandl7ad3df62014-10-31 07:59:37 +01001100 By default :func:`patch` will fail to replace attributes that don't exist. If
1101 you pass in ``create=True``, and the attribute doesn't exist, patch will
Michael Foorda9e6fb22012-03-28 14:36:02 +01001102 create the attribute for you when the patched function is called, and
1103 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001104 attributes that your production code creates at runtime. It is off by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001105 default because it can be dangerous. With it switched on you can write
1106 passing tests against APIs that don't actually exist!
1107
Michael Foordfddcfa22014-04-14 16:25:20 -04001108 .. note::
1109
1110 .. versionchanged:: 3.5
1111 If you are patching builtins in a module then you don't
Georg Brandl7ad3df62014-10-31 07:59:37 +01001112 need to pass ``create=True``, it will be added by default.
Michael Foordfddcfa22014-04-14 16:25:20 -04001113
Georg Brandl7ad3df62014-10-31 07:59:37 +01001114 Patch can be used as a :class:`TestCase` class decorator. It works by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001115 decorating each test method in the class. This reduces the boilerplate
Georg Brandl7ad3df62014-10-31 07:59:37 +01001116 code when your test methods share a common patchings set. :func:`patch` finds
1117 tests by looking for method names that start with ``patch.TEST_PREFIX``.
1118 By default this is ``'test'``, which matches the way :mod:`unittest` finds tests.
1119 You can specify an alternative prefix by setting ``patch.TEST_PREFIX``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001120
1121 Patch can be used as a context manager, with the with statement. Here the
1122 patching applies to the indented block after the with statement. If you
1123 use "as" then the patched object will be bound to the name after the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001124 "as"; very useful if :func:`patch` is creating a mock object for you.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001125
Georg Brandl7ad3df62014-10-31 07:59:37 +01001126 :func:`patch` takes arbitrary keyword arguments. These will be passed to
1127 the :class:`Mock` (or *new_callable*) on construction.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001128
Georg Brandl7ad3df62014-10-31 07:59:37 +01001129 ``patch.dict(...)``, ``patch.multiple(...)`` and ``patch.object(...)`` are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001130 available for alternate use-cases.
1131
Georg Brandl7ad3df62014-10-31 07:59:37 +01001132:func:`patch` as function decorator, creating the mock for you and passing it into
Michael Foord90155362012-03-28 15:32:08 +01001133the decorated function:
1134
1135 >>> @patch('__main__.SomeClass')
Michael Foord324b58b2012-03-28 15:49:08 +01001136 ... def function(normal_argument, mock_class):
Michael Foord90155362012-03-28 15:32:08 +01001137 ... print(mock_class is SomeClass)
1138 ...
Michael Foord324b58b2012-03-28 15:49:08 +01001139 >>> function(None)
Michael Foord90155362012-03-28 15:32:08 +01001140 True
Michael Foorda9e6fb22012-03-28 14:36:02 +01001141
Georg Brandl7ad3df62014-10-31 07:59:37 +01001142Patching a class replaces the class with a :class:`MagicMock` *instance*. If the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001143class is instantiated in the code under test then it will be the
1144:attr:`~Mock.return_value` of the mock that will be used.
1145
1146If the class is instantiated multiple times you could use
1147:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
Georg Brandl7ad3df62014-10-31 07:59:37 +01001148can set the *return_value* to be anything you want.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001149
1150To configure return values on methods of *instances* on the patched class
Georg Brandl7ad3df62014-10-31 07:59:37 +01001151you must do this on the :attr:`return_value`. For example:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001152
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001153 >>> class Class:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001154 ... def method(self):
1155 ... pass
1156 ...
1157 >>> with patch('__main__.Class') as MockClass:
1158 ... instance = MockClass.return_value
1159 ... instance.method.return_value = 'foo'
1160 ... assert Class() is instance
1161 ... assert Class().method() == 'foo'
1162 ...
1163
Georg Brandl7ad3df62014-10-31 07:59:37 +01001164If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001165return value of the created mock will have the same spec.
1166
1167 >>> Original = Class
1168 >>> patcher = patch('__main__.Class', spec=True)
1169 >>> MockClass = patcher.start()
1170 >>> instance = MockClass()
1171 >>> assert isinstance(instance, Original)
1172 >>> patcher.stop()
1173
Georg Brandl7ad3df62014-10-31 07:59:37 +01001174The *new_callable* argument is useful where you want to use an alternative
Michael Foorda9e6fb22012-03-28 14:36:02 +01001175class to the default :class:`MagicMock` for the created mock. For example, if
1176you wanted a :class:`NonCallableMock` to be used:
1177
1178 >>> thing = object()
1179 >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
1180 ... assert thing is mock_thing
1181 ... thing()
1182 ...
1183 Traceback (most recent call last):
1184 ...
1185 TypeError: 'NonCallableMock' object is not callable
1186
Martin Panter7462b6492015-11-02 03:37:02 +00001187Another use case might be to replace an object with an :class:`io.StringIO` instance:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001188
Serhiy Storchakae79be872013-08-17 00:09:55 +03001189 >>> from io import StringIO
Michael Foorda9e6fb22012-03-28 14:36:02 +01001190 >>> def foo():
Berker Peksag920f6db2015-09-10 21:41:15 +03001191 ... print('Something')
Michael Foorda9e6fb22012-03-28 14:36:02 +01001192 ...
1193 >>> @patch('sys.stdout', new_callable=StringIO)
1194 ... def test(mock_stdout):
1195 ... foo()
1196 ... assert mock_stdout.getvalue() == 'Something\n'
1197 ...
1198 >>> test()
1199
Georg Brandl7ad3df62014-10-31 07:59:37 +01001200When :func:`patch` is creating a mock for you, it is common that the first thing
Michael Foorda9e6fb22012-03-28 14:36:02 +01001201you need to do is to configure the mock. Some of that configuration can be done
1202in the call to patch. Any arbitrary keywords you pass into the call will be
1203used to set attributes on the created mock:
1204
1205 >>> patcher = patch('__main__.thing', first='one', second='two')
1206 >>> mock_thing = patcher.start()
1207 >>> mock_thing.first
1208 'one'
1209 >>> mock_thing.second
1210 'two'
1211
1212As well as attributes on the created mock attributes, like the
1213:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
1214also be configured. These aren't syntactically valid to pass in directly as
1215keyword arguments, but a dictionary with these as keys can still be expanded
Georg Brandl7ad3df62014-10-31 07:59:37 +01001216into a :func:`patch` call using ``**``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001217
1218 >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
1219 >>> patcher = patch('__main__.thing', **config)
1220 >>> mock_thing = patcher.start()
1221 >>> mock_thing.method()
1222 3
1223 >>> mock_thing.other()
1224 Traceback (most recent call last):
1225 ...
1226 KeyError
1227
1228
1229patch.object
Georg Brandlfb134382013-02-03 11:47:49 +01001230~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001231
1232.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1233
Georg Brandl7ad3df62014-10-31 07:59:37 +01001234 patch the named member (*attribute*) on an object (*target*) with a mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001235 object.
1236
Georg Brandl7ad3df62014-10-31 07:59:37 +01001237 :func:`patch.object` can be used as a decorator, class decorator or a context
1238 manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* and
1239 *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`,
1240 :func:`patch.object` takes arbitrary keyword arguments for configuring the mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001241 object it creates.
1242
Georg Brandl7ad3df62014-10-31 07:59:37 +01001243 When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001244 for choosing which methods to wrap.
1245
Georg Brandl7ad3df62014-10-31 07:59:37 +01001246You can either call :func:`patch.object` with three arguments or two arguments. The
Michael Foorda9e6fb22012-03-28 14:36:02 +01001247three argument form takes the object to be patched, the attribute name and the
1248object to replace the attribute with.
1249
1250When calling with the two argument form you omit the replacement object, and a
1251mock is created for you and passed in as an extra argument to the decorated
1252function:
1253
1254 >>> @patch.object(SomeClass, 'class_method')
1255 ... def test(mock_method):
1256 ... SomeClass.class_method(3)
1257 ... mock_method.assert_called_with(3)
1258 ...
1259 >>> test()
1260
Georg Brandl7ad3df62014-10-31 07:59:37 +01001261*spec*, *create* and the other arguments to :func:`patch.object` have the same
1262meaning as they do for :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001263
1264
1265patch.dict
Georg Brandlfb134382013-02-03 11:47:49 +01001266~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001267
1268.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs)
1269
1270 Patch a dictionary, or dictionary like object, and restore the dictionary
1271 to its original state after the test.
1272
Georg Brandl7ad3df62014-10-31 07:59:37 +01001273 *in_dict* can be a dictionary or a mapping like container. If it is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01001274 mapping then it must at least support getting, setting and deleting items
1275 plus iterating over keys.
1276
Georg Brandl7ad3df62014-10-31 07:59:37 +01001277 *in_dict* can also be a string specifying the name of the dictionary, which
Michael Foorda9e6fb22012-03-28 14:36:02 +01001278 will then be fetched by importing it.
1279
Georg Brandl7ad3df62014-10-31 07:59:37 +01001280 *values* can be a dictionary of values to set in the dictionary. *values*
1281 can also be an iterable of ``(key, value)`` pairs.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001282
Georg Brandl7ad3df62014-10-31 07:59:37 +01001283 If *clear* is true then the dictionary will be cleared before the new
Michael Foorda9e6fb22012-03-28 14:36:02 +01001284 values are set.
1285
Georg Brandl7ad3df62014-10-31 07:59:37 +01001286 :func:`patch.dict` can also be called with arbitrary keyword arguments to set
Michael Foorda9e6fb22012-03-28 14:36:02 +01001287 values in the dictionary.
1288
Georg Brandl7ad3df62014-10-31 07:59:37 +01001289 :func:`patch.dict` can be used as a context manager, decorator or class
1290 decorator. When used as a class decorator :func:`patch.dict` honours
1291 ``patch.TEST_PREFIX`` for choosing which methods to wrap.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001292
Georg Brandl7ad3df62014-10-31 07:59:37 +01001293:func:`patch.dict` can be used to add members to a dictionary, or simply let a test
Michael Foorda9e6fb22012-03-28 14:36:02 +01001294change a dictionary, and ensure the dictionary is restored when the test
1295ends.
1296
1297 >>> foo = {}
1298 >>> with patch.dict(foo, {'newkey': 'newvalue'}):
1299 ... assert foo == {'newkey': 'newvalue'}
1300 ...
1301 >>> assert foo == {}
1302
1303 >>> import os
1304 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
Berker Peksag920f6db2015-09-10 21:41:15 +03001305 ... print(os.environ['newkey'])
Michael Foorda9e6fb22012-03-28 14:36:02 +01001306 ...
1307 newvalue
1308 >>> assert 'newkey' not in os.environ
1309
Georg Brandl7ad3df62014-10-31 07:59:37 +01001310Keywords can be used in the :func:`patch.dict` call to set values in the dictionary:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001311
1312 >>> mymodule = MagicMock()
1313 >>> mymodule.function.return_value = 'fish'
1314 >>> with patch.dict('sys.modules', mymodule=mymodule):
1315 ... import mymodule
1316 ... mymodule.function('some', 'args')
1317 ...
1318 'fish'
1319
Georg Brandl7ad3df62014-10-31 07:59:37 +01001320:func:`patch.dict` can be used with dictionary like objects that aren't actually
Michael Foorda9e6fb22012-03-28 14:36:02 +01001321dictionaries. At the very minimum they must support item getting, setting,
1322deleting and either iteration or membership test. This corresponds to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001323magic methods :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__` and either
1324:meth:`__iter__` or :meth:`__contains__`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001325
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001326 >>> class Container:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001327 ... def __init__(self):
1328 ... self.values = {}
1329 ... def __getitem__(self, name):
1330 ... return self.values[name]
1331 ... def __setitem__(self, name, value):
1332 ... self.values[name] = value
1333 ... def __delitem__(self, name):
1334 ... del self.values[name]
1335 ... def __iter__(self):
1336 ... return iter(self.values)
1337 ...
1338 >>> thing = Container()
1339 >>> thing['one'] = 1
1340 >>> with patch.dict(thing, one=2, two=3):
1341 ... assert thing['one'] == 2
1342 ... assert thing['two'] == 3
1343 ...
1344 >>> assert thing['one'] == 1
1345 >>> assert list(thing) == ['one']
1346
1347
1348patch.multiple
Georg Brandlfb134382013-02-03 11:47:49 +01001349~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001350
1351.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1352
1353 Perform multiple patches in a single call. It takes the object to be
1354 patched (either as an object or a string to fetch the object by importing)
1355 and keyword arguments for the patches::
1356
1357 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1358 ...
1359
Georg Brandl7ad3df62014-10-31 07:59:37 +01001360 Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create
Michael Foorda9e6fb22012-03-28 14:36:02 +01001361 mocks for you. In this case the created mocks are passed into a decorated
Georg Brandl7ad3df62014-10-31 07:59:37 +01001362 function by keyword, and a dictionary is returned when :func:`patch.multiple` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001363 used as a context manager.
1364
Georg Brandl7ad3df62014-10-31 07:59:37 +01001365 :func:`patch.multiple` can be used as a decorator, class decorator or a context
1366 manager. The arguments *spec*, *spec_set*, *create*, *autospec* and
1367 *new_callable* have the same meaning as for :func:`patch`. These arguments will
1368 be applied to *all* patches done by :func:`patch.multiple`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001369
Georg Brandl7ad3df62014-10-31 07:59:37 +01001370 When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001371 for choosing which methods to wrap.
1372
Georg Brandl7ad3df62014-10-31 07:59:37 +01001373If you want :func:`patch.multiple` to create mocks for you, then you can use
1374:data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator
Michael Foorda9e6fb22012-03-28 14:36:02 +01001375then the created mocks are passed into the decorated function by keyword.
1376
1377 >>> thing = object()
1378 >>> other = object()
1379
1380 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1381 ... def test_function(thing, other):
1382 ... assert isinstance(thing, MagicMock)
1383 ... assert isinstance(other, MagicMock)
1384 ...
1385 >>> test_function()
1386
Georg Brandl7ad3df62014-10-31 07:59:37 +01001387:func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments
1388passed by keyword *after* any of the standard arguments created by :func:`patch`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001389
1390 >>> @patch('sys.exit')
1391 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1392 ... def test_function(mock_exit, other, thing):
1393 ... assert 'other' in repr(other)
1394 ... assert 'thing' in repr(thing)
1395 ... assert 'exit' in repr(mock_exit)
1396 ...
1397 >>> test_function()
1398
Georg Brandl7ad3df62014-10-31 07:59:37 +01001399If :func:`patch.multiple` is used as a context manager, the value returned by the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001400context manger is a dictionary where created mocks are keyed by name:
1401
1402 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
1403 ... assert 'other' in repr(values['other'])
1404 ... assert 'thing' in repr(values['thing'])
1405 ... assert values['thing'] is thing
1406 ... assert values['other'] is other
1407 ...
1408
1409
1410.. _start-and-stop:
1411
1412patch methods: start and stop
Georg Brandlfb134382013-02-03 11:47:49 +01001413~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001414
Georg Brandl7ad3df62014-10-31 07:59:37 +01001415All the patchers have :meth:`start` and :meth:`stop` methods. These make it simpler to do
1416patching in ``setUp`` methods or where you want to do multiple patches without
Michael Foorda9e6fb22012-03-28 14:36:02 +01001417nesting decorators or with statements.
1418
Georg Brandl7ad3df62014-10-31 07:59:37 +01001419To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as
1420normal and keep a reference to the returned ``patcher`` object. You can then
1421call :meth:`start` to put the patch in place and :meth:`stop` to undo it.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001422
Georg Brandl7ad3df62014-10-31 07:59:37 +01001423If you are using :func:`patch` to create a mock for you then it will be returned by
1424the call to ``patcher.start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001425
1426 >>> patcher = patch('package.module.ClassName')
1427 >>> from package import module
1428 >>> original = module.ClassName
1429 >>> new_mock = patcher.start()
1430 >>> assert module.ClassName is not original
1431 >>> assert module.ClassName is new_mock
1432 >>> patcher.stop()
1433 >>> assert module.ClassName is original
1434 >>> assert module.ClassName is not new_mock
1435
1436
Georg Brandl7ad3df62014-10-31 07:59:37 +01001437A typical use case for this might be for doing multiple patches in the ``setUp``
1438method of a :class:`TestCase`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001439
1440 >>> class MyTest(TestCase):
1441 ... def setUp(self):
1442 ... self.patcher1 = patch('package.module.Class1')
1443 ... self.patcher2 = patch('package.module.Class2')
1444 ... self.MockClass1 = self.patcher1.start()
1445 ... self.MockClass2 = self.patcher2.start()
1446 ...
1447 ... def tearDown(self):
1448 ... self.patcher1.stop()
1449 ... self.patcher2.stop()
1450 ...
1451 ... def test_something(self):
1452 ... assert package.module.Class1 is self.MockClass1
1453 ... assert package.module.Class2 is self.MockClass2
1454 ...
1455 >>> MyTest('test_something').run()
1456
1457.. caution::
1458
1459 If you use this technique you must ensure that the patching is "undone" by
Georg Brandl7ad3df62014-10-31 07:59:37 +01001460 calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001461 exception is raised in the ``setUp`` then ``tearDown`` is not called.
1462 :meth:`unittest.TestCase.addCleanup` makes this easier:
1463
1464 >>> class MyTest(TestCase):
1465 ... def setUp(self):
1466 ... patcher = patch('package.module.Class')
1467 ... self.MockClass = patcher.start()
1468 ... self.addCleanup(patcher.stop)
1469 ...
1470 ... def test_something(self):
1471 ... assert package.module.Class is self.MockClass
1472 ...
1473
Georg Brandl7ad3df62014-10-31 07:59:37 +01001474 As an added bonus you no longer need to keep a reference to the ``patcher``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001475 object.
1476
Michael Foordf7c41582012-06-10 20:36:32 +01001477It is also possible to stop all patches which have been started by using
Georg Brandl7ad3df62014-10-31 07:59:37 +01001478:func:`patch.stopall`.
Michael Foordf7c41582012-06-10 20:36:32 +01001479
1480.. function:: patch.stopall
1481
Georg Brandl7ad3df62014-10-31 07:59:37 +01001482 Stop all active patches. Only stops patches started with ``start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001483
Georg Brandl7ad3df62014-10-31 07:59:37 +01001484
1485.. _patch-builtins:
Michael Foordfddcfa22014-04-14 16:25:20 -04001486
1487patch builtins
Georg Brandl7ad3df62014-10-31 07:59:37 +01001488~~~~~~~~~~~~~~
Michael Foordfddcfa22014-04-14 16:25:20 -04001489You can patch any builtins within a module. The following example patches
Georg Brandl7ad3df62014-10-31 07:59:37 +01001490builtin :func:`ord`:
Michael Foordfddcfa22014-04-14 16:25:20 -04001491
1492 >>> @patch('__main__.ord')
1493 ... def test(mock_ord):
1494 ... mock_ord.return_value = 101
1495 ... print(ord('c'))
1496 ...
1497 >>> test()
1498 101
1499
Michael Foorda9e6fb22012-03-28 14:36:02 +01001500
1501TEST_PREFIX
Georg Brandlfb134382013-02-03 11:47:49 +01001502~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001503
1504All of the patchers can be used as class decorators. When used in this way
1505they wrap every test method on the class. The patchers recognise methods that
Georg Brandl7ad3df62014-10-31 07:59:37 +01001506start with ``'test'`` as being test methods. This is the same way that the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001507:class:`unittest.TestLoader` finds test methods by default.
1508
1509It is possible that you want to use a different prefix for your tests. You can
Georg Brandl7ad3df62014-10-31 07:59:37 +01001510inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001511
1512 >>> patch.TEST_PREFIX = 'foo'
1513 >>> value = 3
1514 >>>
1515 >>> @patch('__main__.value', 'not three')
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001516 ... class Thing:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001517 ... def foo_one(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001518 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001519 ... def foo_two(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001520 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001521 ...
1522 >>>
1523 >>> Thing().foo_one()
1524 not three
1525 >>> Thing().foo_two()
1526 not three
1527 >>> value
1528 3
1529
1530
1531Nesting Patch Decorators
Georg Brandlfb134382013-02-03 11:47:49 +01001532~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001533
1534If you want to perform multiple patches then you can simply stack up the
1535decorators.
1536
1537You can stack up multiple patch decorators using this pattern:
1538
1539 >>> @patch.object(SomeClass, 'class_method')
1540 ... @patch.object(SomeClass, 'static_method')
1541 ... def test(mock1, mock2):
1542 ... assert SomeClass.static_method is mock1
1543 ... assert SomeClass.class_method is mock2
1544 ... SomeClass.static_method('foo')
1545 ... SomeClass.class_method('bar')
1546 ... return mock1, mock2
1547 ...
1548 >>> mock1, mock2 = test()
1549 >>> mock1.assert_called_once_with('foo')
1550 >>> mock2.assert_called_once_with('bar')
1551
1552
1553Note that the decorators are applied from the bottom upwards. This is the
1554standard way that Python applies decorators. The order of the created mocks
1555passed into your test function matches this order.
1556
1557
1558.. _where-to-patch:
1559
1560Where to patch
Georg Brandlfb134382013-02-03 11:47:49 +01001561~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001562
Georg Brandl7ad3df62014-10-31 07:59:37 +01001563:func:`patch` works by (temporarily) changing the object that a *name* points to with
Michael Foorda9e6fb22012-03-28 14:36:02 +01001564another one. There can be many names pointing to any individual object, so
1565for patching to work you must ensure that you patch the name used by the system
1566under test.
1567
1568The basic principle is that you patch where an object is *looked up*, which
1569is not necessarily the same place as where it is defined. A couple of
1570examples will help to clarify this.
1571
1572Imagine we have a project that we want to test with the following structure::
1573
1574 a.py
1575 -> Defines SomeClass
1576
1577 b.py
1578 -> from a import SomeClass
1579 -> some_function instantiates SomeClass
1580
Georg Brandl7ad3df62014-10-31 07:59:37 +01001581Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
1582:func:`patch`. The problem is that when we import module b, which we will have to
1583do then it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
1584``a.SomeClass`` then it will have no effect on our test; module b already has a
1585reference to the *real* ``SomeClass`` and it looks like our patching had no
Michael Foorda9e6fb22012-03-28 14:36:02 +01001586effect.
1587
Ben Lloyd15033d12017-05-22 12:06:56 +01001588The key is to patch out ``SomeClass`` where it is used (or where it is looked up).
1589In this case ``some_function`` will actually look up ``SomeClass`` in module b,
Michael Foorda9e6fb22012-03-28 14:36:02 +01001590where we have imported it. The patching should look like::
1591
1592 @patch('b.SomeClass')
1593
Georg Brandl7ad3df62014-10-31 07:59:37 +01001594However, consider the alternative scenario where instead of ``from a import
1595SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both
Michael Foorda9e6fb22012-03-28 14:36:02 +01001596of these import forms are common. In this case the class we want to patch is
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001597being looked up in the module and so we have to patch ``a.SomeClass`` instead::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001598
1599 @patch('a.SomeClass')
1600
1601
1602Patching Descriptors and Proxy Objects
Georg Brandlfb134382013-02-03 11:47:49 +01001603~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001604
1605Both patch_ and patch.object_ correctly patch and restore descriptors: class
1606methods, static methods and properties. You should patch these on the *class*
1607rather than an instance. They also work with *some* objects
Zachary Ware5ea5d2c2014-02-26 09:34:43 -06001608that proxy attribute access, like the `django settings object
Michael Foorda9e6fb22012-03-28 14:36:02 +01001609<http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
1610
1611
Michael Foord2309ed82012-03-28 15:38:36 +01001612MagicMock and magic method support
Georg Brandlfb134382013-02-03 11:47:49 +01001613----------------------------------
Michael Foord2309ed82012-03-28 15:38:36 +01001614
1615.. _magic-methods:
1616
1617Mocking Magic Methods
Georg Brandlfb134382013-02-03 11:47:49 +01001618~~~~~~~~~~~~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001619
1620:class:`Mock` supports mocking the Python protocol methods, also known as
1621"magic methods". This allows mock objects to replace containers or other
1622objects that implement Python protocols.
1623
1624Because magic methods are looked up differently from normal methods [#]_, this
1625support has been specially implemented. This means that only specific magic
1626methods are supported. The supported list includes *almost* all of them. If
1627there are any missing that you need please let us know.
1628
1629You mock magic methods by setting the method you are interested in to a function
1630or a mock instance. If you are using a function then it *must* take ``self`` as
1631the first argument [#]_.
1632
1633 >>> def __str__(self):
1634 ... return 'fooble'
1635 ...
1636 >>> mock = Mock()
1637 >>> mock.__str__ = __str__
1638 >>> str(mock)
1639 'fooble'
1640
1641 >>> mock = Mock()
1642 >>> mock.__str__ = Mock()
1643 >>> mock.__str__.return_value = 'fooble'
1644 >>> str(mock)
1645 'fooble'
1646
1647 >>> mock = Mock()
1648 >>> mock.__iter__ = Mock(return_value=iter([]))
1649 >>> list(mock)
1650 []
1651
1652One use case for this is for mocking objects used as context managers in a
Georg Brandl7ad3df62014-10-31 07:59:37 +01001653:keyword:`with` statement:
Michael Foord2309ed82012-03-28 15:38:36 +01001654
1655 >>> mock = Mock()
1656 >>> mock.__enter__ = Mock(return_value='foo')
1657 >>> mock.__exit__ = Mock(return_value=False)
1658 >>> with mock as m:
1659 ... assert m == 'foo'
1660 ...
1661 >>> mock.__enter__.assert_called_with()
1662 >>> mock.__exit__.assert_called_with(None, None, None)
1663
1664Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they
1665are recorded in :attr:`~Mock.mock_calls`.
1666
1667.. note::
1668
Georg Brandl7ad3df62014-10-31 07:59:37 +01001669 If you use the *spec* keyword argument to create a mock then attempting to
1670 set a magic method that isn't in the spec will raise an :exc:`AttributeError`.
Michael Foord2309ed82012-03-28 15:38:36 +01001671
1672The full list of supported magic methods is:
1673
1674* ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``
1675* ``__dir__``, ``__format__`` and ``__subclasses__``
1676* ``__floor__``, ``__trunc__`` and ``__ceil__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001677* Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001678 ``__eq__`` and ``__ne__``
1679* Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``,
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001680 ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__``
1681 and ``__missing__``
Michael Foord2309ed82012-03-28 15:38:36 +01001682* Context manager: ``__enter__`` and ``__exit__``
1683* Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``
1684* The numeric methods (including right hand and in-place variants):
Serhiy Storchakac2ccce72015-03-12 22:01:30 +02001685 ``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__div__``, ``__truediv__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001686 ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``,
1687 ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001688* Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__``
1689 and ``__index__``
Michael Foord2309ed82012-03-28 15:38:36 +01001690* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
1691* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
1692 ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
1693
1694
1695The following methods exist but are *not* supported as they are either in use
1696by mock, can't be set dynamically, or can cause problems:
1697
1698* ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``
1699* ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``
1700
1701
1702
1703Magic Mock
Georg Brandlfb134382013-02-03 11:47:49 +01001704~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001705
Georg Brandl7ad3df62014-10-31 07:59:37 +01001706There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001707
1708
1709.. class:: MagicMock(*args, **kw)
1710
1711 ``MagicMock`` is a subclass of :class:`Mock` with default implementations
1712 of most of the magic methods. You can use ``MagicMock`` without having to
1713 configure the magic methods yourself.
1714
1715 The constructor parameters have the same meaning as for :class:`Mock`.
1716
Georg Brandl7ad3df62014-10-31 07:59:37 +01001717 If you use the *spec* or *spec_set* arguments then *only* magic methods
Michael Foord2309ed82012-03-28 15:38:36 +01001718 that exist in the spec will be created.
1719
1720
1721.. class:: NonCallableMagicMock(*args, **kw)
1722
Georg Brandl7ad3df62014-10-31 07:59:37 +01001723 A non-callable version of :class:`MagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001724
1725 The constructor parameters have the same meaning as for
Georg Brandl7ad3df62014-10-31 07:59:37 +01001726 :class:`MagicMock`, with the exception of *return_value* and
1727 *side_effect* which have no meaning on a non-callable mock.
Michael Foord2309ed82012-03-28 15:38:36 +01001728
Georg Brandl7ad3df62014-10-31 07:59:37 +01001729The magic methods are setup with :class:`MagicMock` objects, so you can configure them
Michael Foord2309ed82012-03-28 15:38:36 +01001730and use them in the usual way:
1731
1732 >>> mock = MagicMock()
1733 >>> mock[3] = 'fish'
1734 >>> mock.__setitem__.assert_called_with(3, 'fish')
1735 >>> mock.__getitem__.return_value = 'result'
1736 >>> mock[2]
1737 'result'
1738
1739By default many of the protocol methods are required to return objects of a
1740specific type. These methods are preconfigured with a default return value, so
1741that they can be used without you having to do anything if you aren't interested
1742in the return value. You can still *set* the return value manually if you want
1743to change the default.
1744
1745Methods and their defaults:
1746
1747* ``__lt__``: NotImplemented
1748* ``__gt__``: NotImplemented
1749* ``__le__``: NotImplemented
1750* ``__ge__``: NotImplemented
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001751* ``__int__``: 1
1752* ``__contains__``: False
Berker Peksag8fafc742016-04-11 12:23:04 +03001753* ``__len__``: 0
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001754* ``__iter__``: iter([])
1755* ``__exit__``: False
1756* ``__complex__``: 1j
1757* ``__float__``: 1.0
1758* ``__bool__``: True
1759* ``__index__``: 1
1760* ``__hash__``: default hash for the mock
1761* ``__str__``: default str for the mock
Michael Foord2309ed82012-03-28 15:38:36 +01001762* ``__sizeof__``: default sizeof for the mock
1763
1764For example:
1765
1766 >>> mock = MagicMock()
1767 >>> int(mock)
1768 1
1769 >>> len(mock)
1770 0
1771 >>> list(mock)
1772 []
1773 >>> object() in mock
1774 False
1775
Berker Peksag283f1aa2015-01-07 21:15:02 +02001776The two equality methods, :meth:`__eq__` and :meth:`__ne__`, are special.
1777They do the default equality comparison on identity, using the
1778:attr:`~Mock.side_effect` attribute, unless you change their return value to
1779return something else::
Michael Foord2309ed82012-03-28 15:38:36 +01001780
1781 >>> MagicMock() == 3
1782 False
1783 >>> MagicMock() != 3
1784 True
1785 >>> mock = MagicMock()
1786 >>> mock.__eq__.return_value = True
1787 >>> mock == 3
1788 True
1789
Georg Brandl7ad3df62014-10-31 07:59:37 +01001790The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
Michael Foord2309ed82012-03-28 15:38:36 +01001791required to be an iterator:
1792
1793 >>> mock = MagicMock()
1794 >>> mock.__iter__.return_value = ['a', 'b', 'c']
1795 >>> list(mock)
1796 ['a', 'b', 'c']
1797 >>> list(mock)
1798 ['a', 'b', 'c']
1799
1800If the return value *is* an iterator, then iterating over it once will consume
1801it and subsequent iterations will result in an empty list:
1802
1803 >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
1804 >>> list(mock)
1805 ['a', 'b', 'c']
1806 >>> list(mock)
1807 []
1808
1809``MagicMock`` has all of the supported magic methods configured except for some
1810of the obscure and obsolete ones. You can still set these up if you want.
1811
1812Magic methods that are supported but not setup by default in ``MagicMock`` are:
1813
1814* ``__subclasses__``
1815* ``__dir__``
1816* ``__format__``
1817* ``__get__``, ``__set__`` and ``__delete__``
1818* ``__reversed__`` and ``__missing__``
1819* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
1820 ``__getstate__`` and ``__setstate__``
1821* ``__getformat__`` and ``__setformat__``
1822
1823
1824
1825.. [#] Magic methods *should* be looked up on the class rather than the
1826 instance. Different versions of Python are inconsistent about applying this
1827 rule. The supported protocol methods should work with all supported versions
1828 of Python.
1829.. [#] The function is basically hooked up to the class, but each ``Mock``
1830 instance is kept isolated from the others.
1831
1832
Michael Foorda9e6fb22012-03-28 14:36:02 +01001833Helpers
Georg Brandlfb134382013-02-03 11:47:49 +01001834-------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001835
1836sentinel
Georg Brandlfb134382013-02-03 11:47:49 +01001837~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001838
1839.. data:: sentinel
1840
Miss Islington (bot)79c6b352018-07-08 17:48:02 -07001841 The ``sentinel`` object provides a convenient way of providing unique
1842 objects for your tests.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001843
Miss Islington (bot)79c6b352018-07-08 17:48:02 -07001844 Attributes are created on demand when you access them by name. Accessing
1845 the same attribute will always return the same object. The objects
1846 returned have a sensible repr so that test failure messages are readable.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001847
Serhiy Storchakad9c956f2017-01-11 20:13:03 +02001848 .. versionchanged:: 3.7
1849 The ``sentinel`` attributes now preserve their identity when they are
1850 :mod:`copied <copy>` or :mod:`pickled <pickle>`.
1851
Michael Foorda9e6fb22012-03-28 14:36:02 +01001852Sometimes when testing you need to test that a specific object is passed as an
1853argument to another method, or returned. It can be common to create named
Georg Brandl7ad3df62014-10-31 07:59:37 +01001854sentinel objects to test this. :data:`sentinel` provides a convenient way of
Michael Foorda9e6fb22012-03-28 14:36:02 +01001855creating and testing the identity of objects like this.
1856
Georg Brandl7ad3df62014-10-31 07:59:37 +01001857In this example we monkey patch ``method`` to return ``sentinel.some_object``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001858
1859 >>> real = ProductionClass()
1860 >>> real.method = Mock(name="method")
1861 >>> real.method.return_value = sentinel.some_object
1862 >>> result = real.method()
1863 >>> assert result is sentinel.some_object
1864 >>> sentinel.some_object
1865 sentinel.some_object
1866
1867
1868DEFAULT
Georg Brandlfb134382013-02-03 11:47:49 +01001869~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001870
1871
1872.. data:: DEFAULT
1873
Georg Brandl7ad3df62014-10-31 07:59:37 +01001874 The :data:`DEFAULT` object is a pre-created sentinel (actually
1875 ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001876 functions to indicate that the normal return value should be used.
1877
1878
Michael Foorda9e6fb22012-03-28 14:36:02 +01001879call
Georg Brandlfb134382013-02-03 11:47:49 +01001880~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001881
1882.. function:: call(*args, **kwargs)
1883
Georg Brandl7ad3df62014-10-31 07:59:37 +01001884 :func:`call` is a helper object for making simpler assertions, for comparing with
Georg Brandl24891672012-04-01 13:48:26 +02001885 :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
Georg Brandl7ad3df62014-10-31 07:59:37 +01001886 :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be
Michael Foorda9e6fb22012-03-28 14:36:02 +01001887 used with :meth:`~Mock.assert_has_calls`.
1888
1889 >>> m = MagicMock(return_value=None)
1890 >>> m(1, 2, a='foo', b='bar')
1891 >>> m()
1892 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
1893 True
1894
1895.. method:: call.call_list()
1896
Georg Brandl7ad3df62014-10-31 07:59:37 +01001897 For a call object that represents multiple calls, :meth:`call_list`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001898 returns a list of all the intermediate calls as well as the
1899 final call.
1900
Georg Brandl7ad3df62014-10-31 07:59:37 +01001901``call_list`` is particularly useful for making assertions on "chained calls". A
Michael Foorda9e6fb22012-03-28 14:36:02 +01001902chained call is multiple calls on a single line of code. This results in
1903multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
1904the sequence of calls can be tedious.
1905
1906:meth:`~call.call_list` can construct the sequence of calls from the same
1907chained call:
1908
1909 >>> m = MagicMock()
1910 >>> m(1).method(arg='foo').other('bar')(2.0)
1911 <MagicMock name='mock().method().other()()' id='...'>
1912 >>> kall = call(1).method(arg='foo').other('bar')(2.0)
1913 >>> kall.call_list()
1914 [call(1),
1915 call().method(arg='foo'),
1916 call().method().other('bar'),
1917 call().method().other()(2.0)]
1918 >>> m.mock_calls == kall.call_list()
1919 True
1920
1921.. _calls-as-tuples:
1922
Georg Brandl7ad3df62014-10-31 07:59:37 +01001923A ``call`` object is either a tuple of (positional args, keyword args) or
Michael Foorda9e6fb22012-03-28 14:36:02 +01001924(name, positional args, keyword args) depending on how it was constructed. When
Georg Brandl7ad3df62014-10-31 07:59:37 +01001925you construct them yourself this isn't particularly interesting, but the ``call``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001926objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
1927:attr:`Mock.mock_calls` attributes can be introspected to get at the individual
1928arguments they contain.
1929
Georg Brandl7ad3df62014-10-31 07:59:37 +01001930The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
1931are two-tuples of (positional args, keyword args) whereas the ``call`` objects
Michael Foorda9e6fb22012-03-28 14:36:02 +01001932in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
1933three-tuples of (name, positional args, keyword args).
1934
1935You can use their "tupleness" to pull out the individual arguments for more
1936complex introspection and assertions. The positional arguments are a tuple
1937(an empty tuple if there are no positional arguments) and the keyword
1938arguments are a dictionary:
1939
1940 >>> m = MagicMock(return_value=None)
1941 >>> m(1, 2, 3, arg='one', arg2='two')
1942 >>> kall = m.call_args
1943 >>> args, kwargs = kall
1944 >>> args
1945 (1, 2, 3)
1946 >>> kwargs
1947 {'arg2': 'two', 'arg': 'one'}
1948 >>> args is kall[0]
1949 True
1950 >>> kwargs is kall[1]
1951 True
1952
1953 >>> m = MagicMock()
1954 >>> m.foo(4, 5, 6, arg='two', arg2='three')
1955 <MagicMock name='mock.foo()' id='...'>
1956 >>> kall = m.mock_calls[0]
1957 >>> name, args, kwargs = kall
1958 >>> name
1959 'foo'
1960 >>> args
1961 (4, 5, 6)
1962 >>> kwargs
1963 {'arg2': 'three', 'arg': 'two'}
1964 >>> name is m.mock_calls[0][0]
1965 True
1966
1967
1968create_autospec
Georg Brandlfb134382013-02-03 11:47:49 +01001969~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001970
1971.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
1972
1973 Create a mock object using another object as a spec. Attributes on the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001974 mock will use the corresponding attribute on the *spec* object as their
Michael Foorda9e6fb22012-03-28 14:36:02 +01001975 spec.
1976
1977 Functions or methods being mocked will have their arguments checked to
1978 ensure that they are called with the correct signature.
1979
Georg Brandl7ad3df62014-10-31 07:59:37 +01001980 If *spec_set* is ``True`` then attempting to set attributes that don't exist
1981 on the spec object will raise an :exc:`AttributeError`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001982
1983 If a class is used as a spec then the return value of the mock (the
1984 instance of the class) will have the same spec. You can use a class as the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001985 spec for an instance object by passing ``instance=True``. The returned mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001986 will only be callable if instances of the mock are callable.
1987
Georg Brandl7ad3df62014-10-31 07:59:37 +01001988 :func:`create_autospec` also takes arbitrary keyword arguments that are passed to
Michael Foorda9e6fb22012-03-28 14:36:02 +01001989 the constructor of the created mock.
1990
1991See :ref:`auto-speccing` for examples of how to use auto-speccing with
Georg Brandl7ad3df62014-10-31 07:59:37 +01001992:func:`create_autospec` and the *autospec* argument to :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001993
1994
1995ANY
Georg Brandlfb134382013-02-03 11:47:49 +01001996~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001997
1998.. data:: ANY
1999
2000Sometimes you may need to make assertions about *some* of the arguments in a
2001call to mock, but either not care about some of the arguments or want to pull
2002them individually out of :attr:`~Mock.call_args` and make more complex
2003assertions on them.
2004
2005To ignore certain arguments you can pass in objects that compare equal to
2006*everything*. Calls to :meth:`~Mock.assert_called_with` and
2007:meth:`~Mock.assert_called_once_with` will then succeed no matter what was
2008passed in.
2009
2010 >>> mock = Mock(return_value=None)
2011 >>> mock('foo', bar=object())
2012 >>> mock.assert_called_once_with('foo', bar=ANY)
2013
Georg Brandl7ad3df62014-10-31 07:59:37 +01002014:data:`ANY` can also be used in comparisons with call lists like
Michael Foorda9e6fb22012-03-28 14:36:02 +01002015:attr:`~Mock.mock_calls`:
2016
2017 >>> m = MagicMock(return_value=None)
2018 >>> m(1)
2019 >>> m(1, 2)
2020 >>> m(object())
2021 >>> m.mock_calls == [call(1), call(1, 2), ANY]
2022 True
2023
2024
2025
2026FILTER_DIR
Georg Brandlfb134382013-02-03 11:47:49 +01002027~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002028
2029.. data:: FILTER_DIR
2030
Georg Brandl7ad3df62014-10-31 07:59:37 +01002031:data:`FILTER_DIR` is a module level variable that controls the way mock objects
2032respond to :func:`dir` (only for Python 2.6 or more recent). The default is ``True``,
Michael Foorda9e6fb22012-03-28 14:36:02 +01002033which uses the filtering described below, to only show useful members. If you
2034dislike this filtering, or need to switch it off for diagnostic purposes, then
Georg Brandl7ad3df62014-10-31 07:59:37 +01002035set ``mock.FILTER_DIR = False``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002036
Georg Brandl7ad3df62014-10-31 07:59:37 +01002037With filtering on, ``dir(some_mock)`` shows only useful attributes and will
Michael Foorda9e6fb22012-03-28 14:36:02 +01002038include any dynamically created attributes that wouldn't normally be shown.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002039If the mock was created with a *spec* (or *autospec* of course) then all the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002040attributes from the original are shown, even if they haven't been accessed
2041yet:
2042
2043 >>> dir(Mock())
2044 ['assert_any_call',
2045 'assert_called_once_with',
2046 'assert_called_with',
2047 'assert_has_calls',
2048 'attach_mock',
2049 ...
2050 >>> from urllib import request
2051 >>> dir(Mock(spec=request))
2052 ['AbstractBasicAuthHandler',
2053 'AbstractDigestAuthHandler',
2054 'AbstractHTTPHandler',
2055 'BaseHandler',
2056 ...
2057
Georg Brandl7ad3df62014-10-31 07:59:37 +01002058Many of the not-very-useful (private to :class:`Mock` rather than the thing being
Michael Foorda9e6fb22012-03-28 14:36:02 +01002059mocked) underscore and double underscore prefixed attributes have been
Georg Brandl7ad3df62014-10-31 07:59:37 +01002060filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this
Michael Foorda9e6fb22012-03-28 14:36:02 +01002061behaviour you can switch it off by setting the module level switch
Georg Brandl7ad3df62014-10-31 07:59:37 +01002062:data:`FILTER_DIR`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002063
2064 >>> from unittest import mock
2065 >>> mock.FILTER_DIR = False
2066 >>> dir(mock.Mock())
2067 ['_NonCallableMock__get_return_value',
2068 '_NonCallableMock__get_side_effect',
2069 '_NonCallableMock__return_value_doc',
2070 '_NonCallableMock__set_return_value',
2071 '_NonCallableMock__set_side_effect',
2072 '__call__',
2073 '__class__',
2074 ...
2075
Georg Brandl7ad3df62014-10-31 07:59:37 +01002076Alternatively you can just use ``vars(my_mock)`` (instance members) and
2077``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of
2078:data:`mock.FILTER_DIR`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002079
2080
2081mock_open
Georg Brandlfb134382013-02-03 11:47:49 +01002082~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002083
2084.. function:: mock_open(mock=None, read_data=None)
2085
Miss Islington (bot)79c6b352018-07-08 17:48:02 -07002086 A helper function to create a mock to replace the use of :func:`open`. It works
2087 for :func:`open` called directly or used as a context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002088
Miss Islington (bot)79c6b352018-07-08 17:48:02 -07002089 The *mock* argument is the mock object to configure. If ``None`` (the
2090 default) then a :class:`MagicMock` will be created for you, with the API limited
2091 to methods or attributes available on standard file handles.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002092
Miss Islington (bot)79c6b352018-07-08 17:48:02 -07002093 *read_data* is a string for the :meth:`~io.IOBase.read`,
2094 :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods
2095 of the file handle to return. Calls to those methods will take data from
2096 *read_data* until it is depleted. The mock of these methods is pretty
2097 simplistic: every time the *mock* is called, the *read_data* is rewound to
2098 the start. If you need more control over the data that you are feeding to
2099 the tested code you will need to customize this mock for yourself. When that
2100 is insufficient, one of the in-memory filesystem packages on `PyPI
2101 <https://pypi.org>`_ can offer a realistic filesystem for testing.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002102
Robert Collinsf79dfe32015-07-24 04:09:59 +12002103 .. versionchanged:: 3.4
2104 Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support.
2105 The mock of :meth:`~io.IOBase.read` changed to consume *read_data* rather
2106 than returning it on each call.
2107
Robert Collins70398392015-07-24 04:10:27 +12002108 .. versionchanged:: 3.5
Robert Collinsf79dfe32015-07-24 04:09:59 +12002109 *read_data* is now reset on each call to the *mock*.
2110
Miss Islington (bot)c83c3752018-09-14 14:30:04 -07002111 .. versionchanged:: 3.7.1
2112 Added :meth:`__iter__` to implementation so that iteration (such as in for
2113 loops) correctly consumes *read_data*.
2114
Georg Brandl7ad3df62014-10-31 07:59:37 +01002115Using :func:`open` as a context manager is a great way to ensure your file handles
Michael Foorda9e6fb22012-03-28 14:36:02 +01002116are closed properly and is becoming common::
2117
2118 with open('/some/path', 'w') as f:
2119 f.write('something')
2120
Georg Brandl7ad3df62014-10-31 07:59:37 +01002121The issue is that even if you mock out the call to :func:`open` it is the
2122*returned object* that is used as a context manager (and has :meth:`__enter__` and
2123:meth:`__exit__` called).
Michael Foorda9e6fb22012-03-28 14:36:02 +01002124
2125Mocking context managers with a :class:`MagicMock` is common enough and fiddly
2126enough that a helper function is useful.
2127
2128 >>> m = mock_open()
Michael Foordfddcfa22014-04-14 16:25:20 -04002129 >>> with patch('__main__.open', m):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002130 ... with open('foo', 'w') as h:
2131 ... h.write('some stuff')
2132 ...
2133 >>> m.mock_calls
2134 [call('foo', 'w'),
2135 call().__enter__(),
2136 call().write('some stuff'),
2137 call().__exit__(None, None, None)]
2138 >>> m.assert_called_once_with('foo', 'w')
2139 >>> handle = m()
2140 >>> handle.write.assert_called_once_with('some stuff')
2141
2142And for reading files:
2143
Michael Foordfddcfa22014-04-14 16:25:20 -04002144 >>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002145 ... with open('foo') as h:
2146 ... result = h.read()
2147 ...
2148 >>> m.assert_called_once_with('foo')
2149 >>> assert result == 'bibble'
2150
2151
2152.. _auto-speccing:
2153
2154Autospeccing
Georg Brandlfb134382013-02-03 11:47:49 +01002155~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002156
Georg Brandl7ad3df62014-10-31 07:59:37 +01002157Autospeccing is based on the existing :attr:`spec` feature of mock. It limits the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002158api of mocks to the api of an original object (the spec), but it is recursive
2159(implemented lazily) so that attributes of mocks only have the same api as
2160the attributes of the spec. In addition mocked functions / methods have the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002161same call signature as the original so they raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002162called incorrectly.
2163
2164Before I explain how auto-speccing works, here's why it is needed.
2165
Georg Brandl7ad3df62014-10-31 07:59:37 +01002166:class:`Mock` is a very powerful and flexible object, but it suffers from two flaws
Michael Foorda9e6fb22012-03-28 14:36:02 +01002167when used to mock out objects from a system under test. One of these flaws is
Georg Brandl7ad3df62014-10-31 07:59:37 +01002168specific to the :class:`Mock` api and the other is a more general problem with using
Michael Foorda9e6fb22012-03-28 14:36:02 +01002169mock objects.
2170
Georg Brandl7ad3df62014-10-31 07:59:37 +01002171First the problem specific to :class:`Mock`. :class:`Mock` has two assert methods that are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002172extremely handy: :meth:`~Mock.assert_called_with` and
2173:meth:`~Mock.assert_called_once_with`.
2174
2175 >>> mock = Mock(name='Thing', return_value=None)
2176 >>> mock(1, 2, 3)
2177 >>> mock.assert_called_once_with(1, 2, 3)
2178 >>> mock(1, 2, 3)
2179 >>> mock.assert_called_once_with(1, 2, 3)
2180 Traceback (most recent call last):
2181 ...
Michael Foord28d591c2012-09-28 16:15:22 +01002182 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002183
2184Because mocks auto-create attributes on demand, and allow you to call them
2185with arbitrary arguments, if you misspell one of these assert methods then
2186your assertion is gone:
2187
2188.. code-block:: pycon
2189
2190 >>> mock = Mock(name='Thing', return_value=None)
2191 >>> mock(1, 2, 3)
2192 >>> mock.assret_called_once_with(4, 5, 6)
2193
2194Your tests can pass silently and incorrectly because of the typo.
2195
2196The second issue is more general to mocking. If you refactor some of your
2197code, rename members and so on, any tests for code that is still using the
2198*old api* but uses mocks instead of the real objects will still pass. This
2199means your tests can all pass even though your code is broken.
2200
2201Note that this is another reason why you need integration tests as well as
2202unit tests. Testing everything in isolation is all fine and dandy, but if you
2203don't test how your units are "wired together" there is still lots of room
2204for bugs that tests might have caught.
2205
Georg Brandl7ad3df62014-10-31 07:59:37 +01002206:mod:`mock` already provides a feature to help with this, called speccing. If you
2207use a class or instance as the :attr:`spec` for a mock then you can only access
Michael Foorda9e6fb22012-03-28 14:36:02 +01002208attributes on the mock that exist on the real class:
2209
2210 >>> from urllib import request
2211 >>> mock = Mock(spec=request.Request)
2212 >>> mock.assret_called_with
2213 Traceback (most recent call last):
2214 ...
2215 AttributeError: Mock object has no attribute 'assret_called_with'
2216
2217The spec only applies to the mock itself, so we still have the same issue
2218with any methods on the mock:
2219
2220.. code-block:: pycon
2221
2222 >>> mock.has_data()
2223 <mock.Mock object at 0x...>
2224 >>> mock.has_data.assret_called_with()
2225
Georg Brandl7ad3df62014-10-31 07:59:37 +01002226Auto-speccing solves this problem. You can either pass ``autospec=True`` to
2227:func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a
2228mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002229object that is being replaced will be used as the spec object. Because the
2230speccing is done "lazily" (the spec is created as attributes on the mock are
2231accessed) you can use it with very complex or deeply nested objects (like
2232modules that import modules that import modules) without a big performance
2233hit.
2234
2235Here's an example of it in use:
2236
2237 >>> from urllib import request
2238 >>> patcher = patch('__main__.request', autospec=True)
2239 >>> mock_request = patcher.start()
2240 >>> request is mock_request
2241 True
2242 >>> mock_request.Request
2243 <MagicMock name='request.Request' spec='Request' id='...'>
2244
Georg Brandl7ad3df62014-10-31 07:59:37 +01002245You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two
2246arguments in the constructor (one of which is *self*). Here's what happens if
Michael Foorda9e6fb22012-03-28 14:36:02 +01002247we try to call it incorrectly:
2248
2249 >>> req = request.Request()
2250 Traceback (most recent call last):
2251 ...
2252 TypeError: <lambda>() takes at least 2 arguments (1 given)
2253
2254The spec also applies to instantiated classes (i.e. the return value of
2255specced mocks):
2256
2257 >>> req = request.Request('foo')
2258 >>> req
2259 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
2260
Georg Brandl7ad3df62014-10-31 07:59:37 +01002261:class:`Request` objects are not callable, so the return value of instantiating our
2262mocked out :class:`request.Request` is a non-callable mock. With the spec in place
Michael Foorda9e6fb22012-03-28 14:36:02 +01002263any typos in our asserts will raise the correct error:
2264
2265 >>> req.add_header('spam', 'eggs')
2266 <MagicMock name='request.Request().add_header()' id='...'>
2267 >>> req.add_header.assret_called_with
2268 Traceback (most recent call last):
2269 ...
2270 AttributeError: Mock object has no attribute 'assret_called_with'
2271 >>> req.add_header.assert_called_with('spam', 'eggs')
2272
Georg Brandl7ad3df62014-10-31 07:59:37 +01002273In many cases you will just be able to add ``autospec=True`` to your existing
2274:func:`patch` calls and then be protected against bugs due to typos and api
Michael Foorda9e6fb22012-03-28 14:36:02 +01002275changes.
2276
Georg Brandl7ad3df62014-10-31 07:59:37 +01002277As well as using *autospec* through :func:`patch` there is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002278:func:`create_autospec` for creating autospecced mocks directly:
2279
2280 >>> from urllib import request
2281 >>> mock_request = create_autospec(request)
2282 >>> mock_request.Request('foo', 'bar')
2283 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
2284
2285This isn't without caveats and limitations however, which is why it is not
2286the default behaviour. In order to know what attributes are available on the
2287spec object, autospec has to introspect (access attributes) the spec. As you
2288traverse attributes on the mock a corresponding traversal of the original
2289object is happening under the hood. If any of your specced objects have
2290properties or descriptors that can trigger code execution then you may not be
2291able to use autospec. On the other hand it is much better to design your
2292objects so that introspection is safe [#]_.
2293
2294A more serious problem is that it is common for instance attributes to be
Georg Brandl7ad3df62014-10-31 07:59:37 +01002295created in the :meth:`__init__` method and not to exist on the class at all.
2296*autospec* can't know about any dynamically created attributes and restricts
Michael Foorda9e6fb22012-03-28 14:36:02 +01002297the api to visible attributes.
2298
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002299 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002300 ... def __init__(self):
2301 ... self.a = 33
2302 ...
2303 >>> with patch('__main__.Something', autospec=True):
2304 ... thing = Something()
2305 ... thing.a
2306 ...
2307 Traceback (most recent call last):
2308 ...
2309 AttributeError: Mock object has no attribute 'a'
2310
2311There are a few different ways of resolving this problem. The easiest, but
2312not necessarily the least annoying, way is to simply set the required
Georg Brandl7ad3df62014-10-31 07:59:37 +01002313attributes on the mock after creation. Just because *autospec* doesn't allow
Michael Foorda9e6fb22012-03-28 14:36:02 +01002314you to fetch attributes that don't exist on the spec it doesn't prevent you
2315setting them:
2316
2317 >>> with patch('__main__.Something', autospec=True):
2318 ... thing = Something()
2319 ... thing.a = 33
2320 ...
2321
Georg Brandl7ad3df62014-10-31 07:59:37 +01002322There is a more aggressive version of both *spec* and *autospec* that *does*
Michael Foorda9e6fb22012-03-28 14:36:02 +01002323prevent you setting non-existent attributes. This is useful if you want to
2324ensure your code only *sets* valid attributes too, but obviously it prevents
2325this particular scenario:
2326
2327 >>> with patch('__main__.Something', autospec=True, spec_set=True):
2328 ... thing = Something()
2329 ... thing.a = 33
2330 ...
2331 Traceback (most recent call last):
2332 ...
2333 AttributeError: Mock object has no attribute 'a'
2334
2335Probably the best way of solving the problem is to add class attributes as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002336default values for instance members initialised in :meth:`__init__`. Note that if
2337you are only setting default attributes in :meth:`__init__` then providing them via
Michael Foorda9e6fb22012-03-28 14:36:02 +01002338class attributes (shared between instances of course) is faster too. e.g.
2339
2340.. code-block:: python
2341
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002342 class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002343 a = 33
2344
2345This brings up another issue. It is relatively common to provide a default
Georg Brandl7ad3df62014-10-31 07:59:37 +01002346value of ``None`` for members that will later be an object of a different type.
2347``None`` would be useless as a spec because it wouldn't let you access *any*
2348attributes or methods on it. As ``None`` is *never* going to be useful as a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002349spec, and probably indicates a member that will normally of some other type,
Georg Brandl7ad3df62014-10-31 07:59:37 +01002350autospec doesn't use a spec for members that are set to ``None``. These will
2351just be ordinary mocks (well - MagicMocks):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002352
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002353 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002354 ... member = None
2355 ...
2356 >>> mock = create_autospec(Something)
2357 >>> mock.member.foo.bar.baz()
2358 <MagicMock name='mock.member.foo.bar.baz()' id='...'>
2359
2360If modifying your production classes to add defaults isn't to your liking
2361then there are more options. One of these is simply to use an instance as the
2362spec rather than the class. The other is to create a subclass of the
2363production class and add the defaults to the subclass without affecting the
2364production class. Both of these require you to use an alternative object as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002365the spec. Thankfully :func:`patch` supports this - you can simply pass the
2366alternative object as the *autospec* argument:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002367
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002368 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002369 ... def __init__(self):
2370 ... self.a = 33
2371 ...
2372 >>> class SomethingForTest(Something):
2373 ... a = 33
2374 ...
2375 >>> p = patch('__main__.Something', autospec=SomethingForTest)
2376 >>> mock = p.start()
2377 >>> mock.a
2378 <NonCallableMagicMock name='Something.a' spec='int' id='...'>
2379
2380
2381.. [#] This only applies to classes or already instantiated objects. Calling
2382 a mocked class to create a mock instance *does not* create a real instance.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002383 It is only attribute lookups - along with calls to :func:`dir` - that are done.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002384
Mario Corchero552be9d2017-10-17 12:35:11 +01002385Sealing mocks
2386~~~~~~~~~~~~~
2387
2388.. function:: seal(mock)
2389
Miss Islington (bot)984a8002018-10-19 15:17:31 -07002390 Seal will disable the automatic creation of mocks when accessing an attribute of
2391 the mock being sealed or any of its attributes that are already mocks recursively.
Mario Corchero552be9d2017-10-17 12:35:11 +01002392
Miss Islington (bot)984a8002018-10-19 15:17:31 -07002393 If a mock instance with a name or a spec is assigned to an attribute
Paul Ganssle85ac7262018-01-06 08:25:34 -05002394 it won't be considered in the sealing chain. This allows one to prevent seal from
2395 fixing part of the mock object.
Mario Corchero552be9d2017-10-17 12:35:11 +01002396
2397 >>> mock = Mock()
2398 >>> mock.submock.attribute1 = 2
Miss Islington (bot)984a8002018-10-19 15:17:31 -07002399 >>> mock.not_submock = mock.Mock(name="sample_name")
Mario Corchero552be9d2017-10-17 12:35:11 +01002400 >>> seal(mock)
Miss Islington (bot)984a8002018-10-19 15:17:31 -07002401 >>> mock.new_attribute # This will raise AttributeError.
Mario Corchero552be9d2017-10-17 12:35:11 +01002402 >>> mock.submock.attribute2 # This will raise AttributeError.
2403 >>> mock.not_submock.attribute2 # This won't raise.
2404
2405 .. versionadded:: 3.7