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