blob: 929ceadbd7a9f3d35cde01e8a1439b7108fc55f1 [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.
7.. moduleauthor:: Michael Foord <michael@python.org>
8.. currentmodule:: unittest.mock
9
10.. versionadded:: 3.3
11
12:mod:`unittest.mock` is a library for testing in Python. It allows you to
13replace parts of your system under test with mock objects and make assertions
14about how they have been used.
15
Georg Brandl7ad3df62014-10-31 07:59:37 +010016:mod:`unittest.mock` provides a core :class:`Mock` class removing the need to
Michael Foord944e02d2012-03-25 23:12:55 +010017create a host of stubs throughout your test suite. After performing an
18action, you can make assertions about which methods / attributes were used
19and arguments they were called with. You can also specify return values and
20set needed attributes in the normal way.
21
22Additionally, mock provides a :func:`patch` decorator that handles patching
23module and class level attributes within the scope of a test, along with
24:const:`sentinel` for creating unique objects. See the `quick guide`_ for
25some examples of how to use :class:`Mock`, :class:`MagicMock` and
26:func:`patch`.
27
28Mock is very easy to use and is designed for use with :mod:`unittest`. Mock
Georg Brandl7ad3df62014-10-31 07:59:37 +010029is based on the 'action -> assertion' pattern instead of 'record -> replay'
Michael Foord944e02d2012-03-25 23:12:55 +010030used by many mocking frameworks.
31
Georg Brandl7ad3df62014-10-31 07:59:37 +010032There is a backport of :mod:`unittest.mock` for earlier versions of Python,
Georg Brandle73778c2014-10-29 08:36:35 +010033available as `mock on PyPI <https://pypi.python.org/pypi/mock>`_.
Michael Foord944e02d2012-03-25 23:12:55 +010034
35**Source code:** :source:`Lib/unittest/mock.py`
36
37
38Quick Guide
39-----------
40
41:class:`Mock` and :class:`MagicMock` objects create all attributes and
42methods as you access them and store details of how they have been used. You
43can configure them, to specify return values or limit what attributes are
44available, and then make assertions about how they have been used:
45
46 >>> from unittest.mock import MagicMock
47 >>> thing = ProductionClass()
48 >>> thing.method = MagicMock(return_value=3)
49 >>> thing.method(3, 4, 5, key='value')
50 3
51 >>> thing.method.assert_called_with(3, 4, 5, key='value')
52
53:attr:`side_effect` allows you to perform side effects, including raising an
54exception when a mock is called:
55
56 >>> mock = Mock(side_effect=KeyError('foo'))
57 >>> mock()
58 Traceback (most recent call last):
59 ...
60 KeyError: 'foo'
61
62 >>> values = {'a': 1, 'b': 2, 'c': 3}
63 >>> def side_effect(arg):
64 ... return values[arg]
65 ...
66 >>> mock.side_effect = side_effect
67 >>> mock('a'), mock('b'), mock('c')
68 (1, 2, 3)
69 >>> mock.side_effect = [5, 4, 3, 2, 1]
70 >>> mock(), mock(), mock()
71 (5, 4, 3)
72
73Mock has many other ways you can configure it and control its behaviour. For
Georg Brandl7ad3df62014-10-31 07:59:37 +010074example the *spec* argument configures the mock to take its specification
Michael Foord944e02d2012-03-25 23:12:55 +010075from another object. Attempting to access attributes or methods on the mock
Georg Brandl7ad3df62014-10-31 07:59:37 +010076that don't exist on the spec will fail with an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +010077
78The :func:`patch` decorator / context manager makes it easy to mock classes or
79objects in a module under test. The object you specify will be replaced with a
80mock (or other object) during the test and restored when the test ends:
81
82 >>> from unittest.mock import patch
83 >>> @patch('module.ClassName2')
84 ... @patch('module.ClassName1')
85 ... def test(MockClass1, MockClass2):
86 ... module.ClassName1()
87 ... module.ClassName2()
Michael Foord944e02d2012-03-25 23:12:55 +010088 ... assert MockClass1 is module.ClassName1
89 ... assert MockClass2 is module.ClassName2
90 ... assert MockClass1.called
91 ... assert MockClass2.called
92 ...
93 >>> test()
94
95.. note::
96
97 When you nest patch decorators the mocks are passed in to the decorated
98 function in the same order they applied (the normal *python* order that
99 decorators are applied). This means from the bottom up, so in the example
Georg Brandl7ad3df62014-10-31 07:59:37 +0100100 above the mock for ``module.ClassName1`` is passed in first.
Michael Foord944e02d2012-03-25 23:12:55 +0100101
Georg Brandl7ad3df62014-10-31 07:59:37 +0100102 With :func:`patch` it matters that you patch objects in the namespace where they
Michael Foord944e02d2012-03-25 23:12:55 +0100103 are looked up. This is normally straightforward, but for a quick guide
104 read :ref:`where to patch <where-to-patch>`.
105
Georg Brandl7ad3df62014-10-31 07:59:37 +0100106As well as a decorator :func:`patch` can be used as a context manager in a with
Michael Foord944e02d2012-03-25 23:12:55 +0100107statement:
108
109 >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
110 ... thing = ProductionClass()
111 ... thing.method(1, 2, 3)
112 ...
113 >>> mock_method.assert_called_once_with(1, 2, 3)
114
115
116There is also :func:`patch.dict` for setting values in a dictionary just
117during a scope and restoring the dictionary to its original state when the test
118ends:
119
120 >>> foo = {'key': 'value'}
121 >>> original = foo.copy()
122 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
123 ... assert foo == {'newkey': 'newvalue'}
124 ...
125 >>> assert foo == original
126
127Mock supports the mocking of Python :ref:`magic methods <magic-methods>`. The
128easiest way of using magic methods is with the :class:`MagicMock` class. It
129allows you to do things like:
130
131 >>> mock = MagicMock()
132 >>> mock.__str__.return_value = 'foobarbaz'
133 >>> str(mock)
134 'foobarbaz'
135 >>> mock.__str__.assert_called_with()
136
137Mock allows you to assign functions (or other Mock instances) to magic methods
Georg Brandl7ad3df62014-10-31 07:59:37 +0100138and they will be called appropriately. The :class:`MagicMock` class is just a Mock
Michael Foord944e02d2012-03-25 23:12:55 +0100139variant that has all of the magic methods pre-created for you (well, all the
140useful ones anyway).
141
142The following is an example of using magic methods with the ordinary Mock
143class:
144
145 >>> mock = Mock()
146 >>> mock.__str__ = Mock(return_value='wheeeeee')
147 >>> str(mock)
148 'wheeeeee'
149
150For ensuring that the mock objects in your tests have the same api as the
151objects they are replacing, you can use :ref:`auto-speccing <auto-speccing>`.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100152Auto-speccing can be done through the *autospec* argument to patch, or the
Michael Foord944e02d2012-03-25 23:12:55 +0100153:func:`create_autospec` function. Auto-speccing creates mock objects that
154have the same attributes and methods as the objects they are replacing, and
155any functions and methods (including constructors) have the same call
156signature as the real object.
157
158This ensures that your mocks will fail in the same way as your production
159code if they are used incorrectly:
160
161 >>> from unittest.mock import create_autospec
162 >>> def function(a, b, c):
163 ... pass
164 ...
165 >>> mock_function = create_autospec(function, return_value='fishy')
166 >>> mock_function(1, 2, 3)
167 'fishy'
168 >>> mock_function.assert_called_once_with(1, 2, 3)
169 >>> mock_function('wrong arguments')
170 Traceback (most recent call last):
171 ...
172 TypeError: <lambda>() takes exactly 3 arguments (1 given)
173
Georg Brandl7ad3df62014-10-31 07:59:37 +0100174:func:`create_autospec` can also be used on classes, where it copies the signature of
175the ``__init__`` method, and on callable objects where it copies the signature of
176the ``__call__`` method.
Michael Foord944e02d2012-03-25 23:12:55 +0100177
178
179
180The Mock Class
181--------------
182
183
Georg Brandl7ad3df62014-10-31 07:59:37 +0100184:class:`Mock` is a flexible mock object intended to replace the use of stubs and
Michael Foord944e02d2012-03-25 23:12:55 +0100185test doubles throughout your code. Mocks are callable and create attributes as
186new mocks when you access them [#]_. Accessing the same attribute will always
187return the same mock. Mocks record how you use them, allowing you to make
188assertions about what your code has done to them.
189
Georg Brandl7ad3df62014-10-31 07:59:37 +0100190:class:`MagicMock` is a subclass of :class:`Mock` with all the magic methods
Michael Foord944e02d2012-03-25 23:12:55 +0100191pre-created and ready to use. There are also non-callable variants, useful
192when you are mocking out objects that aren't callable:
193:class:`NonCallableMock` and :class:`NonCallableMagicMock`
194
195The :func:`patch` decorators makes it easy to temporarily replace classes
Georg Brandl7ad3df62014-10-31 07:59:37 +0100196in a particular module with a :class:`Mock` object. By default :func:`patch` will create
197a :class:`MagicMock` for you. You can specify an alternative class of :class:`Mock` using
198the *new_callable* argument to :func:`patch`.
Michael Foord944e02d2012-03-25 23:12:55 +0100199
200
Kushal Das8c145342014-04-16 23:32:21 +0530201.. 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 +0100202
Georg Brandl7ad3df62014-10-31 07:59:37 +0100203 Create a new :class:`Mock` object. :class:`Mock` takes several optional arguments
Michael Foord944e02d2012-03-25 23:12:55 +0100204 that specify the behaviour of the Mock object:
205
Georg Brandl7ad3df62014-10-31 07:59:37 +0100206 * *spec*: This can be either a list of strings or an existing object (a
Michael Foord944e02d2012-03-25 23:12:55 +0100207 class or instance) that acts as the specification for the mock object. If
208 you pass in an object then a list of strings is formed by calling dir on
209 the object (excluding unsupported magic attributes and methods).
Georg Brandl7ad3df62014-10-31 07:59:37 +0100210 Accessing any attribute not in this list will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100211
Georg Brandl7ad3df62014-10-31 07:59:37 +0100212 If *spec* is an object (rather than a list of strings) then
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300213 :attr:`~instance.__class__` returns the class of the spec object. This
Georg Brandl7ad3df62014-10-31 07:59:37 +0100214 allows mocks to pass :func:`isinstance` tests.
Michael Foord944e02d2012-03-25 23:12:55 +0100215
Georg Brandl7ad3df62014-10-31 07:59:37 +0100216 * *spec_set*: A stricter variant of *spec*. If used, attempting to *set*
Michael Foord944e02d2012-03-25 23:12:55 +0100217 or get an attribute on the mock that isn't on the object passed as
Georg Brandl7ad3df62014-10-31 07:59:37 +0100218 *spec_set* will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100219
Georg Brandl7ad3df62014-10-31 07:59:37 +0100220 * *side_effect*: A function to be called whenever the Mock is called. See
Michael Foord944e02d2012-03-25 23:12:55 +0100221 the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or
222 dynamically changing return values. The function is called with the same
223 arguments as the mock, and unless it returns :data:`DEFAULT`, the return
224 value of this function is used as the return value.
225
Georg Brandl7ad3df62014-10-31 07:59:37 +0100226 Alternatively *side_effect* can be an exception class or instance. In
Michael Foord944e02d2012-03-25 23:12:55 +0100227 this case the exception will be raised when the mock is called.
228
Georg Brandl7ad3df62014-10-31 07:59:37 +0100229 If *side_effect* is an iterable then each call to the mock will return
Michael Foord944e02d2012-03-25 23:12:55 +0100230 the next value from the iterable.
231
Georg Brandl7ad3df62014-10-31 07:59:37 +0100232 A *side_effect* can be cleared by setting it to ``None``.
Michael Foord944e02d2012-03-25 23:12:55 +0100233
Georg Brandl7ad3df62014-10-31 07:59:37 +0100234 * *return_value*: The value returned when the mock is called. By default
Michael Foord944e02d2012-03-25 23:12:55 +0100235 this is a new Mock (created on first access). See the
236 :attr:`return_value` attribute.
237
Georg Brandl7ad3df62014-10-31 07:59:37 +0100238 * *unsafe*: By default if any attribute starts with *assert* or
239 *assret* will raise an :exc:`AttributeError`. Passing ``unsafe=True``
240 will allow access to these attributes.
Kushal Das8c145342014-04-16 23:32:21 +0530241
242 .. versionadded:: 3.5
243
Georg Brandl7ad3df62014-10-31 07:59:37 +0100244 * *wraps*: Item for the mock object to wrap. If *wraps* is not None then
Michael Foord944e02d2012-03-25 23:12:55 +0100245 calling the Mock will pass the call through to the wrapped object
Michael Foord0682a0c2012-04-13 20:51:20 +0100246 (returning the real result). Attribute access on the mock will return a
247 Mock object that wraps the corresponding attribute of the wrapped
248 object (so attempting to access an attribute that doesn't exist will
Georg Brandl7ad3df62014-10-31 07:59:37 +0100249 raise an :exc:`AttributeError`).
Michael Foord944e02d2012-03-25 23:12:55 +0100250
Georg Brandl7ad3df62014-10-31 07:59:37 +0100251 If the mock has an explicit *return_value* set then calls are not passed
252 to the wrapped object and the *return_value* is returned instead.
Michael Foord944e02d2012-03-25 23:12:55 +0100253
Georg Brandl7ad3df62014-10-31 07:59:37 +0100254 * *name*: If the mock has a name then it will be used in the repr of the
Michael Foord944e02d2012-03-25 23:12:55 +0100255 mock. This can be useful for debugging. The name is propagated to child
256 mocks.
257
258 Mocks can also be called with arbitrary keyword arguments. These will be
259 used to set attributes on the mock after it is created. See the
260 :meth:`configure_mock` method for details.
261
262
263 .. method:: assert_called_with(*args, **kwargs)
264
265 This method is a convenient way of asserting that calls are made in a
266 particular way:
267
268 >>> mock = Mock()
269 >>> mock.method(1, 2, 3, test='wow')
270 <Mock name='mock.method()' id='...'>
271 >>> mock.method.assert_called_with(1, 2, 3, test='wow')
272
Michael Foord944e02d2012-03-25 23:12:55 +0100273 .. method:: assert_called_once_with(*args, **kwargs)
274
275 Assert that the mock was called exactly once and with the specified
276 arguments.
277
278 >>> mock = Mock(return_value=None)
279 >>> mock('foo', bar='baz')
280 >>> mock.assert_called_once_with('foo', bar='baz')
281 >>> mock('foo', bar='baz')
282 >>> mock.assert_called_once_with('foo', bar='baz')
283 Traceback (most recent call last):
284 ...
Michael Foord28d591c2012-09-28 16:15:22 +0100285 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foord944e02d2012-03-25 23:12:55 +0100286
287
288 .. method:: assert_any_call(*args, **kwargs)
289
290 assert the mock has been called with the specified arguments.
291
292 The assert passes if the mock has *ever* been called, unlike
293 :meth:`assert_called_with` and :meth:`assert_called_once_with` that
294 only pass if the call is the most recent one.
295
296 >>> mock = Mock(return_value=None)
297 >>> mock(1, 2, arg='thing')
298 >>> mock('some', 'thing', 'else')
299 >>> mock.assert_any_call(1, 2, arg='thing')
300
301
302 .. method:: assert_has_calls(calls, any_order=False)
303
304 assert the mock has been called with the specified calls.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100305 The :attr:`mock_calls` list is checked for the calls.
Michael Foord944e02d2012-03-25 23:12:55 +0100306
Georg Brandl7ad3df62014-10-31 07:59:37 +0100307 If *any_order* is false (the default) then the calls must be
Michael Foord944e02d2012-03-25 23:12:55 +0100308 sequential. There can be extra calls before or after the
309 specified calls.
310
Georg Brandl7ad3df62014-10-31 07:59:37 +0100311 If *any_order* is true then the calls can be in any order, but
Michael Foord944e02d2012-03-25 23:12:55 +0100312 they must all appear in :attr:`mock_calls`.
313
314 >>> mock = Mock(return_value=None)
315 >>> mock(1)
316 >>> mock(2)
317 >>> mock(3)
318 >>> mock(4)
319 >>> calls = [call(2), call(3)]
320 >>> mock.assert_has_calls(calls)
321 >>> calls = [call(4), call(2), call(3)]
322 >>> mock.assert_has_calls(calls, any_order=True)
323
Kushal Das8af9db32014-04-17 01:36:14 +0530324 .. method:: assert_not_called(*args, **kwargs)
325
326 Assert the mock was never called.
327
328 >>> m = Mock()
329 >>> m.hello.assert_not_called()
330 >>> obj = m.hello()
331 >>> m.hello.assert_not_called()
332 Traceback (most recent call last):
333 ...
334 AssertionError: Expected 'hello' to not have been called. Called 1 times.
335
336 .. versionadded:: 3.5
337
Michael Foord944e02d2012-03-25 23:12:55 +0100338
339 .. method:: reset_mock()
340
341 The reset_mock method resets all the call attributes on a mock object:
342
343 >>> mock = Mock(return_value=None)
344 >>> mock('hello')
345 >>> mock.called
346 True
347 >>> mock.reset_mock()
348 >>> mock.called
349 False
350
351 This can be useful where you want to make a series of assertions that
Georg Brandl7ad3df62014-10-31 07:59:37 +0100352 reuse the same object. Note that :meth:`reset_mock` *doesn't* clear the
Michael Foord944e02d2012-03-25 23:12:55 +0100353 return value, :attr:`side_effect` or any child attributes you have
354 set using normal assignment. Child mocks and the return value mock
355 (if any) are reset as well.
356
357
358 .. method:: mock_add_spec(spec, spec_set=False)
359
Georg Brandl7ad3df62014-10-31 07:59:37 +0100360 Add a spec to a mock. *spec* can either be an object or a
361 list of strings. Only attributes on the *spec* can be fetched as
Michael Foord944e02d2012-03-25 23:12:55 +0100362 attributes from the mock.
363
Georg Brandl7ad3df62014-10-31 07:59:37 +0100364 If *spec_set* is true then only attributes on the spec can be set.
Michael Foord944e02d2012-03-25 23:12:55 +0100365
366
367 .. method:: attach_mock(mock, attribute)
368
369 Attach a mock as an attribute of this one, replacing its name and
370 parent. Calls to the attached mock will be recorded in the
371 :attr:`method_calls` and :attr:`mock_calls` attributes of this one.
372
373
374 .. method:: configure_mock(**kwargs)
375
376 Set attributes on the mock through keyword arguments.
377
378 Attributes plus return values and side effects can be set on child
379 mocks using standard dot notation and unpacking a dictionary in the
380 method call:
381
382 >>> mock = Mock()
383 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
384 >>> mock.configure_mock(**attrs)
385 >>> mock.method()
386 3
387 >>> mock.other()
388 Traceback (most recent call last):
389 ...
390 KeyError
391
392 The same thing can be achieved in the constructor call to mocks:
393
394 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
395 >>> mock = Mock(some_attribute='eggs', **attrs)
396 >>> mock.some_attribute
397 'eggs'
398 >>> mock.method()
399 3
400 >>> mock.other()
401 Traceback (most recent call last):
402 ...
403 KeyError
404
Georg Brandl7ad3df62014-10-31 07:59:37 +0100405 :meth:`configure_mock` exists to make it easier to do configuration
Michael Foord944e02d2012-03-25 23:12:55 +0100406 after the mock has been created.
407
408
409 .. method:: __dir__()
410
Georg Brandl7ad3df62014-10-31 07:59:37 +0100411 :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results.
412 For mocks with a *spec* this includes all the permitted attributes
Michael Foord944e02d2012-03-25 23:12:55 +0100413 for the mock.
414
415 See :data:`FILTER_DIR` for what this filtering does, and how to
416 switch it off.
417
418
419 .. method:: _get_child_mock(**kw)
420
421 Create the child mocks for attributes and return value.
422 By default child mocks will be the same type as the parent.
423 Subclasses of Mock may want to override this to customize the way
424 child mocks are made.
425
426 For non-callable mocks the callable variant will be used (rather than
427 any custom subclass).
428
429
430 .. attribute:: called
431
432 A boolean representing whether or not the mock object has been called:
433
434 >>> mock = Mock(return_value=None)
435 >>> mock.called
436 False
437 >>> mock()
438 >>> mock.called
439 True
440
441 .. attribute:: call_count
442
443 An integer telling you how many times the mock object has been called:
444
445 >>> mock = Mock(return_value=None)
446 >>> mock.call_count
447 0
448 >>> mock()
449 >>> mock()
450 >>> mock.call_count
451 2
452
453
454 .. attribute:: return_value
455
456 Set this to configure the value returned by calling the mock:
457
458 >>> mock = Mock()
459 >>> mock.return_value = 'fish'
460 >>> mock()
461 'fish'
462
463 The default return value is a mock object and you can configure it in
464 the normal way:
465
466 >>> mock = Mock()
467 >>> mock.return_value.attribute = sentinel.Attribute
468 >>> mock.return_value()
469 <Mock name='mock()()' id='...'>
470 >>> mock.return_value.assert_called_with()
471
Georg Brandl7ad3df62014-10-31 07:59:37 +0100472 :attr:`return_value` can also be set in the constructor:
Michael Foord944e02d2012-03-25 23:12:55 +0100473
474 >>> mock = Mock(return_value=3)
475 >>> mock.return_value
476 3
477 >>> mock()
478 3
479
480
481 .. attribute:: side_effect
482
483 This can either be a function to be called when the mock is called,
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100484 an iterable or an exception (class or instance) to be raised.
Michael Foord944e02d2012-03-25 23:12:55 +0100485
486 If you pass in a function it will be called with same arguments as the
487 mock and unless the function returns the :data:`DEFAULT` singleton the
488 call to the mock will then return whatever the function returns. If the
489 function returns :data:`DEFAULT` then the mock will return its normal
Brett Cannon533f1ed2013-05-25 11:28:20 -0400490 value (from the :attr:`return_value`).
Michael Foord944e02d2012-03-25 23:12:55 +0100491
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100492 If you pass in an iterable, it is used to retrieve an iterator which
493 must yield a value on every call. This value can either be an exception
494 instance to be raised, or a value to be returned from the call to the
495 mock (:data:`DEFAULT` handling is identical to the function case).
496
Michael Foord944e02d2012-03-25 23:12:55 +0100497 An example of a mock that raises an exception (to test exception
498 handling of an API):
499
500 >>> mock = Mock()
501 >>> mock.side_effect = Exception('Boom!')
502 >>> mock()
503 Traceback (most recent call last):
504 ...
505 Exception: Boom!
506
Georg Brandl7ad3df62014-10-31 07:59:37 +0100507 Using :attr:`side_effect` to return a sequence of values:
Michael Foord944e02d2012-03-25 23:12:55 +0100508
509 >>> mock = Mock()
510 >>> mock.side_effect = [3, 2, 1]
511 >>> mock(), mock(), mock()
512 (3, 2, 1)
513
Georg Brandl8ed75cd2014-10-31 10:25:48 +0100514 Using a callable:
Michael Foord944e02d2012-03-25 23:12:55 +0100515
516 >>> mock = Mock(return_value=3)
517 >>> def side_effect(*args, **kwargs):
518 ... return DEFAULT
519 ...
520 >>> mock.side_effect = side_effect
521 >>> mock()
522 3
523
Georg Brandl7ad3df62014-10-31 07:59:37 +0100524 :attr:`side_effect` can be set in the constructor. Here's an example that
Michael Foord944e02d2012-03-25 23:12:55 +0100525 adds one to the value the mock is called with and returns it:
526
527 >>> side_effect = lambda value: value + 1
528 >>> mock = Mock(side_effect=side_effect)
529 >>> mock(3)
530 4
531 >>> mock(-8)
532 -7
533
Georg Brandl7ad3df62014-10-31 07:59:37 +0100534 Setting :attr:`side_effect` to ``None`` clears it:
Michael Foord944e02d2012-03-25 23:12:55 +0100535
536 >>> m = Mock(side_effect=KeyError, return_value=3)
537 >>> m()
538 Traceback (most recent call last):
539 ...
540 KeyError
541 >>> m.side_effect = None
542 >>> m()
543 3
544
545
546 .. attribute:: call_args
547
Georg Brandl7ad3df62014-10-31 07:59:37 +0100548 This is either ``None`` (if the mock hasn't been called), or the
Michael Foord944e02d2012-03-25 23:12:55 +0100549 arguments that the mock was last called with. This will be in the
550 form of a tuple: the first member is any ordered arguments the mock
551 was called with (or an empty tuple) and the second member is any
552 keyword arguments (or an empty dictionary).
553
554 >>> mock = Mock(return_value=None)
Berker Peksag920f6db2015-09-10 21:41:15 +0300555 >>> print(mock.call_args)
Michael Foord944e02d2012-03-25 23:12:55 +0100556 None
557 >>> mock()
558 >>> mock.call_args
559 call()
560 >>> mock.call_args == ()
561 True
562 >>> mock(3, 4)
563 >>> mock.call_args
564 call(3, 4)
565 >>> mock.call_args == ((3, 4),)
566 True
567 >>> mock(3, 4, 5, key='fish', next='w00t!')
568 >>> mock.call_args
569 call(3, 4, 5, key='fish', next='w00t!')
570
Georg Brandl7ad3df62014-10-31 07:59:37 +0100571 :attr:`call_args`, along with members of the lists :attr:`call_args_list`,
Michael Foord944e02d2012-03-25 23:12:55 +0100572 :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects.
573 These are tuples, so they can be unpacked to get at the individual
574 arguments and make more complex assertions. See
575 :ref:`calls as tuples <calls-as-tuples>`.
576
577
578 .. attribute:: call_args_list
579
580 This is a list of all the calls made to the mock object in sequence
581 (so the length of the list is the number of times it has been
582 called). Before any calls have been made it is an empty list. The
583 :data:`call` object can be used for conveniently constructing lists of
Georg Brandl7ad3df62014-10-31 07:59:37 +0100584 calls to compare with :attr:`call_args_list`.
Michael Foord944e02d2012-03-25 23:12:55 +0100585
586 >>> mock = Mock(return_value=None)
587 >>> mock()
588 >>> mock(3, 4)
589 >>> mock(key='fish', next='w00t!')
590 >>> mock.call_args_list
591 [call(), call(3, 4), call(key='fish', next='w00t!')]
592 >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)]
593 >>> mock.call_args_list == expected
594 True
595
Georg Brandl7ad3df62014-10-31 07:59:37 +0100596 Members of :attr:`call_args_list` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100597 unpacked as tuples to get at the individual arguments. See
598 :ref:`calls as tuples <calls-as-tuples>`.
599
600
601 .. attribute:: method_calls
602
603 As well as tracking calls to themselves, mocks also track calls to
604 methods and attributes, and *their* methods and attributes:
605
606 >>> mock = Mock()
607 >>> mock.method()
608 <Mock name='mock.method()' id='...'>
609 >>> mock.property.method.attribute()
610 <Mock name='mock.property.method.attribute()' id='...'>
611 >>> mock.method_calls
612 [call.method(), call.property.method.attribute()]
613
Georg Brandl7ad3df62014-10-31 07:59:37 +0100614 Members of :attr:`method_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100615 unpacked as tuples to get at the individual arguments. See
616 :ref:`calls as tuples <calls-as-tuples>`.
617
618
619 .. attribute:: mock_calls
620
Georg Brandl7ad3df62014-10-31 07:59:37 +0100621 :attr:`mock_calls` records *all* calls to the mock object, its methods,
622 magic methods *and* return value mocks.
Michael Foord944e02d2012-03-25 23:12:55 +0100623
624 >>> mock = MagicMock()
625 >>> result = mock(1, 2, 3)
626 >>> mock.first(a=3)
627 <MagicMock name='mock.first()' id='...'>
628 >>> mock.second()
629 <MagicMock name='mock.second()' id='...'>
630 >>> int(mock)
631 1
632 >>> result(1)
633 <MagicMock name='mock()()' id='...'>
634 >>> expected = [call(1, 2, 3), call.first(a=3), call.second(),
635 ... call.__int__(), call()(1)]
636 >>> mock.mock_calls == expected
637 True
638
Georg Brandl7ad3df62014-10-31 07:59:37 +0100639 Members of :attr:`mock_calls` are :data:`call` objects. These can be
Michael Foord944e02d2012-03-25 23:12:55 +0100640 unpacked as tuples to get at the individual arguments. See
641 :ref:`calls as tuples <calls-as-tuples>`.
642
643
644 .. attribute:: __class__
645
Georg Brandl7ad3df62014-10-31 07:59:37 +0100646 Normally the :attr:`__class__` attribute of an object will return its type.
647 For a mock object with a :attr:`spec`, ``__class__`` returns the spec class
648 instead. This allows mock objects to pass :func:`isinstance` tests for the
Michael Foord944e02d2012-03-25 23:12:55 +0100649 object they are replacing / masquerading as:
650
651 >>> mock = Mock(spec=3)
652 >>> isinstance(mock, int)
653 True
654
Georg Brandl7ad3df62014-10-31 07:59:37 +0100655 :attr:`__class__` is assignable to, this allows a mock to pass an
656 :func:`isinstance` check without forcing you to use a spec:
Michael Foord944e02d2012-03-25 23:12:55 +0100657
658 >>> mock = Mock()
659 >>> mock.__class__ = dict
660 >>> isinstance(mock, dict)
661 True
662
663.. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs)
664
Georg Brandl7ad3df62014-10-31 07:59:37 +0100665 A non-callable version of :class:`Mock`. The constructor parameters have the same
666 meaning of :class:`Mock`, with the exception of *return_value* and *side_effect*
Michael Foord944e02d2012-03-25 23:12:55 +0100667 which have no meaning on a non-callable mock.
668
Georg Brandl7ad3df62014-10-31 07:59:37 +0100669Mock objects that use a class or an instance as a :attr:`spec` or
670:attr:`spec_set` are able to pass :func:`isinstance` tests:
Michael Foord944e02d2012-03-25 23:12:55 +0100671
672 >>> mock = Mock(spec=SomeClass)
673 >>> isinstance(mock, SomeClass)
674 True
675 >>> mock = Mock(spec_set=SomeClass())
676 >>> isinstance(mock, SomeClass)
677 True
678
Georg Brandl7ad3df62014-10-31 07:59:37 +0100679The :class:`Mock` classes have support for mocking magic methods. See :ref:`magic
Michael Foord944e02d2012-03-25 23:12:55 +0100680methods <magic-methods>` for the full details.
681
682The mock classes and the :func:`patch` decorators all take arbitrary keyword
Georg Brandl7ad3df62014-10-31 07:59:37 +0100683arguments for configuration. For the :func:`patch` decorators the keywords are
Michael Foord944e02d2012-03-25 23:12:55 +0100684passed to the constructor of the mock being created. The keyword arguments
685are for configuring attributes of the mock:
686
687 >>> m = MagicMock(attribute=3, other='fish')
688 >>> m.attribute
689 3
690 >>> m.other
691 'fish'
692
693The return value and side effect of child mocks can be set in the same way,
694using dotted notation. As you can't use dotted names directly in a call you
Georg Brandl7ad3df62014-10-31 07:59:37 +0100695have to create a dictionary and unpack it using ``**``:
Michael Foord944e02d2012-03-25 23:12:55 +0100696
697 >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError}
698 >>> mock = Mock(some_attribute='eggs', **attrs)
699 >>> mock.some_attribute
700 'eggs'
701 >>> mock.method()
702 3
703 >>> mock.other()
704 Traceback (most recent call last):
705 ...
706 KeyError
707
Antoine Pitrou5c64df72013-02-03 00:23:58 +0100708A callable mock which was created with a *spec* (or a *spec_set*) will
709introspect the specification object's signature when matching calls to
710the mock. Therefore, it can match the actual call's arguments regardless
711of whether they were passed positionally or by name::
712
713 >>> def f(a, b, c): pass
714 ...
715 >>> mock = Mock(spec=f)
716 >>> mock(1, 2, c=3)
717 <Mock name='mock()' id='140161580456576'>
718 >>> mock.assert_called_with(1, 2, 3)
719 >>> mock.assert_called_with(a=1, b=2, c=3)
720
721This applies to :meth:`~Mock.assert_called_with`,
722:meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and
723:meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also
724apply to method calls on the mock object.
725
726 .. versionchanged:: 3.4
727 Added signature introspection on specced and autospecced mock objects.
728
Michael Foord944e02d2012-03-25 23:12:55 +0100729
730.. class:: PropertyMock(*args, **kwargs)
731
732 A mock intended to be used as a property, or other descriptor, on a class.
Georg Brandl7ad3df62014-10-31 07:59:37 +0100733 :class:`PropertyMock` provides :meth:`__get__` and :meth:`__set__` methods
734 so you can specify a return value when it is fetched.
Michael Foord944e02d2012-03-25 23:12:55 +0100735
Georg Brandl7ad3df62014-10-31 07:59:37 +0100736 Fetching a :class:`PropertyMock` instance from an object calls the mock, with
Michael Foord944e02d2012-03-25 23:12:55 +0100737 no args. Setting it calls the mock with the value being set.
738
Ezio Melottic9cfcf12013-03-11 09:42:40 +0200739 >>> class Foo:
Michael Foord944e02d2012-03-25 23:12:55 +0100740 ... @property
741 ... def foo(self):
742 ... return 'something'
743 ... @foo.setter
744 ... def foo(self, value):
745 ... pass
746 ...
747 >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo:
748 ... mock_foo.return_value = 'mockity-mock'
749 ... this_foo = Foo()
Berker Peksag920f6db2015-09-10 21:41:15 +0300750 ... print(this_foo.foo)
Michael Foord944e02d2012-03-25 23:12:55 +0100751 ... this_foo.foo = 6
752 ...
753 mockity-mock
754 >>> mock_foo.mock_calls
755 [call(), call(6)]
756
Michael Foordc2870622012-04-13 16:57:22 +0100757Because of the way mock attributes are stored you can't directly attach a
Georg Brandl7ad3df62014-10-31 07:59:37 +0100758:class:`PropertyMock` to a mock object. Instead you can attach it to the mock type
Michael Foordc2870622012-04-13 16:57:22 +0100759object::
760
761 >>> m = MagicMock()
762 >>> p = PropertyMock(return_value=3)
763 >>> type(m).foo = p
764 >>> m.foo
765 3
766 >>> p.assert_called_once_with()
767
Michael Foord944e02d2012-03-25 23:12:55 +0100768
769Calling
770~~~~~~~
771
772Mock objects are callable. The call will return the value set as the
773:attr:`~Mock.return_value` attribute. The default return value is a new Mock
774object; it is created the first time the return value is accessed (either
775explicitly or by calling the Mock) - but it is stored and the same one
776returned each time.
777
778Calls made to the object will be recorded in the attributes
779like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`.
780
781If :attr:`~Mock.side_effect` is set then it will be called after the call has
Georg Brandl7ad3df62014-10-31 07:59:37 +0100782been recorded, so if :attr:`side_effect` raises an exception the call is still
Michael Foord944e02d2012-03-25 23:12:55 +0100783recorded.
784
785The simplest way to make a mock raise an exception when called is to make
786:attr:`~Mock.side_effect` an exception class or instance:
787
788 >>> m = MagicMock(side_effect=IndexError)
789 >>> m(1, 2, 3)
790 Traceback (most recent call last):
791 ...
792 IndexError
793 >>> m.mock_calls
794 [call(1, 2, 3)]
795 >>> m.side_effect = KeyError('Bang!')
796 >>> m('two', 'three', 'four')
797 Traceback (most recent call last):
798 ...
799 KeyError: 'Bang!'
800 >>> m.mock_calls
801 [call(1, 2, 3), call('two', 'three', 'four')]
802
Georg Brandl7ad3df62014-10-31 07:59:37 +0100803If :attr:`side_effect` is a function then whatever that function returns is what
804calls to the mock return. The :attr:`side_effect` function is called with the
Michael Foord944e02d2012-03-25 23:12:55 +0100805same arguments as the mock. This allows you to vary the return value of the
806call dynamically, based on the input:
807
808 >>> def side_effect(value):
809 ... return value + 1
810 ...
811 >>> m = MagicMock(side_effect=side_effect)
812 >>> m(1)
813 2
814 >>> m(2)
815 3
816 >>> m.mock_calls
817 [call(1), call(2)]
818
819If you want the mock to still return the default return value (a new mock), or
820any set return value, then there are two ways of doing this. Either return
Georg Brandl7ad3df62014-10-31 07:59:37 +0100821:attr:`mock.return_value` from inside :attr:`side_effect`, or return :data:`DEFAULT`:
Michael Foord944e02d2012-03-25 23:12:55 +0100822
823 >>> m = MagicMock()
824 >>> def side_effect(*args, **kwargs):
825 ... return m.return_value
826 ...
827 >>> m.side_effect = side_effect
828 >>> m.return_value = 3
829 >>> m()
830 3
831 >>> def side_effect(*args, **kwargs):
832 ... return DEFAULT
833 ...
834 >>> m.side_effect = side_effect
835 >>> m()
836 3
837
Georg Brandl7ad3df62014-10-31 07:59:37 +0100838To remove a :attr:`side_effect`, and return to the default behaviour, set the
839:attr:`side_effect` to ``None``:
Michael Foord944e02d2012-03-25 23:12:55 +0100840
841 >>> m = MagicMock(return_value=6)
842 >>> def side_effect(*args, **kwargs):
843 ... return 3
844 ...
845 >>> m.side_effect = side_effect
846 >>> m()
847 3
848 >>> m.side_effect = None
849 >>> m()
850 6
851
Georg Brandl7ad3df62014-10-31 07:59:37 +0100852The :attr:`side_effect` can also be any iterable object. Repeated calls to the mock
Michael Foord944e02d2012-03-25 23:12:55 +0100853will return values from the iterable (until the iterable is exhausted and
Georg Brandl7ad3df62014-10-31 07:59:37 +0100854a :exc:`StopIteration` is raised):
Michael Foord944e02d2012-03-25 23:12:55 +0100855
856 >>> m = MagicMock(side_effect=[1, 2, 3])
857 >>> m()
858 1
859 >>> m()
860 2
861 >>> m()
862 3
863 >>> m()
864 Traceback (most recent call last):
865 ...
866 StopIteration
867
Michael Foord2cd48732012-04-21 15:52:11 +0100868If any members of the iterable are exceptions they will be raised instead of
869returned::
870
871 >>> iterable = (33, ValueError, 66)
872 >>> m = MagicMock(side_effect=iterable)
873 >>> m()
874 33
875 >>> m()
876 Traceback (most recent call last):
877 ...
878 ValueError
879 >>> m()
880 66
881
Michael Foord944e02d2012-03-25 23:12:55 +0100882
883.. _deleting-attributes:
884
885Deleting Attributes
886~~~~~~~~~~~~~~~~~~~
887
888Mock objects create attributes on demand. This allows them to pretend to be
889objects of any type.
890
Georg Brandl7ad3df62014-10-31 07:59:37 +0100891You may want a mock object to return ``False`` to a :func:`hasattr` call, or raise an
892:exc:`AttributeError` when an attribute is fetched. You can do this by providing
893an object as a :attr:`spec` for a mock, but that isn't always convenient.
Michael Foord944e02d2012-03-25 23:12:55 +0100894
895You "block" attributes by deleting them. Once deleted, accessing an attribute
Georg Brandl7ad3df62014-10-31 07:59:37 +0100896will raise an :exc:`AttributeError`.
Michael Foord944e02d2012-03-25 23:12:55 +0100897
898 >>> mock = MagicMock()
899 >>> hasattr(mock, 'm')
900 True
901 >>> del mock.m
902 >>> hasattr(mock, 'm')
903 False
904 >>> del mock.f
905 >>> mock.f
906 Traceback (most recent call last):
907 ...
908 AttributeError: f
909
910
Michael Foordf5752302013-03-18 15:04:03 -0700911Mock names and the name attribute
912~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
913
914Since "name" is an argument to the :class:`Mock` constructor, if you want your
915mock object to have a "name" attribute you can't just pass it in at creation
916time. There are two alternatives. One option is to use
917:meth:`~Mock.configure_mock`::
918
919 >>> mock = MagicMock()
920 >>> mock.configure_mock(name='my_name')
921 >>> mock.name
922 'my_name'
923
924A simpler option is to simply set the "name" attribute after mock creation::
925
926 >>> mock = MagicMock()
927 >>> mock.name = "foo"
928
929
Michael Foord944e02d2012-03-25 23:12:55 +0100930Attaching Mocks as Attributes
931~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
932
933When you attach a mock as an attribute of another mock (or as the return
934value) it becomes a "child" of that mock. Calls to the child are recorded in
935the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the
936parent. This is useful for configuring child mocks and then attaching them to
937the parent, or for attaching mocks to a parent that records all calls to the
938children and allows you to make assertions about the order of calls between
939mocks:
940
941 >>> parent = MagicMock()
942 >>> child1 = MagicMock(return_value=None)
943 >>> child2 = MagicMock(return_value=None)
944 >>> parent.child1 = child1
945 >>> parent.child2 = child2
946 >>> child1(1)
947 >>> child2(2)
948 >>> parent.mock_calls
949 [call.child1(1), call.child2(2)]
950
951The exception to this is if the mock has a name. This allows you to prevent
952the "parenting" if for some reason you don't want it to happen.
953
954 >>> mock = MagicMock()
955 >>> not_a_child = MagicMock(name='not-a-child')
956 >>> mock.attribute = not_a_child
957 >>> mock.attribute()
958 <MagicMock name='not-a-child()' id='...'>
959 >>> mock.mock_calls
960 []
961
962Mocks created for you by :func:`patch` are automatically given names. To
963attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock`
964method:
965
966 >>> thing1 = object()
967 >>> thing2 = object()
968 >>> parent = MagicMock()
969 >>> with patch('__main__.thing1', return_value=None) as child1:
970 ... with patch('__main__.thing2', return_value=None) as child2:
971 ... parent.attach_mock(child1, 'child1')
972 ... parent.attach_mock(child2, 'child2')
973 ... child1('one')
974 ... child2('two')
975 ...
976 >>> parent.mock_calls
977 [call.child1('one'), call.child2('two')]
978
979
980.. [#] The only exceptions are magic methods and attributes (those that have
981 leading and trailing double underscores). Mock doesn't create these but
Georg Brandl7ad3df62014-10-31 07:59:37 +0100982 instead raises an :exc:`AttributeError`. This is because the interpreter
Michael Foord944e02d2012-03-25 23:12:55 +0100983 will often implicitly request these methods, and gets *very* confused to
984 get a new Mock object when it expects a magic method. If you need magic
985 method support see :ref:`magic methods <magic-methods>`.
Michael Foorda9e6fb22012-03-28 14:36:02 +0100986
987
988The patchers
Georg Brandlfb134382013-02-03 11:47:49 +0100989------------
Michael Foorda9e6fb22012-03-28 14:36:02 +0100990
991The patch decorators are used for patching objects only within the scope of
992the function they decorate. They automatically handle the unpatching for you,
993even if exceptions are raised. All of these functions can also be used in with
994statements or as class decorators.
995
996
997patch
Georg Brandlfb134382013-02-03 11:47:49 +0100998~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +0100999
1000.. note::
1001
Georg Brandl7ad3df62014-10-31 07:59:37 +01001002 :func:`patch` is straightforward to use. The key is to do the patching in the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001003 right namespace. See the section `where to patch`_.
1004
1005.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1006
Georg Brandl7ad3df62014-10-31 07:59:37 +01001007 :func:`patch` acts as a function decorator, class decorator or a context
1008 manager. Inside the body of the function or with statement, the *target*
1009 is patched with a *new* object. When the function/with statement exits
Michael Foord54b3db82012-03-28 15:08:08 +01001010 the patch is undone.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001011
Georg Brandl7ad3df62014-10-31 07:59:37 +01001012 If *new* is omitted, then the target is replaced with a
1013 :class:`MagicMock`. If :func:`patch` is used as a decorator and *new* is
Michael Foord54b3db82012-03-28 15:08:08 +01001014 omitted, the created mock is passed in as an extra argument to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001015 decorated function. If :func:`patch` is used as a context manager the created
Michael Foord54b3db82012-03-28 15:08:08 +01001016 mock is returned by the context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001017
Georg Brandl7ad3df62014-10-31 07:59:37 +01001018 *target* should be a string in the form ``'package.module.ClassName'``. The
1019 *target* is imported and the specified object replaced with the *new*
1020 object, so the *target* must be importable from the environment you are
1021 calling :func:`patch` from. The target is imported when the decorated function
Michael Foord54b3db82012-03-28 15:08:08 +01001022 is executed, not at decoration time.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001023
Georg Brandl7ad3df62014-10-31 07:59:37 +01001024 The *spec* and *spec_set* keyword arguments are passed to the :class:`MagicMock`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001025 if patch is creating one for you.
1026
Georg Brandl7ad3df62014-10-31 07:59:37 +01001027 In addition you can pass ``spec=True`` or ``spec_set=True``, which causes
Michael Foorda9e6fb22012-03-28 14:36:02 +01001028 patch to pass in the object being mocked as the spec/spec_set object.
1029
Georg Brandl7ad3df62014-10-31 07:59:37 +01001030 *new_callable* allows you to specify a different class, or callable object,
1031 that will be called to create the *new* object. By default :class:`MagicMock` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001032 used.
1033
Georg Brandl7ad3df62014-10-31 07:59:37 +01001034 A more powerful form of *spec* is *autospec*. If you set ``autospec=True``
Georg Brandl8ed75cd2014-10-31 10:25:48 +01001035 then the mock will be created with a spec from the object being replaced.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001036 All attributes of the mock will also have the spec of the corresponding
1037 attribute of the object being replaced. Methods and functions being mocked
Georg Brandl7ad3df62014-10-31 07:59:37 +01001038 will have their arguments checked and will raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001039 called with the wrong signature. For mocks
1040 replacing a class, their return value (the 'instance') will have the same
1041 spec as the class. See the :func:`create_autospec` function and
1042 :ref:`auto-speccing`.
1043
Georg Brandl7ad3df62014-10-31 07:59:37 +01001044 Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001045 arbitrary object as the spec instead of the one being replaced.
1046
Georg Brandl7ad3df62014-10-31 07:59:37 +01001047 By default :func:`patch` will fail to replace attributes that don't exist. If
1048 you pass in ``create=True``, and the attribute doesn't exist, patch will
Michael Foorda9e6fb22012-03-28 14:36:02 +01001049 create the attribute for you when the patched function is called, and
1050 delete it again afterwards. This is useful for writing tests against
Terry Jan Reedy0f847642013-03-11 18:34:00 -04001051 attributes that your production code creates at runtime. It is off by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001052 default because it can be dangerous. With it switched on you can write
1053 passing tests against APIs that don't actually exist!
1054
Michael Foordfddcfa22014-04-14 16:25:20 -04001055 .. note::
1056
1057 .. versionchanged:: 3.5
1058 If you are patching builtins in a module then you don't
Georg Brandl7ad3df62014-10-31 07:59:37 +01001059 need to pass ``create=True``, it will be added by default.
Michael Foordfddcfa22014-04-14 16:25:20 -04001060
Georg Brandl7ad3df62014-10-31 07:59:37 +01001061 Patch can be used as a :class:`TestCase` class decorator. It works by
Michael Foorda9e6fb22012-03-28 14:36:02 +01001062 decorating each test method in the class. This reduces the boilerplate
Georg Brandl7ad3df62014-10-31 07:59:37 +01001063 code when your test methods share a common patchings set. :func:`patch` finds
1064 tests by looking for method names that start with ``patch.TEST_PREFIX``.
1065 By default this is ``'test'``, which matches the way :mod:`unittest` finds tests.
1066 You can specify an alternative prefix by setting ``patch.TEST_PREFIX``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001067
1068 Patch can be used as a context manager, with the with statement. Here the
1069 patching applies to the indented block after the with statement. If you
1070 use "as" then the patched object will be bound to the name after the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001071 "as"; very useful if :func:`patch` is creating a mock object for you.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001072
Georg Brandl7ad3df62014-10-31 07:59:37 +01001073 :func:`patch` takes arbitrary keyword arguments. These will be passed to
1074 the :class:`Mock` (or *new_callable*) on construction.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001075
Georg Brandl7ad3df62014-10-31 07:59:37 +01001076 ``patch.dict(...)``, ``patch.multiple(...)`` and ``patch.object(...)`` are
Michael Foorda9e6fb22012-03-28 14:36:02 +01001077 available for alternate use-cases.
1078
Georg Brandl7ad3df62014-10-31 07:59:37 +01001079:func:`patch` as function decorator, creating the mock for you and passing it into
Michael Foord90155362012-03-28 15:32:08 +01001080the decorated function:
1081
1082 >>> @patch('__main__.SomeClass')
Michael Foord324b58b2012-03-28 15:49:08 +01001083 ... def function(normal_argument, mock_class):
Michael Foord90155362012-03-28 15:32:08 +01001084 ... print(mock_class is SomeClass)
1085 ...
Michael Foord324b58b2012-03-28 15:49:08 +01001086 >>> function(None)
Michael Foord90155362012-03-28 15:32:08 +01001087 True
Michael Foorda9e6fb22012-03-28 14:36:02 +01001088
Georg Brandl7ad3df62014-10-31 07:59:37 +01001089Patching a class replaces the class with a :class:`MagicMock` *instance*. If the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001090class is instantiated in the code under test then it will be the
1091:attr:`~Mock.return_value` of the mock that will be used.
1092
1093If the class is instantiated multiple times you could use
1094:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
Georg Brandl7ad3df62014-10-31 07:59:37 +01001095can set the *return_value* to be anything you want.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001096
1097To configure return values on methods of *instances* on the patched class
Georg Brandl7ad3df62014-10-31 07:59:37 +01001098you must do this on the :attr:`return_value`. For example:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001099
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001100 >>> class Class:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001101 ... def method(self):
1102 ... pass
1103 ...
1104 >>> with patch('__main__.Class') as MockClass:
1105 ... instance = MockClass.return_value
1106 ... instance.method.return_value = 'foo'
1107 ... assert Class() is instance
1108 ... assert Class().method() == 'foo'
1109 ...
1110
Georg Brandl7ad3df62014-10-31 07:59:37 +01001111If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001112return value of the created mock will have the same spec.
1113
1114 >>> Original = Class
1115 >>> patcher = patch('__main__.Class', spec=True)
1116 >>> MockClass = patcher.start()
1117 >>> instance = MockClass()
1118 >>> assert isinstance(instance, Original)
1119 >>> patcher.stop()
1120
Georg Brandl7ad3df62014-10-31 07:59:37 +01001121The *new_callable* argument is useful where you want to use an alternative
Michael Foorda9e6fb22012-03-28 14:36:02 +01001122class to the default :class:`MagicMock` for the created mock. For example, if
1123you wanted a :class:`NonCallableMock` to be used:
1124
1125 >>> thing = object()
1126 >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
1127 ... assert thing is mock_thing
1128 ... thing()
1129 ...
1130 Traceback (most recent call last):
1131 ...
1132 TypeError: 'NonCallableMock' object is not callable
1133
Martin Panter7462b6492015-11-02 03:37:02 +00001134Another use case might be to replace an object with an :class:`io.StringIO` instance:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001135
Serhiy Storchakae79be872013-08-17 00:09:55 +03001136 >>> from io import StringIO
Michael Foorda9e6fb22012-03-28 14:36:02 +01001137 >>> def foo():
Berker Peksag920f6db2015-09-10 21:41:15 +03001138 ... print('Something')
Michael Foorda9e6fb22012-03-28 14:36:02 +01001139 ...
1140 >>> @patch('sys.stdout', new_callable=StringIO)
1141 ... def test(mock_stdout):
1142 ... foo()
1143 ... assert mock_stdout.getvalue() == 'Something\n'
1144 ...
1145 >>> test()
1146
Georg Brandl7ad3df62014-10-31 07:59:37 +01001147When :func:`patch` is creating a mock for you, it is common that the first thing
Michael Foorda9e6fb22012-03-28 14:36:02 +01001148you need to do is to configure the mock. Some of that configuration can be done
1149in the call to patch. Any arbitrary keywords you pass into the call will be
1150used to set attributes on the created mock:
1151
1152 >>> patcher = patch('__main__.thing', first='one', second='two')
1153 >>> mock_thing = patcher.start()
1154 >>> mock_thing.first
1155 'one'
1156 >>> mock_thing.second
1157 'two'
1158
1159As well as attributes on the created mock attributes, like the
1160:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
1161also be configured. These aren't syntactically valid to pass in directly as
1162keyword arguments, but a dictionary with these as keys can still be expanded
Georg Brandl7ad3df62014-10-31 07:59:37 +01001163into a :func:`patch` call using ``**``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001164
1165 >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
1166 >>> patcher = patch('__main__.thing', **config)
1167 >>> mock_thing = patcher.start()
1168 >>> mock_thing.method()
1169 3
1170 >>> mock_thing.other()
1171 Traceback (most recent call last):
1172 ...
1173 KeyError
1174
1175
1176patch.object
Georg Brandlfb134382013-02-03 11:47:49 +01001177~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001178
1179.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1180
Georg Brandl7ad3df62014-10-31 07:59:37 +01001181 patch the named member (*attribute*) on an object (*target*) with a mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001182 object.
1183
Georg Brandl7ad3df62014-10-31 07:59:37 +01001184 :func:`patch.object` can be used as a decorator, class decorator or a context
1185 manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* and
1186 *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`,
1187 :func:`patch.object` takes arbitrary keyword arguments for configuring the mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001188 object it creates.
1189
Georg Brandl7ad3df62014-10-31 07:59:37 +01001190 When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001191 for choosing which methods to wrap.
1192
Georg Brandl7ad3df62014-10-31 07:59:37 +01001193You can either call :func:`patch.object` with three arguments or two arguments. The
Michael Foorda9e6fb22012-03-28 14:36:02 +01001194three argument form takes the object to be patched, the attribute name and the
1195object to replace the attribute with.
1196
1197When calling with the two argument form you omit the replacement object, and a
1198mock is created for you and passed in as an extra argument to the decorated
1199function:
1200
1201 >>> @patch.object(SomeClass, 'class_method')
1202 ... def test(mock_method):
1203 ... SomeClass.class_method(3)
1204 ... mock_method.assert_called_with(3)
1205 ...
1206 >>> test()
1207
Georg Brandl7ad3df62014-10-31 07:59:37 +01001208*spec*, *create* and the other arguments to :func:`patch.object` have the same
1209meaning as they do for :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001210
1211
1212patch.dict
Georg Brandlfb134382013-02-03 11:47:49 +01001213~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001214
1215.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs)
1216
1217 Patch a dictionary, or dictionary like object, and restore the dictionary
1218 to its original state after the test.
1219
Georg Brandl7ad3df62014-10-31 07:59:37 +01001220 *in_dict* can be a dictionary or a mapping like container. If it is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01001221 mapping then it must at least support getting, setting and deleting items
1222 plus iterating over keys.
1223
Georg Brandl7ad3df62014-10-31 07:59:37 +01001224 *in_dict* can also be a string specifying the name of the dictionary, which
Michael Foorda9e6fb22012-03-28 14:36:02 +01001225 will then be fetched by importing it.
1226
Georg Brandl7ad3df62014-10-31 07:59:37 +01001227 *values* can be a dictionary of values to set in the dictionary. *values*
1228 can also be an iterable of ``(key, value)`` pairs.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001229
Georg Brandl7ad3df62014-10-31 07:59:37 +01001230 If *clear* is true then the dictionary will be cleared before the new
Michael Foorda9e6fb22012-03-28 14:36:02 +01001231 values are set.
1232
Georg Brandl7ad3df62014-10-31 07:59:37 +01001233 :func:`patch.dict` can also be called with arbitrary keyword arguments to set
Michael Foorda9e6fb22012-03-28 14:36:02 +01001234 values in the dictionary.
1235
Georg Brandl7ad3df62014-10-31 07:59:37 +01001236 :func:`patch.dict` can be used as a context manager, decorator or class
1237 decorator. When used as a class decorator :func:`patch.dict` honours
1238 ``patch.TEST_PREFIX`` for choosing which methods to wrap.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001239
Georg Brandl7ad3df62014-10-31 07:59:37 +01001240:func:`patch.dict` can be used to add members to a dictionary, or simply let a test
Michael Foorda9e6fb22012-03-28 14:36:02 +01001241change a dictionary, and ensure the dictionary is restored when the test
1242ends.
1243
1244 >>> foo = {}
1245 >>> with patch.dict(foo, {'newkey': 'newvalue'}):
1246 ... assert foo == {'newkey': 'newvalue'}
1247 ...
1248 >>> assert foo == {}
1249
1250 >>> import os
1251 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
Berker Peksag920f6db2015-09-10 21:41:15 +03001252 ... print(os.environ['newkey'])
Michael Foorda9e6fb22012-03-28 14:36:02 +01001253 ...
1254 newvalue
1255 >>> assert 'newkey' not in os.environ
1256
Georg Brandl7ad3df62014-10-31 07:59:37 +01001257Keywords can be used in the :func:`patch.dict` call to set values in the dictionary:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001258
1259 >>> mymodule = MagicMock()
1260 >>> mymodule.function.return_value = 'fish'
1261 >>> with patch.dict('sys.modules', mymodule=mymodule):
1262 ... import mymodule
1263 ... mymodule.function('some', 'args')
1264 ...
1265 'fish'
1266
Georg Brandl7ad3df62014-10-31 07:59:37 +01001267:func:`patch.dict` can be used with dictionary like objects that aren't actually
Michael Foorda9e6fb22012-03-28 14:36:02 +01001268dictionaries. At the very minimum they must support item getting, setting,
1269deleting and either iteration or membership test. This corresponds to the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001270magic methods :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__` and either
1271:meth:`__iter__` or :meth:`__contains__`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001272
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001273 >>> class Container:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001274 ... def __init__(self):
1275 ... self.values = {}
1276 ... def __getitem__(self, name):
1277 ... return self.values[name]
1278 ... def __setitem__(self, name, value):
1279 ... self.values[name] = value
1280 ... def __delitem__(self, name):
1281 ... del self.values[name]
1282 ... def __iter__(self):
1283 ... return iter(self.values)
1284 ...
1285 >>> thing = Container()
1286 >>> thing['one'] = 1
1287 >>> with patch.dict(thing, one=2, two=3):
1288 ... assert thing['one'] == 2
1289 ... assert thing['two'] == 3
1290 ...
1291 >>> assert thing['one'] == 1
1292 >>> assert list(thing) == ['one']
1293
1294
1295patch.multiple
Georg Brandlfb134382013-02-03 11:47:49 +01001296~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001297
1298.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
1299
1300 Perform multiple patches in a single call. It takes the object to be
1301 patched (either as an object or a string to fetch the object by importing)
1302 and keyword arguments for the patches::
1303
1304 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
1305 ...
1306
Georg Brandl7ad3df62014-10-31 07:59:37 +01001307 Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create
Michael Foorda9e6fb22012-03-28 14:36:02 +01001308 mocks for you. In this case the created mocks are passed into a decorated
Georg Brandl7ad3df62014-10-31 07:59:37 +01001309 function by keyword, and a dictionary is returned when :func:`patch.multiple` is
Michael Foorda9e6fb22012-03-28 14:36:02 +01001310 used as a context manager.
1311
Georg Brandl7ad3df62014-10-31 07:59:37 +01001312 :func:`patch.multiple` can be used as a decorator, class decorator or a context
1313 manager. The arguments *spec*, *spec_set*, *create*, *autospec* and
1314 *new_callable* have the same meaning as for :func:`patch`. These arguments will
1315 be applied to *all* patches done by :func:`patch.multiple`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001316
Georg Brandl7ad3df62014-10-31 07:59:37 +01001317 When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001318 for choosing which methods to wrap.
1319
Georg Brandl7ad3df62014-10-31 07:59:37 +01001320If you want :func:`patch.multiple` to create mocks for you, then you can use
1321:data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator
Michael Foorda9e6fb22012-03-28 14:36:02 +01001322then the created mocks are passed into the decorated function by keyword.
1323
1324 >>> thing = object()
1325 >>> other = object()
1326
1327 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1328 ... def test_function(thing, other):
1329 ... assert isinstance(thing, MagicMock)
1330 ... assert isinstance(other, MagicMock)
1331 ...
1332 >>> test_function()
1333
Georg Brandl7ad3df62014-10-31 07:59:37 +01001334:func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments
1335passed by keyword *after* any of the standard arguments created by :func:`patch`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001336
1337 >>> @patch('sys.exit')
1338 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
1339 ... def test_function(mock_exit, other, thing):
1340 ... assert 'other' in repr(other)
1341 ... assert 'thing' in repr(thing)
1342 ... assert 'exit' in repr(mock_exit)
1343 ...
1344 >>> test_function()
1345
Georg Brandl7ad3df62014-10-31 07:59:37 +01001346If :func:`patch.multiple` is used as a context manager, the value returned by the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001347context manger is a dictionary where created mocks are keyed by name:
1348
1349 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
1350 ... assert 'other' in repr(values['other'])
1351 ... assert 'thing' in repr(values['thing'])
1352 ... assert values['thing'] is thing
1353 ... assert values['other'] is other
1354 ...
1355
1356
1357.. _start-and-stop:
1358
1359patch methods: start and stop
Georg Brandlfb134382013-02-03 11:47:49 +01001360~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001361
Georg Brandl7ad3df62014-10-31 07:59:37 +01001362All the patchers have :meth:`start` and :meth:`stop` methods. These make it simpler to do
1363patching in ``setUp`` methods or where you want to do multiple patches without
Michael Foorda9e6fb22012-03-28 14:36:02 +01001364nesting decorators or with statements.
1365
Georg Brandl7ad3df62014-10-31 07:59:37 +01001366To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as
1367normal and keep a reference to the returned ``patcher`` object. You can then
1368call :meth:`start` to put the patch in place and :meth:`stop` to undo it.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001369
Georg Brandl7ad3df62014-10-31 07:59:37 +01001370If you are using :func:`patch` to create a mock for you then it will be returned by
1371the call to ``patcher.start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001372
1373 >>> patcher = patch('package.module.ClassName')
1374 >>> from package import module
1375 >>> original = module.ClassName
1376 >>> new_mock = patcher.start()
1377 >>> assert module.ClassName is not original
1378 >>> assert module.ClassName is new_mock
1379 >>> patcher.stop()
1380 >>> assert module.ClassName is original
1381 >>> assert module.ClassName is not new_mock
1382
1383
Georg Brandl7ad3df62014-10-31 07:59:37 +01001384A typical use case for this might be for doing multiple patches in the ``setUp``
1385method of a :class:`TestCase`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001386
1387 >>> class MyTest(TestCase):
1388 ... def setUp(self):
1389 ... self.patcher1 = patch('package.module.Class1')
1390 ... self.patcher2 = patch('package.module.Class2')
1391 ... self.MockClass1 = self.patcher1.start()
1392 ... self.MockClass2 = self.patcher2.start()
1393 ...
1394 ... def tearDown(self):
1395 ... self.patcher1.stop()
1396 ... self.patcher2.stop()
1397 ...
1398 ... def test_something(self):
1399 ... assert package.module.Class1 is self.MockClass1
1400 ... assert package.module.Class2 is self.MockClass2
1401 ...
1402 >>> MyTest('test_something').run()
1403
1404.. caution::
1405
1406 If you use this technique you must ensure that the patching is "undone" by
Georg Brandl7ad3df62014-10-31 07:59:37 +01001407 calling ``stop``. This can be fiddlier than you might think, because if an
Michael Foorda9e6fb22012-03-28 14:36:02 +01001408 exception is raised in the ``setUp`` then ``tearDown`` is not called.
1409 :meth:`unittest.TestCase.addCleanup` makes this easier:
1410
1411 >>> class MyTest(TestCase):
1412 ... def setUp(self):
1413 ... patcher = patch('package.module.Class')
1414 ... self.MockClass = patcher.start()
1415 ... self.addCleanup(patcher.stop)
1416 ...
1417 ... def test_something(self):
1418 ... assert package.module.Class is self.MockClass
1419 ...
1420
Georg Brandl7ad3df62014-10-31 07:59:37 +01001421 As an added bonus you no longer need to keep a reference to the ``patcher``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001422 object.
1423
Michael Foordf7c41582012-06-10 20:36:32 +01001424It is also possible to stop all patches which have been started by using
Georg Brandl7ad3df62014-10-31 07:59:37 +01001425:func:`patch.stopall`.
Michael Foordf7c41582012-06-10 20:36:32 +01001426
1427.. function:: patch.stopall
1428
Georg Brandl7ad3df62014-10-31 07:59:37 +01001429 Stop all active patches. Only stops patches started with ``start``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001430
Georg Brandl7ad3df62014-10-31 07:59:37 +01001431
1432.. _patch-builtins:
Michael Foordfddcfa22014-04-14 16:25:20 -04001433
1434patch builtins
Georg Brandl7ad3df62014-10-31 07:59:37 +01001435~~~~~~~~~~~~~~
Michael Foordfddcfa22014-04-14 16:25:20 -04001436You can patch any builtins within a module. The following example patches
Georg Brandl7ad3df62014-10-31 07:59:37 +01001437builtin :func:`ord`:
Michael Foordfddcfa22014-04-14 16:25:20 -04001438
1439 >>> @patch('__main__.ord')
1440 ... def test(mock_ord):
1441 ... mock_ord.return_value = 101
1442 ... print(ord('c'))
1443 ...
1444 >>> test()
1445 101
1446
Michael Foorda9e6fb22012-03-28 14:36:02 +01001447
1448TEST_PREFIX
Georg Brandlfb134382013-02-03 11:47:49 +01001449~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001450
1451All of the patchers can be used as class decorators. When used in this way
1452they wrap every test method on the class. The patchers recognise methods that
Georg Brandl7ad3df62014-10-31 07:59:37 +01001453start with ``'test'`` as being test methods. This is the same way that the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001454:class:`unittest.TestLoader` finds test methods by default.
1455
1456It is possible that you want to use a different prefix for your tests. You can
Georg Brandl7ad3df62014-10-31 07:59:37 +01001457inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001458
1459 >>> patch.TEST_PREFIX = 'foo'
1460 >>> value = 3
1461 >>>
1462 >>> @patch('__main__.value', 'not three')
Ezio Melottic9cfcf12013-03-11 09:42:40 +02001463 ... class Thing:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001464 ... def foo_one(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001465 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001466 ... def foo_two(self):
Berker Peksag920f6db2015-09-10 21:41:15 +03001467 ... print(value)
Michael Foorda9e6fb22012-03-28 14:36:02 +01001468 ...
1469 >>>
1470 >>> Thing().foo_one()
1471 not three
1472 >>> Thing().foo_two()
1473 not three
1474 >>> value
1475 3
1476
1477
1478Nesting Patch Decorators
Georg Brandlfb134382013-02-03 11:47:49 +01001479~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001480
1481If you want to perform multiple patches then you can simply stack up the
1482decorators.
1483
1484You can stack up multiple patch decorators using this pattern:
1485
1486 >>> @patch.object(SomeClass, 'class_method')
1487 ... @patch.object(SomeClass, 'static_method')
1488 ... def test(mock1, mock2):
1489 ... assert SomeClass.static_method is mock1
1490 ... assert SomeClass.class_method is mock2
1491 ... SomeClass.static_method('foo')
1492 ... SomeClass.class_method('bar')
1493 ... return mock1, mock2
1494 ...
1495 >>> mock1, mock2 = test()
1496 >>> mock1.assert_called_once_with('foo')
1497 >>> mock2.assert_called_once_with('bar')
1498
1499
1500Note that the decorators are applied from the bottom upwards. This is the
1501standard way that Python applies decorators. The order of the created mocks
1502passed into your test function matches this order.
1503
1504
1505.. _where-to-patch:
1506
1507Where to patch
Georg Brandlfb134382013-02-03 11:47:49 +01001508~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001509
Georg Brandl7ad3df62014-10-31 07:59:37 +01001510:func:`patch` works by (temporarily) changing the object that a *name* points to with
Michael Foorda9e6fb22012-03-28 14:36:02 +01001511another one. There can be many names pointing to any individual object, so
1512for patching to work you must ensure that you patch the name used by the system
1513under test.
1514
1515The basic principle is that you patch where an object is *looked up*, which
1516is not necessarily the same place as where it is defined. A couple of
1517examples will help to clarify this.
1518
1519Imagine we have a project that we want to test with the following structure::
1520
1521 a.py
1522 -> Defines SomeClass
1523
1524 b.py
1525 -> from a import SomeClass
1526 -> some_function instantiates SomeClass
1527
Georg Brandl7ad3df62014-10-31 07:59:37 +01001528Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using
1529:func:`patch`. The problem is that when we import module b, which we will have to
1530do then it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out
1531``a.SomeClass`` then it will have no effect on our test; module b already has a
1532reference to the *real* ``SomeClass`` and it looks like our patching had no
Michael Foorda9e6fb22012-03-28 14:36:02 +01001533effect.
1534
Georg Brandl7ad3df62014-10-31 07:59:37 +01001535The key is to patch out ``SomeClass`` where it is used (or where it is looked up
1536). In this case ``some_function`` will actually look up ``SomeClass`` in module b,
Michael Foorda9e6fb22012-03-28 14:36:02 +01001537where we have imported it. The patching should look like::
1538
1539 @patch('b.SomeClass')
1540
Georg Brandl7ad3df62014-10-31 07:59:37 +01001541However, consider the alternative scenario where instead of ``from a import
1542SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both
Michael Foorda9e6fb22012-03-28 14:36:02 +01001543of these import forms are common. In this case the class we want to patch is
Benjamin Peterson82f34ad2015-01-13 09:17:24 -05001544being looked up in the module and so we have to patch ``a.SomeClass`` instead::
Michael Foorda9e6fb22012-03-28 14:36:02 +01001545
1546 @patch('a.SomeClass')
1547
1548
1549Patching Descriptors and Proxy Objects
Georg Brandlfb134382013-02-03 11:47:49 +01001550~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001551
1552Both patch_ and patch.object_ correctly patch and restore descriptors: class
1553methods, static methods and properties. You should patch these on the *class*
1554rather than an instance. They also work with *some* objects
Zachary Ware5ea5d2c2014-02-26 09:34:43 -06001555that proxy attribute access, like the `django settings object
Michael Foorda9e6fb22012-03-28 14:36:02 +01001556<http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
1557
1558
Michael Foord2309ed82012-03-28 15:38:36 +01001559MagicMock and magic method support
Georg Brandlfb134382013-02-03 11:47:49 +01001560----------------------------------
Michael Foord2309ed82012-03-28 15:38:36 +01001561
1562.. _magic-methods:
1563
1564Mocking Magic Methods
Georg Brandlfb134382013-02-03 11:47:49 +01001565~~~~~~~~~~~~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001566
1567:class:`Mock` supports mocking the Python protocol methods, also known as
1568"magic methods". This allows mock objects to replace containers or other
1569objects that implement Python protocols.
1570
1571Because magic methods are looked up differently from normal methods [#]_, this
1572support has been specially implemented. This means that only specific magic
1573methods are supported. The supported list includes *almost* all of them. If
1574there are any missing that you need please let us know.
1575
1576You mock magic methods by setting the method you are interested in to a function
1577or a mock instance. If you are using a function then it *must* take ``self`` as
1578the first argument [#]_.
1579
1580 >>> def __str__(self):
1581 ... return 'fooble'
1582 ...
1583 >>> mock = Mock()
1584 >>> mock.__str__ = __str__
1585 >>> str(mock)
1586 'fooble'
1587
1588 >>> mock = Mock()
1589 >>> mock.__str__ = Mock()
1590 >>> mock.__str__.return_value = 'fooble'
1591 >>> str(mock)
1592 'fooble'
1593
1594 >>> mock = Mock()
1595 >>> mock.__iter__ = Mock(return_value=iter([]))
1596 >>> list(mock)
1597 []
1598
1599One use case for this is for mocking objects used as context managers in a
Georg Brandl7ad3df62014-10-31 07:59:37 +01001600:keyword:`with` statement:
Michael Foord2309ed82012-03-28 15:38:36 +01001601
1602 >>> mock = Mock()
1603 >>> mock.__enter__ = Mock(return_value='foo')
1604 >>> mock.__exit__ = Mock(return_value=False)
1605 >>> with mock as m:
1606 ... assert m == 'foo'
1607 ...
1608 >>> mock.__enter__.assert_called_with()
1609 >>> mock.__exit__.assert_called_with(None, None, None)
1610
1611Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they
1612are recorded in :attr:`~Mock.mock_calls`.
1613
1614.. note::
1615
Georg Brandl7ad3df62014-10-31 07:59:37 +01001616 If you use the *spec* keyword argument to create a mock then attempting to
1617 set a magic method that isn't in the spec will raise an :exc:`AttributeError`.
Michael Foord2309ed82012-03-28 15:38:36 +01001618
1619The full list of supported magic methods is:
1620
1621* ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__``
1622* ``__dir__``, ``__format__`` and ``__subclasses__``
1623* ``__floor__``, ``__trunc__`` and ``__ceil__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001624* Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001625 ``__eq__`` and ``__ne__``
1626* Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``,
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001627 ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__``
1628 and ``__missing__``
Michael Foord2309ed82012-03-28 15:38:36 +01001629* Context manager: ``__enter__`` and ``__exit__``
1630* Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__``
1631* The numeric methods (including right hand and in-place variants):
Serhiy Storchakac2ccce72015-03-12 22:01:30 +02001632 ``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__div__``, ``__truediv__``,
Michael Foord2309ed82012-03-28 15:38:36 +01001633 ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``,
1634 ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__``
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02001635* Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__``
1636 and ``__index__``
Michael Foord2309ed82012-03-28 15:38:36 +01001637* Descriptor methods: ``__get__``, ``__set__`` and ``__delete__``
1638* Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``,
1639 ``__getnewargs__``, ``__getstate__`` and ``__setstate__``
1640
1641
1642The following methods exist but are *not* supported as they are either in use
1643by mock, can't be set dynamically, or can cause problems:
1644
1645* ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__``
1646* ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__``
1647
1648
1649
1650Magic Mock
Georg Brandlfb134382013-02-03 11:47:49 +01001651~~~~~~~~~~
Michael Foord2309ed82012-03-28 15:38:36 +01001652
Georg Brandl7ad3df62014-10-31 07:59:37 +01001653There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001654
1655
1656.. class:: MagicMock(*args, **kw)
1657
1658 ``MagicMock`` is a subclass of :class:`Mock` with default implementations
1659 of most of the magic methods. You can use ``MagicMock`` without having to
1660 configure the magic methods yourself.
1661
1662 The constructor parameters have the same meaning as for :class:`Mock`.
1663
Georg Brandl7ad3df62014-10-31 07:59:37 +01001664 If you use the *spec* or *spec_set* arguments then *only* magic methods
Michael Foord2309ed82012-03-28 15:38:36 +01001665 that exist in the spec will be created.
1666
1667
1668.. class:: NonCallableMagicMock(*args, **kw)
1669
Georg Brandl7ad3df62014-10-31 07:59:37 +01001670 A non-callable version of :class:`MagicMock`.
Michael Foord2309ed82012-03-28 15:38:36 +01001671
1672 The constructor parameters have the same meaning as for
Georg Brandl7ad3df62014-10-31 07:59:37 +01001673 :class:`MagicMock`, with the exception of *return_value* and
1674 *side_effect* which have no meaning on a non-callable mock.
Michael Foord2309ed82012-03-28 15:38:36 +01001675
Georg Brandl7ad3df62014-10-31 07:59:37 +01001676The magic methods are setup with :class:`MagicMock` objects, so you can configure them
Michael Foord2309ed82012-03-28 15:38:36 +01001677and use them in the usual way:
1678
1679 >>> mock = MagicMock()
1680 >>> mock[3] = 'fish'
1681 >>> mock.__setitem__.assert_called_with(3, 'fish')
1682 >>> mock.__getitem__.return_value = 'result'
1683 >>> mock[2]
1684 'result'
1685
1686By default many of the protocol methods are required to return objects of a
1687specific type. These methods are preconfigured with a default return value, so
1688that they can be used without you having to do anything if you aren't interested
1689in the return value. You can still *set* the return value manually if you want
1690to change the default.
1691
1692Methods and their defaults:
1693
1694* ``__lt__``: NotImplemented
1695* ``__gt__``: NotImplemented
1696* ``__le__``: NotImplemented
1697* ``__ge__``: NotImplemented
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001698* ``__int__``: 1
1699* ``__contains__``: False
Berker Peksag8fafc742016-04-11 12:23:04 +03001700* ``__len__``: 0
Serhiy Storchakaf47036c2013-12-24 11:04:36 +02001701* ``__iter__``: iter([])
1702* ``__exit__``: False
1703* ``__complex__``: 1j
1704* ``__float__``: 1.0
1705* ``__bool__``: True
1706* ``__index__``: 1
1707* ``__hash__``: default hash for the mock
1708* ``__str__``: default str for the mock
Michael Foord2309ed82012-03-28 15:38:36 +01001709* ``__sizeof__``: default sizeof for the mock
1710
1711For example:
1712
1713 >>> mock = MagicMock()
1714 >>> int(mock)
1715 1
1716 >>> len(mock)
1717 0
1718 >>> list(mock)
1719 []
1720 >>> object() in mock
1721 False
1722
Berker Peksag283f1aa2015-01-07 21:15:02 +02001723The two equality methods, :meth:`__eq__` and :meth:`__ne__`, are special.
1724They do the default equality comparison on identity, using the
1725:attr:`~Mock.side_effect` attribute, unless you change their return value to
1726return something else::
Michael Foord2309ed82012-03-28 15:38:36 +01001727
1728 >>> MagicMock() == 3
1729 False
1730 >>> MagicMock() != 3
1731 True
1732 >>> mock = MagicMock()
1733 >>> mock.__eq__.return_value = True
1734 >>> mock == 3
1735 True
1736
Georg Brandl7ad3df62014-10-31 07:59:37 +01001737The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't
Michael Foord2309ed82012-03-28 15:38:36 +01001738required to be an iterator:
1739
1740 >>> mock = MagicMock()
1741 >>> mock.__iter__.return_value = ['a', 'b', 'c']
1742 >>> list(mock)
1743 ['a', 'b', 'c']
1744 >>> list(mock)
1745 ['a', 'b', 'c']
1746
1747If the return value *is* an iterator, then iterating over it once will consume
1748it and subsequent iterations will result in an empty list:
1749
1750 >>> mock.__iter__.return_value = iter(['a', 'b', 'c'])
1751 >>> list(mock)
1752 ['a', 'b', 'c']
1753 >>> list(mock)
1754 []
1755
1756``MagicMock`` has all of the supported magic methods configured except for some
1757of the obscure and obsolete ones. You can still set these up if you want.
1758
1759Magic methods that are supported but not setup by default in ``MagicMock`` are:
1760
1761* ``__subclasses__``
1762* ``__dir__``
1763* ``__format__``
1764* ``__get__``, ``__set__`` and ``__delete__``
1765* ``__reversed__`` and ``__missing__``
1766* ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``,
1767 ``__getstate__`` and ``__setstate__``
1768* ``__getformat__`` and ``__setformat__``
1769
1770
1771
1772.. [#] Magic methods *should* be looked up on the class rather than the
1773 instance. Different versions of Python are inconsistent about applying this
1774 rule. The supported protocol methods should work with all supported versions
1775 of Python.
1776.. [#] The function is basically hooked up to the class, but each ``Mock``
1777 instance is kept isolated from the others.
1778
1779
Michael Foorda9e6fb22012-03-28 14:36:02 +01001780Helpers
Georg Brandlfb134382013-02-03 11:47:49 +01001781-------
Michael Foorda9e6fb22012-03-28 14:36:02 +01001782
1783sentinel
Georg Brandlfb134382013-02-03 11:47:49 +01001784~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001785
1786.. data:: sentinel
1787
1788 The ``sentinel`` object provides a convenient way of providing unique
1789 objects for your tests.
1790
1791 Attributes are created on demand when you access them by name. Accessing
1792 the same attribute will always return the same object. The objects
1793 returned have a sensible repr so that test failure messages are readable.
1794
1795Sometimes when testing you need to test that a specific object is passed as an
1796argument to another method, or returned. It can be common to create named
Georg Brandl7ad3df62014-10-31 07:59:37 +01001797sentinel objects to test this. :data:`sentinel` provides a convenient way of
Michael Foorda9e6fb22012-03-28 14:36:02 +01001798creating and testing the identity of objects like this.
1799
Georg Brandl7ad3df62014-10-31 07:59:37 +01001800In this example we monkey patch ``method`` to return ``sentinel.some_object``:
Michael Foorda9e6fb22012-03-28 14:36:02 +01001801
1802 >>> real = ProductionClass()
1803 >>> real.method = Mock(name="method")
1804 >>> real.method.return_value = sentinel.some_object
1805 >>> result = real.method()
1806 >>> assert result is sentinel.some_object
1807 >>> sentinel.some_object
1808 sentinel.some_object
1809
1810
1811DEFAULT
Georg Brandlfb134382013-02-03 11:47:49 +01001812~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001813
1814
1815.. data:: DEFAULT
1816
Georg Brandl7ad3df62014-10-31 07:59:37 +01001817 The :data:`DEFAULT` object is a pre-created sentinel (actually
1818 ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001819 functions to indicate that the normal return value should be used.
1820
1821
Michael Foorda9e6fb22012-03-28 14:36:02 +01001822call
Georg Brandlfb134382013-02-03 11:47:49 +01001823~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001824
1825.. function:: call(*args, **kwargs)
1826
Georg Brandl7ad3df62014-10-31 07:59:37 +01001827 :func:`call` is a helper object for making simpler assertions, for comparing with
Georg Brandl24891672012-04-01 13:48:26 +02001828 :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`,
Georg Brandl7ad3df62014-10-31 07:59:37 +01001829 :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be
Michael Foorda9e6fb22012-03-28 14:36:02 +01001830 used with :meth:`~Mock.assert_has_calls`.
1831
1832 >>> m = MagicMock(return_value=None)
1833 >>> m(1, 2, a='foo', b='bar')
1834 >>> m()
1835 >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()]
1836 True
1837
1838.. method:: call.call_list()
1839
Georg Brandl7ad3df62014-10-31 07:59:37 +01001840 For a call object that represents multiple calls, :meth:`call_list`
Michael Foorda9e6fb22012-03-28 14:36:02 +01001841 returns a list of all the intermediate calls as well as the
1842 final call.
1843
Georg Brandl7ad3df62014-10-31 07:59:37 +01001844``call_list`` is particularly useful for making assertions on "chained calls". A
Michael Foorda9e6fb22012-03-28 14:36:02 +01001845chained call is multiple calls on a single line of code. This results in
1846multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing
1847the sequence of calls can be tedious.
1848
1849:meth:`~call.call_list` can construct the sequence of calls from the same
1850chained call:
1851
1852 >>> m = MagicMock()
1853 >>> m(1).method(arg='foo').other('bar')(2.0)
1854 <MagicMock name='mock().method().other()()' id='...'>
1855 >>> kall = call(1).method(arg='foo').other('bar')(2.0)
1856 >>> kall.call_list()
1857 [call(1),
1858 call().method(arg='foo'),
1859 call().method().other('bar'),
1860 call().method().other()(2.0)]
1861 >>> m.mock_calls == kall.call_list()
1862 True
1863
1864.. _calls-as-tuples:
1865
Georg Brandl7ad3df62014-10-31 07:59:37 +01001866A ``call`` object is either a tuple of (positional args, keyword args) or
Michael Foorda9e6fb22012-03-28 14:36:02 +01001867(name, positional args, keyword args) depending on how it was constructed. When
Georg Brandl7ad3df62014-10-31 07:59:37 +01001868you construct them yourself this isn't particularly interesting, but the ``call``
Michael Foorda9e6fb22012-03-28 14:36:02 +01001869objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and
1870:attr:`Mock.mock_calls` attributes can be introspected to get at the individual
1871arguments they contain.
1872
Georg Brandl7ad3df62014-10-31 07:59:37 +01001873The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list`
1874are two-tuples of (positional args, keyword args) whereas the ``call`` objects
Michael Foorda9e6fb22012-03-28 14:36:02 +01001875in :attr:`Mock.mock_calls`, along with ones you construct yourself, are
1876three-tuples of (name, positional args, keyword args).
1877
1878You can use their "tupleness" to pull out the individual arguments for more
1879complex introspection and assertions. The positional arguments are a tuple
1880(an empty tuple if there are no positional arguments) and the keyword
1881arguments are a dictionary:
1882
1883 >>> m = MagicMock(return_value=None)
1884 >>> m(1, 2, 3, arg='one', arg2='two')
1885 >>> kall = m.call_args
1886 >>> args, kwargs = kall
1887 >>> args
1888 (1, 2, 3)
1889 >>> kwargs
1890 {'arg2': 'two', 'arg': 'one'}
1891 >>> args is kall[0]
1892 True
1893 >>> kwargs is kall[1]
1894 True
1895
1896 >>> m = MagicMock()
1897 >>> m.foo(4, 5, 6, arg='two', arg2='three')
1898 <MagicMock name='mock.foo()' id='...'>
1899 >>> kall = m.mock_calls[0]
1900 >>> name, args, kwargs = kall
1901 >>> name
1902 'foo'
1903 >>> args
1904 (4, 5, 6)
1905 >>> kwargs
1906 {'arg2': 'three', 'arg': 'two'}
1907 >>> name is m.mock_calls[0][0]
1908 True
1909
1910
1911create_autospec
Georg Brandlfb134382013-02-03 11:47:49 +01001912~~~~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001913
1914.. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs)
1915
1916 Create a mock object using another object as a spec. Attributes on the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001917 mock will use the corresponding attribute on the *spec* object as their
Michael Foorda9e6fb22012-03-28 14:36:02 +01001918 spec.
1919
1920 Functions or methods being mocked will have their arguments checked to
1921 ensure that they are called with the correct signature.
1922
Georg Brandl7ad3df62014-10-31 07:59:37 +01001923 If *spec_set* is ``True`` then attempting to set attributes that don't exist
1924 on the spec object will raise an :exc:`AttributeError`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001925
1926 If a class is used as a spec then the return value of the mock (the
1927 instance of the class) will have the same spec. You can use a class as the
Georg Brandl7ad3df62014-10-31 07:59:37 +01001928 spec for an instance object by passing ``instance=True``. The returned mock
Michael Foorda9e6fb22012-03-28 14:36:02 +01001929 will only be callable if instances of the mock are callable.
1930
Georg Brandl7ad3df62014-10-31 07:59:37 +01001931 :func:`create_autospec` also takes arbitrary keyword arguments that are passed to
Michael Foorda9e6fb22012-03-28 14:36:02 +01001932 the constructor of the created mock.
1933
1934See :ref:`auto-speccing` for examples of how to use auto-speccing with
Georg Brandl7ad3df62014-10-31 07:59:37 +01001935:func:`create_autospec` and the *autospec* argument to :func:`patch`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001936
1937
1938ANY
Georg Brandlfb134382013-02-03 11:47:49 +01001939~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001940
1941.. data:: ANY
1942
1943Sometimes you may need to make assertions about *some* of the arguments in a
1944call to mock, but either not care about some of the arguments or want to pull
1945them individually out of :attr:`~Mock.call_args` and make more complex
1946assertions on them.
1947
1948To ignore certain arguments you can pass in objects that compare equal to
1949*everything*. Calls to :meth:`~Mock.assert_called_with` and
1950:meth:`~Mock.assert_called_once_with` will then succeed no matter what was
1951passed in.
1952
1953 >>> mock = Mock(return_value=None)
1954 >>> mock('foo', bar=object())
1955 >>> mock.assert_called_once_with('foo', bar=ANY)
1956
Georg Brandl7ad3df62014-10-31 07:59:37 +01001957:data:`ANY` can also be used in comparisons with call lists like
Michael Foorda9e6fb22012-03-28 14:36:02 +01001958:attr:`~Mock.mock_calls`:
1959
1960 >>> m = MagicMock(return_value=None)
1961 >>> m(1)
1962 >>> m(1, 2)
1963 >>> m(object())
1964 >>> m.mock_calls == [call(1), call(1, 2), ANY]
1965 True
1966
1967
1968
1969FILTER_DIR
Georg Brandlfb134382013-02-03 11:47:49 +01001970~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01001971
1972.. data:: FILTER_DIR
1973
Georg Brandl7ad3df62014-10-31 07:59:37 +01001974:data:`FILTER_DIR` is a module level variable that controls the way mock objects
1975respond to :func:`dir` (only for Python 2.6 or more recent). The default is ``True``,
Michael Foorda9e6fb22012-03-28 14:36:02 +01001976which uses the filtering described below, to only show useful members. If you
1977dislike this filtering, or need to switch it off for diagnostic purposes, then
Georg Brandl7ad3df62014-10-31 07:59:37 +01001978set ``mock.FILTER_DIR = False``.
Michael Foorda9e6fb22012-03-28 14:36:02 +01001979
Georg Brandl7ad3df62014-10-31 07:59:37 +01001980With filtering on, ``dir(some_mock)`` shows only useful attributes and will
Michael Foorda9e6fb22012-03-28 14:36:02 +01001981include any dynamically created attributes that wouldn't normally be shown.
Georg Brandl7ad3df62014-10-31 07:59:37 +01001982If the mock was created with a *spec* (or *autospec* of course) then all the
Michael Foorda9e6fb22012-03-28 14:36:02 +01001983attributes from the original are shown, even if they haven't been accessed
1984yet:
1985
1986 >>> dir(Mock())
1987 ['assert_any_call',
1988 'assert_called_once_with',
1989 'assert_called_with',
1990 'assert_has_calls',
1991 'attach_mock',
1992 ...
1993 >>> from urllib import request
1994 >>> dir(Mock(spec=request))
1995 ['AbstractBasicAuthHandler',
1996 'AbstractDigestAuthHandler',
1997 'AbstractHTTPHandler',
1998 'BaseHandler',
1999 ...
2000
Georg Brandl7ad3df62014-10-31 07:59:37 +01002001Many of the not-very-useful (private to :class:`Mock` rather than the thing being
Michael Foorda9e6fb22012-03-28 14:36:02 +01002002mocked) underscore and double underscore prefixed attributes have been
Georg Brandl7ad3df62014-10-31 07:59:37 +01002003filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this
Michael Foorda9e6fb22012-03-28 14:36:02 +01002004behaviour you can switch it off by setting the module level switch
Georg Brandl7ad3df62014-10-31 07:59:37 +01002005:data:`FILTER_DIR`:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002006
2007 >>> from unittest import mock
2008 >>> mock.FILTER_DIR = False
2009 >>> dir(mock.Mock())
2010 ['_NonCallableMock__get_return_value',
2011 '_NonCallableMock__get_side_effect',
2012 '_NonCallableMock__return_value_doc',
2013 '_NonCallableMock__set_return_value',
2014 '_NonCallableMock__set_side_effect',
2015 '__call__',
2016 '__class__',
2017 ...
2018
Georg Brandl7ad3df62014-10-31 07:59:37 +01002019Alternatively you can just use ``vars(my_mock)`` (instance members) and
2020``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of
2021:data:`mock.FILTER_DIR`.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002022
2023
2024mock_open
Georg Brandlfb134382013-02-03 11:47:49 +01002025~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002026
2027.. function:: mock_open(mock=None, read_data=None)
2028
Georg Brandl7ad3df62014-10-31 07:59:37 +01002029 A helper function to create a mock to replace the use of :func:`open`. It works
2030 for :func:`open` called directly or used as a context manager.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002031
Georg Brandl7ad3df62014-10-31 07:59:37 +01002032 The *mock* argument is the mock object to configure. If ``None`` (the
2033 default) then a :class:`MagicMock` will be created for you, with the API limited
Michael Foorda9e6fb22012-03-28 14:36:02 +01002034 to methods or attributes available on standard file handles.
2035
Georg Brandl7ad3df62014-10-31 07:59:37 +01002036 *read_data* is a string for the :meth:`~io.IOBase.read`,
Serhiy Storchaka98b28fd2013-10-13 23:12:09 +03002037 :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods
Michael Foord04cbe0c2013-03-19 17:22:51 -07002038 of the file handle to return. Calls to those methods will take data from
Georg Brandl7ad3df62014-10-31 07:59:37 +01002039 *read_data* until it is depleted. The mock of these methods is pretty
Robert Collinsca647ef2015-07-24 03:48:20 +12002040 simplistic: every time the *mock* is called, the *read_data* is rewound to
2041 the start. If you need more control over the data that you are feeding to
2042 the tested code you will need to customize this mock for yourself. When that
2043 is insufficient, one of the in-memory filesystem packages on `PyPI
2044 <https://pypi.python.org/pypi>`_ can offer a realistic filesystem for testing.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002045
Robert Collinsf79dfe32015-07-24 04:09:59 +12002046 .. versionchanged:: 3.4
2047 Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support.
2048 The mock of :meth:`~io.IOBase.read` changed to consume *read_data* rather
2049 than returning it on each call.
2050
Robert Collins70398392015-07-24 04:10:27 +12002051 .. versionchanged:: 3.5
Robert Collinsf79dfe32015-07-24 04:09:59 +12002052 *read_data* is now reset on each call to the *mock*.
2053
Georg Brandl7ad3df62014-10-31 07:59:37 +01002054Using :func:`open` as a context manager is a great way to ensure your file handles
Michael Foorda9e6fb22012-03-28 14:36:02 +01002055are closed properly and is becoming common::
2056
2057 with open('/some/path', 'w') as f:
2058 f.write('something')
2059
Georg Brandl7ad3df62014-10-31 07:59:37 +01002060The issue is that even if you mock out the call to :func:`open` it is the
2061*returned object* that is used as a context manager (and has :meth:`__enter__` and
2062:meth:`__exit__` called).
Michael Foorda9e6fb22012-03-28 14:36:02 +01002063
2064Mocking context managers with a :class:`MagicMock` is common enough and fiddly
2065enough that a helper function is useful.
2066
2067 >>> m = mock_open()
Michael Foordfddcfa22014-04-14 16:25:20 -04002068 >>> with patch('__main__.open', m):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002069 ... with open('foo', 'w') as h:
2070 ... h.write('some stuff')
2071 ...
2072 >>> m.mock_calls
2073 [call('foo', 'w'),
2074 call().__enter__(),
2075 call().write('some stuff'),
2076 call().__exit__(None, None, None)]
2077 >>> m.assert_called_once_with('foo', 'w')
2078 >>> handle = m()
2079 >>> handle.write.assert_called_once_with('some stuff')
2080
2081And for reading files:
2082
Michael Foordfddcfa22014-04-14 16:25:20 -04002083 >>> with patch('__main__.open', mock_open(read_data='bibble')) as m:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002084 ... with open('foo') as h:
2085 ... result = h.read()
2086 ...
2087 >>> m.assert_called_once_with('foo')
2088 >>> assert result == 'bibble'
2089
2090
2091.. _auto-speccing:
2092
2093Autospeccing
Georg Brandlfb134382013-02-03 11:47:49 +01002094~~~~~~~~~~~~
Michael Foorda9e6fb22012-03-28 14:36:02 +01002095
Georg Brandl7ad3df62014-10-31 07:59:37 +01002096Autospeccing is based on the existing :attr:`spec` feature of mock. It limits the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002097api of mocks to the api of an original object (the spec), but it is recursive
2098(implemented lazily) so that attributes of mocks only have the same api as
2099the attributes of the spec. In addition mocked functions / methods have the
Georg Brandl7ad3df62014-10-31 07:59:37 +01002100same call signature as the original so they raise a :exc:`TypeError` if they are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002101called incorrectly.
2102
2103Before I explain how auto-speccing works, here's why it is needed.
2104
Georg Brandl7ad3df62014-10-31 07:59:37 +01002105:class:`Mock` is a very powerful and flexible object, but it suffers from two flaws
Michael Foorda9e6fb22012-03-28 14:36:02 +01002106when used to mock out objects from a system under test. One of these flaws is
Georg Brandl7ad3df62014-10-31 07:59:37 +01002107specific to the :class:`Mock` api and the other is a more general problem with using
Michael Foorda9e6fb22012-03-28 14:36:02 +01002108mock objects.
2109
Georg Brandl7ad3df62014-10-31 07:59:37 +01002110First the problem specific to :class:`Mock`. :class:`Mock` has two assert methods that are
Michael Foorda9e6fb22012-03-28 14:36:02 +01002111extremely handy: :meth:`~Mock.assert_called_with` and
2112:meth:`~Mock.assert_called_once_with`.
2113
2114 >>> mock = Mock(name='Thing', return_value=None)
2115 >>> mock(1, 2, 3)
2116 >>> mock.assert_called_once_with(1, 2, 3)
2117 >>> mock(1, 2, 3)
2118 >>> mock.assert_called_once_with(1, 2, 3)
2119 Traceback (most recent call last):
2120 ...
Michael Foord28d591c2012-09-28 16:15:22 +01002121 AssertionError: Expected 'mock' to be called once. Called 2 times.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002122
2123Because mocks auto-create attributes on demand, and allow you to call them
2124with arbitrary arguments, if you misspell one of these assert methods then
2125your assertion is gone:
2126
2127.. code-block:: pycon
2128
2129 >>> mock = Mock(name='Thing', return_value=None)
2130 >>> mock(1, 2, 3)
2131 >>> mock.assret_called_once_with(4, 5, 6)
2132
2133Your tests can pass silently and incorrectly because of the typo.
2134
2135The second issue is more general to mocking. If you refactor some of your
2136code, rename members and so on, any tests for code that is still using the
2137*old api* but uses mocks instead of the real objects will still pass. This
2138means your tests can all pass even though your code is broken.
2139
2140Note that this is another reason why you need integration tests as well as
2141unit tests. Testing everything in isolation is all fine and dandy, but if you
2142don't test how your units are "wired together" there is still lots of room
2143for bugs that tests might have caught.
2144
Georg Brandl7ad3df62014-10-31 07:59:37 +01002145:mod:`mock` already provides a feature to help with this, called speccing. If you
2146use a class or instance as the :attr:`spec` for a mock then you can only access
Michael Foorda9e6fb22012-03-28 14:36:02 +01002147attributes on the mock that exist on the real class:
2148
2149 >>> from urllib import request
2150 >>> mock = Mock(spec=request.Request)
2151 >>> mock.assret_called_with
2152 Traceback (most recent call last):
2153 ...
2154 AttributeError: Mock object has no attribute 'assret_called_with'
2155
2156The spec only applies to the mock itself, so we still have the same issue
2157with any methods on the mock:
2158
2159.. code-block:: pycon
2160
2161 >>> mock.has_data()
2162 <mock.Mock object at 0x...>
2163 >>> mock.has_data.assret_called_with()
2164
Georg Brandl7ad3df62014-10-31 07:59:37 +01002165Auto-speccing solves this problem. You can either pass ``autospec=True`` to
2166:func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a
2167mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the
Michael Foorda9e6fb22012-03-28 14:36:02 +01002168object that is being replaced will be used as the spec object. Because the
2169speccing is done "lazily" (the spec is created as attributes on the mock are
2170accessed) you can use it with very complex or deeply nested objects (like
2171modules that import modules that import modules) without a big performance
2172hit.
2173
2174Here's an example of it in use:
2175
2176 >>> from urllib import request
2177 >>> patcher = patch('__main__.request', autospec=True)
2178 >>> mock_request = patcher.start()
2179 >>> request is mock_request
2180 True
2181 >>> mock_request.Request
2182 <MagicMock name='request.Request' spec='Request' id='...'>
2183
Georg Brandl7ad3df62014-10-31 07:59:37 +01002184You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two
2185arguments in the constructor (one of which is *self*). Here's what happens if
Michael Foorda9e6fb22012-03-28 14:36:02 +01002186we try to call it incorrectly:
2187
2188 >>> req = request.Request()
2189 Traceback (most recent call last):
2190 ...
2191 TypeError: <lambda>() takes at least 2 arguments (1 given)
2192
2193The spec also applies to instantiated classes (i.e. the return value of
2194specced mocks):
2195
2196 >>> req = request.Request('foo')
2197 >>> req
2198 <NonCallableMagicMock name='request.Request()' spec='Request' id='...'>
2199
Georg Brandl7ad3df62014-10-31 07:59:37 +01002200:class:`Request` objects are not callable, so the return value of instantiating our
2201mocked out :class:`request.Request` is a non-callable mock. With the spec in place
Michael Foorda9e6fb22012-03-28 14:36:02 +01002202any typos in our asserts will raise the correct error:
2203
2204 >>> req.add_header('spam', 'eggs')
2205 <MagicMock name='request.Request().add_header()' id='...'>
2206 >>> req.add_header.assret_called_with
2207 Traceback (most recent call last):
2208 ...
2209 AttributeError: Mock object has no attribute 'assret_called_with'
2210 >>> req.add_header.assert_called_with('spam', 'eggs')
2211
Georg Brandl7ad3df62014-10-31 07:59:37 +01002212In many cases you will just be able to add ``autospec=True`` to your existing
2213:func:`patch` calls and then be protected against bugs due to typos and api
Michael Foorda9e6fb22012-03-28 14:36:02 +01002214changes.
2215
Georg Brandl7ad3df62014-10-31 07:59:37 +01002216As well as using *autospec* through :func:`patch` there is a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002217:func:`create_autospec` for creating autospecced mocks directly:
2218
2219 >>> from urllib import request
2220 >>> mock_request = create_autospec(request)
2221 >>> mock_request.Request('foo', 'bar')
2222 <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>
2223
2224This isn't without caveats and limitations however, which is why it is not
2225the default behaviour. In order to know what attributes are available on the
2226spec object, autospec has to introspect (access attributes) the spec. As you
2227traverse attributes on the mock a corresponding traversal of the original
2228object is happening under the hood. If any of your specced objects have
2229properties or descriptors that can trigger code execution then you may not be
2230able to use autospec. On the other hand it is much better to design your
2231objects so that introspection is safe [#]_.
2232
2233A more serious problem is that it is common for instance attributes to be
Georg Brandl7ad3df62014-10-31 07:59:37 +01002234created in the :meth:`__init__` method and not to exist on the class at all.
2235*autospec* can't know about any dynamically created attributes and restricts
Michael Foorda9e6fb22012-03-28 14:36:02 +01002236the api to visible attributes.
2237
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002238 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002239 ... def __init__(self):
2240 ... self.a = 33
2241 ...
2242 >>> with patch('__main__.Something', autospec=True):
2243 ... thing = Something()
2244 ... thing.a
2245 ...
2246 Traceback (most recent call last):
2247 ...
2248 AttributeError: Mock object has no attribute 'a'
2249
2250There are a few different ways of resolving this problem. The easiest, but
2251not necessarily the least annoying, way is to simply set the required
Georg Brandl7ad3df62014-10-31 07:59:37 +01002252attributes on the mock after creation. Just because *autospec* doesn't allow
Michael Foorda9e6fb22012-03-28 14:36:02 +01002253you to fetch attributes that don't exist on the spec it doesn't prevent you
2254setting them:
2255
2256 >>> with patch('__main__.Something', autospec=True):
2257 ... thing = Something()
2258 ... thing.a = 33
2259 ...
2260
Georg Brandl7ad3df62014-10-31 07:59:37 +01002261There is a more aggressive version of both *spec* and *autospec* that *does*
Michael Foorda9e6fb22012-03-28 14:36:02 +01002262prevent you setting non-existent attributes. This is useful if you want to
2263ensure your code only *sets* valid attributes too, but obviously it prevents
2264this particular scenario:
2265
2266 >>> with patch('__main__.Something', autospec=True, spec_set=True):
2267 ... thing = Something()
2268 ... thing.a = 33
2269 ...
2270 Traceback (most recent call last):
2271 ...
2272 AttributeError: Mock object has no attribute 'a'
2273
2274Probably the best way of solving the problem is to add class attributes as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002275default values for instance members initialised in :meth:`__init__`. Note that if
2276you are only setting default attributes in :meth:`__init__` then providing them via
Michael Foorda9e6fb22012-03-28 14:36:02 +01002277class attributes (shared between instances of course) is faster too. e.g.
2278
2279.. code-block:: python
2280
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002281 class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002282 a = 33
2283
2284This brings up another issue. It is relatively common to provide a default
Georg Brandl7ad3df62014-10-31 07:59:37 +01002285value of ``None`` for members that will later be an object of a different type.
2286``None`` would be useless as a spec because it wouldn't let you access *any*
2287attributes or methods on it. As ``None`` is *never* going to be useful as a
Michael Foorda9e6fb22012-03-28 14:36:02 +01002288spec, and probably indicates a member that will normally of some other type,
Georg Brandl7ad3df62014-10-31 07:59:37 +01002289autospec doesn't use a spec for members that are set to ``None``. These will
2290just be ordinary mocks (well - MagicMocks):
Michael Foorda9e6fb22012-03-28 14:36:02 +01002291
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002292 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002293 ... member = None
2294 ...
2295 >>> mock = create_autospec(Something)
2296 >>> mock.member.foo.bar.baz()
2297 <MagicMock name='mock.member.foo.bar.baz()' id='...'>
2298
2299If modifying your production classes to add defaults isn't to your liking
2300then there are more options. One of these is simply to use an instance as the
2301spec rather than the class. The other is to create a subclass of the
2302production class and add the defaults to the subclass without affecting the
2303production class. Both of these require you to use an alternative object as
Georg Brandl7ad3df62014-10-31 07:59:37 +01002304the spec. Thankfully :func:`patch` supports this - you can simply pass the
2305alternative object as the *autospec* argument:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002306
Ezio Melottic9cfcf12013-03-11 09:42:40 +02002307 >>> class Something:
Michael Foorda9e6fb22012-03-28 14:36:02 +01002308 ... def __init__(self):
2309 ... self.a = 33
2310 ...
2311 >>> class SomethingForTest(Something):
2312 ... a = 33
2313 ...
2314 >>> p = patch('__main__.Something', autospec=SomethingForTest)
2315 >>> mock = p.start()
2316 >>> mock.a
2317 <NonCallableMagicMock name='Something.a' spec='int' id='...'>
2318
2319
2320.. [#] This only applies to classes or already instantiated objects. Calling
2321 a mocked class to create a mock instance *does not* create a real instance.
Georg Brandl7ad3df62014-10-31 07:59:37 +01002322 It is only attribute lookups - along with calls to :func:`dir` - that are done.
Michael Foorda9e6fb22012-03-28 14:36:02 +01002323