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