Andrew Svetlov | 7ea6f70 | 2012-10-31 11:29:52 +0200 | [diff] [blame] | 1 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 2 | :mod:`unittest.mock` --- mock object library |
| 3 | ============================================ |
| 4 | |
| 5 | .. module:: unittest.mock |
| 6 | :synopsis: Mock object library. |
Terry Jan Reedy | fa089b9 | 2016-06-11 15:02:54 -0400 | [diff] [blame] | 7 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 8 | .. moduleauthor:: Michael Foord <michael@python.org> |
| 9 | .. currentmodule:: unittest.mock |
| 10 | |
| 11 | .. versionadded:: 3.3 |
| 12 | |
Terry Jan Reedy | fa089b9 | 2016-06-11 15:02:54 -0400 | [diff] [blame] | 13 | **Source code:** :source:`Lib/unittest/mock.py` |
| 14 | |
| 15 | -------------- |
| 16 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 17 | :mod:`unittest.mock` is a library for testing in Python. It allows you to |
| 18 | replace parts of your system under test with mock objects and make assertions |
| 19 | about how they have been used. |
| 20 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 21 | :mod:`unittest.mock` provides a core :class:`Mock` class removing the need to |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 22 | create a host of stubs throughout your test suite. After performing an |
| 23 | action, you can make assertions about which methods / attributes were used |
| 24 | and arguments they were called with. You can also specify return values and |
| 25 | set needed attributes in the normal way. |
| 26 | |
| 27 | Additionally, mock provides a :func:`patch` decorator that handles patching |
| 28 | module and class level attributes within the scope of a test, along with |
| 29 | :const:`sentinel` for creating unique objects. See the `quick guide`_ for |
| 30 | some examples of how to use :class:`Mock`, :class:`MagicMock` and |
| 31 | :func:`patch`. |
| 32 | |
| 33 | Mock is very easy to use and is designed for use with :mod:`unittest`. Mock |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 34 | is based on the 'action -> assertion' pattern instead of 'record -> replay' |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 35 | used by many mocking frameworks. |
| 36 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 37 | There is a backport of :mod:`unittest.mock` for earlier versions of Python, |
Stéphane Wirtel | 19177fb | 2018-05-15 20:58:35 +0200 | [diff] [blame] | 38 | available as `mock on PyPI <https://pypi.org/project/mock>`_. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 39 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 40 | |
| 41 | Quick Guide |
| 42 | ----------- |
| 43 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 44 | .. testsetup:: |
| 45 | |
| 46 | class ProductionClass: |
| 47 | def method(self, a, b, c): |
| 48 | pass |
| 49 | |
| 50 | class SomeClass: |
| 51 | @staticmethod |
| 52 | def static_method(args): |
| 53 | return args |
| 54 | |
| 55 | @classmethod |
| 56 | def class_method(cls, args): |
| 57 | return args |
| 58 | |
| 59 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 60 | :class:`Mock` and :class:`MagicMock` objects create all attributes and |
| 61 | methods as you access them and store details of how they have been used. You |
| 62 | can configure them, to specify return values or limit what attributes are |
| 63 | available, and then make assertions about how they have been used: |
| 64 | |
| 65 | >>> from unittest.mock import MagicMock |
| 66 | >>> thing = ProductionClass() |
| 67 | >>> thing.method = MagicMock(return_value=3) |
| 68 | >>> thing.method(3, 4, 5, key='value') |
| 69 | 3 |
| 70 | >>> thing.method.assert_called_with(3, 4, 5, key='value') |
| 71 | |
| 72 | :attr:`side_effect` allows you to perform side effects, including raising an |
| 73 | exception when a mock is called: |
| 74 | |
| 75 | >>> mock = Mock(side_effect=KeyError('foo')) |
| 76 | >>> mock() |
| 77 | Traceback (most recent call last): |
| 78 | ... |
| 79 | KeyError: 'foo' |
| 80 | |
| 81 | >>> values = {'a': 1, 'b': 2, 'c': 3} |
| 82 | >>> def side_effect(arg): |
| 83 | ... return values[arg] |
| 84 | ... |
| 85 | >>> mock.side_effect = side_effect |
| 86 | >>> mock('a'), mock('b'), mock('c') |
| 87 | (1, 2, 3) |
| 88 | >>> mock.side_effect = [5, 4, 3, 2, 1] |
| 89 | >>> mock(), mock(), mock() |
| 90 | (5, 4, 3) |
| 91 | |
| 92 | Mock has many other ways you can configure it and control its behaviour. For |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 93 | example the *spec* argument configures the mock to take its specification |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 94 | from another object. Attempting to access attributes or methods on the mock |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 95 | that don't exist on the spec will fail with an :exc:`AttributeError`. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 96 | |
| 97 | The :func:`patch` decorator / context manager makes it easy to mock classes or |
| 98 | objects in a module under test. The object you specify will be replaced with a |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 99 | mock (or other object) during the test and restored when the test ends:: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 100 | |
| 101 | >>> from unittest.mock import patch |
| 102 | >>> @patch('module.ClassName2') |
| 103 | ... @patch('module.ClassName1') |
| 104 | ... def test(MockClass1, MockClass2): |
| 105 | ... module.ClassName1() |
| 106 | ... module.ClassName2() |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 107 | ... assert MockClass1 is module.ClassName1 |
| 108 | ... assert MockClass2 is module.ClassName2 |
| 109 | ... assert MockClass1.called |
| 110 | ... assert MockClass2.called |
| 111 | ... |
| 112 | >>> test() |
| 113 | |
| 114 | .. note:: |
| 115 | |
| 116 | When you nest patch decorators the mocks are passed in to the decorated |
Andrés Delfino | 271818f | 2018-09-14 14:13:09 -0300 | [diff] [blame] | 117 | function in the same order they applied (the normal *Python* order that |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 118 | decorators are applied). This means from the bottom up, so in the example |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 119 | above the mock for ``module.ClassName1`` is passed in first. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 120 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 121 | With :func:`patch` it matters that you patch objects in the namespace where they |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 122 | are looked up. This is normally straightforward, but for a quick guide |
| 123 | read :ref:`where to patch <where-to-patch>`. |
| 124 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 125 | As well as a decorator :func:`patch` can be used as a context manager in a with |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 126 | statement: |
| 127 | |
| 128 | >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method: |
| 129 | ... thing = ProductionClass() |
| 130 | ... thing.method(1, 2, 3) |
| 131 | ... |
| 132 | >>> mock_method.assert_called_once_with(1, 2, 3) |
| 133 | |
| 134 | |
| 135 | There is also :func:`patch.dict` for setting values in a dictionary just |
| 136 | during a scope and restoring the dictionary to its original state when the test |
| 137 | ends: |
| 138 | |
| 139 | >>> foo = {'key': 'value'} |
| 140 | >>> original = foo.copy() |
| 141 | >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True): |
| 142 | ... assert foo == {'newkey': 'newvalue'} |
| 143 | ... |
| 144 | >>> assert foo == original |
| 145 | |
| 146 | Mock supports the mocking of Python :ref:`magic methods <magic-methods>`. The |
| 147 | easiest way of using magic methods is with the :class:`MagicMock` class. It |
| 148 | allows you to do things like: |
| 149 | |
| 150 | >>> mock = MagicMock() |
| 151 | >>> mock.__str__.return_value = 'foobarbaz' |
| 152 | >>> str(mock) |
| 153 | 'foobarbaz' |
| 154 | >>> mock.__str__.assert_called_with() |
| 155 | |
| 156 | Mock allows you to assign functions (or other Mock instances) to magic methods |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 157 | and they will be called appropriately. The :class:`MagicMock` class is just a Mock |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 158 | variant that has all of the magic methods pre-created for you (well, all the |
| 159 | useful ones anyway). |
| 160 | |
| 161 | The following is an example of using magic methods with the ordinary Mock |
| 162 | class: |
| 163 | |
| 164 | >>> mock = Mock() |
| 165 | >>> mock.__str__ = Mock(return_value='wheeeeee') |
| 166 | >>> str(mock) |
| 167 | 'wheeeeee' |
| 168 | |
| 169 | For ensuring that the mock objects in your tests have the same api as the |
| 170 | objects they are replacing, you can use :ref:`auto-speccing <auto-speccing>`. |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 171 | Auto-speccing can be done through the *autospec* argument to patch, or the |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 172 | :func:`create_autospec` function. Auto-speccing creates mock objects that |
| 173 | have the same attributes and methods as the objects they are replacing, and |
| 174 | any functions and methods (including constructors) have the same call |
| 175 | signature as the real object. |
| 176 | |
| 177 | This ensures that your mocks will fail in the same way as your production |
| 178 | code if they are used incorrectly: |
| 179 | |
| 180 | >>> from unittest.mock import create_autospec |
| 181 | >>> def function(a, b, c): |
| 182 | ... pass |
| 183 | ... |
| 184 | >>> mock_function = create_autospec(function, return_value='fishy') |
| 185 | >>> mock_function(1, 2, 3) |
| 186 | 'fishy' |
| 187 | >>> mock_function.assert_called_once_with(1, 2, 3) |
| 188 | >>> mock_function('wrong arguments') |
| 189 | Traceback (most recent call last): |
| 190 | ... |
| 191 | TypeError: <lambda>() takes exactly 3 arguments (1 given) |
| 192 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 193 | :func:`create_autospec` can also be used on classes, where it copies the signature of |
| 194 | the ``__init__`` method, and on callable objects where it copies the signature of |
| 195 | the ``__call__`` method. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 196 | |
| 197 | |
| 198 | |
| 199 | The Mock Class |
| 200 | -------------- |
| 201 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 202 | .. testsetup:: |
| 203 | |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 204 | import asyncio |
| 205 | import inspect |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 206 | import unittest |
| 207 | from unittest.mock import sentinel, DEFAULT, ANY |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 208 | from unittest.mock import patch, call, Mock, MagicMock, PropertyMock, AsyncMock |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 209 | from unittest.mock import mock_open |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 210 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 211 | :class:`Mock` is a flexible mock object intended to replace the use of stubs and |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 212 | test doubles throughout your code. Mocks are callable and create attributes as |
| 213 | new mocks when you access them [#]_. Accessing the same attribute will always |
| 214 | return the same mock. Mocks record how you use them, allowing you to make |
| 215 | assertions about what your code has done to them. |
| 216 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 217 | :class:`MagicMock` is a subclass of :class:`Mock` with all the magic methods |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 218 | pre-created and ready to use. There are also non-callable variants, useful |
| 219 | when you are mocking out objects that aren't callable: |
| 220 | :class:`NonCallableMock` and :class:`NonCallableMagicMock` |
| 221 | |
| 222 | The :func:`patch` decorators makes it easy to temporarily replace classes |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 223 | in a particular module with a :class:`Mock` object. By default :func:`patch` will create |
| 224 | a :class:`MagicMock` for you. You can specify an alternative class of :class:`Mock` using |
| 225 | the *new_callable* argument to :func:`patch`. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 226 | |
| 227 | |
Kushal Das | 8c14534 | 2014-04-16 23:32:21 +0530 | [diff] [blame] | 228 | .. class:: Mock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 229 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 230 | Create a new :class:`Mock` object. :class:`Mock` takes several optional arguments |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 231 | that specify the behaviour of the Mock object: |
| 232 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 233 | * *spec*: This can be either a list of strings or an existing object (a |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 234 | class or instance) that acts as the specification for the mock object. If |
| 235 | you pass in an object then a list of strings is formed by calling dir on |
| 236 | the object (excluding unsupported magic attributes and methods). |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 237 | Accessing any attribute not in this list will raise an :exc:`AttributeError`. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 238 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 239 | If *spec* is an object (rather than a list of strings) then |
Serhiy Storchaka | bfdcd43 | 2013-10-13 23:09:14 +0300 | [diff] [blame] | 240 | :attr:`~instance.__class__` returns the class of the spec object. This |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 241 | allows mocks to pass :func:`isinstance` tests. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 242 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 243 | * *spec_set*: A stricter variant of *spec*. If used, attempting to *set* |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 244 | or get an attribute on the mock that isn't on the object passed as |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 245 | *spec_set* will raise an :exc:`AttributeError`. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 246 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 247 | * *side_effect*: A function to be called whenever the Mock is called. See |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 248 | the :attr:`~Mock.side_effect` attribute. Useful for raising exceptions or |
| 249 | dynamically changing return values. The function is called with the same |
| 250 | arguments as the mock, and unless it returns :data:`DEFAULT`, the return |
| 251 | value of this function is used as the return value. |
| 252 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 253 | Alternatively *side_effect* can be an exception class or instance. In |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 254 | this case the exception will be raised when the mock is called. |
| 255 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 256 | If *side_effect* is an iterable then each call to the mock will return |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 257 | the next value from the iterable. |
| 258 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 259 | A *side_effect* can be cleared by setting it to ``None``. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 260 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 261 | * *return_value*: The value returned when the mock is called. By default |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 262 | this is a new Mock (created on first access). See the |
| 263 | :attr:`return_value` attribute. |
| 264 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 265 | * *unsafe*: By default if any attribute starts with *assert* or |
| 266 | *assret* will raise an :exc:`AttributeError`. Passing ``unsafe=True`` |
| 267 | will allow access to these attributes. |
Kushal Das | 8c14534 | 2014-04-16 23:32:21 +0530 | [diff] [blame] | 268 | |
| 269 | .. versionadded:: 3.5 |
| 270 | |
Serhiy Storchaka | ecf41da | 2016-10-19 16:29:26 +0300 | [diff] [blame] | 271 | * *wraps*: Item for the mock object to wrap. If *wraps* is not ``None`` then |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 272 | calling the Mock will pass the call through to the wrapped object |
Michael Foord | 0682a0c | 2012-04-13 20:51:20 +0100 | [diff] [blame] | 273 | (returning the real result). Attribute access on the mock will return a |
| 274 | Mock object that wraps the corresponding attribute of the wrapped |
| 275 | object (so attempting to access an attribute that doesn't exist will |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 276 | raise an :exc:`AttributeError`). |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 277 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 278 | If the mock has an explicit *return_value* set then calls are not passed |
| 279 | to the wrapped object and the *return_value* is returned instead. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 280 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 281 | * *name*: If the mock has a name then it will be used in the repr of the |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 282 | mock. This can be useful for debugging. The name is propagated to child |
| 283 | mocks. |
| 284 | |
| 285 | Mocks can also be called with arbitrary keyword arguments. These will be |
| 286 | used to set attributes on the mock after it is created. See the |
| 287 | :meth:`configure_mock` method for details. |
| 288 | |
Ismail S | f9590ed | 2019-08-12 07:57:03 +0100 | [diff] [blame] | 289 | .. method:: assert_called() |
Victor Stinner | 2c2a4e6 | 2016-03-11 22:17:48 +0100 | [diff] [blame] | 290 | |
| 291 | Assert that the mock was called at least once. |
| 292 | |
| 293 | >>> mock = Mock() |
| 294 | >>> mock.method() |
| 295 | <Mock name='mock.method()' id='...'> |
| 296 | >>> mock.method.assert_called() |
| 297 | |
| 298 | .. versionadded:: 3.6 |
| 299 | |
Ismail S | f9590ed | 2019-08-12 07:57:03 +0100 | [diff] [blame] | 300 | .. method:: assert_called_once() |
Victor Stinner | 2c2a4e6 | 2016-03-11 22:17:48 +0100 | [diff] [blame] | 301 | |
| 302 | Assert that the mock was called exactly once. |
| 303 | |
| 304 | >>> mock = Mock() |
| 305 | >>> mock.method() |
| 306 | <Mock name='mock.method()' id='...'> |
| 307 | >>> mock.method.assert_called_once() |
| 308 | >>> mock.method() |
| 309 | <Mock name='mock.method()' id='...'> |
| 310 | >>> mock.method.assert_called_once() |
| 311 | Traceback (most recent call last): |
| 312 | ... |
| 313 | AssertionError: Expected 'method' to have been called once. Called 2 times. |
| 314 | |
| 315 | .. versionadded:: 3.6 |
| 316 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 317 | |
| 318 | .. method:: assert_called_with(*args, **kwargs) |
| 319 | |
Rémi Lapeyre | f5896a0 | 2019-08-29 08:15:53 +0200 | [diff] [blame] | 320 | This method is a convenient way of asserting that the last call has been |
| 321 | made in a particular way: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 322 | |
| 323 | >>> mock = Mock() |
| 324 | >>> mock.method(1, 2, 3, test='wow') |
| 325 | <Mock name='mock.method()' id='...'> |
| 326 | >>> mock.method.assert_called_with(1, 2, 3, test='wow') |
| 327 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 328 | .. method:: assert_called_once_with(*args, **kwargs) |
| 329 | |
Arne de Laat | 324c5d8 | 2017-02-23 15:57:25 +0100 | [diff] [blame] | 330 | Assert that the mock was called exactly once and that that call was |
| 331 | with the specified arguments. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 332 | |
| 333 | >>> mock = Mock(return_value=None) |
| 334 | >>> mock('foo', bar='baz') |
| 335 | >>> mock.assert_called_once_with('foo', bar='baz') |
Arne de Laat | 324c5d8 | 2017-02-23 15:57:25 +0100 | [diff] [blame] | 336 | >>> mock('other', bar='values') |
| 337 | >>> mock.assert_called_once_with('other', bar='values') |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 338 | Traceback (most recent call last): |
| 339 | ... |
Michael Foord | 28d591c | 2012-09-28 16:15:22 +0100 | [diff] [blame] | 340 | AssertionError: Expected 'mock' to be called once. Called 2 times. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 341 | |
| 342 | |
| 343 | .. method:: assert_any_call(*args, **kwargs) |
| 344 | |
| 345 | assert the mock has been called with the specified arguments. |
| 346 | |
| 347 | The assert passes if the mock has *ever* been called, unlike |
| 348 | :meth:`assert_called_with` and :meth:`assert_called_once_with` that |
Arne de Laat | 324c5d8 | 2017-02-23 15:57:25 +0100 | [diff] [blame] | 349 | only pass if the call is the most recent one, and in the case of |
| 350 | :meth:`assert_called_once_with` it must also be the only call. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 351 | |
| 352 | >>> mock = Mock(return_value=None) |
| 353 | >>> mock(1, 2, arg='thing') |
| 354 | >>> mock('some', 'thing', 'else') |
| 355 | >>> mock.assert_any_call(1, 2, arg='thing') |
| 356 | |
| 357 | |
| 358 | .. method:: assert_has_calls(calls, any_order=False) |
| 359 | |
| 360 | assert the mock has been called with the specified calls. |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 361 | The :attr:`mock_calls` list is checked for the calls. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 362 | |
Serhiy Storchaka | 138ccbb | 2019-11-12 16:57:03 +0200 | [diff] [blame] | 363 | If *any_order* is false then the calls must be |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 364 | sequential. There can be extra calls before or after the |
| 365 | specified calls. |
| 366 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 367 | If *any_order* is true then the calls can be in any order, but |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 368 | they must all appear in :attr:`mock_calls`. |
| 369 | |
| 370 | >>> mock = Mock(return_value=None) |
| 371 | >>> mock(1) |
| 372 | >>> mock(2) |
| 373 | >>> mock(3) |
| 374 | >>> mock(4) |
| 375 | >>> calls = [call(2), call(3)] |
| 376 | >>> mock.assert_has_calls(calls) |
| 377 | >>> calls = [call(4), call(2), call(3)] |
| 378 | >>> mock.assert_has_calls(calls, any_order=True) |
| 379 | |
Berker Peksag | ebf9fd3 | 2016-07-17 15:26:46 +0300 | [diff] [blame] | 380 | .. method:: assert_not_called() |
Kushal Das | 8af9db3 | 2014-04-17 01:36:14 +0530 | [diff] [blame] | 381 | |
| 382 | Assert the mock was never called. |
| 383 | |
| 384 | >>> m = Mock() |
| 385 | >>> m.hello.assert_not_called() |
| 386 | >>> obj = m.hello() |
| 387 | >>> m.hello.assert_not_called() |
| 388 | Traceback (most recent call last): |
| 389 | ... |
| 390 | AssertionError: Expected 'hello' to not have been called. Called 1 times. |
| 391 | |
| 392 | .. versionadded:: 3.5 |
| 393 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 394 | |
Kushal Das | 9cd39a1 | 2016-06-02 10:20:16 -0700 | [diff] [blame] | 395 | .. method:: reset_mock(*, return_value=False, side_effect=False) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 396 | |
| 397 | The reset_mock method resets all the call attributes on a mock object: |
| 398 | |
| 399 | >>> mock = Mock(return_value=None) |
| 400 | >>> mock('hello') |
| 401 | >>> mock.called |
| 402 | True |
| 403 | >>> mock.reset_mock() |
| 404 | >>> mock.called |
| 405 | False |
| 406 | |
Kushal Das | 9cd39a1 | 2016-06-02 10:20:16 -0700 | [diff] [blame] | 407 | .. versionchanged:: 3.6 |
| 408 | Added two keyword only argument to the reset_mock function. |
| 409 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 410 | This can be useful where you want to make a series of assertions that |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 411 | reuse the same object. Note that :meth:`reset_mock` *doesn't* clear the |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 412 | return value, :attr:`side_effect` or any child attributes you have |
Kushal Das | 9cd39a1 | 2016-06-02 10:20:16 -0700 | [diff] [blame] | 413 | set using normal assignment by default. In case you want to reset |
| 414 | *return_value* or :attr:`side_effect`, then pass the corresponding |
| 415 | parameter as ``True``. Child mocks and the return value mock |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 416 | (if any) are reset as well. |
| 417 | |
Kushal Das | 9cd39a1 | 2016-06-02 10:20:16 -0700 | [diff] [blame] | 418 | .. note:: *return_value*, and :attr:`side_effect` are keyword only |
| 419 | argument. |
| 420 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 421 | |
| 422 | .. method:: mock_add_spec(spec, spec_set=False) |
| 423 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 424 | Add a spec to a mock. *spec* can either be an object or a |
| 425 | list of strings. Only attributes on the *spec* can be fetched as |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 426 | attributes from the mock. |
| 427 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 428 | If *spec_set* is true then only attributes on the spec can be set. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 429 | |
| 430 | |
| 431 | .. method:: attach_mock(mock, attribute) |
| 432 | |
| 433 | Attach a mock as an attribute of this one, replacing its name and |
| 434 | parent. Calls to the attached mock will be recorded in the |
| 435 | :attr:`method_calls` and :attr:`mock_calls` attributes of this one. |
| 436 | |
| 437 | |
| 438 | .. method:: configure_mock(**kwargs) |
| 439 | |
| 440 | Set attributes on the mock through keyword arguments. |
| 441 | |
| 442 | Attributes plus return values and side effects can be set on child |
| 443 | mocks using standard dot notation and unpacking a dictionary in the |
| 444 | method call: |
| 445 | |
| 446 | >>> mock = Mock() |
| 447 | >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} |
| 448 | >>> mock.configure_mock(**attrs) |
| 449 | >>> mock.method() |
| 450 | 3 |
| 451 | >>> mock.other() |
| 452 | Traceback (most recent call last): |
| 453 | ... |
| 454 | KeyError |
| 455 | |
| 456 | The same thing can be achieved in the constructor call to mocks: |
| 457 | |
| 458 | >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} |
| 459 | >>> mock = Mock(some_attribute='eggs', **attrs) |
| 460 | >>> mock.some_attribute |
| 461 | 'eggs' |
| 462 | >>> mock.method() |
| 463 | 3 |
| 464 | >>> mock.other() |
| 465 | Traceback (most recent call last): |
| 466 | ... |
| 467 | KeyError |
| 468 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 469 | :meth:`configure_mock` exists to make it easier to do configuration |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 470 | after the mock has been created. |
| 471 | |
| 472 | |
| 473 | .. method:: __dir__() |
| 474 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 475 | :class:`Mock` objects limit the results of ``dir(some_mock)`` to useful results. |
| 476 | For mocks with a *spec* this includes all the permitted attributes |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 477 | for the mock. |
| 478 | |
| 479 | See :data:`FILTER_DIR` for what this filtering does, and how to |
| 480 | switch it off. |
| 481 | |
| 482 | |
| 483 | .. method:: _get_child_mock(**kw) |
| 484 | |
| 485 | Create the child mocks for attributes and return value. |
| 486 | By default child mocks will be the same type as the parent. |
| 487 | Subclasses of Mock may want to override this to customize the way |
| 488 | child mocks are made. |
| 489 | |
| 490 | For non-callable mocks the callable variant will be used (rather than |
| 491 | any custom subclass). |
| 492 | |
| 493 | |
| 494 | .. attribute:: called |
| 495 | |
| 496 | A boolean representing whether or not the mock object has been called: |
| 497 | |
| 498 | >>> mock = Mock(return_value=None) |
| 499 | >>> mock.called |
| 500 | False |
| 501 | >>> mock() |
| 502 | >>> mock.called |
| 503 | True |
| 504 | |
| 505 | .. attribute:: call_count |
| 506 | |
| 507 | An integer telling you how many times the mock object has been called: |
| 508 | |
| 509 | >>> mock = Mock(return_value=None) |
| 510 | >>> mock.call_count |
| 511 | 0 |
| 512 | >>> mock() |
| 513 | >>> mock() |
| 514 | >>> mock.call_count |
| 515 | 2 |
| 516 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 517 | .. attribute:: return_value |
| 518 | |
| 519 | Set this to configure the value returned by calling the mock: |
| 520 | |
| 521 | >>> mock = Mock() |
| 522 | >>> mock.return_value = 'fish' |
| 523 | >>> mock() |
| 524 | 'fish' |
| 525 | |
| 526 | The default return value is a mock object and you can configure it in |
| 527 | the normal way: |
| 528 | |
| 529 | >>> mock = Mock() |
| 530 | >>> mock.return_value.attribute = sentinel.Attribute |
| 531 | >>> mock.return_value() |
| 532 | <Mock name='mock()()' id='...'> |
| 533 | >>> mock.return_value.assert_called_with() |
| 534 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 535 | :attr:`return_value` can also be set in the constructor: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 536 | |
| 537 | >>> mock = Mock(return_value=3) |
| 538 | >>> mock.return_value |
| 539 | 3 |
| 540 | >>> mock() |
| 541 | 3 |
| 542 | |
| 543 | |
| 544 | .. attribute:: side_effect |
| 545 | |
| 546 | This can either be a function to be called when the mock is called, |
Georg Brandl | 8ed75cd | 2014-10-31 10:25:48 +0100 | [diff] [blame] | 547 | an iterable or an exception (class or instance) to be raised. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 548 | |
| 549 | If you pass in a function it will be called with same arguments as the |
| 550 | mock and unless the function returns the :data:`DEFAULT` singleton the |
| 551 | call to the mock will then return whatever the function returns. If the |
| 552 | function returns :data:`DEFAULT` then the mock will return its normal |
Brett Cannon | 533f1ed | 2013-05-25 11:28:20 -0400 | [diff] [blame] | 553 | value (from the :attr:`return_value`). |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 554 | |
Georg Brandl | 8ed75cd | 2014-10-31 10:25:48 +0100 | [diff] [blame] | 555 | If you pass in an iterable, it is used to retrieve an iterator which |
| 556 | must yield a value on every call. This value can either be an exception |
| 557 | instance to be raised, or a value to be returned from the call to the |
| 558 | mock (:data:`DEFAULT` handling is identical to the function case). |
| 559 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 560 | An example of a mock that raises an exception (to test exception |
| 561 | handling of an API): |
| 562 | |
| 563 | >>> mock = Mock() |
| 564 | >>> mock.side_effect = Exception('Boom!') |
| 565 | >>> mock() |
| 566 | Traceback (most recent call last): |
| 567 | ... |
| 568 | Exception: Boom! |
| 569 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 570 | Using :attr:`side_effect` to return a sequence of values: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 571 | |
| 572 | >>> mock = Mock() |
| 573 | >>> mock.side_effect = [3, 2, 1] |
| 574 | >>> mock(), mock(), mock() |
| 575 | (3, 2, 1) |
| 576 | |
Georg Brandl | 8ed75cd | 2014-10-31 10:25:48 +0100 | [diff] [blame] | 577 | Using a callable: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 578 | |
| 579 | >>> mock = Mock(return_value=3) |
| 580 | >>> def side_effect(*args, **kwargs): |
| 581 | ... return DEFAULT |
| 582 | ... |
| 583 | >>> mock.side_effect = side_effect |
| 584 | >>> mock() |
| 585 | 3 |
| 586 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 587 | :attr:`side_effect` can be set in the constructor. Here's an example that |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 588 | adds one to the value the mock is called with and returns it: |
| 589 | |
| 590 | >>> side_effect = lambda value: value + 1 |
| 591 | >>> mock = Mock(side_effect=side_effect) |
| 592 | >>> mock(3) |
| 593 | 4 |
| 594 | >>> mock(-8) |
| 595 | -7 |
| 596 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 597 | Setting :attr:`side_effect` to ``None`` clears it: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 598 | |
| 599 | >>> m = Mock(side_effect=KeyError, return_value=3) |
| 600 | >>> m() |
| 601 | Traceback (most recent call last): |
| 602 | ... |
| 603 | KeyError |
| 604 | >>> m.side_effect = None |
| 605 | >>> m() |
| 606 | 3 |
| 607 | |
| 608 | |
| 609 | .. attribute:: call_args |
| 610 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 611 | This is either ``None`` (if the mock hasn't been called), or the |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 612 | arguments that the mock was last called with. This will be in the |
Kumar Akshay | b0df45e | 2019-03-22 13:40:40 +0530 | [diff] [blame] | 613 | form of a tuple: the first member, which can also be accessed through |
| 614 | the ``args`` property, is any ordered arguments the mock was |
| 615 | called with (or an empty tuple) and the second member, which can |
| 616 | also be accessed through the ``kwargs`` property, is any keyword |
| 617 | arguments (or an empty dictionary). |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 618 | |
| 619 | >>> mock = Mock(return_value=None) |
Berker Peksag | 920f6db | 2015-09-10 21:41:15 +0300 | [diff] [blame] | 620 | >>> print(mock.call_args) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 621 | None |
| 622 | >>> mock() |
| 623 | >>> mock.call_args |
| 624 | call() |
| 625 | >>> mock.call_args == () |
| 626 | True |
| 627 | >>> mock(3, 4) |
| 628 | >>> mock.call_args |
| 629 | call(3, 4) |
| 630 | >>> mock.call_args == ((3, 4),) |
| 631 | True |
Kumar Akshay | b0df45e | 2019-03-22 13:40:40 +0530 | [diff] [blame] | 632 | >>> mock.call_args.args |
| 633 | (3, 4) |
| 634 | >>> mock.call_args.kwargs |
| 635 | {} |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 636 | >>> mock(3, 4, 5, key='fish', next='w00t!') |
| 637 | >>> mock.call_args |
| 638 | call(3, 4, 5, key='fish', next='w00t!') |
Kumar Akshay | b0df45e | 2019-03-22 13:40:40 +0530 | [diff] [blame] | 639 | >>> mock.call_args.args |
| 640 | (3, 4, 5) |
| 641 | >>> mock.call_args.kwargs |
| 642 | {'key': 'fish', 'next': 'w00t!'} |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 643 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 644 | :attr:`call_args`, along with members of the lists :attr:`call_args_list`, |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 645 | :attr:`method_calls` and :attr:`mock_calls` are :data:`call` objects. |
| 646 | These are tuples, so they can be unpacked to get at the individual |
| 647 | arguments and make more complex assertions. See |
| 648 | :ref:`calls as tuples <calls-as-tuples>`. |
| 649 | |
| 650 | |
| 651 | .. attribute:: call_args_list |
| 652 | |
| 653 | This is a list of all the calls made to the mock object in sequence |
| 654 | (so the length of the list is the number of times it has been |
| 655 | called). Before any calls have been made it is an empty list. The |
| 656 | :data:`call` object can be used for conveniently constructing lists of |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 657 | calls to compare with :attr:`call_args_list`. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 658 | |
| 659 | >>> mock = Mock(return_value=None) |
| 660 | >>> mock() |
| 661 | >>> mock(3, 4) |
| 662 | >>> mock(key='fish', next='w00t!') |
| 663 | >>> mock.call_args_list |
| 664 | [call(), call(3, 4), call(key='fish', next='w00t!')] |
| 665 | >>> expected = [(), ((3, 4),), ({'key': 'fish', 'next': 'w00t!'},)] |
| 666 | >>> mock.call_args_list == expected |
| 667 | True |
| 668 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 669 | Members of :attr:`call_args_list` are :data:`call` objects. These can be |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 670 | unpacked as tuples to get at the individual arguments. See |
| 671 | :ref:`calls as tuples <calls-as-tuples>`. |
| 672 | |
| 673 | |
| 674 | .. attribute:: method_calls |
| 675 | |
| 676 | As well as tracking calls to themselves, mocks also track calls to |
| 677 | methods and attributes, and *their* methods and attributes: |
| 678 | |
| 679 | >>> mock = Mock() |
| 680 | >>> mock.method() |
| 681 | <Mock name='mock.method()' id='...'> |
| 682 | >>> mock.property.method.attribute() |
| 683 | <Mock name='mock.property.method.attribute()' id='...'> |
| 684 | >>> mock.method_calls |
| 685 | [call.method(), call.property.method.attribute()] |
| 686 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 687 | Members of :attr:`method_calls` are :data:`call` objects. These can be |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 688 | unpacked as tuples to get at the individual arguments. See |
| 689 | :ref:`calls as tuples <calls-as-tuples>`. |
| 690 | |
| 691 | |
| 692 | .. attribute:: mock_calls |
| 693 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 694 | :attr:`mock_calls` records *all* calls to the mock object, its methods, |
| 695 | magic methods *and* return value mocks. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 696 | |
| 697 | >>> mock = MagicMock() |
| 698 | >>> result = mock(1, 2, 3) |
| 699 | >>> mock.first(a=3) |
| 700 | <MagicMock name='mock.first()' id='...'> |
| 701 | >>> mock.second() |
| 702 | <MagicMock name='mock.second()' id='...'> |
| 703 | >>> int(mock) |
| 704 | 1 |
| 705 | >>> result(1) |
| 706 | <MagicMock name='mock()()' id='...'> |
| 707 | >>> expected = [call(1, 2, 3), call.first(a=3), call.second(), |
| 708 | ... call.__int__(), call()(1)] |
| 709 | >>> mock.mock_calls == expected |
| 710 | True |
| 711 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 712 | Members of :attr:`mock_calls` are :data:`call` objects. These can be |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 713 | unpacked as tuples to get at the individual arguments. See |
| 714 | :ref:`calls as tuples <calls-as-tuples>`. |
| 715 | |
Chris Withers | 8ca0fa9 | 2018-12-03 21:31:37 +0000 | [diff] [blame] | 716 | .. note:: |
| 717 | |
| 718 | The way :attr:`mock_calls` are recorded means that where nested |
| 719 | calls are made, the parameters of ancestor calls are not recorded |
| 720 | and so will always compare equal: |
| 721 | |
| 722 | >>> mock = MagicMock() |
| 723 | >>> mock.top(a=3).bottom() |
| 724 | <MagicMock name='mock.top().bottom()' id='...'> |
| 725 | >>> mock.mock_calls |
| 726 | [call.top(a=3), call.top().bottom()] |
| 727 | >>> mock.mock_calls[-1] == call.top(a=-1).bottom() |
| 728 | True |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 729 | |
| 730 | .. attribute:: __class__ |
| 731 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 732 | Normally the :attr:`__class__` attribute of an object will return its type. |
| 733 | For a mock object with a :attr:`spec`, ``__class__`` returns the spec class |
| 734 | instead. This allows mock objects to pass :func:`isinstance` tests for the |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 735 | object they are replacing / masquerading as: |
| 736 | |
| 737 | >>> mock = Mock(spec=3) |
| 738 | >>> isinstance(mock, int) |
| 739 | True |
| 740 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 741 | :attr:`__class__` is assignable to, this allows a mock to pass an |
| 742 | :func:`isinstance` check without forcing you to use a spec: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 743 | |
| 744 | >>> mock = Mock() |
| 745 | >>> mock.__class__ = dict |
| 746 | >>> isinstance(mock, dict) |
| 747 | True |
| 748 | |
| 749 | .. class:: NonCallableMock(spec=None, wraps=None, name=None, spec_set=None, **kwargs) |
| 750 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 751 | A non-callable version of :class:`Mock`. The constructor parameters have the same |
| 752 | meaning of :class:`Mock`, with the exception of *return_value* and *side_effect* |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 753 | which have no meaning on a non-callable mock. |
| 754 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 755 | Mock objects that use a class or an instance as a :attr:`spec` or |
| 756 | :attr:`spec_set` are able to pass :func:`isinstance` tests: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 757 | |
| 758 | >>> mock = Mock(spec=SomeClass) |
| 759 | >>> isinstance(mock, SomeClass) |
| 760 | True |
| 761 | >>> mock = Mock(spec_set=SomeClass()) |
| 762 | >>> isinstance(mock, SomeClass) |
| 763 | True |
| 764 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 765 | The :class:`Mock` classes have support for mocking magic methods. See :ref:`magic |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 766 | methods <magic-methods>` for the full details. |
| 767 | |
| 768 | The mock classes and the :func:`patch` decorators all take arbitrary keyword |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 769 | arguments for configuration. For the :func:`patch` decorators the keywords are |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 770 | passed to the constructor of the mock being created. The keyword arguments |
| 771 | are for configuring attributes of the mock: |
| 772 | |
| 773 | >>> m = MagicMock(attribute=3, other='fish') |
| 774 | >>> m.attribute |
| 775 | 3 |
| 776 | >>> m.other |
| 777 | 'fish' |
| 778 | |
| 779 | The return value and side effect of child mocks can be set in the same way, |
| 780 | using dotted notation. As you can't use dotted names directly in a call you |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 781 | have to create a dictionary and unpack it using ``**``: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 782 | |
| 783 | >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} |
| 784 | >>> mock = Mock(some_attribute='eggs', **attrs) |
| 785 | >>> mock.some_attribute |
| 786 | 'eggs' |
| 787 | >>> mock.method() |
| 788 | 3 |
| 789 | >>> mock.other() |
| 790 | Traceback (most recent call last): |
| 791 | ... |
| 792 | KeyError |
| 793 | |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 794 | A callable mock which was created with a *spec* (or a *spec_set*) will |
| 795 | introspect the specification object's signature when matching calls to |
| 796 | the mock. Therefore, it can match the actual call's arguments regardless |
| 797 | of whether they were passed positionally or by name:: |
| 798 | |
| 799 | >>> def f(a, b, c): pass |
| 800 | ... |
| 801 | >>> mock = Mock(spec=f) |
| 802 | >>> mock(1, 2, c=3) |
| 803 | <Mock name='mock()' id='140161580456576'> |
| 804 | >>> mock.assert_called_with(1, 2, 3) |
| 805 | >>> mock.assert_called_with(a=1, b=2, c=3) |
| 806 | |
| 807 | This applies to :meth:`~Mock.assert_called_with`, |
| 808 | :meth:`~Mock.assert_called_once_with`, :meth:`~Mock.assert_has_calls` and |
| 809 | :meth:`~Mock.assert_any_call`. When :ref:`auto-speccing`, it will also |
| 810 | apply to method calls on the mock object. |
| 811 | |
| 812 | .. versionchanged:: 3.4 |
| 813 | Added signature introspection on specced and autospecced mock objects. |
| 814 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 815 | |
| 816 | .. class:: PropertyMock(*args, **kwargs) |
| 817 | |
| 818 | A mock intended to be used as a property, or other descriptor, on a class. |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 819 | :class:`PropertyMock` provides :meth:`__get__` and :meth:`__set__` methods |
| 820 | so you can specify a return value when it is fetched. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 821 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 822 | Fetching a :class:`PropertyMock` instance from an object calls the mock, with |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 823 | no args. Setting it calls the mock with the value being set. :: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 824 | |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 825 | >>> class Foo: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 826 | ... @property |
| 827 | ... def foo(self): |
| 828 | ... return 'something' |
| 829 | ... @foo.setter |
| 830 | ... def foo(self, value): |
| 831 | ... pass |
| 832 | ... |
| 833 | >>> with patch('__main__.Foo.foo', new_callable=PropertyMock) as mock_foo: |
| 834 | ... mock_foo.return_value = 'mockity-mock' |
| 835 | ... this_foo = Foo() |
Berker Peksag | 920f6db | 2015-09-10 21:41:15 +0300 | [diff] [blame] | 836 | ... print(this_foo.foo) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 837 | ... this_foo.foo = 6 |
| 838 | ... |
| 839 | mockity-mock |
| 840 | >>> mock_foo.mock_calls |
| 841 | [call(), call(6)] |
| 842 | |
Michael Foord | c287062 | 2012-04-13 16:57:22 +0100 | [diff] [blame] | 843 | Because of the way mock attributes are stored you can't directly attach a |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 844 | :class:`PropertyMock` to a mock object. Instead you can attach it to the mock type |
Michael Foord | c287062 | 2012-04-13 16:57:22 +0100 | [diff] [blame] | 845 | object:: |
| 846 | |
| 847 | >>> m = MagicMock() |
| 848 | >>> p = PropertyMock(return_value=3) |
| 849 | >>> type(m).foo = p |
| 850 | >>> m.foo |
| 851 | 3 |
| 852 | >>> p.assert_called_once_with() |
| 853 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 854 | |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 855 | .. class:: AsyncMock(spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, unsafe=False, **kwargs) |
| 856 | |
| 857 | An asynchronous version of :class:`Mock`. The :class:`AsyncMock` object will |
| 858 | behave so the object is recognized as an async function, and the result of a |
| 859 | call is an awaitable. |
| 860 | |
| 861 | >>> mock = AsyncMock() |
| 862 | >>> asyncio.iscoroutinefunction(mock) |
| 863 | True |
Xtreak | e7cb23b | 2019-05-21 14:17:17 +0530 | [diff] [blame] | 864 | >>> inspect.isawaitable(mock()) # doctest: +SKIP |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 865 | True |
| 866 | |
| 867 | The result of ``mock()`` is an async function which will have the outcome |
Lisa Roach | 3667e1e | 2019-09-29 21:56:47 -0700 | [diff] [blame] | 868 | of ``side_effect`` or ``return_value`` after it has been awaited: |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 869 | |
| 870 | - if ``side_effect`` is a function, the async function will return the |
| 871 | result of that function, |
| 872 | - if ``side_effect`` is an exception, the async function will raise the |
| 873 | exception, |
| 874 | - if ``side_effect`` is an iterable, the async function will return the |
| 875 | next value of the iterable, however, if the sequence of result is |
| 876 | exhausted, ``StopIteration`` is raised immediately, |
| 877 | - if ``side_effect`` is not defined, the async function will return the |
| 878 | value defined by ``return_value``, hence, by default, the async function |
| 879 | returns a new :class:`AsyncMock` object. |
| 880 | |
| 881 | |
| 882 | Setting the *spec* of a :class:`Mock` or :class:`MagicMock` to an async function |
| 883 | will result in a coroutine object being returned after calling. |
| 884 | |
| 885 | >>> async def async_func(): pass |
| 886 | ... |
| 887 | >>> mock = MagicMock(async_func) |
| 888 | >>> mock |
| 889 | <MagicMock spec='function' id='...'> |
Xtreak | e7cb23b | 2019-05-21 14:17:17 +0530 | [diff] [blame] | 890 | >>> mock() # doctest: +SKIP |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 891 | <coroutine object AsyncMockMixin._mock_call at ...> |
| 892 | |
Lisa Roach | 3667e1e | 2019-09-29 21:56:47 -0700 | [diff] [blame] | 893 | |
| 894 | Setting the *spec* of a :class:`Mock`, :class:`MagicMock`, or :class:`AsyncMock` |
| 895 | to a class with asynchronous and synchronous functions will automatically |
| 896 | detect the synchronous functions and set them as :class:`MagicMock` (if the |
| 897 | parent mock is :class:`AsyncMock` or :class:`MagicMock`) or :class:`Mock` (if |
| 898 | the parent mock is :class:`Mock`). All asynchronous functions will be |
| 899 | :class:`AsyncMock`. |
| 900 | |
| 901 | >>> class ExampleClass: |
| 902 | ... def sync_foo(): |
| 903 | ... pass |
| 904 | ... async def async_foo(): |
| 905 | ... pass |
| 906 | ... |
| 907 | >>> a_mock = AsyncMock(ExampleClass) |
| 908 | >>> a_mock.sync_foo |
| 909 | <MagicMock name='mock.sync_foo' id='...'> |
| 910 | >>> a_mock.async_foo |
| 911 | <AsyncMock name='mock.async_foo' id='...'> |
| 912 | >>> mock = Mock(ExampleClass) |
| 913 | >>> mock.sync_foo |
| 914 | <Mock name='mock.sync_foo' id='...'> |
| 915 | >>> mock.async_foo |
| 916 | <AsyncMock name='mock.async_foo' id='...'> |
| 917 | |
| 918 | |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 919 | .. method:: assert_awaited() |
| 920 | |
Lisa Roach | ef04851 | 2019-09-23 20:49:40 -0700 | [diff] [blame] | 921 | Assert that the mock was awaited at least once. Note that this is separate |
| 922 | from the object having been called, the ``await`` keyword must be used: |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 923 | |
| 924 | >>> mock = AsyncMock() |
Lisa Roach | ef04851 | 2019-09-23 20:49:40 -0700 | [diff] [blame] | 925 | >>> async def main(coroutine_mock): |
| 926 | ... await coroutine_mock |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 927 | ... |
Lisa Roach | ef04851 | 2019-09-23 20:49:40 -0700 | [diff] [blame] | 928 | >>> coroutine_mock = mock() |
| 929 | >>> mock.called |
| 930 | True |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 931 | >>> mock.assert_awaited() |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 932 | Traceback (most recent call last): |
| 933 | ... |
| 934 | AssertionError: Expected mock to have been awaited. |
Lisa Roach | ef04851 | 2019-09-23 20:49:40 -0700 | [diff] [blame] | 935 | >>> asyncio.run(main(coroutine_mock)) |
| 936 | >>> mock.assert_awaited() |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 937 | |
| 938 | .. method:: assert_awaited_once() |
| 939 | |
| 940 | Assert that the mock was awaited exactly once. |
| 941 | |
| 942 | >>> mock = AsyncMock() |
| 943 | >>> async def main(): |
| 944 | ... await mock() |
| 945 | ... |
| 946 | >>> asyncio.run(main()) |
| 947 | >>> mock.assert_awaited_once() |
| 948 | >>> asyncio.run(main()) |
| 949 | >>> mock.method.assert_awaited_once() |
| 950 | Traceback (most recent call last): |
| 951 | ... |
| 952 | AssertionError: Expected mock to have been awaited once. Awaited 2 times. |
| 953 | |
| 954 | .. method:: assert_awaited_with(*args, **kwargs) |
| 955 | |
| 956 | Assert that the last await was with the specified arguments. |
| 957 | |
| 958 | >>> mock = AsyncMock() |
| 959 | >>> async def main(*args, **kwargs): |
| 960 | ... await mock(*args, **kwargs) |
| 961 | ... |
| 962 | >>> asyncio.run(main('foo', bar='bar')) |
| 963 | >>> mock.assert_awaited_with('foo', bar='bar') |
| 964 | >>> mock.assert_awaited_with('other') |
| 965 | Traceback (most recent call last): |
| 966 | ... |
| 967 | AssertionError: expected call not found. |
| 968 | Expected: mock('other') |
| 969 | Actual: mock('foo', bar='bar') |
| 970 | |
| 971 | .. method:: assert_awaited_once_with(*args, **kwargs) |
| 972 | |
| 973 | Assert that the mock was awaited exactly once and with the specified |
| 974 | arguments. |
| 975 | |
| 976 | >>> mock = AsyncMock() |
| 977 | >>> async def main(*args, **kwargs): |
| 978 | ... await mock(*args, **kwargs) |
| 979 | ... |
| 980 | >>> asyncio.run(main('foo', bar='bar')) |
| 981 | >>> mock.assert_awaited_once_with('foo', bar='bar') |
| 982 | >>> asyncio.run(main('foo', bar='bar')) |
| 983 | >>> mock.assert_awaited_once_with('foo', bar='bar') |
| 984 | Traceback (most recent call last): |
| 985 | ... |
| 986 | AssertionError: Expected mock to have been awaited once. Awaited 2 times. |
| 987 | |
| 988 | .. method:: assert_any_await(*args, **kwargs) |
| 989 | |
| 990 | Assert the mock has ever been awaited with the specified arguments. |
| 991 | |
| 992 | >>> mock = AsyncMock() |
| 993 | >>> async def main(*args, **kwargs): |
| 994 | ... await mock(*args, **kwargs) |
| 995 | ... |
| 996 | >>> asyncio.run(main('foo', bar='bar')) |
| 997 | >>> asyncio.run(main('hello')) |
| 998 | >>> mock.assert_any_await('foo', bar='bar') |
| 999 | >>> mock.assert_any_await('other') |
| 1000 | Traceback (most recent call last): |
| 1001 | ... |
| 1002 | AssertionError: mock('other') await not found |
| 1003 | |
| 1004 | .. method:: assert_has_awaits(calls, any_order=False) |
| 1005 | |
| 1006 | Assert the mock has been awaited with the specified calls. |
| 1007 | The :attr:`await_args_list` list is checked for the awaits. |
| 1008 | |
Serhiy Storchaka | 138ccbb | 2019-11-12 16:57:03 +0200 | [diff] [blame] | 1009 | If *any_order* is false then the awaits must be |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 1010 | sequential. There can be extra calls before or after the |
| 1011 | specified awaits. |
| 1012 | |
Serhiy Storchaka | 138ccbb | 2019-11-12 16:57:03 +0200 | [diff] [blame] | 1013 | If *any_order* is true then the awaits can be in any order, but |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 1014 | they must all appear in :attr:`await_args_list`. |
| 1015 | |
| 1016 | >>> mock = AsyncMock() |
| 1017 | >>> async def main(*args, **kwargs): |
| 1018 | ... await mock(*args, **kwargs) |
| 1019 | ... |
| 1020 | >>> calls = [call("foo"), call("bar")] |
Lisa Roach | ef04851 | 2019-09-23 20:49:40 -0700 | [diff] [blame] | 1021 | >>> mock.assert_has_awaits(calls) |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 1022 | Traceback (most recent call last): |
| 1023 | ... |
Lisa Roach | ef04851 | 2019-09-23 20:49:40 -0700 | [diff] [blame] | 1024 | AssertionError: Awaits not found. |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 1025 | Expected: [call('foo'), call('bar')] |
Lisa Roach | ef04851 | 2019-09-23 20:49:40 -0700 | [diff] [blame] | 1026 | Actual: [] |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 1027 | >>> asyncio.run(main('foo')) |
| 1028 | >>> asyncio.run(main('bar')) |
Lisa Roach | ef04851 | 2019-09-23 20:49:40 -0700 | [diff] [blame] | 1029 | >>> mock.assert_has_awaits(calls) |
Lisa Roach | 77b3b77 | 2019-05-20 09:19:53 -0700 | [diff] [blame] | 1030 | |
| 1031 | .. method:: assert_not_awaited() |
| 1032 | |
| 1033 | Assert that the mock was never awaited. |
| 1034 | |
| 1035 | >>> mock = AsyncMock() |
| 1036 | >>> mock.assert_not_awaited() |
| 1037 | |
| 1038 | .. method:: reset_mock(*args, **kwargs) |
| 1039 | |
| 1040 | See :func:`Mock.reset_mock`. Also sets :attr:`await_count` to 0, |
| 1041 | :attr:`await_args` to None, and clears the :attr:`await_args_list`. |
| 1042 | |
| 1043 | .. attribute:: await_count |
| 1044 | |
| 1045 | An integer keeping track of how many times the mock object has been awaited. |
| 1046 | |
| 1047 | >>> mock = AsyncMock() |
| 1048 | >>> async def main(): |
| 1049 | ... await mock() |
| 1050 | ... |
| 1051 | >>> asyncio.run(main()) |
| 1052 | >>> mock.await_count |
| 1053 | 1 |
| 1054 | >>> asyncio.run(main()) |
| 1055 | >>> mock.await_count |
| 1056 | 2 |
| 1057 | |
| 1058 | .. attribute:: await_args |
| 1059 | |
| 1060 | This is either ``None`` (if the mock hasn’t been awaited), or the arguments that |
| 1061 | the mock was last awaited with. Functions the same as :attr:`Mock.call_args`. |
| 1062 | |
| 1063 | >>> mock = AsyncMock() |
| 1064 | >>> async def main(*args): |
| 1065 | ... await mock(*args) |
| 1066 | ... |
| 1067 | >>> mock.await_args |
| 1068 | >>> asyncio.run(main('foo')) |
| 1069 | >>> mock.await_args |
| 1070 | call('foo') |
| 1071 | >>> asyncio.run(main('bar')) |
| 1072 | >>> mock.await_args |
| 1073 | call('bar') |
| 1074 | |
| 1075 | |
| 1076 | .. attribute:: await_args_list |
| 1077 | |
| 1078 | This is a list of all the awaits made to the mock object in sequence (so the |
| 1079 | length of the list is the number of times it has been awaited). Before any |
| 1080 | awaits have been made it is an empty list. |
| 1081 | |
| 1082 | >>> mock = AsyncMock() |
| 1083 | >>> async def main(*args): |
| 1084 | ... await mock(*args) |
| 1085 | ... |
| 1086 | >>> mock.await_args_list |
| 1087 | [] |
| 1088 | >>> asyncio.run(main('foo')) |
| 1089 | >>> mock.await_args_list |
| 1090 | [call('foo')] |
| 1091 | >>> asyncio.run(main('bar')) |
| 1092 | >>> mock.await_args_list |
| 1093 | [call('foo'), call('bar')] |
| 1094 | |
| 1095 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1096 | Calling |
| 1097 | ~~~~~~~ |
| 1098 | |
| 1099 | Mock objects are callable. The call will return the value set as the |
| 1100 | :attr:`~Mock.return_value` attribute. The default return value is a new Mock |
| 1101 | object; it is created the first time the return value is accessed (either |
| 1102 | explicitly or by calling the Mock) - but it is stored and the same one |
| 1103 | returned each time. |
| 1104 | |
| 1105 | Calls made to the object will be recorded in the attributes |
| 1106 | like :attr:`~Mock.call_args` and :attr:`~Mock.call_args_list`. |
| 1107 | |
| 1108 | If :attr:`~Mock.side_effect` is set then it will be called after the call has |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1109 | been recorded, so if :attr:`side_effect` raises an exception the call is still |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1110 | recorded. |
| 1111 | |
| 1112 | The simplest way to make a mock raise an exception when called is to make |
| 1113 | :attr:`~Mock.side_effect` an exception class or instance: |
| 1114 | |
| 1115 | >>> m = MagicMock(side_effect=IndexError) |
| 1116 | >>> m(1, 2, 3) |
| 1117 | Traceback (most recent call last): |
| 1118 | ... |
| 1119 | IndexError |
| 1120 | >>> m.mock_calls |
| 1121 | [call(1, 2, 3)] |
| 1122 | >>> m.side_effect = KeyError('Bang!') |
| 1123 | >>> m('two', 'three', 'four') |
| 1124 | Traceback (most recent call last): |
| 1125 | ... |
| 1126 | KeyError: 'Bang!' |
| 1127 | >>> m.mock_calls |
| 1128 | [call(1, 2, 3), call('two', 'three', 'four')] |
| 1129 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1130 | If :attr:`side_effect` is a function then whatever that function returns is what |
| 1131 | calls to the mock return. The :attr:`side_effect` function is called with the |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1132 | same arguments as the mock. This allows you to vary the return value of the |
| 1133 | call dynamically, based on the input: |
| 1134 | |
| 1135 | >>> def side_effect(value): |
| 1136 | ... return value + 1 |
| 1137 | ... |
| 1138 | >>> m = MagicMock(side_effect=side_effect) |
| 1139 | >>> m(1) |
| 1140 | 2 |
| 1141 | >>> m(2) |
| 1142 | 3 |
| 1143 | >>> m.mock_calls |
| 1144 | [call(1), call(2)] |
| 1145 | |
| 1146 | If you want the mock to still return the default return value (a new mock), or |
| 1147 | any set return value, then there are two ways of doing this. Either return |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1148 | :attr:`mock.return_value` from inside :attr:`side_effect`, or return :data:`DEFAULT`: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1149 | |
| 1150 | >>> m = MagicMock() |
| 1151 | >>> def side_effect(*args, **kwargs): |
| 1152 | ... return m.return_value |
| 1153 | ... |
| 1154 | >>> m.side_effect = side_effect |
| 1155 | >>> m.return_value = 3 |
| 1156 | >>> m() |
| 1157 | 3 |
| 1158 | >>> def side_effect(*args, **kwargs): |
| 1159 | ... return DEFAULT |
| 1160 | ... |
| 1161 | >>> m.side_effect = side_effect |
| 1162 | >>> m() |
| 1163 | 3 |
| 1164 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1165 | To remove a :attr:`side_effect`, and return to the default behaviour, set the |
| 1166 | :attr:`side_effect` to ``None``: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1167 | |
| 1168 | >>> m = MagicMock(return_value=6) |
| 1169 | >>> def side_effect(*args, **kwargs): |
| 1170 | ... return 3 |
| 1171 | ... |
| 1172 | >>> m.side_effect = side_effect |
| 1173 | >>> m() |
| 1174 | 3 |
| 1175 | >>> m.side_effect = None |
| 1176 | >>> m() |
| 1177 | 6 |
| 1178 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1179 | The :attr:`side_effect` can also be any iterable object. Repeated calls to the mock |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1180 | will return values from the iterable (until the iterable is exhausted and |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1181 | a :exc:`StopIteration` is raised): |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1182 | |
| 1183 | >>> m = MagicMock(side_effect=[1, 2, 3]) |
| 1184 | >>> m() |
| 1185 | 1 |
| 1186 | >>> m() |
| 1187 | 2 |
| 1188 | >>> m() |
| 1189 | 3 |
| 1190 | >>> m() |
| 1191 | Traceback (most recent call last): |
| 1192 | ... |
| 1193 | StopIteration |
| 1194 | |
Michael Foord | 2cd4873 | 2012-04-21 15:52:11 +0100 | [diff] [blame] | 1195 | If any members of the iterable are exceptions they will be raised instead of |
| 1196 | returned:: |
| 1197 | |
| 1198 | >>> iterable = (33, ValueError, 66) |
| 1199 | >>> m = MagicMock(side_effect=iterable) |
| 1200 | >>> m() |
| 1201 | 33 |
| 1202 | >>> m() |
| 1203 | Traceback (most recent call last): |
| 1204 | ... |
| 1205 | ValueError |
| 1206 | >>> m() |
| 1207 | 66 |
| 1208 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1209 | |
| 1210 | .. _deleting-attributes: |
| 1211 | |
| 1212 | Deleting Attributes |
| 1213 | ~~~~~~~~~~~~~~~~~~~ |
| 1214 | |
| 1215 | Mock objects create attributes on demand. This allows them to pretend to be |
| 1216 | objects of any type. |
| 1217 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1218 | You may want a mock object to return ``False`` to a :func:`hasattr` call, or raise an |
| 1219 | :exc:`AttributeError` when an attribute is fetched. You can do this by providing |
| 1220 | an object as a :attr:`spec` for a mock, but that isn't always convenient. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1221 | |
| 1222 | You "block" attributes by deleting them. Once deleted, accessing an attribute |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1223 | will raise an :exc:`AttributeError`. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1224 | |
| 1225 | >>> mock = MagicMock() |
| 1226 | >>> hasattr(mock, 'm') |
| 1227 | True |
| 1228 | >>> del mock.m |
| 1229 | >>> hasattr(mock, 'm') |
| 1230 | False |
| 1231 | >>> del mock.f |
| 1232 | >>> mock.f |
| 1233 | Traceback (most recent call last): |
| 1234 | ... |
| 1235 | AttributeError: f |
| 1236 | |
| 1237 | |
Michael Foord | f575230 | 2013-03-18 15:04:03 -0700 | [diff] [blame] | 1238 | Mock names and the name attribute |
| 1239 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 1240 | |
| 1241 | Since "name" is an argument to the :class:`Mock` constructor, if you want your |
| 1242 | mock object to have a "name" attribute you can't just pass it in at creation |
| 1243 | time. There are two alternatives. One option is to use |
| 1244 | :meth:`~Mock.configure_mock`:: |
| 1245 | |
| 1246 | >>> mock = MagicMock() |
| 1247 | >>> mock.configure_mock(name='my_name') |
| 1248 | >>> mock.name |
| 1249 | 'my_name' |
| 1250 | |
| 1251 | A simpler option is to simply set the "name" attribute after mock creation:: |
| 1252 | |
| 1253 | >>> mock = MagicMock() |
| 1254 | >>> mock.name = "foo" |
| 1255 | |
| 1256 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1257 | Attaching Mocks as Attributes |
| 1258 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 1259 | |
| 1260 | When you attach a mock as an attribute of another mock (or as the return |
| 1261 | value) it becomes a "child" of that mock. Calls to the child are recorded in |
| 1262 | the :attr:`~Mock.method_calls` and :attr:`~Mock.mock_calls` attributes of the |
| 1263 | parent. This is useful for configuring child mocks and then attaching them to |
| 1264 | the parent, or for attaching mocks to a parent that records all calls to the |
| 1265 | children and allows you to make assertions about the order of calls between |
| 1266 | mocks: |
| 1267 | |
| 1268 | >>> parent = MagicMock() |
| 1269 | >>> child1 = MagicMock(return_value=None) |
| 1270 | >>> child2 = MagicMock(return_value=None) |
| 1271 | >>> parent.child1 = child1 |
| 1272 | >>> parent.child2 = child2 |
| 1273 | >>> child1(1) |
| 1274 | >>> child2(2) |
| 1275 | >>> parent.mock_calls |
| 1276 | [call.child1(1), call.child2(2)] |
| 1277 | |
| 1278 | The exception to this is if the mock has a name. This allows you to prevent |
| 1279 | the "parenting" if for some reason you don't want it to happen. |
| 1280 | |
| 1281 | >>> mock = MagicMock() |
| 1282 | >>> not_a_child = MagicMock(name='not-a-child') |
| 1283 | >>> mock.attribute = not_a_child |
| 1284 | >>> mock.attribute() |
| 1285 | <MagicMock name='not-a-child()' id='...'> |
| 1286 | >>> mock.mock_calls |
| 1287 | [] |
| 1288 | |
| 1289 | Mocks created for you by :func:`patch` are automatically given names. To |
| 1290 | attach mocks that have names to a parent you use the :meth:`~Mock.attach_mock` |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1291 | method:: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1292 | |
| 1293 | >>> thing1 = object() |
| 1294 | >>> thing2 = object() |
| 1295 | >>> parent = MagicMock() |
| 1296 | >>> with patch('__main__.thing1', return_value=None) as child1: |
| 1297 | ... with patch('__main__.thing2', return_value=None) as child2: |
| 1298 | ... parent.attach_mock(child1, 'child1') |
| 1299 | ... parent.attach_mock(child2, 'child2') |
| 1300 | ... child1('one') |
| 1301 | ... child2('two') |
| 1302 | ... |
| 1303 | >>> parent.mock_calls |
| 1304 | [call.child1('one'), call.child2('two')] |
| 1305 | |
| 1306 | |
| 1307 | .. [#] The only exceptions are magic methods and attributes (those that have |
| 1308 | leading and trailing double underscores). Mock doesn't create these but |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1309 | instead raises an :exc:`AttributeError`. This is because the interpreter |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1310 | will often implicitly request these methods, and gets *very* confused to |
| 1311 | get a new Mock object when it expects a magic method. If you need magic |
| 1312 | method support see :ref:`magic methods <magic-methods>`. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1313 | |
| 1314 | |
| 1315 | The patchers |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 1316 | ------------ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1317 | |
| 1318 | The patch decorators are used for patching objects only within the scope of |
| 1319 | the function they decorate. They automatically handle the unpatching for you, |
| 1320 | even if exceptions are raised. All of these functions can also be used in with |
| 1321 | statements or as class decorators. |
| 1322 | |
| 1323 | |
| 1324 | patch |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 1325 | ~~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1326 | |
| 1327 | .. note:: |
| 1328 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1329 | :func:`patch` is straightforward to use. The key is to do the patching in the |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1330 | right namespace. See the section `where to patch`_. |
| 1331 | |
| 1332 | .. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) |
| 1333 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1334 | :func:`patch` acts as a function decorator, class decorator or a context |
| 1335 | manager. Inside the body of the function or with statement, the *target* |
| 1336 | is patched with a *new* object. When the function/with statement exits |
Michael Foord | 54b3db8 | 2012-03-28 15:08:08 +0100 | [diff] [blame] | 1337 | the patch is undone. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1338 | |
Mario Corchero | f5e7f39 | 2019-09-09 15:18:06 +0100 | [diff] [blame] | 1339 | If *new* is omitted, then the target is replaced with an |
| 1340 | :class:`AsyncMock` if the patched object is an async function or |
| 1341 | a :class:`MagicMock` otherwise. |
| 1342 | If :func:`patch` is used as a decorator and *new* is |
Michael Foord | 54b3db8 | 2012-03-28 15:08:08 +0100 | [diff] [blame] | 1343 | omitted, the created mock is passed in as an extra argument to the |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1344 | decorated function. If :func:`patch` is used as a context manager the created |
Michael Foord | 54b3db8 | 2012-03-28 15:08:08 +0100 | [diff] [blame] | 1345 | mock is returned by the context manager. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1346 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1347 | *target* should be a string in the form ``'package.module.ClassName'``. The |
| 1348 | *target* is imported and the specified object replaced with the *new* |
| 1349 | object, so the *target* must be importable from the environment you are |
| 1350 | calling :func:`patch` from. The target is imported when the decorated function |
Michael Foord | 54b3db8 | 2012-03-28 15:08:08 +0100 | [diff] [blame] | 1351 | is executed, not at decoration time. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1352 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1353 | The *spec* and *spec_set* keyword arguments are passed to the :class:`MagicMock` |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1354 | if patch is creating one for you. |
| 1355 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1356 | In addition you can pass ``spec=True`` or ``spec_set=True``, which causes |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1357 | patch to pass in the object being mocked as the spec/spec_set object. |
| 1358 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1359 | *new_callable* allows you to specify a different class, or callable object, |
Mario Corchero | f5e7f39 | 2019-09-09 15:18:06 +0100 | [diff] [blame] | 1360 | that will be called to create the *new* object. By default :class:`AsyncMock` |
| 1361 | is used for async functions and :class:`MagicMock` for the rest. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1362 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1363 | A more powerful form of *spec* is *autospec*. If you set ``autospec=True`` |
Georg Brandl | 8ed75cd | 2014-10-31 10:25:48 +0100 | [diff] [blame] | 1364 | then the mock will be created with a spec from the object being replaced. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1365 | All attributes of the mock will also have the spec of the corresponding |
| 1366 | attribute of the object being replaced. Methods and functions being mocked |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1367 | will have their arguments checked and will raise a :exc:`TypeError` if they are |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1368 | called with the wrong signature. For mocks |
| 1369 | replacing a class, their return value (the 'instance') will have the same |
| 1370 | spec as the class. See the :func:`create_autospec` function and |
| 1371 | :ref:`auto-speccing`. |
| 1372 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1373 | Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1374 | arbitrary object as the spec instead of the one being replaced. |
| 1375 | |
Pablo Galindo | d6acf17 | 2019-01-09 21:43:24 +0000 | [diff] [blame] | 1376 | By default :func:`patch` will fail to replace attributes that don't exist. |
| 1377 | If you pass in ``create=True``, and the attribute doesn't exist, patch will |
| 1378 | create the attribute for you when the patched function is called, and delete |
| 1379 | it again after the patched function has exited. This is useful for writing |
| 1380 | tests against attributes that your production code creates at runtime. It is |
| 1381 | off by default because it can be dangerous. With it switched on you can |
| 1382 | write passing tests against APIs that don't actually exist! |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1383 | |
Michael Foord | fddcfa2 | 2014-04-14 16:25:20 -0400 | [diff] [blame] | 1384 | .. note:: |
| 1385 | |
| 1386 | .. versionchanged:: 3.5 |
| 1387 | If you are patching builtins in a module then you don't |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1388 | need to pass ``create=True``, it will be added by default. |
Michael Foord | fddcfa2 | 2014-04-14 16:25:20 -0400 | [diff] [blame] | 1389 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1390 | Patch can be used as a :class:`TestCase` class decorator. It works by |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1391 | decorating each test method in the class. This reduces the boilerplate |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1392 | code when your test methods share a common patchings set. :func:`patch` finds |
| 1393 | tests by looking for method names that start with ``patch.TEST_PREFIX``. |
| 1394 | By default this is ``'test'``, which matches the way :mod:`unittest` finds tests. |
| 1395 | You can specify an alternative prefix by setting ``patch.TEST_PREFIX``. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1396 | |
| 1397 | Patch can be used as a context manager, with the with statement. Here the |
| 1398 | patching applies to the indented block after the with statement. If you |
| 1399 | use "as" then the patched object will be bound to the name after the |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1400 | "as"; very useful if :func:`patch` is creating a mock object for you. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1401 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1402 | :func:`patch` takes arbitrary keyword arguments. These will be passed to |
| 1403 | the :class:`Mock` (or *new_callable*) on construction. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1404 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1405 | ``patch.dict(...)``, ``patch.multiple(...)`` and ``patch.object(...)`` are |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1406 | available for alternate use-cases. |
| 1407 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1408 | :func:`patch` as function decorator, creating the mock for you and passing it into |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1409 | the decorated function:: |
Michael Foord | 9015536 | 2012-03-28 15:32:08 +0100 | [diff] [blame] | 1410 | |
| 1411 | >>> @patch('__main__.SomeClass') |
Michael Foord | 324b58b | 2012-03-28 15:49:08 +0100 | [diff] [blame] | 1412 | ... def function(normal_argument, mock_class): |
Michael Foord | 9015536 | 2012-03-28 15:32:08 +0100 | [diff] [blame] | 1413 | ... print(mock_class is SomeClass) |
| 1414 | ... |
Michael Foord | 324b58b | 2012-03-28 15:49:08 +0100 | [diff] [blame] | 1415 | >>> function(None) |
Michael Foord | 9015536 | 2012-03-28 15:32:08 +0100 | [diff] [blame] | 1416 | True |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1417 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1418 | Patching a class replaces the class with a :class:`MagicMock` *instance*. If the |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1419 | class is instantiated in the code under test then it will be the |
| 1420 | :attr:`~Mock.return_value` of the mock that will be used. |
| 1421 | |
| 1422 | If the class is instantiated multiple times you could use |
| 1423 | :attr:`~Mock.side_effect` to return a new mock each time. Alternatively you |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1424 | can set the *return_value* to be anything you want. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1425 | |
| 1426 | To configure return values on methods of *instances* on the patched class |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1427 | you must do this on the :attr:`return_value`. For example:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1428 | |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 1429 | >>> class Class: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1430 | ... def method(self): |
| 1431 | ... pass |
| 1432 | ... |
| 1433 | >>> with patch('__main__.Class') as MockClass: |
| 1434 | ... instance = MockClass.return_value |
| 1435 | ... instance.method.return_value = 'foo' |
| 1436 | ... assert Class() is instance |
| 1437 | ... assert Class().method() == 'foo' |
| 1438 | ... |
| 1439 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1440 | If you use *spec* or *spec_set* and :func:`patch` is replacing a *class*, then the |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1441 | return value of the created mock will have the same spec. :: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1442 | |
| 1443 | >>> Original = Class |
| 1444 | >>> patcher = patch('__main__.Class', spec=True) |
| 1445 | >>> MockClass = patcher.start() |
| 1446 | >>> instance = MockClass() |
| 1447 | >>> assert isinstance(instance, Original) |
| 1448 | >>> patcher.stop() |
| 1449 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1450 | The *new_callable* argument is useful where you want to use an alternative |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1451 | class to the default :class:`MagicMock` for the created mock. For example, if |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1452 | you wanted a :class:`NonCallableMock` to be used:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1453 | |
| 1454 | >>> thing = object() |
| 1455 | >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing: |
| 1456 | ... assert thing is mock_thing |
| 1457 | ... thing() |
| 1458 | ... |
| 1459 | Traceback (most recent call last): |
| 1460 | ... |
| 1461 | TypeError: 'NonCallableMock' object is not callable |
| 1462 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1463 | Another use case might be to replace an object with an :class:`io.StringIO` instance:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1464 | |
Serhiy Storchaka | e79be87 | 2013-08-17 00:09:55 +0300 | [diff] [blame] | 1465 | >>> from io import StringIO |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1466 | >>> def foo(): |
Berker Peksag | 920f6db | 2015-09-10 21:41:15 +0300 | [diff] [blame] | 1467 | ... print('Something') |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1468 | ... |
| 1469 | >>> @patch('sys.stdout', new_callable=StringIO) |
| 1470 | ... def test(mock_stdout): |
| 1471 | ... foo() |
| 1472 | ... assert mock_stdout.getvalue() == 'Something\n' |
| 1473 | ... |
| 1474 | >>> test() |
| 1475 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1476 | When :func:`patch` is creating a mock for you, it is common that the first thing |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1477 | you need to do is to configure the mock. Some of that configuration can be done |
| 1478 | in the call to patch. Any arbitrary keywords you pass into the call will be |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1479 | used to set attributes on the created mock:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1480 | |
| 1481 | >>> patcher = patch('__main__.thing', first='one', second='two') |
| 1482 | >>> mock_thing = patcher.start() |
| 1483 | >>> mock_thing.first |
| 1484 | 'one' |
| 1485 | >>> mock_thing.second |
| 1486 | 'two' |
| 1487 | |
| 1488 | As well as attributes on the created mock attributes, like the |
| 1489 | :attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can |
| 1490 | also be configured. These aren't syntactically valid to pass in directly as |
| 1491 | keyword arguments, but a dictionary with these as keys can still be expanded |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1492 | into a :func:`patch` call using ``**``:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1493 | |
| 1494 | >>> config = {'method.return_value': 3, 'other.side_effect': KeyError} |
| 1495 | >>> patcher = patch('__main__.thing', **config) |
| 1496 | >>> mock_thing = patcher.start() |
| 1497 | >>> mock_thing.method() |
| 1498 | 3 |
| 1499 | >>> mock_thing.other() |
| 1500 | Traceback (most recent call last): |
| 1501 | ... |
| 1502 | KeyError |
| 1503 | |
Pablo Galindo | d6acf17 | 2019-01-09 21:43:24 +0000 | [diff] [blame] | 1504 | By default, attempting to patch a function in a module (or a method or an |
| 1505 | attribute in a class) that does not exist will fail with :exc:`AttributeError`:: |
| 1506 | |
| 1507 | >>> @patch('sys.non_existing_attribute', 42) |
| 1508 | ... def test(): |
| 1509 | ... assert sys.non_existing_attribute == 42 |
| 1510 | ... |
| 1511 | >>> test() |
| 1512 | Traceback (most recent call last): |
| 1513 | ... |
| 1514 | AttributeError: <module 'sys' (built-in)> does not have the attribute 'non_existing' |
| 1515 | |
| 1516 | but adding ``create=True`` in the call to :func:`patch` will make the previous example |
| 1517 | work as expected:: |
| 1518 | |
| 1519 | >>> @patch('sys.non_existing_attribute', 42, create=True) |
| 1520 | ... def test(mock_stdout): |
| 1521 | ... assert sys.non_existing_attribute == 42 |
| 1522 | ... |
| 1523 | >>> test() |
| 1524 | |
Mario Corchero | f5e7f39 | 2019-09-09 15:18:06 +0100 | [diff] [blame] | 1525 | .. versionchanged:: 3.8 |
| 1526 | |
| 1527 | :func:`patch` now returns an :class:`AsyncMock` if the target is an async function. |
| 1528 | |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1529 | |
| 1530 | patch.object |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 1531 | ~~~~~~~~~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1532 | |
| 1533 | .. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) |
| 1534 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1535 | patch the named member (*attribute*) on an object (*target*) with a mock |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1536 | object. |
| 1537 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1538 | :func:`patch.object` can be used as a decorator, class decorator or a context |
| 1539 | manager. Arguments *new*, *spec*, *create*, *spec_set*, *autospec* and |
| 1540 | *new_callable* have the same meaning as for :func:`patch`. Like :func:`patch`, |
| 1541 | :func:`patch.object` takes arbitrary keyword arguments for configuring the mock |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1542 | object it creates. |
| 1543 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1544 | When used as a class decorator :func:`patch.object` honours ``patch.TEST_PREFIX`` |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1545 | for choosing which methods to wrap. |
| 1546 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1547 | You can either call :func:`patch.object` with three arguments or two arguments. The |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1548 | three argument form takes the object to be patched, the attribute name and the |
| 1549 | object to replace the attribute with. |
| 1550 | |
| 1551 | When calling with the two argument form you omit the replacement object, and a |
| 1552 | mock is created for you and passed in as an extra argument to the decorated |
| 1553 | function: |
| 1554 | |
| 1555 | >>> @patch.object(SomeClass, 'class_method') |
| 1556 | ... def test(mock_method): |
| 1557 | ... SomeClass.class_method(3) |
| 1558 | ... mock_method.assert_called_with(3) |
| 1559 | ... |
| 1560 | >>> test() |
| 1561 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1562 | *spec*, *create* and the other arguments to :func:`patch.object` have the same |
| 1563 | meaning as they do for :func:`patch`. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1564 | |
| 1565 | |
| 1566 | patch.dict |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 1567 | ~~~~~~~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1568 | |
| 1569 | .. function:: patch.dict(in_dict, values=(), clear=False, **kwargs) |
| 1570 | |
| 1571 | Patch a dictionary, or dictionary like object, and restore the dictionary |
| 1572 | to its original state after the test. |
| 1573 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1574 | *in_dict* can be a dictionary or a mapping like container. If it is a |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1575 | mapping then it must at least support getting, setting and deleting items |
| 1576 | plus iterating over keys. |
| 1577 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1578 | *in_dict* can also be a string specifying the name of the dictionary, which |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1579 | will then be fetched by importing it. |
| 1580 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1581 | *values* can be a dictionary of values to set in the dictionary. *values* |
| 1582 | can also be an iterable of ``(key, value)`` pairs. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1583 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1584 | If *clear* is true then the dictionary will be cleared before the new |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1585 | values are set. |
| 1586 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1587 | :func:`patch.dict` can also be called with arbitrary keyword arguments to set |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1588 | values in the dictionary. |
| 1589 | |
Mario Corchero | 0453081 | 2019-05-28 13:53:31 +0100 | [diff] [blame] | 1590 | .. versionchanged:: 3.8 |
| 1591 | |
| 1592 | :func:`patch.dict` now returns the patched dictionary when used as a context |
| 1593 | manager. |
| 1594 | |
Emmanuel Arias | 31a82e2 | 2019-09-12 08:29:54 -0300 | [diff] [blame] | 1595 | :func:`patch.dict` can be used as a context manager, decorator or class |
| 1596 | decorator: |
| 1597 | |
| 1598 | >>> foo = {} |
| 1599 | >>> @patch.dict(foo, {'newkey': 'newvalue'}) |
| 1600 | ... def test(): |
| 1601 | ... assert foo == {'newkey': 'newvalue'} |
| 1602 | >>> test() |
| 1603 | >>> assert foo == {} |
| 1604 | |
| 1605 | When used as a class decorator :func:`patch.dict` honours |
| 1606 | ``patch.TEST_PREFIX`` (default to ``'test'``) for choosing which methods to wrap: |
| 1607 | |
| 1608 | >>> import os |
| 1609 | >>> import unittest |
| 1610 | >>> from unittest.mock import patch |
| 1611 | >>> @patch.dict('os.environ', {'newkey': 'newvalue'}) |
| 1612 | ... class TestSample(unittest.TestCase): |
| 1613 | ... def test_sample(self): |
| 1614 | ... self.assertEqual(os.environ['newkey'], 'newvalue') |
| 1615 | |
| 1616 | If you want to use a different prefix for your test, you can inform the |
| 1617 | patchers of the different prefix by setting ``patch.TEST_PREFIX``. For |
| 1618 | more details about how to change the value of see :ref:`test-prefix`. |
| 1619 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1620 | :func:`patch.dict` can be used to add members to a dictionary, or simply let a test |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1621 | change a dictionary, and ensure the dictionary is restored when the test |
| 1622 | ends. |
| 1623 | |
| 1624 | >>> foo = {} |
Mario Corchero | 0453081 | 2019-05-28 13:53:31 +0100 | [diff] [blame] | 1625 | >>> with patch.dict(foo, {'newkey': 'newvalue'}) as patched_foo: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1626 | ... assert foo == {'newkey': 'newvalue'} |
Mario Corchero | 0453081 | 2019-05-28 13:53:31 +0100 | [diff] [blame] | 1627 | ... assert patched_foo == {'newkey': 'newvalue'} |
| 1628 | ... # You can add, update or delete keys of foo (or patched_foo, it's the same dict) |
| 1629 | ... patched_foo['spam'] = 'eggs' |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1630 | ... |
| 1631 | >>> assert foo == {} |
Mario Corchero | 0453081 | 2019-05-28 13:53:31 +0100 | [diff] [blame] | 1632 | >>> assert patched_foo == {} |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1633 | |
| 1634 | >>> import os |
| 1635 | >>> with patch.dict('os.environ', {'newkey': 'newvalue'}): |
Berker Peksag | 920f6db | 2015-09-10 21:41:15 +0300 | [diff] [blame] | 1636 | ... print(os.environ['newkey']) |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1637 | ... |
| 1638 | newvalue |
| 1639 | >>> assert 'newkey' not in os.environ |
| 1640 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1641 | Keywords can be used in the :func:`patch.dict` call to set values in the dictionary: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1642 | |
| 1643 | >>> mymodule = MagicMock() |
| 1644 | >>> mymodule.function.return_value = 'fish' |
| 1645 | >>> with patch.dict('sys.modules', mymodule=mymodule): |
| 1646 | ... import mymodule |
| 1647 | ... mymodule.function('some', 'args') |
| 1648 | ... |
| 1649 | 'fish' |
| 1650 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1651 | :func:`patch.dict` can be used with dictionary like objects that aren't actually |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1652 | dictionaries. At the very minimum they must support item getting, setting, |
| 1653 | deleting and either iteration or membership test. This corresponds to the |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1654 | magic methods :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__` and either |
| 1655 | :meth:`__iter__` or :meth:`__contains__`. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1656 | |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 1657 | >>> class Container: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1658 | ... def __init__(self): |
| 1659 | ... self.values = {} |
| 1660 | ... def __getitem__(self, name): |
| 1661 | ... return self.values[name] |
| 1662 | ... def __setitem__(self, name, value): |
| 1663 | ... self.values[name] = value |
| 1664 | ... def __delitem__(self, name): |
| 1665 | ... del self.values[name] |
| 1666 | ... def __iter__(self): |
| 1667 | ... return iter(self.values) |
| 1668 | ... |
| 1669 | >>> thing = Container() |
| 1670 | >>> thing['one'] = 1 |
| 1671 | >>> with patch.dict(thing, one=2, two=3): |
| 1672 | ... assert thing['one'] == 2 |
| 1673 | ... assert thing['two'] == 3 |
| 1674 | ... |
| 1675 | >>> assert thing['one'] == 1 |
| 1676 | >>> assert list(thing) == ['one'] |
| 1677 | |
| 1678 | |
| 1679 | patch.multiple |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 1680 | ~~~~~~~~~~~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1681 | |
| 1682 | .. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) |
| 1683 | |
| 1684 | Perform multiple patches in a single call. It takes the object to be |
| 1685 | patched (either as an object or a string to fetch the object by importing) |
| 1686 | and keyword arguments for the patches:: |
| 1687 | |
| 1688 | with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'): |
| 1689 | ... |
| 1690 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1691 | Use :data:`DEFAULT` as the value if you want :func:`patch.multiple` to create |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1692 | mocks for you. In this case the created mocks are passed into a decorated |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1693 | function by keyword, and a dictionary is returned when :func:`patch.multiple` is |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1694 | used as a context manager. |
| 1695 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1696 | :func:`patch.multiple` can be used as a decorator, class decorator or a context |
| 1697 | manager. The arguments *spec*, *spec_set*, *create*, *autospec* and |
| 1698 | *new_callable* have the same meaning as for :func:`patch`. These arguments will |
| 1699 | be applied to *all* patches done by :func:`patch.multiple`. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1700 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1701 | When used as a class decorator :func:`patch.multiple` honours ``patch.TEST_PREFIX`` |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1702 | for choosing which methods to wrap. |
| 1703 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1704 | If you want :func:`patch.multiple` to create mocks for you, then you can use |
| 1705 | :data:`DEFAULT` as the value. If you use :func:`patch.multiple` as a decorator |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1706 | then the created mocks are passed into the decorated function by keyword. :: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1707 | |
| 1708 | >>> thing = object() |
| 1709 | >>> other = object() |
| 1710 | |
| 1711 | >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) |
| 1712 | ... def test_function(thing, other): |
| 1713 | ... assert isinstance(thing, MagicMock) |
| 1714 | ... assert isinstance(other, MagicMock) |
| 1715 | ... |
| 1716 | >>> test_function() |
| 1717 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1718 | :func:`patch.multiple` can be nested with other ``patch`` decorators, but put arguments |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1719 | passed by keyword *after* any of the standard arguments created by :func:`patch`:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1720 | |
| 1721 | >>> @patch('sys.exit') |
| 1722 | ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) |
| 1723 | ... def test_function(mock_exit, other, thing): |
| 1724 | ... assert 'other' in repr(other) |
| 1725 | ... assert 'thing' in repr(thing) |
| 1726 | ... assert 'exit' in repr(mock_exit) |
| 1727 | ... |
| 1728 | >>> test_function() |
| 1729 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1730 | If :func:`patch.multiple` is used as a context manager, the value returned by the |
Joan Massich | dc69f69 | 2019-03-18 00:34:22 +0100 | [diff] [blame] | 1731 | context manager is a dictionary where created mocks are keyed by name:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1732 | |
| 1733 | >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values: |
| 1734 | ... assert 'other' in repr(values['other']) |
| 1735 | ... assert 'thing' in repr(values['thing']) |
| 1736 | ... assert values['thing'] is thing |
| 1737 | ... assert values['other'] is other |
| 1738 | ... |
| 1739 | |
| 1740 | |
| 1741 | .. _start-and-stop: |
| 1742 | |
| 1743 | patch methods: start and stop |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 1744 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1745 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1746 | All the patchers have :meth:`start` and :meth:`stop` methods. These make it simpler to do |
| 1747 | patching in ``setUp`` methods or where you want to do multiple patches without |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1748 | nesting decorators or with statements. |
| 1749 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1750 | To use them call :func:`patch`, :func:`patch.object` or :func:`patch.dict` as |
| 1751 | normal and keep a reference to the returned ``patcher`` object. You can then |
| 1752 | call :meth:`start` to put the patch in place and :meth:`stop` to undo it. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1753 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1754 | If you are using :func:`patch` to create a mock for you then it will be returned by |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1755 | the call to ``patcher.start``. :: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1756 | |
| 1757 | >>> patcher = patch('package.module.ClassName') |
| 1758 | >>> from package import module |
| 1759 | >>> original = module.ClassName |
| 1760 | >>> new_mock = patcher.start() |
| 1761 | >>> assert module.ClassName is not original |
| 1762 | >>> assert module.ClassName is new_mock |
| 1763 | >>> patcher.stop() |
| 1764 | >>> assert module.ClassName is original |
| 1765 | >>> assert module.ClassName is not new_mock |
| 1766 | |
| 1767 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1768 | A typical use case for this might be for doing multiple patches in the ``setUp`` |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1769 | method of a :class:`TestCase`:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1770 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1771 | >>> class MyTest(unittest.TestCase): |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1772 | ... def setUp(self): |
| 1773 | ... self.patcher1 = patch('package.module.Class1') |
| 1774 | ... self.patcher2 = patch('package.module.Class2') |
| 1775 | ... self.MockClass1 = self.patcher1.start() |
| 1776 | ... self.MockClass2 = self.patcher2.start() |
| 1777 | ... |
| 1778 | ... def tearDown(self): |
| 1779 | ... self.patcher1.stop() |
| 1780 | ... self.patcher2.stop() |
| 1781 | ... |
| 1782 | ... def test_something(self): |
| 1783 | ... assert package.module.Class1 is self.MockClass1 |
| 1784 | ... assert package.module.Class2 is self.MockClass2 |
| 1785 | ... |
| 1786 | >>> MyTest('test_something').run() |
| 1787 | |
| 1788 | .. caution:: |
| 1789 | |
| 1790 | If you use this technique you must ensure that the patching is "undone" by |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1791 | calling ``stop``. This can be fiddlier than you might think, because if an |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1792 | exception is raised in the ``setUp`` then ``tearDown`` is not called. |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1793 | :meth:`unittest.TestCase.addCleanup` makes this easier:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1794 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1795 | >>> class MyTest(unittest.TestCase): |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1796 | ... def setUp(self): |
| 1797 | ... patcher = patch('package.module.Class') |
| 1798 | ... self.MockClass = patcher.start() |
| 1799 | ... self.addCleanup(patcher.stop) |
| 1800 | ... |
| 1801 | ... def test_something(self): |
| 1802 | ... assert package.module.Class is self.MockClass |
| 1803 | ... |
| 1804 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1805 | As an added bonus you no longer need to keep a reference to the ``patcher`` |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1806 | object. |
| 1807 | |
Michael Foord | f7c4158 | 2012-06-10 20:36:32 +0100 | [diff] [blame] | 1808 | It is also possible to stop all patches which have been started by using |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1809 | :func:`patch.stopall`. |
Michael Foord | f7c4158 | 2012-06-10 20:36:32 +0100 | [diff] [blame] | 1810 | |
| 1811 | .. function:: patch.stopall |
| 1812 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1813 | Stop all active patches. Only stops patches started with ``start``. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1814 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1815 | |
| 1816 | .. _patch-builtins: |
Michael Foord | fddcfa2 | 2014-04-14 16:25:20 -0400 | [diff] [blame] | 1817 | |
| 1818 | patch builtins |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1819 | ~~~~~~~~~~~~~~ |
Michael Foord | fddcfa2 | 2014-04-14 16:25:20 -0400 | [diff] [blame] | 1820 | You can patch any builtins within a module. The following example patches |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1821 | builtin :func:`ord`:: |
Michael Foord | fddcfa2 | 2014-04-14 16:25:20 -0400 | [diff] [blame] | 1822 | |
| 1823 | >>> @patch('__main__.ord') |
| 1824 | ... def test(mock_ord): |
| 1825 | ... mock_ord.return_value = 101 |
| 1826 | ... print(ord('c')) |
| 1827 | ... |
| 1828 | >>> test() |
| 1829 | 101 |
| 1830 | |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1831 | |
Emmanuel Arias | 31a82e2 | 2019-09-12 08:29:54 -0300 | [diff] [blame] | 1832 | .. _test-prefix: |
| 1833 | |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1834 | TEST_PREFIX |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 1835 | ~~~~~~~~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1836 | |
| 1837 | All of the patchers can be used as class decorators. When used in this way |
| 1838 | they wrap every test method on the class. The patchers recognise methods that |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1839 | start with ``'test'`` as being test methods. This is the same way that the |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1840 | :class:`unittest.TestLoader` finds test methods by default. |
| 1841 | |
| 1842 | It is possible that you want to use a different prefix for your tests. You can |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1843 | inform the patchers of the different prefix by setting ``patch.TEST_PREFIX``:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1844 | |
| 1845 | >>> patch.TEST_PREFIX = 'foo' |
| 1846 | >>> value = 3 |
| 1847 | >>> |
| 1848 | >>> @patch('__main__.value', 'not three') |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 1849 | ... class Thing: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1850 | ... def foo_one(self): |
Berker Peksag | 920f6db | 2015-09-10 21:41:15 +0300 | [diff] [blame] | 1851 | ... print(value) |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1852 | ... def foo_two(self): |
Berker Peksag | 920f6db | 2015-09-10 21:41:15 +0300 | [diff] [blame] | 1853 | ... print(value) |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1854 | ... |
| 1855 | >>> |
| 1856 | >>> Thing().foo_one() |
| 1857 | not three |
| 1858 | >>> Thing().foo_two() |
| 1859 | not three |
| 1860 | >>> value |
| 1861 | 3 |
| 1862 | |
| 1863 | |
| 1864 | Nesting Patch Decorators |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 1865 | ~~~~~~~~~~~~~~~~~~~~~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1866 | |
| 1867 | If you want to perform multiple patches then you can simply stack up the |
| 1868 | decorators. |
| 1869 | |
| 1870 | You can stack up multiple patch decorators using this pattern: |
| 1871 | |
| 1872 | >>> @patch.object(SomeClass, 'class_method') |
| 1873 | ... @patch.object(SomeClass, 'static_method') |
| 1874 | ... def test(mock1, mock2): |
| 1875 | ... assert SomeClass.static_method is mock1 |
| 1876 | ... assert SomeClass.class_method is mock2 |
| 1877 | ... SomeClass.static_method('foo') |
| 1878 | ... SomeClass.class_method('bar') |
| 1879 | ... return mock1, mock2 |
| 1880 | ... |
| 1881 | >>> mock1, mock2 = test() |
| 1882 | >>> mock1.assert_called_once_with('foo') |
| 1883 | >>> mock2.assert_called_once_with('bar') |
| 1884 | |
| 1885 | |
| 1886 | Note that the decorators are applied from the bottom upwards. This is the |
| 1887 | standard way that Python applies decorators. The order of the created mocks |
| 1888 | passed into your test function matches this order. |
| 1889 | |
| 1890 | |
| 1891 | .. _where-to-patch: |
| 1892 | |
| 1893 | Where to patch |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 1894 | ~~~~~~~~~~~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1895 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1896 | :func:`patch` works by (temporarily) changing the object that a *name* points to with |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1897 | another one. There can be many names pointing to any individual object, so |
| 1898 | for patching to work you must ensure that you patch the name used by the system |
| 1899 | under test. |
| 1900 | |
| 1901 | The basic principle is that you patch where an object is *looked up*, which |
| 1902 | is not necessarily the same place as where it is defined. A couple of |
| 1903 | examples will help to clarify this. |
| 1904 | |
| 1905 | Imagine we have a project that we want to test with the following structure:: |
| 1906 | |
| 1907 | a.py |
| 1908 | -> Defines SomeClass |
| 1909 | |
| 1910 | b.py |
| 1911 | -> from a import SomeClass |
| 1912 | -> some_function instantiates SomeClass |
| 1913 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1914 | Now we want to test ``some_function`` but we want to mock out ``SomeClass`` using |
| 1915 | :func:`patch`. The problem is that when we import module b, which we will have to |
| 1916 | do then it imports ``SomeClass`` from module a. If we use :func:`patch` to mock out |
| 1917 | ``a.SomeClass`` then it will have no effect on our test; module b already has a |
| 1918 | reference to the *real* ``SomeClass`` and it looks like our patching had no |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1919 | effect. |
| 1920 | |
Ben Lloyd | 15033d1 | 2017-05-22 12:06:56 +0100 | [diff] [blame] | 1921 | The key is to patch out ``SomeClass`` where it is used (or where it is looked up). |
| 1922 | In this case ``some_function`` will actually look up ``SomeClass`` in module b, |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1923 | where we have imported it. The patching should look like:: |
| 1924 | |
| 1925 | @patch('b.SomeClass') |
| 1926 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1927 | However, consider the alternative scenario where instead of ``from a import |
| 1928 | SomeClass`` module b does ``import a`` and ``some_function`` uses ``a.SomeClass``. Both |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1929 | of these import forms are common. In this case the class we want to patch is |
Benjamin Peterson | 82f34ad | 2015-01-13 09:17:24 -0500 | [diff] [blame] | 1930 | being looked up in the module and so we have to patch ``a.SomeClass`` instead:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1931 | |
| 1932 | @patch('a.SomeClass') |
| 1933 | |
| 1934 | |
| 1935 | Patching Descriptors and Proxy Objects |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 1936 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1937 | |
| 1938 | Both patch_ and patch.object_ correctly patch and restore descriptors: class |
| 1939 | methods, static methods and properties. You should patch these on the *class* |
| 1940 | rather than an instance. They also work with *some* objects |
Zachary Ware | 5ea5d2c | 2014-02-26 09:34:43 -0600 | [diff] [blame] | 1941 | that proxy attribute access, like the `django settings object |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1942 | <http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_. |
| 1943 | |
| 1944 | |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 1945 | MagicMock and magic method support |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 1946 | ---------------------------------- |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 1947 | |
| 1948 | .. _magic-methods: |
| 1949 | |
| 1950 | Mocking Magic Methods |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 1951 | ~~~~~~~~~~~~~~~~~~~~~ |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 1952 | |
| 1953 | :class:`Mock` supports mocking the Python protocol methods, also known as |
| 1954 | "magic methods". This allows mock objects to replace containers or other |
| 1955 | objects that implement Python protocols. |
| 1956 | |
| 1957 | Because magic methods are looked up differently from normal methods [#]_, this |
| 1958 | support has been specially implemented. This means that only specific magic |
| 1959 | methods are supported. The supported list includes *almost* all of them. If |
| 1960 | there are any missing that you need please let us know. |
| 1961 | |
| 1962 | You mock magic methods by setting the method you are interested in to a function |
| 1963 | or a mock instance. If you are using a function then it *must* take ``self`` as |
| 1964 | the first argument [#]_. |
| 1965 | |
| 1966 | >>> def __str__(self): |
| 1967 | ... return 'fooble' |
| 1968 | ... |
| 1969 | >>> mock = Mock() |
| 1970 | >>> mock.__str__ = __str__ |
| 1971 | >>> str(mock) |
| 1972 | 'fooble' |
| 1973 | |
| 1974 | >>> mock = Mock() |
| 1975 | >>> mock.__str__ = Mock() |
| 1976 | >>> mock.__str__.return_value = 'fooble' |
| 1977 | >>> str(mock) |
| 1978 | 'fooble' |
| 1979 | |
| 1980 | >>> mock = Mock() |
| 1981 | >>> mock.__iter__ = Mock(return_value=iter([])) |
| 1982 | >>> list(mock) |
| 1983 | [] |
| 1984 | |
| 1985 | One use case for this is for mocking objects used as context managers in a |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1986 | :keyword:`with` statement: |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 1987 | |
| 1988 | >>> mock = Mock() |
| 1989 | >>> mock.__enter__ = Mock(return_value='foo') |
| 1990 | >>> mock.__exit__ = Mock(return_value=False) |
| 1991 | >>> with mock as m: |
| 1992 | ... assert m == 'foo' |
| 1993 | ... |
| 1994 | >>> mock.__enter__.assert_called_with() |
| 1995 | >>> mock.__exit__.assert_called_with(None, None, None) |
| 1996 | |
| 1997 | Calls to magic methods do not appear in :attr:`~Mock.method_calls`, but they |
| 1998 | are recorded in :attr:`~Mock.mock_calls`. |
| 1999 | |
| 2000 | .. note:: |
| 2001 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2002 | If you use the *spec* keyword argument to create a mock then attempting to |
| 2003 | set a magic method that isn't in the spec will raise an :exc:`AttributeError`. |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2004 | |
| 2005 | The full list of supported magic methods is: |
| 2006 | |
| 2007 | * ``__hash__``, ``__sizeof__``, ``__repr__`` and ``__str__`` |
| 2008 | * ``__dir__``, ``__format__`` and ``__subclasses__`` |
John Reese | 6c4fab0 | 2018-05-22 13:01:10 -0700 | [diff] [blame] | 2009 | * ``__round__``, ``__floor__``, ``__trunc__`` and ``__ceil__`` |
Serhiy Storchaka | a60c2fe | 2015-03-12 21:56:08 +0200 | [diff] [blame] | 2010 | * Comparisons: ``__lt__``, ``__gt__``, ``__le__``, ``__ge__``, |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2011 | ``__eq__`` and ``__ne__`` |
| 2012 | * Container methods: ``__getitem__``, ``__setitem__``, ``__delitem__``, |
Serhiy Storchaka | a60c2fe | 2015-03-12 21:56:08 +0200 | [diff] [blame] | 2013 | ``__contains__``, ``__len__``, ``__iter__``, ``__reversed__`` |
| 2014 | and ``__missing__`` |
Xtreak | 0ae022c | 2019-05-29 12:32:26 +0530 | [diff] [blame] | 2015 | * Context manager: ``__enter__``, ``__exit__``, ``__aenter__`` and ``__aexit__`` |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2016 | * Unary numeric methods: ``__neg__``, ``__pos__`` and ``__invert__`` |
| 2017 | * The numeric methods (including right hand and in-place variants): |
Serhiy Storchaka | c2ccce7 | 2015-03-12 22:01:30 +0200 | [diff] [blame] | 2018 | ``__add__``, ``__sub__``, ``__mul__``, ``__matmul__``, ``__div__``, ``__truediv__``, |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2019 | ``__floordiv__``, ``__mod__``, ``__divmod__``, ``__lshift__``, |
| 2020 | ``__rshift__``, ``__and__``, ``__xor__``, ``__or__``, and ``__pow__`` |
Serhiy Storchaka | a60c2fe | 2015-03-12 21:56:08 +0200 | [diff] [blame] | 2021 | * Numeric conversion methods: ``__complex__``, ``__int__``, ``__float__`` |
| 2022 | and ``__index__`` |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2023 | * Descriptor methods: ``__get__``, ``__set__`` and ``__delete__`` |
| 2024 | * Pickling: ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, |
| 2025 | ``__getnewargs__``, ``__getstate__`` and ``__setstate__`` |
Max Bélanger | 6c83d9f | 2018-10-25 14:48:58 -0700 | [diff] [blame] | 2026 | * File system path representation: ``__fspath__`` |
Xtreak | ff6b2e6 | 2019-05-27 18:26:23 +0530 | [diff] [blame] | 2027 | * Asynchronous iteration methods: ``__aiter__`` and ``__anext__`` |
Max Bélanger | 6c83d9f | 2018-10-25 14:48:58 -0700 | [diff] [blame] | 2028 | |
| 2029 | .. versionchanged:: 3.8 |
| 2030 | Added support for :func:`os.PathLike.__fspath__`. |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2031 | |
Xtreak | ff6b2e6 | 2019-05-27 18:26:23 +0530 | [diff] [blame] | 2032 | .. versionchanged:: 3.8 |
| 2033 | Added support for ``__aenter__``, ``__aexit__``, ``__aiter__`` and ``__anext__``. |
| 2034 | |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2035 | |
| 2036 | The following methods exist but are *not* supported as they are either in use |
| 2037 | by mock, can't be set dynamically, or can cause problems: |
| 2038 | |
| 2039 | * ``__getattr__``, ``__setattr__``, ``__init__`` and ``__new__`` |
| 2040 | * ``__prepare__``, ``__instancecheck__``, ``__subclasscheck__``, ``__del__`` |
| 2041 | |
| 2042 | |
| 2043 | |
| 2044 | Magic Mock |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 2045 | ~~~~~~~~~~ |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2046 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2047 | There are two ``MagicMock`` variants: :class:`MagicMock` and :class:`NonCallableMagicMock`. |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2048 | |
| 2049 | |
| 2050 | .. class:: MagicMock(*args, **kw) |
| 2051 | |
| 2052 | ``MagicMock`` is a subclass of :class:`Mock` with default implementations |
| 2053 | of most of the magic methods. You can use ``MagicMock`` without having to |
| 2054 | configure the magic methods yourself. |
| 2055 | |
| 2056 | The constructor parameters have the same meaning as for :class:`Mock`. |
| 2057 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2058 | If you use the *spec* or *spec_set* arguments then *only* magic methods |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2059 | that exist in the spec will be created. |
| 2060 | |
| 2061 | |
| 2062 | .. class:: NonCallableMagicMock(*args, **kw) |
| 2063 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2064 | A non-callable version of :class:`MagicMock`. |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2065 | |
| 2066 | The constructor parameters have the same meaning as for |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2067 | :class:`MagicMock`, with the exception of *return_value* and |
| 2068 | *side_effect* which have no meaning on a non-callable mock. |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2069 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2070 | The magic methods are setup with :class:`MagicMock` objects, so you can configure them |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2071 | and use them in the usual way: |
| 2072 | |
| 2073 | >>> mock = MagicMock() |
| 2074 | >>> mock[3] = 'fish' |
| 2075 | >>> mock.__setitem__.assert_called_with(3, 'fish') |
| 2076 | >>> mock.__getitem__.return_value = 'result' |
| 2077 | >>> mock[2] |
| 2078 | 'result' |
| 2079 | |
| 2080 | By default many of the protocol methods are required to return objects of a |
| 2081 | specific type. These methods are preconfigured with a default return value, so |
| 2082 | that they can be used without you having to do anything if you aren't interested |
| 2083 | in the return value. You can still *set* the return value manually if you want |
| 2084 | to change the default. |
| 2085 | |
| 2086 | Methods and their defaults: |
| 2087 | |
Serhiy Storchaka | 138ccbb | 2019-11-12 16:57:03 +0200 | [diff] [blame] | 2088 | * ``__lt__``: ``NotImplemented`` |
| 2089 | * ``__gt__``: ``NotImplemented`` |
| 2090 | * ``__le__``: ``NotImplemented`` |
| 2091 | * ``__ge__``: ``NotImplemented`` |
| 2092 | * ``__int__``: ``1`` |
| 2093 | * ``__contains__``: ``False`` |
| 2094 | * ``__len__``: ``0`` |
| 2095 | * ``__iter__``: ``iter([])`` |
| 2096 | * ``__exit__``: ``False`` |
| 2097 | * ``__aexit__``: ``False`` |
| 2098 | * ``__complex__``: ``1j`` |
| 2099 | * ``__float__``: ``1.0`` |
| 2100 | * ``__bool__``: ``True`` |
| 2101 | * ``__index__``: ``1`` |
Serhiy Storchaka | f47036c | 2013-12-24 11:04:36 +0200 | [diff] [blame] | 2102 | * ``__hash__``: default hash for the mock |
| 2103 | * ``__str__``: default str for the mock |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2104 | * ``__sizeof__``: default sizeof for the mock |
| 2105 | |
| 2106 | For example: |
| 2107 | |
| 2108 | >>> mock = MagicMock() |
| 2109 | >>> int(mock) |
| 2110 | 1 |
| 2111 | >>> len(mock) |
| 2112 | 0 |
| 2113 | >>> list(mock) |
| 2114 | [] |
| 2115 | >>> object() in mock |
| 2116 | False |
| 2117 | |
Berker Peksag | 283f1aa | 2015-01-07 21:15:02 +0200 | [diff] [blame] | 2118 | The two equality methods, :meth:`__eq__` and :meth:`__ne__`, are special. |
| 2119 | They do the default equality comparison on identity, using the |
| 2120 | :attr:`~Mock.side_effect` attribute, unless you change their return value to |
| 2121 | return something else:: |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2122 | |
| 2123 | >>> MagicMock() == 3 |
| 2124 | False |
| 2125 | >>> MagicMock() != 3 |
| 2126 | True |
| 2127 | >>> mock = MagicMock() |
| 2128 | >>> mock.__eq__.return_value = True |
| 2129 | >>> mock == 3 |
| 2130 | True |
| 2131 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2132 | The return value of :meth:`MagicMock.__iter__` can be any iterable object and isn't |
Michael Foord | 2309ed8 | 2012-03-28 15:38:36 +0100 | [diff] [blame] | 2133 | required to be an iterator: |
| 2134 | |
| 2135 | >>> mock = MagicMock() |
| 2136 | >>> mock.__iter__.return_value = ['a', 'b', 'c'] |
| 2137 | >>> list(mock) |
| 2138 | ['a', 'b', 'c'] |
| 2139 | >>> list(mock) |
| 2140 | ['a', 'b', 'c'] |
| 2141 | |
| 2142 | If the return value *is* an iterator, then iterating over it once will consume |
| 2143 | it and subsequent iterations will result in an empty list: |
| 2144 | |
| 2145 | >>> mock.__iter__.return_value = iter(['a', 'b', 'c']) |
| 2146 | >>> list(mock) |
| 2147 | ['a', 'b', 'c'] |
| 2148 | >>> list(mock) |
| 2149 | [] |
| 2150 | |
| 2151 | ``MagicMock`` has all of the supported magic methods configured except for some |
| 2152 | of the obscure and obsolete ones. You can still set these up if you want. |
| 2153 | |
| 2154 | Magic methods that are supported but not setup by default in ``MagicMock`` are: |
| 2155 | |
| 2156 | * ``__subclasses__`` |
| 2157 | * ``__dir__`` |
| 2158 | * ``__format__`` |
| 2159 | * ``__get__``, ``__set__`` and ``__delete__`` |
| 2160 | * ``__reversed__`` and ``__missing__`` |
| 2161 | * ``__reduce__``, ``__reduce_ex__``, ``__getinitargs__``, ``__getnewargs__``, |
| 2162 | ``__getstate__`` and ``__setstate__`` |
| 2163 | * ``__getformat__`` and ``__setformat__`` |
| 2164 | |
| 2165 | |
| 2166 | |
| 2167 | .. [#] Magic methods *should* be looked up on the class rather than the |
| 2168 | instance. Different versions of Python are inconsistent about applying this |
| 2169 | rule. The supported protocol methods should work with all supported versions |
| 2170 | of Python. |
| 2171 | .. [#] The function is basically hooked up to the class, but each ``Mock`` |
| 2172 | instance is kept isolated from the others. |
| 2173 | |
| 2174 | |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2175 | Helpers |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 2176 | ------- |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2177 | |
| 2178 | sentinel |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 2179 | ~~~~~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2180 | |
| 2181 | .. data:: sentinel |
| 2182 | |
Andrés Delfino | f85af03 | 2018-07-08 21:28:51 -0300 | [diff] [blame] | 2183 | The ``sentinel`` object provides a convenient way of providing unique |
| 2184 | objects for your tests. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2185 | |
Andrés Delfino | f85af03 | 2018-07-08 21:28:51 -0300 | [diff] [blame] | 2186 | Attributes are created on demand when you access them by name. Accessing |
| 2187 | the same attribute will always return the same object. The objects |
| 2188 | returned have a sensible repr so that test failure messages are readable. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2189 | |
Serhiy Storchaka | d9c956f | 2017-01-11 20:13:03 +0200 | [diff] [blame] | 2190 | .. versionchanged:: 3.7 |
| 2191 | The ``sentinel`` attributes now preserve their identity when they are |
| 2192 | :mod:`copied <copy>` or :mod:`pickled <pickle>`. |
| 2193 | |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2194 | Sometimes when testing you need to test that a specific object is passed as an |
| 2195 | argument to another method, or returned. It can be common to create named |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2196 | sentinel objects to test this. :data:`sentinel` provides a convenient way of |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2197 | creating and testing the identity of objects like this. |
| 2198 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2199 | In this example we monkey patch ``method`` to return ``sentinel.some_object``: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2200 | |
| 2201 | >>> real = ProductionClass() |
| 2202 | >>> real.method = Mock(name="method") |
| 2203 | >>> real.method.return_value = sentinel.some_object |
| 2204 | >>> result = real.method() |
| 2205 | >>> assert result is sentinel.some_object |
| 2206 | >>> sentinel.some_object |
| 2207 | sentinel.some_object |
| 2208 | |
| 2209 | |
| 2210 | DEFAULT |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 2211 | ~~~~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2212 | |
| 2213 | |
| 2214 | .. data:: DEFAULT |
| 2215 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2216 | The :data:`DEFAULT` object is a pre-created sentinel (actually |
| 2217 | ``sentinel.DEFAULT``). It can be used by :attr:`~Mock.side_effect` |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2218 | functions to indicate that the normal return value should be used. |
| 2219 | |
| 2220 | |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2221 | call |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 2222 | ~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2223 | |
| 2224 | .. function:: call(*args, **kwargs) |
| 2225 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2226 | :func:`call` is a helper object for making simpler assertions, for comparing with |
Georg Brandl | 2489167 | 2012-04-01 13:48:26 +0200 | [diff] [blame] | 2227 | :attr:`~Mock.call_args`, :attr:`~Mock.call_args_list`, |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2228 | :attr:`~Mock.mock_calls` and :attr:`~Mock.method_calls`. :func:`call` can also be |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2229 | used with :meth:`~Mock.assert_has_calls`. |
| 2230 | |
| 2231 | >>> m = MagicMock(return_value=None) |
| 2232 | >>> m(1, 2, a='foo', b='bar') |
| 2233 | >>> m() |
| 2234 | >>> m.call_args_list == [call(1, 2, a='foo', b='bar'), call()] |
| 2235 | True |
| 2236 | |
| 2237 | .. method:: call.call_list() |
| 2238 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2239 | For a call object that represents multiple calls, :meth:`call_list` |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2240 | returns a list of all the intermediate calls as well as the |
| 2241 | final call. |
| 2242 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2243 | ``call_list`` is particularly useful for making assertions on "chained calls". A |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2244 | chained call is multiple calls on a single line of code. This results in |
| 2245 | multiple entries in :attr:`~Mock.mock_calls` on a mock. Manually constructing |
| 2246 | the sequence of calls can be tedious. |
| 2247 | |
| 2248 | :meth:`~call.call_list` can construct the sequence of calls from the same |
| 2249 | chained call: |
| 2250 | |
| 2251 | >>> m = MagicMock() |
| 2252 | >>> m(1).method(arg='foo').other('bar')(2.0) |
| 2253 | <MagicMock name='mock().method().other()()' id='...'> |
| 2254 | >>> kall = call(1).method(arg='foo').other('bar')(2.0) |
| 2255 | >>> kall.call_list() |
| 2256 | [call(1), |
| 2257 | call().method(arg='foo'), |
| 2258 | call().method().other('bar'), |
| 2259 | call().method().other()(2.0)] |
| 2260 | >>> m.mock_calls == kall.call_list() |
| 2261 | True |
| 2262 | |
| 2263 | .. _calls-as-tuples: |
| 2264 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2265 | A ``call`` object is either a tuple of (positional args, keyword args) or |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2266 | (name, positional args, keyword args) depending on how it was constructed. When |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2267 | you construct them yourself this isn't particularly interesting, but the ``call`` |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2268 | objects that are in the :attr:`Mock.call_args`, :attr:`Mock.call_args_list` and |
| 2269 | :attr:`Mock.mock_calls` attributes can be introspected to get at the individual |
| 2270 | arguments they contain. |
| 2271 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2272 | The ``call`` objects in :attr:`Mock.call_args` and :attr:`Mock.call_args_list` |
| 2273 | are two-tuples of (positional args, keyword args) whereas the ``call`` objects |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2274 | in :attr:`Mock.mock_calls`, along with ones you construct yourself, are |
| 2275 | three-tuples of (name, positional args, keyword args). |
| 2276 | |
| 2277 | You can use their "tupleness" to pull out the individual arguments for more |
| 2278 | complex introspection and assertions. The positional arguments are a tuple |
| 2279 | (an empty tuple if there are no positional arguments) and the keyword |
| 2280 | arguments are a dictionary: |
| 2281 | |
| 2282 | >>> m = MagicMock(return_value=None) |
| 2283 | >>> m(1, 2, 3, arg='one', arg2='two') |
| 2284 | >>> kall = m.call_args |
Kumar Akshay | b0df45e | 2019-03-22 13:40:40 +0530 | [diff] [blame] | 2285 | >>> kall.args |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2286 | (1, 2, 3) |
Kumar Akshay | b0df45e | 2019-03-22 13:40:40 +0530 | [diff] [blame] | 2287 | >>> kall.kwargs |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2288 | {'arg': 'one', 'arg2': 'two'} |
Kumar Akshay | b0df45e | 2019-03-22 13:40:40 +0530 | [diff] [blame] | 2289 | >>> kall.args is kall[0] |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2290 | True |
Kumar Akshay | b0df45e | 2019-03-22 13:40:40 +0530 | [diff] [blame] | 2291 | >>> kall.kwargs is kall[1] |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2292 | True |
| 2293 | |
| 2294 | >>> m = MagicMock() |
| 2295 | >>> m.foo(4, 5, 6, arg='two', arg2='three') |
| 2296 | <MagicMock name='mock.foo()' id='...'> |
| 2297 | >>> kall = m.mock_calls[0] |
| 2298 | >>> name, args, kwargs = kall |
| 2299 | >>> name |
| 2300 | 'foo' |
| 2301 | >>> args |
| 2302 | (4, 5, 6) |
| 2303 | >>> kwargs |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2304 | {'arg': 'two', 'arg2': 'three'} |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2305 | >>> name is m.mock_calls[0][0] |
| 2306 | True |
| 2307 | |
| 2308 | |
| 2309 | create_autospec |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 2310 | ~~~~~~~~~~~~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2311 | |
| 2312 | .. function:: create_autospec(spec, spec_set=False, instance=False, **kwargs) |
| 2313 | |
| 2314 | Create a mock object using another object as a spec. Attributes on the |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2315 | mock will use the corresponding attribute on the *spec* object as their |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2316 | spec. |
| 2317 | |
| 2318 | Functions or methods being mocked will have their arguments checked to |
| 2319 | ensure that they are called with the correct signature. |
| 2320 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2321 | If *spec_set* is ``True`` then attempting to set attributes that don't exist |
| 2322 | on the spec object will raise an :exc:`AttributeError`. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2323 | |
| 2324 | If a class is used as a spec then the return value of the mock (the |
| 2325 | instance of the class) will have the same spec. You can use a class as the |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2326 | spec for an instance object by passing ``instance=True``. The returned mock |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2327 | will only be callable if instances of the mock are callable. |
| 2328 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2329 | :func:`create_autospec` also takes arbitrary keyword arguments that are passed to |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2330 | the constructor of the created mock. |
| 2331 | |
| 2332 | See :ref:`auto-speccing` for examples of how to use auto-speccing with |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2333 | :func:`create_autospec` and the *autospec* argument to :func:`patch`. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2334 | |
| 2335 | |
Mario Corchero | f5e7f39 | 2019-09-09 15:18:06 +0100 | [diff] [blame] | 2336 | .. versionchanged:: 3.8 |
| 2337 | |
| 2338 | :func:`create_autospec` now returns an :class:`AsyncMock` if the target is |
| 2339 | an async function. |
| 2340 | |
| 2341 | |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2342 | ANY |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 2343 | ~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2344 | |
| 2345 | .. data:: ANY |
| 2346 | |
| 2347 | Sometimes you may need to make assertions about *some* of the arguments in a |
| 2348 | call to mock, but either not care about some of the arguments or want to pull |
| 2349 | them individually out of :attr:`~Mock.call_args` and make more complex |
| 2350 | assertions on them. |
| 2351 | |
| 2352 | To ignore certain arguments you can pass in objects that compare equal to |
| 2353 | *everything*. Calls to :meth:`~Mock.assert_called_with` and |
| 2354 | :meth:`~Mock.assert_called_once_with` will then succeed no matter what was |
| 2355 | passed in. |
| 2356 | |
| 2357 | >>> mock = Mock(return_value=None) |
| 2358 | >>> mock('foo', bar=object()) |
| 2359 | >>> mock.assert_called_once_with('foo', bar=ANY) |
| 2360 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2361 | :data:`ANY` can also be used in comparisons with call lists like |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2362 | :attr:`~Mock.mock_calls`: |
| 2363 | |
| 2364 | >>> m = MagicMock(return_value=None) |
| 2365 | >>> m(1) |
| 2366 | >>> m(1, 2) |
| 2367 | >>> m(object()) |
| 2368 | >>> m.mock_calls == [call(1), call(1, 2), ANY] |
| 2369 | True |
| 2370 | |
| 2371 | |
| 2372 | |
| 2373 | FILTER_DIR |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 2374 | ~~~~~~~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2375 | |
| 2376 | .. data:: FILTER_DIR |
| 2377 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2378 | :data:`FILTER_DIR` is a module level variable that controls the way mock objects |
| 2379 | respond to :func:`dir` (only for Python 2.6 or more recent). The default is ``True``, |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2380 | which uses the filtering described below, to only show useful members. If you |
| 2381 | dislike this filtering, or need to switch it off for diagnostic purposes, then |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2382 | set ``mock.FILTER_DIR = False``. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2383 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2384 | With filtering on, ``dir(some_mock)`` shows only useful attributes and will |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2385 | include any dynamically created attributes that wouldn't normally be shown. |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2386 | If the mock was created with a *spec* (or *autospec* of course) then all the |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2387 | attributes from the original are shown, even if they haven't been accessed |
| 2388 | yet: |
| 2389 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2390 | .. doctest:: |
| 2391 | :options: +ELLIPSIS,+NORMALIZE_WHITESPACE |
| 2392 | |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2393 | >>> dir(Mock()) |
| 2394 | ['assert_any_call', |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2395 | 'assert_called', |
| 2396 | 'assert_called_once', |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2397 | 'assert_called_once_with', |
| 2398 | 'assert_called_with', |
| 2399 | 'assert_has_calls', |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2400 | 'assert_not_called', |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2401 | 'attach_mock', |
| 2402 | ... |
| 2403 | >>> from urllib import request |
| 2404 | >>> dir(Mock(spec=request)) |
| 2405 | ['AbstractBasicAuthHandler', |
| 2406 | 'AbstractDigestAuthHandler', |
| 2407 | 'AbstractHTTPHandler', |
| 2408 | 'BaseHandler', |
| 2409 | ... |
| 2410 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2411 | Many of the not-very-useful (private to :class:`Mock` rather than the thing being |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2412 | mocked) underscore and double underscore prefixed attributes have been |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2413 | filtered from the result of calling :func:`dir` on a :class:`Mock`. If you dislike this |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2414 | behaviour you can switch it off by setting the module level switch |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2415 | :data:`FILTER_DIR`: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2416 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2417 | .. doctest:: |
| 2418 | :options: +ELLIPSIS,+NORMALIZE_WHITESPACE |
| 2419 | |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2420 | >>> from unittest import mock |
| 2421 | >>> mock.FILTER_DIR = False |
| 2422 | >>> dir(mock.Mock()) |
| 2423 | ['_NonCallableMock__get_return_value', |
| 2424 | '_NonCallableMock__get_side_effect', |
| 2425 | '_NonCallableMock__return_value_doc', |
| 2426 | '_NonCallableMock__set_return_value', |
| 2427 | '_NonCallableMock__set_side_effect', |
| 2428 | '__call__', |
| 2429 | '__class__', |
| 2430 | ... |
| 2431 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2432 | Alternatively you can just use ``vars(my_mock)`` (instance members) and |
| 2433 | ``dir(type(my_mock))`` (type members) to bypass the filtering irrespective of |
| 2434 | :data:`mock.FILTER_DIR`. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2435 | |
| 2436 | |
| 2437 | mock_open |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 2438 | ~~~~~~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2439 | |
| 2440 | .. function:: mock_open(mock=None, read_data=None) |
| 2441 | |
Andrés Delfino | f85af03 | 2018-07-08 21:28:51 -0300 | [diff] [blame] | 2442 | A helper function to create a mock to replace the use of :func:`open`. It works |
| 2443 | for :func:`open` called directly or used as a context manager. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2444 | |
Andrés Delfino | f85af03 | 2018-07-08 21:28:51 -0300 | [diff] [blame] | 2445 | The *mock* argument is the mock object to configure. If ``None`` (the |
| 2446 | default) then a :class:`MagicMock` will be created for you, with the API limited |
| 2447 | to methods or attributes available on standard file handles. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2448 | |
Andrés Delfino | f85af03 | 2018-07-08 21:28:51 -0300 | [diff] [blame] | 2449 | *read_data* is a string for the :meth:`~io.IOBase.read`, |
| 2450 | :meth:`~io.IOBase.readline`, and :meth:`~io.IOBase.readlines` methods |
| 2451 | of the file handle to return. Calls to those methods will take data from |
| 2452 | *read_data* until it is depleted. The mock of these methods is pretty |
| 2453 | simplistic: every time the *mock* is called, the *read_data* is rewound to |
| 2454 | the start. If you need more control over the data that you are feeding to |
| 2455 | the tested code you will need to customize this mock for yourself. When that |
| 2456 | is insufficient, one of the in-memory filesystem packages on `PyPI |
| 2457 | <https://pypi.org>`_ can offer a realistic filesystem for testing. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2458 | |
Robert Collins | f79dfe3 | 2015-07-24 04:09:59 +1200 | [diff] [blame] | 2459 | .. versionchanged:: 3.4 |
| 2460 | Added :meth:`~io.IOBase.readline` and :meth:`~io.IOBase.readlines` support. |
| 2461 | The mock of :meth:`~io.IOBase.read` changed to consume *read_data* rather |
| 2462 | than returning it on each call. |
| 2463 | |
Robert Collins | 7039839 | 2015-07-24 04:10:27 +1200 | [diff] [blame] | 2464 | .. versionchanged:: 3.5 |
Robert Collins | f79dfe3 | 2015-07-24 04:09:59 +1200 | [diff] [blame] | 2465 | *read_data* is now reset on each call to the *mock*. |
| 2466 | |
Tony Flury | 2087023 | 2018-09-12 23:21:16 +0100 | [diff] [blame] | 2467 | .. versionchanged:: 3.8 |
| 2468 | Added :meth:`__iter__` to implementation so that iteration (such as in for |
| 2469 | loops) correctly consumes *read_data*. |
| 2470 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2471 | Using :func:`open` as a context manager is a great way to ensure your file handles |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2472 | are closed properly and is becoming common:: |
| 2473 | |
| 2474 | with open('/some/path', 'w') as f: |
| 2475 | f.write('something') |
| 2476 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2477 | The issue is that even if you mock out the call to :func:`open` it is the |
| 2478 | *returned object* that is used as a context manager (and has :meth:`__enter__` and |
| 2479 | :meth:`__exit__` called). |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2480 | |
| 2481 | Mocking context managers with a :class:`MagicMock` is common enough and fiddly |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2482 | enough that a helper function is useful. :: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2483 | |
| 2484 | >>> m = mock_open() |
Michael Foord | fddcfa2 | 2014-04-14 16:25:20 -0400 | [diff] [blame] | 2485 | >>> with patch('__main__.open', m): |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2486 | ... with open('foo', 'w') as h: |
| 2487 | ... h.write('some stuff') |
| 2488 | ... |
| 2489 | >>> m.mock_calls |
| 2490 | [call('foo', 'w'), |
| 2491 | call().__enter__(), |
| 2492 | call().write('some stuff'), |
| 2493 | call().__exit__(None, None, None)] |
| 2494 | >>> m.assert_called_once_with('foo', 'w') |
| 2495 | >>> handle = m() |
| 2496 | >>> handle.write.assert_called_once_with('some stuff') |
| 2497 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2498 | And for reading files:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2499 | |
Michael Foord | fddcfa2 | 2014-04-14 16:25:20 -0400 | [diff] [blame] | 2500 | >>> with patch('__main__.open', mock_open(read_data='bibble')) as m: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2501 | ... with open('foo') as h: |
| 2502 | ... result = h.read() |
| 2503 | ... |
| 2504 | >>> m.assert_called_once_with('foo') |
| 2505 | >>> assert result == 'bibble' |
| 2506 | |
| 2507 | |
| 2508 | .. _auto-speccing: |
| 2509 | |
| 2510 | Autospeccing |
Georg Brandl | fb13438 | 2013-02-03 11:47:49 +0100 | [diff] [blame] | 2511 | ~~~~~~~~~~~~ |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2512 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2513 | Autospeccing is based on the existing :attr:`spec` feature of mock. It limits the |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2514 | api of mocks to the api of an original object (the spec), but it is recursive |
| 2515 | (implemented lazily) so that attributes of mocks only have the same api as |
| 2516 | the attributes of the spec. In addition mocked functions / methods have the |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2517 | same call signature as the original so they raise a :exc:`TypeError` if they are |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2518 | called incorrectly. |
| 2519 | |
| 2520 | Before I explain how auto-speccing works, here's why it is needed. |
| 2521 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2522 | :class:`Mock` is a very powerful and flexible object, but it suffers from two flaws |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2523 | when used to mock out objects from a system under test. One of these flaws is |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2524 | specific to the :class:`Mock` api and the other is a more general problem with using |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2525 | mock objects. |
| 2526 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2527 | First the problem specific to :class:`Mock`. :class:`Mock` has two assert methods that are |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2528 | extremely handy: :meth:`~Mock.assert_called_with` and |
| 2529 | :meth:`~Mock.assert_called_once_with`. |
| 2530 | |
| 2531 | >>> mock = Mock(name='Thing', return_value=None) |
| 2532 | >>> mock(1, 2, 3) |
| 2533 | >>> mock.assert_called_once_with(1, 2, 3) |
| 2534 | >>> mock(1, 2, 3) |
| 2535 | >>> mock.assert_called_once_with(1, 2, 3) |
| 2536 | Traceback (most recent call last): |
| 2537 | ... |
Michael Foord | 28d591c | 2012-09-28 16:15:22 +0100 | [diff] [blame] | 2538 | AssertionError: Expected 'mock' to be called once. Called 2 times. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2539 | |
| 2540 | Because mocks auto-create attributes on demand, and allow you to call them |
| 2541 | with arbitrary arguments, if you misspell one of these assert methods then |
| 2542 | your assertion is gone: |
| 2543 | |
| 2544 | .. code-block:: pycon |
| 2545 | |
| 2546 | >>> mock = Mock(name='Thing', return_value=None) |
| 2547 | >>> mock(1, 2, 3) |
| 2548 | >>> mock.assret_called_once_with(4, 5, 6) |
| 2549 | |
| 2550 | Your tests can pass silently and incorrectly because of the typo. |
| 2551 | |
| 2552 | The second issue is more general to mocking. If you refactor some of your |
| 2553 | code, rename members and so on, any tests for code that is still using the |
| 2554 | *old api* but uses mocks instead of the real objects will still pass. This |
| 2555 | means your tests can all pass even though your code is broken. |
| 2556 | |
| 2557 | Note that this is another reason why you need integration tests as well as |
| 2558 | unit tests. Testing everything in isolation is all fine and dandy, but if you |
| 2559 | don't test how your units are "wired together" there is still lots of room |
| 2560 | for bugs that tests might have caught. |
| 2561 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2562 | :mod:`mock` already provides a feature to help with this, called speccing. If you |
| 2563 | use a class or instance as the :attr:`spec` for a mock then you can only access |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2564 | attributes on the mock that exist on the real class: |
| 2565 | |
| 2566 | >>> from urllib import request |
| 2567 | >>> mock = Mock(spec=request.Request) |
| 2568 | >>> mock.assret_called_with |
| 2569 | Traceback (most recent call last): |
| 2570 | ... |
| 2571 | AttributeError: Mock object has no attribute 'assret_called_with' |
| 2572 | |
| 2573 | The spec only applies to the mock itself, so we still have the same issue |
| 2574 | with any methods on the mock: |
| 2575 | |
| 2576 | .. code-block:: pycon |
| 2577 | |
| 2578 | >>> mock.has_data() |
| 2579 | <mock.Mock object at 0x...> |
| 2580 | >>> mock.has_data.assret_called_with() |
| 2581 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2582 | Auto-speccing solves this problem. You can either pass ``autospec=True`` to |
| 2583 | :func:`patch` / :func:`patch.object` or use the :func:`create_autospec` function to create a |
| 2584 | mock with a spec. If you use the ``autospec=True`` argument to :func:`patch` then the |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2585 | object that is being replaced will be used as the spec object. Because the |
| 2586 | speccing is done "lazily" (the spec is created as attributes on the mock are |
| 2587 | accessed) you can use it with very complex or deeply nested objects (like |
| 2588 | modules that import modules that import modules) without a big performance |
| 2589 | hit. |
| 2590 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2591 | Here's an example of it in use:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2592 | |
| 2593 | >>> from urllib import request |
| 2594 | >>> patcher = patch('__main__.request', autospec=True) |
| 2595 | >>> mock_request = patcher.start() |
| 2596 | >>> request is mock_request |
| 2597 | True |
| 2598 | >>> mock_request.Request |
| 2599 | <MagicMock name='request.Request' spec='Request' id='...'> |
| 2600 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2601 | You can see that :class:`request.Request` has a spec. :class:`request.Request` takes two |
| 2602 | arguments in the constructor (one of which is *self*). Here's what happens if |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2603 | we try to call it incorrectly:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2604 | |
| 2605 | >>> req = request.Request() |
| 2606 | Traceback (most recent call last): |
| 2607 | ... |
| 2608 | TypeError: <lambda>() takes at least 2 arguments (1 given) |
| 2609 | |
| 2610 | The spec also applies to instantiated classes (i.e. the return value of |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2611 | specced mocks):: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2612 | |
| 2613 | >>> req = request.Request('foo') |
| 2614 | >>> req |
| 2615 | <NonCallableMagicMock name='request.Request()' spec='Request' id='...'> |
| 2616 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2617 | :class:`Request` objects are not callable, so the return value of instantiating our |
| 2618 | mocked out :class:`request.Request` is a non-callable mock. With the spec in place |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2619 | any typos in our asserts will raise the correct error:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2620 | |
| 2621 | >>> req.add_header('spam', 'eggs') |
| 2622 | <MagicMock name='request.Request().add_header()' id='...'> |
| 2623 | >>> req.add_header.assret_called_with |
| 2624 | Traceback (most recent call last): |
| 2625 | ... |
| 2626 | AttributeError: Mock object has no attribute 'assret_called_with' |
| 2627 | >>> req.add_header.assert_called_with('spam', 'eggs') |
| 2628 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2629 | In many cases you will just be able to add ``autospec=True`` to your existing |
| 2630 | :func:`patch` calls and then be protected against bugs due to typos and api |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2631 | changes. |
| 2632 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2633 | As well as using *autospec* through :func:`patch` there is a |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2634 | :func:`create_autospec` for creating autospecced mocks directly: |
| 2635 | |
| 2636 | >>> from urllib import request |
| 2637 | >>> mock_request = create_autospec(request) |
| 2638 | >>> mock_request.Request('foo', 'bar') |
| 2639 | <NonCallableMagicMock name='mock.Request()' spec='Request' id='...'> |
| 2640 | |
| 2641 | This isn't without caveats and limitations however, which is why it is not |
| 2642 | the default behaviour. In order to know what attributes are available on the |
| 2643 | spec object, autospec has to introspect (access attributes) the spec. As you |
| 2644 | traverse attributes on the mock a corresponding traversal of the original |
| 2645 | object is happening under the hood. If any of your specced objects have |
| 2646 | properties or descriptors that can trigger code execution then you may not be |
| 2647 | able to use autospec. On the other hand it is much better to design your |
| 2648 | objects so that introspection is safe [#]_. |
| 2649 | |
| 2650 | A more serious problem is that it is common for instance attributes to be |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2651 | created in the :meth:`__init__` method and not to exist on the class at all. |
| 2652 | *autospec* can't know about any dynamically created attributes and restricts |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2653 | the api to visible attributes. :: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2654 | |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 2655 | >>> class Something: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2656 | ... def __init__(self): |
| 2657 | ... self.a = 33 |
| 2658 | ... |
| 2659 | >>> with patch('__main__.Something', autospec=True): |
| 2660 | ... thing = Something() |
| 2661 | ... thing.a |
| 2662 | ... |
| 2663 | Traceback (most recent call last): |
| 2664 | ... |
| 2665 | AttributeError: Mock object has no attribute 'a' |
| 2666 | |
| 2667 | There are a few different ways of resolving this problem. The easiest, but |
| 2668 | not necessarily the least annoying, way is to simply set the required |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2669 | attributes on the mock after creation. Just because *autospec* doesn't allow |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2670 | you to fetch attributes that don't exist on the spec it doesn't prevent you |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2671 | setting them:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2672 | |
| 2673 | >>> with patch('__main__.Something', autospec=True): |
| 2674 | ... thing = Something() |
| 2675 | ... thing.a = 33 |
| 2676 | ... |
| 2677 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2678 | There is a more aggressive version of both *spec* and *autospec* that *does* |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2679 | prevent you setting non-existent attributes. This is useful if you want to |
| 2680 | ensure your code only *sets* valid attributes too, but obviously it prevents |
| 2681 | this particular scenario: |
| 2682 | |
| 2683 | >>> with patch('__main__.Something', autospec=True, spec_set=True): |
| 2684 | ... thing = Something() |
| 2685 | ... thing.a = 33 |
| 2686 | ... |
| 2687 | Traceback (most recent call last): |
| 2688 | ... |
| 2689 | AttributeError: Mock object has no attribute 'a' |
| 2690 | |
| 2691 | Probably the best way of solving the problem is to add class attributes as |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2692 | default values for instance members initialised in :meth:`__init__`. Note that if |
| 2693 | you are only setting default attributes in :meth:`__init__` then providing them via |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2694 | class attributes (shared between instances of course) is faster too. e.g. |
| 2695 | |
| 2696 | .. code-block:: python |
| 2697 | |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 2698 | class Something: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2699 | a = 33 |
| 2700 | |
| 2701 | This brings up another issue. It is relatively common to provide a default |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2702 | value of ``None`` for members that will later be an object of a different type. |
| 2703 | ``None`` would be useless as a spec because it wouldn't let you access *any* |
| 2704 | attributes or methods on it. As ``None`` is *never* going to be useful as a |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2705 | spec, and probably indicates a member that will normally of some other type, |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2706 | autospec doesn't use a spec for members that are set to ``None``. These will |
| 2707 | just be ordinary mocks (well - MagicMocks): |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2708 | |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 2709 | >>> class Something: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2710 | ... member = None |
| 2711 | ... |
| 2712 | >>> mock = create_autospec(Something) |
| 2713 | >>> mock.member.foo.bar.baz() |
| 2714 | <MagicMock name='mock.member.foo.bar.baz()' id='...'> |
| 2715 | |
| 2716 | If modifying your production classes to add defaults isn't to your liking |
| 2717 | then there are more options. One of these is simply to use an instance as the |
| 2718 | spec rather than the class. The other is to create a subclass of the |
| 2719 | production class and add the defaults to the subclass without affecting the |
| 2720 | production class. Both of these require you to use an alternative object as |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2721 | the spec. Thankfully :func:`patch` supports this - you can simply pass the |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2722 | alternative object as the *autospec* argument:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2723 | |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 2724 | >>> class Something: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2725 | ... def __init__(self): |
| 2726 | ... self.a = 33 |
| 2727 | ... |
| 2728 | >>> class SomethingForTest(Something): |
| 2729 | ... a = 33 |
| 2730 | ... |
| 2731 | >>> p = patch('__main__.Something', autospec=SomethingForTest) |
| 2732 | >>> mock = p.start() |
| 2733 | >>> mock.a |
| 2734 | <NonCallableMagicMock name='Something.a' spec='int' id='...'> |
| 2735 | |
| 2736 | |
| 2737 | .. [#] This only applies to classes or already instantiated objects. Calling |
| 2738 | a mocked class to create a mock instance *does not* create a real instance. |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 2739 | It is only attribute lookups - along with calls to :func:`dir` - that are done. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 2740 | |
Mario Corchero | 552be9d | 2017-10-17 12:35:11 +0100 | [diff] [blame] | 2741 | Sealing mocks |
| 2742 | ~~~~~~~~~~~~~ |
| 2743 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2744 | |
| 2745 | .. testsetup:: |
| 2746 | |
| 2747 | from unittest.mock import seal |
| 2748 | |
Mario Corchero | 552be9d | 2017-10-17 12:35:11 +0100 | [diff] [blame] | 2749 | .. function:: seal(mock) |
| 2750 | |
Mario Corchero | 96200eb | 2018-10-19 22:57:37 +0100 | [diff] [blame] | 2751 | Seal will disable the automatic creation of mocks when accessing an attribute of |
| 2752 | the mock being sealed or any of its attributes that are already mocks recursively. |
Mario Corchero | 552be9d | 2017-10-17 12:35:11 +0100 | [diff] [blame] | 2753 | |
Mario Corchero | 96200eb | 2018-10-19 22:57:37 +0100 | [diff] [blame] | 2754 | If a mock instance with a name or a spec is assigned to an attribute |
Paul Ganssle | 85ac726 | 2018-01-06 08:25:34 -0500 | [diff] [blame] | 2755 | it won't be considered in the sealing chain. This allows one to prevent seal from |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 2756 | fixing part of the mock object. :: |
Mario Corchero | 552be9d | 2017-10-17 12:35:11 +0100 | [diff] [blame] | 2757 | |
| 2758 | >>> mock = Mock() |
| 2759 | >>> mock.submock.attribute1 = 2 |
Mario Corchero | 96200eb | 2018-10-19 22:57:37 +0100 | [diff] [blame] | 2760 | >>> mock.not_submock = mock.Mock(name="sample_name") |
Mario Corchero | 552be9d | 2017-10-17 12:35:11 +0100 | [diff] [blame] | 2761 | >>> seal(mock) |
Mario Corchero | 96200eb | 2018-10-19 22:57:37 +0100 | [diff] [blame] | 2762 | >>> mock.new_attribute # This will raise AttributeError. |
Mario Corchero | 552be9d | 2017-10-17 12:35:11 +0100 | [diff] [blame] | 2763 | >>> mock.submock.attribute2 # This will raise AttributeError. |
| 2764 | >>> mock.not_submock.attribute2 # This won't raise. |
| 2765 | |
| 2766 | .. versionadded:: 3.7 |