blob: c011e54e3e73ec6d8462fcb27a72698d3242a0a9 [file] [log] [blame]
Andrew Svetlov7ea6f702012-10-31 11:29:52 +02001
Michael Foord944e02d2012-03-25 23:12:55 +01002:mod:`unittest.mock` --- mock object library
3============================================
4
5.. module:: unittest.mock
6 :synopsis: Mock object library.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04007
Michael Foord944e02d2012-03-25 23:12:55 +01008.. moduleauthor:: Michael Foord <michael@python.org>
9.. currentmodule:: unittest.mock
10
11.. versionadded:: 3.3
12
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040013**Source code:** :source:`Lib/unittest/mock.py`
14
15--------------
16
Michael Foord944e02d2012-03-25 23:12:55 +010017:mod:`unittest.mock` is a library for testing in Python. It allows you to
18replace parts of your system under test with mock objects and make assertions
19about how they have been used.
20
Georg Brandl7ad3df62014-10-31 07:59:37 +010021:mod:`unittest.mock` provides a core :class:`Mock` class removing the need to
Michael Foord944e02d2012-03-25 23:12:55 +010022create a host of stubs throughout your test suite. After performing an
23action, you can make assertions about which methods / attributes were used
24and arguments they were called with. You can also specify return values and
25set needed attributes in the normal way.
26
27Additionally, mock provides a :func:`patch` decorator that handles patching
28module and class level attributes within the scope of a test, along with
29:const:`sentinel` for creating unique objects. See the `quick guide`_ for
30some examples of how to use :class:`Mock`, :class:`MagicMock` and
31:func:`patch`.
32
33Mock is very easy to use and is designed for use with :mod:`unittest`. Mock
Georg Brandl7ad3df62014-10-31 07:59:37 +010034is based on the 'action -> assertion' pattern instead of 'record -> replay'
Michael Foord944e02d2012-03-25 23:12:55 +010035used by many mocking frameworks.
36
Georg Brandl7ad3df62014-10-31 07:59:37 +010037There is a backport of :mod:`unittest.mock` for earlier versions of Python,
Stéphane Wirtel19177fb2018-05-15 20:58:35 +020038available as `mock on PyPI <https://pypi.org/project/mock>`_.
Michael Foord944e02d2012-03-25 23:12:55 +010039
Michael Foord944e02d2012-03-25 23:12:55 +010040
41Quick Guide
42-----------
43
Stéphane Wirtel859c0682018-10-12 09:51:05 +020044.. testsetup::
45
46 class ProductionClass:
47 def method(self, a, b, c):
48 pass
49
50 class SomeClass:
51 @staticmethod
52 def static_method(args):
53 return args
54
55 @classmethod
56 def class_method(cls, args):
57 return args
58
59
Michael Foord944e02d2012-03-25 23:12:55 +010060:class:`Mock` and :class:`MagicMock` objects create all attributes and
61methods as you access them and store details of how they have been used. You
62can configure them, to specify return values or limit what attributes are
63available, and then make assertions about how they have been used:
64
65 >>> from unittest.mock import MagicMock
66 >>> thing = ProductionClass()
67 >>> thing.method = MagicMock(return_value=3)
68 >>> thing.method(3, 4, 5, key='value')
69 3
70 >>> thing.method.assert_called_with(3, 4, 5, key='value')
71
72:attr:`side_effect` allows you to perform side effects, including raising an
73exception when a mock is called:
74
75 >>> mock = Mock(side_effect=KeyError('foo'))
76 >>> mock()
77 Traceback (most recent call last):
78 ...
79 KeyError: 'foo'
80
81 >>> values = {'a': 1, 'b': 2, 'c': 3}
82 >>> def side_effect(arg):
83 ... return values[arg]
84 ...
85 >>> mock.side_effect = side_effect
86 >>> mock('a'), mock('b'), mock('c')
87 (1, 2, 3)
88 >>> mock.side_effect = [5, 4, 3, 2, 1]
89 >>> mock(), mock(), mock()
90 (5, 4, 3)
91
92Mock has many other ways you can configure it and control its behaviour. For
Georg Brandl7ad3df62014-10-31 07:59:37 +010093example the *spec* argument configures the mock to take its specification
Michael Foord944e02d2012-03-25 23:12:55 +010094from another object. Attempting to access attributes or methods on the mock
Georg Brandl7ad3df62014-10-31 07:59:37 +010095that don't exist on the spec will fail with an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +010096
97The :func:`patch` decorator / context manager makes it easy to mock classes or
98objects in a module under test. The object you specify will be replaced with a
Stéphane Wirtel859c0682018-10-12 09:51:05 +020099mock (or other object) during the test and restored when the test ends::
Michael Foord944e02d2012-03-25 23:12:55 +0100100
101 >>> from unittest.mock import patch
102 >>> @patch('module.ClassName2')
103 ... @patch('module.ClassName1')
104 ... def test(MockClass1, MockClass2):
105 ... module.ClassName1()
106 ... module.ClassName2()
Michael Foord944e02d2012-03-25 23:12:55 +0100107 ... assert MockClass1 is module.ClassName1
108 ... assert MockClass2 is module.ClassName2
109 ... assert MockClass1.called
110 ... assert MockClass2.called
111 ...
112 >>> test()
113
114.. note::
115
116 When you nest patch decorators the mocks are passed in to the decorated
Andrés Delfino271818f2018-09-14 14:13:09 -0300117 function in the same order they applied (the normal *Python* order that
Michael Foord944e02d2012-03-25 23:12:55 +0100118 decorators are applied). This means from the bottom up, so in the example
Georg Brandl7ad3df62014-10-31 07:59:37 +0100119 above the mock for ``module.ClassName1`` is passed in first.
Michael Foord944e02d2012-03-25 23:12:55 +0100120
Georg Brandl7ad3df62014-10-31 07:59:37 +0100121 With :func:`patch` it matters that you patch objects in the namespace where they
Michael Foord944e02d2012-03-25 23:12:55 +0100122 are looked up. This is normally straightforward, but for a quick guide
123 read :ref:`where to patch <where-to-patch>`.
124
Georg Brandl7ad3df62014-10-31 07:59:37 +0100125As well as a decorator :func:`patch` can be used as a context manager in a with
Michael Foord944e02d2012-03-25 23:12:55 +0100126statement:
127
128 >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
129 ... thing = ProductionClass()
130 ... thing.method(1, 2, 3)
131 ...
132 >>> mock_method.assert_called_once_with(1, 2, 3)
133
134
135There is also :func:`patch.dict` for setting values in a dictionary just
136during a scope and restoring the dictionary to its original state when the test
137ends:
138
139 >>> foo = {'key': 'value'}
140 >>> original = foo.copy()
141 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
142 ... assert foo == {'newkey': 'newvalue'}
143 ...
144 >>> assert foo == original
145
146Mock supports the mocking of Python :ref:`magic methods <magic-methods>`. The
147easiest way of using magic methods is with the :class:`MagicMock` class. It
148allows you to do things like:
149
150 >>> mock = MagicMock()
151 >>> mock.__str__.return_value = 'foobarbaz'
152 >>> str(mock)
153 'foobarbaz'
154 >>> mock.__str__.assert_called_with()
155
156Mock allows you to assign functions (or other Mock instances) to magic methods
Georg Brandl7ad3df62014-10-31 07:59:37 +0100157and they will be called appropriately. The :class:`MagicMock` class is just a Mock
Michael Foord944e02d2012-03-25 23:12:55 +0100158variant that has all of the magic methods pre-created for you (well, all the
159useful ones anyway).
160
161The following is an example of using magic methods with the ordinary Mock
162class:
163
164 >>> mock = Mock()
165 >>> mock.__str__ = Mock(return_value='wheeeeee')
166 >>> str(mock)
167 'wheeeeee'
168
169For ensuring that the mock objects in your tests have the same api as the
170objects they are replacing, you can use :ref:`auto-speccing <auto-speccing>`.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100171Auto-speccing can be done through the *autospec* argument to patch, or the
Michael Foord944e02d2012-03-25 23:12:55 +0100172:func:`create_autospec` function. Auto-speccing creates mock objects that
173have the same attributes and methods as the objects they are replacing, and
174any functions and methods (including constructors) have the same call
175signature as the real object.
176
177This ensures that your mocks will fail in the same way as your production
178code if they are used incorrectly:
179
180 >>> from unittest.mock import create_autospec
181 >>> def function(a, b, c):
182 ... pass
183 ...
184 >>> mock_function = create_autospec(function, return_value='fishy')
185 >>> mock_function(1, 2, 3)
186 'fishy'
187 >>> mock_function.assert_called_once_with(1, 2, 3)
188 >>> mock_function('wrong arguments')
189 Traceback (most recent call last):
190 ...
191 TypeError: <lambda>() takes exactly 3 arguments (1 given)
192
Georg Brandl7ad3df62014-10-31 07:59:37 +0100193:func:`create_autospec` can also be used on classes, where it copies the signature of
194the ``__init__`` method, and on callable objects where it copies the signature of
195the ``__call__`` method.
Michael Foord944e02d2012-03-25 23:12:55 +0100196
197
198
199The Mock Class
200--------------
201
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200202.. testsetup::
203
204 import unittest
205 from unittest.mock import sentinel, DEFAULT, ANY
206 from unittest.mock import patch, call, Mock, MagicMock, PropertyMock
207 from unittest.mock import mock_open
Michael Foord944e02d2012-03-25 23:12:55 +0100208
Georg Brandl7ad3df62014-10-31 07:59:37 +0100209:class:`Mock` is a flexible mock object intended to replace the use of stubs and
Michael Foord944e02d2012-03-25 23:12:55 +0100210test doubles throughout your code. Mocks are callable and create attributes as
211new mocks when you access them [#]_. Accessing the same attribute will always
212return the same mock. Mocks record how you use them, allowing you to make
213assertions about what your code has done to them.
214
Georg Brandl7ad3df62014-10-31 07:59:37 +0100215:class:`MagicMock` is a subclass of :class:`Mock` with all the magic methods
Michael Foord944e02d2012-03-25 23:12:55 +0100216pre-created and ready to use. There are also non-callable variants, useful
217when you are mocking out objects that aren't callable:
218:class:`NonCallableMock` and :class:`NonCallableMagicMock`
219
220The :func:`patch` decorators makes it easy to temporarily replace classes
Georg Brandl7ad3df62014-10-31 07:59:37 +0100221in a particular module with a :class:`Mock` object. By default :func:`patch` will create
222a :class:`MagicMock` for you. You can specify an alternative class of :class:`Mock` using
223the *new_callable* argument to :func:`patch`.
Michael Foord944e02d2012-03-25 23:12:55 +0100224
225
Kushal Das8c145342014-04-16 23:32:21 +0530226.. class:: Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs)
Michael Foord944e02d2012-03-25 23:12:55 +0100227
Georg Brandl7ad3df62014-10-31 07:59:37 +0100228 Create a new :class:`Mock` object. :class:`Mock` takes several optional arguments
Michael Foord944e02d2012-03-25 23:12:55 +0100229 that specify the behaviour of the Mock object:
230
Georg Brandl7ad3df62014-10-31 07:59:37 +0100231 * *spec*: This can be either a list of strings or an existing object (a
Michael Foord944e02d2012-03-25 23:12:55 +0100232 class or instance) that acts as the specification for the mock object. If
233 you pass in an object then a list of strings is formed by calling dir on
234 the object (excluding unsupported magic attributes and methods).
Georg Brandl7ad3df62014-10-31 07:59:37 +0100235 Accessing any attribute not in this list will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100236
Georg Brandl7ad3df62014-10-31 07:59:37 +0100237 If *spec* is an object (rather than a list of strings) then
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300238 :attr:`~instance.__class__` returns the class of the spec object. This
Georg Brandl7ad3df62014-10-31 07:59:37 +0100239 allows mocks to pass :func:`isinstance` tests.
Michael Foord944e02d2012-03-25 23:12:55 +0100240
Georg Brandl7ad3df62014-10-31 07:59:37 +0100241 * *spec_set*: A stricter variant of *spec*. If used, attempting to *set*
Michael Foord944e02d2012-03-25 23:12:55 +0100242 or get an attribute on the mock that isn't on the object passed as
Georg Brandl7ad3df62014-10-31 07:59:37 +0100243 *spec_set* will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100244
Georg Brandl7ad3df62014-10-31 07:59:37 +0100245 * *side_effect*: A function to be called whenever the Mock is called. See
Michael Foord944e02d2012-03-25 23:12:55 +0100246 the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or
247 dynamically changing return values. The function is called with the same
248 arguments as the mock, and unless it returns :data:`DEFAULT`, the return
249 value of this function is used as the return value.
250
Georg Brandl7ad3df62014-10-31 07:59:37 +0100251 Alternatively *side_effect* can be an exception class or instance. In
Michael Foord944e02d2012-03-25 23:12:55 +0100252 this case the exception will be raised when the mock is called.
253
Georg Brandl7ad3df62014-10-31 07:59:37 +0100254 If *side_effect* is an iterable then each call to the mock will return
Michael Foord944e02d2012-03-25 23:12:55 +0100255 the next value from the iterable.
256
Georg Brandl7ad3df62014-10-31 07:59:37 +0100257 A *side_effect* can be cleared by setting it to ``None``.
Michael Foord944e02d2012-03-25 23:12:55 +0100258
Georg Brandl7ad3df62014-10-31 07:59:37 +0100259 * *return_value*: The value returned when the mock is called. By default
Michael Foord944e02d2012-03-25 23:12:55 +0100260 this is a new Mock (created on first access). See the
261 :attr:`return_value` attribute.
262
Georg Brandl7ad3df62014-10-31 07:59:37 +0100263 * *unsafe*: By default if any attribute starts with *assert* or
264 *assret* will raise an :exc:`AttributeError`. Passing ``unsafe=True``
265 will allow access to these attributes.
Kushal Das8c145342014-04-16 23:32:21 +0530266
267 .. versionadded:: 3.5
268
Serhiy Storchakaecf41da2016-10-19 16:29:26 +0300269 * *wraps*: Item for the mock object to wrap. If *wraps* is not ``None`` then
Michael Foord944e02d2012-03-25 23:12:55 +0100270 calling the Mock will pass the call through to the wrapped object
Michael Foord0682a0c2012-04-13 20:51:20 +0100271 (returning the real result). Attribute access on the mock will return a
272 Mock object that wraps the corresponding attribute of the wrapped
273 object (so attempting to access an attribute that doesn't exist will
Georg Brandl7ad3df62014-10-31 07:59:37 +0100274 raise an :exc:`AttributeError`).
Michael Foord944e02d2012-03-25 23:12:55 +0100275
Georg Brandl7ad3df62014-10-31 07:59:37 +0100276 If the mock has an explicit *return_value* set then calls are not passed
277 to the wrapped object and the *return_value* is returned instead.
Michael Foord944e02d2012-03-25 23:12:55 +0100278
Georg Brandl7ad3df62014-10-31 07:59:37 +0100279 * *name*: If the mock has a name then it will be used in the repr of the
Michael Foord944e02d2012-03-25 23:12:55 +0100280 mock. This can be useful for debugging. The name is propagated to child
281 mocks.
282
283 Mocks can also be called with arbitrary keyword arguments. These will be
284 used to set attributes on the mock after it is created. See the
285 :meth:`configure_mock` method for details.
286
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100287 .. method:: assert_called(*args, **kwargs)
288
289 Assert that the mock was called at least once.
290
291 >>> mock = Mock()
292 >>> mock.method()
293 <Mock name='mock.method()' id='...'>
294 >>> mock.method.assert_called()
295
296 .. versionadded:: 3.6
297
298 .. method:: assert_called_once(*args, **kwargs)
299
300 Assert that the mock was called exactly once.
301
302 >>> mock = Mock()
303 >>> mock.method()
304 <Mock name='mock.method()' id='...'>
305 >>> mock.method.assert_called_once()
306 >>> mock.method()
307 <Mock name='mock.method()' id='...'>
308 >>> mock.method.assert_called_once()
309 Traceback (most recent call last):
310 ...
311 AssertionError: Expected 'method' to have been called once. Called 2 times.
312
313 .. versionadded:: 3.6
314
Michael Foord944e02d2012-03-25 23:12:55 +0100315
316 .. method:: assert_called_with(*args, **kwargs)
317
318 This method is a convenient way of asserting that calls are made in a
319 particular way:
320
321 >>> mock = Mock()
322 >>> mock.method(1, 2, 3, test='wow')
323 <Mock name='mock.method()' id='...'>
324 >>> mock.method.assert_called_with(1, 2, 3, test='wow')
325
Michael Foord944e02d2012-03-25 23:12:55 +0100326 .. method:: assert_called_once_with(*args, **kwargs)
327
Arne de Laat324c5d82017-02-23 15:57:25 +0100328 Assert that the mock was called exactly once and that that call was
329 with the specified arguments.
Michael Foord944e02d2012-03-25 23:12:55 +0100330
331 >>> mock = Mock(return_value=None)
332 >>> mock('foo', bar='baz')
333 >>> mock.assert_called_once_with('foo', bar='baz')
Arne de Laat324c5d82017-02-23 15:57:25 +0100334 >>> mock('other', bar='values')
335 >>> mock.assert_called_once_with('other', bar='values')
Michael Foord944e02d2012-03-25 23:12:55 +0100336 Traceback (most recent call last):
337 ...
Michael Foord28d591c2012-09-28 16:15:22 +0100338 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foord944e02d2012-03-25 23:12:55 +0100339
340
341 .. method:: assert_any_call(*args, **kwargs)
342
343 assert the mock has been called with the specified arguments.
344
345 The assert passes if the mock has *ever* been called, unlike
346 :meth:`assert_called_with` and :meth:`assert_called_once_with` that
Arne de Laat324c5d82017-02-23 15:57:25 +0100347 only pass if the call is the most recent one, and in the case of
348 :meth:`assert_called_once_with` it must also be the only call.
Michael Foord944e02d2012-03-25 23:12:55 +0100349
350 >>> mock = Mock(return_value=None)
351 >>> mock(1, 2, arg='thing')
352 >>> mock('some', 'thing', 'else')
353 >>> mock.assert_any_call(1, 2, arg='thing')
354
355
356 .. method:: assert_has_calls(calls, any_order=False)
357
358 assert the mock has been called with the specified calls.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100359 The :attr:`mock_calls` list is checked for the calls.
Michael Foord944e02d2012-03-25 23:12:55 +0100360
Georg Brandl7ad3df62014-10-31 07:59:37 +0100361 If *any_order* is false (the default) then the calls must be
Michael Foord944e02d2012-03-25 23:12:55 +0100362 sequential. There can be extra calls before or after the
363 specified calls.
364
Georg Brandl7ad3df62014-10-31 07:59:37 +0100365 If *any_order* is true then the calls can be in any order, but
Michael Foord944e02d2012-03-25 23:12:55 +0100366 they must all appear in :attr:`mock_calls`.
367
368 >>> mock = Mock(return_value=None)
369 >>> mock(1)
370 >>> mock(2)
371 >>> mock(3)
372 >>> mock(4)
373 >>> calls = [call(2), call(3)]
374 >>> mock.assert_has_calls(calls)
375 >>> calls = [call(4), call(2), call(3)]
376 >>> mock.assert_has_calls(calls, any_order=True)
377
Berker Peksagebf9fd32016-07-17 15:26:46 +0300378 .. method:: assert_not_called()
Kushal Das8af9db32014-04-17 01:36:14 +0530379
380 Assert the mock was never called.
381
382 >>> m = Mock()
383 >>> m.hello.assert_not_called()
384 >>> obj = m.hello()
385 >>> m.hello.assert_not_called()
386 Traceback (most recent call last):
387 ...
388 AssertionError: Expected 'hello' to not have been called. Called 1 times.
389
390 .. versionadded:: 3.5
391
Michael Foord944e02d2012-03-25 23:12:55 +0100392
Kushal Das9cd39a12016-06-02 10:20:16 -0700393 .. method:: reset_mock(*, return_value=False, side_effect=False)
Michael Foord944e02d2012-03-25 23:12:55 +0100394
395 The reset_mock method resets all the call attributes on a mock object:
396
397 >>> mock = Mock(return_value=None)
398 >>> mock('hello')
399 >>> mock.called
400 True
401 >>> mock.reset_mock()
402 >>> mock.called
403 False
404
Kushal Das9cd39a12016-06-02 10:20:16 -0700405 .. versionchanged:: 3.6
406 Added two keyword only argument to the reset_mock function.
407
Michael Foord944e02d2012-03-25 23:12:55 +0100408 This can be useful where you want to make a series of assertions that
Georg Brandl7ad3df62014-10-31 07:59:37 +0100409 reuse the same object. Note that :meth:`reset_mock` *doesn't* clear the
Michael Foord944e02d2012-03-25 23:12:55 +0100410 return value, :attr:`side_effect` or any child attributes you have
Kushal Das9cd39a12016-06-02 10:20:16 -0700411 set using normal assignment by default. In case you want to reset
412 *return_value* or :attr:`side_effect`, then pass the corresponding
413 parameter as ``True``. Child mocks and the return value mock
Michael Foord944e02d2012-03-25 23:12:55 +0100414 (if any) are reset as well.
415
Kushal Das9cd39a12016-06-02 10:20:16 -0700416 .. note:: *return_value*, and :attr:`side_effect` are keyword only
417 argument.
418
Michael Foord944e02d2012-03-25 23:12:55 +0100419
420 .. method:: mock_add_spec(spec, spec_set=False)
421
Georg Brandl7ad3df62014-10-31 07:59:37 +0100422 Add a spec to a mock. *spec* can either be an object or a
423 list of strings. Only attributes on the *spec* can be fetched as
Michael Foord944e02d2012-03-25 23:12:55 +0100424 attributes from the mock.
425
Georg Brandl7ad3df62014-10-31 07:59:37 +0100426 If *spec_set* is true then only attributes on the spec can be set.
Michael Foord944e02d2012-03-25 23:12:55 +0100427
428
429 .. method:: attach_mock(mock, attribute)
430
431 Attach a mock as an attribute of this one, replacing its name and
432 parent. Calls to the attached mock will be recorded in the
433 :attr:`method_calls` and :attr:`mock_calls` attributes of this one.
434
435
436 .. method:: configure_mock(**kwargs)
437
438 Set attributes on the mock through keyword arguments.
439
440 Attributes plus return values and side effects can be set on child
441 mocks using standard dot notation and unpacking a dictionary in the
442 method call:
443
444 >>> mock = Mock()
445 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
446 >>> mock.configure_mock(**attrs)
447 >>> mock.method()
448 3
449 >>> mock.other()
450 Traceback (most recent call last):
451 ...
452 KeyError
453
454 The same thing can be achieved in the constructor call to mocks:
455
456 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
457 >>> mock = Mock(some_attribute='eggs', **attrs)
458 >>> mock.some_attribute
459 'eggs'
460 >>> mock.method()
461 3
462 >>> mock.other()
463 Traceback (most recent call last):
464 ...
465 KeyError
466
Georg Brandl7ad3df62014-10-31 07:59:37 +0100467 :meth:`configure_mock` exists to make it easier to do configuration
Michael Foord944e02d2012-03-25 23:12:55 +0100468 after the mock has been created.
469
470
471 .. method:: __dir__()
472
Georg Brandl7ad3df62014-10-31 07:59:37 +0100473 :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results.
474 For mocks with a *spec* this includes all the permitted attributes
Michael Foord944e02d2012-03-25 23:12:55 +0100475 for the mock.
476
477 See :data:`FILTER_DIR` for what this filtering does, and how to
478 switch it off.
479
480
481 .. method:: _get_child_mock(**kw)
482
483 Create the child mocks for attributes and return value.
484 By default child mocks will be the same type as the parent.
485 Subclasses of Mock may want to override this to customize the way
486 child mocks are made.
487
488 For non-callable mocks the callable variant will be used (rather than
489 any custom subclass).
490
491
492 .. attribute:: called
493
494 A boolean representing whether or not the mock object has been called:
495
496 >>> mock = Mock(return_value=None)
497 >>> mock.called
498 False
499 >>> mock()
500 >>> mock.called
501 True
502
503 .. attribute:: call_count
504
505 An integer telling you how many times the mock object has been called:
506
507 >>> mock = Mock(return_value=None)
508 >>> mock.call_count
509 0
510 >>> mock()
511 >>> mock()
512 >>> mock.call_count
513 2
514
515
516 .. attribute:: return_value
517
518 Set this to configure the value returned by calling the mock:
519
520 >>> mock = Mock()
521 >>> mock.return_value = 'fish'
522 >>> mock()
523 'fish'
524
525 The default return value is a mock object and you can configure it in
526 the normal way:
527
528 >>> mock = Mock()
529 >>> mock.return_value.attribute = sentinel.Attribute
530 >>> mock.return_value()
531 <Mock name='mock()()' id='...'>
532 >>> mock.return_value.assert_called_with()
533
Georg Brandl7ad3df62014-10-31 07:59:37 +0100534 :attr:`return_value` can also be set in the constructor:
Michael Foord944e02d2012-03-25 23:12:55 +0100535
536 >>> mock = Mock(return_value=3)
537 >>> mock.return_value
538 3
539 >>> mock()
540 3
541
542
543 .. attribute:: side_effect
544
545 This can either be a function to be called when the mock is called,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100546 an iterable or an exception (class or instance) to be raised.
Michael Foord944e02d2012-03-25 23:12:55 +0100547
548 If you pass in a function it will be called with same arguments as the
549 mock and unless the function returns the :data:`DEFAULT` singleton the
550 call to the mock will then return whatever the function returns. If the
551 function returns :data:`DEFAULT` then the mock will return its normal
Brett Cannon533f1ed2013-05-25 11:28:20 -0400552 value (from the :attr:`return_value`).
Michael Foord944e02d2012-03-25 23:12:55 +0100553
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100554 If you pass in an iterable, it is used to retrieve an iterator which
555 must yield a value on every call. This value can either be an exception
556 instance to be raised, or a value to be returned from the call to the
557 mock (:data:`DEFAULT` handling is identical to the function case).
558
Michael Foord944e02d2012-03-25 23:12:55 +0100559 An example of a mock that raises an exception (to test exception
560 handling of an API):
561
562 >>> mock = Mock()
563 >>> mock.side_effect = Exception('Boom!')
564 >>> mock()
565 Traceback (most recent call last):
566 ...
567 Exception: Boom!
568
Georg Brandl7ad3df62014-10-31 07:59:37 +0100569 Using :attr:`side_effect` to return a sequence of values:
Michael Foord944e02d2012-03-25 23:12:55 +0100570
571 >>> mock = Mock()
572 >>> mock.side_effect = [3, 2, 1]
573 >>> mock(), mock(), mock()
574 (3, 2, 1)
575
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100576 Using a callable:
Michael Foord944e02d2012-03-25 23:12:55 +0100577
578 >>> mock = Mock(return_value=3)
579 >>> def side_effect(*args, **kwargs):
580 ... return DEFAULT
581 ...
582 >>> mock.side_effect = side_effect
583 >>> mock()
584 3
585
Georg Brandl7ad3df62014-10-31 07:59:37 +0100586 :attr:`side_effect` can be set in the constructor. Here's an example that
Michael Foord944e02d2012-03-25 23:12:55 +0100587 adds one to the value the mock is called with and returns it:
588
589 >>> side_effect = lambda value: value + 1
590 >>> mock = Mock(side_effect=side_effect)
591 >>> mock(3)
592 4
593 >>> mock(-8)
594 -7
595
Georg Brandl7ad3df62014-10-31 07:59:37 +0100596 Setting :attr:`side_effect` to ``None`` clears it:
Michael Foord944e02d2012-03-25 23:12:55 +0100597
598 >>> m = Mock(side_effect=KeyError, return_value=3)
599 >>> m()
600 Traceback (most recent call last):
601 ...
602 KeyError
603 >>> m.side_effect = None
604 >>> m()
605 3
606
607
608 .. attribute:: call_args
609
Georg Brandl7ad3df62014-10-31 07:59:37 +0100610 This is either ``None`` (if the mock hasn't been called), or the
Michael Foord944e02d2012-03-25 23:12:55 +0100611 arguments that the mock was last called with. This will be in the
612 form of a tuple: the first member is any ordered arguments the mock
613 was called with (or an empty tuple) and the second member is any
614 keyword arguments (or an empty dictionary).
615
616 >>> mock = Mock(return_value=None)
Berker Peksag920f6db2015-09-10 21:41:15 +0300617 >>> print(mock.call_args)
Michael Foord944e02d2012-03-25 23:12:55 +0100618 None
619 >>> mock()
620 >>> mock.call_args
621 call()
622 >>> mock.call_args == ()
623 True
624 >>> mock(3, 4)
625 >>> mock.call_args
626 call(3, 4)
627 >>> mock.call_args == ((3, 4),)
628 True
629 >>> mock(3, 4, 5, key='fish', next='w00t!')
630 >>> mock.call_args
631 call(3, 4, 5, key='fish', next='w00t!')
632
Georg Brandl7ad3df62014-10-31 07:59:37 +0100633 :attr:`call_args`, along with members of the lists :attr:`call_args_list`,
Michael Foord944e02d2012-03-25 23:12:55 +0100634 :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects.
635 These are tuples, so they can be unpacked to get at the individual
636 arguments and make more complex assertions. See
637 :ref:`calls as tuples <calls-as-tuples>`.
638
639
640 .. attribute:: call_args_list
641
642 This is a list of all the calls made to the mock object in sequence
643 (so the length of the list is the number of times it has been
644 called). Before any calls have been made it is an empty list. The
645 :data:`call` object can be used for conveniently constructing lists of
Georg Brandl7ad3df62014-10-31 07:59:37 +0100646 calls to compare with :attr:`call_args_list`.
Michael Foord944e02d2012-03-25 23:12:55 +0100647
648 >>> mock = Mock(return_value=None)
649 >>> mock()
650 >>> mock(3, 4)
651 >>> mock(key='fish', next='w00t!')
652 >>> mock.call_args_list
653 [call(), call(3, 4), call(key='fish', next='w00t!')]
654 >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
655 >>> mock.call_args_list == expected
656 True
657
Georg Brandl7ad3df62014-10-31 07:59:37 +0100658 Members of :attr:`call_args_list` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100659 unpacked as tuples to get at the individual arguments. See
660 :ref:`calls as tuples <calls-as-tuples>`.
661
662
663 .. attribute:: method_calls
664
665 As well as tracking calls to themselves, mocks also track calls to
666 methods and attributes, and *their* methods and attributes:
667
668 >>> mock = Mock()
669 >>> mock.method()
670 <Mock name='mock.method()' id='...'>
671 >>> mock.property.method.attribute()
672 <Mock name='mock.property.method.attribute()' id='...'>
673 >>> mock.method_calls
674 [call.method(), call.property.method.attribute()]
675
Georg Brandl7ad3df62014-10-31 07:59:37 +0100676 Members of :attr:`method_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100677 unpacked as tuples to get at the individual arguments. See
678 :ref:`calls as tuples <calls-as-tuples>`.
679
680
681 .. attribute:: mock_calls
682
Georg Brandl7ad3df62014-10-31 07:59:37 +0100683 :attr:`mock_calls` records *all* calls to the mock object, its methods,
684 magic methods *and* return value mocks.
Michael Foord944e02d2012-03-25 23:12:55 +0100685
686 >>> mock = MagicMock()
687 >>> result = mock(1, 2, 3)
688 >>> mock.first(a=3)
689 <MagicMock name='mock.first()' id='...'>
690 >>> mock.second()
691 <MagicMock name='mock.second()' id='...'>
692 >>> int(mock)
693 1
694 >>> result(1)
695 <MagicMock name='mock()()' id='...'>
696 >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
697 ... call.__int__(), call()(1)]
698 >>> mock.mock_calls == expected
699 True
700
Georg Brandl7ad3df62014-10-31 07:59:37 +0100701 Members of :attr:`mock_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100702 unpacked as tuples to get at the individual arguments. See
703 :ref:`calls as tuples <calls-as-tuples>`.
704
Chris Withers8ca0fa92018-12-03 21:31:37 +0000705 .. note::
706
707 The way :attr:`mock_calls` are recorded means that where nested
708 calls are made, the parameters of ancestor calls are not recorded
709 and so will always compare equal:
710
711 >>> mock = MagicMock()
712 >>> mock.top(a=3).bottom()
713 <MagicMock name='mock.top().bottom()' id='...'>
714 >>> mock.mock_calls
715 [call.top(a=3), call.top().bottom()]
716 >>> mock.mock_calls[-1] == call.top(a=-1).bottom()
717 True
Michael Foord944e02d2012-03-25 23:12:55 +0100718
719 .. attribute:: __class__
720
Georg Brandl7ad3df62014-10-31 07:59:37 +0100721 Normally the :attr:`__class__` attribute of an object will return its type.
722 For a mock object with a :attr:`spec`, ``__class__`` returns the spec class
723 instead. This allows mock objects to pass :func:`isinstance` tests for the
Michael Foord944e02d2012-03-25 23:12:55 +0100724 object they are replacing / masquerading as:
725
726 >>> mock = Mock(spec=3)
727 >>> isinstance(mock, int)
728 True
729
Georg Brandl7ad3df62014-10-31 07:59:37 +0100730 :attr:`__class__` is assignable to, this allows a mock to pass an
731 :func:`isinstance` check without forcing you to use a spec:
Michael Foord944e02d2012-03-25 23:12:55 +0100732
733 >>> mock = Mock()
734 >>> mock.__class__ = dict
735 >>> isinstance(mock, dict)
736 True
737
738.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
739
Georg Brandl7ad3df62014-10-31 07:59:37 +0100740 A non-callable version of :class:`Mock`. The constructor parameters have the same
741 meaning of :class:`Mock`, with the exception of *return_value* and *side_effect*
Michael Foord944e02d2012-03-25 23:12:55 +0100742 which have no meaning on a non-callable mock.
743
Georg Brandl7ad3df62014-10-31 07:59:37 +0100744Mock objects that use a class or an instance as a :attr:`spec` or
745:attr:`spec_set` are able to pass :func:`isinstance` tests:
Michael Foord944e02d2012-03-25 23:12:55 +0100746
747 >>> mock = Mock(spec=SomeClass)
748 >>> isinstance(mock, SomeClass)
749 True
750 >>> mock = Mock(spec_set=SomeClass())
751 >>> isinstance(mock, SomeClass)
752 True
753
Georg Brandl7ad3df62014-10-31 07:59:37 +0100754The :class:`Mock` classes have support for mocking magic methods. See :ref:`magic
Michael Foord944e02d2012-03-25 23:12:55 +0100755methods <magic-methods>` for the full details.
756
757The mock classes and the :func:`patch` decorators all take arbitrary keyword
Georg Brandl7ad3df62014-10-31 07:59:37 +0100758arguments for configuration. For the :func:`patch` decorators the keywords are
Michael Foord944e02d2012-03-25 23:12:55 +0100759passed to the constructor of the mock being created. The keyword arguments
760are for configuring attributes of the mock:
761
762 >>> m = MagicMock(attribute=3, other='fish')
763 >>> m.attribute
764 3
765 >>> m.other
766 'fish'
767
768The return value and side effect of child mocks can be set in the same way,
769using dotted notation. As you can't use dotted names directly in a call you
Georg Brandl7ad3df62014-10-31 07:59:37 +0100770have to create a dictionary and unpack it using ``**``:
Michael Foord944e02d2012-03-25 23:12:55 +0100771
772 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
773 >>> mock = Mock(some_attribute='eggs', **attrs)
774 >>> mock.some_attribute
775 'eggs'
776 >>> mock.method()
777 3
778 >>> mock.other()
779 Traceback (most recent call last):
780 ...
781 KeyError
782
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100783A callable mock which was created with a *spec* (or a *spec_set*) will
784introspect the specification object's signature when matching calls to
785the mock. Therefore, it can match the actual call's arguments regardless
786of whether they were passed positionally or by name::
787
788 >>> def f(a, b, c): pass
789 ...
790 >>> mock = Mock(spec=f)
791 >>> mock(1, 2, c=3)
792 <Mock name='mock()' id='140161580456576'>
793 >>> mock.assert_called_with(1, 2, 3)
794 >>> mock.assert_called_with(a=1, b=2, c=3)
795
796This applies to :meth:`~Mock.assert_called_with`,
797:meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and
798:meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also
799apply to method calls on the mock object.
800
801 .. versionchanged:: 3.4
802 Added signature introspection on specced and autospecced mock objects.
803
Michael Foord944e02d2012-03-25 23:12:55 +0100804
805.. class:: PropertyMock(*args, **kwargs)
806
807 A mock intended to be used as a property, or other descriptor, on a class.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100808 :class:`PropertyMock` provides :meth:`__get__` and :meth:`__set__` methods
809 so you can specify a return value when it is fetched.
Michael Foord944e02d2012-03-25 23:12:55 +0100810
Georg Brandl7ad3df62014-10-31 07:59:37 +0100811 Fetching a :class:`PropertyMock` instance from an object calls the mock, with
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200812 no args. Setting it calls the mock with the value being set. ::
Michael Foord944e02d2012-03-25 23:12:55 +0100813
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200814 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100815 ... @property
816 ... def foo(self):
817 ... return 'something'
818 ... @foo.setter
819 ... def foo(self, value):
820 ... pass
821 ...
822 >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
823 ... mock_foo.return_value = 'mockity-mock'
824 ... this_foo = Foo()
Berker Peksag920f6db2015-09-10 21:41:15 +0300825 ... print(this_foo.foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100826 ... this_foo.foo = 6
827 ...
828 mockity-mock
829 >>> mock_foo.mock_calls
830 [call(), call(6)]
831
Michael Foordc2870622012-04-13 16:57:22 +0100832Because of the way mock attributes are stored you can't directly attach a
Georg Brandl7ad3df62014-10-31 07:59:37 +0100833:class:`PropertyMock` to a mock object. Instead you can attach it to the mock type
Michael Foordc2870622012-04-13 16:57:22 +0100834object::
835
836 >>> m = MagicMock()
837 >>> p = PropertyMock(return_value=3)
838 >>> type(m).foo = p
839 >>> m.foo
840 3
841 >>> p.assert_called_once_with()
842
Michael Foord944e02d2012-03-25 23:12:55 +0100843
844Calling
845~~~~~~~
846
847Mock objects are callable. The call will return the value set as the
848:attr:`~Mock.return_value` attribute. The default return value is a new Mock
849object; it is created the first time the return value is accessed (either
850explicitly or by calling the Mock) - but it is stored and the same one
851returned each time.
852
853Calls made to the object will be recorded in the attributes
854like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
855
856If :attr:`~Mock.side_effect` is set then it will be called after the call has
Georg Brandl7ad3df62014-10-31 07:59:37 +0100857been recorded, so if :attr:`side_effect` raises an exception the call is still
Michael Foord944e02d2012-03-25 23:12:55 +0100858recorded.
859
860The simplest way to make a mock raise an exception when called is to make
861:attr:`~Mock.side_effect` an exception class or instance:
862
863 >>> m = MagicMock(side_effect=IndexError)
864 >>> m(1, 2, 3)
865 Traceback (most recent call last):
866 ...
867 IndexError
868 >>> m.mock_calls
869 [call(1, 2, 3)]
870 >>> m.side_effect = KeyError('Bang!')
871 >>> m('two', 'three', 'four')
872 Traceback (most recent call last):
873 ...
874 KeyError: 'Bang!'
875 >>> m.mock_calls
876 [call(1, 2, 3), call('two', 'three', 'four')]
877
Georg Brandl7ad3df62014-10-31 07:59:37 +0100878If :attr:`side_effect` is a function then whatever that function returns is what
879calls to the mock return. The :attr:`side_effect` function is called with the
Michael Foord944e02d2012-03-25 23:12:55 +0100880same arguments as the mock. This allows you to vary the return value of the
881call dynamically, based on the input:
882
883 >>> def side_effect(value):
884 ... return value + 1
885 ...
886 >>> m = MagicMock(side_effect=side_effect)
887 >>> m(1)
888 2
889 >>> m(2)
890 3
891 >>> m.mock_calls
892 [call(1), call(2)]
893
894If you want the mock to still return the default return value (a new mock), or
895any set return value, then there are two ways of doing this. Either return
Georg Brandl7ad3df62014-10-31 07:59:37 +0100896:attr:`mock.return_value` from inside :attr:`side_effect`, or return :data:`DEFAULT`:
Michael Foord944e02d2012-03-25 23:12:55 +0100897
898 >>> m = MagicMock()
899 >>> def side_effect(*args, **kwargs):
900 ... return m.return_value
901 ...
902 >>> m.side_effect = side_effect
903 >>> m.return_value = 3
904 >>> m()
905 3
906 >>> def side_effect(*args, **kwargs):
907 ... return DEFAULT
908 ...
909 >>> m.side_effect = side_effect
910 >>> m()
911 3
912
Georg Brandl7ad3df62014-10-31 07:59:37 +0100913To remove a :attr:`side_effect`, and return to the default behaviour, set the
914:attr:`side_effect` to ``None``:
Michael Foord944e02d2012-03-25 23:12:55 +0100915
916 >>> m = MagicMock(return_value=6)
917 >>> def side_effect(*args, **kwargs):
918 ... return 3
919 ...
920 >>> m.side_effect = side_effect
921 >>> m()
922 3
923 >>> m.side_effect = None
924 >>> m()
925 6
926
Georg Brandl7ad3df62014-10-31 07:59:37 +0100927The :attr:`side_effect` can also be any iterable object. Repeated calls to the mock
Michael Foord944e02d2012-03-25 23:12:55 +0100928will return values from the iterable (until the iterable is exhausted and
Georg Brandl7ad3df62014-10-31 07:59:37 +0100929a :exc:`StopIteration` is raised):
Michael Foord944e02d2012-03-25 23:12:55 +0100930
931 >>> m = MagicMock(side_effect=[1, 2, 3])
932 >>> m()
933 1
934 >>> m()
935 2
936 >>> m()
937 3
938 >>> m()
939 Traceback (most recent call last):
940 ...
941 StopIteration
942
Michael Foord2cd48732012-04-21 15:52:11 +0100943If any members of the iterable are exceptions they will be raised instead of
944returned::
945
946 >>> iterable = (33, ValueError, 66)
947 >>> m = MagicMock(side_effect=iterable)
948 >>> m()
949 33
950 >>> m()
951 Traceback (most recent call last):
952 ...
953 ValueError
954 >>> m()
955 66
956
Michael Foord944e02d2012-03-25 23:12:55 +0100957
958.. _deleting-attributes:
959
960Deleting Attributes
961~~~~~~~~~~~~~~~~~~~
962
963Mock objects create attributes on demand. This allows them to pretend to be
964objects of any type.
965
Georg Brandl7ad3df62014-10-31 07:59:37 +0100966You may want a mock object to return ``False`` to a :func:`hasattr` call, or raise an
967:exc:`AttributeError` when an attribute is fetched. You can do this by providing
968an object as a :attr:`spec` for a mock, but that isn't always convenient.
Michael Foord944e02d2012-03-25 23:12:55 +0100969
970You "block" attributes by deleting them. Once deleted, accessing an attribute
Georg Brandl7ad3df62014-10-31 07:59:37 +0100971will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100972
973 >>> mock = MagicMock()
974 >>> hasattr(mock, 'm')
975 True
976 >>> del mock.m
977 >>> hasattr(mock, 'm')
978 False
979 >>> del mock.f
980 >>> mock.f
981 Traceback (most recent call last):
982 ...
983 AttributeError: f
984
985
Michael Foordf5752302013-03-18 15:04:03 -0700986Mock names and the name attribute
987~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
988
989Since "name" is an argument to the :class:`Mock` constructor, if you want your
990mock object to have a "name" attribute you can't just pass it in at creation
991time. There are two alternatives. One option is to use
992:meth:`~Mock.configure_mock`::
993
994 >>> mock = MagicMock()
995 >>> mock.configure_mock(name='my_name')
996 >>> mock.name
997 'my_name'
998
999A simpler option is to simply set the "name" attribute after mock creation::
1000
1001 >>> mock = MagicMock()
1002 >>> mock.name = "foo"
1003
1004
Michael Foord944e02d2012-03-25 23:12:55 +01001005Attaching Mocks as Attributes
1006~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1007
1008When you attach a mock as an attribute of another mock (or as the return
1009value) it becomes a "child" of that mock. Calls to the child are recorded in
1010the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
1011parent. This is useful for configuring child mocks and then attaching them to
1012the parent, or for attaching mocks to a parent that records all calls to the
1013children and allows you to make assertions about the order of calls between
1014mocks:
1015
1016 >>> parent = MagicMock()
1017 >>> child1 = MagicMock(return_value=None)
1018 >>> child2 = MagicMock(return_value=None)
1019 >>> parent.child1 = child1
1020 >>> parent.child2 = child2
1021 >>> child1(1)
1022 >>> child2(2)
1023 >>> parent.mock_calls
1024 [call.child1(1), call.child2(2)]
1025
1026The exception to this is if the mock has a name. This allows you to prevent
1027the "parenting" if for some reason you don't want it to happen.
1028
1029 >>> mock = MagicMock()
1030 >>> not_a_child = MagicMock(name='not-a-child')
1031 >>> mock.attribute = not_a_child
1032 >>> mock.attribute()
1033 <MagicMock name='not-a-child()' id='...'>
1034 >>> mock.mock_calls
1035 []
1036
1037Mocks created for you by :func:`patch` are automatically given names. To
1038attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001039method::
Michael Foord944e02d2012-03-25 23:12:55 +01001040
1041 >>> thing1 = object()
1042 >>> thing2 = object()
1043 >>> parent = MagicMock()
1044 >>> with patch('__main__.thing1', return_value=None) as child1:
1045 ... with patch('__main__.thing2', return_value=None) as child2:
1046 ... parent.attach_mock(child1, 'child1')
1047 ... parent.attach_mock(child2, 'child2')
1048 ... child1('one')
1049 ... child2('two')
1050 ...
1051 >>> parent.mock_calls
1052 [call.child1('one'), call.child2('two')]
1053
1054
1055.. [#] The only exceptions are magic methods and attributes (those that have
1056 leading and trailing double underscores). Mock doesn't create these but
Georg Brandl7ad3df62014-10-31 07:59:37 +01001057 instead raises an :exc:`AttributeError`. This is because the interpreter
Michael Foord944e02d2012-03-25 23:12:55 +01001058 will often implicitly request these methods, and gets *very* confused to
1059 get a new Mock object when it expects a magic method. If you need magic
1060 method support see :ref:`magic methods <magic-methods>`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001061
1062
1063The patchers
Georg Brandlfb134382013-02-03 11:47:49 +01001064------------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001065
1066The patch decorators are used for patching objects only within the scope of
1067the function they decorate. They automatically handle the unpatching for you,
1068even if exceptions are raised. All of these functions can also be used in with
1069statements or as class decorators.
1070
1071
1072patch
Georg Brandlfb134382013-02-03 11:47:49 +01001073~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001074
1075.. note::
1076
Georg Brandl7ad3df62014-10-31 07:59:37 +01001077 :func:`patch` is straightforward to use. The key is to do the patching in the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001078 right namespace. See the section `where to patch`_.
1079
1080.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1081
Georg Brandl7ad3df62014-10-31 07:59:37 +01001082 :func:`patch` acts as a function decorator, class decorator or a context
1083 manager. Inside the body of the function or with statement, the *target*
1084 is patched with a *new* object. When the function/with statement exits
Michael Foord54b3db82012-03-28 15:08:08 +01001085 the patch is undone.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001086
Georg Brandl7ad3df62014-10-31 07:59:37 +01001087 If *new* is omitted, then the target is replaced with a
1088 :class:`MagicMock`. If :func:`patch` is used as a decorator and *new* is
Michael Foord54b3db82012-03-28 15:08:08 +01001089 omitted, the created mock is passed in as an extra argument to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001090 decorated function. If :func:`patch` is used as a context manager the created
Michael Foord54b3db82012-03-28 15:08:08 +01001091 mock is returned by the context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001092
Georg Brandl7ad3df62014-10-31 07:59:37 +01001093 *target* should be a string in the form ``'package.module.ClassName'``. The
1094 *target* is imported and the specified object replaced with the *new*
1095 object, so the *target* must be importable from the environment you are
1096 calling :func:`patch` from. The target is imported when the decorated function
Michael Foord54b3db82012-03-28 15:08:08 +01001097 is executed, not at decoration time.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001098
Georg Brandl7ad3df62014-10-31 07:59:37 +01001099 The *spec* and *spec_set* keyword arguments are passed to the :class:`MagicMock`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001100 if patch is creating one for you.
1101
Georg Brandl7ad3df62014-10-31 07:59:37 +01001102 In addition you can pass ``spec=True`` or ``spec_set=True``, which causes
Michael Foorda9e6fb22012-03-28 14:36:02 +01001103 patch to pass in the object being mocked as the spec/spec_set object.
1104
Georg Brandl7ad3df62014-10-31 07:59:37 +01001105 *new_callable* allows you to specify a different class, or callable object,
1106 that will be called to create the *new* object. By default :class:`MagicMock` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001107 used.
1108
Georg Brandl7ad3df62014-10-31 07:59:37 +01001109 A more powerful form of *spec* is *autospec*. If you set ``autospec=True``
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001110 then the mock will be created with a spec from the object being replaced.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001111 All attributes of the mock will also have the spec of the corresponding
1112 attribute of the object being replaced. Methods and functions being mocked
Georg Brandl7ad3df62014-10-31 07:59:37 +01001113 will have their arguments checked and will raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001114 called with the wrong signature. For mocks
1115 replacing a class, their return value (the 'instance') will have the same
1116 spec as the class. See the :func:`create_autospec` function and
1117 :ref:`auto-speccing`.
1118
Georg Brandl7ad3df62014-10-31 07:59:37 +01001119 Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001120 arbitrary object as the spec instead of the one being replaced.
1121
Pablo Galindod6acf172019-01-09 21:43:24 +00001122 By default :func:`patch` will fail to replace attributes that don't exist.
1123 If you pass in ``create=True``, and the attribute doesn't exist, patch will
1124 create the attribute for you when the patched function is called, and delete
1125 it again after the patched function has exited. This is useful for writing
1126 tests against attributes that your production code creates at runtime. It is
1127 off by default because it can be dangerous. With it switched on you can
1128 write passing tests against APIs that don't actually exist!
Michael Foorda9e6fb22012-03-28 14:36:02 +01001129
Michael Foordfddcfa22014-04-14 16:25:20 -04001130 .. note::
1131
1132 .. versionchanged:: 3.5
1133 If you are patching builtins in a module then you don't
Georg Brandl7ad3df62014-10-31 07:59:37 +01001134 need to pass ``create=True``, it will be added by default.
Michael Foordfddcfa22014-04-14 16:25:20 -04001135
Georg Brandl7ad3df62014-10-31 07:59:37 +01001136 Patch can be used as a :class:`TestCase` class decorator. It works by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001137 decorating each test method in the class. This reduces the boilerplate
Georg Brandl7ad3df62014-10-31 07:59:37 +01001138 code when your test methods share a common patchings set. :func:`patch` finds
1139 tests by looking for method names that start with ``patch.TEST_PREFIX``.
1140 By default this is ``'test'``, which matches the way :mod:`unittest` finds tests.
1141 You can specify an alternative prefix by setting ``patch.TEST_PREFIX``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001142
1143 Patch can be used as a context manager, with the with statement. Here the
1144 patching applies to the indented block after the with statement. If you
1145 use "as" then the patched object will be bound to the name after the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001146 "as"; very useful if :func:`patch` is creating a mock object for you.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001147
Georg Brandl7ad3df62014-10-31 07:59:37 +01001148 :func:`patch` takes arbitrary keyword arguments. These will be passed to
1149 the :class:`Mock` (or *new_callable*) on construction.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001150
Georg Brandl7ad3df62014-10-31 07:59:37 +01001151 ``patch.dict(...)``, ``patch.multiple(...)`` and ``patch.object(...)`` are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001152 available for alternate use-cases.
1153
Georg Brandl7ad3df62014-10-31 07:59:37 +01001154:func:`patch` as function decorator, creating the mock for you and passing it into
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001155the decorated function::
Michael Foord90155362012-03-28 15:32:08 +01001156
1157 >>> @patch('__main__.SomeClass')
Michael Foord324b58b2012-03-28 15:49:08 +01001158 ... def function(normal_argument, mock_class):
Michael Foord90155362012-03-28 15:32:08 +01001159 ... print(mock_class is SomeClass)
1160 ...
Michael Foord324b58b2012-03-28 15:49:08 +01001161 >>> function(None)
Michael Foord90155362012-03-28 15:32:08 +01001162 True
Michael Foorda9e6fb22012-03-28 14:36:02 +01001163
Georg Brandl7ad3df62014-10-31 07:59:37 +01001164Patching a class replaces the class with a :class:`MagicMock` *instance*. If the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001165class is instantiated in the code under test then it will be the
1166:attr:`~Mock.return_value` of the mock that will be used.
1167
1168If the class is instantiated multiple times you could use
1169:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
Georg Brandl7ad3df62014-10-31 07:59:37 +01001170can set the *return_value* to be anything you want.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001171
1172To configure return values on methods of *instances* on the patched class
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001173you must do this on the :attr:`return_value`. For example::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001174
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001175 >>> class Class:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001176 ... def method(self):
1177 ... pass
1178 ...
1179 >>> with patch('__main__.Class') as MockClass:
1180 ... instance = MockClass.return_value
1181 ... instance.method.return_value = 'foo'
1182 ... assert Class() is instance
1183 ... assert Class().method() == 'foo'
1184 ...
1185
Georg Brandl7ad3df62014-10-31 07:59:37 +01001186If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001187return value of the created mock will have the same spec. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001188
1189 >>> Original = Class
1190 >>> patcher = patch('__main__.Class', spec=True)
1191 >>> MockClass = patcher.start()
1192 >>> instance = MockClass()
1193 >>> assert isinstance(instance, Original)
1194 >>> patcher.stop()
1195
Georg Brandl7ad3df62014-10-31 07:59:37 +01001196The *new_callable* argument is useful where you want to use an alternative
Michael Foorda9e6fb22012-03-28 14:36:02 +01001197class to the default :class:`MagicMock` for the created mock. For example, if
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001198you wanted a :class:`NonCallableMock` to be used::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001199
1200 >>> thing = object()
1201 >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
1202 ... assert thing is mock_thing
1203 ... thing()
1204 ...
1205 Traceback (most recent call last):
1206 ...
1207 TypeError: 'NonCallableMock' object is not callable
1208
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001209Another use case might be to replace an object with an :class:`io.StringIO` instance::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001210
Serhiy Storchakae79be872013-08-17 00:09:55 +03001211 >>> from io import StringIO
Michael Foorda9e6fb22012-03-28 14:36:02 +01001212 >>> def foo():
Berker Peksag920f6db2015-09-10 21:41:15 +03001213 ... print('Something')
Michael Foorda9e6fb22012-03-28 14:36:02 +01001214 ...
1215 >>> @patch('sys.stdout', new_callable=StringIO)
1216 ... def test(mock_stdout):
1217 ... foo()
1218 ... assert mock_stdout.getvalue() == 'Something\n'
1219 ...
1220 >>> test()
1221
Georg Brandl7ad3df62014-10-31 07:59:37 +01001222When :func:`patch` is creating a mock for you, it is common that the first thing
Michael Foorda9e6fb22012-03-28 14:36:02 +01001223you need to do is to configure the mock. Some of that configuration can be done
1224in the call to patch. Any arbitrary keywords you pass into the call will be
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001225used to set attributes on the created mock::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001226
1227 >>> patcher = patch('__main__.thing', first='one', second='two')
1228 >>> mock_thing = patcher.start()
1229 >>> mock_thing.first
1230 'one'
1231 >>> mock_thing.second
1232 'two'
1233
1234As well as attributes on the created mock attributes, like the
1235:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
1236also be configured. These aren't syntactically valid to pass in directly as
1237keyword arguments, but a dictionary with these as keys can still be expanded
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001238into a :func:`patch` call using ``**``::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001239
1240 >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
1241 >>> patcher = patch('__main__.thing', **config)
1242 >>> mock_thing = patcher.start()
1243 >>> mock_thing.method()
1244 3
1245 >>> mock_thing.other()
1246 Traceback (most recent call last):
1247 ...
1248 KeyError
1249
Pablo Galindod6acf172019-01-09 21:43:24 +00001250By default, attempting to patch a function in a module (or a method or an
1251attribute in a class) that does not exist will fail with :exc:`AttributeError`::
1252
1253 >>> @patch('sys.non_existing_attribute', 42)
1254 ... def test():
1255 ... assert sys.non_existing_attribute == 42
1256 ...
1257 >>> test()
1258 Traceback (most recent call last):
1259 ...
1260 AttributeError: <module 'sys' (built-in)> does not have the attribute 'non_existing'
1261
1262but adding ``create=True`` in the call to :func:`patch` will make the previous example
1263work as expected::
1264
1265 >>> @patch('sys.non_existing_attribute', 42, create=True)
1266 ... def test(mock_stdout):
1267 ... assert sys.non_existing_attribute == 42
1268 ...
1269 >>> test()
1270
Michael Foorda9e6fb22012-03-28 14:36:02 +01001271
1272patch.object
Georg Brandlfb134382013-02-03 11:47:49 +01001273~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001274
1275.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1276
Georg Brandl7ad3df62014-10-31 07:59:37 +01001277 patch the named member (*attribute*) on an object (*target*) with a mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001278 object.
1279
Georg Brandl7ad3df62014-10-31 07:59:37 +01001280 :func:`patch.object` can be used as a decorator, class decorator or a context
1281 manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* and
1282 *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`,
1283 :func:`patch.object` takes arbitrary keyword arguments for configuring the mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001284 object it creates.
1285
Georg Brandl7ad3df62014-10-31 07:59:37 +01001286 When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001287 for choosing which methods to wrap.
1288
Georg Brandl7ad3df62014-10-31 07:59:37 +01001289You can either call :func:`patch.object` with three arguments or two arguments. The
Michael Foorda9e6fb22012-03-28 14:36:02 +01001290three argument form takes the object to be patched, the attribute name and the
1291object to replace the attribute with.
1292
1293When calling with the two argument form you omit the replacement object, and a
1294mock is created for you and passed in as an extra argument to the decorated
1295function:
1296
1297 >>> @patch.object(SomeClass, 'class_method')
1298 ... def test(mock_method):
1299 ... SomeClass.class_method(3)
1300 ... mock_method.assert_called_with(3)
1301 ...
1302 >>> test()
1303
Georg Brandl7ad3df62014-10-31 07:59:37 +01001304*spec*, *create* and the other arguments to :func:`patch.object` have the same
1305meaning as they do for :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001306
1307
1308patch.dict
Georg Brandlfb134382013-02-03 11:47:49 +01001309~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001310
1311.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs)
1312
1313 Patch a dictionary, or dictionary like object, and restore the dictionary
1314 to its original state after the test.
1315
Georg Brandl7ad3df62014-10-31 07:59:37 +01001316 *in_dict* can be a dictionary or a mapping like container. If it is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01001317 mapping then it must at least support getting, setting and deleting items
1318 plus iterating over keys.
1319
Georg Brandl7ad3df62014-10-31 07:59:37 +01001320 *in_dict* can also be a string specifying the name of the dictionary, which
Michael Foorda9e6fb22012-03-28 14:36:02 +01001321 will then be fetched by importing it.
1322
Georg Brandl7ad3df62014-10-31 07:59:37 +01001323 *values* can be a dictionary of values to set in the dictionary. *values*
1324 can also be an iterable of ``(key, value)`` pairs.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001325
Georg Brandl7ad3df62014-10-31 07:59:37 +01001326 If *clear* is true then the dictionary will be cleared before the new
Michael Foorda9e6fb22012-03-28 14:36:02 +01001327 values are set.
1328
Georg Brandl7ad3df62014-10-31 07:59:37 +01001329 :func:`patch.dict` can also be called with arbitrary keyword arguments to set
Michael Foorda9e6fb22012-03-28 14:36:02 +01001330 values in the dictionary.
1331
Georg Brandl7ad3df62014-10-31 07:59:37 +01001332 :func:`patch.dict` can be used as a context manager, decorator or class
1333 decorator. When used as a class decorator :func:`patch.dict` honours
1334 ``patch.TEST_PREFIX`` for choosing which methods to wrap.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001335
Georg Brandl7ad3df62014-10-31 07:59:37 +01001336:func:`patch.dict` can be used to add members to a dictionary, or simply let a test
Michael Foorda9e6fb22012-03-28 14:36:02 +01001337change a dictionary, and ensure the dictionary is restored when the test
1338ends.
1339
1340 >>> foo = {}
1341 >>> with patch.dict(foo, {'newkey': 'newvalue'}):
1342 ... assert foo == {'newkey': 'newvalue'}
1343 ...
1344 >>> assert foo == {}
1345
1346 >>> import os
1347 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
Berker Peksag920f6db2015-09-10 21:41:15 +03001348 ... print(os.environ['newkey'])
Michael Foorda9e6fb22012-03-28 14:36:02 +01001349 ...
1350 newvalue
1351 >>> assert 'newkey' not in os.environ
1352
Georg Brandl7ad3df62014-10-31 07:59:37 +01001353Keywords can be used in the :func:`patch.dict` call to set values in the dictionary:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001354
1355 >>> mymodule = MagicMock()
1356 >>> mymodule.function.return_value = 'fish'
1357 >>> with patch.dict('sys.modules', mymodule=mymodule):
1358 ... import mymodule
1359 ... mymodule.function('some', 'args')
1360 ...
1361 'fish'
1362
Georg Brandl7ad3df62014-10-31 07:59:37 +01001363:func:`patch.dict` can be used with dictionary like objects that aren't actually
Michael Foorda9e6fb22012-03-28 14:36:02 +01001364dictionaries. At the very minimum they must support item getting, setting,
1365deleting and either iteration or membership test. This corresponds to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001366magic methods :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__` and either
1367:meth:`__iter__` or :meth:`__contains__`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001368
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001369 >>> class Container:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001370 ... def __init__(self):
1371 ... self.values = {}
1372 ... def __getitem__(self, name):
1373 ... return self.values[name]
1374 ... def __setitem__(self, name, value):
1375 ... self.values[name] = value
1376 ... def __delitem__(self, name):
1377 ... del self.values[name]
1378 ... def __iter__(self):
1379 ... return iter(self.values)
1380 ...
1381 >>> thing = Container()
1382 >>> thing['one'] = 1
1383 >>> with patch.dict(thing, one=2, two=3):
1384 ... assert thing['one'] == 2
1385 ... assert thing['two'] == 3
1386 ...
1387 >>> assert thing['one'] == 1
1388 >>> assert list(thing) == ['one']
1389
1390
1391patch.multiple
Georg Brandlfb134382013-02-03 11:47:49 +01001392~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001393
1394.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1395
1396 Perform multiple patches in a single call. It takes the object to be
1397 patched (either as an object or a string to fetch the object by importing)
1398 and keyword arguments for the patches::
1399
1400 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1401 ...
1402
Georg Brandl7ad3df62014-10-31 07:59:37 +01001403 Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create
Michael Foorda9e6fb22012-03-28 14:36:02 +01001404 mocks for you. In this case the created mocks are passed into a decorated
Georg Brandl7ad3df62014-10-31 07:59:37 +01001405 function by keyword, and a dictionary is returned when :func:`patch.multiple` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001406 used as a context manager.
1407
Georg Brandl7ad3df62014-10-31 07:59:37 +01001408 :func:`patch.multiple` can be used as a decorator, class decorator or a context
1409 manager. The arguments *spec*, *spec_set*, *create*, *autospec* and
1410 *new_callable* have the same meaning as for :func:`patch`. These arguments will
1411 be applied to *all* patches done by :func:`patch.multiple`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001412
Georg Brandl7ad3df62014-10-31 07:59:37 +01001413 When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001414 for choosing which methods to wrap.
1415
Georg Brandl7ad3df62014-10-31 07:59:37 +01001416If you want :func:`patch.multiple` to create mocks for you, then you can use
1417:data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001418then the created mocks are passed into the decorated function by keyword. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001419
1420 >>> thing = object()
1421 >>> other = object()
1422
1423 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1424 ... def test_function(thing, other):
1425 ... assert isinstance(thing, MagicMock)
1426 ... assert isinstance(other, MagicMock)
1427 ...
1428 >>> test_function()
1429
Georg Brandl7ad3df62014-10-31 07:59:37 +01001430:func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001431passed by keyword *after* any of the standard arguments created by :func:`patch`::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001432
1433 >>> @patch('sys.exit')
1434 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1435 ... def test_function(mock_exit, other, thing):
1436 ... assert 'other' in repr(other)
1437 ... assert 'thing' in repr(thing)
1438 ... assert 'exit' in repr(mock_exit)
1439 ...
1440 >>> test_function()
1441
Georg Brandl7ad3df62014-10-31 07:59:37 +01001442If :func:`patch.multiple` is used as a context manager, the value returned by the
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001443context manger is a dictionary where created mocks are keyed by name::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001444
1445 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
1446 ... assert 'other' in repr(values['other'])
1447 ... assert 'thing' in repr(values['thing'])
1448 ... assert values['thing'] is thing
1449 ... assert values['other'] is other
1450 ...
1451
1452
1453.. _start-and-stop:
1454
1455patch methods: start and stop
Georg Brandlfb134382013-02-03 11:47:49 +01001456~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001457
Georg Brandl7ad3df62014-10-31 07:59:37 +01001458All the patchers have :meth:`start` and :meth:`stop` methods. These make it simpler to do
1459patching in ``setUp`` methods or where you want to do multiple patches without
Michael Foorda9e6fb22012-03-28 14:36:02 +01001460nesting decorators or with statements.
1461
Georg Brandl7ad3df62014-10-31 07:59:37 +01001462To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as
1463normal and keep a reference to the returned ``patcher`` object. You can then
1464call :meth:`start` to put the patch in place and :meth:`stop` to undo it.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001465
Georg Brandl7ad3df62014-10-31 07:59:37 +01001466If you are using :func:`patch` to create a mock for you then it will be returned by
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001467the call to ``patcher.start``. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001468
1469 >>> patcher = patch('package.module.ClassName')
1470 >>> from package import module
1471 >>> original = module.ClassName
1472 >>> new_mock = patcher.start()
1473 >>> assert module.ClassName is not original
1474 >>> assert module.ClassName is new_mock
1475 >>> patcher.stop()
1476 >>> assert module.ClassName is original
1477 >>> assert module.ClassName is not new_mock
1478
1479
Georg Brandl7ad3df62014-10-31 07:59:37 +01001480A typical use case for this might be for doing multiple patches in the ``setUp``
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001481method of a :class:`TestCase`::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001482
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001483 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +01001484 ... def setUp(self):
1485 ... self.patcher1 = patch('package.module.Class1')
1486 ... self.patcher2 = patch('package.module.Class2')
1487 ... self.MockClass1 = self.patcher1.start()
1488 ... self.MockClass2 = self.patcher2.start()
1489 ...
1490 ... def tearDown(self):
1491 ... self.patcher1.stop()
1492 ... self.patcher2.stop()
1493 ...
1494 ... def test_something(self):
1495 ... assert package.module.Class1 is self.MockClass1
1496 ... assert package.module.Class2 is self.MockClass2
1497 ...
1498 >>> MyTest('test_something').run()
1499
1500.. caution::
1501
1502 If you use this technique you must ensure that the patching is "undone" by
Georg Brandl7ad3df62014-10-31 07:59:37 +01001503 calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001504 exception is raised in the ``setUp`` then ``tearDown`` is not called.
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001505 :meth:`unittest.TestCase.addCleanup` makes this easier::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001506
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001507 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +01001508 ... def setUp(self):
1509 ... patcher = patch('package.module.Class')
1510 ... self.MockClass = patcher.start()
1511 ... self.addCleanup(patcher.stop)
1512 ...
1513 ... def test_something(self):
1514 ... assert package.module.Class is self.MockClass
1515 ...
1516
Georg Brandl7ad3df62014-10-31 07:59:37 +01001517 As an added bonus you no longer need to keep a reference to the ``patcher``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001518 object.
1519
Michael Foordf7c41582012-06-10 20:36:32 +01001520It is also possible to stop all patches which have been started by using
Georg Brandl7ad3df62014-10-31 07:59:37 +01001521:func:`patch.stopall`.
Michael Foordf7c41582012-06-10 20:36:32 +01001522
1523.. function:: patch.stopall
1524
Georg Brandl7ad3df62014-10-31 07:59:37 +01001525 Stop all active patches. Only stops patches started with ``start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001526
Georg Brandl7ad3df62014-10-31 07:59:37 +01001527
1528.. _patch-builtins:
Michael Foordfddcfa22014-04-14 16:25:20 -04001529
1530patch builtins
Georg Brandl7ad3df62014-10-31 07:59:37 +01001531~~~~~~~~~~~~~~
Michael Foordfddcfa22014-04-14 16:25:20 -04001532You can patch any builtins within a module. The following example patches
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001533builtin :func:`ord`::
Michael Foordfddcfa22014-04-14 16:25:20 -04001534
1535 >>> @patch('__main__.ord')
1536 ... def test(mock_ord):
1537 ... mock_ord.return_value = 101
1538 ... print(ord('c'))
1539 ...
1540 >>> test()
1541 101
1542
Michael Foorda9e6fb22012-03-28 14:36:02 +01001543
1544TEST_PREFIX
Georg Brandlfb134382013-02-03 11:47:49 +01001545~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001546
1547All of the patchers can be used as class decorators. When used in this way
1548they wrap every test method on the class. The patchers recognise methods that
Georg Brandl7ad3df62014-10-31 07:59:37 +01001549start with ``'test'`` as being test methods. This is the same way that the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001550:class:`unittest.TestLoader` finds test methods by default.
1551
1552It is possible that you want to use a different prefix for your tests. You can
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001553inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001554
1555 >>> patch.TEST_PREFIX = 'foo'
1556 >>> value = 3
1557 >>>
1558 >>> @patch('__main__.value', 'not three')
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001559 ... class Thing:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001560 ... def foo_one(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001561 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001562 ... def foo_two(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001563 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001564 ...
1565 >>>
1566 >>> Thing().foo_one()
1567 not three
1568 >>> Thing().foo_two()
1569 not three
1570 >>> value
1571 3
1572
1573
1574Nesting Patch Decorators
Georg Brandlfb134382013-02-03 11:47:49 +01001575~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001576
1577If you want to perform multiple patches then you can simply stack up the
1578decorators.
1579
1580You can stack up multiple patch decorators using this pattern:
1581
1582 >>> @patch.object(SomeClass, 'class_method')
1583 ... @patch.object(SomeClass, 'static_method')
1584 ... def test(mock1, mock2):
1585 ... assert SomeClass.static_method is mock1
1586 ... assert SomeClass.class_method is mock2
1587 ... SomeClass.static_method('foo')
1588 ... SomeClass.class_method('bar')
1589 ... return mock1, mock2
1590 ...
1591 >>> mock1, mock2 = test()
1592 >>> mock1.assert_called_once_with('foo')
1593 >>> mock2.assert_called_once_with('bar')
1594
1595
1596Note that the decorators are applied from the bottom upwards. This is the
1597standard way that Python applies decorators. The order of the created mocks
1598passed into your test function matches this order.
1599
1600
1601.. _where-to-patch:
1602
1603Where to patch
Georg Brandlfb134382013-02-03 11:47:49 +01001604~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001605
Georg Brandl7ad3df62014-10-31 07:59:37 +01001606:func:`patch` works by (temporarily) changing the object that a *name* points to with
Michael Foorda9e6fb22012-03-28 14:36:02 +01001607another one. There can be many names pointing to any individual object, so
1608for patching to work you must ensure that you patch the name used by the system
1609under test.
1610
1611The basic principle is that you patch where an object is *looked up*, which
1612is not necessarily the same place as where it is defined. A couple of
1613examples will help to clarify this.
1614
1615Imagine we have a project that we want to test with the following structure::
1616
1617 a.py
1618 -> Defines SomeClass
1619
1620 b.py
1621 -> from a import SomeClass
1622 -> some_function instantiates SomeClass
1623
Georg Brandl7ad3df62014-10-31 07:59:37 +01001624Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
1625:func:`patch`. The problem is that when we import module b, which we will have to
1626do then it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
1627``a.SomeClass`` then it will have no effect on our test; module b already has a
1628reference to the *real* ``SomeClass`` and it looks like our patching had no
Michael Foorda9e6fb22012-03-28 14:36:02 +01001629effect.
1630
Ben Lloyd15033d12017-05-22 12:06:56 +01001631The key is to patch out ``SomeClass`` where it is used (or where it is looked up).
1632In this case ``some_function`` will actually look up ``SomeClass`` in module b,
Michael Foorda9e6fb22012-03-28 14:36:02 +01001633where we have imported it. The patching should look like::
1634
1635 @patch('b.SomeClass')
1636
Georg Brandl7ad3df62014-10-31 07:59:37 +01001637However, consider the alternative scenario where instead of ``from a import
1638SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both
Michael Foorda9e6fb22012-03-28 14:36:02 +01001639of these import forms are common. In this case the class we want to patch is
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001640being looked up in the module and so we have to patch ``a.SomeClass`` instead::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001641
1642 @patch('a.SomeClass')
1643
1644
1645Patching Descriptors and Proxy Objects
Georg Brandlfb134382013-02-03 11:47:49 +01001646~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001647
1648Both patch_ and patch.object_ correctly patch and restore descriptors: class
1649methods, static methods and properties. You should patch these on the *class*
1650rather than an instance. They also work with *some* objects
Zachary Ware5ea5d2c2014-02-26 09:34:43 -06001651that proxy attribute access, like the `django settings object
Michael Foorda9e6fb22012-03-28 14:36:02 +01001652<http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
1653
1654
Michael Foord2309ed82012-03-28 15:38:36 +01001655MagicMock and magic method support
Georg Brandlfb134382013-02-03 11:47:49 +01001656----------------------------------
Michael Foord2309ed82012-03-28 15:38:36 +01001657
1658.. _magic-methods:
1659
1660Mocking Magic Methods
Georg Brandlfb134382013-02-03 11:47:49 +01001661~~~~~~~~~~~~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001662
1663:class:`Mock` supports mocking the Python protocol methods, also known as
1664"magic methods". This allows mock objects to replace containers or other
1665objects that implement Python protocols.
1666
1667Because magic methods are looked up differently from normal methods [#]_, this
1668support has been specially implemented. This means that only specific magic
1669methods are supported. The supported list includes *almost* all of them. If
1670there are any missing that you need please let us know.
1671
1672You mock magic methods by setting the method you are interested in to a function
1673or a mock instance. If you are using a function then it *must* take ``self`` as
1674the first argument [#]_.
1675
1676 >>> def __str__(self):
1677 ... return 'fooble'
1678 ...
1679 >>> mock = Mock()
1680 >>> mock.__str__ = __str__
1681 >>> str(mock)
1682 'fooble'
1683
1684 >>> mock = Mock()
1685 >>> mock.__str__ = Mock()
1686 >>> mock.__str__.return_value = 'fooble'
1687 >>> str(mock)
1688 'fooble'
1689
1690 >>> mock = Mock()
1691 >>> mock.__iter__ = Mock(return_value=iter([]))
1692 >>> list(mock)
1693 []
1694
1695One use case for this is for mocking objects used as context managers in a
Georg Brandl7ad3df62014-10-31 07:59:37 +01001696:keyword:`with` statement:
Michael Foord2309ed82012-03-28 15:38:36 +01001697
1698 >>> mock = Mock()
1699 >>> mock.__enter__ = Mock(return_value='foo')
1700 >>> mock.__exit__ = Mock(return_value=False)
1701 >>> with mock as m:
1702 ... assert m == 'foo'
1703 ...
1704 >>> mock.__enter__.assert_called_with()
1705 >>> mock.__exit__.assert_called_with(None, None, None)
1706
1707Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they
1708are recorded in :attr:`~Mock.mock_calls`.
1709
1710.. note::
1711
Georg Brandl7ad3df62014-10-31 07:59:37 +01001712 If you use the *spec* keyword argument to create a mock then attempting to
1713 set a magic method that isn't in the spec will raise an :exc:`AttributeError`.
Michael Foord2309ed82012-03-28 15:38:36 +01001714
1715The full list of supported magic methods is:
1716
1717* ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``
1718* ``__dir__``, ``__format__`` and ``__subclasses__``
John Reese6c4fab02018-05-22 13:01:10 -07001719* ``__round__``, ``__floor__``, ``__trunc__`` and ``__ceil__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001720* Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001721 ``__eq__`` and ``__ne__``
1722* Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``,
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001723 ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__``
1724 and ``__missing__``
Michael Foord2309ed82012-03-28 15:38:36 +01001725* Context manager: ``__enter__`` and ``__exit__``
1726* Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``
1727* The numeric methods (including right hand and in-place variants):
Serhiy Storchakac2ccce72015-03-12 22:01:30 +02001728 ``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__div__``, ``__truediv__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001729 ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``,
1730 ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001731* Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__``
1732 and ``__index__``
Michael Foord2309ed82012-03-28 15:38:36 +01001733* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
1734* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
1735 ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001736* File system path representation: ``__fspath__``
1737
1738.. versionchanged:: 3.8
1739 Added support for :func:`os.PathLike.__fspath__`.
Michael Foord2309ed82012-03-28 15:38:36 +01001740
1741
1742The following methods exist but are *not* supported as they are either in use
1743by mock, can't be set dynamically, or can cause problems:
1744
1745* ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``
1746* ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``
1747
1748
1749
1750Magic Mock
Georg Brandlfb134382013-02-03 11:47:49 +01001751~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001752
Georg Brandl7ad3df62014-10-31 07:59:37 +01001753There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001754
1755
1756.. class:: MagicMock(*args, **kw)
1757
1758 ``MagicMock`` is a subclass of :class:`Mock` with default implementations
1759 of most of the magic methods. You can use ``MagicMock`` without having to
1760 configure the magic methods yourself.
1761
1762 The constructor parameters have the same meaning as for :class:`Mock`.
1763
Georg Brandl7ad3df62014-10-31 07:59:37 +01001764 If you use the *spec* or *spec_set* arguments then *only* magic methods
Michael Foord2309ed82012-03-28 15:38:36 +01001765 that exist in the spec will be created.
1766
1767
1768.. class:: NonCallableMagicMock(*args, **kw)
1769
Georg Brandl7ad3df62014-10-31 07:59:37 +01001770 A non-callable version of :class:`MagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001771
1772 The constructor parameters have the same meaning as for
Georg Brandl7ad3df62014-10-31 07:59:37 +01001773 :class:`MagicMock`, with the exception of *return_value* and
1774 *side_effect* which have no meaning on a non-callable mock.
Michael Foord2309ed82012-03-28 15:38:36 +01001775
Georg Brandl7ad3df62014-10-31 07:59:37 +01001776The magic methods are setup with :class:`MagicMock` objects, so you can configure them
Michael Foord2309ed82012-03-28 15:38:36 +01001777and use them in the usual way:
1778
1779 >>> mock = MagicMock()
1780 >>> mock[3] = 'fish'
1781 >>> mock.__setitem__.assert_called_with(3, 'fish')
1782 >>> mock.__getitem__.return_value = 'result'
1783 >>> mock[2]
1784 'result'
1785
1786By default many of the protocol methods are required to return objects of a
1787specific type. These methods are preconfigured with a default return value, so
1788that they can be used without you having to do anything if you aren't interested
1789in the return value. You can still *set* the return value manually if you want
1790to change the default.
1791
1792Methods and their defaults:
1793
1794* ``__lt__``: NotImplemented
1795* ``__gt__``: NotImplemented
1796* ``__le__``: NotImplemented
1797* ``__ge__``: NotImplemented
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001798* ``__int__``: 1
1799* ``__contains__``: False
Berker Peksag8fafc742016-04-11 12:23:04 +03001800* ``__len__``: 0
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001801* ``__iter__``: iter([])
1802* ``__exit__``: False
1803* ``__complex__``: 1j
1804* ``__float__``: 1.0
1805* ``__bool__``: True
1806* ``__index__``: 1
1807* ``__hash__``: default hash for the mock
1808* ``__str__``: default str for the mock
Michael Foord2309ed82012-03-28 15:38:36 +01001809* ``__sizeof__``: default sizeof for the mock
1810
1811For example:
1812
1813 >>> mock = MagicMock()
1814 >>> int(mock)
1815 1
1816 >>> len(mock)
1817 0
1818 >>> list(mock)
1819 []
1820 >>> object() in mock
1821 False
1822
Berker Peksag283f1aa2015-01-07 21:15:02 +02001823The two equality methods, :meth:`__eq__` and :meth:`__ne__`, are special.
1824They do the default equality comparison on identity, using the
1825:attr:`~Mock.side_effect` attribute, unless you change their return value to
1826return something else::
Michael Foord2309ed82012-03-28 15:38:36 +01001827
1828 >>> MagicMock() == 3
1829 False
1830 >>> MagicMock() != 3
1831 True
1832 >>> mock = MagicMock()
1833 >>> mock.__eq__.return_value = True
1834 >>> mock == 3
1835 True
1836
Georg Brandl7ad3df62014-10-31 07:59:37 +01001837The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
Michael Foord2309ed82012-03-28 15:38:36 +01001838required to be an iterator:
1839
1840 >>> mock = MagicMock()
1841 >>> mock.__iter__.return_value = ['a', 'b', 'c']
1842 >>> list(mock)
1843 ['a', 'b', 'c']
1844 >>> list(mock)
1845 ['a', 'b', 'c']
1846
1847If the return value *is* an iterator, then iterating over it once will consume
1848it and subsequent iterations will result in an empty list:
1849
1850 >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
1851 >>> list(mock)
1852 ['a', 'b', 'c']
1853 >>> list(mock)
1854 []
1855
1856``MagicMock`` has all of the supported magic methods configured except for some
1857of the obscure and obsolete ones. You can still set these up if you want.
1858
1859Magic methods that are supported but not setup by default in ``MagicMock`` are:
1860
1861* ``__subclasses__``
1862* ``__dir__``
1863* ``__format__``
1864* ``__get__``, ``__set__`` and ``__delete__``
1865* ``__reversed__`` and ``__missing__``
1866* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
1867 ``__getstate__`` and ``__setstate__``
1868* ``__getformat__`` and ``__setformat__``
1869
1870
1871
1872.. [#] Magic methods *should* be looked up on the class rather than the
1873 instance. Different versions of Python are inconsistent about applying this
1874 rule. The supported protocol methods should work with all supported versions
1875 of Python.
1876.. [#] The function is basically hooked up to the class, but each ``Mock``
1877 instance is kept isolated from the others.
1878
1879
Michael Foorda9e6fb22012-03-28 14:36:02 +01001880Helpers
Georg Brandlfb134382013-02-03 11:47:49 +01001881-------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001882
1883sentinel
Georg Brandlfb134382013-02-03 11:47:49 +01001884~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001885
1886.. data:: sentinel
1887
Andrés Delfinof85af032018-07-08 21:28:51 -03001888 The ``sentinel`` object provides a convenient way of providing unique
1889 objects for your tests.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001890
Andrés Delfinof85af032018-07-08 21:28:51 -03001891 Attributes are created on demand when you access them by name. Accessing
1892 the same attribute will always return the same object. The objects
1893 returned have a sensible repr so that test failure messages are readable.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001894
Serhiy Storchakad9c956f2017-01-11 20:13:03 +02001895 .. versionchanged:: 3.7
1896 The ``sentinel`` attributes now preserve their identity when they are
1897 :mod:`copied <copy>` or :mod:`pickled <pickle>`.
1898
Michael Foorda9e6fb22012-03-28 14:36:02 +01001899Sometimes when testing you need to test that a specific object is passed as an
1900argument to another method, or returned. It can be common to create named
Georg Brandl7ad3df62014-10-31 07:59:37 +01001901sentinel objects to test this. :data:`sentinel` provides a convenient way of
Michael Foorda9e6fb22012-03-28 14:36:02 +01001902creating and testing the identity of objects like this.
1903
Georg Brandl7ad3df62014-10-31 07:59:37 +01001904In this example we monkey patch ``method`` to return ``sentinel.some_object``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001905
1906 >>> real = ProductionClass()
1907 >>> real.method = Mock(name="method")
1908 >>> real.method.return_value = sentinel.some_object
1909 >>> result = real.method()
1910 >>> assert result is sentinel.some_object
1911 >>> sentinel.some_object
1912 sentinel.some_object
1913
1914
1915DEFAULT
Georg Brandlfb134382013-02-03 11:47:49 +01001916~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001917
1918
1919.. data:: DEFAULT
1920
Georg Brandl7ad3df62014-10-31 07:59:37 +01001921 The :data:`DEFAULT` object is a pre-created sentinel (actually
1922 ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001923 functions to indicate that the normal return value should be used.
1924
1925
Michael Foorda9e6fb22012-03-28 14:36:02 +01001926call
Georg Brandlfb134382013-02-03 11:47:49 +01001927~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001928
1929.. function:: call(*args, **kwargs)
1930
Georg Brandl7ad3df62014-10-31 07:59:37 +01001931 :func:`call` is a helper object for making simpler assertions, for comparing with
Georg Brandl24891672012-04-01 13:48:26 +02001932 :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
Georg Brandl7ad3df62014-10-31 07:59:37 +01001933 :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be
Michael Foorda9e6fb22012-03-28 14:36:02 +01001934 used with :meth:`~Mock.assert_has_calls`.
1935
1936 >>> m = MagicMock(return_value=None)
1937 >>> m(1, 2, a='foo', b='bar')
1938 >>> m()
1939 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
1940 True
1941
1942.. method:: call.call_list()
1943
Georg Brandl7ad3df62014-10-31 07:59:37 +01001944 For a call object that represents multiple calls, :meth:`call_list`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001945 returns a list of all the intermediate calls as well as the
1946 final call.
1947
Georg Brandl7ad3df62014-10-31 07:59:37 +01001948``call_list`` is particularly useful for making assertions on "chained calls". A
Michael Foorda9e6fb22012-03-28 14:36:02 +01001949chained call is multiple calls on a single line of code. This results in
1950multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
1951the sequence of calls can be tedious.
1952
1953:meth:`~call.call_list` can construct the sequence of calls from the same
1954chained call:
1955
1956 >>> m = MagicMock()
1957 >>> m(1).method(arg='foo').other('bar')(2.0)
1958 <MagicMock name='mock().method().other()()' id='...'>
1959 >>> kall = call(1).method(arg='foo').other('bar')(2.0)
1960 >>> kall.call_list()
1961 [call(1),
1962 call().method(arg='foo'),
1963 call().method().other('bar'),
1964 call().method().other()(2.0)]
1965 >>> m.mock_calls == kall.call_list()
1966 True
1967
1968.. _calls-as-tuples:
1969
Georg Brandl7ad3df62014-10-31 07:59:37 +01001970A ``call`` object is either a tuple of (positional args, keyword args) or
Michael Foorda9e6fb22012-03-28 14:36:02 +01001971(name, positional args, keyword args) depending on how it was constructed. When
Georg Brandl7ad3df62014-10-31 07:59:37 +01001972you construct them yourself this isn't particularly interesting, but the ``call``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001973objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
1974:attr:`Mock.mock_calls` attributes can be introspected to get at the individual
1975arguments they contain.
1976
Georg Brandl7ad3df62014-10-31 07:59:37 +01001977The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
1978are two-tuples of (positional args, keyword args) whereas the ``call`` objects
Michael Foorda9e6fb22012-03-28 14:36:02 +01001979in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
1980three-tuples of (name, positional args, keyword args).
1981
1982You can use their "tupleness" to pull out the individual arguments for more
1983complex introspection and assertions. The positional arguments are a tuple
1984(an empty tuple if there are no positional arguments) and the keyword
1985arguments are a dictionary:
1986
1987 >>> m = MagicMock(return_value=None)
1988 >>> m(1, 2, 3, arg='one', arg2='two')
1989 >>> kall = m.call_args
1990 >>> args, kwargs = kall
1991 >>> args
1992 (1, 2, 3)
1993 >>> kwargs
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001994 {'arg': 'one', 'arg2': 'two'}
Michael Foorda9e6fb22012-03-28 14:36:02 +01001995 >>> args is kall[0]
1996 True
1997 >>> kwargs is kall[1]
1998 True
1999
2000 >>> m = MagicMock()
2001 >>> m.foo(4, 5, 6, arg='two', arg2='three')
2002 <MagicMock name='mock.foo()' id='...'>
2003 >>> kall = m.mock_calls[0]
2004 >>> name, args, kwargs = kall
2005 >>> name
2006 'foo'
2007 >>> args
2008 (4, 5, 6)
2009 >>> kwargs
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002010 {'arg': 'two', 'arg2': 'three'}
Michael Foorda9e6fb22012-03-28 14:36:02 +01002011 >>> name is m.mock_calls[0][0]
2012 True
2013
2014
2015create_autospec
Georg Brandlfb134382013-02-03 11:47:49 +01002016~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002017
2018.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
2019
2020 Create a mock object using another object as a spec. Attributes on the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002021 mock will use the corresponding attribute on the *spec* object as their
Michael Foorda9e6fb22012-03-28 14:36:02 +01002022 spec.
2023
2024 Functions or methods being mocked will have their arguments checked to
2025 ensure that they are called with the correct signature.
2026
Georg Brandl7ad3df62014-10-31 07:59:37 +01002027 If *spec_set* is ``True`` then attempting to set attributes that don't exist
2028 on the spec object will raise an :exc:`AttributeError`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002029
2030 If a class is used as a spec then the return value of the mock (the
2031 instance of the class) will have the same spec. You can use a class as the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002032 spec for an instance object by passing ``instance=True``. The returned mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01002033 will only be callable if instances of the mock are callable.
2034
Georg Brandl7ad3df62014-10-31 07:59:37 +01002035 :func:`create_autospec` also takes arbitrary keyword arguments that are passed to
Michael Foorda9e6fb22012-03-28 14:36:02 +01002036 the constructor of the created mock.
2037
2038See :ref:`auto-speccing` for examples of how to use auto-speccing with
Georg Brandl7ad3df62014-10-31 07:59:37 +01002039:func:`create_autospec` and the *autospec* argument to :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002040
2041
2042ANY
Georg Brandlfb134382013-02-03 11:47:49 +01002043~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002044
2045.. data:: ANY
2046
2047Sometimes you may need to make assertions about *some* of the arguments in a
2048call to mock, but either not care about some of the arguments or want to pull
2049them individually out of :attr:`~Mock.call_args` and make more complex
2050assertions on them.
2051
2052To ignore certain arguments you can pass in objects that compare equal to
2053*everything*. Calls to :meth:`~Mock.assert_called_with` and
2054:meth:`~Mock.assert_called_once_with` will then succeed no matter what was
2055passed in.
2056
2057 >>> mock = Mock(return_value=None)
2058 >>> mock('foo', bar=object())
2059 >>> mock.assert_called_once_with('foo', bar=ANY)
2060
Georg Brandl7ad3df62014-10-31 07:59:37 +01002061:data:`ANY` can also be used in comparisons with call lists like
Michael Foorda9e6fb22012-03-28 14:36:02 +01002062:attr:`~Mock.mock_calls`:
2063
2064 >>> m = MagicMock(return_value=None)
2065 >>> m(1)
2066 >>> m(1, 2)
2067 >>> m(object())
2068 >>> m.mock_calls == [call(1), call(1, 2), ANY]
2069 True
2070
2071
2072
2073FILTER_DIR
Georg Brandlfb134382013-02-03 11:47:49 +01002074~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002075
2076.. data:: FILTER_DIR
2077
Georg Brandl7ad3df62014-10-31 07:59:37 +01002078:data:`FILTER_DIR` is a module level variable that controls the way mock objects
2079respond to :func:`dir` (only for Python 2.6 or more recent). The default is ``True``,
Michael Foorda9e6fb22012-03-28 14:36:02 +01002080which uses the filtering described below, to only show useful members. If you
2081dislike this filtering, or need to switch it off for diagnostic purposes, then
Georg Brandl7ad3df62014-10-31 07:59:37 +01002082set ``mock.FILTER_DIR = False``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002083
Georg Brandl7ad3df62014-10-31 07:59:37 +01002084With filtering on, ``dir(some_mock)`` shows only useful attributes and will
Michael Foorda9e6fb22012-03-28 14:36:02 +01002085include any dynamically created attributes that wouldn't normally be shown.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002086If the mock was created with a *spec* (or *autospec* of course) then all the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002087attributes from the original are shown, even if they haven't been accessed
2088yet:
2089
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002090.. doctest::
2091 :options: +ELLIPSIS,+NORMALIZE_WHITESPACE
2092
Michael Foorda9e6fb22012-03-28 14:36:02 +01002093 >>> dir(Mock())
2094 ['assert_any_call',
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002095 'assert_called',
2096 'assert_called_once',
Michael Foorda9e6fb22012-03-28 14:36:02 +01002097 'assert_called_once_with',
2098 'assert_called_with',
2099 'assert_has_calls',
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002100 'assert_not_called',
Michael Foorda9e6fb22012-03-28 14:36:02 +01002101 'attach_mock',
2102 ...
2103 >>> from urllib import request
2104 >>> dir(Mock(spec=request))
2105 ['AbstractBasicAuthHandler',
2106 'AbstractDigestAuthHandler',
2107 'AbstractHTTPHandler',
2108 'BaseHandler',
2109 ...
2110
Georg Brandl7ad3df62014-10-31 07:59:37 +01002111Many of the not-very-useful (private to :class:`Mock` rather than the thing being
Michael Foorda9e6fb22012-03-28 14:36:02 +01002112mocked) underscore and double underscore prefixed attributes have been
Georg Brandl7ad3df62014-10-31 07:59:37 +01002113filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this
Michael Foorda9e6fb22012-03-28 14:36:02 +01002114behaviour you can switch it off by setting the module level switch
Georg Brandl7ad3df62014-10-31 07:59:37 +01002115:data:`FILTER_DIR`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002116
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002117.. doctest::
2118 :options: +ELLIPSIS,+NORMALIZE_WHITESPACE
2119
Michael Foorda9e6fb22012-03-28 14:36:02 +01002120 >>> from unittest import mock
2121 >>> mock.FILTER_DIR = False
2122 >>> dir(mock.Mock())
2123 ['_NonCallableMock__get_return_value',
2124 '_NonCallableMock__get_side_effect',
2125 '_NonCallableMock__return_value_doc',
2126 '_NonCallableMock__set_return_value',
2127 '_NonCallableMock__set_side_effect',
2128 '__call__',
2129 '__class__',
2130 ...
2131
Georg Brandl7ad3df62014-10-31 07:59:37 +01002132Alternatively you can just use ``vars(my_mock)`` (instance members) and
2133``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of
2134:data:`mock.FILTER_DIR`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002135
2136
2137mock_open
Georg Brandlfb134382013-02-03 11:47:49 +01002138~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002139
2140.. function:: mock_open(mock=None, read_data=None)
2141
Andrés Delfinof85af032018-07-08 21:28:51 -03002142 A helper function to create a mock to replace the use of :func:`open`. It works
2143 for :func:`open` called directly or used as a context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002144
Andrés Delfinof85af032018-07-08 21:28:51 -03002145 The *mock* argument is the mock object to configure. If ``None`` (the
2146 default) then a :class:`MagicMock` will be created for you, with the API limited
2147 to methods or attributes available on standard file handles.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002148
Andrés Delfinof85af032018-07-08 21:28:51 -03002149 *read_data* is a string for the :meth:`~io.IOBase.read`,
2150 :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods
2151 of the file handle to return. Calls to those methods will take data from
2152 *read_data* until it is depleted. The mock of these methods is pretty
2153 simplistic: every time the *mock* is called, the *read_data* is rewound to
2154 the start. If you need more control over the data that you are feeding to
2155 the tested code you will need to customize this mock for yourself. When that
2156 is insufficient, one of the in-memory filesystem packages on `PyPI
2157 <https://pypi.org>`_ can offer a realistic filesystem for testing.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002158
Robert Collinsf79dfe32015-07-24 04:09:59 +12002159 .. versionchanged:: 3.4
2160 Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support.
2161 The mock of :meth:`~io.IOBase.read` changed to consume *read_data* rather
2162 than returning it on each call.
2163
Robert Collins70398392015-07-24 04:10:27 +12002164 .. versionchanged:: 3.5
Robert Collinsf79dfe32015-07-24 04:09:59 +12002165 *read_data* is now reset on each call to the *mock*.
2166
Tony Flury20870232018-09-12 23:21:16 +01002167 .. versionchanged:: 3.8
2168 Added :meth:`__iter__` to implementation so that iteration (such as in for
2169 loops) correctly consumes *read_data*.
2170
Georg Brandl7ad3df62014-10-31 07:59:37 +01002171Using :func:`open` as a context manager is a great way to ensure your file handles
Michael Foorda9e6fb22012-03-28 14:36:02 +01002172are closed properly and is becoming common::
2173
2174 with open('/some/path', 'w') as f:
2175 f.write('something')
2176
Georg Brandl7ad3df62014-10-31 07:59:37 +01002177The issue is that even if you mock out the call to :func:`open` it is the
2178*returned object* that is used as a context manager (and has :meth:`__enter__` and
2179:meth:`__exit__` called).
Michael Foorda9e6fb22012-03-28 14:36:02 +01002180
2181Mocking context managers with a :class:`MagicMock` is common enough and fiddly
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002182enough that a helper function is useful. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002183
2184 >>> m = mock_open()
Michael Foordfddcfa22014-04-14 16:25:20 -04002185 >>> with patch('__main__.open', m):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002186 ... with open('foo', 'w') as h:
2187 ... h.write('some stuff')
2188 ...
2189 >>> m.mock_calls
2190 [call('foo', 'w'),
2191 call().__enter__(),
2192 call().write('some stuff'),
2193 call().__exit__(None, None, None)]
2194 >>> m.assert_called_once_with('foo', 'w')
2195 >>> handle = m()
2196 >>> handle.write.assert_called_once_with('some stuff')
2197
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002198And for reading files::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002199
Michael Foordfddcfa22014-04-14 16:25:20 -04002200 >>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002201 ... with open('foo') as h:
2202 ... result = h.read()
2203 ...
2204 >>> m.assert_called_once_with('foo')
2205 >>> assert result == 'bibble'
2206
2207
2208.. _auto-speccing:
2209
2210Autospeccing
Georg Brandlfb134382013-02-03 11:47:49 +01002211~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002212
Georg Brandl7ad3df62014-10-31 07:59:37 +01002213Autospeccing is based on the existing :attr:`spec` feature of mock. It limits the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002214api of mocks to the api of an original object (the spec), but it is recursive
2215(implemented lazily) so that attributes of mocks only have the same api as
2216the attributes of the spec. In addition mocked functions / methods have the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002217same call signature as the original so they raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002218called incorrectly.
2219
2220Before I explain how auto-speccing works, here's why it is needed.
2221
Georg Brandl7ad3df62014-10-31 07:59:37 +01002222:class:`Mock` is a very powerful and flexible object, but it suffers from two flaws
Michael Foorda9e6fb22012-03-28 14:36:02 +01002223when used to mock out objects from a system under test. One of these flaws is
Georg Brandl7ad3df62014-10-31 07:59:37 +01002224specific to the :class:`Mock` api and the other is a more general problem with using
Michael Foorda9e6fb22012-03-28 14:36:02 +01002225mock objects.
2226
Georg Brandl7ad3df62014-10-31 07:59:37 +01002227First the problem specific to :class:`Mock`. :class:`Mock` has two assert methods that are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002228extremely handy: :meth:`~Mock.assert_called_with` and
2229:meth:`~Mock.assert_called_once_with`.
2230
2231 >>> mock = Mock(name='Thing', return_value=None)
2232 >>> mock(1, 2, 3)
2233 >>> mock.assert_called_once_with(1, 2, 3)
2234 >>> mock(1, 2, 3)
2235 >>> mock.assert_called_once_with(1, 2, 3)
2236 Traceback (most recent call last):
2237 ...
Michael Foord28d591c2012-09-28 16:15:22 +01002238 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002239
2240Because mocks auto-create attributes on demand, and allow you to call them
2241with arbitrary arguments, if you misspell one of these assert methods then
2242your assertion is gone:
2243
2244.. code-block:: pycon
2245
2246 >>> mock = Mock(name='Thing', return_value=None)
2247 >>> mock(1, 2, 3)
2248 >>> mock.assret_called_once_with(4, 5, 6)
2249
2250Your tests can pass silently and incorrectly because of the typo.
2251
2252The second issue is more general to mocking. If you refactor some of your
2253code, rename members and so on, any tests for code that is still using the
2254*old api* but uses mocks instead of the real objects will still pass. This
2255means your tests can all pass even though your code is broken.
2256
2257Note that this is another reason why you need integration tests as well as
2258unit tests. Testing everything in isolation is all fine and dandy, but if you
2259don't test how your units are "wired together" there is still lots of room
2260for bugs that tests might have caught.
2261
Georg Brandl7ad3df62014-10-31 07:59:37 +01002262:mod:`mock` already provides a feature to help with this, called speccing. If you
2263use a class or instance as the :attr:`spec` for a mock then you can only access
Michael Foorda9e6fb22012-03-28 14:36:02 +01002264attributes on the mock that exist on the real class:
2265
2266 >>> from urllib import request
2267 >>> mock = Mock(spec=request.Request)
2268 >>> mock.assret_called_with
2269 Traceback (most recent call last):
2270 ...
2271 AttributeError: Mock object has no attribute 'assret_called_with'
2272
2273The spec only applies to the mock itself, so we still have the same issue
2274with any methods on the mock:
2275
2276.. code-block:: pycon
2277
2278 >>> mock.has_data()
2279 <mock.Mock object at 0x...>
2280 >>> mock.has_data.assret_called_with()
2281
Georg Brandl7ad3df62014-10-31 07:59:37 +01002282Auto-speccing solves this problem. You can either pass ``autospec=True`` to
2283:func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a
2284mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002285object that is being replaced will be used as the spec object. Because the
2286speccing is done "lazily" (the spec is created as attributes on the mock are
2287accessed) you can use it with very complex or deeply nested objects (like
2288modules that import modules that import modules) without a big performance
2289hit.
2290
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002291Here's an example of it in use::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002292
2293 >>> from urllib import request
2294 >>> patcher = patch('__main__.request', autospec=True)
2295 >>> mock_request = patcher.start()
2296 >>> request is mock_request
2297 True
2298 >>> mock_request.Request
2299 <MagicMock name='request.Request' spec='Request' id='...'>
2300
Georg Brandl7ad3df62014-10-31 07:59:37 +01002301You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two
2302arguments in the constructor (one of which is *self*). Here's what happens if
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002303we try to call it incorrectly::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002304
2305 >>> req = request.Request()
2306 Traceback (most recent call last):
2307 ...
2308 TypeError: <lambda>() takes at least 2 arguments (1 given)
2309
2310The spec also applies to instantiated classes (i.e. the return value of
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002311specced mocks)::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002312
2313 >>> req = request.Request('foo')
2314 >>> req
2315 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
2316
Georg Brandl7ad3df62014-10-31 07:59:37 +01002317:class:`Request` objects are not callable, so the return value of instantiating our
2318mocked out :class:`request.Request` is a non-callable mock. With the spec in place
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002319any typos in our asserts will raise the correct error::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002320
2321 >>> req.add_header('spam', 'eggs')
2322 <MagicMock name='request.Request().add_header()' id='...'>
2323 >>> req.add_header.assret_called_with
2324 Traceback (most recent call last):
2325 ...
2326 AttributeError: Mock object has no attribute 'assret_called_with'
2327 >>> req.add_header.assert_called_with('spam', 'eggs')
2328
Georg Brandl7ad3df62014-10-31 07:59:37 +01002329In many cases you will just be able to add ``autospec=True`` to your existing
2330:func:`patch` calls and then be protected against bugs due to typos and api
Michael Foorda9e6fb22012-03-28 14:36:02 +01002331changes.
2332
Georg Brandl7ad3df62014-10-31 07:59:37 +01002333As well as using *autospec* through :func:`patch` there is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002334:func:`create_autospec` for creating autospecced mocks directly:
2335
2336 >>> from urllib import request
2337 >>> mock_request = create_autospec(request)
2338 >>> mock_request.Request('foo', 'bar')
2339 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
2340
2341This isn't without caveats and limitations however, which is why it is not
2342the default behaviour. In order to know what attributes are available on the
2343spec object, autospec has to introspect (access attributes) the spec. As you
2344traverse attributes on the mock a corresponding traversal of the original
2345object is happening under the hood. If any of your specced objects have
2346properties or descriptors that can trigger code execution then you may not be
2347able to use autospec. On the other hand it is much better to design your
2348objects so that introspection is safe [#]_.
2349
2350A more serious problem is that it is common for instance attributes to be
Georg Brandl7ad3df62014-10-31 07:59:37 +01002351created in the :meth:`__init__` method and not to exist on the class at all.
2352*autospec* can't know about any dynamically created attributes and restricts
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002353the api to visible attributes. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002354
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002355 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002356 ... def __init__(self):
2357 ... self.a = 33
2358 ...
2359 >>> with patch('__main__.Something', autospec=True):
2360 ... thing = Something()
2361 ... thing.a
2362 ...
2363 Traceback (most recent call last):
2364 ...
2365 AttributeError: Mock object has no attribute 'a'
2366
2367There are a few different ways of resolving this problem. The easiest, but
2368not necessarily the least annoying, way is to simply set the required
Georg Brandl7ad3df62014-10-31 07:59:37 +01002369attributes on the mock after creation. Just because *autospec* doesn't allow
Michael Foorda9e6fb22012-03-28 14:36:02 +01002370you to fetch attributes that don't exist on the spec it doesn't prevent you
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002371setting them::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002372
2373 >>> with patch('__main__.Something', autospec=True):
2374 ... thing = Something()
2375 ... thing.a = 33
2376 ...
2377
Georg Brandl7ad3df62014-10-31 07:59:37 +01002378There is a more aggressive version of both *spec* and *autospec* that *does*
Michael Foorda9e6fb22012-03-28 14:36:02 +01002379prevent you setting non-existent attributes. This is useful if you want to
2380ensure your code only *sets* valid attributes too, but obviously it prevents
2381this particular scenario:
2382
2383 >>> with patch('__main__.Something', autospec=True, spec_set=True):
2384 ... thing = Something()
2385 ... thing.a = 33
2386 ...
2387 Traceback (most recent call last):
2388 ...
2389 AttributeError: Mock object has no attribute 'a'
2390
2391Probably the best way of solving the problem is to add class attributes as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002392default values for instance members initialised in :meth:`__init__`. Note that if
2393you are only setting default attributes in :meth:`__init__` then providing them via
Michael Foorda9e6fb22012-03-28 14:36:02 +01002394class attributes (shared between instances of course) is faster too. e.g.
2395
2396.. code-block:: python
2397
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002398 class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002399 a = 33
2400
2401This brings up another issue. It is relatively common to provide a default
Georg Brandl7ad3df62014-10-31 07:59:37 +01002402value of ``None`` for members that will later be an object of a different type.
2403``None`` would be useless as a spec because it wouldn't let you access *any*
2404attributes or methods on it. As ``None`` is *never* going to be useful as a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002405spec, and probably indicates a member that will normally of some other type,
Georg Brandl7ad3df62014-10-31 07:59:37 +01002406autospec doesn't use a spec for members that are set to ``None``. These will
2407just be ordinary mocks (well - MagicMocks):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002408
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002409 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002410 ... member = None
2411 ...
2412 >>> mock = create_autospec(Something)
2413 >>> mock.member.foo.bar.baz()
2414 <MagicMock name='mock.member.foo.bar.baz()' id='...'>
2415
2416If modifying your production classes to add defaults isn't to your liking
2417then there are more options. One of these is simply to use an instance as the
2418spec rather than the class. The other is to create a subclass of the
2419production class and add the defaults to the subclass without affecting the
2420production class. Both of these require you to use an alternative object as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002421the spec. Thankfully :func:`patch` supports this - you can simply pass the
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002422alternative object as the *autospec* argument::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002423
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002424 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002425 ... def __init__(self):
2426 ... self.a = 33
2427 ...
2428 >>> class SomethingForTest(Something):
2429 ... a = 33
2430 ...
2431 >>> p = patch('__main__.Something', autospec=SomethingForTest)
2432 >>> mock = p.start()
2433 >>> mock.a
2434 <NonCallableMagicMock name='Something.a' spec='int' id='...'>
2435
2436
2437.. [#] This only applies to classes or already instantiated objects. Calling
2438 a mocked class to create a mock instance *does not* create a real instance.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002439 It is only attribute lookups - along with calls to :func:`dir` - that are done.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002440
Mario Corchero552be9d2017-10-17 12:35:11 +01002441Sealing mocks
2442~~~~~~~~~~~~~
2443
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002444
2445.. testsetup::
2446
2447 from unittest.mock import seal
2448
Mario Corchero552be9d2017-10-17 12:35:11 +01002449.. function:: seal(mock)
2450
Mario Corchero96200eb2018-10-19 22:57:37 +01002451 Seal will disable the automatic creation of mocks when accessing an attribute of
2452 the mock being sealed or any of its attributes that are already mocks recursively.
Mario Corchero552be9d2017-10-17 12:35:11 +01002453
Mario Corchero96200eb2018-10-19 22:57:37 +01002454 If a mock instance with a name or a spec is assigned to an attribute
Paul Ganssle85ac7262018-01-06 08:25:34 -05002455 it won't be considered in the sealing chain. This allows one to prevent seal from
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002456 fixing part of the mock object. ::
Mario Corchero552be9d2017-10-17 12:35:11 +01002457
2458 >>> mock = Mock()
2459 >>> mock.submock.attribute1 = 2
Mario Corchero96200eb2018-10-19 22:57:37 +01002460 >>> mock.not_submock = mock.Mock(name="sample_name")
Mario Corchero552be9d2017-10-17 12:35:11 +01002461 >>> seal(mock)
Mario Corchero96200eb2018-10-19 22:57:37 +01002462 >>> mock.new_attribute # This will raise AttributeError.
Mario Corchero552be9d2017-10-17 12:35:11 +01002463 >>> mock.submock.attribute2 # This will raise AttributeError.
2464 >>> mock.not_submock.attribute2 # This won't raise.
2465
2466 .. versionadded:: 3.7