blob: 1bc1edb8dbdc01fe62f90151e102b5dcf45cc373 [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,
Georg Brandle73778c2014-10-29 08:36:35 +010038available as `mock on PyPI <https://pypi.python.org/pypi/mock>`_.
Michael Foord944e02d2012-03-25 23:12:55 +010039
Michael Foord944e02d2012-03-25 23:12:55 +010040
41Quick Guide
42-----------
43
44:class:`Mock` and :class:`MagicMock` objects create all attributes and
45methods as you access them and store details of how they have been used. You
46can configure them, to specify return values or limit what attributes are
47available, and then make assertions about how they have been used:
48
49 >>> from unittest.mock import MagicMock
50 >>> thing = ProductionClass()
51 >>> thing.method = MagicMock(return_value=3)
52 >>> thing.method(3, 4, 5, key='value')
53 3
54 >>> thing.method.assert_called_with(3, 4, 5, key='value')
55
56:attr:`side_effect` allows you to perform side effects, including raising an
57exception when a mock is called:
58
59 >>> mock = Mock(side_effect=KeyError('foo'))
60 >>> mock()
61 Traceback (most recent call last):
62 ...
63 KeyError: 'foo'
64
65 >>> values = {'a': 1, 'b': 2, 'c': 3}
66 >>> def side_effect(arg):
67 ... return values[arg]
68 ...
69 >>> mock.side_effect = side_effect
70 >>> mock('a'), mock('b'), mock('c')
71 (1, 2, 3)
72 >>> mock.side_effect = [5, 4, 3, 2, 1]
73 >>> mock(), mock(), mock()
74 (5, 4, 3)
75
76Mock has many other ways you can configure it and control its behaviour. For
Georg Brandl7ad3df62014-10-31 07:59:37 +010077example the *spec* argument configures the mock to take its specification
Michael Foord944e02d2012-03-25 23:12:55 +010078from another object. Attempting to access attributes or methods on the mock
Georg Brandl7ad3df62014-10-31 07:59:37 +010079that don't exist on the spec will fail with an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +010080
81The :func:`patch` decorator / context manager makes it easy to mock classes or
82objects in a module under test. The object you specify will be replaced with a
83mock (or other object) during the test and restored when the test ends:
84
85 >>> from unittest.mock import patch
86 >>> @patch('module.ClassName2')
87 ... @patch('module.ClassName1')
88 ... def test(MockClass1, MockClass2):
89 ... module.ClassName1()
90 ... module.ClassName2()
Michael Foord944e02d2012-03-25 23:12:55 +010091 ... assert MockClass1 is module.ClassName1
92 ... assert MockClass2 is module.ClassName2
93 ... assert MockClass1.called
94 ... assert MockClass2.called
95 ...
96 >>> test()
97
98.. note::
99
100 When you nest patch decorators the mocks are passed in to the decorated
101 function in the same order they applied (the normal *python* order that
102 decorators are applied). This means from the bottom up, so in the example
Georg Brandl7ad3df62014-10-31 07:59:37 +0100103 above the mock for ``module.ClassName1`` is passed in first.
Michael Foord944e02d2012-03-25 23:12:55 +0100104
Georg Brandl7ad3df62014-10-31 07:59:37 +0100105 With :func:`patch` it matters that you patch objects in the namespace where they
Michael Foord944e02d2012-03-25 23:12:55 +0100106 are looked up. This is normally straightforward, but for a quick guide
107 read :ref:`where to patch <where-to-patch>`.
108
Georg Brandl7ad3df62014-10-31 07:59:37 +0100109As well as a decorator :func:`patch` can be used as a context manager in a with
Michael Foord944e02d2012-03-25 23:12:55 +0100110statement:
111
112 >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
113 ... thing = ProductionClass()
114 ... thing.method(1, 2, 3)
115 ...
116 >>> mock_method.assert_called_once_with(1, 2, 3)
117
118
119There is also :func:`patch.dict` for setting values in a dictionary just
120during a scope and restoring the dictionary to its original state when the test
121ends:
122
123 >>> foo = {'key': 'value'}
124 >>> original = foo.copy()
125 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
126 ... assert foo == {'newkey': 'newvalue'}
127 ...
128 >>> assert foo == original
129
130Mock supports the mocking of Python :ref:`magic methods <magic-methods>`. The
131easiest way of using magic methods is with the :class:`MagicMock` class. It
132allows you to do things like:
133
134 >>> mock = MagicMock()
135 >>> mock.__str__.return_value = 'foobarbaz'
136 >>> str(mock)
137 'foobarbaz'
138 >>> mock.__str__.assert_called_with()
139
140Mock allows you to assign functions (or other Mock instances) to magic methods
Georg Brandl7ad3df62014-10-31 07:59:37 +0100141and they will be called appropriately. The :class:`MagicMock` class is just a Mock
Michael Foord944e02d2012-03-25 23:12:55 +0100142variant that has all of the magic methods pre-created for you (well, all the
143useful ones anyway).
144
145The following is an example of using magic methods with the ordinary Mock
146class:
147
148 >>> mock = Mock()
149 >>> mock.__str__ = Mock(return_value='wheeeeee')
150 >>> str(mock)
151 'wheeeeee'
152
153For ensuring that the mock objects in your tests have the same api as the
154objects they are replacing, you can use :ref:`auto-speccing <auto-speccing>`.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100155Auto-speccing can be done through the *autospec* argument to patch, or the
Michael Foord944e02d2012-03-25 23:12:55 +0100156:func:`create_autospec` function. Auto-speccing creates mock objects that
157have the same attributes and methods as the objects they are replacing, and
158any functions and methods (including constructors) have the same call
159signature as the real object.
160
161This ensures that your mocks will fail in the same way as your production
162code if they are used incorrectly:
163
164 >>> from unittest.mock import create_autospec
165 >>> def function(a, b, c):
166 ... pass
167 ...
168 >>> mock_function = create_autospec(function, return_value='fishy')
169 >>> mock_function(1, 2, 3)
170 'fishy'
171 >>> mock_function.assert_called_once_with(1, 2, 3)
172 >>> mock_function('wrong arguments')
173 Traceback (most recent call last):
174 ...
175 TypeError: <lambda>() takes exactly 3 arguments (1 given)
176
Georg Brandl7ad3df62014-10-31 07:59:37 +0100177:func:`create_autospec` can also be used on classes, where it copies the signature of
178the ``__init__`` method, and on callable objects where it copies the signature of
179the ``__call__`` method.
Michael Foord944e02d2012-03-25 23:12:55 +0100180
181
182
183The Mock Class
184--------------
185
186
Georg Brandl7ad3df62014-10-31 07:59:37 +0100187:class:`Mock` is a flexible mock object intended to replace the use of stubs and
Michael Foord944e02d2012-03-25 23:12:55 +0100188test doubles throughout your code. Mocks are callable and create attributes as
189new mocks when you access them [#]_. Accessing the same attribute will always
190return the same mock. Mocks record how you use them, allowing you to make
191assertions about what your code has done to them.
192
Georg Brandl7ad3df62014-10-31 07:59:37 +0100193:class:`MagicMock` is a subclass of :class:`Mock` with all the magic methods
Michael Foord944e02d2012-03-25 23:12:55 +0100194pre-created and ready to use. There are also non-callable variants, useful
195when you are mocking out objects that aren't callable:
196:class:`NonCallableMock` and :class:`NonCallableMagicMock`
197
198The :func:`patch` decorators makes it easy to temporarily replace classes
Georg Brandl7ad3df62014-10-31 07:59:37 +0100199in a particular module with a :class:`Mock` object. By default :func:`patch` will create
200a :class:`MagicMock` for you. You can specify an alternative class of :class:`Mock` using
201the *new_callable* argument to :func:`patch`.
Michael Foord944e02d2012-03-25 23:12:55 +0100202
203
Kushal Das8c145342014-04-16 23:32:21 +0530204.. class:: Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs)
Michael Foord944e02d2012-03-25 23:12:55 +0100205
Georg Brandl7ad3df62014-10-31 07:59:37 +0100206 Create a new :class:`Mock` object. :class:`Mock` takes several optional arguments
Michael Foord944e02d2012-03-25 23:12:55 +0100207 that specify the behaviour of the Mock object:
208
Georg Brandl7ad3df62014-10-31 07:59:37 +0100209 * *spec*: This can be either a list of strings or an existing object (a
Michael Foord944e02d2012-03-25 23:12:55 +0100210 class or instance) that acts as the specification for the mock object. If
211 you pass in an object then a list of strings is formed by calling dir on
212 the object (excluding unsupported magic attributes and methods).
Georg Brandl7ad3df62014-10-31 07:59:37 +0100213 Accessing any attribute not in this list will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100214
Georg Brandl7ad3df62014-10-31 07:59:37 +0100215 If *spec* is an object (rather than a list of strings) then
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300216 :attr:`~instance.__class__` returns the class of the spec object. This
Georg Brandl7ad3df62014-10-31 07:59:37 +0100217 allows mocks to pass :func:`isinstance` tests.
Michael Foord944e02d2012-03-25 23:12:55 +0100218
Georg Brandl7ad3df62014-10-31 07:59:37 +0100219 * *spec_set*: A stricter variant of *spec*. If used, attempting to *set*
Michael Foord944e02d2012-03-25 23:12:55 +0100220 or get an attribute on the mock that isn't on the object passed as
Georg Brandl7ad3df62014-10-31 07:59:37 +0100221 *spec_set* will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100222
Georg Brandl7ad3df62014-10-31 07:59:37 +0100223 * *side_effect*: A function to be called whenever the Mock is called. See
Michael Foord944e02d2012-03-25 23:12:55 +0100224 the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or
225 dynamically changing return values. The function is called with the same
226 arguments as the mock, and unless it returns :data:`DEFAULT`, the return
227 value of this function is used as the return value.
228
Georg Brandl7ad3df62014-10-31 07:59:37 +0100229 Alternatively *side_effect* can be an exception class or instance. In
Michael Foord944e02d2012-03-25 23:12:55 +0100230 this case the exception will be raised when the mock is called.
231
Georg Brandl7ad3df62014-10-31 07:59:37 +0100232 If *side_effect* is an iterable then each call to the mock will return
Michael Foord944e02d2012-03-25 23:12:55 +0100233 the next value from the iterable.
234
Georg Brandl7ad3df62014-10-31 07:59:37 +0100235 A *side_effect* can be cleared by setting it to ``None``.
Michael Foord944e02d2012-03-25 23:12:55 +0100236
Georg Brandl7ad3df62014-10-31 07:59:37 +0100237 * *return_value*: The value returned when the mock is called. By default
Michael Foord944e02d2012-03-25 23:12:55 +0100238 this is a new Mock (created on first access). See the
239 :attr:`return_value` attribute.
240
Georg Brandl7ad3df62014-10-31 07:59:37 +0100241 * *unsafe*: By default if any attribute starts with *assert* or
242 *assret* will raise an :exc:`AttributeError`. Passing ``unsafe=True``
243 will allow access to these attributes.
Kushal Das8c145342014-04-16 23:32:21 +0530244
245 .. versionadded:: 3.5
246
Georg Brandl7ad3df62014-10-31 07:59:37 +0100247 * *wraps*: Item for the mock object to wrap. If *wraps* is not None then
Michael Foord944e02d2012-03-25 23:12:55 +0100248 calling the Mock will pass the call through to the wrapped object
Michael Foord0682a0c2012-04-13 20:51:20 +0100249 (returning the real result). Attribute access on the mock will return a
250 Mock object that wraps the corresponding attribute of the wrapped
251 object (so attempting to access an attribute that doesn't exist will
Georg Brandl7ad3df62014-10-31 07:59:37 +0100252 raise an :exc:`AttributeError`).
Michael Foord944e02d2012-03-25 23:12:55 +0100253
Georg Brandl7ad3df62014-10-31 07:59:37 +0100254 If the mock has an explicit *return_value* set then calls are not passed
255 to the wrapped object and the *return_value* is returned instead.
Michael Foord944e02d2012-03-25 23:12:55 +0100256
Georg Brandl7ad3df62014-10-31 07:59:37 +0100257 * *name*: If the mock has a name then it will be used in the repr of the
Michael Foord944e02d2012-03-25 23:12:55 +0100258 mock. This can be useful for debugging. The name is propagated to child
259 mocks.
260
261 Mocks can also be called with arbitrary keyword arguments. These will be
262 used to set attributes on the mock after it is created. See the
263 :meth:`configure_mock` method for details.
264
Victor Stinner2c2a4e62016-03-11 22:17:48 +0100265 .. method:: assert_called(*args, **kwargs)
266
267 Assert that the mock was called at least once.
268
269 >>> mock = Mock()
270 >>> mock.method()
271 <Mock name='mock.method()' id='...'>
272 >>> mock.method.assert_called()
273
274 .. versionadded:: 3.6
275
276 .. method:: assert_called_once(*args, **kwargs)
277
278 Assert that the mock was called exactly once.
279
280 >>> mock = Mock()
281 >>> mock.method()
282 <Mock name='mock.method()' id='...'>
283 >>> mock.method.assert_called_once()
284 >>> mock.method()
285 <Mock name='mock.method()' id='...'>
286 >>> mock.method.assert_called_once()
287 Traceback (most recent call last):
288 ...
289 AssertionError: Expected 'method' to have been called once. Called 2 times.
290
291 .. versionadded:: 3.6
292
Michael Foord944e02d2012-03-25 23:12:55 +0100293
294 .. method:: assert_called_with(*args, **kwargs)
295
296 This method is a convenient way of asserting that calls are made in a
297 particular way:
298
299 >>> mock = Mock()
300 >>> mock.method(1, 2, 3, test='wow')
301 <Mock name='mock.method()' id='...'>
302 >>> mock.method.assert_called_with(1, 2, 3, test='wow')
303
Michael Foord944e02d2012-03-25 23:12:55 +0100304 .. method:: assert_called_once_with(*args, **kwargs)
305
306 Assert that the mock was called exactly once and with the specified
307 arguments.
308
309 >>> mock = Mock(return_value=None)
310 >>> mock('foo', bar='baz')
311 >>> mock.assert_called_once_with('foo', bar='baz')
312 >>> mock('foo', bar='baz')
313 >>> mock.assert_called_once_with('foo', bar='baz')
314 Traceback (most recent call last):
315 ...
Michael Foord28d591c2012-09-28 16:15:22 +0100316 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foord944e02d2012-03-25 23:12:55 +0100317
318
319 .. method:: assert_any_call(*args, **kwargs)
320
321 assert the mock has been called with the specified arguments.
322
323 The assert passes if the mock has *ever* been called, unlike
324 :meth:`assert_called_with` and :meth:`assert_called_once_with` that
325 only pass if the call is the most recent one.
326
327 >>> mock = Mock(return_value=None)
328 >>> mock(1, 2, arg='thing')
329 >>> mock('some', 'thing', 'else')
330 >>> mock.assert_any_call(1, 2, arg='thing')
331
332
333 .. method:: assert_has_calls(calls, any_order=False)
334
335 assert the mock has been called with the specified calls.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100336 The :attr:`mock_calls` list is checked for the calls.
Michael Foord944e02d2012-03-25 23:12:55 +0100337
Georg Brandl7ad3df62014-10-31 07:59:37 +0100338 If *any_order* is false (the default) then the calls must be
Michael Foord944e02d2012-03-25 23:12:55 +0100339 sequential. There can be extra calls before or after the
340 specified calls.
341
Georg Brandl7ad3df62014-10-31 07:59:37 +0100342 If *any_order* is true then the calls can be in any order, but
Michael Foord944e02d2012-03-25 23:12:55 +0100343 they must all appear in :attr:`mock_calls`.
344
345 >>> mock = Mock(return_value=None)
346 >>> mock(1)
347 >>> mock(2)
348 >>> mock(3)
349 >>> mock(4)
350 >>> calls = [call(2), call(3)]
351 >>> mock.assert_has_calls(calls)
352 >>> calls = [call(4), call(2), call(3)]
353 >>> mock.assert_has_calls(calls, any_order=True)
354
Berker Peksagebf9fd32016-07-17 15:26:46 +0300355 .. method:: assert_not_called()
Kushal Das8af9db32014-04-17 01:36:14 +0530356
357 Assert the mock was never called.
358
359 >>> m = Mock()
360 >>> m.hello.assert_not_called()
361 >>> obj = m.hello()
362 >>> m.hello.assert_not_called()
363 Traceback (most recent call last):
364 ...
365 AssertionError: Expected 'hello' to not have been called. Called 1 times.
366
367 .. versionadded:: 3.5
368
Michael Foord944e02d2012-03-25 23:12:55 +0100369
Kushal Das9cd39a12016-06-02 10:20:16 -0700370 .. method:: reset_mock(*, return_value=False, side_effect=False)
Michael Foord944e02d2012-03-25 23:12:55 +0100371
372 The reset_mock method resets all the call attributes on a mock object:
373
374 >>> mock = Mock(return_value=None)
375 >>> mock('hello')
376 >>> mock.called
377 True
378 >>> mock.reset_mock()
379 >>> mock.called
380 False
381
Kushal Das9cd39a12016-06-02 10:20:16 -0700382 .. versionchanged:: 3.6
383 Added two keyword only argument to the reset_mock function.
384
Michael Foord944e02d2012-03-25 23:12:55 +0100385 This can be useful where you want to make a series of assertions that
Georg Brandl7ad3df62014-10-31 07:59:37 +0100386 reuse the same object. Note that :meth:`reset_mock` *doesn't* clear the
Michael Foord944e02d2012-03-25 23:12:55 +0100387 return value, :attr:`side_effect` or any child attributes you have
Kushal Das9cd39a12016-06-02 10:20:16 -0700388 set using normal assignment by default. In case you want to reset
389 *return_value* or :attr:`side_effect`, then pass the corresponding
390 parameter as ``True``. Child mocks and the return value mock
Michael Foord944e02d2012-03-25 23:12:55 +0100391 (if any) are reset as well.
392
Kushal Das9cd39a12016-06-02 10:20:16 -0700393 .. note:: *return_value*, and :attr:`side_effect` are keyword only
394 argument.
395
Michael Foord944e02d2012-03-25 23:12:55 +0100396
397 .. method:: mock_add_spec(spec, spec_set=False)
398
Georg Brandl7ad3df62014-10-31 07:59:37 +0100399 Add a spec to a mock. *spec* can either be an object or a
400 list of strings. Only attributes on the *spec* can be fetched as
Michael Foord944e02d2012-03-25 23:12:55 +0100401 attributes from the mock.
402
Georg Brandl7ad3df62014-10-31 07:59:37 +0100403 If *spec_set* is true then only attributes on the spec can be set.
Michael Foord944e02d2012-03-25 23:12:55 +0100404
405
406 .. method:: attach_mock(mock, attribute)
407
408 Attach a mock as an attribute of this one, replacing its name and
409 parent. Calls to the attached mock will be recorded in the
410 :attr:`method_calls` and :attr:`mock_calls` attributes of this one.
411
412
413 .. method:: configure_mock(**kwargs)
414
415 Set attributes on the mock through keyword arguments.
416
417 Attributes plus return values and side effects can be set on child
418 mocks using standard dot notation and unpacking a dictionary in the
419 method call:
420
421 >>> mock = Mock()
422 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
423 >>> mock.configure_mock(**attrs)
424 >>> mock.method()
425 3
426 >>> mock.other()
427 Traceback (most recent call last):
428 ...
429 KeyError
430
431 The same thing can be achieved in the constructor call to mocks:
432
433 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
434 >>> mock = Mock(some_attribute='eggs', **attrs)
435 >>> mock.some_attribute
436 'eggs'
437 >>> mock.method()
438 3
439 >>> mock.other()
440 Traceback (most recent call last):
441 ...
442 KeyError
443
Georg Brandl7ad3df62014-10-31 07:59:37 +0100444 :meth:`configure_mock` exists to make it easier to do configuration
Michael Foord944e02d2012-03-25 23:12:55 +0100445 after the mock has been created.
446
447
448 .. method:: __dir__()
449
Georg Brandl7ad3df62014-10-31 07:59:37 +0100450 :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results.
451 For mocks with a *spec* this includes all the permitted attributes
Michael Foord944e02d2012-03-25 23:12:55 +0100452 for the mock.
453
454 See :data:`FILTER_DIR` for what this filtering does, and how to
455 switch it off.
456
457
458 .. method:: _get_child_mock(**kw)
459
460 Create the child mocks for attributes and return value.
461 By default child mocks will be the same type as the parent.
462 Subclasses of Mock may want to override this to customize the way
463 child mocks are made.
464
465 For non-callable mocks the callable variant will be used (rather than
466 any custom subclass).
467
468
469 .. attribute:: called
470
471 A boolean representing whether or not the mock object has been called:
472
473 >>> mock = Mock(return_value=None)
474 >>> mock.called
475 False
476 >>> mock()
477 >>> mock.called
478 True
479
480 .. attribute:: call_count
481
482 An integer telling you how many times the mock object has been called:
483
484 >>> mock = Mock(return_value=None)
485 >>> mock.call_count
486 0
487 >>> mock()
488 >>> mock()
489 >>> mock.call_count
490 2
491
492
493 .. attribute:: return_value
494
495 Set this to configure the value returned by calling the mock:
496
497 >>> mock = Mock()
498 >>> mock.return_value = 'fish'
499 >>> mock()
500 'fish'
501
502 The default return value is a mock object and you can configure it in
503 the normal way:
504
505 >>> mock = Mock()
506 >>> mock.return_value.attribute = sentinel.Attribute
507 >>> mock.return_value()
508 <Mock name='mock()()' id='...'>
509 >>> mock.return_value.assert_called_with()
510
Georg Brandl7ad3df62014-10-31 07:59:37 +0100511 :attr:`return_value` can also be set in the constructor:
Michael Foord944e02d2012-03-25 23:12:55 +0100512
513 >>> mock = Mock(return_value=3)
514 >>> mock.return_value
515 3
516 >>> mock()
517 3
518
519
520 .. attribute:: side_effect
521
522 This can either be a function to be called when the mock is called,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100523 an iterable or an exception (class or instance) to be raised.
Michael Foord944e02d2012-03-25 23:12:55 +0100524
525 If you pass in a function it will be called with same arguments as the
526 mock and unless the function returns the :data:`DEFAULT` singleton the
527 call to the mock will then return whatever the function returns. If the
528 function returns :data:`DEFAULT` then the mock will return its normal
Brett Cannon533f1ed2013-05-25 11:28:20 -0400529 value (from the :attr:`return_value`).
Michael Foord944e02d2012-03-25 23:12:55 +0100530
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100531 If you pass in an iterable, it is used to retrieve an iterator which
532 must yield a value on every call. This value can either be an exception
533 instance to be raised, or a value to be returned from the call to the
534 mock (:data:`DEFAULT` handling is identical to the function case).
535
Michael Foord944e02d2012-03-25 23:12:55 +0100536 An example of a mock that raises an exception (to test exception
537 handling of an API):
538
539 >>> mock = Mock()
540 >>> mock.side_effect = Exception('Boom!')
541 >>> mock()
542 Traceback (most recent call last):
543 ...
544 Exception: Boom!
545
Georg Brandl7ad3df62014-10-31 07:59:37 +0100546 Using :attr:`side_effect` to return a sequence of values:
Michael Foord944e02d2012-03-25 23:12:55 +0100547
548 >>> mock = Mock()
549 >>> mock.side_effect = [3, 2, 1]
550 >>> mock(), mock(), mock()
551 (3, 2, 1)
552
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100553 Using a callable:
Michael Foord944e02d2012-03-25 23:12:55 +0100554
555 >>> mock = Mock(return_value=3)
556 >>> def side_effect(*args, **kwargs):
557 ... return DEFAULT
558 ...
559 >>> mock.side_effect = side_effect
560 >>> mock()
561 3
562
Georg Brandl7ad3df62014-10-31 07:59:37 +0100563 :attr:`side_effect` can be set in the constructor. Here's an example that
Michael Foord944e02d2012-03-25 23:12:55 +0100564 adds one to the value the mock is called with and returns it:
565
566 >>> side_effect = lambda value: value + 1
567 >>> mock = Mock(side_effect=side_effect)
568 >>> mock(3)
569 4
570 >>> mock(-8)
571 -7
572
Georg Brandl7ad3df62014-10-31 07:59:37 +0100573 Setting :attr:`side_effect` to ``None`` clears it:
Michael Foord944e02d2012-03-25 23:12:55 +0100574
575 >>> m = Mock(side_effect=KeyError, return_value=3)
576 >>> m()
577 Traceback (most recent call last):
578 ...
579 KeyError
580 >>> m.side_effect = None
581 >>> m()
582 3
583
584
585 .. attribute:: call_args
586
Georg Brandl7ad3df62014-10-31 07:59:37 +0100587 This is either ``None`` (if the mock hasn't been called), or the
Michael Foord944e02d2012-03-25 23:12:55 +0100588 arguments that the mock was last called with. This will be in the
589 form of a tuple: the first member is any ordered arguments the mock
590 was called with (or an empty tuple) and the second member is any
591 keyword arguments (or an empty dictionary).
592
593 >>> mock = Mock(return_value=None)
Berker Peksag920f6db2015-09-10 21:41:15 +0300594 >>> print(mock.call_args)
Michael Foord944e02d2012-03-25 23:12:55 +0100595 None
596 >>> mock()
597 >>> mock.call_args
598 call()
599 >>> mock.call_args == ()
600 True
601 >>> mock(3, 4)
602 >>> mock.call_args
603 call(3, 4)
604 >>> mock.call_args == ((3, 4),)
605 True
606 >>> mock(3, 4, 5, key='fish', next='w00t!')
607 >>> mock.call_args
608 call(3, 4, 5, key='fish', next='w00t!')
609
Georg Brandl7ad3df62014-10-31 07:59:37 +0100610 :attr:`call_args`, along with members of the lists :attr:`call_args_list`,
Michael Foord944e02d2012-03-25 23:12:55 +0100611 :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects.
612 These are tuples, so they can be unpacked to get at the individual
613 arguments and make more complex assertions. See
614 :ref:`calls as tuples <calls-as-tuples>`.
615
616
617 .. attribute:: call_args_list
618
619 This is a list of all the calls made to the mock object in sequence
620 (so the length of the list is the number of times it has been
621 called). Before any calls have been made it is an empty list. The
622 :data:`call` object can be used for conveniently constructing lists of
Georg Brandl7ad3df62014-10-31 07:59:37 +0100623 calls to compare with :attr:`call_args_list`.
Michael Foord944e02d2012-03-25 23:12:55 +0100624
625 >>> mock = Mock(return_value=None)
626 >>> mock()
627 >>> mock(3, 4)
628 >>> mock(key='fish', next='w00t!')
629 >>> mock.call_args_list
630 [call(), call(3, 4), call(key='fish', next='w00t!')]
631 >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
632 >>> mock.call_args_list == expected
633 True
634
Georg Brandl7ad3df62014-10-31 07:59:37 +0100635 Members of :attr:`call_args_list` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100636 unpacked as tuples to get at the individual arguments. See
637 :ref:`calls as tuples <calls-as-tuples>`.
638
639
640 .. attribute:: method_calls
641
642 As well as tracking calls to themselves, mocks also track calls to
643 methods and attributes, and *their* methods and attributes:
644
645 >>> mock = Mock()
646 >>> mock.method()
647 <Mock name='mock.method()' id='...'>
648 >>> mock.property.method.attribute()
649 <Mock name='mock.property.method.attribute()' id='...'>
650 >>> mock.method_calls
651 [call.method(), call.property.method.attribute()]
652
Georg Brandl7ad3df62014-10-31 07:59:37 +0100653 Members of :attr:`method_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100654 unpacked as tuples to get at the individual arguments. See
655 :ref:`calls as tuples <calls-as-tuples>`.
656
657
658 .. attribute:: mock_calls
659
Georg Brandl7ad3df62014-10-31 07:59:37 +0100660 :attr:`mock_calls` records *all* calls to the mock object, its methods,
661 magic methods *and* return value mocks.
Michael Foord944e02d2012-03-25 23:12:55 +0100662
663 >>> mock = MagicMock()
664 >>> result = mock(1, 2, 3)
665 >>> mock.first(a=3)
666 <MagicMock name='mock.first()' id='...'>
667 >>> mock.second()
668 <MagicMock name='mock.second()' id='...'>
669 >>> int(mock)
670 1
671 >>> result(1)
672 <MagicMock name='mock()()' id='...'>
673 >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
674 ... call.__int__(), call()(1)]
675 >>> mock.mock_calls == expected
676 True
677
Georg Brandl7ad3df62014-10-31 07:59:37 +0100678 Members of :attr:`mock_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100679 unpacked as tuples to get at the individual arguments. See
680 :ref:`calls as tuples <calls-as-tuples>`.
681
682
683 .. attribute:: __class__
684
Georg Brandl7ad3df62014-10-31 07:59:37 +0100685 Normally the :attr:`__class__` attribute of an object will return its type.
686 For a mock object with a :attr:`spec`, ``__class__`` returns the spec class
687 instead. This allows mock objects to pass :func:`isinstance` tests for the
Michael Foord944e02d2012-03-25 23:12:55 +0100688 object they are replacing / masquerading as:
689
690 >>> mock = Mock(spec=3)
691 >>> isinstance(mock, int)
692 True
693
Georg Brandl7ad3df62014-10-31 07:59:37 +0100694 :attr:`__class__` is assignable to, this allows a mock to pass an
695 :func:`isinstance` check without forcing you to use a spec:
Michael Foord944e02d2012-03-25 23:12:55 +0100696
697 >>> mock = Mock()
698 >>> mock.__class__ = dict
699 >>> isinstance(mock, dict)
700 True
701
702.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
703
Georg Brandl7ad3df62014-10-31 07:59:37 +0100704 A non-callable version of :class:`Mock`. The constructor parameters have the same
705 meaning of :class:`Mock`, with the exception of *return_value* and *side_effect*
Michael Foord944e02d2012-03-25 23:12:55 +0100706 which have no meaning on a non-callable mock.
707
Georg Brandl7ad3df62014-10-31 07:59:37 +0100708Mock objects that use a class or an instance as a :attr:`spec` or
709:attr:`spec_set` are able to pass :func:`isinstance` tests:
Michael Foord944e02d2012-03-25 23:12:55 +0100710
711 >>> mock = Mock(spec=SomeClass)
712 >>> isinstance(mock, SomeClass)
713 True
714 >>> mock = Mock(spec_set=SomeClass())
715 >>> isinstance(mock, SomeClass)
716 True
717
Georg Brandl7ad3df62014-10-31 07:59:37 +0100718The :class:`Mock` classes have support for mocking magic methods. See :ref:`magic
Michael Foord944e02d2012-03-25 23:12:55 +0100719methods <magic-methods>` for the full details.
720
721The mock classes and the :func:`patch` decorators all take arbitrary keyword
Georg Brandl7ad3df62014-10-31 07:59:37 +0100722arguments for configuration. For the :func:`patch` decorators the keywords are
Michael Foord944e02d2012-03-25 23:12:55 +0100723passed to the constructor of the mock being created. The keyword arguments
724are for configuring attributes of the mock:
725
726 >>> m = MagicMock(attribute=3, other='fish')
727 >>> m.attribute
728 3
729 >>> m.other
730 'fish'
731
732The return value and side effect of child mocks can be set in the same way,
733using dotted notation. As you can't use dotted names directly in a call you
Georg Brandl7ad3df62014-10-31 07:59:37 +0100734have to create a dictionary and unpack it using ``**``:
Michael Foord944e02d2012-03-25 23:12:55 +0100735
736 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
737 >>> mock = Mock(some_attribute='eggs', **attrs)
738 >>> mock.some_attribute
739 'eggs'
740 >>> mock.method()
741 3
742 >>> mock.other()
743 Traceback (most recent call last):
744 ...
745 KeyError
746
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100747A callable mock which was created with a *spec* (or a *spec_set*) will
748introspect the specification object's signature when matching calls to
749the mock. Therefore, it can match the actual call's arguments regardless
750of whether they were passed positionally or by name::
751
752 >>> def f(a, b, c): pass
753 ...
754 >>> mock = Mock(spec=f)
755 >>> mock(1, 2, c=3)
756 <Mock name='mock()' id='140161580456576'>
757 >>> mock.assert_called_with(1, 2, 3)
758 >>> mock.assert_called_with(a=1, b=2, c=3)
759
760This applies to :meth:`~Mock.assert_called_with`,
761:meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and
762:meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also
763apply to method calls on the mock object.
764
765 .. versionchanged:: 3.4
766 Added signature introspection on specced and autospecced mock objects.
767
Michael Foord944e02d2012-03-25 23:12:55 +0100768
769.. class:: PropertyMock(*args, **kwargs)
770
771 A mock intended to be used as a property, or other descriptor, on a class.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100772 :class:`PropertyMock` provides :meth:`__get__` and :meth:`__set__` methods
773 so you can specify a return value when it is fetched.
Michael Foord944e02d2012-03-25 23:12:55 +0100774
Georg Brandl7ad3df62014-10-31 07:59:37 +0100775 Fetching a :class:`PropertyMock` instance from an object calls the mock, with
Michael Foord944e02d2012-03-25 23:12:55 +0100776 no args. Setting it calls the mock with the value being set.
777
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200778 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100779 ... @property
780 ... def foo(self):
781 ... return 'something'
782 ... @foo.setter
783 ... def foo(self, value):
784 ... pass
785 ...
786 >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
787 ... mock_foo.return_value = 'mockity-mock'
788 ... this_foo = Foo()
Berker Peksag920f6db2015-09-10 21:41:15 +0300789 ... print(this_foo.foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100790 ... this_foo.foo = 6
791 ...
792 mockity-mock
793 >>> mock_foo.mock_calls
794 [call(), call(6)]
795
Michael Foordc2870622012-04-13 16:57:22 +0100796Because of the way mock attributes are stored you can't directly attach a
Georg Brandl7ad3df62014-10-31 07:59:37 +0100797:class:`PropertyMock` to a mock object. Instead you can attach it to the mock type
Michael Foordc2870622012-04-13 16:57:22 +0100798object::
799
800 >>> m = MagicMock()
801 >>> p = PropertyMock(return_value=3)
802 >>> type(m).foo = p
803 >>> m.foo
804 3
805 >>> p.assert_called_once_with()
806
Michael Foord944e02d2012-03-25 23:12:55 +0100807
808Calling
809~~~~~~~
810
811Mock objects are callable. The call will return the value set as the
812:attr:`~Mock.return_value` attribute. The default return value is a new Mock
813object; it is created the first time the return value is accessed (either
814explicitly or by calling the Mock) - but it is stored and the same one
815returned each time.
816
817Calls made to the object will be recorded in the attributes
818like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
819
820If :attr:`~Mock.side_effect` is set then it will be called after the call has
Georg Brandl7ad3df62014-10-31 07:59:37 +0100821been recorded, so if :attr:`side_effect` raises an exception the call is still
Michael Foord944e02d2012-03-25 23:12:55 +0100822recorded.
823
824The simplest way to make a mock raise an exception when called is to make
825:attr:`~Mock.side_effect` an exception class or instance:
826
827 >>> m = MagicMock(side_effect=IndexError)
828 >>> m(1, 2, 3)
829 Traceback (most recent call last):
830 ...
831 IndexError
832 >>> m.mock_calls
833 [call(1, 2, 3)]
834 >>> m.side_effect = KeyError('Bang!')
835 >>> m('two', 'three', 'four')
836 Traceback (most recent call last):
837 ...
838 KeyError: 'Bang!'
839 >>> m.mock_calls
840 [call(1, 2, 3), call('two', 'three', 'four')]
841
Georg Brandl7ad3df62014-10-31 07:59:37 +0100842If :attr:`side_effect` is a function then whatever that function returns is what
843calls to the mock return. The :attr:`side_effect` function is called with the
Michael Foord944e02d2012-03-25 23:12:55 +0100844same arguments as the mock. This allows you to vary the return value of the
845call dynamically, based on the input:
846
847 >>> def side_effect(value):
848 ... return value + 1
849 ...
850 >>> m = MagicMock(side_effect=side_effect)
851 >>> m(1)
852 2
853 >>> m(2)
854 3
855 >>> m.mock_calls
856 [call(1), call(2)]
857
858If you want the mock to still return the default return value (a new mock), or
859any set return value, then there are two ways of doing this. Either return
Georg Brandl7ad3df62014-10-31 07:59:37 +0100860:attr:`mock.return_value` from inside :attr:`side_effect`, or return :data:`DEFAULT`:
Michael Foord944e02d2012-03-25 23:12:55 +0100861
862 >>> m = MagicMock()
863 >>> def side_effect(*args, **kwargs):
864 ... return m.return_value
865 ...
866 >>> m.side_effect = side_effect
867 >>> m.return_value = 3
868 >>> m()
869 3
870 >>> def side_effect(*args, **kwargs):
871 ... return DEFAULT
872 ...
873 >>> m.side_effect = side_effect
874 >>> m()
875 3
876
Georg Brandl7ad3df62014-10-31 07:59:37 +0100877To remove a :attr:`side_effect`, and return to the default behaviour, set the
878:attr:`side_effect` to ``None``:
Michael Foord944e02d2012-03-25 23:12:55 +0100879
880 >>> m = MagicMock(return_value=6)
881 >>> def side_effect(*args, **kwargs):
882 ... return 3
883 ...
884 >>> m.side_effect = side_effect
885 >>> m()
886 3
887 >>> m.side_effect = None
888 >>> m()
889 6
890
Georg Brandl7ad3df62014-10-31 07:59:37 +0100891The :attr:`side_effect` can also be any iterable object. Repeated calls to the mock
Michael Foord944e02d2012-03-25 23:12:55 +0100892will return values from the iterable (until the iterable is exhausted and
Georg Brandl7ad3df62014-10-31 07:59:37 +0100893a :exc:`StopIteration` is raised):
Michael Foord944e02d2012-03-25 23:12:55 +0100894
895 >>> m = MagicMock(side_effect=[1, 2, 3])
896 >>> m()
897 1
898 >>> m()
899 2
900 >>> m()
901 3
902 >>> m()
903 Traceback (most recent call last):
904 ...
905 StopIteration
906
Michael Foord2cd48732012-04-21 15:52:11 +0100907If any members of the iterable are exceptions they will be raised instead of
908returned::
909
910 >>> iterable = (33, ValueError, 66)
911 >>> m = MagicMock(side_effect=iterable)
912 >>> m()
913 33
914 >>> m()
915 Traceback (most recent call last):
916 ...
917 ValueError
918 >>> m()
919 66
920
Michael Foord944e02d2012-03-25 23:12:55 +0100921
922.. _deleting-attributes:
923
924Deleting Attributes
925~~~~~~~~~~~~~~~~~~~
926
927Mock objects create attributes on demand. This allows them to pretend to be
928objects of any type.
929
Georg Brandl7ad3df62014-10-31 07:59:37 +0100930You may want a mock object to return ``False`` to a :func:`hasattr` call, or raise an
931:exc:`AttributeError` when an attribute is fetched. You can do this by providing
932an object as a :attr:`spec` for a mock, but that isn't always convenient.
Michael Foord944e02d2012-03-25 23:12:55 +0100933
934You "block" attributes by deleting them. Once deleted, accessing an attribute
Georg Brandl7ad3df62014-10-31 07:59:37 +0100935will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100936
937 >>> mock = MagicMock()
938 >>> hasattr(mock, 'm')
939 True
940 >>> del mock.m
941 >>> hasattr(mock, 'm')
942 False
943 >>> del mock.f
944 >>> mock.f
945 Traceback (most recent call last):
946 ...
947 AttributeError: f
948
949
Michael Foordf5752302013-03-18 15:04:03 -0700950Mock names and the name attribute
951~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
952
953Since "name" is an argument to the :class:`Mock` constructor, if you want your
954mock object to have a "name" attribute you can't just pass it in at creation
955time. There are two alternatives. One option is to use
956:meth:`~Mock.configure_mock`::
957
958 >>> mock = MagicMock()
959 >>> mock.configure_mock(name='my_name')
960 >>> mock.name
961 'my_name'
962
963A simpler option is to simply set the "name" attribute after mock creation::
964
965 >>> mock = MagicMock()
966 >>> mock.name = "foo"
967
968
Michael Foord944e02d2012-03-25 23:12:55 +0100969Attaching Mocks as Attributes
970~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
971
972When you attach a mock as an attribute of another mock (or as the return
973value) it becomes a "child" of that mock. Calls to the child are recorded in
974the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
975parent. This is useful for configuring child mocks and then attaching them to
976the parent, or for attaching mocks to a parent that records all calls to the
977children and allows you to make assertions about the order of calls between
978mocks:
979
980 >>> parent = MagicMock()
981 >>> child1 = MagicMock(return_value=None)
982 >>> child2 = MagicMock(return_value=None)
983 >>> parent.child1 = child1
984 >>> parent.child2 = child2
985 >>> child1(1)
986 >>> child2(2)
987 >>> parent.mock_calls
988 [call.child1(1), call.child2(2)]
989
990The exception to this is if the mock has a name. This allows you to prevent
991the "parenting" if for some reason you don't want it to happen.
992
993 >>> mock = MagicMock()
994 >>> not_a_child = MagicMock(name='not-a-child')
995 >>> mock.attribute = not_a_child
996 >>> mock.attribute()
997 <MagicMock name='not-a-child()' id='...'>
998 >>> mock.mock_calls
999 []
1000
1001Mocks created for you by :func:`patch` are automatically given names. To
1002attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
1003method:
1004
1005 >>> thing1 = object()
1006 >>> thing2 = object()
1007 >>> parent = MagicMock()
1008 >>> with patch('__main__.thing1', return_value=None) as child1:
1009 ... with patch('__main__.thing2', return_value=None) as child2:
1010 ... parent.attach_mock(child1, 'child1')
1011 ... parent.attach_mock(child2, 'child2')
1012 ... child1('one')
1013 ... child2('two')
1014 ...
1015 >>> parent.mock_calls
1016 [call.child1('one'), call.child2('two')]
1017
1018
1019.. [#] The only exceptions are magic methods and attributes (those that have
1020 leading and trailing double underscores). Mock doesn't create these but
Georg Brandl7ad3df62014-10-31 07:59:37 +01001021 instead raises an :exc:`AttributeError`. This is because the interpreter
Michael Foord944e02d2012-03-25 23:12:55 +01001022 will often implicitly request these methods, and gets *very* confused to
1023 get a new Mock object when it expects a magic method. If you need magic
1024 method support see :ref:`magic methods <magic-methods>`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001025
1026
1027The patchers
Georg Brandlfb134382013-02-03 11:47:49 +01001028------------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001029
1030The patch decorators are used for patching objects only within the scope of
1031the function they decorate. They automatically handle the unpatching for you,
1032even if exceptions are raised. All of these functions can also be used in with
1033statements or as class decorators.
1034
1035
1036patch
Georg Brandlfb134382013-02-03 11:47:49 +01001037~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001038
1039.. note::
1040
Georg Brandl7ad3df62014-10-31 07:59:37 +01001041 :func:`patch` is straightforward to use. The key is to do the patching in the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001042 right namespace. See the section `where to patch`_.
1043
1044.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1045
Georg Brandl7ad3df62014-10-31 07:59:37 +01001046 :func:`patch` acts as a function decorator, class decorator or a context
1047 manager. Inside the body of the function or with statement, the *target*
1048 is patched with a *new* object. When the function/with statement exits
Michael Foord54b3db82012-03-28 15:08:08 +01001049 the patch is undone.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001050
Georg Brandl7ad3df62014-10-31 07:59:37 +01001051 If *new* is omitted, then the target is replaced with a
1052 :class:`MagicMock`. If :func:`patch` is used as a decorator and *new* is
Michael Foord54b3db82012-03-28 15:08:08 +01001053 omitted, the created mock is passed in as an extra argument to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001054 decorated function. If :func:`patch` is used as a context manager the created
Michael Foord54b3db82012-03-28 15:08:08 +01001055 mock is returned by the context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001056
Georg Brandl7ad3df62014-10-31 07:59:37 +01001057 *target* should be a string in the form ``'package.module.ClassName'``. The
1058 *target* is imported and the specified object replaced with the *new*
1059 object, so the *target* must be importable from the environment you are
1060 calling :func:`patch` from. The target is imported when the decorated function
Michael Foord54b3db82012-03-28 15:08:08 +01001061 is executed, not at decoration time.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001062
Georg Brandl7ad3df62014-10-31 07:59:37 +01001063 The *spec* and *spec_set* keyword arguments are passed to the :class:`MagicMock`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001064 if patch is creating one for you.
1065
Georg Brandl7ad3df62014-10-31 07:59:37 +01001066 In addition you can pass ``spec=True`` or ``spec_set=True``, which causes
Michael Foorda9e6fb22012-03-28 14:36:02 +01001067 patch to pass in the object being mocked as the spec/spec_set object.
1068
Georg Brandl7ad3df62014-10-31 07:59:37 +01001069 *new_callable* allows you to specify a different class, or callable object,
1070 that will be called to create the *new* object. By default :class:`MagicMock` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001071 used.
1072
Georg Brandl7ad3df62014-10-31 07:59:37 +01001073 A more powerful form of *spec* is *autospec*. If you set ``autospec=True``
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001074 then the mock will be created with a spec from the object being replaced.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001075 All attributes of the mock will also have the spec of the corresponding
1076 attribute of the object being replaced. Methods and functions being mocked
Georg Brandl7ad3df62014-10-31 07:59:37 +01001077 will have their arguments checked and will raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001078 called with the wrong signature. For mocks
1079 replacing a class, their return value (the 'instance') will have the same
1080 spec as the class. See the :func:`create_autospec` function and
1081 :ref:`auto-speccing`.
1082
Georg Brandl7ad3df62014-10-31 07:59:37 +01001083 Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001084 arbitrary object as the spec instead of the one being replaced.
1085
Georg Brandl7ad3df62014-10-31 07:59:37 +01001086 By default :func:`patch` will fail to replace attributes that don't exist. If
1087 you pass in ``create=True``, and the attribute doesn't exist, patch will
Michael Foorda9e6fb22012-03-28 14:36:02 +01001088 create the attribute for you when the patched function is called, and
1089 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001090 attributes that your production code creates at runtime. It is off by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001091 default because it can be dangerous. With it switched on you can write
1092 passing tests against APIs that don't actually exist!
1093
Michael Foordfddcfa22014-04-14 16:25:20 -04001094 .. note::
1095
1096 .. versionchanged:: 3.5
1097 If you are patching builtins in a module then you don't
Georg Brandl7ad3df62014-10-31 07:59:37 +01001098 need to pass ``create=True``, it will be added by default.
Michael Foordfddcfa22014-04-14 16:25:20 -04001099
Georg Brandl7ad3df62014-10-31 07:59:37 +01001100 Patch can be used as a :class:`TestCase` class decorator. It works by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001101 decorating each test method in the class. This reduces the boilerplate
Georg Brandl7ad3df62014-10-31 07:59:37 +01001102 code when your test methods share a common patchings set. :func:`patch` finds
1103 tests by looking for method names that start with ``patch.TEST_PREFIX``.
1104 By default this is ``'test'``, which matches the way :mod:`unittest` finds tests.
1105 You can specify an alternative prefix by setting ``patch.TEST_PREFIX``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001106
1107 Patch can be used as a context manager, with the with statement. Here the
1108 patching applies to the indented block after the with statement. If you
1109 use "as" then the patched object will be bound to the name after the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001110 "as"; very useful if :func:`patch` is creating a mock object for you.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001111
Georg Brandl7ad3df62014-10-31 07:59:37 +01001112 :func:`patch` takes arbitrary keyword arguments. These will be passed to
1113 the :class:`Mock` (or *new_callable*) on construction.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001114
Georg Brandl7ad3df62014-10-31 07:59:37 +01001115 ``patch.dict(...)``, ``patch.multiple(...)`` and ``patch.object(...)`` are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001116 available for alternate use-cases.
1117
Georg Brandl7ad3df62014-10-31 07:59:37 +01001118:func:`patch` as function decorator, creating the mock for you and passing it into
Michael Foord90155362012-03-28 15:32:08 +01001119the decorated function:
1120
1121 >>> @patch('__main__.SomeClass')
Michael Foord324b58b2012-03-28 15:49:08 +01001122 ... def function(normal_argument, mock_class):
Michael Foord90155362012-03-28 15:32:08 +01001123 ... print(mock_class is SomeClass)
1124 ...
Michael Foord324b58b2012-03-28 15:49:08 +01001125 >>> function(None)
Michael Foord90155362012-03-28 15:32:08 +01001126 True
Michael Foorda9e6fb22012-03-28 14:36:02 +01001127
Georg Brandl7ad3df62014-10-31 07:59:37 +01001128Patching a class replaces the class with a :class:`MagicMock` *instance*. If the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001129class is instantiated in the code under test then it will be the
1130:attr:`~Mock.return_value` of the mock that will be used.
1131
1132If the class is instantiated multiple times you could use
1133:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
Georg Brandl7ad3df62014-10-31 07:59:37 +01001134can set the *return_value* to be anything you want.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001135
1136To configure return values on methods of *instances* on the patched class
Georg Brandl7ad3df62014-10-31 07:59:37 +01001137you must do this on the :attr:`return_value`. For example:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001138
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001139 >>> class Class:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001140 ... def method(self):
1141 ... pass
1142 ...
1143 >>> with patch('__main__.Class') as MockClass:
1144 ... instance = MockClass.return_value
1145 ... instance.method.return_value = 'foo'
1146 ... assert Class() is instance
1147 ... assert Class().method() == 'foo'
1148 ...
1149
Georg Brandl7ad3df62014-10-31 07:59:37 +01001150If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001151return value of the created mock will have the same spec.
1152
1153 >>> Original = Class
1154 >>> patcher = patch('__main__.Class', spec=True)
1155 >>> MockClass = patcher.start()
1156 >>> instance = MockClass()
1157 >>> assert isinstance(instance, Original)
1158 >>> patcher.stop()
1159
Georg Brandl7ad3df62014-10-31 07:59:37 +01001160The *new_callable* argument is useful where you want to use an alternative
Michael Foorda9e6fb22012-03-28 14:36:02 +01001161class to the default :class:`MagicMock` for the created mock. For example, if
1162you wanted a :class:`NonCallableMock` to be used:
1163
1164 >>> thing = object()
1165 >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
1166 ... assert thing is mock_thing
1167 ... thing()
1168 ...
1169 Traceback (most recent call last):
1170 ...
1171 TypeError: 'NonCallableMock' object is not callable
1172
Martin Panter7462b6492015-11-02 03:37:02 +00001173Another use case might be to replace an object with an :class:`io.StringIO` instance:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001174
Serhiy Storchakae79be872013-08-17 00:09:55 +03001175 >>> from io import StringIO
Michael Foorda9e6fb22012-03-28 14:36:02 +01001176 >>> def foo():
Berker Peksag920f6db2015-09-10 21:41:15 +03001177 ... print('Something')
Michael Foorda9e6fb22012-03-28 14:36:02 +01001178 ...
1179 >>> @patch('sys.stdout', new_callable=StringIO)
1180 ... def test(mock_stdout):
1181 ... foo()
1182 ... assert mock_stdout.getvalue() == 'Something\n'
1183 ...
1184 >>> test()
1185
Georg Brandl7ad3df62014-10-31 07:59:37 +01001186When :func:`patch` is creating a mock for you, it is common that the first thing
Michael Foorda9e6fb22012-03-28 14:36:02 +01001187you need to do is to configure the mock. Some of that configuration can be done
1188in the call to patch. Any arbitrary keywords you pass into the call will be
1189used to set attributes on the created mock:
1190
1191 >>> patcher = patch('__main__.thing', first='one', second='two')
1192 >>> mock_thing = patcher.start()
1193 >>> mock_thing.first
1194 'one'
1195 >>> mock_thing.second
1196 'two'
1197
1198As well as attributes on the created mock attributes, like the
1199:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
1200also be configured. These aren't syntactically valid to pass in directly as
1201keyword arguments, but a dictionary with these as keys can still be expanded
Georg Brandl7ad3df62014-10-31 07:59:37 +01001202into a :func:`patch` call using ``**``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001203
1204 >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
1205 >>> patcher = patch('__main__.thing', **config)
1206 >>> mock_thing = patcher.start()
1207 >>> mock_thing.method()
1208 3
1209 >>> mock_thing.other()
1210 Traceback (most recent call last):
1211 ...
1212 KeyError
1213
1214
1215patch.object
Georg Brandlfb134382013-02-03 11:47:49 +01001216~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001217
1218.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1219
Georg Brandl7ad3df62014-10-31 07:59:37 +01001220 patch the named member (*attribute*) on an object (*target*) with a mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001221 object.
1222
Georg Brandl7ad3df62014-10-31 07:59:37 +01001223 :func:`patch.object` can be used as a decorator, class decorator or a context
1224 manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* and
1225 *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`,
1226 :func:`patch.object` takes arbitrary keyword arguments for configuring the mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001227 object it creates.
1228
Georg Brandl7ad3df62014-10-31 07:59:37 +01001229 When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001230 for choosing which methods to wrap.
1231
Georg Brandl7ad3df62014-10-31 07:59:37 +01001232You can either call :func:`patch.object` with three arguments or two arguments. The
Michael Foorda9e6fb22012-03-28 14:36:02 +01001233three argument form takes the object to be patched, the attribute name and the
1234object to replace the attribute with.
1235
1236When calling with the two argument form you omit the replacement object, and a
1237mock is created for you and passed in as an extra argument to the decorated
1238function:
1239
1240 >>> @patch.object(SomeClass, 'class_method')
1241 ... def test(mock_method):
1242 ... SomeClass.class_method(3)
1243 ... mock_method.assert_called_with(3)
1244 ...
1245 >>> test()
1246
Georg Brandl7ad3df62014-10-31 07:59:37 +01001247*spec*, *create* and the other arguments to :func:`patch.object` have the same
1248meaning as they do for :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001249
1250
1251patch.dict
Georg Brandlfb134382013-02-03 11:47:49 +01001252~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001253
1254.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs)
1255
1256 Patch a dictionary, or dictionary like object, and restore the dictionary
1257 to its original state after the test.
1258
Georg Brandl7ad3df62014-10-31 07:59:37 +01001259 *in_dict* can be a dictionary or a mapping like container. If it is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01001260 mapping then it must at least support getting, setting and deleting items
1261 plus iterating over keys.
1262
Georg Brandl7ad3df62014-10-31 07:59:37 +01001263 *in_dict* can also be a string specifying the name of the dictionary, which
Michael Foorda9e6fb22012-03-28 14:36:02 +01001264 will then be fetched by importing it.
1265
Georg Brandl7ad3df62014-10-31 07:59:37 +01001266 *values* can be a dictionary of values to set in the dictionary. *values*
1267 can also be an iterable of ``(key, value)`` pairs.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001268
Georg Brandl7ad3df62014-10-31 07:59:37 +01001269 If *clear* is true then the dictionary will be cleared before the new
Michael Foorda9e6fb22012-03-28 14:36:02 +01001270 values are set.
1271
Georg Brandl7ad3df62014-10-31 07:59:37 +01001272 :func:`patch.dict` can also be called with arbitrary keyword arguments to set
Michael Foorda9e6fb22012-03-28 14:36:02 +01001273 values in the dictionary.
1274
Georg Brandl7ad3df62014-10-31 07:59:37 +01001275 :func:`patch.dict` can be used as a context manager, decorator or class
1276 decorator. When used as a class decorator :func:`patch.dict` honours
1277 ``patch.TEST_PREFIX`` for choosing which methods to wrap.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001278
Georg Brandl7ad3df62014-10-31 07:59:37 +01001279:func:`patch.dict` can be used to add members to a dictionary, or simply let a test
Michael Foorda9e6fb22012-03-28 14:36:02 +01001280change a dictionary, and ensure the dictionary is restored when the test
1281ends.
1282
1283 >>> foo = {}
1284 >>> with patch.dict(foo, {'newkey': 'newvalue'}):
1285 ... assert foo == {'newkey': 'newvalue'}
1286 ...
1287 >>> assert foo == {}
1288
1289 >>> import os
1290 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
Berker Peksag920f6db2015-09-10 21:41:15 +03001291 ... print(os.environ['newkey'])
Michael Foorda9e6fb22012-03-28 14:36:02 +01001292 ...
1293 newvalue
1294 >>> assert 'newkey' not in os.environ
1295
Georg Brandl7ad3df62014-10-31 07:59:37 +01001296Keywords can be used in the :func:`patch.dict` call to set values in the dictionary:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001297
1298 >>> mymodule = MagicMock()
1299 >>> mymodule.function.return_value = 'fish'
1300 >>> with patch.dict('sys.modules', mymodule=mymodule):
1301 ... import mymodule
1302 ... mymodule.function('some', 'args')
1303 ...
1304 'fish'
1305
Georg Brandl7ad3df62014-10-31 07:59:37 +01001306:func:`patch.dict` can be used with dictionary like objects that aren't actually
Michael Foorda9e6fb22012-03-28 14:36:02 +01001307dictionaries. At the very minimum they must support item getting, setting,
1308deleting and either iteration or membership test. This corresponds to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001309magic methods :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__` and either
1310:meth:`__iter__` or :meth:`__contains__`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001311
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001312 >>> class Container:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001313 ... def __init__(self):
1314 ... self.values = {}
1315 ... def __getitem__(self, name):
1316 ... return self.values[name]
1317 ... def __setitem__(self, name, value):
1318 ... self.values[name] = value
1319 ... def __delitem__(self, name):
1320 ... del self.values[name]
1321 ... def __iter__(self):
1322 ... return iter(self.values)
1323 ...
1324 >>> thing = Container()
1325 >>> thing['one'] = 1
1326 >>> with patch.dict(thing, one=2, two=3):
1327 ... assert thing['one'] == 2
1328 ... assert thing['two'] == 3
1329 ...
1330 >>> assert thing['one'] == 1
1331 >>> assert list(thing) == ['one']
1332
1333
1334patch.multiple
Georg Brandlfb134382013-02-03 11:47:49 +01001335~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001336
1337.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1338
1339 Perform multiple patches in a single call. It takes the object to be
1340 patched (either as an object or a string to fetch the object by importing)
1341 and keyword arguments for the patches::
1342
1343 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1344 ...
1345
Georg Brandl7ad3df62014-10-31 07:59:37 +01001346 Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create
Michael Foorda9e6fb22012-03-28 14:36:02 +01001347 mocks for you. In this case the created mocks are passed into a decorated
Georg Brandl7ad3df62014-10-31 07:59:37 +01001348 function by keyword, and a dictionary is returned when :func:`patch.multiple` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001349 used as a context manager.
1350
Georg Brandl7ad3df62014-10-31 07:59:37 +01001351 :func:`patch.multiple` can be used as a decorator, class decorator or a context
1352 manager. The arguments *spec*, *spec_set*, *create*, *autospec* and
1353 *new_callable* have the same meaning as for :func:`patch`. These arguments will
1354 be applied to *all* patches done by :func:`patch.multiple`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001355
Georg Brandl7ad3df62014-10-31 07:59:37 +01001356 When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001357 for choosing which methods to wrap.
1358
Georg Brandl7ad3df62014-10-31 07:59:37 +01001359If you want :func:`patch.multiple` to create mocks for you, then you can use
1360:data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator
Michael Foorda9e6fb22012-03-28 14:36:02 +01001361then the created mocks are passed into the decorated function by keyword.
1362
1363 >>> thing = object()
1364 >>> other = object()
1365
1366 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1367 ... def test_function(thing, other):
1368 ... assert isinstance(thing, MagicMock)
1369 ... assert isinstance(other, MagicMock)
1370 ...
1371 >>> test_function()
1372
Georg Brandl7ad3df62014-10-31 07:59:37 +01001373:func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments
1374passed by keyword *after* any of the standard arguments created by :func:`patch`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001375
1376 >>> @patch('sys.exit')
1377 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1378 ... def test_function(mock_exit, other, thing):
1379 ... assert 'other' in repr(other)
1380 ... assert 'thing' in repr(thing)
1381 ... assert 'exit' in repr(mock_exit)
1382 ...
1383 >>> test_function()
1384
Georg Brandl7ad3df62014-10-31 07:59:37 +01001385If :func:`patch.multiple` is used as a context manager, the value returned by the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001386context manger is a dictionary where created mocks are keyed by name:
1387
1388 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
1389 ... assert 'other' in repr(values['other'])
1390 ... assert 'thing' in repr(values['thing'])
1391 ... assert values['thing'] is thing
1392 ... assert values['other'] is other
1393 ...
1394
1395
1396.. _start-and-stop:
1397
1398patch methods: start and stop
Georg Brandlfb134382013-02-03 11:47:49 +01001399~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001400
Georg Brandl7ad3df62014-10-31 07:59:37 +01001401All the patchers have :meth:`start` and :meth:`stop` methods. These make it simpler to do
1402patching in ``setUp`` methods or where you want to do multiple patches without
Michael Foorda9e6fb22012-03-28 14:36:02 +01001403nesting decorators or with statements.
1404
Georg Brandl7ad3df62014-10-31 07:59:37 +01001405To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as
1406normal and keep a reference to the returned ``patcher`` object. You can then
1407call :meth:`start` to put the patch in place and :meth:`stop` to undo it.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001408
Georg Brandl7ad3df62014-10-31 07:59:37 +01001409If you are using :func:`patch` to create a mock for you then it will be returned by
1410the call to ``patcher.start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001411
1412 >>> patcher = patch('package.module.ClassName')
1413 >>> from package import module
1414 >>> original = module.ClassName
1415 >>> new_mock = patcher.start()
1416 >>> assert module.ClassName is not original
1417 >>> assert module.ClassName is new_mock
1418 >>> patcher.stop()
1419 >>> assert module.ClassName is original
1420 >>> assert module.ClassName is not new_mock
1421
1422
Georg Brandl7ad3df62014-10-31 07:59:37 +01001423A typical use case for this might be for doing multiple patches in the ``setUp``
1424method of a :class:`TestCase`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001425
1426 >>> class MyTest(TestCase):
1427 ... def setUp(self):
1428 ... self.patcher1 = patch('package.module.Class1')
1429 ... self.patcher2 = patch('package.module.Class2')
1430 ... self.MockClass1 = self.patcher1.start()
1431 ... self.MockClass2 = self.patcher2.start()
1432 ...
1433 ... def tearDown(self):
1434 ... self.patcher1.stop()
1435 ... self.patcher2.stop()
1436 ...
1437 ... def test_something(self):
1438 ... assert package.module.Class1 is self.MockClass1
1439 ... assert package.module.Class2 is self.MockClass2
1440 ...
1441 >>> MyTest('test_something').run()
1442
1443.. caution::
1444
1445 If you use this technique you must ensure that the patching is "undone" by
Georg Brandl7ad3df62014-10-31 07:59:37 +01001446 calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001447 exception is raised in the ``setUp`` then ``tearDown`` is not called.
1448 :meth:`unittest.TestCase.addCleanup` makes this easier:
1449
1450 >>> class MyTest(TestCase):
1451 ... def setUp(self):
1452 ... patcher = patch('package.module.Class')
1453 ... self.MockClass = patcher.start()
1454 ... self.addCleanup(patcher.stop)
1455 ...
1456 ... def test_something(self):
1457 ... assert package.module.Class is self.MockClass
1458 ...
1459
Georg Brandl7ad3df62014-10-31 07:59:37 +01001460 As an added bonus you no longer need to keep a reference to the ``patcher``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001461 object.
1462
Michael Foordf7c41582012-06-10 20:36:32 +01001463It is also possible to stop all patches which have been started by using
Georg Brandl7ad3df62014-10-31 07:59:37 +01001464:func:`patch.stopall`.
Michael Foordf7c41582012-06-10 20:36:32 +01001465
1466.. function:: patch.stopall
1467
Georg Brandl7ad3df62014-10-31 07:59:37 +01001468 Stop all active patches. Only stops patches started with ``start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001469
Georg Brandl7ad3df62014-10-31 07:59:37 +01001470
1471.. _patch-builtins:
Michael Foordfddcfa22014-04-14 16:25:20 -04001472
1473patch builtins
Georg Brandl7ad3df62014-10-31 07:59:37 +01001474~~~~~~~~~~~~~~
Michael Foordfddcfa22014-04-14 16:25:20 -04001475You can patch any builtins within a module. The following example patches
Georg Brandl7ad3df62014-10-31 07:59:37 +01001476builtin :func:`ord`:
Michael Foordfddcfa22014-04-14 16:25:20 -04001477
1478 >>> @patch('__main__.ord')
1479 ... def test(mock_ord):
1480 ... mock_ord.return_value = 101
1481 ... print(ord('c'))
1482 ...
1483 >>> test()
1484 101
1485
Michael Foorda9e6fb22012-03-28 14:36:02 +01001486
1487TEST_PREFIX
Georg Brandlfb134382013-02-03 11:47:49 +01001488~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001489
1490All of the patchers can be used as class decorators. When used in this way
1491they wrap every test method on the class. The patchers recognise methods that
Georg Brandl7ad3df62014-10-31 07:59:37 +01001492start with ``'test'`` as being test methods. This is the same way that the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001493:class:`unittest.TestLoader` finds test methods by default.
1494
1495It is possible that you want to use a different prefix for your tests. You can
Georg Brandl7ad3df62014-10-31 07:59:37 +01001496inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001497
1498 >>> patch.TEST_PREFIX = 'foo'
1499 >>> value = 3
1500 >>>
1501 >>> @patch('__main__.value', 'not three')
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001502 ... class Thing:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001503 ... def foo_one(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001504 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001505 ... def foo_two(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001506 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001507 ...
1508 >>>
1509 >>> Thing().foo_one()
1510 not three
1511 >>> Thing().foo_two()
1512 not three
1513 >>> value
1514 3
1515
1516
1517Nesting Patch Decorators
Georg Brandlfb134382013-02-03 11:47:49 +01001518~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001519
1520If you want to perform multiple patches then you can simply stack up the
1521decorators.
1522
1523You can stack up multiple patch decorators using this pattern:
1524
1525 >>> @patch.object(SomeClass, 'class_method')
1526 ... @patch.object(SomeClass, 'static_method')
1527 ... def test(mock1, mock2):
1528 ... assert SomeClass.static_method is mock1
1529 ... assert SomeClass.class_method is mock2
1530 ... SomeClass.static_method('foo')
1531 ... SomeClass.class_method('bar')
1532 ... return mock1, mock2
1533 ...
1534 >>> mock1, mock2 = test()
1535 >>> mock1.assert_called_once_with('foo')
1536 >>> mock2.assert_called_once_with('bar')
1537
1538
1539Note that the decorators are applied from the bottom upwards. This is the
1540standard way that Python applies decorators. The order of the created mocks
1541passed into your test function matches this order.
1542
1543
1544.. _where-to-patch:
1545
1546Where to patch
Georg Brandlfb134382013-02-03 11:47:49 +01001547~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001548
Georg Brandl7ad3df62014-10-31 07:59:37 +01001549:func:`patch` works by (temporarily) changing the object that a *name* points to with
Michael Foorda9e6fb22012-03-28 14:36:02 +01001550another one. There can be many names pointing to any individual object, so
1551for patching to work you must ensure that you patch the name used by the system
1552under test.
1553
1554The basic principle is that you patch where an object is *looked up*, which
1555is not necessarily the same place as where it is defined. A couple of
1556examples will help to clarify this.
1557
1558Imagine we have a project that we want to test with the following structure::
1559
1560 a.py
1561 -> Defines SomeClass
1562
1563 b.py
1564 -> from a import SomeClass
1565 -> some_function instantiates SomeClass
1566
Georg Brandl7ad3df62014-10-31 07:59:37 +01001567Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
1568:func:`patch`. The problem is that when we import module b, which we will have to
1569do then it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
1570``a.SomeClass`` then it will have no effect on our test; module b already has a
1571reference to the *real* ``SomeClass`` and it looks like our patching had no
Michael Foorda9e6fb22012-03-28 14:36:02 +01001572effect.
1573
Georg Brandl7ad3df62014-10-31 07:59:37 +01001574The key is to patch out ``SomeClass`` where it is used (or where it is looked up
1575). In this case ``some_function`` will actually look up ``SomeClass`` in module b,
Michael Foorda9e6fb22012-03-28 14:36:02 +01001576where we have imported it. The patching should look like::
1577
1578 @patch('b.SomeClass')
1579
Georg Brandl7ad3df62014-10-31 07:59:37 +01001580However, consider the alternative scenario where instead of ``from a import
1581SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both
Michael Foorda9e6fb22012-03-28 14:36:02 +01001582of these import forms are common. In this case the class we want to patch is
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001583being looked up in the module and so we have to patch ``a.SomeClass`` instead::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001584
1585 @patch('a.SomeClass')
1586
1587
1588Patching Descriptors and Proxy Objects
Georg Brandlfb134382013-02-03 11:47:49 +01001589~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001590
1591Both patch_ and patch.object_ correctly patch and restore descriptors: class
1592methods, static methods and properties. You should patch these on the *class*
1593rather than an instance. They also work with *some* objects
Zachary Ware5ea5d2c2014-02-26 09:34:43 -06001594that proxy attribute access, like the `django settings object
Michael Foorda9e6fb22012-03-28 14:36:02 +01001595<http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
1596
1597
Michael Foord2309ed82012-03-28 15:38:36 +01001598MagicMock and magic method support
Georg Brandlfb134382013-02-03 11:47:49 +01001599----------------------------------
Michael Foord2309ed82012-03-28 15:38:36 +01001600
1601.. _magic-methods:
1602
1603Mocking Magic Methods
Georg Brandlfb134382013-02-03 11:47:49 +01001604~~~~~~~~~~~~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001605
1606:class:`Mock` supports mocking the Python protocol methods, also known as
1607"magic methods". This allows mock objects to replace containers or other
1608objects that implement Python protocols.
1609
1610Because magic methods are looked up differently from normal methods [#]_, this
1611support has been specially implemented. This means that only specific magic
1612methods are supported. The supported list includes *almost* all of them. If
1613there are any missing that you need please let us know.
1614
1615You mock magic methods by setting the method you are interested in to a function
1616or a mock instance. If you are using a function then it *must* take ``self`` as
1617the first argument [#]_.
1618
1619 >>> def __str__(self):
1620 ... return 'fooble'
1621 ...
1622 >>> mock = Mock()
1623 >>> mock.__str__ = __str__
1624 >>> str(mock)
1625 'fooble'
1626
1627 >>> mock = Mock()
1628 >>> mock.__str__ = Mock()
1629 >>> mock.__str__.return_value = 'fooble'
1630 >>> str(mock)
1631 'fooble'
1632
1633 >>> mock = Mock()
1634 >>> mock.__iter__ = Mock(return_value=iter([]))
1635 >>> list(mock)
1636 []
1637
1638One use case for this is for mocking objects used as context managers in a
Georg Brandl7ad3df62014-10-31 07:59:37 +01001639:keyword:`with` statement:
Michael Foord2309ed82012-03-28 15:38:36 +01001640
1641 >>> mock = Mock()
1642 >>> mock.__enter__ = Mock(return_value='foo')
1643 >>> mock.__exit__ = Mock(return_value=False)
1644 >>> with mock as m:
1645 ... assert m == 'foo'
1646 ...
1647 >>> mock.__enter__.assert_called_with()
1648 >>> mock.__exit__.assert_called_with(None, None, None)
1649
1650Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they
1651are recorded in :attr:`~Mock.mock_calls`.
1652
1653.. note::
1654
Georg Brandl7ad3df62014-10-31 07:59:37 +01001655 If you use the *spec* keyword argument to create a mock then attempting to
1656 set a magic method that isn't in the spec will raise an :exc:`AttributeError`.
Michael Foord2309ed82012-03-28 15:38:36 +01001657
1658The full list of supported magic methods is:
1659
1660* ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``
1661* ``__dir__``, ``__format__`` and ``__subclasses__``
1662* ``__floor__``, ``__trunc__`` and ``__ceil__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001663* Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001664 ``__eq__`` and ``__ne__``
1665* Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``,
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001666 ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__``
1667 and ``__missing__``
Michael Foord2309ed82012-03-28 15:38:36 +01001668* Context manager: ``__enter__`` and ``__exit__``
1669* Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``
1670* The numeric methods (including right hand and in-place variants):
Serhiy Storchakac2ccce72015-03-12 22:01:30 +02001671 ``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__div__``, ``__truediv__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001672 ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``,
1673 ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001674* Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__``
1675 and ``__index__``
Michael Foord2309ed82012-03-28 15:38:36 +01001676* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
1677* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
1678 ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
1679
1680
1681The following methods exist but are *not* supported as they are either in use
1682by mock, can't be set dynamically, or can cause problems:
1683
1684* ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``
1685* ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``
1686
1687
1688
1689Magic Mock
Georg Brandlfb134382013-02-03 11:47:49 +01001690~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001691
Georg Brandl7ad3df62014-10-31 07:59:37 +01001692There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001693
1694
1695.. class:: MagicMock(*args, **kw)
1696
1697 ``MagicMock`` is a subclass of :class:`Mock` with default implementations
1698 of most of the magic methods. You can use ``MagicMock`` without having to
1699 configure the magic methods yourself.
1700
1701 The constructor parameters have the same meaning as for :class:`Mock`.
1702
Georg Brandl7ad3df62014-10-31 07:59:37 +01001703 If you use the *spec* or *spec_set* arguments then *only* magic methods
Michael Foord2309ed82012-03-28 15:38:36 +01001704 that exist in the spec will be created.
1705
1706
1707.. class:: NonCallableMagicMock(*args, **kw)
1708
Georg Brandl7ad3df62014-10-31 07:59:37 +01001709 A non-callable version of :class:`MagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001710
1711 The constructor parameters have the same meaning as for
Georg Brandl7ad3df62014-10-31 07:59:37 +01001712 :class:`MagicMock`, with the exception of *return_value* and
1713 *side_effect* which have no meaning on a non-callable mock.
Michael Foord2309ed82012-03-28 15:38:36 +01001714
Georg Brandl7ad3df62014-10-31 07:59:37 +01001715The magic methods are setup with :class:`MagicMock` objects, so you can configure them
Michael Foord2309ed82012-03-28 15:38:36 +01001716and use them in the usual way:
1717
1718 >>> mock = MagicMock()
1719 >>> mock[3] = 'fish'
1720 >>> mock.__setitem__.assert_called_with(3, 'fish')
1721 >>> mock.__getitem__.return_value = 'result'
1722 >>> mock[2]
1723 'result'
1724
1725By default many of the protocol methods are required to return objects of a
1726specific type. These methods are preconfigured with a default return value, so
1727that they can be used without you having to do anything if you aren't interested
1728in the return value. You can still *set* the return value manually if you want
1729to change the default.
1730
1731Methods and their defaults:
1732
1733* ``__lt__``: NotImplemented
1734* ``__gt__``: NotImplemented
1735* ``__le__``: NotImplemented
1736* ``__ge__``: NotImplemented
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001737* ``__int__``: 1
1738* ``__contains__``: False
Berker Peksag8fafc742016-04-11 12:23:04 +03001739* ``__len__``: 0
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001740* ``__iter__``: iter([])
1741* ``__exit__``: False
1742* ``__complex__``: 1j
1743* ``__float__``: 1.0
1744* ``__bool__``: True
1745* ``__index__``: 1
1746* ``__hash__``: default hash for the mock
1747* ``__str__``: default str for the mock
Michael Foord2309ed82012-03-28 15:38:36 +01001748* ``__sizeof__``: default sizeof for the mock
1749
1750For example:
1751
1752 >>> mock = MagicMock()
1753 >>> int(mock)
1754 1
1755 >>> len(mock)
1756 0
1757 >>> list(mock)
1758 []
1759 >>> object() in mock
1760 False
1761
Berker Peksag283f1aa2015-01-07 21:15:02 +02001762The two equality methods, :meth:`__eq__` and :meth:`__ne__`, are special.
1763They do the default equality comparison on identity, using the
1764:attr:`~Mock.side_effect` attribute, unless you change their return value to
1765return something else::
Michael Foord2309ed82012-03-28 15:38:36 +01001766
1767 >>> MagicMock() == 3
1768 False
1769 >>> MagicMock() != 3
1770 True
1771 >>> mock = MagicMock()
1772 >>> mock.__eq__.return_value = True
1773 >>> mock == 3
1774 True
1775
Georg Brandl7ad3df62014-10-31 07:59:37 +01001776The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
Michael Foord2309ed82012-03-28 15:38:36 +01001777required to be an iterator:
1778
1779 >>> mock = MagicMock()
1780 >>> mock.__iter__.return_value = ['a', 'b', 'c']
1781 >>> list(mock)
1782 ['a', 'b', 'c']
1783 >>> list(mock)
1784 ['a', 'b', 'c']
1785
1786If the return value *is* an iterator, then iterating over it once will consume
1787it and subsequent iterations will result in an empty list:
1788
1789 >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
1790 >>> list(mock)
1791 ['a', 'b', 'c']
1792 >>> list(mock)
1793 []
1794
1795``MagicMock`` has all of the supported magic methods configured except for some
1796of the obscure and obsolete ones. You can still set these up if you want.
1797
1798Magic methods that are supported but not setup by default in ``MagicMock`` are:
1799
1800* ``__subclasses__``
1801* ``__dir__``
1802* ``__format__``
1803* ``__get__``, ``__set__`` and ``__delete__``
1804* ``__reversed__`` and ``__missing__``
1805* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
1806 ``__getstate__`` and ``__setstate__``
1807* ``__getformat__`` and ``__setformat__``
1808
1809
1810
1811.. [#] Magic methods *should* be looked up on the class rather than the
1812 instance. Different versions of Python are inconsistent about applying this
1813 rule. The supported protocol methods should work with all supported versions
1814 of Python.
1815.. [#] The function is basically hooked up to the class, but each ``Mock``
1816 instance is kept isolated from the others.
1817
1818
Michael Foorda9e6fb22012-03-28 14:36:02 +01001819Helpers
Georg Brandlfb134382013-02-03 11:47:49 +01001820-------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001821
1822sentinel
Georg Brandlfb134382013-02-03 11:47:49 +01001823~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001824
1825.. data:: sentinel
1826
1827 The ``sentinel`` object provides a convenient way of providing unique
1828 objects for your tests.
1829
1830 Attributes are created on demand when you access them by name. Accessing
1831 the same attribute will always return the same object. The objects
1832 returned have a sensible repr so that test failure messages are readable.
1833
1834Sometimes when testing you need to test that a specific object is passed as an
1835argument to another method, or returned. It can be common to create named
Georg Brandl7ad3df62014-10-31 07:59:37 +01001836sentinel objects to test this. :data:`sentinel` provides a convenient way of
Michael Foorda9e6fb22012-03-28 14:36:02 +01001837creating and testing the identity of objects like this.
1838
Georg Brandl7ad3df62014-10-31 07:59:37 +01001839In this example we monkey patch ``method`` to return ``sentinel.some_object``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001840
1841 >>> real = ProductionClass()
1842 >>> real.method = Mock(name="method")
1843 >>> real.method.return_value = sentinel.some_object
1844 >>> result = real.method()
1845 >>> assert result is sentinel.some_object
1846 >>> sentinel.some_object
1847 sentinel.some_object
1848
1849
1850DEFAULT
Georg Brandlfb134382013-02-03 11:47:49 +01001851~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001852
1853
1854.. data:: DEFAULT
1855
Georg Brandl7ad3df62014-10-31 07:59:37 +01001856 The :data:`DEFAULT` object is a pre-created sentinel (actually
1857 ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001858 functions to indicate that the normal return value should be used.
1859
1860
Michael Foorda9e6fb22012-03-28 14:36:02 +01001861call
Georg Brandlfb134382013-02-03 11:47:49 +01001862~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001863
1864.. function:: call(*args, **kwargs)
1865
Georg Brandl7ad3df62014-10-31 07:59:37 +01001866 :func:`call` is a helper object for making simpler assertions, for comparing with
Georg Brandl24891672012-04-01 13:48:26 +02001867 :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
Georg Brandl7ad3df62014-10-31 07:59:37 +01001868 :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be
Michael Foorda9e6fb22012-03-28 14:36:02 +01001869 used with :meth:`~Mock.assert_has_calls`.
1870
1871 >>> m = MagicMock(return_value=None)
1872 >>> m(1, 2, a='foo', b='bar')
1873 >>> m()
1874 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
1875 True
1876
1877.. method:: call.call_list()
1878
Georg Brandl7ad3df62014-10-31 07:59:37 +01001879 For a call object that represents multiple calls, :meth:`call_list`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001880 returns a list of all the intermediate calls as well as the
1881 final call.
1882
Georg Brandl7ad3df62014-10-31 07:59:37 +01001883``call_list`` is particularly useful for making assertions on "chained calls". A
Michael Foorda9e6fb22012-03-28 14:36:02 +01001884chained call is multiple calls on a single line of code. This results in
1885multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
1886the sequence of calls can be tedious.
1887
1888:meth:`~call.call_list` can construct the sequence of calls from the same
1889chained call:
1890
1891 >>> m = MagicMock()
1892 >>> m(1).method(arg='foo').other('bar')(2.0)
1893 <MagicMock name='mock().method().other()()' id='...'>
1894 >>> kall = call(1).method(arg='foo').other('bar')(2.0)
1895 >>> kall.call_list()
1896 [call(1),
1897 call().method(arg='foo'),
1898 call().method().other('bar'),
1899 call().method().other()(2.0)]
1900 >>> m.mock_calls == kall.call_list()
1901 True
1902
1903.. _calls-as-tuples:
1904
Georg Brandl7ad3df62014-10-31 07:59:37 +01001905A ``call`` object is either a tuple of (positional args, keyword args) or
Michael Foorda9e6fb22012-03-28 14:36:02 +01001906(name, positional args, keyword args) depending on how it was constructed. When
Georg Brandl7ad3df62014-10-31 07:59:37 +01001907you construct them yourself this isn't particularly interesting, but the ``call``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001908objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
1909:attr:`Mock.mock_calls` attributes can be introspected to get at the individual
1910arguments they contain.
1911
Georg Brandl7ad3df62014-10-31 07:59:37 +01001912The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
1913are two-tuples of (positional args, keyword args) whereas the ``call`` objects
Michael Foorda9e6fb22012-03-28 14:36:02 +01001914in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
1915three-tuples of (name, positional args, keyword args).
1916
1917You can use their "tupleness" to pull out the individual arguments for more
1918complex introspection and assertions. The positional arguments are a tuple
1919(an empty tuple if there are no positional arguments) and the keyword
1920arguments are a dictionary:
1921
1922 >>> m = MagicMock(return_value=None)
1923 >>> m(1, 2, 3, arg='one', arg2='two')
1924 >>> kall = m.call_args
1925 >>> args, kwargs = kall
1926 >>> args
1927 (1, 2, 3)
1928 >>> kwargs
1929 {'arg2': 'two', 'arg': 'one'}
1930 >>> args is kall[0]
1931 True
1932 >>> kwargs is kall[1]
1933 True
1934
1935 >>> m = MagicMock()
1936 >>> m.foo(4, 5, 6, arg='two', arg2='three')
1937 <MagicMock name='mock.foo()' id='...'>
1938 >>> kall = m.mock_calls[0]
1939 >>> name, args, kwargs = kall
1940 >>> name
1941 'foo'
1942 >>> args
1943 (4, 5, 6)
1944 >>> kwargs
1945 {'arg2': 'three', 'arg': 'two'}
1946 >>> name is m.mock_calls[0][0]
1947 True
1948
1949
1950create_autospec
Georg Brandlfb134382013-02-03 11:47:49 +01001951~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001952
1953.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
1954
1955 Create a mock object using another object as a spec. Attributes on the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001956 mock will use the corresponding attribute on the *spec* object as their
Michael Foorda9e6fb22012-03-28 14:36:02 +01001957 spec.
1958
1959 Functions or methods being mocked will have their arguments checked to
1960 ensure that they are called with the correct signature.
1961
Georg Brandl7ad3df62014-10-31 07:59:37 +01001962 If *spec_set* is ``True`` then attempting to set attributes that don't exist
1963 on the spec object will raise an :exc:`AttributeError`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001964
1965 If a class is used as a spec then the return value of the mock (the
1966 instance of the class) will have the same spec. You can use a class as the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001967 spec for an instance object by passing ``instance=True``. The returned mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001968 will only be callable if instances of the mock are callable.
1969
Georg Brandl7ad3df62014-10-31 07:59:37 +01001970 :func:`create_autospec` also takes arbitrary keyword arguments that are passed to
Michael Foorda9e6fb22012-03-28 14:36:02 +01001971 the constructor of the created mock.
1972
1973See :ref:`auto-speccing` for examples of how to use auto-speccing with
Georg Brandl7ad3df62014-10-31 07:59:37 +01001974:func:`create_autospec` and the *autospec* argument to :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001975
1976
1977ANY
Georg Brandlfb134382013-02-03 11:47:49 +01001978~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001979
1980.. data:: ANY
1981
1982Sometimes you may need to make assertions about *some* of the arguments in a
1983call to mock, but either not care about some of the arguments or want to pull
1984them individually out of :attr:`~Mock.call_args` and make more complex
1985assertions on them.
1986
1987To ignore certain arguments you can pass in objects that compare equal to
1988*everything*. Calls to :meth:`~Mock.assert_called_with` and
1989:meth:`~Mock.assert_called_once_with` will then succeed no matter what was
1990passed in.
1991
1992 >>> mock = Mock(return_value=None)
1993 >>> mock('foo', bar=object())
1994 >>> mock.assert_called_once_with('foo', bar=ANY)
1995
Georg Brandl7ad3df62014-10-31 07:59:37 +01001996:data:`ANY` can also be used in comparisons with call lists like
Michael Foorda9e6fb22012-03-28 14:36:02 +01001997:attr:`~Mock.mock_calls`:
1998
1999 >>> m = MagicMock(return_value=None)
2000 >>> m(1)
2001 >>> m(1, 2)
2002 >>> m(object())
2003 >>> m.mock_calls == [call(1), call(1, 2), ANY]
2004 True
2005
2006
2007
2008FILTER_DIR
Georg Brandlfb134382013-02-03 11:47:49 +01002009~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002010
2011.. data:: FILTER_DIR
2012
Georg Brandl7ad3df62014-10-31 07:59:37 +01002013:data:`FILTER_DIR` is a module level variable that controls the way mock objects
2014respond to :func:`dir` (only for Python 2.6 or more recent). The default is ``True``,
Michael Foorda9e6fb22012-03-28 14:36:02 +01002015which uses the filtering described below, to only show useful members. If you
2016dislike this filtering, or need to switch it off for diagnostic purposes, then
Georg Brandl7ad3df62014-10-31 07:59:37 +01002017set ``mock.FILTER_DIR = False``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002018
Georg Brandl7ad3df62014-10-31 07:59:37 +01002019With filtering on, ``dir(some_mock)`` shows only useful attributes and will
Michael Foorda9e6fb22012-03-28 14:36:02 +01002020include any dynamically created attributes that wouldn't normally be shown.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002021If the mock was created with a *spec* (or *autospec* of course) then all the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002022attributes from the original are shown, even if they haven't been accessed
2023yet:
2024
2025 >>> dir(Mock())
2026 ['assert_any_call',
2027 'assert_called_once_with',
2028 'assert_called_with',
2029 'assert_has_calls',
2030 'attach_mock',
2031 ...
2032 >>> from urllib import request
2033 >>> dir(Mock(spec=request))
2034 ['AbstractBasicAuthHandler',
2035 'AbstractDigestAuthHandler',
2036 'AbstractHTTPHandler',
2037 'BaseHandler',
2038 ...
2039
Georg Brandl7ad3df62014-10-31 07:59:37 +01002040Many of the not-very-useful (private to :class:`Mock` rather than the thing being
Michael Foorda9e6fb22012-03-28 14:36:02 +01002041mocked) underscore and double underscore prefixed attributes have been
Georg Brandl7ad3df62014-10-31 07:59:37 +01002042filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this
Michael Foorda9e6fb22012-03-28 14:36:02 +01002043behaviour you can switch it off by setting the module level switch
Georg Brandl7ad3df62014-10-31 07:59:37 +01002044:data:`FILTER_DIR`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002045
2046 >>> from unittest import mock
2047 >>> mock.FILTER_DIR = False
2048 >>> dir(mock.Mock())
2049 ['_NonCallableMock__get_return_value',
2050 '_NonCallableMock__get_side_effect',
2051 '_NonCallableMock__return_value_doc',
2052 '_NonCallableMock__set_return_value',
2053 '_NonCallableMock__set_side_effect',
2054 '__call__',
2055 '__class__',
2056 ...
2057
Georg Brandl7ad3df62014-10-31 07:59:37 +01002058Alternatively you can just use ``vars(my_mock)`` (instance members) and
2059``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of
2060:data:`mock.FILTER_DIR`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002061
2062
2063mock_open
Georg Brandlfb134382013-02-03 11:47:49 +01002064~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002065
2066.. function:: mock_open(mock=None, read_data=None)
2067
Georg Brandl7ad3df62014-10-31 07:59:37 +01002068 A helper function to create a mock to replace the use of :func:`open`. It works
2069 for :func:`open` called directly or used as a context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002070
Georg Brandl7ad3df62014-10-31 07:59:37 +01002071 The *mock* argument is the mock object to configure. If ``None`` (the
2072 default) then a :class:`MagicMock` will be created for you, with the API limited
Michael Foorda9e6fb22012-03-28 14:36:02 +01002073 to methods or attributes available on standard file handles.
2074
Georg Brandl7ad3df62014-10-31 07:59:37 +01002075 *read_data* is a string for the :meth:`~io.IOBase.read`,
Serhiy Storchaka98b28fd2013-10-13 23:12:09 +03002076 :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods
Michael Foord04cbe0c2013-03-19 17:22:51 -07002077 of the file handle to return. Calls to those methods will take data from
Georg Brandl7ad3df62014-10-31 07:59:37 +01002078 *read_data* until it is depleted. The mock of these methods is pretty
Robert Collinsca647ef2015-07-24 03:48:20 +12002079 simplistic: every time the *mock* is called, the *read_data* is rewound to
2080 the start. If you need more control over the data that you are feeding to
2081 the tested code you will need to customize this mock for yourself. When that
2082 is insufficient, one of the in-memory filesystem packages on `PyPI
2083 <https://pypi.python.org/pypi>`_ can offer a realistic filesystem for testing.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002084
Robert Collinsf79dfe32015-07-24 04:09:59 +12002085 .. versionchanged:: 3.4
2086 Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support.
2087 The mock of :meth:`~io.IOBase.read` changed to consume *read_data* rather
2088 than returning it on each call.
2089
Robert Collins70398392015-07-24 04:10:27 +12002090 .. versionchanged:: 3.5
Robert Collinsf79dfe32015-07-24 04:09:59 +12002091 *read_data* is now reset on each call to the *mock*.
2092
Georg Brandl7ad3df62014-10-31 07:59:37 +01002093Using :func:`open` as a context manager is a great way to ensure your file handles
Michael Foorda9e6fb22012-03-28 14:36:02 +01002094are closed properly and is becoming common::
2095
2096 with open('/some/path', 'w') as f:
2097 f.write('something')
2098
Georg Brandl7ad3df62014-10-31 07:59:37 +01002099The issue is that even if you mock out the call to :func:`open` it is the
2100*returned object* that is used as a context manager (and has :meth:`__enter__` and
2101:meth:`__exit__` called).
Michael Foorda9e6fb22012-03-28 14:36:02 +01002102
2103Mocking context managers with a :class:`MagicMock` is common enough and fiddly
2104enough that a helper function is useful.
2105
2106 >>> m = mock_open()
Michael Foordfddcfa22014-04-14 16:25:20 -04002107 >>> with patch('__main__.open', m):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002108 ... with open('foo', 'w') as h:
2109 ... h.write('some stuff')
2110 ...
2111 >>> m.mock_calls
2112 [call('foo', 'w'),
2113 call().__enter__(),
2114 call().write('some stuff'),
2115 call().__exit__(None, None, None)]
2116 >>> m.assert_called_once_with('foo', 'w')
2117 >>> handle = m()
2118 >>> handle.write.assert_called_once_with('some stuff')
2119
2120And for reading files:
2121
Michael Foordfddcfa22014-04-14 16:25:20 -04002122 >>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002123 ... with open('foo') as h:
2124 ... result = h.read()
2125 ...
2126 >>> m.assert_called_once_with('foo')
2127 >>> assert result == 'bibble'
2128
2129
2130.. _auto-speccing:
2131
2132Autospeccing
Georg Brandlfb134382013-02-03 11:47:49 +01002133~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002134
Georg Brandl7ad3df62014-10-31 07:59:37 +01002135Autospeccing is based on the existing :attr:`spec` feature of mock. It limits the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002136api of mocks to the api of an original object (the spec), but it is recursive
2137(implemented lazily) so that attributes of mocks only have the same api as
2138the attributes of the spec. In addition mocked functions / methods have the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002139same call signature as the original so they raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002140called incorrectly.
2141
2142Before I explain how auto-speccing works, here's why it is needed.
2143
Georg Brandl7ad3df62014-10-31 07:59:37 +01002144:class:`Mock` is a very powerful and flexible object, but it suffers from two flaws
Michael Foorda9e6fb22012-03-28 14:36:02 +01002145when used to mock out objects from a system under test. One of these flaws is
Georg Brandl7ad3df62014-10-31 07:59:37 +01002146specific to the :class:`Mock` api and the other is a more general problem with using
Michael Foorda9e6fb22012-03-28 14:36:02 +01002147mock objects.
2148
Georg Brandl7ad3df62014-10-31 07:59:37 +01002149First the problem specific to :class:`Mock`. :class:`Mock` has two assert methods that are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002150extremely handy: :meth:`~Mock.assert_called_with` and
2151:meth:`~Mock.assert_called_once_with`.
2152
2153 >>> mock = Mock(name='Thing', return_value=None)
2154 >>> mock(1, 2, 3)
2155 >>> mock.assert_called_once_with(1, 2, 3)
2156 >>> mock(1, 2, 3)
2157 >>> mock.assert_called_once_with(1, 2, 3)
2158 Traceback (most recent call last):
2159 ...
Michael Foord28d591c2012-09-28 16:15:22 +01002160 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002161
2162Because mocks auto-create attributes on demand, and allow you to call them
2163with arbitrary arguments, if you misspell one of these assert methods then
2164your assertion is gone:
2165
2166.. code-block:: pycon
2167
2168 >>> mock = Mock(name='Thing', return_value=None)
2169 >>> mock(1, 2, 3)
2170 >>> mock.assret_called_once_with(4, 5, 6)
2171
2172Your tests can pass silently and incorrectly because of the typo.
2173
2174The second issue is more general to mocking. If you refactor some of your
2175code, rename members and so on, any tests for code that is still using the
2176*old api* but uses mocks instead of the real objects will still pass. This
2177means your tests can all pass even though your code is broken.
2178
2179Note that this is another reason why you need integration tests as well as
2180unit tests. Testing everything in isolation is all fine and dandy, but if you
2181don't test how your units are "wired together" there is still lots of room
2182for bugs that tests might have caught.
2183
Georg Brandl7ad3df62014-10-31 07:59:37 +01002184:mod:`mock` already provides a feature to help with this, called speccing. If you
2185use a class or instance as the :attr:`spec` for a mock then you can only access
Michael Foorda9e6fb22012-03-28 14:36:02 +01002186attributes on the mock that exist on the real class:
2187
2188 >>> from urllib import request
2189 >>> mock = Mock(spec=request.Request)
2190 >>> mock.assret_called_with
2191 Traceback (most recent call last):
2192 ...
2193 AttributeError: Mock object has no attribute 'assret_called_with'
2194
2195The spec only applies to the mock itself, so we still have the same issue
2196with any methods on the mock:
2197
2198.. code-block:: pycon
2199
2200 >>> mock.has_data()
2201 <mock.Mock object at 0x...>
2202 >>> mock.has_data.assret_called_with()
2203
Georg Brandl7ad3df62014-10-31 07:59:37 +01002204Auto-speccing solves this problem. You can either pass ``autospec=True`` to
2205:func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a
2206mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002207object that is being replaced will be used as the spec object. Because the
2208speccing is done "lazily" (the spec is created as attributes on the mock are
2209accessed) you can use it with very complex or deeply nested objects (like
2210modules that import modules that import modules) without a big performance
2211hit.
2212
2213Here's an example of it in use:
2214
2215 >>> from urllib import request
2216 >>> patcher = patch('__main__.request', autospec=True)
2217 >>> mock_request = patcher.start()
2218 >>> request is mock_request
2219 True
2220 >>> mock_request.Request
2221 <MagicMock name='request.Request' spec='Request' id='...'>
2222
Georg Brandl7ad3df62014-10-31 07:59:37 +01002223You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two
2224arguments in the constructor (one of which is *self*). Here's what happens if
Michael Foorda9e6fb22012-03-28 14:36:02 +01002225we try to call it incorrectly:
2226
2227 >>> req = request.Request()
2228 Traceback (most recent call last):
2229 ...
2230 TypeError: <lambda>() takes at least 2 arguments (1 given)
2231
2232The spec also applies to instantiated classes (i.e. the return value of
2233specced mocks):
2234
2235 >>> req = request.Request('foo')
2236 >>> req
2237 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
2238
Georg Brandl7ad3df62014-10-31 07:59:37 +01002239:class:`Request` objects are not callable, so the return value of instantiating our
2240mocked out :class:`request.Request` is a non-callable mock. With the spec in place
Michael Foorda9e6fb22012-03-28 14:36:02 +01002241any typos in our asserts will raise the correct error:
2242
2243 >>> req.add_header('spam', 'eggs')
2244 <MagicMock name='request.Request().add_header()' id='...'>
2245 >>> req.add_header.assret_called_with
2246 Traceback (most recent call last):
2247 ...
2248 AttributeError: Mock object has no attribute 'assret_called_with'
2249 >>> req.add_header.assert_called_with('spam', 'eggs')
2250
Georg Brandl7ad3df62014-10-31 07:59:37 +01002251In many cases you will just be able to add ``autospec=True`` to your existing
2252:func:`patch` calls and then be protected against bugs due to typos and api
Michael Foorda9e6fb22012-03-28 14:36:02 +01002253changes.
2254
Georg Brandl7ad3df62014-10-31 07:59:37 +01002255As well as using *autospec* through :func:`patch` there is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002256:func:`create_autospec` for creating autospecced mocks directly:
2257
2258 >>> from urllib import request
2259 >>> mock_request = create_autospec(request)
2260 >>> mock_request.Request('foo', 'bar')
2261 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
2262
2263This isn't without caveats and limitations however, which is why it is not
2264the default behaviour. In order to know what attributes are available on the
2265spec object, autospec has to introspect (access attributes) the spec. As you
2266traverse attributes on the mock a corresponding traversal of the original
2267object is happening under the hood. If any of your specced objects have
2268properties or descriptors that can trigger code execution then you may not be
2269able to use autospec. On the other hand it is much better to design your
2270objects so that introspection is safe [#]_.
2271
2272A more serious problem is that it is common for instance attributes to be
Georg Brandl7ad3df62014-10-31 07:59:37 +01002273created in the :meth:`__init__` method and not to exist on the class at all.
2274*autospec* can't know about any dynamically created attributes and restricts
Michael Foorda9e6fb22012-03-28 14:36:02 +01002275the api to visible attributes.
2276
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002277 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002278 ... def __init__(self):
2279 ... self.a = 33
2280 ...
2281 >>> with patch('__main__.Something', autospec=True):
2282 ... thing = Something()
2283 ... thing.a
2284 ...
2285 Traceback (most recent call last):
2286 ...
2287 AttributeError: Mock object has no attribute 'a'
2288
2289There are a few different ways of resolving this problem. The easiest, but
2290not necessarily the least annoying, way is to simply set the required
Georg Brandl7ad3df62014-10-31 07:59:37 +01002291attributes on the mock after creation. Just because *autospec* doesn't allow
Michael Foorda9e6fb22012-03-28 14:36:02 +01002292you to fetch attributes that don't exist on the spec it doesn't prevent you
2293setting them:
2294
2295 >>> with patch('__main__.Something', autospec=True):
2296 ... thing = Something()
2297 ... thing.a = 33
2298 ...
2299
Georg Brandl7ad3df62014-10-31 07:59:37 +01002300There is a more aggressive version of both *spec* and *autospec* that *does*
Michael Foorda9e6fb22012-03-28 14:36:02 +01002301prevent you setting non-existent attributes. This is useful if you want to
2302ensure your code only *sets* valid attributes too, but obviously it prevents
2303this particular scenario:
2304
2305 >>> with patch('__main__.Something', autospec=True, spec_set=True):
2306 ... thing = Something()
2307 ... thing.a = 33
2308 ...
2309 Traceback (most recent call last):
2310 ...
2311 AttributeError: Mock object has no attribute 'a'
2312
2313Probably the best way of solving the problem is to add class attributes as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002314default values for instance members initialised in :meth:`__init__`. Note that if
2315you are only setting default attributes in :meth:`__init__` then providing them via
Michael Foorda9e6fb22012-03-28 14:36:02 +01002316class attributes (shared between instances of course) is faster too. e.g.
2317
2318.. code-block:: python
2319
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002320 class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002321 a = 33
2322
2323This brings up another issue. It is relatively common to provide a default
Georg Brandl7ad3df62014-10-31 07:59:37 +01002324value of ``None`` for members that will later be an object of a different type.
2325``None`` would be useless as a spec because it wouldn't let you access *any*
2326attributes or methods on it. As ``None`` is *never* going to be useful as a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002327spec, and probably indicates a member that will normally of some other type,
Georg Brandl7ad3df62014-10-31 07:59:37 +01002328autospec doesn't use a spec for members that are set to ``None``. These will
2329just be ordinary mocks (well - MagicMocks):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002330
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002331 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002332 ... member = None
2333 ...
2334 >>> mock = create_autospec(Something)
2335 >>> mock.member.foo.bar.baz()
2336 <MagicMock name='mock.member.foo.bar.baz()' id='...'>
2337
2338If modifying your production classes to add defaults isn't to your liking
2339then there are more options. One of these is simply to use an instance as the
2340spec rather than the class. The other is to create a subclass of the
2341production class and add the defaults to the subclass without affecting the
2342production class. Both of these require you to use an alternative object as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002343the spec. Thankfully :func:`patch` supports this - you can simply pass the
2344alternative object as the *autospec* argument:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002345
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002346 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002347 ... def __init__(self):
2348 ... self.a = 33
2349 ...
2350 >>> class SomethingForTest(Something):
2351 ... a = 33
2352 ...
2353 >>> p = patch('__main__.Something', autospec=SomethingForTest)
2354 >>> mock = p.start()
2355 >>> mock.a
2356 <NonCallableMagicMock name='Something.a' spec='int' id='...'>
2357
2358
2359.. [#] This only applies to classes or already instantiated objects. Calling
2360 a mocked class to create a mock instance *does not* create a real instance.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002361 It is only attribute lookups - along with calls to :func:`dir` - that are done.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002362