blob: 0ae29546586a0af81efd6009981f17141f51ed85 [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
705
706 .. attribute:: __class__
707
Georg Brandl7ad3df62014-10-31 07:59:37 +0100708 Normally the :attr:`__class__` attribute of an object will return its type.
709 For a mock object with a :attr:`spec`, ``__class__`` returns the spec class
710 instead. This allows mock objects to pass :func:`isinstance` tests for the
Michael Foord944e02d2012-03-25 23:12:55 +0100711 object they are replacing / masquerading as:
712
713 >>> mock = Mock(spec=3)
714 >>> isinstance(mock, int)
715 True
716
Georg Brandl7ad3df62014-10-31 07:59:37 +0100717 :attr:`__class__` is assignable to, this allows a mock to pass an
718 :func:`isinstance` check without forcing you to use a spec:
Michael Foord944e02d2012-03-25 23:12:55 +0100719
720 >>> mock = Mock()
721 >>> mock.__class__ = dict
722 >>> isinstance(mock, dict)
723 True
724
725.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
726
Georg Brandl7ad3df62014-10-31 07:59:37 +0100727 A non-callable version of :class:`Mock`. The constructor parameters have the same
728 meaning of :class:`Mock`, with the exception of *return_value* and *side_effect*
Michael Foord944e02d2012-03-25 23:12:55 +0100729 which have no meaning on a non-callable mock.
730
Georg Brandl7ad3df62014-10-31 07:59:37 +0100731Mock objects that use a class or an instance as a :attr:`spec` or
732:attr:`spec_set` are able to pass :func:`isinstance` tests:
Michael Foord944e02d2012-03-25 23:12:55 +0100733
734 >>> mock = Mock(spec=SomeClass)
735 >>> isinstance(mock, SomeClass)
736 True
737 >>> mock = Mock(spec_set=SomeClass())
738 >>> isinstance(mock, SomeClass)
739 True
740
Georg Brandl7ad3df62014-10-31 07:59:37 +0100741The :class:`Mock` classes have support for mocking magic methods. See :ref:`magic
Michael Foord944e02d2012-03-25 23:12:55 +0100742methods <magic-methods>` for the full details.
743
744The mock classes and the :func:`patch` decorators all take arbitrary keyword
Georg Brandl7ad3df62014-10-31 07:59:37 +0100745arguments for configuration. For the :func:`patch` decorators the keywords are
Michael Foord944e02d2012-03-25 23:12:55 +0100746passed to the constructor of the mock being created. The keyword arguments
747are for configuring attributes of the mock:
748
749 >>> m = MagicMock(attribute=3, other='fish')
750 >>> m.attribute
751 3
752 >>> m.other
753 'fish'
754
755The return value and side effect of child mocks can be set in the same way,
756using dotted notation. As you can't use dotted names directly in a call you
Georg Brandl7ad3df62014-10-31 07:59:37 +0100757have to create a dictionary and unpack it using ``**``:
Michael Foord944e02d2012-03-25 23:12:55 +0100758
759 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
760 >>> mock = Mock(some_attribute='eggs', **attrs)
761 >>> mock.some_attribute
762 'eggs'
763 >>> mock.method()
764 3
765 >>> mock.other()
766 Traceback (most recent call last):
767 ...
768 KeyError
769
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100770A callable mock which was created with a *spec* (or a *spec_set*) will
771introspect the specification object's signature when matching calls to
772the mock. Therefore, it can match the actual call's arguments regardless
773of whether they were passed positionally or by name::
774
775 >>> def f(a, b, c): pass
776 ...
777 >>> mock = Mock(spec=f)
778 >>> mock(1, 2, c=3)
779 <Mock name='mock()' id='140161580456576'>
780 >>> mock.assert_called_with(1, 2, 3)
781 >>> mock.assert_called_with(a=1, b=2, c=3)
782
783This applies to :meth:`~Mock.assert_called_with`,
784:meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and
785:meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also
786apply to method calls on the mock object.
787
788 .. versionchanged:: 3.4
789 Added signature introspection on specced and autospecced mock objects.
790
Michael Foord944e02d2012-03-25 23:12:55 +0100791
792.. class:: PropertyMock(*args, **kwargs)
793
794 A mock intended to be used as a property, or other descriptor, on a class.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100795 :class:`PropertyMock` provides :meth:`__get__` and :meth:`__set__` methods
796 so you can specify a return value when it is fetched.
Michael Foord944e02d2012-03-25 23:12:55 +0100797
Georg Brandl7ad3df62014-10-31 07:59:37 +0100798 Fetching a :class:`PropertyMock` instance from an object calls the mock, with
Stéphane Wirtel859c0682018-10-12 09:51:05 +0200799 no args. Setting it calls the mock with the value being set. ::
Michael Foord944e02d2012-03-25 23:12:55 +0100800
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200801 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100802 ... @property
803 ... def foo(self):
804 ... return 'something'
805 ... @foo.setter
806 ... def foo(self, value):
807 ... pass
808 ...
809 >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
810 ... mock_foo.return_value = 'mockity-mock'
811 ... this_foo = Foo()
Berker Peksag920f6db2015-09-10 21:41:15 +0300812 ... print(this_foo.foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100813 ... this_foo.foo = 6
814 ...
815 mockity-mock
816 >>> mock_foo.mock_calls
817 [call(), call(6)]
818
Michael Foordc2870622012-04-13 16:57:22 +0100819Because of the way mock attributes are stored you can't directly attach a
Georg Brandl7ad3df62014-10-31 07:59:37 +0100820:class:`PropertyMock` to a mock object. Instead you can attach it to the mock type
Michael Foordc2870622012-04-13 16:57:22 +0100821object::
822
823 >>> m = MagicMock()
824 >>> p = PropertyMock(return_value=3)
825 >>> type(m).foo = p
826 >>> m.foo
827 3
828 >>> p.assert_called_once_with()
829
Michael Foord944e02d2012-03-25 23:12:55 +0100830
831Calling
832~~~~~~~
833
834Mock objects are callable. The call will return the value set as the
835:attr:`~Mock.return_value` attribute. The default return value is a new Mock
836object; it is created the first time the return value is accessed (either
837explicitly or by calling the Mock) - but it is stored and the same one
838returned each time.
839
840Calls made to the object will be recorded in the attributes
841like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
842
843If :attr:`~Mock.side_effect` is set then it will be called after the call has
Georg Brandl7ad3df62014-10-31 07:59:37 +0100844been recorded, so if :attr:`side_effect` raises an exception the call is still
Michael Foord944e02d2012-03-25 23:12:55 +0100845recorded.
846
847The simplest way to make a mock raise an exception when called is to make
848:attr:`~Mock.side_effect` an exception class or instance:
849
850 >>> m = MagicMock(side_effect=IndexError)
851 >>> m(1, 2, 3)
852 Traceback (most recent call last):
853 ...
854 IndexError
855 >>> m.mock_calls
856 [call(1, 2, 3)]
857 >>> m.side_effect = KeyError('Bang!')
858 >>> m('two', 'three', 'four')
859 Traceback (most recent call last):
860 ...
861 KeyError: 'Bang!'
862 >>> m.mock_calls
863 [call(1, 2, 3), call('two', 'three', 'four')]
864
Georg Brandl7ad3df62014-10-31 07:59:37 +0100865If :attr:`side_effect` is a function then whatever that function returns is what
866calls to the mock return. The :attr:`side_effect` function is called with the
Michael Foord944e02d2012-03-25 23:12:55 +0100867same arguments as the mock. This allows you to vary the return value of the
868call dynamically, based on the input:
869
870 >>> def side_effect(value):
871 ... return value + 1
872 ...
873 >>> m = MagicMock(side_effect=side_effect)
874 >>> m(1)
875 2
876 >>> m(2)
877 3
878 >>> m.mock_calls
879 [call(1), call(2)]
880
881If you want the mock to still return the default return value (a new mock), or
882any set return value, then there are two ways of doing this. Either return
Georg Brandl7ad3df62014-10-31 07:59:37 +0100883:attr:`mock.return_value` from inside :attr:`side_effect`, or return :data:`DEFAULT`:
Michael Foord944e02d2012-03-25 23:12:55 +0100884
885 >>> m = MagicMock()
886 >>> def side_effect(*args, **kwargs):
887 ... return m.return_value
888 ...
889 >>> m.side_effect = side_effect
890 >>> m.return_value = 3
891 >>> m()
892 3
893 >>> def side_effect(*args, **kwargs):
894 ... return DEFAULT
895 ...
896 >>> m.side_effect = side_effect
897 >>> m()
898 3
899
Georg Brandl7ad3df62014-10-31 07:59:37 +0100900To remove a :attr:`side_effect`, and return to the default behaviour, set the
901:attr:`side_effect` to ``None``:
Michael Foord944e02d2012-03-25 23:12:55 +0100902
903 >>> m = MagicMock(return_value=6)
904 >>> def side_effect(*args, **kwargs):
905 ... return 3
906 ...
907 >>> m.side_effect = side_effect
908 >>> m()
909 3
910 >>> m.side_effect = None
911 >>> m()
912 6
913
Georg Brandl7ad3df62014-10-31 07:59:37 +0100914The :attr:`side_effect` can also be any iterable object. Repeated calls to the mock
Michael Foord944e02d2012-03-25 23:12:55 +0100915will return values from the iterable (until the iterable is exhausted and
Georg Brandl7ad3df62014-10-31 07:59:37 +0100916a :exc:`StopIteration` is raised):
Michael Foord944e02d2012-03-25 23:12:55 +0100917
918 >>> m = MagicMock(side_effect=[1, 2, 3])
919 >>> m()
920 1
921 >>> m()
922 2
923 >>> m()
924 3
925 >>> m()
926 Traceback (most recent call last):
927 ...
928 StopIteration
929
Michael Foord2cd48732012-04-21 15:52:11 +0100930If any members of the iterable are exceptions they will be raised instead of
931returned::
932
933 >>> iterable = (33, ValueError, 66)
934 >>> m = MagicMock(side_effect=iterable)
935 >>> m()
936 33
937 >>> m()
938 Traceback (most recent call last):
939 ...
940 ValueError
941 >>> m()
942 66
943
Michael Foord944e02d2012-03-25 23:12:55 +0100944
945.. _deleting-attributes:
946
947Deleting Attributes
948~~~~~~~~~~~~~~~~~~~
949
950Mock objects create attributes on demand. This allows them to pretend to be
951objects of any type.
952
Georg Brandl7ad3df62014-10-31 07:59:37 +0100953You may want a mock object to return ``False`` to a :func:`hasattr` call, or raise an
954:exc:`AttributeError` when an attribute is fetched. You can do this by providing
955an object as a :attr:`spec` for a mock, but that isn't always convenient.
Michael Foord944e02d2012-03-25 23:12:55 +0100956
957You "block" attributes by deleting them. Once deleted, accessing an attribute
Georg Brandl7ad3df62014-10-31 07:59:37 +0100958will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100959
960 >>> mock = MagicMock()
961 >>> hasattr(mock, 'm')
962 True
963 >>> del mock.m
964 >>> hasattr(mock, 'm')
965 False
966 >>> del mock.f
967 >>> mock.f
968 Traceback (most recent call last):
969 ...
970 AttributeError: f
971
972
Michael Foordf5752302013-03-18 15:04:03 -0700973Mock names and the name attribute
974~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
975
976Since "name" is an argument to the :class:`Mock` constructor, if you want your
977mock object to have a "name" attribute you can't just pass it in at creation
978time. There are two alternatives. One option is to use
979:meth:`~Mock.configure_mock`::
980
981 >>> mock = MagicMock()
982 >>> mock.configure_mock(name='my_name')
983 >>> mock.name
984 'my_name'
985
986A simpler option is to simply set the "name" attribute after mock creation::
987
988 >>> mock = MagicMock()
989 >>> mock.name = "foo"
990
991
Michael Foord944e02d2012-03-25 23:12:55 +0100992Attaching Mocks as Attributes
993~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
994
995When you attach a mock as an attribute of another mock (or as the return
996value) it becomes a "child" of that mock. Calls to the child are recorded in
997the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
998parent. This is useful for configuring child mocks and then attaching them to
999the parent, or for attaching mocks to a parent that records all calls to the
1000children and allows you to make assertions about the order of calls between
1001mocks:
1002
1003 >>> parent = MagicMock()
1004 >>> child1 = MagicMock(return_value=None)
1005 >>> child2 = MagicMock(return_value=None)
1006 >>> parent.child1 = child1
1007 >>> parent.child2 = child2
1008 >>> child1(1)
1009 >>> child2(2)
1010 >>> parent.mock_calls
1011 [call.child1(1), call.child2(2)]
1012
1013The exception to this is if the mock has a name. This allows you to prevent
1014the "parenting" if for some reason you don't want it to happen.
1015
1016 >>> mock = MagicMock()
1017 >>> not_a_child = MagicMock(name='not-a-child')
1018 >>> mock.attribute = not_a_child
1019 >>> mock.attribute()
1020 <MagicMock name='not-a-child()' id='...'>
1021 >>> mock.mock_calls
1022 []
1023
1024Mocks created for you by :func:`patch` are automatically given names. To
1025attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001026method::
Michael Foord944e02d2012-03-25 23:12:55 +01001027
1028 >>> thing1 = object()
1029 >>> thing2 = object()
1030 >>> parent = MagicMock()
1031 >>> with patch('__main__.thing1', return_value=None) as child1:
1032 ... with patch('__main__.thing2', return_value=None) as child2:
1033 ... parent.attach_mock(child1, 'child1')
1034 ... parent.attach_mock(child2, 'child2')
1035 ... child1('one')
1036 ... child2('two')
1037 ...
1038 >>> parent.mock_calls
1039 [call.child1('one'), call.child2('two')]
1040
1041
1042.. [#] The only exceptions are magic methods and attributes (those that have
1043 leading and trailing double underscores). Mock doesn't create these but
Georg Brandl7ad3df62014-10-31 07:59:37 +01001044 instead raises an :exc:`AttributeError`. This is because the interpreter
Michael Foord944e02d2012-03-25 23:12:55 +01001045 will often implicitly request these methods, and gets *very* confused to
1046 get a new Mock object when it expects a magic method. If you need magic
1047 method support see :ref:`magic methods <magic-methods>`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001048
1049
1050The patchers
Georg Brandlfb134382013-02-03 11:47:49 +01001051------------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001052
1053The patch decorators are used for patching objects only within the scope of
1054the function they decorate. They automatically handle the unpatching for you,
1055even if exceptions are raised. All of these functions can also be used in with
1056statements or as class decorators.
1057
1058
1059patch
Georg Brandlfb134382013-02-03 11:47:49 +01001060~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001061
1062.. note::
1063
Georg Brandl7ad3df62014-10-31 07:59:37 +01001064 :func:`patch` is straightforward to use. The key is to do the patching in the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001065 right namespace. See the section `where to patch`_.
1066
1067.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1068
Georg Brandl7ad3df62014-10-31 07:59:37 +01001069 :func:`patch` acts as a function decorator, class decorator or a context
1070 manager. Inside the body of the function or with statement, the *target*
1071 is patched with a *new* object. When the function/with statement exits
Michael Foord54b3db82012-03-28 15:08:08 +01001072 the patch is undone.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001073
Georg Brandl7ad3df62014-10-31 07:59:37 +01001074 If *new* is omitted, then the target is replaced with a
1075 :class:`MagicMock`. If :func:`patch` is used as a decorator and *new* is
Michael Foord54b3db82012-03-28 15:08:08 +01001076 omitted, the created mock is passed in as an extra argument to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001077 decorated function. If :func:`patch` is used as a context manager the created
Michael Foord54b3db82012-03-28 15:08:08 +01001078 mock is returned by the context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001079
Georg Brandl7ad3df62014-10-31 07:59:37 +01001080 *target* should be a string in the form ``'package.module.ClassName'``. The
1081 *target* is imported and the specified object replaced with the *new*
1082 object, so the *target* must be importable from the environment you are
1083 calling :func:`patch` from. The target is imported when the decorated function
Michael Foord54b3db82012-03-28 15:08:08 +01001084 is executed, not at decoration time.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001085
Georg Brandl7ad3df62014-10-31 07:59:37 +01001086 The *spec* and *spec_set* keyword arguments are passed to the :class:`MagicMock`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001087 if patch is creating one for you.
1088
Georg Brandl7ad3df62014-10-31 07:59:37 +01001089 In addition you can pass ``spec=True`` or ``spec_set=True``, which causes
Michael Foorda9e6fb22012-03-28 14:36:02 +01001090 patch to pass in the object being mocked as the spec/spec_set object.
1091
Georg Brandl7ad3df62014-10-31 07:59:37 +01001092 *new_callable* allows you to specify a different class, or callable object,
1093 that will be called to create the *new* object. By default :class:`MagicMock` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001094 used.
1095
Georg Brandl7ad3df62014-10-31 07:59:37 +01001096 A more powerful form of *spec* is *autospec*. If you set ``autospec=True``
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001097 then the mock will be created with a spec from the object being replaced.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001098 All attributes of the mock will also have the spec of the corresponding
1099 attribute of the object being replaced. Methods and functions being mocked
Georg Brandl7ad3df62014-10-31 07:59:37 +01001100 will have their arguments checked and will raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001101 called with the wrong signature. For mocks
1102 replacing a class, their return value (the 'instance') will have the same
1103 spec as the class. See the :func:`create_autospec` function and
1104 :ref:`auto-speccing`.
1105
Georg Brandl7ad3df62014-10-31 07:59:37 +01001106 Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001107 arbitrary object as the spec instead of the one being replaced.
1108
Georg Brandl7ad3df62014-10-31 07:59:37 +01001109 By default :func:`patch` will fail to replace attributes that don't exist. If
1110 you pass in ``create=True``, and the attribute doesn't exist, patch will
Michael Foorda9e6fb22012-03-28 14:36:02 +01001111 create the attribute for you when the patched function is called, and
1112 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001113 attributes that your production code creates at runtime. It is off by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001114 default because it can be dangerous. With it switched on you can write
1115 passing tests against APIs that don't actually exist!
1116
Michael Foordfddcfa22014-04-14 16:25:20 -04001117 .. note::
1118
1119 .. versionchanged:: 3.5
1120 If you are patching builtins in a module then you don't
Georg Brandl7ad3df62014-10-31 07:59:37 +01001121 need to pass ``create=True``, it will be added by default.
Michael Foordfddcfa22014-04-14 16:25:20 -04001122
Georg Brandl7ad3df62014-10-31 07:59:37 +01001123 Patch can be used as a :class:`TestCase` class decorator. It works by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001124 decorating each test method in the class. This reduces the boilerplate
Georg Brandl7ad3df62014-10-31 07:59:37 +01001125 code when your test methods share a common patchings set. :func:`patch` finds
1126 tests by looking for method names that start with ``patch.TEST_PREFIX``.
1127 By default this is ``'test'``, which matches the way :mod:`unittest` finds tests.
1128 You can specify an alternative prefix by setting ``patch.TEST_PREFIX``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001129
1130 Patch can be used as a context manager, with the with statement. Here the
1131 patching applies to the indented block after the with statement. If you
1132 use "as" then the patched object will be bound to the name after the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001133 "as"; very useful if :func:`patch` is creating a mock object for you.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001134
Georg Brandl7ad3df62014-10-31 07:59:37 +01001135 :func:`patch` takes arbitrary keyword arguments. These will be passed to
1136 the :class:`Mock` (or *new_callable*) on construction.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001137
Georg Brandl7ad3df62014-10-31 07:59:37 +01001138 ``patch.dict(...)``, ``patch.multiple(...)`` and ``patch.object(...)`` are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001139 available for alternate use-cases.
1140
Georg Brandl7ad3df62014-10-31 07:59:37 +01001141:func:`patch` as function decorator, creating the mock for you and passing it into
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001142the decorated function::
Michael Foord90155362012-03-28 15:32:08 +01001143
1144 >>> @patch('__main__.SomeClass')
Michael Foord324b58b2012-03-28 15:49:08 +01001145 ... def function(normal_argument, mock_class):
Michael Foord90155362012-03-28 15:32:08 +01001146 ... print(mock_class is SomeClass)
1147 ...
Michael Foord324b58b2012-03-28 15:49:08 +01001148 >>> function(None)
Michael Foord90155362012-03-28 15:32:08 +01001149 True
Michael Foorda9e6fb22012-03-28 14:36:02 +01001150
Georg Brandl7ad3df62014-10-31 07:59:37 +01001151Patching a class replaces the class with a :class:`MagicMock` *instance*. If the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001152class is instantiated in the code under test then it will be the
1153:attr:`~Mock.return_value` of the mock that will be used.
1154
1155If the class is instantiated multiple times you could use
1156:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
Georg Brandl7ad3df62014-10-31 07:59:37 +01001157can set the *return_value* to be anything you want.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001158
1159To configure return values on methods of *instances* on the patched class
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001160you must do this on the :attr:`return_value`. For example::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001161
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001162 >>> class Class:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001163 ... def method(self):
1164 ... pass
1165 ...
1166 >>> with patch('__main__.Class') as MockClass:
1167 ... instance = MockClass.return_value
1168 ... instance.method.return_value = 'foo'
1169 ... assert Class() is instance
1170 ... assert Class().method() == 'foo'
1171 ...
1172
Georg Brandl7ad3df62014-10-31 07:59:37 +01001173If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001174return value of the created mock will have the same spec. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001175
1176 >>> Original = Class
1177 >>> patcher = patch('__main__.Class', spec=True)
1178 >>> MockClass = patcher.start()
1179 >>> instance = MockClass()
1180 >>> assert isinstance(instance, Original)
1181 >>> patcher.stop()
1182
Georg Brandl7ad3df62014-10-31 07:59:37 +01001183The *new_callable* argument is useful where you want to use an alternative
Michael Foorda9e6fb22012-03-28 14:36:02 +01001184class to the default :class:`MagicMock` for the created mock. For example, if
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001185you wanted a :class:`NonCallableMock` to be used::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001186
1187 >>> thing = object()
1188 >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
1189 ... assert thing is mock_thing
1190 ... thing()
1191 ...
1192 Traceback (most recent call last):
1193 ...
1194 TypeError: 'NonCallableMock' object is not callable
1195
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001196Another use case might be to replace an object with an :class:`io.StringIO` instance::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001197
Serhiy Storchakae79be872013-08-17 00:09:55 +03001198 >>> from io import StringIO
Michael Foorda9e6fb22012-03-28 14:36:02 +01001199 >>> def foo():
Berker Peksag920f6db2015-09-10 21:41:15 +03001200 ... print('Something')
Michael Foorda9e6fb22012-03-28 14:36:02 +01001201 ...
1202 >>> @patch('sys.stdout', new_callable=StringIO)
1203 ... def test(mock_stdout):
1204 ... foo()
1205 ... assert mock_stdout.getvalue() == 'Something\n'
1206 ...
1207 >>> test()
1208
Georg Brandl7ad3df62014-10-31 07:59:37 +01001209When :func:`patch` is creating a mock for you, it is common that the first thing
Michael Foorda9e6fb22012-03-28 14:36:02 +01001210you need to do is to configure the mock. Some of that configuration can be done
1211in the call to patch. Any arbitrary keywords you pass into the call will be
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001212used to set attributes on the created mock::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001213
1214 >>> patcher = patch('__main__.thing', first='one', second='two')
1215 >>> mock_thing = patcher.start()
1216 >>> mock_thing.first
1217 'one'
1218 >>> mock_thing.second
1219 'two'
1220
1221As well as attributes on the created mock attributes, like the
1222:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
1223also be configured. These aren't syntactically valid to pass in directly as
1224keyword arguments, but a dictionary with these as keys can still be expanded
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001225into a :func:`patch` call using ``**``::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001226
1227 >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
1228 >>> patcher = patch('__main__.thing', **config)
1229 >>> mock_thing = patcher.start()
1230 >>> mock_thing.method()
1231 3
1232 >>> mock_thing.other()
1233 Traceback (most recent call last):
1234 ...
1235 KeyError
1236
1237
1238patch.object
Georg Brandlfb134382013-02-03 11:47:49 +01001239~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001240
1241.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1242
Georg Brandl7ad3df62014-10-31 07:59:37 +01001243 patch the named member (*attribute*) on an object (*target*) with a mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001244 object.
1245
Georg Brandl7ad3df62014-10-31 07:59:37 +01001246 :func:`patch.object` can be used as a decorator, class decorator or a context
1247 manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* and
1248 *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`,
1249 :func:`patch.object` takes arbitrary keyword arguments for configuring the mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001250 object it creates.
1251
Georg Brandl7ad3df62014-10-31 07:59:37 +01001252 When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001253 for choosing which methods to wrap.
1254
Georg Brandl7ad3df62014-10-31 07:59:37 +01001255You can either call :func:`patch.object` with three arguments or two arguments. The
Michael Foorda9e6fb22012-03-28 14:36:02 +01001256three argument form takes the object to be patched, the attribute name and the
1257object to replace the attribute with.
1258
1259When calling with the two argument form you omit the replacement object, and a
1260mock is created for you and passed in as an extra argument to the decorated
1261function:
1262
1263 >>> @patch.object(SomeClass, 'class_method')
1264 ... def test(mock_method):
1265 ... SomeClass.class_method(3)
1266 ... mock_method.assert_called_with(3)
1267 ...
1268 >>> test()
1269
Georg Brandl7ad3df62014-10-31 07:59:37 +01001270*spec*, *create* and the other arguments to :func:`patch.object` have the same
1271meaning as they do for :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001272
1273
1274patch.dict
Georg Brandlfb134382013-02-03 11:47:49 +01001275~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001276
1277.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs)
1278
1279 Patch a dictionary, or dictionary like object, and restore the dictionary
1280 to its original state after the test.
1281
Georg Brandl7ad3df62014-10-31 07:59:37 +01001282 *in_dict* can be a dictionary or a mapping like container. If it is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01001283 mapping then it must at least support getting, setting and deleting items
1284 plus iterating over keys.
1285
Georg Brandl7ad3df62014-10-31 07:59:37 +01001286 *in_dict* can also be a string specifying the name of the dictionary, which
Michael Foorda9e6fb22012-03-28 14:36:02 +01001287 will then be fetched by importing it.
1288
Georg Brandl7ad3df62014-10-31 07:59:37 +01001289 *values* can be a dictionary of values to set in the dictionary. *values*
1290 can also be an iterable of ``(key, value)`` pairs.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001291
Georg Brandl7ad3df62014-10-31 07:59:37 +01001292 If *clear* is true then the dictionary will be cleared before the new
Michael Foorda9e6fb22012-03-28 14:36:02 +01001293 values are set.
1294
Georg Brandl7ad3df62014-10-31 07:59:37 +01001295 :func:`patch.dict` can also be called with arbitrary keyword arguments to set
Michael Foorda9e6fb22012-03-28 14:36:02 +01001296 values in the dictionary.
1297
Georg Brandl7ad3df62014-10-31 07:59:37 +01001298 :func:`patch.dict` can be used as a context manager, decorator or class
1299 decorator. When used as a class decorator :func:`patch.dict` honours
1300 ``patch.TEST_PREFIX`` for choosing which methods to wrap.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001301
Georg Brandl7ad3df62014-10-31 07:59:37 +01001302:func:`patch.dict` can be used to add members to a dictionary, or simply let a test
Michael Foorda9e6fb22012-03-28 14:36:02 +01001303change a dictionary, and ensure the dictionary is restored when the test
1304ends.
1305
1306 >>> foo = {}
1307 >>> with patch.dict(foo, {'newkey': 'newvalue'}):
1308 ... assert foo == {'newkey': 'newvalue'}
1309 ...
1310 >>> assert foo == {}
1311
1312 >>> import os
1313 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
Berker Peksag920f6db2015-09-10 21:41:15 +03001314 ... print(os.environ['newkey'])
Michael Foorda9e6fb22012-03-28 14:36:02 +01001315 ...
1316 newvalue
1317 >>> assert 'newkey' not in os.environ
1318
Georg Brandl7ad3df62014-10-31 07:59:37 +01001319Keywords can be used in the :func:`patch.dict` call to set values in the dictionary:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001320
1321 >>> mymodule = MagicMock()
1322 >>> mymodule.function.return_value = 'fish'
1323 >>> with patch.dict('sys.modules', mymodule=mymodule):
1324 ... import mymodule
1325 ... mymodule.function('some', 'args')
1326 ...
1327 'fish'
1328
Georg Brandl7ad3df62014-10-31 07:59:37 +01001329:func:`patch.dict` can be used with dictionary like objects that aren't actually
Michael Foorda9e6fb22012-03-28 14:36:02 +01001330dictionaries. At the very minimum they must support item getting, setting,
1331deleting and either iteration or membership test. This corresponds to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001332magic methods :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__` and either
1333:meth:`__iter__` or :meth:`__contains__`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001334
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001335 >>> class Container:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001336 ... def __init__(self):
1337 ... self.values = {}
1338 ... def __getitem__(self, name):
1339 ... return self.values[name]
1340 ... def __setitem__(self, name, value):
1341 ... self.values[name] = value
1342 ... def __delitem__(self, name):
1343 ... del self.values[name]
1344 ... def __iter__(self):
1345 ... return iter(self.values)
1346 ...
1347 >>> thing = Container()
1348 >>> thing['one'] = 1
1349 >>> with patch.dict(thing, one=2, two=3):
1350 ... assert thing['one'] == 2
1351 ... assert thing['two'] == 3
1352 ...
1353 >>> assert thing['one'] == 1
1354 >>> assert list(thing) == ['one']
1355
1356
1357patch.multiple
Georg Brandlfb134382013-02-03 11:47:49 +01001358~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001359
1360.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1361
1362 Perform multiple patches in a single call. It takes the object to be
1363 patched (either as an object or a string to fetch the object by importing)
1364 and keyword arguments for the patches::
1365
1366 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1367 ...
1368
Georg Brandl7ad3df62014-10-31 07:59:37 +01001369 Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create
Michael Foorda9e6fb22012-03-28 14:36:02 +01001370 mocks for you. In this case the created mocks are passed into a decorated
Georg Brandl7ad3df62014-10-31 07:59:37 +01001371 function by keyword, and a dictionary is returned when :func:`patch.multiple` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001372 used as a context manager.
1373
Georg Brandl7ad3df62014-10-31 07:59:37 +01001374 :func:`patch.multiple` can be used as a decorator, class decorator or a context
1375 manager. The arguments *spec*, *spec_set*, *create*, *autospec* and
1376 *new_callable* have the same meaning as for :func:`patch`. These arguments will
1377 be applied to *all* patches done by :func:`patch.multiple`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001378
Georg Brandl7ad3df62014-10-31 07:59:37 +01001379 When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001380 for choosing which methods to wrap.
1381
Georg Brandl7ad3df62014-10-31 07:59:37 +01001382If you want :func:`patch.multiple` to create mocks for you, then you can use
1383:data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001384then the created mocks are passed into the decorated function by keyword. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001385
1386 >>> thing = object()
1387 >>> other = object()
1388
1389 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1390 ... def test_function(thing, other):
1391 ... assert isinstance(thing, MagicMock)
1392 ... assert isinstance(other, MagicMock)
1393 ...
1394 >>> test_function()
1395
Georg Brandl7ad3df62014-10-31 07:59:37 +01001396:func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001397passed by keyword *after* any of the standard arguments created by :func:`patch`::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001398
1399 >>> @patch('sys.exit')
1400 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1401 ... def test_function(mock_exit, other, thing):
1402 ... assert 'other' in repr(other)
1403 ... assert 'thing' in repr(thing)
1404 ... assert 'exit' in repr(mock_exit)
1405 ...
1406 >>> test_function()
1407
Georg Brandl7ad3df62014-10-31 07:59:37 +01001408If :func:`patch.multiple` is used as a context manager, the value returned by the
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001409context manger is a dictionary where created mocks are keyed by name::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001410
1411 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
1412 ... assert 'other' in repr(values['other'])
1413 ... assert 'thing' in repr(values['thing'])
1414 ... assert values['thing'] is thing
1415 ... assert values['other'] is other
1416 ...
1417
1418
1419.. _start-and-stop:
1420
1421patch methods: start and stop
Georg Brandlfb134382013-02-03 11:47:49 +01001422~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001423
Georg Brandl7ad3df62014-10-31 07:59:37 +01001424All the patchers have :meth:`start` and :meth:`stop` methods. These make it simpler to do
1425patching in ``setUp`` methods or where you want to do multiple patches without
Michael Foorda9e6fb22012-03-28 14:36:02 +01001426nesting decorators or with statements.
1427
Georg Brandl7ad3df62014-10-31 07:59:37 +01001428To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as
1429normal and keep a reference to the returned ``patcher`` object. You can then
1430call :meth:`start` to put the patch in place and :meth:`stop` to undo it.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001431
Georg Brandl7ad3df62014-10-31 07:59:37 +01001432If 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 +02001433the call to ``patcher.start``. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001434
1435 >>> patcher = patch('package.module.ClassName')
1436 >>> from package import module
1437 >>> original = module.ClassName
1438 >>> new_mock = patcher.start()
1439 >>> assert module.ClassName is not original
1440 >>> assert module.ClassName is new_mock
1441 >>> patcher.stop()
1442 >>> assert module.ClassName is original
1443 >>> assert module.ClassName is not new_mock
1444
1445
Georg Brandl7ad3df62014-10-31 07:59:37 +01001446A typical use case for this might be for doing multiple patches in the ``setUp``
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001447method of a :class:`TestCase`::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001448
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001449 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +01001450 ... def setUp(self):
1451 ... self.patcher1 = patch('package.module.Class1')
1452 ... self.patcher2 = patch('package.module.Class2')
1453 ... self.MockClass1 = self.patcher1.start()
1454 ... self.MockClass2 = self.patcher2.start()
1455 ...
1456 ... def tearDown(self):
1457 ... self.patcher1.stop()
1458 ... self.patcher2.stop()
1459 ...
1460 ... def test_something(self):
1461 ... assert package.module.Class1 is self.MockClass1
1462 ... assert package.module.Class2 is self.MockClass2
1463 ...
1464 >>> MyTest('test_something').run()
1465
1466.. caution::
1467
1468 If you use this technique you must ensure that the patching is "undone" by
Georg Brandl7ad3df62014-10-31 07:59:37 +01001469 calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001470 exception is raised in the ``setUp`` then ``tearDown`` is not called.
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001471 :meth:`unittest.TestCase.addCleanup` makes this easier::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001472
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001473 >>> class MyTest(unittest.TestCase):
Michael Foorda9e6fb22012-03-28 14:36:02 +01001474 ... def setUp(self):
1475 ... patcher = patch('package.module.Class')
1476 ... self.MockClass = patcher.start()
1477 ... self.addCleanup(patcher.stop)
1478 ...
1479 ... def test_something(self):
1480 ... assert package.module.Class is self.MockClass
1481 ...
1482
Georg Brandl7ad3df62014-10-31 07:59:37 +01001483 As an added bonus you no longer need to keep a reference to the ``patcher``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001484 object.
1485
Michael Foordf7c41582012-06-10 20:36:32 +01001486It is also possible to stop all patches which have been started by using
Georg Brandl7ad3df62014-10-31 07:59:37 +01001487:func:`patch.stopall`.
Michael Foordf7c41582012-06-10 20:36:32 +01001488
1489.. function:: patch.stopall
1490
Georg Brandl7ad3df62014-10-31 07:59:37 +01001491 Stop all active patches. Only stops patches started with ``start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001492
Georg Brandl7ad3df62014-10-31 07:59:37 +01001493
1494.. _patch-builtins:
Michael Foordfddcfa22014-04-14 16:25:20 -04001495
1496patch builtins
Georg Brandl7ad3df62014-10-31 07:59:37 +01001497~~~~~~~~~~~~~~
Michael Foordfddcfa22014-04-14 16:25:20 -04001498You can patch any builtins within a module. The following example patches
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001499builtin :func:`ord`::
Michael Foordfddcfa22014-04-14 16:25:20 -04001500
1501 >>> @patch('__main__.ord')
1502 ... def test(mock_ord):
1503 ... mock_ord.return_value = 101
1504 ... print(ord('c'))
1505 ...
1506 >>> test()
1507 101
1508
Michael Foorda9e6fb22012-03-28 14:36:02 +01001509
1510TEST_PREFIX
Georg Brandlfb134382013-02-03 11:47:49 +01001511~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001512
1513All of the patchers can be used as class decorators. When used in this way
1514they wrap every test method on the class. The patchers recognise methods that
Georg Brandl7ad3df62014-10-31 07:59:37 +01001515start with ``'test'`` as being test methods. This is the same way that the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001516:class:`unittest.TestLoader` finds test methods by default.
1517
1518It is possible that you want to use a different prefix for your tests. You can
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001519inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001520
1521 >>> patch.TEST_PREFIX = 'foo'
1522 >>> value = 3
1523 >>>
1524 >>> @patch('__main__.value', 'not three')
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001525 ... class Thing:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001526 ... def foo_one(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001527 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001528 ... def foo_two(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001529 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001530 ...
1531 >>>
1532 >>> Thing().foo_one()
1533 not three
1534 >>> Thing().foo_two()
1535 not three
1536 >>> value
1537 3
1538
1539
1540Nesting Patch Decorators
Georg Brandlfb134382013-02-03 11:47:49 +01001541~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001542
1543If you want to perform multiple patches then you can simply stack up the
1544decorators.
1545
1546You can stack up multiple patch decorators using this pattern:
1547
1548 >>> @patch.object(SomeClass, 'class_method')
1549 ... @patch.object(SomeClass, 'static_method')
1550 ... def test(mock1, mock2):
1551 ... assert SomeClass.static_method is mock1
1552 ... assert SomeClass.class_method is mock2
1553 ... SomeClass.static_method('foo')
1554 ... SomeClass.class_method('bar')
1555 ... return mock1, mock2
1556 ...
1557 >>> mock1, mock2 = test()
1558 >>> mock1.assert_called_once_with('foo')
1559 >>> mock2.assert_called_once_with('bar')
1560
1561
1562Note that the decorators are applied from the bottom upwards. This is the
1563standard way that Python applies decorators. The order of the created mocks
1564passed into your test function matches this order.
1565
1566
1567.. _where-to-patch:
1568
1569Where to patch
Georg Brandlfb134382013-02-03 11:47:49 +01001570~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001571
Georg Brandl7ad3df62014-10-31 07:59:37 +01001572:func:`patch` works by (temporarily) changing the object that a *name* points to with
Michael Foorda9e6fb22012-03-28 14:36:02 +01001573another one. There can be many names pointing to any individual object, so
1574for patching to work you must ensure that you patch the name used by the system
1575under test.
1576
1577The basic principle is that you patch where an object is *looked up*, which
1578is not necessarily the same place as where it is defined. A couple of
1579examples will help to clarify this.
1580
1581Imagine we have a project that we want to test with the following structure::
1582
1583 a.py
1584 -> Defines SomeClass
1585
1586 b.py
1587 -> from a import SomeClass
1588 -> some_function instantiates SomeClass
1589
Georg Brandl7ad3df62014-10-31 07:59:37 +01001590Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
1591:func:`patch`. The problem is that when we import module b, which we will have to
1592do then it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
1593``a.SomeClass`` then it will have no effect on our test; module b already has a
1594reference to the *real* ``SomeClass`` and it looks like our patching had no
Michael Foorda9e6fb22012-03-28 14:36:02 +01001595effect.
1596
Ben Lloyd15033d12017-05-22 12:06:56 +01001597The key is to patch out ``SomeClass`` where it is used (or where it is looked up).
1598In this case ``some_function`` will actually look up ``SomeClass`` in module b,
Michael Foorda9e6fb22012-03-28 14:36:02 +01001599where we have imported it. The patching should look like::
1600
1601 @patch('b.SomeClass')
1602
Georg Brandl7ad3df62014-10-31 07:59:37 +01001603However, consider the alternative scenario where instead of ``from a import
1604SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both
Michael Foorda9e6fb22012-03-28 14:36:02 +01001605of these import forms are common. In this case the class we want to patch is
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001606being looked up in the module and so we have to patch ``a.SomeClass`` instead::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001607
1608 @patch('a.SomeClass')
1609
1610
1611Patching Descriptors and Proxy Objects
Georg Brandlfb134382013-02-03 11:47:49 +01001612~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001613
1614Both patch_ and patch.object_ correctly patch and restore descriptors: class
1615methods, static methods and properties. You should patch these on the *class*
1616rather than an instance. They also work with *some* objects
Zachary Ware5ea5d2c2014-02-26 09:34:43 -06001617that proxy attribute access, like the `django settings object
Michael Foorda9e6fb22012-03-28 14:36:02 +01001618<http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
1619
1620
Michael Foord2309ed82012-03-28 15:38:36 +01001621MagicMock and magic method support
Georg Brandlfb134382013-02-03 11:47:49 +01001622----------------------------------
Michael Foord2309ed82012-03-28 15:38:36 +01001623
1624.. _magic-methods:
1625
1626Mocking Magic Methods
Georg Brandlfb134382013-02-03 11:47:49 +01001627~~~~~~~~~~~~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001628
1629:class:`Mock` supports mocking the Python protocol methods, also known as
1630"magic methods". This allows mock objects to replace containers or other
1631objects that implement Python protocols.
1632
1633Because magic methods are looked up differently from normal methods [#]_, this
1634support has been specially implemented. This means that only specific magic
1635methods are supported. The supported list includes *almost* all of them. If
1636there are any missing that you need please let us know.
1637
1638You mock magic methods by setting the method you are interested in to a function
1639or a mock instance. If you are using a function then it *must* take ``self`` as
1640the first argument [#]_.
1641
1642 >>> def __str__(self):
1643 ... return 'fooble'
1644 ...
1645 >>> mock = Mock()
1646 >>> mock.__str__ = __str__
1647 >>> str(mock)
1648 'fooble'
1649
1650 >>> mock = Mock()
1651 >>> mock.__str__ = Mock()
1652 >>> mock.__str__.return_value = 'fooble'
1653 >>> str(mock)
1654 'fooble'
1655
1656 >>> mock = Mock()
1657 >>> mock.__iter__ = Mock(return_value=iter([]))
1658 >>> list(mock)
1659 []
1660
1661One use case for this is for mocking objects used as context managers in a
Georg Brandl7ad3df62014-10-31 07:59:37 +01001662:keyword:`with` statement:
Michael Foord2309ed82012-03-28 15:38:36 +01001663
1664 >>> mock = Mock()
1665 >>> mock.__enter__ = Mock(return_value='foo')
1666 >>> mock.__exit__ = Mock(return_value=False)
1667 >>> with mock as m:
1668 ... assert m == 'foo'
1669 ...
1670 >>> mock.__enter__.assert_called_with()
1671 >>> mock.__exit__.assert_called_with(None, None, None)
1672
1673Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they
1674are recorded in :attr:`~Mock.mock_calls`.
1675
1676.. note::
1677
Georg Brandl7ad3df62014-10-31 07:59:37 +01001678 If you use the *spec* keyword argument to create a mock then attempting to
1679 set a magic method that isn't in the spec will raise an :exc:`AttributeError`.
Michael Foord2309ed82012-03-28 15:38:36 +01001680
1681The full list of supported magic methods is:
1682
1683* ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``
1684* ``__dir__``, ``__format__`` and ``__subclasses__``
John Reese6c4fab02018-05-22 13:01:10 -07001685* ``__round__``, ``__floor__``, ``__trunc__`` and ``__ceil__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001686* Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001687 ``__eq__`` and ``__ne__``
1688* Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``,
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001689 ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__``
1690 and ``__missing__``
Michael Foord2309ed82012-03-28 15:38:36 +01001691* Context manager: ``__enter__`` and ``__exit__``
1692* Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``
1693* The numeric methods (including right hand and in-place variants):
Serhiy Storchakac2ccce72015-03-12 22:01:30 +02001694 ``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__div__``, ``__truediv__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001695 ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``,
1696 ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001697* Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__``
1698 and ``__index__``
Michael Foord2309ed82012-03-28 15:38:36 +01001699* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
1700* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
1701 ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
Max Bélanger6c83d9f2018-10-25 14:48:58 -07001702* File system path representation: ``__fspath__``
1703
1704.. versionchanged:: 3.8
1705 Added support for :func:`os.PathLike.__fspath__`.
Michael Foord2309ed82012-03-28 15:38:36 +01001706
1707
1708The following methods exist but are *not* supported as they are either in use
1709by mock, can't be set dynamically, or can cause problems:
1710
1711* ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``
1712* ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``
1713
1714
1715
1716Magic Mock
Georg Brandlfb134382013-02-03 11:47:49 +01001717~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001718
Georg Brandl7ad3df62014-10-31 07:59:37 +01001719There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001720
1721
1722.. class:: MagicMock(*args, **kw)
1723
1724 ``MagicMock`` is a subclass of :class:`Mock` with default implementations
1725 of most of the magic methods. You can use ``MagicMock`` without having to
1726 configure the magic methods yourself.
1727
1728 The constructor parameters have the same meaning as for :class:`Mock`.
1729
Georg Brandl7ad3df62014-10-31 07:59:37 +01001730 If you use the *spec* or *spec_set* arguments then *only* magic methods
Michael Foord2309ed82012-03-28 15:38:36 +01001731 that exist in the spec will be created.
1732
1733
1734.. class:: NonCallableMagicMock(*args, **kw)
1735
Georg Brandl7ad3df62014-10-31 07:59:37 +01001736 A non-callable version of :class:`MagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001737
1738 The constructor parameters have the same meaning as for
Georg Brandl7ad3df62014-10-31 07:59:37 +01001739 :class:`MagicMock`, with the exception of *return_value* and
1740 *side_effect* which have no meaning on a non-callable mock.
Michael Foord2309ed82012-03-28 15:38:36 +01001741
Georg Brandl7ad3df62014-10-31 07:59:37 +01001742The magic methods are setup with :class:`MagicMock` objects, so you can configure them
Michael Foord2309ed82012-03-28 15:38:36 +01001743and use them in the usual way:
1744
1745 >>> mock = MagicMock()
1746 >>> mock[3] = 'fish'
1747 >>> mock.__setitem__.assert_called_with(3, 'fish')
1748 >>> mock.__getitem__.return_value = 'result'
1749 >>> mock[2]
1750 'result'
1751
1752By default many of the protocol methods are required to return objects of a
1753specific type. These methods are preconfigured with a default return value, so
1754that they can be used without you having to do anything if you aren't interested
1755in the return value. You can still *set* the return value manually if you want
1756to change the default.
1757
1758Methods and their defaults:
1759
1760* ``__lt__``: NotImplemented
1761* ``__gt__``: NotImplemented
1762* ``__le__``: NotImplemented
1763* ``__ge__``: NotImplemented
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001764* ``__int__``: 1
1765* ``__contains__``: False
Berker Peksag8fafc742016-04-11 12:23:04 +03001766* ``__len__``: 0
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001767* ``__iter__``: iter([])
1768* ``__exit__``: False
1769* ``__complex__``: 1j
1770* ``__float__``: 1.0
1771* ``__bool__``: True
1772* ``__index__``: 1
1773* ``__hash__``: default hash for the mock
1774* ``__str__``: default str for the mock
Michael Foord2309ed82012-03-28 15:38:36 +01001775* ``__sizeof__``: default sizeof for the mock
1776
1777For example:
1778
1779 >>> mock = MagicMock()
1780 >>> int(mock)
1781 1
1782 >>> len(mock)
1783 0
1784 >>> list(mock)
1785 []
1786 >>> object() in mock
1787 False
1788
Berker Peksag283f1aa2015-01-07 21:15:02 +02001789The two equality methods, :meth:`__eq__` and :meth:`__ne__`, are special.
1790They do the default equality comparison on identity, using the
1791:attr:`~Mock.side_effect` attribute, unless you change their return value to
1792return something else::
Michael Foord2309ed82012-03-28 15:38:36 +01001793
1794 >>> MagicMock() == 3
1795 False
1796 >>> MagicMock() != 3
1797 True
1798 >>> mock = MagicMock()
1799 >>> mock.__eq__.return_value = True
1800 >>> mock == 3
1801 True
1802
Georg Brandl7ad3df62014-10-31 07:59:37 +01001803The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
Michael Foord2309ed82012-03-28 15:38:36 +01001804required to be an iterator:
1805
1806 >>> mock = MagicMock()
1807 >>> mock.__iter__.return_value = ['a', 'b', 'c']
1808 >>> list(mock)
1809 ['a', 'b', 'c']
1810 >>> list(mock)
1811 ['a', 'b', 'c']
1812
1813If the return value *is* an iterator, then iterating over it once will consume
1814it and subsequent iterations will result in an empty list:
1815
1816 >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
1817 >>> list(mock)
1818 ['a', 'b', 'c']
1819 >>> list(mock)
1820 []
1821
1822``MagicMock`` has all of the supported magic methods configured except for some
1823of the obscure and obsolete ones. You can still set these up if you want.
1824
1825Magic methods that are supported but not setup by default in ``MagicMock`` are:
1826
1827* ``__subclasses__``
1828* ``__dir__``
1829* ``__format__``
1830* ``__get__``, ``__set__`` and ``__delete__``
1831* ``__reversed__`` and ``__missing__``
1832* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
1833 ``__getstate__`` and ``__setstate__``
1834* ``__getformat__`` and ``__setformat__``
1835
1836
1837
1838.. [#] Magic methods *should* be looked up on the class rather than the
1839 instance. Different versions of Python are inconsistent about applying this
1840 rule. The supported protocol methods should work with all supported versions
1841 of Python.
1842.. [#] The function is basically hooked up to the class, but each ``Mock``
1843 instance is kept isolated from the others.
1844
1845
Michael Foorda9e6fb22012-03-28 14:36:02 +01001846Helpers
Georg Brandlfb134382013-02-03 11:47:49 +01001847-------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001848
1849sentinel
Georg Brandlfb134382013-02-03 11:47:49 +01001850~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001851
1852.. data:: sentinel
1853
Andrés Delfinof85af032018-07-08 21:28:51 -03001854 The ``sentinel`` object provides a convenient way of providing unique
1855 objects for your tests.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001856
Andrés Delfinof85af032018-07-08 21:28:51 -03001857 Attributes are created on demand when you access them by name. Accessing
1858 the same attribute will always return the same object. The objects
1859 returned have a sensible repr so that test failure messages are readable.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001860
Serhiy Storchakad9c956f2017-01-11 20:13:03 +02001861 .. versionchanged:: 3.7
1862 The ``sentinel`` attributes now preserve their identity when they are
1863 :mod:`copied <copy>` or :mod:`pickled <pickle>`.
1864
Michael Foorda9e6fb22012-03-28 14:36:02 +01001865Sometimes when testing you need to test that a specific object is passed as an
1866argument to another method, or returned. It can be common to create named
Georg Brandl7ad3df62014-10-31 07:59:37 +01001867sentinel objects to test this. :data:`sentinel` provides a convenient way of
Michael Foorda9e6fb22012-03-28 14:36:02 +01001868creating and testing the identity of objects like this.
1869
Georg Brandl7ad3df62014-10-31 07:59:37 +01001870In this example we monkey patch ``method`` to return ``sentinel.some_object``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001871
1872 >>> real = ProductionClass()
1873 >>> real.method = Mock(name="method")
1874 >>> real.method.return_value = sentinel.some_object
1875 >>> result = real.method()
1876 >>> assert result is sentinel.some_object
1877 >>> sentinel.some_object
1878 sentinel.some_object
1879
1880
1881DEFAULT
Georg Brandlfb134382013-02-03 11:47:49 +01001882~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001883
1884
1885.. data:: DEFAULT
1886
Georg Brandl7ad3df62014-10-31 07:59:37 +01001887 The :data:`DEFAULT` object is a pre-created sentinel (actually
1888 ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001889 functions to indicate that the normal return value should be used.
1890
1891
Michael Foorda9e6fb22012-03-28 14:36:02 +01001892call
Georg Brandlfb134382013-02-03 11:47:49 +01001893~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001894
1895.. function:: call(*args, **kwargs)
1896
Georg Brandl7ad3df62014-10-31 07:59:37 +01001897 :func:`call` is a helper object for making simpler assertions, for comparing with
Georg Brandl24891672012-04-01 13:48:26 +02001898 :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
Georg Brandl7ad3df62014-10-31 07:59:37 +01001899 :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be
Michael Foorda9e6fb22012-03-28 14:36:02 +01001900 used with :meth:`~Mock.assert_has_calls`.
1901
1902 >>> m = MagicMock(return_value=None)
1903 >>> m(1, 2, a='foo', b='bar')
1904 >>> m()
1905 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
1906 True
1907
1908.. method:: call.call_list()
1909
Georg Brandl7ad3df62014-10-31 07:59:37 +01001910 For a call object that represents multiple calls, :meth:`call_list`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001911 returns a list of all the intermediate calls as well as the
1912 final call.
1913
Georg Brandl7ad3df62014-10-31 07:59:37 +01001914``call_list`` is particularly useful for making assertions on "chained calls". A
Michael Foorda9e6fb22012-03-28 14:36:02 +01001915chained call is multiple calls on a single line of code. This results in
1916multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
1917the sequence of calls can be tedious.
1918
1919:meth:`~call.call_list` can construct the sequence of calls from the same
1920chained call:
1921
1922 >>> m = MagicMock()
1923 >>> m(1).method(arg='foo').other('bar')(2.0)
1924 <MagicMock name='mock().method().other()()' id='...'>
1925 >>> kall = call(1).method(arg='foo').other('bar')(2.0)
1926 >>> kall.call_list()
1927 [call(1),
1928 call().method(arg='foo'),
1929 call().method().other('bar'),
1930 call().method().other()(2.0)]
1931 >>> m.mock_calls == kall.call_list()
1932 True
1933
1934.. _calls-as-tuples:
1935
Georg Brandl7ad3df62014-10-31 07:59:37 +01001936A ``call`` object is either a tuple of (positional args, keyword args) or
Michael Foorda9e6fb22012-03-28 14:36:02 +01001937(name, positional args, keyword args) depending on how it was constructed. When
Georg Brandl7ad3df62014-10-31 07:59:37 +01001938you construct them yourself this isn't particularly interesting, but the ``call``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001939objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
1940:attr:`Mock.mock_calls` attributes can be introspected to get at the individual
1941arguments they contain.
1942
Georg Brandl7ad3df62014-10-31 07:59:37 +01001943The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
1944are two-tuples of (positional args, keyword args) whereas the ``call`` objects
Michael Foorda9e6fb22012-03-28 14:36:02 +01001945in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
1946three-tuples of (name, positional args, keyword args).
1947
1948You can use their "tupleness" to pull out the individual arguments for more
1949complex introspection and assertions. The positional arguments are a tuple
1950(an empty tuple if there are no positional arguments) and the keyword
1951arguments are a dictionary:
1952
1953 >>> m = MagicMock(return_value=None)
1954 >>> m(1, 2, 3, arg='one', arg2='two')
1955 >>> kall = m.call_args
1956 >>> args, kwargs = kall
1957 >>> args
1958 (1, 2, 3)
1959 >>> kwargs
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001960 {'arg': 'one', 'arg2': 'two'}
Michael Foorda9e6fb22012-03-28 14:36:02 +01001961 >>> args is kall[0]
1962 True
1963 >>> kwargs is kall[1]
1964 True
1965
1966 >>> m = MagicMock()
1967 >>> m.foo(4, 5, 6, arg='two', arg2='three')
1968 <MagicMock name='mock.foo()' id='...'>
1969 >>> kall = m.mock_calls[0]
1970 >>> name, args, kwargs = kall
1971 >>> name
1972 'foo'
1973 >>> args
1974 (4, 5, 6)
1975 >>> kwargs
Stéphane Wirtel859c0682018-10-12 09:51:05 +02001976 {'arg': 'two', 'arg2': 'three'}
Michael Foorda9e6fb22012-03-28 14:36:02 +01001977 >>> name is m.mock_calls[0][0]
1978 True
1979
1980
1981create_autospec
Georg Brandlfb134382013-02-03 11:47:49 +01001982~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001983
1984.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
1985
1986 Create a mock object using another object as a spec. Attributes on the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001987 mock will use the corresponding attribute on the *spec* object as their
Michael Foorda9e6fb22012-03-28 14:36:02 +01001988 spec.
1989
1990 Functions or methods being mocked will have their arguments checked to
1991 ensure that they are called with the correct signature.
1992
Georg Brandl7ad3df62014-10-31 07:59:37 +01001993 If *spec_set* is ``True`` then attempting to set attributes that don't exist
1994 on the spec object will raise an :exc:`AttributeError`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001995
1996 If a class is used as a spec then the return value of the mock (the
1997 instance of the class) will have the same spec. You can use a class as the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001998 spec for an instance object by passing ``instance=True``. The returned mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001999 will only be callable if instances of the mock are callable.
2000
Georg Brandl7ad3df62014-10-31 07:59:37 +01002001 :func:`create_autospec` also takes arbitrary keyword arguments that are passed to
Michael Foorda9e6fb22012-03-28 14:36:02 +01002002 the constructor of the created mock.
2003
2004See :ref:`auto-speccing` for examples of how to use auto-speccing with
Georg Brandl7ad3df62014-10-31 07:59:37 +01002005:func:`create_autospec` and the *autospec* argument to :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002006
2007
2008ANY
Georg Brandlfb134382013-02-03 11:47:49 +01002009~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002010
2011.. data:: ANY
2012
2013Sometimes you may need to make assertions about *some* of the arguments in a
2014call to mock, but either not care about some of the arguments or want to pull
2015them individually out of :attr:`~Mock.call_args` and make more complex
2016assertions on them.
2017
2018To ignore certain arguments you can pass in objects that compare equal to
2019*everything*. Calls to :meth:`~Mock.assert_called_with` and
2020:meth:`~Mock.assert_called_once_with` will then succeed no matter what was
2021passed in.
2022
2023 >>> mock = Mock(return_value=None)
2024 >>> mock('foo', bar=object())
2025 >>> mock.assert_called_once_with('foo', bar=ANY)
2026
Georg Brandl7ad3df62014-10-31 07:59:37 +01002027:data:`ANY` can also be used in comparisons with call lists like
Michael Foorda9e6fb22012-03-28 14:36:02 +01002028:attr:`~Mock.mock_calls`:
2029
2030 >>> m = MagicMock(return_value=None)
2031 >>> m(1)
2032 >>> m(1, 2)
2033 >>> m(object())
2034 >>> m.mock_calls == [call(1), call(1, 2), ANY]
2035 True
2036
2037
2038
2039FILTER_DIR
Georg Brandlfb134382013-02-03 11:47:49 +01002040~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002041
2042.. data:: FILTER_DIR
2043
Georg Brandl7ad3df62014-10-31 07:59:37 +01002044:data:`FILTER_DIR` is a module level variable that controls the way mock objects
2045respond to :func:`dir` (only for Python 2.6 or more recent). The default is ``True``,
Michael Foorda9e6fb22012-03-28 14:36:02 +01002046which uses the filtering described below, to only show useful members. If you
2047dislike this filtering, or need to switch it off for diagnostic purposes, then
Georg Brandl7ad3df62014-10-31 07:59:37 +01002048set ``mock.FILTER_DIR = False``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002049
Georg Brandl7ad3df62014-10-31 07:59:37 +01002050With filtering on, ``dir(some_mock)`` shows only useful attributes and will
Michael Foorda9e6fb22012-03-28 14:36:02 +01002051include any dynamically created attributes that wouldn't normally be shown.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002052If the mock was created with a *spec* (or *autospec* of course) then all the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002053attributes from the original are shown, even if they haven't been accessed
2054yet:
2055
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002056.. doctest::
2057 :options: +ELLIPSIS,+NORMALIZE_WHITESPACE
2058
Michael Foorda9e6fb22012-03-28 14:36:02 +01002059 >>> dir(Mock())
2060 ['assert_any_call',
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002061 'assert_called',
2062 'assert_called_once',
Michael Foorda9e6fb22012-03-28 14:36:02 +01002063 'assert_called_once_with',
2064 'assert_called_with',
2065 'assert_has_calls',
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002066 'assert_not_called',
Michael Foorda9e6fb22012-03-28 14:36:02 +01002067 'attach_mock',
2068 ...
2069 >>> from urllib import request
2070 >>> dir(Mock(spec=request))
2071 ['AbstractBasicAuthHandler',
2072 'AbstractDigestAuthHandler',
2073 'AbstractHTTPHandler',
2074 'BaseHandler',
2075 ...
2076
Georg Brandl7ad3df62014-10-31 07:59:37 +01002077Many of the not-very-useful (private to :class:`Mock` rather than the thing being
Michael Foorda9e6fb22012-03-28 14:36:02 +01002078mocked) underscore and double underscore prefixed attributes have been
Georg Brandl7ad3df62014-10-31 07:59:37 +01002079filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this
Michael Foorda9e6fb22012-03-28 14:36:02 +01002080behaviour you can switch it off by setting the module level switch
Georg Brandl7ad3df62014-10-31 07:59:37 +01002081:data:`FILTER_DIR`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002082
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002083.. doctest::
2084 :options: +ELLIPSIS,+NORMALIZE_WHITESPACE
2085
Michael Foorda9e6fb22012-03-28 14:36:02 +01002086 >>> from unittest import mock
2087 >>> mock.FILTER_DIR = False
2088 >>> dir(mock.Mock())
2089 ['_NonCallableMock__get_return_value',
2090 '_NonCallableMock__get_side_effect',
2091 '_NonCallableMock__return_value_doc',
2092 '_NonCallableMock__set_return_value',
2093 '_NonCallableMock__set_side_effect',
2094 '__call__',
2095 '__class__',
2096 ...
2097
Georg Brandl7ad3df62014-10-31 07:59:37 +01002098Alternatively you can just use ``vars(my_mock)`` (instance members) and
2099``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of
2100:data:`mock.FILTER_DIR`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002101
2102
2103mock_open
Georg Brandlfb134382013-02-03 11:47:49 +01002104~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002105
2106.. function:: mock_open(mock=None, read_data=None)
2107
Andrés Delfinof85af032018-07-08 21:28:51 -03002108 A helper function to create a mock to replace the use of :func:`open`. It works
2109 for :func:`open` called directly or used as a context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002110
Andrés Delfinof85af032018-07-08 21:28:51 -03002111 The *mock* argument is the mock object to configure. If ``None`` (the
2112 default) then a :class:`MagicMock` will be created for you, with the API limited
2113 to methods or attributes available on standard file handles.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002114
Andrés Delfinof85af032018-07-08 21:28:51 -03002115 *read_data* is a string for the :meth:`~io.IOBase.read`,
2116 :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods
2117 of the file handle to return. Calls to those methods will take data from
2118 *read_data* until it is depleted. The mock of these methods is pretty
2119 simplistic: every time the *mock* is called, the *read_data* is rewound to
2120 the start. If you need more control over the data that you are feeding to
2121 the tested code you will need to customize this mock for yourself. When that
2122 is insufficient, one of the in-memory filesystem packages on `PyPI
2123 <https://pypi.org>`_ can offer a realistic filesystem for testing.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002124
Robert Collinsf79dfe32015-07-24 04:09:59 +12002125 .. versionchanged:: 3.4
2126 Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support.
2127 The mock of :meth:`~io.IOBase.read` changed to consume *read_data* rather
2128 than returning it on each call.
2129
Robert Collins70398392015-07-24 04:10:27 +12002130 .. versionchanged:: 3.5
Robert Collinsf79dfe32015-07-24 04:09:59 +12002131 *read_data* is now reset on each call to the *mock*.
2132
Tony Flury20870232018-09-12 23:21:16 +01002133 .. versionchanged:: 3.8
2134 Added :meth:`__iter__` to implementation so that iteration (such as in for
2135 loops) correctly consumes *read_data*.
2136
Georg Brandl7ad3df62014-10-31 07:59:37 +01002137Using :func:`open` as a context manager is a great way to ensure your file handles
Michael Foorda9e6fb22012-03-28 14:36:02 +01002138are closed properly and is becoming common::
2139
2140 with open('/some/path', 'w') as f:
2141 f.write('something')
2142
Georg Brandl7ad3df62014-10-31 07:59:37 +01002143The issue is that even if you mock out the call to :func:`open` it is the
2144*returned object* that is used as a context manager (and has :meth:`__enter__` and
2145:meth:`__exit__` called).
Michael Foorda9e6fb22012-03-28 14:36:02 +01002146
2147Mocking context managers with a :class:`MagicMock` is common enough and fiddly
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002148enough that a helper function is useful. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002149
2150 >>> m = mock_open()
Michael Foordfddcfa22014-04-14 16:25:20 -04002151 >>> with patch('__main__.open', m):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002152 ... with open('foo', 'w') as h:
2153 ... h.write('some stuff')
2154 ...
2155 >>> m.mock_calls
2156 [call('foo', 'w'),
2157 call().__enter__(),
2158 call().write('some stuff'),
2159 call().__exit__(None, None, None)]
2160 >>> m.assert_called_once_with('foo', 'w')
2161 >>> handle = m()
2162 >>> handle.write.assert_called_once_with('some stuff')
2163
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002164And for reading files::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002165
Michael Foordfddcfa22014-04-14 16:25:20 -04002166 >>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002167 ... with open('foo') as h:
2168 ... result = h.read()
2169 ...
2170 >>> m.assert_called_once_with('foo')
2171 >>> assert result == 'bibble'
2172
2173
2174.. _auto-speccing:
2175
2176Autospeccing
Georg Brandlfb134382013-02-03 11:47:49 +01002177~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002178
Georg Brandl7ad3df62014-10-31 07:59:37 +01002179Autospeccing is based on the existing :attr:`spec` feature of mock. It limits the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002180api of mocks to the api of an original object (the spec), but it is recursive
2181(implemented lazily) so that attributes of mocks only have the same api as
2182the attributes of the spec. In addition mocked functions / methods have the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002183same call signature as the original so they raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002184called incorrectly.
2185
2186Before I explain how auto-speccing works, here's why it is needed.
2187
Georg Brandl7ad3df62014-10-31 07:59:37 +01002188:class:`Mock` is a very powerful and flexible object, but it suffers from two flaws
Michael Foorda9e6fb22012-03-28 14:36:02 +01002189when used to mock out objects from a system under test. One of these flaws is
Georg Brandl7ad3df62014-10-31 07:59:37 +01002190specific to the :class:`Mock` api and the other is a more general problem with using
Michael Foorda9e6fb22012-03-28 14:36:02 +01002191mock objects.
2192
Georg Brandl7ad3df62014-10-31 07:59:37 +01002193First the problem specific to :class:`Mock`. :class:`Mock` has two assert methods that are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002194extremely handy: :meth:`~Mock.assert_called_with` and
2195:meth:`~Mock.assert_called_once_with`.
2196
2197 >>> mock = Mock(name='Thing', return_value=None)
2198 >>> mock(1, 2, 3)
2199 >>> mock.assert_called_once_with(1, 2, 3)
2200 >>> mock(1, 2, 3)
2201 >>> mock.assert_called_once_with(1, 2, 3)
2202 Traceback (most recent call last):
2203 ...
Michael Foord28d591c2012-09-28 16:15:22 +01002204 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002205
2206Because mocks auto-create attributes on demand, and allow you to call them
2207with arbitrary arguments, if you misspell one of these assert methods then
2208your assertion is gone:
2209
2210.. code-block:: pycon
2211
2212 >>> mock = Mock(name='Thing', return_value=None)
2213 >>> mock(1, 2, 3)
2214 >>> mock.assret_called_once_with(4, 5, 6)
2215
2216Your tests can pass silently and incorrectly because of the typo.
2217
2218The second issue is more general to mocking. If you refactor some of your
2219code, rename members and so on, any tests for code that is still using the
2220*old api* but uses mocks instead of the real objects will still pass. This
2221means your tests can all pass even though your code is broken.
2222
2223Note that this is another reason why you need integration tests as well as
2224unit tests. Testing everything in isolation is all fine and dandy, but if you
2225don't test how your units are "wired together" there is still lots of room
2226for bugs that tests might have caught.
2227
Georg Brandl7ad3df62014-10-31 07:59:37 +01002228:mod:`mock` already provides a feature to help with this, called speccing. If you
2229use a class or instance as the :attr:`spec` for a mock then you can only access
Michael Foorda9e6fb22012-03-28 14:36:02 +01002230attributes on the mock that exist on the real class:
2231
2232 >>> from urllib import request
2233 >>> mock = Mock(spec=request.Request)
2234 >>> mock.assret_called_with
2235 Traceback (most recent call last):
2236 ...
2237 AttributeError: Mock object has no attribute 'assret_called_with'
2238
2239The spec only applies to the mock itself, so we still have the same issue
2240with any methods on the mock:
2241
2242.. code-block:: pycon
2243
2244 >>> mock.has_data()
2245 <mock.Mock object at 0x...>
2246 >>> mock.has_data.assret_called_with()
2247
Georg Brandl7ad3df62014-10-31 07:59:37 +01002248Auto-speccing solves this problem. You can either pass ``autospec=True`` to
2249:func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a
2250mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002251object that is being replaced will be used as the spec object. Because the
2252speccing is done "lazily" (the spec is created as attributes on the mock are
2253accessed) you can use it with very complex or deeply nested objects (like
2254modules that import modules that import modules) without a big performance
2255hit.
2256
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002257Here's an example of it in use::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002258
2259 >>> from urllib import request
2260 >>> patcher = patch('__main__.request', autospec=True)
2261 >>> mock_request = patcher.start()
2262 >>> request is mock_request
2263 True
2264 >>> mock_request.Request
2265 <MagicMock name='request.Request' spec='Request' id='...'>
2266
Georg Brandl7ad3df62014-10-31 07:59:37 +01002267You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two
2268arguments in the constructor (one of which is *self*). Here's what happens if
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002269we try to call it incorrectly::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002270
2271 >>> req = request.Request()
2272 Traceback (most recent call last):
2273 ...
2274 TypeError: <lambda>() takes at least 2 arguments (1 given)
2275
2276The spec also applies to instantiated classes (i.e. the return value of
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002277specced mocks)::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002278
2279 >>> req = request.Request('foo')
2280 >>> req
2281 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
2282
Georg Brandl7ad3df62014-10-31 07:59:37 +01002283:class:`Request` objects are not callable, so the return value of instantiating our
2284mocked out :class:`request.Request` is a non-callable mock. With the spec in place
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002285any typos in our asserts will raise the correct error::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002286
2287 >>> req.add_header('spam', 'eggs')
2288 <MagicMock name='request.Request().add_header()' id='...'>
2289 >>> req.add_header.assret_called_with
2290 Traceback (most recent call last):
2291 ...
2292 AttributeError: Mock object has no attribute 'assret_called_with'
2293 >>> req.add_header.assert_called_with('spam', 'eggs')
2294
Georg Brandl7ad3df62014-10-31 07:59:37 +01002295In many cases you will just be able to add ``autospec=True`` to your existing
2296:func:`patch` calls and then be protected against bugs due to typos and api
Michael Foorda9e6fb22012-03-28 14:36:02 +01002297changes.
2298
Georg Brandl7ad3df62014-10-31 07:59:37 +01002299As well as using *autospec* through :func:`patch` there is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002300:func:`create_autospec` for creating autospecced mocks directly:
2301
2302 >>> from urllib import request
2303 >>> mock_request = create_autospec(request)
2304 >>> mock_request.Request('foo', 'bar')
2305 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
2306
2307This isn't without caveats and limitations however, which is why it is not
2308the default behaviour. In order to know what attributes are available on the
2309spec object, autospec has to introspect (access attributes) the spec. As you
2310traverse attributes on the mock a corresponding traversal of the original
2311object is happening under the hood. If any of your specced objects have
2312properties or descriptors that can trigger code execution then you may not be
2313able to use autospec. On the other hand it is much better to design your
2314objects so that introspection is safe [#]_.
2315
2316A more serious problem is that it is common for instance attributes to be
Georg Brandl7ad3df62014-10-31 07:59:37 +01002317created in the :meth:`__init__` method and not to exist on the class at all.
2318*autospec* can't know about any dynamically created attributes and restricts
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002319the api to visible attributes. ::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002320
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002321 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002322 ... def __init__(self):
2323 ... self.a = 33
2324 ...
2325 >>> with patch('__main__.Something', autospec=True):
2326 ... thing = Something()
2327 ... thing.a
2328 ...
2329 Traceback (most recent call last):
2330 ...
2331 AttributeError: Mock object has no attribute 'a'
2332
2333There are a few different ways of resolving this problem. The easiest, but
2334not necessarily the least annoying, way is to simply set the required
Georg Brandl7ad3df62014-10-31 07:59:37 +01002335attributes on the mock after creation. Just because *autospec* doesn't allow
Michael Foorda9e6fb22012-03-28 14:36:02 +01002336you to fetch attributes that don't exist on the spec it doesn't prevent you
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002337setting them::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002338
2339 >>> with patch('__main__.Something', autospec=True):
2340 ... thing = Something()
2341 ... thing.a = 33
2342 ...
2343
Georg Brandl7ad3df62014-10-31 07:59:37 +01002344There is a more aggressive version of both *spec* and *autospec* that *does*
Michael Foorda9e6fb22012-03-28 14:36:02 +01002345prevent you setting non-existent attributes. This is useful if you want to
2346ensure your code only *sets* valid attributes too, but obviously it prevents
2347this particular scenario:
2348
2349 >>> with patch('__main__.Something', autospec=True, spec_set=True):
2350 ... thing = Something()
2351 ... thing.a = 33
2352 ...
2353 Traceback (most recent call last):
2354 ...
2355 AttributeError: Mock object has no attribute 'a'
2356
2357Probably the best way of solving the problem is to add class attributes as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002358default values for instance members initialised in :meth:`__init__`. Note that if
2359you are only setting default attributes in :meth:`__init__` then providing them via
Michael Foorda9e6fb22012-03-28 14:36:02 +01002360class attributes (shared between instances of course) is faster too. e.g.
2361
2362.. code-block:: python
2363
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002364 class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002365 a = 33
2366
2367This brings up another issue. It is relatively common to provide a default
Georg Brandl7ad3df62014-10-31 07:59:37 +01002368value of ``None`` for members that will later be an object of a different type.
2369``None`` would be useless as a spec because it wouldn't let you access *any*
2370attributes or methods on it. As ``None`` is *never* going to be useful as a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002371spec, and probably indicates a member that will normally of some other type,
Georg Brandl7ad3df62014-10-31 07:59:37 +01002372autospec doesn't use a spec for members that are set to ``None``. These will
2373just be ordinary mocks (well - MagicMocks):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002374
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002375 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002376 ... member = None
2377 ...
2378 >>> mock = create_autospec(Something)
2379 >>> mock.member.foo.bar.baz()
2380 <MagicMock name='mock.member.foo.bar.baz()' id='...'>
2381
2382If modifying your production classes to add defaults isn't to your liking
2383then there are more options. One of these is simply to use an instance as the
2384spec rather than the class. The other is to create a subclass of the
2385production class and add the defaults to the subclass without affecting the
2386production class. Both of these require you to use an alternative object as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002387the spec. Thankfully :func:`patch` supports this - you can simply pass the
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002388alternative object as the *autospec* argument::
Michael Foorda9e6fb22012-03-28 14:36:02 +01002389
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002390 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002391 ... def __init__(self):
2392 ... self.a = 33
2393 ...
2394 >>> class SomethingForTest(Something):
2395 ... a = 33
2396 ...
2397 >>> p = patch('__main__.Something', autospec=SomethingForTest)
2398 >>> mock = p.start()
2399 >>> mock.a
2400 <NonCallableMagicMock name='Something.a' spec='int' id='...'>
2401
2402
2403.. [#] This only applies to classes or already instantiated objects. Calling
2404 a mocked class to create a mock instance *does not* create a real instance.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002405 It is only attribute lookups - along with calls to :func:`dir` - that are done.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002406
Mario Corchero552be9d2017-10-17 12:35:11 +01002407Sealing mocks
2408~~~~~~~~~~~~~
2409
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002410
2411.. testsetup::
2412
2413 from unittest.mock import seal
2414
Mario Corchero552be9d2017-10-17 12:35:11 +01002415.. function:: seal(mock)
2416
Mario Corchero96200eb2018-10-19 22:57:37 +01002417 Seal will disable the automatic creation of mocks when accessing an attribute of
2418 the mock being sealed or any of its attributes that are already mocks recursively.
Mario Corchero552be9d2017-10-17 12:35:11 +01002419
Mario Corchero96200eb2018-10-19 22:57:37 +01002420 If a mock instance with a name or a spec is assigned to an attribute
Paul Ganssle85ac7262018-01-06 08:25:34 -05002421 it won't be considered in the sealing chain. This allows one to prevent seal from
Stéphane Wirtel859c0682018-10-12 09:51:05 +02002422 fixing part of the mock object. ::
Mario Corchero552be9d2017-10-17 12:35:11 +01002423
2424 >>> mock = Mock()
2425 >>> mock.submock.attribute1 = 2
Mario Corchero96200eb2018-10-19 22:57:37 +01002426 >>> mock.not_submock = mock.Mock(name="sample_name")
Mario Corchero552be9d2017-10-17 12:35:11 +01002427 >>> seal(mock)
Mario Corchero96200eb2018-10-19 22:57:37 +01002428 >>> mock.new_attribute # This will raise AttributeError.
Mario Corchero552be9d2017-10-17 12:35:11 +01002429 >>> mock.submock.attribute2 # This will raise AttributeError.
2430 >>> mock.not_submock.attribute2 # This won't raise.
2431
2432 .. versionadded:: 3.7