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