blob: 5c9177a9c8791220e1ad0fb22e0106e7db289595 [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
265
266 .. method:: assert_called_with(*args, **kwargs)
267
268 This method is a convenient way of asserting that calls are made in a
269 particular way:
270
271 >>> mock = Mock()
272 >>> mock.method(1, 2, 3, test='wow')
273 <Mock name='mock.method()' id='...'>
274 >>> mock.method.assert_called_with(1, 2, 3, test='wow')
275
Michael Foord944e02d2012-03-25 23:12:55 +0100276 .. method:: assert_called_once_with(*args, **kwargs)
277
278 Assert that the mock was called exactly once and with the specified
279 arguments.
280
281 >>> mock = Mock(return_value=None)
282 >>> mock('foo', bar='baz')
283 >>> mock.assert_called_once_with('foo', bar='baz')
284 >>> mock('foo', bar='baz')
285 >>> mock.assert_called_once_with('foo', bar='baz')
286 Traceback (most recent call last):
287 ...
Michael Foord28d591c2012-09-28 16:15:22 +0100288 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foord944e02d2012-03-25 23:12:55 +0100289
290
291 .. method:: assert_any_call(*args, **kwargs)
292
293 assert the mock has been called with the specified arguments.
294
295 The assert passes if the mock has *ever* been called, unlike
296 :meth:`assert_called_with` and :meth:`assert_called_once_with` that
297 only pass if the call is the most recent one.
298
299 >>> mock = Mock(return_value=None)
300 >>> mock(1, 2, arg='thing')
301 >>> mock('some', 'thing', 'else')
302 >>> mock.assert_any_call(1, 2, arg='thing')
303
304
305 .. method:: assert_has_calls(calls, any_order=False)
306
307 assert the mock has been called with the specified calls.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100308 The :attr:`mock_calls` list is checked for the calls.
Michael Foord944e02d2012-03-25 23:12:55 +0100309
Georg Brandl7ad3df62014-10-31 07:59:37 +0100310 If *any_order* is false (the default) then the calls must be
Michael Foord944e02d2012-03-25 23:12:55 +0100311 sequential. There can be extra calls before or after the
312 specified calls.
313
Georg Brandl7ad3df62014-10-31 07:59:37 +0100314 If *any_order* is true then the calls can be in any order, but
Michael Foord944e02d2012-03-25 23:12:55 +0100315 they must all appear in :attr:`mock_calls`.
316
317 >>> mock = Mock(return_value=None)
318 >>> mock(1)
319 >>> mock(2)
320 >>> mock(3)
321 >>> mock(4)
322 >>> calls = [call(2), call(3)]
323 >>> mock.assert_has_calls(calls)
324 >>> calls = [call(4), call(2), call(3)]
325 >>> mock.assert_has_calls(calls, any_order=True)
326
Kushal Das8af9db32014-04-17 01:36:14 +0530327 .. method:: assert_not_called(*args, **kwargs)
328
329 Assert the mock was never called.
330
331 >>> m = Mock()
332 >>> m.hello.assert_not_called()
333 >>> obj = m.hello()
334 >>> m.hello.assert_not_called()
335 Traceback (most recent call last):
336 ...
337 AssertionError: Expected 'hello' to not have been called. Called 1 times.
338
339 .. versionadded:: 3.5
340
Michael Foord944e02d2012-03-25 23:12:55 +0100341
342 .. method:: reset_mock()
343
344 The reset_mock method resets all the call attributes on a mock object:
345
346 >>> mock = Mock(return_value=None)
347 >>> mock('hello')
348 >>> mock.called
349 True
350 >>> mock.reset_mock()
351 >>> mock.called
352 False
353
354 This can be useful where you want to make a series of assertions that
Georg Brandl7ad3df62014-10-31 07:59:37 +0100355 reuse the same object. Note that :meth:`reset_mock` *doesn't* clear the
Michael Foord944e02d2012-03-25 23:12:55 +0100356 return value, :attr:`side_effect` or any child attributes you have
357 set using normal assignment. Child mocks and the return value mock
358 (if any) are reset as well.
359
360
361 .. method:: mock_add_spec(spec, spec_set=False)
362
Georg Brandl7ad3df62014-10-31 07:59:37 +0100363 Add a spec to a mock. *spec* can either be an object or a
364 list of strings. Only attributes on the *spec* can be fetched as
Michael Foord944e02d2012-03-25 23:12:55 +0100365 attributes from the mock.
366
Georg Brandl7ad3df62014-10-31 07:59:37 +0100367 If *spec_set* is true then only attributes on the spec can be set.
Michael Foord944e02d2012-03-25 23:12:55 +0100368
369
370 .. method:: attach_mock(mock, attribute)
371
372 Attach a mock as an attribute of this one, replacing its name and
373 parent. Calls to the attached mock will be recorded in the
374 :attr:`method_calls` and :attr:`mock_calls` attributes of this one.
375
376
377 .. method:: configure_mock(**kwargs)
378
379 Set attributes on the mock through keyword arguments.
380
381 Attributes plus return values and side effects can be set on child
382 mocks using standard dot notation and unpacking a dictionary in the
383 method call:
384
385 >>> mock = Mock()
386 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
387 >>> mock.configure_mock(**attrs)
388 >>> mock.method()
389 3
390 >>> mock.other()
391 Traceback (most recent call last):
392 ...
393 KeyError
394
395 The same thing can be achieved in the constructor call to mocks:
396
397 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
398 >>> mock = Mock(some_attribute='eggs', **attrs)
399 >>> mock.some_attribute
400 'eggs'
401 >>> mock.method()
402 3
403 >>> mock.other()
404 Traceback (most recent call last):
405 ...
406 KeyError
407
Georg Brandl7ad3df62014-10-31 07:59:37 +0100408 :meth:`configure_mock` exists to make it easier to do configuration
Michael Foord944e02d2012-03-25 23:12:55 +0100409 after the mock has been created.
410
411
412 .. method:: __dir__()
413
Georg Brandl7ad3df62014-10-31 07:59:37 +0100414 :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results.
415 For mocks with a *spec* this includes all the permitted attributes
Michael Foord944e02d2012-03-25 23:12:55 +0100416 for the mock.
417
418 See :data:`FILTER_DIR` for what this filtering does, and how to
419 switch it off.
420
421
422 .. method:: _get_child_mock(**kw)
423
424 Create the child mocks for attributes and return value.
425 By default child mocks will be the same type as the parent.
426 Subclasses of Mock may want to override this to customize the way
427 child mocks are made.
428
429 For non-callable mocks the callable variant will be used (rather than
430 any custom subclass).
431
432
433 .. attribute:: called
434
435 A boolean representing whether or not the mock object has been called:
436
437 >>> mock = Mock(return_value=None)
438 >>> mock.called
439 False
440 >>> mock()
441 >>> mock.called
442 True
443
444 .. attribute:: call_count
445
446 An integer telling you how many times the mock object has been called:
447
448 >>> mock = Mock(return_value=None)
449 >>> mock.call_count
450 0
451 >>> mock()
452 >>> mock()
453 >>> mock.call_count
454 2
455
456
457 .. attribute:: return_value
458
459 Set this to configure the value returned by calling the mock:
460
461 >>> mock = Mock()
462 >>> mock.return_value = 'fish'
463 >>> mock()
464 'fish'
465
466 The default return value is a mock object and you can configure it in
467 the normal way:
468
469 >>> mock = Mock()
470 >>> mock.return_value.attribute = sentinel.Attribute
471 >>> mock.return_value()
472 <Mock name='mock()()' id='...'>
473 >>> mock.return_value.assert_called_with()
474
Georg Brandl7ad3df62014-10-31 07:59:37 +0100475 :attr:`return_value` can also be set in the constructor:
Michael Foord944e02d2012-03-25 23:12:55 +0100476
477 >>> mock = Mock(return_value=3)
478 >>> mock.return_value
479 3
480 >>> mock()
481 3
482
483
484 .. attribute:: side_effect
485
486 This can either be a function to be called when the mock is called,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100487 an iterable or an exception (class or instance) to be raised.
Michael Foord944e02d2012-03-25 23:12:55 +0100488
489 If you pass in a function it will be called with same arguments as the
490 mock and unless the function returns the :data:`DEFAULT` singleton the
491 call to the mock will then return whatever the function returns. If the
492 function returns :data:`DEFAULT` then the mock will return its normal
Brett Cannon533f1ed2013-05-25 11:28:20 -0400493 value (from the :attr:`return_value`).
Michael Foord944e02d2012-03-25 23:12:55 +0100494
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100495 If you pass in an iterable, it is used to retrieve an iterator which
496 must yield a value on every call. This value can either be an exception
497 instance to be raised, or a value to be returned from the call to the
498 mock (:data:`DEFAULT` handling is identical to the function case).
499
Michael Foord944e02d2012-03-25 23:12:55 +0100500 An example of a mock that raises an exception (to test exception
501 handling of an API):
502
503 >>> mock = Mock()
504 >>> mock.side_effect = Exception('Boom!')
505 >>> mock()
506 Traceback (most recent call last):
507 ...
508 Exception: Boom!
509
Georg Brandl7ad3df62014-10-31 07:59:37 +0100510 Using :attr:`side_effect` to return a sequence of values:
Michael Foord944e02d2012-03-25 23:12:55 +0100511
512 >>> mock = Mock()
513 >>> mock.side_effect = [3, 2, 1]
514 >>> mock(), mock(), mock()
515 (3, 2, 1)
516
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100517 Using a callable:
Michael Foord944e02d2012-03-25 23:12:55 +0100518
519 >>> mock = Mock(return_value=3)
520 >>> def side_effect(*args, **kwargs):
521 ... return DEFAULT
522 ...
523 >>> mock.side_effect = side_effect
524 >>> mock()
525 3
526
Georg Brandl7ad3df62014-10-31 07:59:37 +0100527 :attr:`side_effect` can be set in the constructor. Here's an example that
Michael Foord944e02d2012-03-25 23:12:55 +0100528 adds one to the value the mock is called with and returns it:
529
530 >>> side_effect = lambda value: value + 1
531 >>> mock = Mock(side_effect=side_effect)
532 >>> mock(3)
533 4
534 >>> mock(-8)
535 -7
536
Georg Brandl7ad3df62014-10-31 07:59:37 +0100537 Setting :attr:`side_effect` to ``None`` clears it:
Michael Foord944e02d2012-03-25 23:12:55 +0100538
539 >>> m = Mock(side_effect=KeyError, return_value=3)
540 >>> m()
541 Traceback (most recent call last):
542 ...
543 KeyError
544 >>> m.side_effect = None
545 >>> m()
546 3
547
548
549 .. attribute:: call_args
550
Georg Brandl7ad3df62014-10-31 07:59:37 +0100551 This is either ``None`` (if the mock hasn't been called), or the
Michael Foord944e02d2012-03-25 23:12:55 +0100552 arguments that the mock was last called with. This will be in the
553 form of a tuple: the first member is any ordered arguments the mock
554 was called with (or an empty tuple) and the second member is any
555 keyword arguments (or an empty dictionary).
556
557 >>> mock = Mock(return_value=None)
Berker Peksag920f6db2015-09-10 21:41:15 +0300558 >>> print(mock.call_args)
Michael Foord944e02d2012-03-25 23:12:55 +0100559 None
560 >>> mock()
561 >>> mock.call_args
562 call()
563 >>> mock.call_args == ()
564 True
565 >>> mock(3, 4)
566 >>> mock.call_args
567 call(3, 4)
568 >>> mock.call_args == ((3, 4),)
569 True
570 >>> mock(3, 4, 5, key='fish', next='w00t!')
571 >>> mock.call_args
572 call(3, 4, 5, key='fish', next='w00t!')
573
Georg Brandl7ad3df62014-10-31 07:59:37 +0100574 :attr:`call_args`, along with members of the lists :attr:`call_args_list`,
Michael Foord944e02d2012-03-25 23:12:55 +0100575 :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects.
576 These are tuples, so they can be unpacked to get at the individual
577 arguments and make more complex assertions. See
578 :ref:`calls as tuples <calls-as-tuples>`.
579
580
581 .. attribute:: call_args_list
582
583 This is a list of all the calls made to the mock object in sequence
584 (so the length of the list is the number of times it has been
585 called). Before any calls have been made it is an empty list. The
586 :data:`call` object can be used for conveniently constructing lists of
Georg Brandl7ad3df62014-10-31 07:59:37 +0100587 calls to compare with :attr:`call_args_list`.
Michael Foord944e02d2012-03-25 23:12:55 +0100588
589 >>> mock = Mock(return_value=None)
590 >>> mock()
591 >>> mock(3, 4)
592 >>> mock(key='fish', next='w00t!')
593 >>> mock.call_args_list
594 [call(), call(3, 4), call(key='fish', next='w00t!')]
595 >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
596 >>> mock.call_args_list == expected
597 True
598
Georg Brandl7ad3df62014-10-31 07:59:37 +0100599 Members of :attr:`call_args_list` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100600 unpacked as tuples to get at the individual arguments. See
601 :ref:`calls as tuples <calls-as-tuples>`.
602
603
604 .. attribute:: method_calls
605
606 As well as tracking calls to themselves, mocks also track calls to
607 methods and attributes, and *their* methods and attributes:
608
609 >>> mock = Mock()
610 >>> mock.method()
611 <Mock name='mock.method()' id='...'>
612 >>> mock.property.method.attribute()
613 <Mock name='mock.property.method.attribute()' id='...'>
614 >>> mock.method_calls
615 [call.method(), call.property.method.attribute()]
616
Georg Brandl7ad3df62014-10-31 07:59:37 +0100617 Members of :attr:`method_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100618 unpacked as tuples to get at the individual arguments. See
619 :ref:`calls as tuples <calls-as-tuples>`.
620
621
622 .. attribute:: mock_calls
623
Georg Brandl7ad3df62014-10-31 07:59:37 +0100624 :attr:`mock_calls` records *all* calls to the mock object, its methods,
625 magic methods *and* return value mocks.
Michael Foord944e02d2012-03-25 23:12:55 +0100626
627 >>> mock = MagicMock()
628 >>> result = mock(1, 2, 3)
629 >>> mock.first(a=3)
630 <MagicMock name='mock.first()' id='...'>
631 >>> mock.second()
632 <MagicMock name='mock.second()' id='...'>
633 >>> int(mock)
634 1
635 >>> result(1)
636 <MagicMock name='mock()()' id='...'>
637 >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
638 ... call.__int__(), call()(1)]
639 >>> mock.mock_calls == expected
640 True
641
Georg Brandl7ad3df62014-10-31 07:59:37 +0100642 Members of :attr:`mock_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100643 unpacked as tuples to get at the individual arguments. See
644 :ref:`calls as tuples <calls-as-tuples>`.
645
646
647 .. attribute:: __class__
648
Georg Brandl7ad3df62014-10-31 07:59:37 +0100649 Normally the :attr:`__class__` attribute of an object will return its type.
650 For a mock object with a :attr:`spec`, ``__class__`` returns the spec class
651 instead. This allows mock objects to pass :func:`isinstance` tests for the
Michael Foord944e02d2012-03-25 23:12:55 +0100652 object they are replacing / masquerading as:
653
654 >>> mock = Mock(spec=3)
655 >>> isinstance(mock, int)
656 True
657
Georg Brandl7ad3df62014-10-31 07:59:37 +0100658 :attr:`__class__` is assignable to, this allows a mock to pass an
659 :func:`isinstance` check without forcing you to use a spec:
Michael Foord944e02d2012-03-25 23:12:55 +0100660
661 >>> mock = Mock()
662 >>> mock.__class__ = dict
663 >>> isinstance(mock, dict)
664 True
665
666.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
667
Georg Brandl7ad3df62014-10-31 07:59:37 +0100668 A non-callable version of :class:`Mock`. The constructor parameters have the same
669 meaning of :class:`Mock`, with the exception of *return_value* and *side_effect*
Michael Foord944e02d2012-03-25 23:12:55 +0100670 which have no meaning on a non-callable mock.
671
Georg Brandl7ad3df62014-10-31 07:59:37 +0100672Mock objects that use a class or an instance as a :attr:`spec` or
673:attr:`spec_set` are able to pass :func:`isinstance` tests:
Michael Foord944e02d2012-03-25 23:12:55 +0100674
675 >>> mock = Mock(spec=SomeClass)
676 >>> isinstance(mock, SomeClass)
677 True
678 >>> mock = Mock(spec_set=SomeClass())
679 >>> isinstance(mock, SomeClass)
680 True
681
Georg Brandl7ad3df62014-10-31 07:59:37 +0100682The :class:`Mock` classes have support for mocking magic methods. See :ref:`magic
Michael Foord944e02d2012-03-25 23:12:55 +0100683methods <magic-methods>` for the full details.
684
685The mock classes and the :func:`patch` decorators all take arbitrary keyword
Georg Brandl7ad3df62014-10-31 07:59:37 +0100686arguments for configuration. For the :func:`patch` decorators the keywords are
Michael Foord944e02d2012-03-25 23:12:55 +0100687passed to the constructor of the mock being created. The keyword arguments
688are for configuring attributes of the mock:
689
690 >>> m = MagicMock(attribute=3, other='fish')
691 >>> m.attribute
692 3
693 >>> m.other
694 'fish'
695
696The return value and side effect of child mocks can be set in the same way,
697using dotted notation. As you can't use dotted names directly in a call you
Georg Brandl7ad3df62014-10-31 07:59:37 +0100698have to create a dictionary and unpack it using ``**``:
Michael Foord944e02d2012-03-25 23:12:55 +0100699
700 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
701 >>> mock = Mock(some_attribute='eggs', **attrs)
702 >>> mock.some_attribute
703 'eggs'
704 >>> mock.method()
705 3
706 >>> mock.other()
707 Traceback (most recent call last):
708 ...
709 KeyError
710
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100711A callable mock which was created with a *spec* (or a *spec_set*) will
712introspect the specification object's signature when matching calls to
713the mock. Therefore, it can match the actual call's arguments regardless
714of whether they were passed positionally or by name::
715
716 >>> def f(a, b, c): pass
717 ...
718 >>> mock = Mock(spec=f)
719 >>> mock(1, 2, c=3)
720 <Mock name='mock()' id='140161580456576'>
721 >>> mock.assert_called_with(1, 2, 3)
722 >>> mock.assert_called_with(a=1, b=2, c=3)
723
724This applies to :meth:`~Mock.assert_called_with`,
725:meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and
726:meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also
727apply to method calls on the mock object.
728
729 .. versionchanged:: 3.4
730 Added signature introspection on specced and autospecced mock objects.
731
Michael Foord944e02d2012-03-25 23:12:55 +0100732
733.. class:: PropertyMock(*args, **kwargs)
734
735 A mock intended to be used as a property, or other descriptor, on a class.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100736 :class:`PropertyMock` provides :meth:`__get__` and :meth:`__set__` methods
737 so you can specify a return value when it is fetched.
Michael Foord944e02d2012-03-25 23:12:55 +0100738
Georg Brandl7ad3df62014-10-31 07:59:37 +0100739 Fetching a :class:`PropertyMock` instance from an object calls the mock, with
Michael Foord944e02d2012-03-25 23:12:55 +0100740 no args. Setting it calls the mock with the value being set.
741
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200742 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100743 ... @property
744 ... def foo(self):
745 ... return 'something'
746 ... @foo.setter
747 ... def foo(self, value):
748 ... pass
749 ...
750 >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
751 ... mock_foo.return_value = 'mockity-mock'
752 ... this_foo = Foo()
Berker Peksag920f6db2015-09-10 21:41:15 +0300753 ... print(this_foo.foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100754 ... this_foo.foo = 6
755 ...
756 mockity-mock
757 >>> mock_foo.mock_calls
758 [call(), call(6)]
759
Michael Foordc2870622012-04-13 16:57:22 +0100760Because of the way mock attributes are stored you can't directly attach a
Georg Brandl7ad3df62014-10-31 07:59:37 +0100761:class:`PropertyMock` to a mock object. Instead you can attach it to the mock type
Michael Foordc2870622012-04-13 16:57:22 +0100762object::
763
764 >>> m = MagicMock()
765 >>> p = PropertyMock(return_value=3)
766 >>> type(m).foo = p
767 >>> m.foo
768 3
769 >>> p.assert_called_once_with()
770
Michael Foord944e02d2012-03-25 23:12:55 +0100771
772Calling
773~~~~~~~
774
775Mock objects are callable. The call will return the value set as the
776:attr:`~Mock.return_value` attribute. The default return value is a new Mock
777object; it is created the first time the return value is accessed (either
778explicitly or by calling the Mock) - but it is stored and the same one
779returned each time.
780
781Calls made to the object will be recorded in the attributes
782like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
783
784If :attr:`~Mock.side_effect` is set then it will be called after the call has
Georg Brandl7ad3df62014-10-31 07:59:37 +0100785been recorded, so if :attr:`side_effect` raises an exception the call is still
Michael Foord944e02d2012-03-25 23:12:55 +0100786recorded.
787
788The simplest way to make a mock raise an exception when called is to make
789:attr:`~Mock.side_effect` an exception class or instance:
790
791 >>> m = MagicMock(side_effect=IndexError)
792 >>> m(1, 2, 3)
793 Traceback (most recent call last):
794 ...
795 IndexError
796 >>> m.mock_calls
797 [call(1, 2, 3)]
798 >>> m.side_effect = KeyError('Bang!')
799 >>> m('two', 'three', 'four')
800 Traceback (most recent call last):
801 ...
802 KeyError: 'Bang!'
803 >>> m.mock_calls
804 [call(1, 2, 3), call('two', 'three', 'four')]
805
Georg Brandl7ad3df62014-10-31 07:59:37 +0100806If :attr:`side_effect` is a function then whatever that function returns is what
807calls to the mock return. The :attr:`side_effect` function is called with the
Michael Foord944e02d2012-03-25 23:12:55 +0100808same arguments as the mock. This allows you to vary the return value of the
809call dynamically, based on the input:
810
811 >>> def side_effect(value):
812 ... return value + 1
813 ...
814 >>> m = MagicMock(side_effect=side_effect)
815 >>> m(1)
816 2
817 >>> m(2)
818 3
819 >>> m.mock_calls
820 [call(1), call(2)]
821
822If you want the mock to still return the default return value (a new mock), or
823any set return value, then there are two ways of doing this. Either return
Georg Brandl7ad3df62014-10-31 07:59:37 +0100824:attr:`mock.return_value` from inside :attr:`side_effect`, or return :data:`DEFAULT`:
Michael Foord944e02d2012-03-25 23:12:55 +0100825
826 >>> m = MagicMock()
827 >>> def side_effect(*args, **kwargs):
828 ... return m.return_value
829 ...
830 >>> m.side_effect = side_effect
831 >>> m.return_value = 3
832 >>> m()
833 3
834 >>> def side_effect(*args, **kwargs):
835 ... return DEFAULT
836 ...
837 >>> m.side_effect = side_effect
838 >>> m()
839 3
840
Georg Brandl7ad3df62014-10-31 07:59:37 +0100841To remove a :attr:`side_effect`, and return to the default behaviour, set the
842:attr:`side_effect` to ``None``:
Michael Foord944e02d2012-03-25 23:12:55 +0100843
844 >>> m = MagicMock(return_value=6)
845 >>> def side_effect(*args, **kwargs):
846 ... return 3
847 ...
848 >>> m.side_effect = side_effect
849 >>> m()
850 3
851 >>> m.side_effect = None
852 >>> m()
853 6
854
Georg Brandl7ad3df62014-10-31 07:59:37 +0100855The :attr:`side_effect` can also be any iterable object. Repeated calls to the mock
Michael Foord944e02d2012-03-25 23:12:55 +0100856will return values from the iterable (until the iterable is exhausted and
Georg Brandl7ad3df62014-10-31 07:59:37 +0100857a :exc:`StopIteration` is raised):
Michael Foord944e02d2012-03-25 23:12:55 +0100858
859 >>> m = MagicMock(side_effect=[1, 2, 3])
860 >>> m()
861 1
862 >>> m()
863 2
864 >>> m()
865 3
866 >>> m()
867 Traceback (most recent call last):
868 ...
869 StopIteration
870
Michael Foord2cd48732012-04-21 15:52:11 +0100871If any members of the iterable are exceptions they will be raised instead of
872returned::
873
874 >>> iterable = (33, ValueError, 66)
875 >>> m = MagicMock(side_effect=iterable)
876 >>> m()
877 33
878 >>> m()
879 Traceback (most recent call last):
880 ...
881 ValueError
882 >>> m()
883 66
884
Michael Foord944e02d2012-03-25 23:12:55 +0100885
886.. _deleting-attributes:
887
888Deleting Attributes
889~~~~~~~~~~~~~~~~~~~
890
891Mock objects create attributes on demand. This allows them to pretend to be
892objects of any type.
893
Georg Brandl7ad3df62014-10-31 07:59:37 +0100894You may want a mock object to return ``False`` to a :func:`hasattr` call, or raise an
895:exc:`AttributeError` when an attribute is fetched. You can do this by providing
896an object as a :attr:`spec` for a mock, but that isn't always convenient.
Michael Foord944e02d2012-03-25 23:12:55 +0100897
898You "block" attributes by deleting them. Once deleted, accessing an attribute
Georg Brandl7ad3df62014-10-31 07:59:37 +0100899will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100900
901 >>> mock = MagicMock()
902 >>> hasattr(mock, 'm')
903 True
904 >>> del mock.m
905 >>> hasattr(mock, 'm')
906 False
907 >>> del mock.f
908 >>> mock.f
909 Traceback (most recent call last):
910 ...
911 AttributeError: f
912
913
Michael Foordf5752302013-03-18 15:04:03 -0700914Mock names and the name attribute
915~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
916
917Since "name" is an argument to the :class:`Mock` constructor, if you want your
918mock object to have a "name" attribute you can't just pass it in at creation
919time. There are two alternatives. One option is to use
920:meth:`~Mock.configure_mock`::
921
922 >>> mock = MagicMock()
923 >>> mock.configure_mock(name='my_name')
924 >>> mock.name
925 'my_name'
926
927A simpler option is to simply set the "name" attribute after mock creation::
928
929 >>> mock = MagicMock()
930 >>> mock.name = "foo"
931
932
Michael Foord944e02d2012-03-25 23:12:55 +0100933Attaching Mocks as Attributes
934~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
935
936When you attach a mock as an attribute of another mock (or as the return
937value) it becomes a "child" of that mock. Calls to the child are recorded in
938the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
939parent. This is useful for configuring child mocks and then attaching them to
940the parent, or for attaching mocks to a parent that records all calls to the
941children and allows you to make assertions about the order of calls between
942mocks:
943
944 >>> parent = MagicMock()
945 >>> child1 = MagicMock(return_value=None)
946 >>> child2 = MagicMock(return_value=None)
947 >>> parent.child1 = child1
948 >>> parent.child2 = child2
949 >>> child1(1)
950 >>> child2(2)
951 >>> parent.mock_calls
952 [call.child1(1), call.child2(2)]
953
954The exception to this is if the mock has a name. This allows you to prevent
955the "parenting" if for some reason you don't want it to happen.
956
957 >>> mock = MagicMock()
958 >>> not_a_child = MagicMock(name='not-a-child')
959 >>> mock.attribute = not_a_child
960 >>> mock.attribute()
961 <MagicMock name='not-a-child()' id='...'>
962 >>> mock.mock_calls
963 []
964
965Mocks created for you by :func:`patch` are automatically given names. To
966attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
967method:
968
969 >>> thing1 = object()
970 >>> thing2 = object()
971 >>> parent = MagicMock()
972 >>> with patch('__main__.thing1', return_value=None) as child1:
973 ... with patch('__main__.thing2', return_value=None) as child2:
974 ... parent.attach_mock(child1, 'child1')
975 ... parent.attach_mock(child2, 'child2')
976 ... child1('one')
977 ... child2('two')
978 ...
979 >>> parent.mock_calls
980 [call.child1('one'), call.child2('two')]
981
982
983.. [#] The only exceptions are magic methods and attributes (those that have
984 leading and trailing double underscores). Mock doesn't create these but
Georg Brandl7ad3df62014-10-31 07:59:37 +0100985 instead raises an :exc:`AttributeError`. This is because the interpreter
Michael Foord944e02d2012-03-25 23:12:55 +0100986 will often implicitly request these methods, and gets *very* confused to
987 get a new Mock object when it expects a magic method. If you need magic
988 method support see :ref:`magic methods <magic-methods>`.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100989
990
991The patchers
Georg Brandlfb134382013-02-03 11:47:49 +0100992------------
Michael Foorda9e6fb22012-03-28 14:36:02 +0100993
994The patch decorators are used for patching objects only within the scope of
995the function they decorate. They automatically handle the unpatching for you,
996even if exceptions are raised. All of these functions can also be used in with
997statements or as class decorators.
998
999
1000patch
Georg Brandlfb134382013-02-03 11:47:49 +01001001~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001002
1003.. note::
1004
Georg Brandl7ad3df62014-10-31 07:59:37 +01001005 :func:`patch` is straightforward to use. The key is to do the patching in the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001006 right namespace. See the section `where to patch`_.
1007
1008.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1009
Georg Brandl7ad3df62014-10-31 07:59:37 +01001010 :func:`patch` acts as a function decorator, class decorator or a context
1011 manager. Inside the body of the function or with statement, the *target*
1012 is patched with a *new* object. When the function/with statement exits
Michael Foord54b3db82012-03-28 15:08:08 +01001013 the patch is undone.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001014
Georg Brandl7ad3df62014-10-31 07:59:37 +01001015 If *new* is omitted, then the target is replaced with a
1016 :class:`MagicMock`. If :func:`patch` is used as a decorator and *new* is
Michael Foord54b3db82012-03-28 15:08:08 +01001017 omitted, the created mock is passed in as an extra argument to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001018 decorated function. If :func:`patch` is used as a context manager the created
Michael Foord54b3db82012-03-28 15:08:08 +01001019 mock is returned by the context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001020
Georg Brandl7ad3df62014-10-31 07:59:37 +01001021 *target* should be a string in the form ``'package.module.ClassName'``. The
1022 *target* is imported and the specified object replaced with the *new*
1023 object, so the *target* must be importable from the environment you are
1024 calling :func:`patch` from. The target is imported when the decorated function
Michael Foord54b3db82012-03-28 15:08:08 +01001025 is executed, not at decoration time.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001026
Georg Brandl7ad3df62014-10-31 07:59:37 +01001027 The *spec* and *spec_set* keyword arguments are passed to the :class:`MagicMock`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001028 if patch is creating one for you.
1029
Georg Brandl7ad3df62014-10-31 07:59:37 +01001030 In addition you can pass ``spec=True`` or ``spec_set=True``, which causes
Michael Foorda9e6fb22012-03-28 14:36:02 +01001031 patch to pass in the object being mocked as the spec/spec_set object.
1032
Georg Brandl7ad3df62014-10-31 07:59:37 +01001033 *new_callable* allows you to specify a different class, or callable object,
1034 that will be called to create the *new* object. By default :class:`MagicMock` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001035 used.
1036
Georg Brandl7ad3df62014-10-31 07:59:37 +01001037 A more powerful form of *spec* is *autospec*. If you set ``autospec=True``
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001038 then the mock will be created with a spec from the object being replaced.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001039 All attributes of the mock will also have the spec of the corresponding
1040 attribute of the object being replaced. Methods and functions being mocked
Georg Brandl7ad3df62014-10-31 07:59:37 +01001041 will have their arguments checked and will raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001042 called with the wrong signature. For mocks
1043 replacing a class, their return value (the 'instance') will have the same
1044 spec as the class. See the :func:`create_autospec` function and
1045 :ref:`auto-speccing`.
1046
Georg Brandl7ad3df62014-10-31 07:59:37 +01001047 Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001048 arbitrary object as the spec instead of the one being replaced.
1049
Georg Brandl7ad3df62014-10-31 07:59:37 +01001050 By default :func:`patch` will fail to replace attributes that don't exist. If
1051 you pass in ``create=True``, and the attribute doesn't exist, patch will
Michael Foorda9e6fb22012-03-28 14:36:02 +01001052 create the attribute for you when the patched function is called, and
1053 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001054 attributes that your production code creates at runtime. It is off by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001055 default because it can be dangerous. With it switched on you can write
1056 passing tests against APIs that don't actually exist!
1057
Michael Foordfddcfa22014-04-14 16:25:20 -04001058 .. note::
1059
1060 .. versionchanged:: 3.5
1061 If you are patching builtins in a module then you don't
Georg Brandl7ad3df62014-10-31 07:59:37 +01001062 need to pass ``create=True``, it will be added by default.
Michael Foordfddcfa22014-04-14 16:25:20 -04001063
Georg Brandl7ad3df62014-10-31 07:59:37 +01001064 Patch can be used as a :class:`TestCase` class decorator. It works by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001065 decorating each test method in the class. This reduces the boilerplate
Georg Brandl7ad3df62014-10-31 07:59:37 +01001066 code when your test methods share a common patchings set. :func:`patch` finds
1067 tests by looking for method names that start with ``patch.TEST_PREFIX``.
1068 By default this is ``'test'``, which matches the way :mod:`unittest` finds tests.
1069 You can specify an alternative prefix by setting ``patch.TEST_PREFIX``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001070
1071 Patch can be used as a context manager, with the with statement. Here the
1072 patching applies to the indented block after the with statement. If you
1073 use "as" then the patched object will be bound to the name after the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001074 "as"; very useful if :func:`patch` is creating a mock object for you.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001075
Georg Brandl7ad3df62014-10-31 07:59:37 +01001076 :func:`patch` takes arbitrary keyword arguments. These will be passed to
1077 the :class:`Mock` (or *new_callable*) on construction.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001078
Georg Brandl7ad3df62014-10-31 07:59:37 +01001079 ``patch.dict(...)``, ``patch.multiple(...)`` and ``patch.object(...)`` are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001080 available for alternate use-cases.
1081
Georg Brandl7ad3df62014-10-31 07:59:37 +01001082:func:`patch` as function decorator, creating the mock for you and passing it into
Michael Foord90155362012-03-28 15:32:08 +01001083the decorated function:
1084
1085 >>> @patch('__main__.SomeClass')
Michael Foord324b58b2012-03-28 15:49:08 +01001086 ... def function(normal_argument, mock_class):
Michael Foord90155362012-03-28 15:32:08 +01001087 ... print(mock_class is SomeClass)
1088 ...
Michael Foord324b58b2012-03-28 15:49:08 +01001089 >>> function(None)
Michael Foord90155362012-03-28 15:32:08 +01001090 True
Michael Foorda9e6fb22012-03-28 14:36:02 +01001091
Georg Brandl7ad3df62014-10-31 07:59:37 +01001092Patching a class replaces the class with a :class:`MagicMock` *instance*. If the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001093class is instantiated in the code under test then it will be the
1094:attr:`~Mock.return_value` of the mock that will be used.
1095
1096If the class is instantiated multiple times you could use
1097:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
Georg Brandl7ad3df62014-10-31 07:59:37 +01001098can set the *return_value* to be anything you want.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001099
1100To configure return values on methods of *instances* on the patched class
Georg Brandl7ad3df62014-10-31 07:59:37 +01001101you must do this on the :attr:`return_value`. For example:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001102
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001103 >>> class Class:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001104 ... def method(self):
1105 ... pass
1106 ...
1107 >>> with patch('__main__.Class') as MockClass:
1108 ... instance = MockClass.return_value
1109 ... instance.method.return_value = 'foo'
1110 ... assert Class() is instance
1111 ... assert Class().method() == 'foo'
1112 ...
1113
Georg Brandl7ad3df62014-10-31 07:59:37 +01001114If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001115return value of the created mock will have the same spec.
1116
1117 >>> Original = Class
1118 >>> patcher = patch('__main__.Class', spec=True)
1119 >>> MockClass = patcher.start()
1120 >>> instance = MockClass()
1121 >>> assert isinstance(instance, Original)
1122 >>> patcher.stop()
1123
Georg Brandl7ad3df62014-10-31 07:59:37 +01001124The *new_callable* argument is useful where you want to use an alternative
Michael Foorda9e6fb22012-03-28 14:36:02 +01001125class to the default :class:`MagicMock` for the created mock. For example, if
1126you wanted a :class:`NonCallableMock` to be used:
1127
1128 >>> thing = object()
1129 >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
1130 ... assert thing is mock_thing
1131 ... thing()
1132 ...
1133 Traceback (most recent call last):
1134 ...
1135 TypeError: 'NonCallableMock' object is not callable
1136
Martin Panter7462b6492015-11-02 03:37:02 +00001137Another use case might be to replace an object with an :class:`io.StringIO` instance:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001138
Serhiy Storchakae79be872013-08-17 00:09:55 +03001139 >>> from io import StringIO
Michael Foorda9e6fb22012-03-28 14:36:02 +01001140 >>> def foo():
Berker Peksag920f6db2015-09-10 21:41:15 +03001141 ... print('Something')
Michael Foorda9e6fb22012-03-28 14:36:02 +01001142 ...
1143 >>> @patch('sys.stdout', new_callable=StringIO)
1144 ... def test(mock_stdout):
1145 ... foo()
1146 ... assert mock_stdout.getvalue() == 'Something\n'
1147 ...
1148 >>> test()
1149
Georg Brandl7ad3df62014-10-31 07:59:37 +01001150When :func:`patch` is creating a mock for you, it is common that the first thing
Michael Foorda9e6fb22012-03-28 14:36:02 +01001151you need to do is to configure the mock. Some of that configuration can be done
1152in the call to patch. Any arbitrary keywords you pass into the call will be
1153used to set attributes on the created mock:
1154
1155 >>> patcher = patch('__main__.thing', first='one', second='two')
1156 >>> mock_thing = patcher.start()
1157 >>> mock_thing.first
1158 'one'
1159 >>> mock_thing.second
1160 'two'
1161
1162As well as attributes on the created mock attributes, like the
1163:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
1164also be configured. These aren't syntactically valid to pass in directly as
1165keyword arguments, but a dictionary with these as keys can still be expanded
Georg Brandl7ad3df62014-10-31 07:59:37 +01001166into a :func:`patch` call using ``**``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001167
1168 >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
1169 >>> patcher = patch('__main__.thing', **config)
1170 >>> mock_thing = patcher.start()
1171 >>> mock_thing.method()
1172 3
1173 >>> mock_thing.other()
1174 Traceback (most recent call last):
1175 ...
1176 KeyError
1177
1178
1179patch.object
Georg Brandlfb134382013-02-03 11:47:49 +01001180~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001181
1182.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1183
Georg Brandl7ad3df62014-10-31 07:59:37 +01001184 patch the named member (*attribute*) on an object (*target*) with a mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001185 object.
1186
Georg Brandl7ad3df62014-10-31 07:59:37 +01001187 :func:`patch.object` can be used as a decorator, class decorator or a context
1188 manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* and
1189 *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`,
1190 :func:`patch.object` takes arbitrary keyword arguments for configuring the mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001191 object it creates.
1192
Georg Brandl7ad3df62014-10-31 07:59:37 +01001193 When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001194 for choosing which methods to wrap.
1195
Georg Brandl7ad3df62014-10-31 07:59:37 +01001196You can either call :func:`patch.object` with three arguments or two arguments. The
Michael Foorda9e6fb22012-03-28 14:36:02 +01001197three argument form takes the object to be patched, the attribute name and the
1198object to replace the attribute with.
1199
1200When calling with the two argument form you omit the replacement object, and a
1201mock is created for you and passed in as an extra argument to the decorated
1202function:
1203
1204 >>> @patch.object(SomeClass, 'class_method')
1205 ... def test(mock_method):
1206 ... SomeClass.class_method(3)
1207 ... mock_method.assert_called_with(3)
1208 ...
1209 >>> test()
1210
Georg Brandl7ad3df62014-10-31 07:59:37 +01001211*spec*, *create* and the other arguments to :func:`patch.object` have the same
1212meaning as they do for :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001213
1214
1215patch.dict
Georg Brandlfb134382013-02-03 11:47:49 +01001216~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001217
1218.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs)
1219
1220 Patch a dictionary, or dictionary like object, and restore the dictionary
1221 to its original state after the test.
1222
Georg Brandl7ad3df62014-10-31 07:59:37 +01001223 *in_dict* can be a dictionary or a mapping like container. If it is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01001224 mapping then it must at least support getting, setting and deleting items
1225 plus iterating over keys.
1226
Georg Brandl7ad3df62014-10-31 07:59:37 +01001227 *in_dict* can also be a string specifying the name of the dictionary, which
Michael Foorda9e6fb22012-03-28 14:36:02 +01001228 will then be fetched by importing it.
1229
Georg Brandl7ad3df62014-10-31 07:59:37 +01001230 *values* can be a dictionary of values to set in the dictionary. *values*
1231 can also be an iterable of ``(key, value)`` pairs.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001232
Georg Brandl7ad3df62014-10-31 07:59:37 +01001233 If *clear* is true then the dictionary will be cleared before the new
Michael Foorda9e6fb22012-03-28 14:36:02 +01001234 values are set.
1235
Georg Brandl7ad3df62014-10-31 07:59:37 +01001236 :func:`patch.dict` can also be called with arbitrary keyword arguments to set
Michael Foorda9e6fb22012-03-28 14:36:02 +01001237 values in the dictionary.
1238
Georg Brandl7ad3df62014-10-31 07:59:37 +01001239 :func:`patch.dict` can be used as a context manager, decorator or class
1240 decorator. When used as a class decorator :func:`patch.dict` honours
1241 ``patch.TEST_PREFIX`` for choosing which methods to wrap.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001242
Georg Brandl7ad3df62014-10-31 07:59:37 +01001243:func:`patch.dict` can be used to add members to a dictionary, or simply let a test
Michael Foorda9e6fb22012-03-28 14:36:02 +01001244change a dictionary, and ensure the dictionary is restored when the test
1245ends.
1246
1247 >>> foo = {}
1248 >>> with patch.dict(foo, {'newkey': 'newvalue'}):
1249 ... assert foo == {'newkey': 'newvalue'}
1250 ...
1251 >>> assert foo == {}
1252
1253 >>> import os
1254 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
Berker Peksag920f6db2015-09-10 21:41:15 +03001255 ... print(os.environ['newkey'])
Michael Foorda9e6fb22012-03-28 14:36:02 +01001256 ...
1257 newvalue
1258 >>> assert 'newkey' not in os.environ
1259
Georg Brandl7ad3df62014-10-31 07:59:37 +01001260Keywords can be used in the :func:`patch.dict` call to set values in the dictionary:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001261
1262 >>> mymodule = MagicMock()
1263 >>> mymodule.function.return_value = 'fish'
1264 >>> with patch.dict('sys.modules', mymodule=mymodule):
1265 ... import mymodule
1266 ... mymodule.function('some', 'args')
1267 ...
1268 'fish'
1269
Georg Brandl7ad3df62014-10-31 07:59:37 +01001270:func:`patch.dict` can be used with dictionary like objects that aren't actually
Michael Foorda9e6fb22012-03-28 14:36:02 +01001271dictionaries. At the very minimum they must support item getting, setting,
1272deleting and either iteration or membership test. This corresponds to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001273magic methods :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__` and either
1274:meth:`__iter__` or :meth:`__contains__`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001275
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001276 >>> class Container:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001277 ... def __init__(self):
1278 ... self.values = {}
1279 ... def __getitem__(self, name):
1280 ... return self.values[name]
1281 ... def __setitem__(self, name, value):
1282 ... self.values[name] = value
1283 ... def __delitem__(self, name):
1284 ... del self.values[name]
1285 ... def __iter__(self):
1286 ... return iter(self.values)
1287 ...
1288 >>> thing = Container()
1289 >>> thing['one'] = 1
1290 >>> with patch.dict(thing, one=2, two=3):
1291 ... assert thing['one'] == 2
1292 ... assert thing['two'] == 3
1293 ...
1294 >>> assert thing['one'] == 1
1295 >>> assert list(thing) == ['one']
1296
1297
1298patch.multiple
Georg Brandlfb134382013-02-03 11:47:49 +01001299~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001300
1301.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1302
1303 Perform multiple patches in a single call. It takes the object to be
1304 patched (either as an object or a string to fetch the object by importing)
1305 and keyword arguments for the patches::
1306
1307 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1308 ...
1309
Georg Brandl7ad3df62014-10-31 07:59:37 +01001310 Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create
Michael Foorda9e6fb22012-03-28 14:36:02 +01001311 mocks for you. In this case the created mocks are passed into a decorated
Georg Brandl7ad3df62014-10-31 07:59:37 +01001312 function by keyword, and a dictionary is returned when :func:`patch.multiple` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001313 used as a context manager.
1314
Georg Brandl7ad3df62014-10-31 07:59:37 +01001315 :func:`patch.multiple` can be used as a decorator, class decorator or a context
1316 manager. The arguments *spec*, *spec_set*, *create*, *autospec* and
1317 *new_callable* have the same meaning as for :func:`patch`. These arguments will
1318 be applied to *all* patches done by :func:`patch.multiple`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001319
Georg Brandl7ad3df62014-10-31 07:59:37 +01001320 When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001321 for choosing which methods to wrap.
1322
Georg Brandl7ad3df62014-10-31 07:59:37 +01001323If you want :func:`patch.multiple` to create mocks for you, then you can use
1324:data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator
Michael Foorda9e6fb22012-03-28 14:36:02 +01001325then the created mocks are passed into the decorated function by keyword.
1326
1327 >>> thing = object()
1328 >>> other = object()
1329
1330 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1331 ... def test_function(thing, other):
1332 ... assert isinstance(thing, MagicMock)
1333 ... assert isinstance(other, MagicMock)
1334 ...
1335 >>> test_function()
1336
Georg Brandl7ad3df62014-10-31 07:59:37 +01001337:func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments
1338passed by keyword *after* any of the standard arguments created by :func:`patch`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001339
1340 >>> @patch('sys.exit')
1341 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1342 ... def test_function(mock_exit, other, thing):
1343 ... assert 'other' in repr(other)
1344 ... assert 'thing' in repr(thing)
1345 ... assert 'exit' in repr(mock_exit)
1346 ...
1347 >>> test_function()
1348
Georg Brandl7ad3df62014-10-31 07:59:37 +01001349If :func:`patch.multiple` is used as a context manager, the value returned by the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001350context manger is a dictionary where created mocks are keyed by name:
1351
1352 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
1353 ... assert 'other' in repr(values['other'])
1354 ... assert 'thing' in repr(values['thing'])
1355 ... assert values['thing'] is thing
1356 ... assert values['other'] is other
1357 ...
1358
1359
1360.. _start-and-stop:
1361
1362patch methods: start and stop
Georg Brandlfb134382013-02-03 11:47:49 +01001363~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001364
Georg Brandl7ad3df62014-10-31 07:59:37 +01001365All the patchers have :meth:`start` and :meth:`stop` methods. These make it simpler to do
1366patching in ``setUp`` methods or where you want to do multiple patches without
Michael Foorda9e6fb22012-03-28 14:36:02 +01001367nesting decorators or with statements.
1368
Georg Brandl7ad3df62014-10-31 07:59:37 +01001369To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as
1370normal and keep a reference to the returned ``patcher`` object. You can then
1371call :meth:`start` to put the patch in place and :meth:`stop` to undo it.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001372
Georg Brandl7ad3df62014-10-31 07:59:37 +01001373If you are using :func:`patch` to create a mock for you then it will be returned by
1374the call to ``patcher.start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001375
1376 >>> patcher = patch('package.module.ClassName')
1377 >>> from package import module
1378 >>> original = module.ClassName
1379 >>> new_mock = patcher.start()
1380 >>> assert module.ClassName is not original
1381 >>> assert module.ClassName is new_mock
1382 >>> patcher.stop()
1383 >>> assert module.ClassName is original
1384 >>> assert module.ClassName is not new_mock
1385
1386
Georg Brandl7ad3df62014-10-31 07:59:37 +01001387A typical use case for this might be for doing multiple patches in the ``setUp``
1388method of a :class:`TestCase`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001389
1390 >>> class MyTest(TestCase):
1391 ... def setUp(self):
1392 ... self.patcher1 = patch('package.module.Class1')
1393 ... self.patcher2 = patch('package.module.Class2')
1394 ... self.MockClass1 = self.patcher1.start()
1395 ... self.MockClass2 = self.patcher2.start()
1396 ...
1397 ... def tearDown(self):
1398 ... self.patcher1.stop()
1399 ... self.patcher2.stop()
1400 ...
1401 ... def test_something(self):
1402 ... assert package.module.Class1 is self.MockClass1
1403 ... assert package.module.Class2 is self.MockClass2
1404 ...
1405 >>> MyTest('test_something').run()
1406
1407.. caution::
1408
1409 If you use this technique you must ensure that the patching is "undone" by
Georg Brandl7ad3df62014-10-31 07:59:37 +01001410 calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001411 exception is raised in the ``setUp`` then ``tearDown`` is not called.
1412 :meth:`unittest.TestCase.addCleanup` makes this easier:
1413
1414 >>> class MyTest(TestCase):
1415 ... def setUp(self):
1416 ... patcher = patch('package.module.Class')
1417 ... self.MockClass = patcher.start()
1418 ... self.addCleanup(patcher.stop)
1419 ...
1420 ... def test_something(self):
1421 ... assert package.module.Class is self.MockClass
1422 ...
1423
Georg Brandl7ad3df62014-10-31 07:59:37 +01001424 As an added bonus you no longer need to keep a reference to the ``patcher``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001425 object.
1426
Michael Foordf7c41582012-06-10 20:36:32 +01001427It is also possible to stop all patches which have been started by using
Georg Brandl7ad3df62014-10-31 07:59:37 +01001428:func:`patch.stopall`.
Michael Foordf7c41582012-06-10 20:36:32 +01001429
1430.. function:: patch.stopall
1431
Georg Brandl7ad3df62014-10-31 07:59:37 +01001432 Stop all active patches. Only stops patches started with ``start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001433
Georg Brandl7ad3df62014-10-31 07:59:37 +01001434
1435.. _patch-builtins:
Michael Foordfddcfa22014-04-14 16:25:20 -04001436
1437patch builtins
Georg Brandl7ad3df62014-10-31 07:59:37 +01001438~~~~~~~~~~~~~~
Michael Foordfddcfa22014-04-14 16:25:20 -04001439You can patch any builtins within a module. The following example patches
Georg Brandl7ad3df62014-10-31 07:59:37 +01001440builtin :func:`ord`:
Michael Foordfddcfa22014-04-14 16:25:20 -04001441
1442 >>> @patch('__main__.ord')
1443 ... def test(mock_ord):
1444 ... mock_ord.return_value = 101
1445 ... print(ord('c'))
1446 ...
1447 >>> test()
1448 101
1449
Michael Foorda9e6fb22012-03-28 14:36:02 +01001450
1451TEST_PREFIX
Georg Brandlfb134382013-02-03 11:47:49 +01001452~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001453
1454All of the patchers can be used as class decorators. When used in this way
1455they wrap every test method on the class. The patchers recognise methods that
Georg Brandl7ad3df62014-10-31 07:59:37 +01001456start with ``'test'`` as being test methods. This is the same way that the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001457:class:`unittest.TestLoader` finds test methods by default.
1458
1459It is possible that you want to use a different prefix for your tests. You can
Georg Brandl7ad3df62014-10-31 07:59:37 +01001460inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001461
1462 >>> patch.TEST_PREFIX = 'foo'
1463 >>> value = 3
1464 >>>
1465 >>> @patch('__main__.value', 'not three')
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001466 ... class Thing:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001467 ... def foo_one(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001468 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001469 ... def foo_two(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001470 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001471 ...
1472 >>>
1473 >>> Thing().foo_one()
1474 not three
1475 >>> Thing().foo_two()
1476 not three
1477 >>> value
1478 3
1479
1480
1481Nesting Patch Decorators
Georg Brandlfb134382013-02-03 11:47:49 +01001482~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001483
1484If you want to perform multiple patches then you can simply stack up the
1485decorators.
1486
1487You can stack up multiple patch decorators using this pattern:
1488
1489 >>> @patch.object(SomeClass, 'class_method')
1490 ... @patch.object(SomeClass, 'static_method')
1491 ... def test(mock1, mock2):
1492 ... assert SomeClass.static_method is mock1
1493 ... assert SomeClass.class_method is mock2
1494 ... SomeClass.static_method('foo')
1495 ... SomeClass.class_method('bar')
1496 ... return mock1, mock2
1497 ...
1498 >>> mock1, mock2 = test()
1499 >>> mock1.assert_called_once_with('foo')
1500 >>> mock2.assert_called_once_with('bar')
1501
1502
1503Note that the decorators are applied from the bottom upwards. This is the
1504standard way that Python applies decorators. The order of the created mocks
1505passed into your test function matches this order.
1506
1507
1508.. _where-to-patch:
1509
1510Where to patch
Georg Brandlfb134382013-02-03 11:47:49 +01001511~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001512
Georg Brandl7ad3df62014-10-31 07:59:37 +01001513:func:`patch` works by (temporarily) changing the object that a *name* points to with
Michael Foorda9e6fb22012-03-28 14:36:02 +01001514another one. There can be many names pointing to any individual object, so
1515for patching to work you must ensure that you patch the name used by the system
1516under test.
1517
1518The basic principle is that you patch where an object is *looked up*, which
1519is not necessarily the same place as where it is defined. A couple of
1520examples will help to clarify this.
1521
1522Imagine we have a project that we want to test with the following structure::
1523
1524 a.py
1525 -> Defines SomeClass
1526
1527 b.py
1528 -> from a import SomeClass
1529 -> some_function instantiates SomeClass
1530
Georg Brandl7ad3df62014-10-31 07:59:37 +01001531Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
1532:func:`patch`. The problem is that when we import module b, which we will have to
1533do then it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
1534``a.SomeClass`` then it will have no effect on our test; module b already has a
1535reference to the *real* ``SomeClass`` and it looks like our patching had no
Michael Foorda9e6fb22012-03-28 14:36:02 +01001536effect.
1537
Georg Brandl7ad3df62014-10-31 07:59:37 +01001538The key is to patch out ``SomeClass`` where it is used (or where it is looked up
1539). In this case ``some_function`` will actually look up ``SomeClass`` in module b,
Michael Foorda9e6fb22012-03-28 14:36:02 +01001540where we have imported it. The patching should look like::
1541
1542 @patch('b.SomeClass')
1543
Georg Brandl7ad3df62014-10-31 07:59:37 +01001544However, consider the alternative scenario where instead of ``from a import
1545SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both
Michael Foorda9e6fb22012-03-28 14:36:02 +01001546of these import forms are common. In this case the class we want to patch is
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001547being looked up in the module and so we have to patch ``a.SomeClass`` instead::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001548
1549 @patch('a.SomeClass')
1550
1551
1552Patching Descriptors and Proxy Objects
Georg Brandlfb134382013-02-03 11:47:49 +01001553~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001554
1555Both patch_ and patch.object_ correctly patch and restore descriptors: class
1556methods, static methods and properties. You should patch these on the *class*
1557rather than an instance. They also work with *some* objects
Zachary Ware5ea5d2c2014-02-26 09:34:43 -06001558that proxy attribute access, like the `django settings object
Michael Foorda9e6fb22012-03-28 14:36:02 +01001559<http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
1560
1561
Michael Foord2309ed82012-03-28 15:38:36 +01001562MagicMock and magic method support
Georg Brandlfb134382013-02-03 11:47:49 +01001563----------------------------------
Michael Foord2309ed82012-03-28 15:38:36 +01001564
1565.. _magic-methods:
1566
1567Mocking Magic Methods
Georg Brandlfb134382013-02-03 11:47:49 +01001568~~~~~~~~~~~~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001569
1570:class:`Mock` supports mocking the Python protocol methods, also known as
1571"magic methods". This allows mock objects to replace containers or other
1572objects that implement Python protocols.
1573
1574Because magic methods are looked up differently from normal methods [#]_, this
1575support has been specially implemented. This means that only specific magic
1576methods are supported. The supported list includes *almost* all of them. If
1577there are any missing that you need please let us know.
1578
1579You mock magic methods by setting the method you are interested in to a function
1580or a mock instance. If you are using a function then it *must* take ``self`` as
1581the first argument [#]_.
1582
1583 >>> def __str__(self):
1584 ... return 'fooble'
1585 ...
1586 >>> mock = Mock()
1587 >>> mock.__str__ = __str__
1588 >>> str(mock)
1589 'fooble'
1590
1591 >>> mock = Mock()
1592 >>> mock.__str__ = Mock()
1593 >>> mock.__str__.return_value = 'fooble'
1594 >>> str(mock)
1595 'fooble'
1596
1597 >>> mock = Mock()
1598 >>> mock.__iter__ = Mock(return_value=iter([]))
1599 >>> list(mock)
1600 []
1601
1602One use case for this is for mocking objects used as context managers in a
Georg Brandl7ad3df62014-10-31 07:59:37 +01001603:keyword:`with` statement:
Michael Foord2309ed82012-03-28 15:38:36 +01001604
1605 >>> mock = Mock()
1606 >>> mock.__enter__ = Mock(return_value='foo')
1607 >>> mock.__exit__ = Mock(return_value=False)
1608 >>> with mock as m:
1609 ... assert m == 'foo'
1610 ...
1611 >>> mock.__enter__.assert_called_with()
1612 >>> mock.__exit__.assert_called_with(None, None, None)
1613
1614Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they
1615are recorded in :attr:`~Mock.mock_calls`.
1616
1617.. note::
1618
Georg Brandl7ad3df62014-10-31 07:59:37 +01001619 If you use the *spec* keyword argument to create a mock then attempting to
1620 set a magic method that isn't in the spec will raise an :exc:`AttributeError`.
Michael Foord2309ed82012-03-28 15:38:36 +01001621
1622The full list of supported magic methods is:
1623
1624* ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``
1625* ``__dir__``, ``__format__`` and ``__subclasses__``
1626* ``__floor__``, ``__trunc__`` and ``__ceil__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001627* Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001628 ``__eq__`` and ``__ne__``
1629* Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``,
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001630 ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__``
1631 and ``__missing__``
Michael Foord2309ed82012-03-28 15:38:36 +01001632* Context manager: ``__enter__`` and ``__exit__``
1633* Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``
1634* The numeric methods (including right hand and in-place variants):
Serhiy Storchakac2ccce72015-03-12 22:01:30 +02001635 ``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__div__``, ``__truediv__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001636 ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``,
1637 ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001638* Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__``
1639 and ``__index__``
Michael Foord2309ed82012-03-28 15:38:36 +01001640* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
1641* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
1642 ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
1643
1644
1645The following methods exist but are *not* supported as they are either in use
1646by mock, can't be set dynamically, or can cause problems:
1647
1648* ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``
1649* ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``
1650
1651
1652
1653Magic Mock
Georg Brandlfb134382013-02-03 11:47:49 +01001654~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001655
Georg Brandl7ad3df62014-10-31 07:59:37 +01001656There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001657
1658
1659.. class:: MagicMock(*args, **kw)
1660
1661 ``MagicMock`` is a subclass of :class:`Mock` with default implementations
1662 of most of the magic methods. You can use ``MagicMock`` without having to
1663 configure the magic methods yourself.
1664
1665 The constructor parameters have the same meaning as for :class:`Mock`.
1666
Georg Brandl7ad3df62014-10-31 07:59:37 +01001667 If you use the *spec* or *spec_set* arguments then *only* magic methods
Michael Foord2309ed82012-03-28 15:38:36 +01001668 that exist in the spec will be created.
1669
1670
1671.. class:: NonCallableMagicMock(*args, **kw)
1672
Georg Brandl7ad3df62014-10-31 07:59:37 +01001673 A non-callable version of :class:`MagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001674
1675 The constructor parameters have the same meaning as for
Georg Brandl7ad3df62014-10-31 07:59:37 +01001676 :class:`MagicMock`, with the exception of *return_value* and
1677 *side_effect* which have no meaning on a non-callable mock.
Michael Foord2309ed82012-03-28 15:38:36 +01001678
Georg Brandl7ad3df62014-10-31 07:59:37 +01001679The magic methods are setup with :class:`MagicMock` objects, so you can configure them
Michael Foord2309ed82012-03-28 15:38:36 +01001680and use them in the usual way:
1681
1682 >>> mock = MagicMock()
1683 >>> mock[3] = 'fish'
1684 >>> mock.__setitem__.assert_called_with(3, 'fish')
1685 >>> mock.__getitem__.return_value = 'result'
1686 >>> mock[2]
1687 'result'
1688
1689By default many of the protocol methods are required to return objects of a
1690specific type. These methods are preconfigured with a default return value, so
1691that they can be used without you having to do anything if you aren't interested
1692in the return value. You can still *set* the return value manually if you want
1693to change the default.
1694
1695Methods and their defaults:
1696
1697* ``__lt__``: NotImplemented
1698* ``__gt__``: NotImplemented
1699* ``__le__``: NotImplemented
1700* ``__ge__``: NotImplemented
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001701* ``__int__``: 1
1702* ``__contains__``: False
Berker Peksag8fafc742016-04-11 12:23:04 +03001703* ``__len__``: 0
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001704* ``__iter__``: iter([])
1705* ``__exit__``: False
1706* ``__complex__``: 1j
1707* ``__float__``: 1.0
1708* ``__bool__``: True
1709* ``__index__``: 1
1710* ``__hash__``: default hash for the mock
1711* ``__str__``: default str for the mock
Michael Foord2309ed82012-03-28 15:38:36 +01001712* ``__sizeof__``: default sizeof for the mock
1713
1714For example:
1715
1716 >>> mock = MagicMock()
1717 >>> int(mock)
1718 1
1719 >>> len(mock)
1720 0
1721 >>> list(mock)
1722 []
1723 >>> object() in mock
1724 False
1725
Berker Peksag283f1aa2015-01-07 21:15:02 +02001726The two equality methods, :meth:`__eq__` and :meth:`__ne__`, are special.
1727They do the default equality comparison on identity, using the
1728:attr:`~Mock.side_effect` attribute, unless you change their return value to
1729return something else::
Michael Foord2309ed82012-03-28 15:38:36 +01001730
1731 >>> MagicMock() == 3
1732 False
1733 >>> MagicMock() != 3
1734 True
1735 >>> mock = MagicMock()
1736 >>> mock.__eq__.return_value = True
1737 >>> mock == 3
1738 True
1739
Georg Brandl7ad3df62014-10-31 07:59:37 +01001740The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
Michael Foord2309ed82012-03-28 15:38:36 +01001741required to be an iterator:
1742
1743 >>> mock = MagicMock()
1744 >>> mock.__iter__.return_value = ['a', 'b', 'c']
1745 >>> list(mock)
1746 ['a', 'b', 'c']
1747 >>> list(mock)
1748 ['a', 'b', 'c']
1749
1750If the return value *is* an iterator, then iterating over it once will consume
1751it and subsequent iterations will result in an empty list:
1752
1753 >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
1754 >>> list(mock)
1755 ['a', 'b', 'c']
1756 >>> list(mock)
1757 []
1758
1759``MagicMock`` has all of the supported magic methods configured except for some
1760of the obscure and obsolete ones. You can still set these up if you want.
1761
1762Magic methods that are supported but not setup by default in ``MagicMock`` are:
1763
1764* ``__subclasses__``
1765* ``__dir__``
1766* ``__format__``
1767* ``__get__``, ``__set__`` and ``__delete__``
1768* ``__reversed__`` and ``__missing__``
1769* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
1770 ``__getstate__`` and ``__setstate__``
1771* ``__getformat__`` and ``__setformat__``
1772
1773
1774
1775.. [#] Magic methods *should* be looked up on the class rather than the
1776 instance. Different versions of Python are inconsistent about applying this
1777 rule. The supported protocol methods should work with all supported versions
1778 of Python.
1779.. [#] The function is basically hooked up to the class, but each ``Mock``
1780 instance is kept isolated from the others.
1781
1782
Michael Foorda9e6fb22012-03-28 14:36:02 +01001783Helpers
Georg Brandlfb134382013-02-03 11:47:49 +01001784-------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001785
1786sentinel
Georg Brandlfb134382013-02-03 11:47:49 +01001787~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001788
1789.. data:: sentinel
1790
1791 The ``sentinel`` object provides a convenient way of providing unique
1792 objects for your tests.
1793
1794 Attributes are created on demand when you access them by name. Accessing
1795 the same attribute will always return the same object. The objects
1796 returned have a sensible repr so that test failure messages are readable.
1797
1798Sometimes when testing you need to test that a specific object is passed as an
1799argument to another method, or returned. It can be common to create named
Georg Brandl7ad3df62014-10-31 07:59:37 +01001800sentinel objects to test this. :data:`sentinel` provides a convenient way of
Michael Foorda9e6fb22012-03-28 14:36:02 +01001801creating and testing the identity of objects like this.
1802
Georg Brandl7ad3df62014-10-31 07:59:37 +01001803In this example we monkey patch ``method`` to return ``sentinel.some_object``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001804
1805 >>> real = ProductionClass()
1806 >>> real.method = Mock(name="method")
1807 >>> real.method.return_value = sentinel.some_object
1808 >>> result = real.method()
1809 >>> assert result is sentinel.some_object
1810 >>> sentinel.some_object
1811 sentinel.some_object
1812
1813
1814DEFAULT
Georg Brandlfb134382013-02-03 11:47:49 +01001815~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001816
1817
1818.. data:: DEFAULT
1819
Georg Brandl7ad3df62014-10-31 07:59:37 +01001820 The :data:`DEFAULT` object is a pre-created sentinel (actually
1821 ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001822 functions to indicate that the normal return value should be used.
1823
1824
Michael Foorda9e6fb22012-03-28 14:36:02 +01001825call
Georg Brandlfb134382013-02-03 11:47:49 +01001826~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001827
1828.. function:: call(*args, **kwargs)
1829
Georg Brandl7ad3df62014-10-31 07:59:37 +01001830 :func:`call` is a helper object for making simpler assertions, for comparing with
Georg Brandl24891672012-04-01 13:48:26 +02001831 :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
Georg Brandl7ad3df62014-10-31 07:59:37 +01001832 :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be
Michael Foorda9e6fb22012-03-28 14:36:02 +01001833 used with :meth:`~Mock.assert_has_calls`.
1834
1835 >>> m = MagicMock(return_value=None)
1836 >>> m(1, 2, a='foo', b='bar')
1837 >>> m()
1838 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
1839 True
1840
1841.. method:: call.call_list()
1842
Georg Brandl7ad3df62014-10-31 07:59:37 +01001843 For a call object that represents multiple calls, :meth:`call_list`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001844 returns a list of all the intermediate calls as well as the
1845 final call.
1846
Georg Brandl7ad3df62014-10-31 07:59:37 +01001847``call_list`` is particularly useful for making assertions on "chained calls". A
Michael Foorda9e6fb22012-03-28 14:36:02 +01001848chained call is multiple calls on a single line of code. This results in
1849multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
1850the sequence of calls can be tedious.
1851
1852:meth:`~call.call_list` can construct the sequence of calls from the same
1853chained call:
1854
1855 >>> m = MagicMock()
1856 >>> m(1).method(arg='foo').other('bar')(2.0)
1857 <MagicMock name='mock().method().other()()' id='...'>
1858 >>> kall = call(1).method(arg='foo').other('bar')(2.0)
1859 >>> kall.call_list()
1860 [call(1),
1861 call().method(arg='foo'),
1862 call().method().other('bar'),
1863 call().method().other()(2.0)]
1864 >>> m.mock_calls == kall.call_list()
1865 True
1866
1867.. _calls-as-tuples:
1868
Georg Brandl7ad3df62014-10-31 07:59:37 +01001869A ``call`` object is either a tuple of (positional args, keyword args) or
Michael Foorda9e6fb22012-03-28 14:36:02 +01001870(name, positional args, keyword args) depending on how it was constructed. When
Georg Brandl7ad3df62014-10-31 07:59:37 +01001871you construct them yourself this isn't particularly interesting, but the ``call``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001872objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
1873:attr:`Mock.mock_calls` attributes can be introspected to get at the individual
1874arguments they contain.
1875
Georg Brandl7ad3df62014-10-31 07:59:37 +01001876The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
1877are two-tuples of (positional args, keyword args) whereas the ``call`` objects
Michael Foorda9e6fb22012-03-28 14:36:02 +01001878in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
1879three-tuples of (name, positional args, keyword args).
1880
1881You can use their "tupleness" to pull out the individual arguments for more
1882complex introspection and assertions. The positional arguments are a tuple
1883(an empty tuple if there are no positional arguments) and the keyword
1884arguments are a dictionary:
1885
1886 >>> m = MagicMock(return_value=None)
1887 >>> m(1, 2, 3, arg='one', arg2='two')
1888 >>> kall = m.call_args
1889 >>> args, kwargs = kall
1890 >>> args
1891 (1, 2, 3)
1892 >>> kwargs
1893 {'arg2': 'two', 'arg': 'one'}
1894 >>> args is kall[0]
1895 True
1896 >>> kwargs is kall[1]
1897 True
1898
1899 >>> m = MagicMock()
1900 >>> m.foo(4, 5, 6, arg='two', arg2='three')
1901 <MagicMock name='mock.foo()' id='...'>
1902 >>> kall = m.mock_calls[0]
1903 >>> name, args, kwargs = kall
1904 >>> name
1905 'foo'
1906 >>> args
1907 (4, 5, 6)
1908 >>> kwargs
1909 {'arg2': 'three', 'arg': 'two'}
1910 >>> name is m.mock_calls[0][0]
1911 True
1912
1913
1914create_autospec
Georg Brandlfb134382013-02-03 11:47:49 +01001915~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001916
1917.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
1918
1919 Create a mock object using another object as a spec. Attributes on the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001920 mock will use the corresponding attribute on the *spec* object as their
Michael Foorda9e6fb22012-03-28 14:36:02 +01001921 spec.
1922
1923 Functions or methods being mocked will have their arguments checked to
1924 ensure that they are called with the correct signature.
1925
Georg Brandl7ad3df62014-10-31 07:59:37 +01001926 If *spec_set* is ``True`` then attempting to set attributes that don't exist
1927 on the spec object will raise an :exc:`AttributeError`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001928
1929 If a class is used as a spec then the return value of the mock (the
1930 instance of the class) will have the same spec. You can use a class as the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001931 spec for an instance object by passing ``instance=True``. The returned mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001932 will only be callable if instances of the mock are callable.
1933
Georg Brandl7ad3df62014-10-31 07:59:37 +01001934 :func:`create_autospec` also takes arbitrary keyword arguments that are passed to
Michael Foorda9e6fb22012-03-28 14:36:02 +01001935 the constructor of the created mock.
1936
1937See :ref:`auto-speccing` for examples of how to use auto-speccing with
Georg Brandl7ad3df62014-10-31 07:59:37 +01001938:func:`create_autospec` and the *autospec* argument to :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001939
1940
1941ANY
Georg Brandlfb134382013-02-03 11:47:49 +01001942~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001943
1944.. data:: ANY
1945
1946Sometimes you may need to make assertions about *some* of the arguments in a
1947call to mock, but either not care about some of the arguments or want to pull
1948them individually out of :attr:`~Mock.call_args` and make more complex
1949assertions on them.
1950
1951To ignore certain arguments you can pass in objects that compare equal to
1952*everything*. Calls to :meth:`~Mock.assert_called_with` and
1953:meth:`~Mock.assert_called_once_with` will then succeed no matter what was
1954passed in.
1955
1956 >>> mock = Mock(return_value=None)
1957 >>> mock('foo', bar=object())
1958 >>> mock.assert_called_once_with('foo', bar=ANY)
1959
Georg Brandl7ad3df62014-10-31 07:59:37 +01001960:data:`ANY` can also be used in comparisons with call lists like
Michael Foorda9e6fb22012-03-28 14:36:02 +01001961:attr:`~Mock.mock_calls`:
1962
1963 >>> m = MagicMock(return_value=None)
1964 >>> m(1)
1965 >>> m(1, 2)
1966 >>> m(object())
1967 >>> m.mock_calls == [call(1), call(1, 2), ANY]
1968 True
1969
1970
1971
1972FILTER_DIR
Georg Brandlfb134382013-02-03 11:47:49 +01001973~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001974
1975.. data:: FILTER_DIR
1976
Georg Brandl7ad3df62014-10-31 07:59:37 +01001977:data:`FILTER_DIR` is a module level variable that controls the way mock objects
1978respond to :func:`dir` (only for Python 2.6 or more recent). The default is ``True``,
Michael Foorda9e6fb22012-03-28 14:36:02 +01001979which uses the filtering described below, to only show useful members. If you
1980dislike this filtering, or need to switch it off for diagnostic purposes, then
Georg Brandl7ad3df62014-10-31 07:59:37 +01001981set ``mock.FILTER_DIR = False``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001982
Georg Brandl7ad3df62014-10-31 07:59:37 +01001983With filtering on, ``dir(some_mock)`` shows only useful attributes and will
Michael Foorda9e6fb22012-03-28 14:36:02 +01001984include any dynamically created attributes that wouldn't normally be shown.
Georg Brandl7ad3df62014-10-31 07:59:37 +01001985If the mock was created with a *spec* (or *autospec* of course) then all the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001986attributes from the original are shown, even if they haven't been accessed
1987yet:
1988
1989 >>> dir(Mock())
1990 ['assert_any_call',
1991 'assert_called_once_with',
1992 'assert_called_with',
1993 'assert_has_calls',
1994 'attach_mock',
1995 ...
1996 >>> from urllib import request
1997 >>> dir(Mock(spec=request))
1998 ['AbstractBasicAuthHandler',
1999 'AbstractDigestAuthHandler',
2000 'AbstractHTTPHandler',
2001 'BaseHandler',
2002 ...
2003
Georg Brandl7ad3df62014-10-31 07:59:37 +01002004Many of the not-very-useful (private to :class:`Mock` rather than the thing being
Michael Foorda9e6fb22012-03-28 14:36:02 +01002005mocked) underscore and double underscore prefixed attributes have been
Georg Brandl7ad3df62014-10-31 07:59:37 +01002006filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this
Michael Foorda9e6fb22012-03-28 14:36:02 +01002007behaviour you can switch it off by setting the module level switch
Georg Brandl7ad3df62014-10-31 07:59:37 +01002008:data:`FILTER_DIR`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002009
2010 >>> from unittest import mock
2011 >>> mock.FILTER_DIR = False
2012 >>> dir(mock.Mock())
2013 ['_NonCallableMock__get_return_value',
2014 '_NonCallableMock__get_side_effect',
2015 '_NonCallableMock__return_value_doc',
2016 '_NonCallableMock__set_return_value',
2017 '_NonCallableMock__set_side_effect',
2018 '__call__',
2019 '__class__',
2020 ...
2021
Georg Brandl7ad3df62014-10-31 07:59:37 +01002022Alternatively you can just use ``vars(my_mock)`` (instance members) and
2023``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of
2024:data:`mock.FILTER_DIR`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002025
2026
2027mock_open
Georg Brandlfb134382013-02-03 11:47:49 +01002028~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002029
2030.. function:: mock_open(mock=None, read_data=None)
2031
Georg Brandl7ad3df62014-10-31 07:59:37 +01002032 A helper function to create a mock to replace the use of :func:`open`. It works
2033 for :func:`open` called directly or used as a context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002034
Georg Brandl7ad3df62014-10-31 07:59:37 +01002035 The *mock* argument is the mock object to configure. If ``None`` (the
2036 default) then a :class:`MagicMock` will be created for you, with the API limited
Michael Foorda9e6fb22012-03-28 14:36:02 +01002037 to methods or attributes available on standard file handles.
2038
Georg Brandl7ad3df62014-10-31 07:59:37 +01002039 *read_data* is a string for the :meth:`~io.IOBase.read`,
Serhiy Storchaka98b28fd2013-10-13 23:12:09 +03002040 :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods
Michael Foord04cbe0c2013-03-19 17:22:51 -07002041 of the file handle to return. Calls to those methods will take data from
Georg Brandl7ad3df62014-10-31 07:59:37 +01002042 *read_data* until it is depleted. The mock of these methods is pretty
Robert Collinsca647ef2015-07-24 03:48:20 +12002043 simplistic: every time the *mock* is called, the *read_data* is rewound to
2044 the start. If you need more control over the data that you are feeding to
2045 the tested code you will need to customize this mock for yourself. When that
2046 is insufficient, one of the in-memory filesystem packages on `PyPI
2047 <https://pypi.python.org/pypi>`_ can offer a realistic filesystem for testing.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002048
Robert Collinsf79dfe32015-07-24 04:09:59 +12002049 .. versionchanged:: 3.4
2050 Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support.
2051 The mock of :meth:`~io.IOBase.read` changed to consume *read_data* rather
2052 than returning it on each call.
2053
Robert Collins70398392015-07-24 04:10:27 +12002054 .. versionchanged:: 3.5
Robert Collinsf79dfe32015-07-24 04:09:59 +12002055 *read_data* is now reset on each call to the *mock*.
2056
Georg Brandl7ad3df62014-10-31 07:59:37 +01002057Using :func:`open` as a context manager is a great way to ensure your file handles
Michael Foorda9e6fb22012-03-28 14:36:02 +01002058are closed properly and is becoming common::
2059
2060 with open('/some/path', 'w') as f:
2061 f.write('something')
2062
Georg Brandl7ad3df62014-10-31 07:59:37 +01002063The issue is that even if you mock out the call to :func:`open` it is the
2064*returned object* that is used as a context manager (and has :meth:`__enter__` and
2065:meth:`__exit__` called).
Michael Foorda9e6fb22012-03-28 14:36:02 +01002066
2067Mocking context managers with a :class:`MagicMock` is common enough and fiddly
2068enough that a helper function is useful.
2069
2070 >>> m = mock_open()
Michael Foordfddcfa22014-04-14 16:25:20 -04002071 >>> with patch('__main__.open', m):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002072 ... with open('foo', 'w') as h:
2073 ... h.write('some stuff')
2074 ...
2075 >>> m.mock_calls
2076 [call('foo', 'w'),
2077 call().__enter__(),
2078 call().write('some stuff'),
2079 call().__exit__(None, None, None)]
2080 >>> m.assert_called_once_with('foo', 'w')
2081 >>> handle = m()
2082 >>> handle.write.assert_called_once_with('some stuff')
2083
2084And for reading files:
2085
Michael Foordfddcfa22014-04-14 16:25:20 -04002086 >>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002087 ... with open('foo') as h:
2088 ... result = h.read()
2089 ...
2090 >>> m.assert_called_once_with('foo')
2091 >>> assert result == 'bibble'
2092
2093
2094.. _auto-speccing:
2095
2096Autospeccing
Georg Brandlfb134382013-02-03 11:47:49 +01002097~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002098
Georg Brandl7ad3df62014-10-31 07:59:37 +01002099Autospeccing is based on the existing :attr:`spec` feature of mock. It limits the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002100api of mocks to the api of an original object (the spec), but it is recursive
2101(implemented lazily) so that attributes of mocks only have the same api as
2102the attributes of the spec. In addition mocked functions / methods have the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002103same call signature as the original so they raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002104called incorrectly.
2105
2106Before I explain how auto-speccing works, here's why it is needed.
2107
Georg Brandl7ad3df62014-10-31 07:59:37 +01002108:class:`Mock` is a very powerful and flexible object, but it suffers from two flaws
Michael Foorda9e6fb22012-03-28 14:36:02 +01002109when used to mock out objects from a system under test. One of these flaws is
Georg Brandl7ad3df62014-10-31 07:59:37 +01002110specific to the :class:`Mock` api and the other is a more general problem with using
Michael Foorda9e6fb22012-03-28 14:36:02 +01002111mock objects.
2112
Georg Brandl7ad3df62014-10-31 07:59:37 +01002113First the problem specific to :class:`Mock`. :class:`Mock` has two assert methods that are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002114extremely handy: :meth:`~Mock.assert_called_with` and
2115:meth:`~Mock.assert_called_once_with`.
2116
2117 >>> mock = Mock(name='Thing', return_value=None)
2118 >>> mock(1, 2, 3)
2119 >>> mock.assert_called_once_with(1, 2, 3)
2120 >>> mock(1, 2, 3)
2121 >>> mock.assert_called_once_with(1, 2, 3)
2122 Traceback (most recent call last):
2123 ...
Michael Foord28d591c2012-09-28 16:15:22 +01002124 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002125
2126Because mocks auto-create attributes on demand, and allow you to call them
2127with arbitrary arguments, if you misspell one of these assert methods then
2128your assertion is gone:
2129
2130.. code-block:: pycon
2131
2132 >>> mock = Mock(name='Thing', return_value=None)
2133 >>> mock(1, 2, 3)
2134 >>> mock.assret_called_once_with(4, 5, 6)
2135
2136Your tests can pass silently and incorrectly because of the typo.
2137
2138The second issue is more general to mocking. If you refactor some of your
2139code, rename members and so on, any tests for code that is still using the
2140*old api* but uses mocks instead of the real objects will still pass. This
2141means your tests can all pass even though your code is broken.
2142
2143Note that this is another reason why you need integration tests as well as
2144unit tests. Testing everything in isolation is all fine and dandy, but if you
2145don't test how your units are "wired together" there is still lots of room
2146for bugs that tests might have caught.
2147
Georg Brandl7ad3df62014-10-31 07:59:37 +01002148:mod:`mock` already provides a feature to help with this, called speccing. If you
2149use a class or instance as the :attr:`spec` for a mock then you can only access
Michael Foorda9e6fb22012-03-28 14:36:02 +01002150attributes on the mock that exist on the real class:
2151
2152 >>> from urllib import request
2153 >>> mock = Mock(spec=request.Request)
2154 >>> mock.assret_called_with
2155 Traceback (most recent call last):
2156 ...
2157 AttributeError: Mock object has no attribute 'assret_called_with'
2158
2159The spec only applies to the mock itself, so we still have the same issue
2160with any methods on the mock:
2161
2162.. code-block:: pycon
2163
2164 >>> mock.has_data()
2165 <mock.Mock object at 0x...>
2166 >>> mock.has_data.assret_called_with()
2167
Georg Brandl7ad3df62014-10-31 07:59:37 +01002168Auto-speccing solves this problem. You can either pass ``autospec=True`` to
2169:func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a
2170mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002171object that is being replaced will be used as the spec object. Because the
2172speccing is done "lazily" (the spec is created as attributes on the mock are
2173accessed) you can use it with very complex or deeply nested objects (like
2174modules that import modules that import modules) without a big performance
2175hit.
2176
2177Here's an example of it in use:
2178
2179 >>> from urllib import request
2180 >>> patcher = patch('__main__.request', autospec=True)
2181 >>> mock_request = patcher.start()
2182 >>> request is mock_request
2183 True
2184 >>> mock_request.Request
2185 <MagicMock name='request.Request' spec='Request' id='...'>
2186
Georg Brandl7ad3df62014-10-31 07:59:37 +01002187You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two
2188arguments in the constructor (one of which is *self*). Here's what happens if
Michael Foorda9e6fb22012-03-28 14:36:02 +01002189we try to call it incorrectly:
2190
2191 >>> req = request.Request()
2192 Traceback (most recent call last):
2193 ...
2194 TypeError: <lambda>() takes at least 2 arguments (1 given)
2195
2196The spec also applies to instantiated classes (i.e. the return value of
2197specced mocks):
2198
2199 >>> req = request.Request('foo')
2200 >>> req
2201 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
2202
Georg Brandl7ad3df62014-10-31 07:59:37 +01002203:class:`Request` objects are not callable, so the return value of instantiating our
2204mocked out :class:`request.Request` is a non-callable mock. With the spec in place
Michael Foorda9e6fb22012-03-28 14:36:02 +01002205any typos in our asserts will raise the correct error:
2206
2207 >>> req.add_header('spam', 'eggs')
2208 <MagicMock name='request.Request().add_header()' id='...'>
2209 >>> req.add_header.assret_called_with
2210 Traceback (most recent call last):
2211 ...
2212 AttributeError: Mock object has no attribute 'assret_called_with'
2213 >>> req.add_header.assert_called_with('spam', 'eggs')
2214
Georg Brandl7ad3df62014-10-31 07:59:37 +01002215In many cases you will just be able to add ``autospec=True`` to your existing
2216:func:`patch` calls and then be protected against bugs due to typos and api
Michael Foorda9e6fb22012-03-28 14:36:02 +01002217changes.
2218
Georg Brandl7ad3df62014-10-31 07:59:37 +01002219As well as using *autospec* through :func:`patch` there is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002220:func:`create_autospec` for creating autospecced mocks directly:
2221
2222 >>> from urllib import request
2223 >>> mock_request = create_autospec(request)
2224 >>> mock_request.Request('foo', 'bar')
2225 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
2226
2227This isn't without caveats and limitations however, which is why it is not
2228the default behaviour. In order to know what attributes are available on the
2229spec object, autospec has to introspect (access attributes) the spec. As you
2230traverse attributes on the mock a corresponding traversal of the original
2231object is happening under the hood. If any of your specced objects have
2232properties or descriptors that can trigger code execution then you may not be
2233able to use autospec. On the other hand it is much better to design your
2234objects so that introspection is safe [#]_.
2235
2236A more serious problem is that it is common for instance attributes to be
Georg Brandl7ad3df62014-10-31 07:59:37 +01002237created in the :meth:`__init__` method and not to exist on the class at all.
2238*autospec* can't know about any dynamically created attributes and restricts
Michael Foorda9e6fb22012-03-28 14:36:02 +01002239the api to visible attributes.
2240
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002241 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002242 ... def __init__(self):
2243 ... self.a = 33
2244 ...
2245 >>> with patch('__main__.Something', autospec=True):
2246 ... thing = Something()
2247 ... thing.a
2248 ...
2249 Traceback (most recent call last):
2250 ...
2251 AttributeError: Mock object has no attribute 'a'
2252
2253There are a few different ways of resolving this problem. The easiest, but
2254not necessarily the least annoying, way is to simply set the required
Georg Brandl7ad3df62014-10-31 07:59:37 +01002255attributes on the mock after creation. Just because *autospec* doesn't allow
Michael Foorda9e6fb22012-03-28 14:36:02 +01002256you to fetch attributes that don't exist on the spec it doesn't prevent you
2257setting them:
2258
2259 >>> with patch('__main__.Something', autospec=True):
2260 ... thing = Something()
2261 ... thing.a = 33
2262 ...
2263
Georg Brandl7ad3df62014-10-31 07:59:37 +01002264There is a more aggressive version of both *spec* and *autospec* that *does*
Michael Foorda9e6fb22012-03-28 14:36:02 +01002265prevent you setting non-existent attributes. This is useful if you want to
2266ensure your code only *sets* valid attributes too, but obviously it prevents
2267this particular scenario:
2268
2269 >>> with patch('__main__.Something', autospec=True, spec_set=True):
2270 ... thing = Something()
2271 ... thing.a = 33
2272 ...
2273 Traceback (most recent call last):
2274 ...
2275 AttributeError: Mock object has no attribute 'a'
2276
2277Probably the best way of solving the problem is to add class attributes as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002278default values for instance members initialised in :meth:`__init__`. Note that if
2279you are only setting default attributes in :meth:`__init__` then providing them via
Michael Foorda9e6fb22012-03-28 14:36:02 +01002280class attributes (shared between instances of course) is faster too. e.g.
2281
2282.. code-block:: python
2283
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002284 class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002285 a = 33
2286
2287This brings up another issue. It is relatively common to provide a default
Georg Brandl7ad3df62014-10-31 07:59:37 +01002288value of ``None`` for members that will later be an object of a different type.
2289``None`` would be useless as a spec because it wouldn't let you access *any*
2290attributes or methods on it. As ``None`` is *never* going to be useful as a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002291spec, and probably indicates a member that will normally of some other type,
Georg Brandl7ad3df62014-10-31 07:59:37 +01002292autospec doesn't use a spec for members that are set to ``None``. These will
2293just be ordinary mocks (well - MagicMocks):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002294
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002295 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002296 ... member = None
2297 ...
2298 >>> mock = create_autospec(Something)
2299 >>> mock.member.foo.bar.baz()
2300 <MagicMock name='mock.member.foo.bar.baz()' id='...'>
2301
2302If modifying your production classes to add defaults isn't to your liking
2303then there are more options. One of these is simply to use an instance as the
2304spec rather than the class. The other is to create a subclass of the
2305production class and add the defaults to the subclass without affecting the
2306production class. Both of these require you to use an alternative object as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002307the spec. Thankfully :func:`patch` supports this - you can simply pass the
2308alternative object as the *autospec* argument:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002309
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002310 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002311 ... def __init__(self):
2312 ... self.a = 33
2313 ...
2314 >>> class SomethingForTest(Something):
2315 ... a = 33
2316 ...
2317 >>> p = patch('__main__.Something', autospec=SomethingForTest)
2318 >>> mock = p.start()
2319 >>> mock.a
2320 <NonCallableMagicMock name='Something.a' spec='int' id='...'>
2321
2322
2323.. [#] This only applies to classes or already instantiated objects. Calling
2324 a mocked class to create a mock instance *does not* create a real instance.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002325 It is only attribute lookups - along with calls to :func:`dir` - that are done.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002326