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