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