Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 1 | :mod:`unittest.mock` --- getting started |
| 2 | ======================================== |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 3 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 4 | .. moduleauthor:: Michael Foord <michael@python.org> |
| 5 | .. currentmodule:: unittest.mock |
| 6 | |
| 7 | .. versionadded:: 3.3 |
| 8 | |
| 9 | |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 10 | .. _getting-started: |
| 11 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 12 | |
| 13 | .. testsetup:: |
| 14 | |
| 15 | import unittest |
| 16 | from unittest.mock import Mock, MagicMock, patch, call, sentinel |
| 17 | |
| 18 | class SomeClass: |
| 19 | attribute = 'this is a doctest' |
| 20 | |
| 21 | @staticmethod |
| 22 | def static_method(): |
| 23 | pass |
| 24 | |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 25 | Using Mock |
| 26 | ---------- |
| 27 | |
| 28 | Mock Patching Methods |
| 29 | ~~~~~~~~~~~~~~~~~~~~~ |
| 30 | |
| 31 | Common uses for :class:`Mock` objects include: |
| 32 | |
| 33 | * Patching methods |
| 34 | * Recording method calls on objects |
| 35 | |
| 36 | You might want to replace a method on an object to check that |
| 37 | it is called with the correct arguments by another part of the system: |
| 38 | |
| 39 | >>> real = SomeClass() |
| 40 | >>> real.method = MagicMock(name='method') |
| 41 | >>> real.method(3, 4, 5, key='value') |
| 42 | <MagicMock name='method()' id='...'> |
| 43 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 44 | Once our mock has been used (``real.method`` in this example) it has methods |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 45 | and attributes that allow you to make assertions about how it has been used. |
| 46 | |
| 47 | .. note:: |
| 48 | |
| 49 | In most of these examples the :class:`Mock` and :class:`MagicMock` classes |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 50 | are interchangeable. As the ``MagicMock`` is the more capable class it makes |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 51 | a sensible one to use by default. |
| 52 | |
| 53 | Once the mock has been called its :attr:`~Mock.called` attribute is set to |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 54 | ``True``. More importantly we can use the :meth:`~Mock.assert_called_with` or |
Georg Brandl | 2489167 | 2012-04-01 13:48:26 +0200 | [diff] [blame] | 55 | :meth:`~Mock.assert_called_once_with` method to check that it was called with |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 56 | the correct arguments. |
| 57 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 58 | This example tests that calling ``ProductionClass().method`` results in a call to |
| 59 | the ``something`` method: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 60 | |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 61 | >>> class ProductionClass: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 62 | ... def method(self): |
| 63 | ... self.something(1, 2, 3) |
| 64 | ... def something(self, a, b, c): |
| 65 | ... pass |
| 66 | ... |
| 67 | >>> real = ProductionClass() |
| 68 | >>> real.something = MagicMock() |
| 69 | >>> real.method() |
| 70 | >>> real.something.assert_called_once_with(1, 2, 3) |
| 71 | |
| 72 | |
| 73 | |
| 74 | Mock for Method Calls on an Object |
| 75 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 76 | |
| 77 | In the last example we patched a method directly on an object to check that it |
| 78 | was called correctly. Another common use case is to pass an object into a |
| 79 | method (or some part of the system under test) and then check that it is used |
| 80 | in the correct way. |
| 81 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 82 | The simple ``ProductionClass`` below has a ``closer`` method. If it is called with |
| 83 | an object then it calls ``close`` on it. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 84 | |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 85 | >>> class ProductionClass: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 86 | ... def closer(self, something): |
| 87 | ... something.close() |
| 88 | ... |
| 89 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 90 | So to test it we need to pass in an object with a ``close`` method and check |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 91 | that it was called correctly. |
| 92 | |
| 93 | >>> real = ProductionClass() |
| 94 | >>> mock = Mock() |
| 95 | >>> real.closer(mock) |
| 96 | >>> mock.close.assert_called_with() |
| 97 | |
| 98 | We don't have to do any work to provide the 'close' method on our mock. |
| 99 | Accessing close creates it. So, if 'close' hasn't already been called then |
| 100 | accessing it in the test will create it, but :meth:`~Mock.assert_called_with` |
| 101 | will raise a failure exception. |
| 102 | |
| 103 | |
| 104 | Mocking Classes |
| 105 | ~~~~~~~~~~~~~~~ |
| 106 | |
| 107 | A common use case is to mock out classes instantiated by your code under test. |
| 108 | When you patch a class, then that class is replaced with a mock. Instances |
| 109 | are created by *calling the class*. This means you access the "mock instance" |
| 110 | by looking at the return value of the mocked class. |
| 111 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 112 | In the example below we have a function ``some_function`` that instantiates ``Foo`` |
| 113 | and calls a method on it. The call to :func:`patch` replaces the class ``Foo`` with a |
| 114 | mock. The ``Foo`` instance is the result of calling the mock, so it is configured |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 115 | by modifying the mock :attr:`~Mock.return_value`. :: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 116 | |
| 117 | >>> def some_function(): |
| 118 | ... instance = module.Foo() |
| 119 | ... return instance.method() |
| 120 | ... |
| 121 | >>> with patch('module.Foo') as mock: |
| 122 | ... instance = mock.return_value |
| 123 | ... instance.method.return_value = 'the result' |
| 124 | ... result = some_function() |
| 125 | ... assert result == 'the result' |
| 126 | |
| 127 | |
| 128 | Naming your mocks |
| 129 | ~~~~~~~~~~~~~~~~~ |
| 130 | |
| 131 | It can be useful to give your mocks a name. The name is shown in the repr of |
| 132 | the mock and can be helpful when the mock appears in test failure messages. The |
| 133 | name is also propagated to attributes or methods of the mock: |
| 134 | |
| 135 | >>> mock = MagicMock(name='foo') |
| 136 | >>> mock |
| 137 | <MagicMock name='foo' id='...'> |
| 138 | >>> mock.method |
| 139 | <MagicMock name='foo.method' id='...'> |
| 140 | |
| 141 | |
| 142 | Tracking all Calls |
| 143 | ~~~~~~~~~~~~~~~~~~ |
| 144 | |
| 145 | Often you want to track more than a single call to a method. The |
| 146 | :attr:`~Mock.mock_calls` attribute records all calls |
| 147 | to child attributes of the mock - and also to their children. |
| 148 | |
| 149 | >>> mock = MagicMock() |
| 150 | >>> mock.method() |
| 151 | <MagicMock name='mock.method()' id='...'> |
| 152 | >>> mock.attribute.method(10, x=53) |
| 153 | <MagicMock name='mock.attribute.method()' id='...'> |
| 154 | >>> mock.mock_calls |
| 155 | [call.method(), call.attribute.method(10, x=53)] |
| 156 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 157 | If you make an assertion about ``mock_calls`` and any unexpected methods |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 158 | have been called, then the assertion will fail. This is useful because as well |
| 159 | as asserting that the calls you expected have been made, you are also checking |
| 160 | that they were made in the right order and with no additional calls: |
| 161 | |
| 162 | You use the :data:`call` object to construct lists for comparing with |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 163 | ``mock_calls``: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 164 | |
| 165 | >>> expected = [call.method(), call.attribute.method(10, x=53)] |
| 166 | >>> mock.mock_calls == expected |
| 167 | True |
| 168 | |
Chris Withers | 8ca0fa9 | 2018-12-03 21:31:37 +0000 | [diff] [blame] | 169 | However, parameters to calls that return mocks are not recorded, which means it is not |
| 170 | possible to track nested calls where the parameters used to create ancestors are important: |
| 171 | |
| 172 | >>> m = Mock() |
| 173 | >>> m.factory(important=True).deliver() |
| 174 | <Mock name='mock.factory().deliver()' id='...'> |
| 175 | >>> m.mock_calls[-1] == call.factory(important=False).deliver() |
| 176 | True |
| 177 | |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 178 | |
| 179 | Setting Return Values and Attributes |
| 180 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 181 | |
| 182 | Setting the return values on a mock object is trivially easy: |
| 183 | |
| 184 | >>> mock = Mock() |
| 185 | >>> mock.return_value = 3 |
| 186 | >>> mock() |
| 187 | 3 |
| 188 | |
| 189 | Of course you can do the same for methods on the mock: |
| 190 | |
| 191 | >>> mock = Mock() |
| 192 | >>> mock.method.return_value = 3 |
| 193 | >>> mock.method() |
| 194 | 3 |
| 195 | |
| 196 | The return value can also be set in the constructor: |
| 197 | |
| 198 | >>> mock = Mock(return_value=3) |
| 199 | >>> mock() |
| 200 | 3 |
| 201 | |
| 202 | If you need an attribute setting on your mock, just do it: |
| 203 | |
| 204 | >>> mock = Mock() |
| 205 | >>> mock.x = 3 |
| 206 | >>> mock.x |
| 207 | 3 |
| 208 | |
| 209 | Sometimes you want to mock up a more complex situation, like for example |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 210 | ``mock.connection.cursor().execute("SELECT 1")``. If we wanted this call to |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 211 | return a list, then we have to configure the result of the nested call. |
| 212 | |
| 213 | We can use :data:`call` to construct the set of calls in a "chained call" like |
| 214 | this for easy assertion afterwards: |
| 215 | |
| 216 | >>> mock = Mock() |
| 217 | >>> cursor = mock.connection.cursor.return_value |
| 218 | >>> cursor.execute.return_value = ['foo'] |
| 219 | >>> mock.connection.cursor().execute("SELECT 1") |
| 220 | ['foo'] |
| 221 | >>> expected = call.connection.cursor().execute("SELECT 1").call_list() |
| 222 | >>> mock.mock_calls |
| 223 | [call.connection.cursor(), call.connection.cursor().execute('SELECT 1')] |
| 224 | >>> mock.mock_calls == expected |
| 225 | True |
| 226 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 227 | It is the call to ``.call_list()`` that turns our call object into a list of |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 228 | calls representing the chained calls. |
| 229 | |
| 230 | |
| 231 | Raising exceptions with mocks |
| 232 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 233 | |
| 234 | A useful attribute is :attr:`~Mock.side_effect`. If you set this to an |
| 235 | exception class or instance then the exception will be raised when the mock |
| 236 | is called. |
| 237 | |
| 238 | >>> mock = Mock(side_effect=Exception('Boom!')) |
| 239 | >>> mock() |
| 240 | Traceback (most recent call last): |
| 241 | ... |
| 242 | Exception: Boom! |
| 243 | |
| 244 | |
| 245 | Side effect functions and iterables |
| 246 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 247 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 248 | ``side_effect`` can also be set to a function or an iterable. The use case for |
| 249 | ``side_effect`` as an iterable is where your mock is going to be called several |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 250 | times, and you want each call to return a different value. When you set |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 251 | ``side_effect`` to an iterable every call to the mock returns the next value |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 252 | from the iterable: |
| 253 | |
| 254 | >>> mock = MagicMock(side_effect=[4, 5, 6]) |
| 255 | >>> mock() |
| 256 | 4 |
| 257 | >>> mock() |
| 258 | 5 |
| 259 | >>> mock() |
| 260 | 6 |
| 261 | |
| 262 | |
| 263 | For more advanced use cases, like dynamically varying the return values |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 264 | depending on what the mock is called with, ``side_effect`` can be a function. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 265 | The function will be called with the same arguments as the mock. Whatever the |
| 266 | function returns is what the call returns: |
| 267 | |
| 268 | >>> vals = {(1, 2): 1, (2, 3): 2} |
| 269 | >>> def side_effect(*args): |
| 270 | ... return vals[args] |
| 271 | ... |
| 272 | >>> mock = MagicMock(side_effect=side_effect) |
| 273 | >>> mock(1, 2) |
| 274 | 1 |
| 275 | >>> mock(2, 3) |
| 276 | 2 |
| 277 | |
| 278 | |
| 279 | Creating a Mock from an Existing Object |
| 280 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 281 | |
| 282 | One problem with over use of mocking is that it couples your tests to the |
| 283 | implementation of your mocks rather than your real code. Suppose you have a |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 284 | class that implements ``some_method``. In a test for another class, you |
| 285 | provide a mock of this object that *also* provides ``some_method``. If later |
| 286 | you refactor the first class, so that it no longer has ``some_method`` - then |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 287 | your tests will continue to pass even though your code is now broken! |
| 288 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 289 | :class:`Mock` allows you to provide an object as a specification for the mock, |
| 290 | using the *spec* keyword argument. Accessing methods / attributes on the |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 291 | mock that don't exist on your specification object will immediately raise an |
| 292 | attribute error. If you change the implementation of your specification, then |
| 293 | tests that use that class will start failing immediately without you having to |
| 294 | instantiate the class in those tests. |
| 295 | |
| 296 | >>> mock = Mock(spec=SomeClass) |
| 297 | >>> mock.old_method() |
| 298 | Traceback (most recent call last): |
| 299 | ... |
| 300 | AttributeError: object has no attribute 'old_method' |
| 301 | |
Antoine Pitrou | 5c64df7 | 2013-02-03 00:23:58 +0100 | [diff] [blame] | 302 | Using a specification also enables a smarter matching of calls made to the |
| 303 | mock, regardless of whether some parameters were passed as positional or |
| 304 | named arguments:: |
| 305 | |
| 306 | >>> def f(a, b, c): pass |
| 307 | ... |
| 308 | >>> mock = Mock(spec=f) |
| 309 | >>> mock(1, 2, 3) |
| 310 | <Mock name='mock()' id='140161580456576'> |
| 311 | >>> mock.assert_called_with(a=1, b=2, c=3) |
| 312 | |
| 313 | If you want this smarter matching to also work with method calls on the mock, |
| 314 | you can use :ref:`auto-speccing <auto-speccing>`. |
| 315 | |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 316 | If you want a stronger form of specification that prevents the setting |
| 317 | of arbitrary attributes as well as the getting of them then you can use |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 318 | *spec_set* instead of *spec*. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 319 | |
| 320 | |
| 321 | |
| 322 | Patch Decorators |
| 323 | ---------------- |
| 324 | |
| 325 | .. note:: |
| 326 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 327 | With :func:`patch` it matters that you patch objects in the namespace where |
| 328 | they are looked up. This is normally straightforward, but for a quick guide |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 329 | read :ref:`where to patch <where-to-patch>`. |
| 330 | |
| 331 | |
| 332 | A common need in tests is to patch a class attribute or a module attribute, |
| 333 | for example patching a builtin or patching a class in a module to test that it |
| 334 | is instantiated. Modules and classes are effectively global, so patching on |
| 335 | them has to be undone after the test or the patch will persist into other |
| 336 | tests and cause hard to diagnose problems. |
| 337 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 338 | mock provides three convenient decorators for this: :func:`patch`, :func:`patch.object` and |
| 339 | :func:`patch.dict`. ``patch`` takes a single string, of the form |
| 340 | ``package.module.Class.attribute`` to specify the attribute you are patching. It |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 341 | also optionally takes a value that you want the attribute (or class or |
| 342 | whatever) to be replaced with. 'patch.object' takes an object and the name of |
| 343 | the attribute you would like patched, plus optionally the value to patch it |
| 344 | with. |
| 345 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 346 | ``patch.object``:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 347 | |
| 348 | >>> original = SomeClass.attribute |
| 349 | >>> @patch.object(SomeClass, 'attribute', sentinel.attribute) |
| 350 | ... def test(): |
| 351 | ... assert SomeClass.attribute == sentinel.attribute |
| 352 | ... |
| 353 | >>> test() |
| 354 | >>> assert SomeClass.attribute == original |
| 355 | |
| 356 | >>> @patch('package.module.attribute', sentinel.attribute) |
| 357 | ... def test(): |
| 358 | ... from package.module import attribute |
| 359 | ... assert attribute is sentinel.attribute |
| 360 | ... |
| 361 | >>> test() |
| 362 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 363 | If you are patching a module (including :mod:`builtins`) then use :func:`patch` |
| 364 | instead of :func:`patch.object`: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 365 | |
Ezio Melotti | b40a220 | 2013-03-30 05:55:52 +0200 | [diff] [blame] | 366 | >>> mock = MagicMock(return_value=sentinel.file_handle) |
| 367 | >>> with patch('builtins.open', mock): |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 368 | ... handle = open('filename', 'r') |
| 369 | ... |
| 370 | >>> mock.assert_called_with('filename', 'r') |
| 371 | >>> assert handle == sentinel.file_handle, "incorrect file handle returned" |
| 372 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 373 | The module name can be 'dotted', in the form ``package.module`` if needed:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 374 | |
| 375 | >>> @patch('package.module.ClassName.attribute', sentinel.attribute) |
| 376 | ... def test(): |
| 377 | ... from package.module import ClassName |
| 378 | ... assert ClassName.attribute == sentinel.attribute |
| 379 | ... |
| 380 | >>> test() |
| 381 | |
| 382 | A nice pattern is to actually decorate test methods themselves: |
| 383 | |
Berker Peksag | b31daff | 2016-04-02 04:32:06 +0300 | [diff] [blame] | 384 | >>> class MyTest(unittest.TestCase): |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 385 | ... @patch.object(SomeClass, 'attribute', sentinel.attribute) |
| 386 | ... def test_something(self): |
| 387 | ... self.assertEqual(SomeClass.attribute, sentinel.attribute) |
| 388 | ... |
| 389 | >>> original = SomeClass.attribute |
| 390 | >>> MyTest('test_something').test_something() |
| 391 | >>> assert SomeClass.attribute == original |
| 392 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 393 | If you want to patch with a Mock, you can use :func:`patch` with only one argument |
| 394 | (or :func:`patch.object` with two arguments). The mock will be created for you and |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 395 | passed into the test function / method: |
| 396 | |
Berker Peksag | b31daff | 2016-04-02 04:32:06 +0300 | [diff] [blame] | 397 | >>> class MyTest(unittest.TestCase): |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 398 | ... @patch.object(SomeClass, 'static_method') |
| 399 | ... def test_something(self, mock_method): |
| 400 | ... SomeClass.static_method() |
| 401 | ... mock_method.assert_called_with() |
| 402 | ... |
| 403 | >>> MyTest('test_something').test_something() |
| 404 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 405 | You can stack up multiple patch decorators using this pattern:: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 406 | |
Berker Peksag | b31daff | 2016-04-02 04:32:06 +0300 | [diff] [blame] | 407 | >>> class MyTest(unittest.TestCase): |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 408 | ... @patch('package.module.ClassName1') |
| 409 | ... @patch('package.module.ClassName2') |
| 410 | ... def test_something(self, MockClass2, MockClass1): |
Ezio Melotti | e212370 | 2013-01-10 03:43:33 +0200 | [diff] [blame] | 411 | ... self.assertIs(package.module.ClassName1, MockClass1) |
| 412 | ... self.assertIs(package.module.ClassName2, MockClass2) |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 413 | ... |
| 414 | >>> MyTest('test_something').test_something() |
| 415 | |
| 416 | When you nest patch decorators the mocks are passed in to the decorated |
Andrés Delfino | 271818f | 2018-09-14 14:13:09 -0300 | [diff] [blame] | 417 | function in the same order they applied (the normal *Python* order that |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 418 | decorators are applied). This means from the bottom up, so in the example |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 419 | above the mock for ``test_module.ClassName2`` is passed in first. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 420 | |
| 421 | There is also :func:`patch.dict` for setting values in a dictionary just |
| 422 | during a scope and restoring the dictionary to its original state when the test |
| 423 | ends: |
| 424 | |
| 425 | >>> foo = {'key': 'value'} |
| 426 | >>> original = foo.copy() |
| 427 | >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True): |
| 428 | ... assert foo == {'newkey': 'newvalue'} |
| 429 | ... |
| 430 | >>> assert foo == original |
| 431 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 432 | ``patch``, ``patch.object`` and ``patch.dict`` can all be used as context managers. |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 433 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 434 | Where you use :func:`patch` to create a mock for you, you can get a reference to the |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 435 | mock using the "as" form of the with statement: |
| 436 | |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 437 | >>> class ProductionClass: |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 438 | ... def method(self): |
| 439 | ... pass |
| 440 | ... |
| 441 | >>> with patch.object(ProductionClass, 'method') as mock_method: |
| 442 | ... mock_method.return_value = None |
| 443 | ... real = ProductionClass() |
| 444 | ... real.method(1, 2, 3) |
| 445 | ... |
| 446 | >>> mock_method.assert_called_with(1, 2, 3) |
| 447 | |
| 448 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 449 | As an alternative ``patch``, ``patch.object`` and ``patch.dict`` can be used as |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 450 | class decorators. When used in this way it is the same as applying the |
Larry Hastings | 3732ed2 | 2014-03-15 21:13:56 -0700 | [diff] [blame] | 451 | decorator individually to every method whose name starts with "test". |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 452 | |
| 453 | |
| 454 | .. _further-examples: |
| 455 | |
| 456 | Further Examples |
Georg Brandl | 7fc972a | 2013-02-03 14:00:04 +0100 | [diff] [blame] | 457 | ---------------- |
Michael Foord | a9e6fb2 | 2012-03-28 14:36:02 +0100 | [diff] [blame] | 458 | |
| 459 | |
| 460 | Here are some more examples for some slightly more advanced scenarios. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 461 | |
| 462 | |
| 463 | Mocking chained calls |
Georg Brandl | 7fc972a | 2013-02-03 14:00:04 +0100 | [diff] [blame] | 464 | ~~~~~~~~~~~~~~~~~~~~~ |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 465 | |
| 466 | Mocking chained calls is actually straightforward with mock once you |
| 467 | understand the :attr:`~Mock.return_value` attribute. When a mock is called for |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 468 | the first time, or you fetch its ``return_value`` before it has been called, a |
| 469 | new :class:`Mock` is created. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 470 | |
| 471 | This means that you can see how the object returned from a call to a mocked |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 472 | object has been used by interrogating the ``return_value`` mock: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 473 | |
| 474 | >>> mock = Mock() |
| 475 | >>> mock().foo(a=2, b=3) |
| 476 | <Mock name='mock().foo()' id='...'> |
| 477 | >>> mock.return_value.foo.assert_called_with(a=2, b=3) |
| 478 | |
| 479 | From here it is a simple step to configure and then make assertions about |
| 480 | chained calls. Of course another alternative is writing your code in a more |
| 481 | testable way in the first place... |
| 482 | |
| 483 | So, suppose we have some code that looks a little bit like this: |
| 484 | |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 485 | >>> class Something: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 486 | ... def __init__(self): |
| 487 | ... self.backend = BackendProvider() |
| 488 | ... def method(self): |
| 489 | ... response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call() |
| 490 | ... # more code |
| 491 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 492 | Assuming that ``BackendProvider`` is already well tested, how do we test |
| 493 | ``method()``? Specifically, we want to test that the code section ``# more |
| 494 | code`` uses the response object in the correct way. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 495 | |
| 496 | As this chain of calls is made from an instance attribute we can monkey patch |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 497 | the ``backend`` attribute on a ``Something`` instance. In this particular case |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 498 | we are only interested in the return value from the final call to |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 499 | ``start_call`` so we don't have much configuration to do. Let's assume the |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 500 | object it returns is 'file-like', so we'll ensure that our response object |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 501 | uses the builtin :func:`open` as its ``spec``. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 502 | |
| 503 | To do this we create a mock instance as our mock backend and create a mock |
| 504 | response object for it. To set the response as the return value for that final |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 505 | ``start_call`` we could do this:: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 506 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 507 | mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 508 | |
| 509 | We can do that in a slightly nicer way using the :meth:`~Mock.configure_mock` |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 510 | method to directly set the return value for us:: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 511 | |
| 512 | >>> something = Something() |
Terry Jan Reedy | 30ffe7e | 2014-01-21 00:01:51 -0500 | [diff] [blame] | 513 | >>> mock_response = Mock(spec=open) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 514 | >>> mock_backend = Mock() |
| 515 | >>> config = {'get_endpoint.return_value.create_call.return_value.start_call.return_value': mock_response} |
| 516 | >>> mock_backend.configure_mock(**config) |
| 517 | |
| 518 | With these we monkey patch the "mock backend" in place and can make the real |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 519 | call:: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 520 | |
| 521 | >>> something.backend = mock_backend |
| 522 | >>> something.method() |
| 523 | |
| 524 | Using :attr:`~Mock.mock_calls` we can check the chained call with a single |
| 525 | assert. A chained call is several calls in one line of code, so there will be |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 526 | several entries in ``mock_calls``. We can use :meth:`call.call_list` to create |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 527 | this list of calls for us:: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 528 | |
| 529 | >>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call() |
| 530 | >>> call_list = chained.call_list() |
| 531 | >>> assert mock_backend.mock_calls == call_list |
| 532 | |
| 533 | |
| 534 | Partial mocking |
Georg Brandl | 7fc972a | 2013-02-03 14:00:04 +0100 | [diff] [blame] | 535 | ~~~~~~~~~~~~~~~ |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 536 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 537 | In some tests I wanted to mock out a call to :meth:`datetime.date.today` |
Georg Brandl | 728e4de | 2014-10-29 09:00:30 +0100 | [diff] [blame] | 538 | to return a known date, but I didn't want to prevent the code under test from |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 539 | creating new date objects. Unfortunately :class:`datetime.date` is written in C, and |
| 540 | so I couldn't just monkey-patch out the static :meth:`date.today` method. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 541 | |
| 542 | I found a simple way of doing this that involved effectively wrapping the date |
| 543 | class with a mock, but passing through calls to the constructor to the real |
| 544 | class (and returning real instances). |
| 545 | |
| 546 | The :func:`patch decorator <patch>` is used here to |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 547 | mock out the ``date`` class in the module under test. The :attr:`side_effect` |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 548 | attribute on the mock date class is then set to a lambda function that returns |
| 549 | a real date. When the mock date class is called a real date will be |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 550 | constructed and returned by ``side_effect``. :: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 551 | |
| 552 | >>> from datetime import date |
| 553 | >>> with patch('mymodule.date') as mock_date: |
| 554 | ... mock_date.today.return_value = date(2010, 10, 8) |
| 555 | ... mock_date.side_effect = lambda *args, **kw: date(*args, **kw) |
| 556 | ... |
| 557 | ... assert mymodule.date.today() == date(2010, 10, 8) |
| 558 | ... assert mymodule.date(2009, 6, 8) == date(2009, 6, 8) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 559 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 560 | Note that we don't patch :class:`datetime.date` globally, we patch ``date`` in the |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 561 | module that *uses* it. See :ref:`where to patch <where-to-patch>`. |
| 562 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 563 | When ``date.today()`` is called a known date is returned, but calls to the |
| 564 | ``date(...)`` constructor still return normal dates. Without this you can find |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 565 | yourself having to calculate an expected result using exactly the same |
| 566 | algorithm as the code under test, which is a classic testing anti-pattern. |
| 567 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 568 | Calls to the date constructor are recorded in the ``mock_date`` attributes |
| 569 | (``call_count`` and friends) which may also be useful for your tests. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 570 | |
| 571 | An alternative way of dealing with mocking dates, or other builtin classes, |
| 572 | is discussed in `this blog entry |
Serhiy Storchaka | 6dff020 | 2016-05-07 10:49:07 +0300 | [diff] [blame] | 573 | <https://williambert.online/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/>`_. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 574 | |
| 575 | |
| 576 | Mocking a Generator Method |
Georg Brandl | 7fc972a | 2013-02-03 14:00:04 +0100 | [diff] [blame] | 577 | ~~~~~~~~~~~~~~~~~~~~~~~~~~ |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 578 | |
Georg Brandl | 728e4de | 2014-10-29 09:00:30 +0100 | [diff] [blame] | 579 | A Python generator is a function or method that uses the :keyword:`yield` statement |
| 580 | to return a series of values when iterated over [#]_. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 581 | |
| 582 | A generator method / function is called to return the generator object. It is |
| 583 | the generator object that is then iterated over. The protocol method for |
Georg Brandl | 728e4de | 2014-10-29 09:00:30 +0100 | [diff] [blame] | 584 | iteration is :meth:`~container.__iter__`, so we can |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 585 | mock this using a :class:`MagicMock`. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 586 | |
| 587 | Here's an example class with an "iter" method implemented as a generator: |
| 588 | |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 589 | >>> class Foo: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 590 | ... def iter(self): |
| 591 | ... for i in [1, 2, 3]: |
| 592 | ... yield i |
| 593 | ... |
| 594 | >>> foo = Foo() |
| 595 | >>> list(foo.iter()) |
| 596 | [1, 2, 3] |
| 597 | |
| 598 | |
| 599 | How would we mock this class, and in particular its "iter" method? |
| 600 | |
| 601 | To configure the values returned from the iteration (implicit in the call to |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 602 | :class:`list`), we need to configure the object returned by the call to ``foo.iter()``. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 603 | |
| 604 | >>> mock_foo = MagicMock() |
| 605 | >>> mock_foo.iter.return_value = iter([1, 2, 3]) |
| 606 | >>> list(mock_foo.iter()) |
| 607 | [1, 2, 3] |
| 608 | |
| 609 | .. [#] There are also generator expressions and more `advanced uses |
| 610 | <http://www.dabeaz.com/coroutines/index.html>`_ of generators, but we aren't |
| 611 | concerned about them here. A very good introduction to generators and how |
| 612 | powerful they are is: `Generator Tricks for Systems Programmers |
| 613 | <http://www.dabeaz.com/generators/>`_. |
| 614 | |
| 615 | |
| 616 | Applying the same patch to every test method |
Georg Brandl | 7fc972a | 2013-02-03 14:00:04 +0100 | [diff] [blame] | 617 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 618 | |
| 619 | If you want several patches in place for multiple test methods the obvious way |
| 620 | is to apply the patch decorators to every method. This can feel like unnecessary |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 621 | repetition. For Python 2.6 or more recent you can use :func:`patch` (in all its |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 622 | various forms) as a class decorator. This applies the patches to all test |
| 623 | methods on the class. A test method is identified by methods whose names start |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 624 | with ``test``:: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 625 | |
| 626 | >>> @patch('mymodule.SomeClass') |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 627 | ... class MyTest(unittest.TestCase): |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 628 | ... |
| 629 | ... def test_one(self, MockSomeClass): |
Ezio Melotti | e212370 | 2013-01-10 03:43:33 +0200 | [diff] [blame] | 630 | ... self.assertIs(mymodule.SomeClass, MockSomeClass) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 631 | ... |
| 632 | ... def test_two(self, MockSomeClass): |
Ezio Melotti | e212370 | 2013-01-10 03:43:33 +0200 | [diff] [blame] | 633 | ... self.assertIs(mymodule.SomeClass, MockSomeClass) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 634 | ... |
| 635 | ... def not_a_test(self): |
| 636 | ... return 'something' |
| 637 | ... |
| 638 | >>> MyTest('test_one').test_one() |
| 639 | >>> MyTest('test_two').test_two() |
| 640 | >>> MyTest('test_two').not_a_test() |
| 641 | 'something' |
| 642 | |
| 643 | An alternative way of managing patches is to use the :ref:`start-and-stop`. |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 644 | These allow you to move the patching into your ``setUp`` and ``tearDown`` methods. |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 645 | :: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 646 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 647 | >>> class MyTest(unittest.TestCase): |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 648 | ... def setUp(self): |
| 649 | ... self.patcher = patch('mymodule.foo') |
| 650 | ... self.mock_foo = self.patcher.start() |
| 651 | ... |
| 652 | ... def test_foo(self): |
Ezio Melotti | e212370 | 2013-01-10 03:43:33 +0200 | [diff] [blame] | 653 | ... self.assertIs(mymodule.foo, self.mock_foo) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 654 | ... |
| 655 | ... def tearDown(self): |
| 656 | ... self.patcher.stop() |
| 657 | ... |
| 658 | >>> MyTest('test_foo').run() |
| 659 | |
| 660 | If you use this technique you must ensure that the patching is "undone" by |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 661 | calling ``stop``. This can be fiddlier than you might think, because if an |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 662 | exception is raised in the setUp then tearDown is not called. |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 663 | :meth:`unittest.TestCase.addCleanup` makes this easier:: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 664 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 665 | >>> class MyTest(unittest.TestCase): |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 666 | ... def setUp(self): |
| 667 | ... patcher = patch('mymodule.foo') |
| 668 | ... self.addCleanup(patcher.stop) |
| 669 | ... self.mock_foo = patcher.start() |
| 670 | ... |
| 671 | ... def test_foo(self): |
Ezio Melotti | e212370 | 2013-01-10 03:43:33 +0200 | [diff] [blame] | 672 | ... self.assertIs(mymodule.foo, self.mock_foo) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 673 | ... |
| 674 | >>> MyTest('test_foo').run() |
| 675 | |
| 676 | |
| 677 | Mocking Unbound Methods |
Georg Brandl | 7fc972a | 2013-02-03 14:00:04 +0100 | [diff] [blame] | 678 | ~~~~~~~~~~~~~~~~~~~~~~~ |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 679 | |
| 680 | Whilst writing tests today I needed to patch an *unbound method* (patching the |
| 681 | method on the class rather than on the instance). I needed self to be passed |
| 682 | in as the first argument because I want to make asserts about which objects |
| 683 | were calling this particular method. The issue is that you can't patch with a |
| 684 | mock for this, because if you replace an unbound method with a mock it doesn't |
| 685 | become a bound method when fetched from the instance, and so it doesn't get |
| 686 | self passed in. The workaround is to patch the unbound method with a real |
| 687 | function instead. The :func:`patch` decorator makes it so simple to |
| 688 | patch out methods with a mock that having to create a real function becomes a |
| 689 | nuisance. |
| 690 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 691 | If you pass ``autospec=True`` to patch then it does the patching with a |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 692 | *real* function object. This function object has the same signature as the one |
| 693 | it is replacing, but delegates to a mock under the hood. You still get your |
| 694 | mock auto-created in exactly the same way as before. What it means though, is |
| 695 | that if you use it to patch out an unbound method on a class the mocked |
| 696 | function will be turned into a bound method if it is fetched from an instance. |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 697 | It will have ``self`` passed in as the first argument, which is exactly what I |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 698 | wanted: |
| 699 | |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 700 | >>> class Foo: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 701 | ... def foo(self): |
| 702 | ... pass |
| 703 | ... |
| 704 | >>> with patch.object(Foo, 'foo', autospec=True) as mock_foo: |
| 705 | ... mock_foo.return_value = 'foo' |
| 706 | ... foo = Foo() |
| 707 | ... foo.foo() |
| 708 | ... |
| 709 | 'foo' |
| 710 | >>> mock_foo.assert_called_once_with(foo) |
| 711 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 712 | If we don't use ``autospec=True`` then the unbound method is patched out |
| 713 | with a Mock instance instead, and isn't called with ``self``. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 714 | |
| 715 | |
| 716 | Checking multiple calls with mock |
Georg Brandl | 7fc972a | 2013-02-03 14:00:04 +0100 | [diff] [blame] | 717 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 718 | |
| 719 | mock has a nice API for making assertions about how your mock objects are used. |
| 720 | |
| 721 | >>> mock = Mock() |
| 722 | >>> mock.foo_bar.return_value = None |
| 723 | >>> mock.foo_bar('baz', spam='eggs') |
| 724 | >>> mock.foo_bar.assert_called_with('baz', spam='eggs') |
| 725 | |
| 726 | If your mock is only being called once you can use the |
| 727 | :meth:`assert_called_once_with` method that also asserts that the |
| 728 | :attr:`call_count` is one. |
| 729 | |
| 730 | >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs') |
| 731 | >>> mock.foo_bar() |
| 732 | >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs') |
| 733 | Traceback (most recent call last): |
| 734 | ... |
| 735 | AssertionError: Expected to be called once. Called 2 times. |
| 736 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 737 | Both ``assert_called_with`` and ``assert_called_once_with`` make assertions about |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 738 | the *most recent* call. If your mock is going to be called several times, and |
| 739 | you want to make assertions about *all* those calls you can use |
| 740 | :attr:`~Mock.call_args_list`: |
| 741 | |
| 742 | >>> mock = Mock(return_value=None) |
| 743 | >>> mock(1, 2, 3) |
| 744 | >>> mock(4, 5, 6) |
| 745 | >>> mock() |
| 746 | >>> mock.call_args_list |
| 747 | [call(1, 2, 3), call(4, 5, 6), call()] |
| 748 | |
| 749 | The :data:`call` helper makes it easy to make assertions about these calls. You |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 750 | can build up a list of expected calls and compare it to ``call_args_list``. This |
| 751 | looks remarkably similar to the repr of the ``call_args_list``: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 752 | |
| 753 | >>> expected = [call(1, 2, 3), call(4, 5, 6), call()] |
| 754 | >>> mock.call_args_list == expected |
| 755 | True |
| 756 | |
| 757 | |
| 758 | Coping with mutable arguments |
Georg Brandl | 7fc972a | 2013-02-03 14:00:04 +0100 | [diff] [blame] | 759 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 760 | |
| 761 | Another situation is rare, but can bite you, is when your mock is called with |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 762 | mutable arguments. ``call_args`` and ``call_args_list`` store *references* to the |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 763 | arguments. If the arguments are mutated by the code under test then you can no |
| 764 | longer make assertions about what the values were when the mock was called. |
| 765 | |
| 766 | Here's some example code that shows the problem. Imagine the following functions |
| 767 | defined in 'mymodule':: |
| 768 | |
| 769 | def frob(val): |
| 770 | pass |
| 771 | |
| 772 | def grob(val): |
| 773 | "First frob and then clear val" |
| 774 | frob(val) |
| 775 | val.clear() |
| 776 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 777 | When we try to test that ``grob`` calls ``frob`` with the correct argument look |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 778 | what happens:: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 779 | |
| 780 | >>> with patch('mymodule.frob') as mock_frob: |
Serhiy Storchaka | c02d188 | 2014-12-11 10:28:14 +0200 | [diff] [blame] | 781 | ... val = {6} |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 782 | ... mymodule.grob(val) |
| 783 | ... |
| 784 | >>> val |
Serhiy Storchaka | c02d188 | 2014-12-11 10:28:14 +0200 | [diff] [blame] | 785 | set() |
| 786 | >>> mock_frob.assert_called_with({6}) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 787 | Traceback (most recent call last): |
| 788 | ... |
Serhiy Storchaka | c02d188 | 2014-12-11 10:28:14 +0200 | [diff] [blame] | 789 | AssertionError: Expected: (({6},), {}) |
| 790 | Called with: ((set(),), {}) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 791 | |
| 792 | One possibility would be for mock to copy the arguments you pass in. This |
| 793 | could then cause problems if you do assertions that rely on object identity |
| 794 | for equality. |
| 795 | |
| 796 | Here's one solution that uses the :attr:`side_effect` |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 797 | functionality. If you provide a ``side_effect`` function for a mock then |
| 798 | ``side_effect`` will be called with the same args as the mock. This gives us an |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 799 | opportunity to copy the arguments and store them for later assertions. In this |
| 800 | example I'm using *another* mock to store the arguments so that I can use the |
| 801 | mock methods for doing the assertion. Again a helper function sets this up for |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 802 | me. :: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 803 | |
| 804 | >>> from copy import deepcopy |
| 805 | >>> from unittest.mock import Mock, patch, DEFAULT |
| 806 | >>> def copy_call_args(mock): |
| 807 | ... new_mock = Mock() |
| 808 | ... def side_effect(*args, **kwargs): |
| 809 | ... args = deepcopy(args) |
| 810 | ... kwargs = deepcopy(kwargs) |
| 811 | ... new_mock(*args, **kwargs) |
| 812 | ... return DEFAULT |
| 813 | ... mock.side_effect = side_effect |
| 814 | ... return new_mock |
| 815 | ... |
| 816 | >>> with patch('mymodule.frob') as mock_frob: |
| 817 | ... new_mock = copy_call_args(mock_frob) |
Serhiy Storchaka | c02d188 | 2014-12-11 10:28:14 +0200 | [diff] [blame] | 818 | ... val = {6} |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 819 | ... mymodule.grob(val) |
| 820 | ... |
Serhiy Storchaka | c02d188 | 2014-12-11 10:28:14 +0200 | [diff] [blame] | 821 | >>> new_mock.assert_called_with({6}) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 822 | >>> new_mock.call_args |
Serhiy Storchaka | c02d188 | 2014-12-11 10:28:14 +0200 | [diff] [blame] | 823 | call({6}) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 824 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 825 | ``copy_call_args`` is called with the mock that will be called. It returns a new |
| 826 | mock that we do the assertion on. The ``side_effect`` function makes a copy of |
| 827 | the args and calls our ``new_mock`` with the copy. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 828 | |
| 829 | .. note:: |
| 830 | |
| 831 | If your mock is only going to be used once there is an easier way of |
| 832 | checking arguments at the point they are called. You can simply do the |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 833 | checking inside a ``side_effect`` function. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 834 | |
| 835 | >>> def side_effect(arg): |
Serhiy Storchaka | c02d188 | 2014-12-11 10:28:14 +0200 | [diff] [blame] | 836 | ... assert arg == {6} |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 837 | ... |
| 838 | >>> mock = Mock(side_effect=side_effect) |
Serhiy Storchaka | c02d188 | 2014-12-11 10:28:14 +0200 | [diff] [blame] | 839 | >>> mock({6}) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 840 | >>> mock(set()) |
| 841 | Traceback (most recent call last): |
| 842 | ... |
| 843 | AssertionError |
| 844 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 845 | An alternative approach is to create a subclass of :class:`Mock` or |
| 846 | :class:`MagicMock` that copies (using :func:`copy.deepcopy`) the arguments. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 847 | Here's an example implementation: |
| 848 | |
| 849 | >>> from copy import deepcopy |
| 850 | >>> class CopyingMock(MagicMock): |
| 851 | ... def __call__(self, *args, **kwargs): |
| 852 | ... args = deepcopy(args) |
| 853 | ... kwargs = deepcopy(kwargs) |
| 854 | ... return super(CopyingMock, self).__call__(*args, **kwargs) |
| 855 | ... |
| 856 | >>> c = CopyingMock(return_value=None) |
| 857 | >>> arg = set() |
| 858 | >>> c(arg) |
| 859 | >>> arg.add(1) |
| 860 | >>> c.assert_called_with(set()) |
| 861 | >>> c.assert_called_with(arg) |
| 862 | Traceback (most recent call last): |
| 863 | ... |
Serhiy Storchaka | c02d188 | 2014-12-11 10:28:14 +0200 | [diff] [blame] | 864 | AssertionError: Expected call: mock({1}) |
| 865 | Actual call: mock(set()) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 866 | >>> c.foo |
| 867 | <CopyingMock name='mock.foo' id='...'> |
| 868 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 869 | When you subclass ``Mock`` or ``MagicMock`` all dynamically created attributes, |
| 870 | and the ``return_value`` will use your subclass automatically. That means all |
| 871 | children of a ``CopyingMock`` will also have the type ``CopyingMock``. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 872 | |
| 873 | |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 874 | Nesting Patches |
Georg Brandl | 7fc972a | 2013-02-03 14:00:04 +0100 | [diff] [blame] | 875 | ~~~~~~~~~~~~~~~ |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 876 | |
| 877 | Using patch as a context manager is nice, but if you do multiple patches you |
| 878 | can end up with nested with statements indenting further and further to the |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 879 | right:: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 880 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 881 | >>> class MyTest(unittest.TestCase): |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 882 | ... |
| 883 | ... def test_foo(self): |
| 884 | ... with patch('mymodule.Foo') as mock_foo: |
| 885 | ... with patch('mymodule.Bar') as mock_bar: |
| 886 | ... with patch('mymodule.Spam') as mock_spam: |
| 887 | ... assert mymodule.Foo is mock_foo |
| 888 | ... assert mymodule.Bar is mock_bar |
| 889 | ... assert mymodule.Spam is mock_spam |
| 890 | ... |
| 891 | >>> original = mymodule.Foo |
| 892 | >>> MyTest('test_foo').test_foo() |
| 893 | >>> assert mymodule.Foo is original |
| 894 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 895 | With unittest ``cleanup`` functions and the :ref:`start-and-stop` we can |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 896 | achieve the same effect without the nested indentation. A simple helper |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 897 | method, ``create_patch``, puts the patch in place and returns the created mock |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 898 | for us:: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 899 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 900 | >>> class MyTest(unittest.TestCase): |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 901 | ... |
| 902 | ... def create_patch(self, name): |
| 903 | ... patcher = patch(name) |
| 904 | ... thing = patcher.start() |
| 905 | ... self.addCleanup(patcher.stop) |
| 906 | ... return thing |
| 907 | ... |
| 908 | ... def test_foo(self): |
| 909 | ... mock_foo = self.create_patch('mymodule.Foo') |
| 910 | ... mock_bar = self.create_patch('mymodule.Bar') |
| 911 | ... mock_spam = self.create_patch('mymodule.Spam') |
| 912 | ... |
| 913 | ... assert mymodule.Foo is mock_foo |
| 914 | ... assert mymodule.Bar is mock_bar |
| 915 | ... assert mymodule.Spam is mock_spam |
| 916 | ... |
| 917 | >>> original = mymodule.Foo |
| 918 | >>> MyTest('test_foo').run() |
| 919 | >>> assert mymodule.Foo is original |
| 920 | |
| 921 | |
| 922 | Mocking a dictionary with MagicMock |
Georg Brandl | 7fc972a | 2013-02-03 14:00:04 +0100 | [diff] [blame] | 923 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 924 | |
| 925 | You may want to mock a dictionary, or other container object, recording all |
| 926 | access to it whilst having it still behave like a dictionary. |
| 927 | |
| 928 | We can do this with :class:`MagicMock`, which will behave like a dictionary, |
| 929 | and using :data:`~Mock.side_effect` to delegate dictionary access to a real |
| 930 | underlying dictionary that is under our control. |
| 931 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 932 | When the :meth:`__getitem__` and :meth:`__setitem__` methods of our ``MagicMock`` are called |
| 933 | (normal dictionary access) then ``side_effect`` is called with the key (and in |
| 934 | the case of ``__setitem__`` the value too). We can also control what is returned. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 935 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 936 | After the ``MagicMock`` has been used we can use attributes like |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 937 | :data:`~Mock.call_args_list` to assert about how the dictionary was used: |
| 938 | |
| 939 | >>> my_dict = {'a': 1, 'b': 2, 'c': 3} |
| 940 | >>> def getitem(name): |
| 941 | ... return my_dict[name] |
| 942 | ... |
| 943 | >>> def setitem(name, val): |
| 944 | ... my_dict[name] = val |
| 945 | ... |
| 946 | >>> mock = MagicMock() |
| 947 | >>> mock.__getitem__.side_effect = getitem |
| 948 | >>> mock.__setitem__.side_effect = setitem |
| 949 | |
| 950 | .. note:: |
| 951 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 952 | An alternative to using ``MagicMock`` is to use ``Mock`` and *only* provide |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 953 | the magic methods you specifically want: |
| 954 | |
| 955 | >>> mock = Mock() |
Éric Araujo | 0b1be1a | 2014-03-17 16:48:13 -0400 | [diff] [blame] | 956 | >>> mock.__getitem__ = Mock(side_effect=getitem) |
| 957 | >>> mock.__setitem__ = Mock(side_effect=setitem) |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 958 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 959 | A *third* option is to use ``MagicMock`` but passing in ``dict`` as the *spec* |
| 960 | (or *spec_set*) argument so that the ``MagicMock`` created only has |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 961 | dictionary magic methods available: |
| 962 | |
| 963 | >>> mock = MagicMock(spec_set=dict) |
| 964 | >>> mock.__getitem__.side_effect = getitem |
| 965 | >>> mock.__setitem__.side_effect = setitem |
| 966 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 967 | With these side effect functions in place, the ``mock`` will behave like a normal |
| 968 | dictionary but recording the access. It even raises a :exc:`KeyError` if you try |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 969 | to access a key that doesn't exist. |
| 970 | |
| 971 | >>> mock['a'] |
| 972 | 1 |
| 973 | >>> mock['c'] |
| 974 | 3 |
| 975 | >>> mock['d'] |
| 976 | Traceback (most recent call last): |
| 977 | ... |
| 978 | KeyError: 'd' |
| 979 | >>> mock['b'] = 'fish' |
| 980 | >>> mock['d'] = 'eggs' |
| 981 | >>> mock['b'] |
| 982 | 'fish' |
| 983 | >>> mock['d'] |
| 984 | 'eggs' |
| 985 | |
| 986 | After it has been used you can make assertions about the access using the normal |
| 987 | mock methods and attributes: |
| 988 | |
| 989 | >>> mock.__getitem__.call_args_list |
| 990 | [call('a'), call('c'), call('d'), call('b'), call('d')] |
| 991 | >>> mock.__setitem__.call_args_list |
| 992 | [call('b', 'fish'), call('d', 'eggs')] |
| 993 | >>> my_dict |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 994 | {'a': 1, 'b': 'fish', 'c': 3, 'd': 'eggs'} |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 995 | |
| 996 | |
| 997 | Mock subclasses and their attributes |
Georg Brandl | 7fc972a | 2013-02-03 14:00:04 +0100 | [diff] [blame] | 998 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 999 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1000 | There are various reasons why you might want to subclass :class:`Mock`. One |
| 1001 | reason might be to add helper methods. Here's a silly example: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1002 | |
| 1003 | >>> class MyMock(MagicMock): |
| 1004 | ... def has_been_called(self): |
| 1005 | ... return self.called |
| 1006 | ... |
| 1007 | >>> mymock = MyMock(return_value=None) |
| 1008 | >>> mymock |
| 1009 | <MyMock id='...'> |
| 1010 | >>> mymock.has_been_called() |
| 1011 | False |
| 1012 | >>> mymock() |
| 1013 | >>> mymock.has_been_called() |
| 1014 | True |
| 1015 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1016 | The standard behaviour for ``Mock`` instances is that attributes and the return |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1017 | value mocks are of the same type as the mock they are accessed on. This ensures |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1018 | that ``Mock`` attributes are ``Mocks`` and ``MagicMock`` attributes are ``MagicMocks`` |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1019 | [#]_. So if you're subclassing to add helper methods then they'll also be |
| 1020 | available on the attributes and return value mock of instances of your |
| 1021 | subclass. |
| 1022 | |
| 1023 | >>> mymock.foo |
| 1024 | <MyMock name='mock.foo' id='...'> |
| 1025 | >>> mymock.foo.has_been_called() |
| 1026 | False |
| 1027 | >>> mymock.foo() |
| 1028 | <MyMock name='mock.foo()' id='...'> |
| 1029 | >>> mymock.foo.has_been_called() |
| 1030 | True |
| 1031 | |
| 1032 | Sometimes this is inconvenient. For example, `one user |
Sanyam Khurana | 338cd83 | 2018-01-20 05:55:37 +0530 | [diff] [blame] | 1033 | <https://code.google.com/archive/p/mock/issues/105>`_ is subclassing mock to |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1034 | created a `Twisted adaptor |
Serhiy Storchaka | 6dff020 | 2016-05-07 10:49:07 +0300 | [diff] [blame] | 1035 | <https://twistedmatrix.com/documents/11.0.0/api/twisted.python.components.html>`_. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1036 | Having this applied to attributes too actually causes errors. |
| 1037 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1038 | ``Mock`` (in all its flavours) uses a method called ``_get_child_mock`` to create |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1039 | these "sub-mocks" for attributes and return values. You can prevent your |
| 1040 | subclass being used for attributes by overriding this method. The signature is |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1041 | that it takes arbitrary keyword arguments (``**kwargs``) which are then passed |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1042 | onto the mock constructor: |
| 1043 | |
| 1044 | >>> class Subclass(MagicMock): |
| 1045 | ... def _get_child_mock(self, **kwargs): |
| 1046 | ... return MagicMock(**kwargs) |
| 1047 | ... |
| 1048 | >>> mymock = Subclass() |
| 1049 | >>> mymock.foo |
| 1050 | <MagicMock name='mock.foo' id='...'> |
| 1051 | >>> assert isinstance(mymock, Subclass) |
| 1052 | >>> assert not isinstance(mymock.foo, Subclass) |
| 1053 | >>> assert not isinstance(mymock(), Subclass) |
| 1054 | |
| 1055 | .. [#] An exception to this rule are the non-callable mocks. Attributes use the |
| 1056 | callable variant because otherwise non-callable mocks couldn't have callable |
| 1057 | methods. |
| 1058 | |
| 1059 | |
| 1060 | Mocking imports with patch.dict |
Georg Brandl | 7fc972a | 2013-02-03 14:00:04 +0100 | [diff] [blame] | 1061 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1062 | |
| 1063 | One situation where mocking can be hard is where you have a local import inside |
| 1064 | a function. These are harder to mock because they aren't using an object from |
| 1065 | the module namespace that we can patch out. |
| 1066 | |
| 1067 | Generally local imports are to be avoided. They are sometimes done to prevent |
| 1068 | circular dependencies, for which there is *usually* a much better way to solve |
| 1069 | the problem (refactor the code) or to prevent "up front costs" by delaying the |
| 1070 | import. This can also be solved in better ways than an unconditional local |
| 1071 | import (store the module as a class or module attribute and only do the import |
| 1072 | on first use). |
| 1073 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1074 | That aside there is a way to use ``mock`` to affect the results of an import. |
| 1075 | Importing fetches an *object* from the :data:`sys.modules` dictionary. Note that it |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1076 | fetches an *object*, which need not be a module. Importing a module for the |
| 1077 | first time results in a module object being put in `sys.modules`, so usually |
| 1078 | when you import something you get a module back. This need not be the case |
| 1079 | however. |
| 1080 | |
| 1081 | This means you can use :func:`patch.dict` to *temporarily* put a mock in place |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1082 | in :data:`sys.modules`. Any imports whilst this patch is active will fetch the mock. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1083 | When the patch is complete (the decorated function exits, the with statement |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1084 | body is complete or ``patcher.stop()`` is called) then whatever was there |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1085 | previously will be restored safely. |
| 1086 | |
| 1087 | Here's an example that mocks out the 'fooble' module. |
| 1088 | |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1089 | >>> import sys |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1090 | >>> mock = Mock() |
| 1091 | >>> with patch.dict('sys.modules', {'fooble': mock}): |
| 1092 | ... import fooble |
| 1093 | ... fooble.blob() |
| 1094 | ... |
| 1095 | <Mock name='mock.blob()' id='...'> |
| 1096 | >>> assert 'fooble' not in sys.modules |
| 1097 | >>> mock.blob.assert_called_once_with() |
| 1098 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1099 | As you can see the ``import fooble`` succeeds, but on exit there is no 'fooble' |
| 1100 | left in :data:`sys.modules`. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1101 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1102 | This also works for the ``from module import name`` form: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1103 | |
| 1104 | >>> mock = Mock() |
| 1105 | >>> with patch.dict('sys.modules', {'fooble': mock}): |
| 1106 | ... from fooble import blob |
| 1107 | ... blob.blip() |
| 1108 | ... |
| 1109 | <Mock name='mock.blob.blip()' id='...'> |
| 1110 | >>> mock.blob.blip.assert_called_once_with() |
| 1111 | |
| 1112 | With slightly more work you can also mock package imports: |
| 1113 | |
| 1114 | >>> mock = Mock() |
| 1115 | >>> modules = {'package': mock, 'package.module': mock.module} |
| 1116 | >>> with patch.dict('sys.modules', modules): |
| 1117 | ... from package.module import fooble |
| 1118 | ... fooble() |
| 1119 | ... |
| 1120 | <Mock name='mock.module.fooble()' id='...'> |
| 1121 | >>> mock.module.fooble.assert_called_once_with() |
| 1122 | |
| 1123 | |
| 1124 | Tracking order of calls and less verbose call assertions |
Georg Brandl | 7fc972a | 2013-02-03 14:00:04 +0100 | [diff] [blame] | 1125 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1126 | |
| 1127 | The :class:`Mock` class allows you to track the *order* of method calls on |
| 1128 | your mock objects through the :attr:`~Mock.method_calls` attribute. This |
| 1129 | doesn't allow you to track the order of calls between separate mock objects, |
| 1130 | however we can use :attr:`~Mock.mock_calls` to achieve the same effect. |
| 1131 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1132 | Because mocks track calls to child mocks in ``mock_calls``, and accessing an |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1133 | arbitrary attribute of a mock creates a child mock, we can create our separate |
| 1134 | mocks from a parent one. Calls to those child mock will then all be recorded, |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1135 | in order, in the ``mock_calls`` of the parent: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1136 | |
| 1137 | >>> manager = Mock() |
| 1138 | >>> mock_foo = manager.foo |
| 1139 | >>> mock_bar = manager.bar |
| 1140 | |
| 1141 | >>> mock_foo.something() |
| 1142 | <Mock name='mock.foo.something()' id='...'> |
| 1143 | >>> mock_bar.other.thing() |
| 1144 | <Mock name='mock.bar.other.thing()' id='...'> |
| 1145 | |
| 1146 | >>> manager.mock_calls |
| 1147 | [call.foo.something(), call.bar.other.thing()] |
| 1148 | |
| 1149 | We can then assert about the calls, including the order, by comparing with |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1150 | the ``mock_calls`` attribute on the manager mock: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1151 | |
| 1152 | >>> expected_calls = [call.foo.something(), call.bar.other.thing()] |
| 1153 | >>> manager.mock_calls == expected_calls |
| 1154 | True |
| 1155 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1156 | If ``patch`` is creating, and putting in place, your mocks then you can attach |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1157 | them to a manager mock using the :meth:`~Mock.attach_mock` method. After |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1158 | attaching calls will be recorded in ``mock_calls`` of the manager. :: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1159 | |
| 1160 | >>> manager = MagicMock() |
| 1161 | >>> with patch('mymodule.Class1') as MockClass1: |
| 1162 | ... with patch('mymodule.Class2') as MockClass2: |
| 1163 | ... manager.attach_mock(MockClass1, 'MockClass1') |
| 1164 | ... manager.attach_mock(MockClass2, 'MockClass2') |
| 1165 | ... MockClass1().foo() |
| 1166 | ... MockClass2().bar() |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1167 | <MagicMock name='mock.MockClass1().foo()' id='...'> |
| 1168 | <MagicMock name='mock.MockClass2().bar()' id='...'> |
| 1169 | >>> manager.mock_calls |
| 1170 | [call.MockClass1(), |
Stéphane Wirtel | 859c068 | 2018-10-12 09:51:05 +0200 | [diff] [blame] | 1171 | call.MockClass1().foo(), |
| 1172 | call.MockClass2(), |
| 1173 | call.MockClass2().bar()] |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1174 | |
| 1175 | If many calls have been made, but you're only interested in a particular |
| 1176 | sequence of them then an alternative is to use the |
| 1177 | :meth:`~Mock.assert_has_calls` method. This takes a list of calls (constructed |
| 1178 | with the :data:`call` object). If that sequence of calls are in |
| 1179 | :attr:`~Mock.mock_calls` then the assert succeeds. |
| 1180 | |
| 1181 | >>> m = MagicMock() |
| 1182 | >>> m().foo().bar().baz() |
| 1183 | <MagicMock name='mock().foo().bar().baz()' id='...'> |
| 1184 | >>> m.one().two().three() |
| 1185 | <MagicMock name='mock.one().two().three()' id='...'> |
| 1186 | >>> calls = call.one().two().three().call_list() |
| 1187 | >>> m.assert_has_calls(calls) |
| 1188 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1189 | Even though the chained call ``m.one().two().three()`` aren't the only calls that |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1190 | have been made to the mock, the assert still succeeds. |
| 1191 | |
| 1192 | Sometimes a mock may have several calls made to it, and you are only interested |
| 1193 | in asserting about *some* of those calls. You may not even care about the |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1194 | order. In this case you can pass ``any_order=True`` to ``assert_has_calls``: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1195 | |
| 1196 | >>> m = MagicMock() |
| 1197 | >>> m(1), m.two(2, 3), m.seven(7), m.fifty('50') |
| 1198 | (...) |
| 1199 | >>> calls = [call.fifty('50'), call(1), call.seven(7)] |
| 1200 | >>> m.assert_has_calls(calls, any_order=True) |
| 1201 | |
| 1202 | |
| 1203 | More complex argument matching |
Georg Brandl | 7fc972a | 2013-02-03 14:00:04 +0100 | [diff] [blame] | 1204 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1205 | |
| 1206 | Using the same basic concept as :data:`ANY` we can implement matchers to do more |
| 1207 | complex assertions on objects used as arguments to mocks. |
| 1208 | |
| 1209 | Suppose we expect some object to be passed to a mock that by default |
| 1210 | compares equal based on object identity (which is the Python default for user |
| 1211 | defined classes). To use :meth:`~Mock.assert_called_with` we would need to pass |
| 1212 | in the exact same object. If we are only interested in some of the attributes |
| 1213 | of this object then we can create a matcher that will check these attributes |
| 1214 | for us. |
| 1215 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1216 | You can see in this example how a 'standard' call to ``assert_called_with`` isn't |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1217 | sufficient: |
| 1218 | |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 1219 | >>> class Foo: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1220 | ... def __init__(self, a, b): |
| 1221 | ... self.a, self.b = a, b |
| 1222 | ... |
| 1223 | >>> mock = Mock(return_value=None) |
| 1224 | >>> mock(Foo(1, 2)) |
| 1225 | >>> mock.assert_called_with(Foo(1, 2)) |
| 1226 | Traceback (most recent call last): |
| 1227 | ... |
| 1228 | AssertionError: Expected: call(<__main__.Foo object at 0x...>) |
| 1229 | Actual call: call(<__main__.Foo object at 0x...>) |
| 1230 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1231 | A comparison function for our ``Foo`` class might look something like this: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1232 | |
| 1233 | >>> def compare(self, other): |
| 1234 | ... if not type(self) == type(other): |
| 1235 | ... return False |
| 1236 | ... if self.a != other.a: |
| 1237 | ... return False |
| 1238 | ... if self.b != other.b: |
| 1239 | ... return False |
| 1240 | ... return True |
| 1241 | ... |
| 1242 | |
| 1243 | And a matcher object that can use comparison functions like this for its |
| 1244 | equality operation would look something like this: |
| 1245 | |
Ezio Melotti | c9cfcf1 | 2013-03-11 09:42:40 +0200 | [diff] [blame] | 1246 | >>> class Matcher: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1247 | ... def __init__(self, compare, some_obj): |
| 1248 | ... self.compare = compare |
| 1249 | ... self.some_obj = some_obj |
| 1250 | ... def __eq__(self, other): |
| 1251 | ... return self.compare(self.some_obj, other) |
| 1252 | ... |
| 1253 | |
| 1254 | Putting all this together: |
| 1255 | |
| 1256 | >>> match_foo = Matcher(compare, Foo(1, 2)) |
| 1257 | >>> mock.assert_called_with(match_foo) |
| 1258 | |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1259 | The ``Matcher`` is instantiated with our compare function and the ``Foo`` object |
| 1260 | we want to compare against. In ``assert_called_with`` the ``Matcher`` equality |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1261 | method will be called, which compares the object the mock was called with |
| 1262 | against the one we created our matcher with. If they match then |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1263 | ``assert_called_with`` passes, and if they don't an :exc:`AssertionError` is raised: |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1264 | |
| 1265 | >>> match_wrong = Matcher(compare, Foo(3, 4)) |
| 1266 | >>> mock.assert_called_with(match_wrong) |
| 1267 | Traceback (most recent call last): |
| 1268 | ... |
| 1269 | AssertionError: Expected: ((<Matcher object at 0x...>,), {}) |
| 1270 | Called with: ((<Foo object at 0x...>,), {}) |
| 1271 | |
| 1272 | With a bit of tweaking you could have the comparison function raise the |
Georg Brandl | 7ad3df6 | 2014-10-31 07:59:37 +0100 | [diff] [blame] | 1273 | :exc:`AssertionError` directly and provide a more useful failure message. |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1274 | |
| 1275 | As of version 1.5, the Python testing library `PyHamcrest |
Sanyam Khurana | 338cd83 | 2018-01-20 05:55:37 +0530 | [diff] [blame] | 1276 | <https://pyhamcrest.readthedocs.io/>`_ provides similar functionality, |
Michael Foord | 944e02d | 2012-03-25 23:12:55 +0100 | [diff] [blame] | 1277 | that may be useful here, in the form of its equality matcher |
| 1278 | (`hamcrest.library.integration.match_equality |
Sanyam Khurana | 338cd83 | 2018-01-20 05:55:37 +0530 | [diff] [blame] | 1279 | <https://pyhamcrest.readthedocs.io/en/release-1.8/integration/#module-hamcrest.library.integration.match_equality>`_). |