Wed, 31 Dec 2014 06:55:50 +0100
Added tag UPSTREAM_283F7C6 for changeset ca08bd8f51b2
michael@0 | 1 | .. _further-examples: |
michael@0 | 2 | |
michael@0 | 3 | ================== |
michael@0 | 4 | Further Examples |
michael@0 | 5 | ================== |
michael@0 | 6 | |
michael@0 | 7 | .. currentmodule:: mock |
michael@0 | 8 | |
michael@0 | 9 | .. testsetup:: |
michael@0 | 10 | |
michael@0 | 11 | from datetime import date |
michael@0 | 12 | |
michael@0 | 13 | BackendProvider = Mock() |
michael@0 | 14 | sys.modules['mymodule'] = mymodule = Mock(name='mymodule') |
michael@0 | 15 | |
michael@0 | 16 | def grob(val): |
michael@0 | 17 | "First frob and then clear val" |
michael@0 | 18 | mymodule.frob(val) |
michael@0 | 19 | val.clear() |
michael@0 | 20 | |
michael@0 | 21 | mymodule.frob = lambda val: val |
michael@0 | 22 | mymodule.grob = grob |
michael@0 | 23 | mymodule.date = date |
michael@0 | 24 | |
michael@0 | 25 | class TestCase(unittest2.TestCase): |
michael@0 | 26 | def run(self): |
michael@0 | 27 | result = unittest2.TestResult() |
michael@0 | 28 | out = unittest2.TestCase.run(self, result) |
michael@0 | 29 | assert result.wasSuccessful() |
michael@0 | 30 | |
michael@0 | 31 | from mock import inPy3k |
michael@0 | 32 | |
michael@0 | 33 | |
michael@0 | 34 | |
michael@0 | 35 | For comprehensive examples, see the unit tests included in the full source |
michael@0 | 36 | distribution. |
michael@0 | 37 | |
michael@0 | 38 | Here are some more examples for some slightly more advanced scenarios than in |
michael@0 | 39 | the :ref:`getting started <getting-started>` guide. |
michael@0 | 40 | |
michael@0 | 41 | |
michael@0 | 42 | Mocking chained calls |
michael@0 | 43 | ===================== |
michael@0 | 44 | |
michael@0 | 45 | Mocking chained calls is actually straightforward with mock once you |
michael@0 | 46 | understand the :attr:`~Mock.return_value` attribute. When a mock is called for |
michael@0 | 47 | the first time, or you fetch its `return_value` before it has been called, a |
michael@0 | 48 | new `Mock` is created. |
michael@0 | 49 | |
michael@0 | 50 | This means that you can see how the object returned from a call to a mocked |
michael@0 | 51 | object has been used by interrogating the `return_value` mock: |
michael@0 | 52 | |
michael@0 | 53 | .. doctest:: |
michael@0 | 54 | |
michael@0 | 55 | >>> mock = Mock() |
michael@0 | 56 | >>> mock().foo(a=2, b=3) |
michael@0 | 57 | <Mock name='mock().foo()' id='...'> |
michael@0 | 58 | >>> mock.return_value.foo.assert_called_with(a=2, b=3) |
michael@0 | 59 | |
michael@0 | 60 | From here it is a simple step to configure and then make assertions about |
michael@0 | 61 | chained calls. Of course another alternative is writing your code in a more |
michael@0 | 62 | testable way in the first place... |
michael@0 | 63 | |
michael@0 | 64 | So, suppose we have some code that looks a little bit like this: |
michael@0 | 65 | |
michael@0 | 66 | .. doctest:: |
michael@0 | 67 | |
michael@0 | 68 | >>> class Something(object): |
michael@0 | 69 | ... def __init__(self): |
michael@0 | 70 | ... self.backend = BackendProvider() |
michael@0 | 71 | ... def method(self): |
michael@0 | 72 | ... response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call() |
michael@0 | 73 | ... # more code |
michael@0 | 74 | |
michael@0 | 75 | Assuming that `BackendProvider` is already well tested, how do we test |
michael@0 | 76 | `method()`? Specifically, we want to test that the code section `# more |
michael@0 | 77 | code` uses the response object in the correct way. |
michael@0 | 78 | |
michael@0 | 79 | As this chain of calls is made from an instance attribute we can monkey patch |
michael@0 | 80 | the `backend` attribute on a `Something` instance. In this particular case |
michael@0 | 81 | we are only interested in the return value from the final call to |
michael@0 | 82 | `start_call` so we don't have much configuration to do. Let's assume the |
michael@0 | 83 | object it returns is 'file-like', so we'll ensure that our response object |
michael@0 | 84 | uses the builtin `file` as its `spec`. |
michael@0 | 85 | |
michael@0 | 86 | To do this we create a mock instance as our mock backend and create a mock |
michael@0 | 87 | response object for it. To set the response as the return value for that final |
michael@0 | 88 | `start_call` we could do this: |
michael@0 | 89 | |
michael@0 | 90 | `mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response`. |
michael@0 | 91 | |
michael@0 | 92 | We can do that in a slightly nicer way using the :meth:`~Mock.configure_mock` |
michael@0 | 93 | method to directly set the return value for us: |
michael@0 | 94 | |
michael@0 | 95 | .. doctest:: |
michael@0 | 96 | |
michael@0 | 97 | >>> something = Something() |
michael@0 | 98 | >>> mock_response = Mock(spec=file) |
michael@0 | 99 | >>> mock_backend = Mock() |
michael@0 | 100 | >>> config = {'get_endpoint.return_value.create_call.return_value.start_call.return_value': mock_response} |
michael@0 | 101 | >>> mock_backend.configure_mock(**config) |
michael@0 | 102 | |
michael@0 | 103 | With these we monkey patch the "mock backend" in place and can make the real |
michael@0 | 104 | call: |
michael@0 | 105 | |
michael@0 | 106 | .. doctest:: |
michael@0 | 107 | |
michael@0 | 108 | >>> something.backend = mock_backend |
michael@0 | 109 | >>> something.method() |
michael@0 | 110 | |
michael@0 | 111 | Using :attr:`~Mock.mock_calls` we can check the chained call with a single |
michael@0 | 112 | assert. A chained call is several calls in one line of code, so there will be |
michael@0 | 113 | several entries in `mock_calls`. We can use :meth:`call.call_list` to create |
michael@0 | 114 | this list of calls for us: |
michael@0 | 115 | |
michael@0 | 116 | .. doctest:: |
michael@0 | 117 | |
michael@0 | 118 | >>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call() |
michael@0 | 119 | >>> call_list = chained.call_list() |
michael@0 | 120 | >>> assert mock_backend.mock_calls == call_list |
michael@0 | 121 | |
michael@0 | 122 | |
michael@0 | 123 | Partial mocking |
michael@0 | 124 | =============== |
michael@0 | 125 | |
michael@0 | 126 | In some tests I wanted to mock out a call to `datetime.date.today() |
michael@0 | 127 | <http://docs.python.org/library/datetime.html#datetime.date.today>`_ to return |
michael@0 | 128 | a known date, but I didn't want to prevent the code under test from |
michael@0 | 129 | creating new date objects. Unfortunately `datetime.date` is written in C, and |
michael@0 | 130 | so I couldn't just monkey-patch out the static `date.today` method. |
michael@0 | 131 | |
michael@0 | 132 | I found a simple way of doing this that involved effectively wrapping the date |
michael@0 | 133 | class with a mock, but passing through calls to the constructor to the real |
michael@0 | 134 | class (and returning real instances). |
michael@0 | 135 | |
michael@0 | 136 | The :func:`patch decorator <patch>` is used here to |
michael@0 | 137 | mock out the `date` class in the module under test. The :attr:`side_effect` |
michael@0 | 138 | attribute on the mock date class is then set to a lambda function that returns |
michael@0 | 139 | a real date. When the mock date class is called a real date will be |
michael@0 | 140 | constructed and returned by `side_effect`. |
michael@0 | 141 | |
michael@0 | 142 | .. doctest:: |
michael@0 | 143 | |
michael@0 | 144 | >>> from datetime import date |
michael@0 | 145 | >>> with patch('mymodule.date') as mock_date: |
michael@0 | 146 | ... mock_date.today.return_value = date(2010, 10, 8) |
michael@0 | 147 | ... mock_date.side_effect = lambda *args, **kw: date(*args, **kw) |
michael@0 | 148 | ... |
michael@0 | 149 | ... assert mymodule.date.today() == date(2010, 10, 8) |
michael@0 | 150 | ... assert mymodule.date(2009, 6, 8) == date(2009, 6, 8) |
michael@0 | 151 | ... |
michael@0 | 152 | |
michael@0 | 153 | Note that we don't patch `datetime.date` globally, we patch `date` in the |
michael@0 | 154 | module that *uses* it. See :ref:`where to patch <where-to-patch>`. |
michael@0 | 155 | |
michael@0 | 156 | When `date.today()` is called a known date is returned, but calls to the |
michael@0 | 157 | `date(...)` constructor still return normal dates. Without this you can find |
michael@0 | 158 | yourself having to calculate an expected result using exactly the same |
michael@0 | 159 | algorithm as the code under test, which is a classic testing anti-pattern. |
michael@0 | 160 | |
michael@0 | 161 | Calls to the date constructor are recorded in the `mock_date` attributes |
michael@0 | 162 | (`call_count` and friends) which may also be useful for your tests. |
michael@0 | 163 | |
michael@0 | 164 | An alternative way of dealing with mocking dates, or other builtin classes, |
michael@0 | 165 | is discussed in `this blog entry |
michael@0 | 166 | <http://williamjohnbert.com/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/>`_. |
michael@0 | 167 | |
michael@0 | 168 | |
michael@0 | 169 | Mocking a Generator Method |
michael@0 | 170 | ========================== |
michael@0 | 171 | |
michael@0 | 172 | A Python generator is a function or method that uses the `yield statement |
michael@0 | 173 | <http://docs.python.org/reference/simple_stmts.html#the-yield-statement>`_ to |
michael@0 | 174 | return a series of values when iterated over [#]_. |
michael@0 | 175 | |
michael@0 | 176 | A generator method / function is called to return the generator object. It is |
michael@0 | 177 | the generator object that is then iterated over. The protocol method for |
michael@0 | 178 | iteration is `__iter__ |
michael@0 | 179 | <http://docs.python.org/library/stdtypes.html#container.__iter__>`_, so we can |
michael@0 | 180 | mock this using a `MagicMock`. |
michael@0 | 181 | |
michael@0 | 182 | Here's an example class with an "iter" method implemented as a generator: |
michael@0 | 183 | |
michael@0 | 184 | .. doctest:: |
michael@0 | 185 | |
michael@0 | 186 | >>> class Foo(object): |
michael@0 | 187 | ... def iter(self): |
michael@0 | 188 | ... for i in [1, 2, 3]: |
michael@0 | 189 | ... yield i |
michael@0 | 190 | ... |
michael@0 | 191 | >>> foo = Foo() |
michael@0 | 192 | >>> list(foo.iter()) |
michael@0 | 193 | [1, 2, 3] |
michael@0 | 194 | |
michael@0 | 195 | |
michael@0 | 196 | How would we mock this class, and in particular its "iter" method? |
michael@0 | 197 | |
michael@0 | 198 | To configure the values returned from the iteration (implicit in the call to |
michael@0 | 199 | `list`), we need to configure the object returned by the call to `foo.iter()`. |
michael@0 | 200 | |
michael@0 | 201 | .. doctest:: |
michael@0 | 202 | |
michael@0 | 203 | >>> mock_foo = MagicMock() |
michael@0 | 204 | >>> mock_foo.iter.return_value = iter([1, 2, 3]) |
michael@0 | 205 | >>> list(mock_foo.iter()) |
michael@0 | 206 | [1, 2, 3] |
michael@0 | 207 | |
michael@0 | 208 | .. [#] There are also generator expressions and more `advanced uses |
michael@0 | 209 | <http://www.dabeaz.com/coroutines/index.html>`_ of generators, but we aren't |
michael@0 | 210 | concerned about them here. A very good introduction to generators and how |
michael@0 | 211 | powerful they are is: `Generator Tricks for Systems Programmers |
michael@0 | 212 | <http://www.dabeaz.com/generators/>`_. |
michael@0 | 213 | |
michael@0 | 214 | |
michael@0 | 215 | Applying the same patch to every test method |
michael@0 | 216 | ============================================ |
michael@0 | 217 | |
michael@0 | 218 | If you want several patches in place for multiple test methods the obvious way |
michael@0 | 219 | is to apply the patch decorators to every method. This can feel like unnecessary |
michael@0 | 220 | repetition. For Python 2.6 or more recent you can use `patch` (in all its |
michael@0 | 221 | various forms) as a class decorator. This applies the patches to all test |
michael@0 | 222 | methods on the class. A test method is identified by methods whose names start |
michael@0 | 223 | with `test`: |
michael@0 | 224 | |
michael@0 | 225 | .. doctest:: |
michael@0 | 226 | |
michael@0 | 227 | >>> @patch('mymodule.SomeClass') |
michael@0 | 228 | ... class MyTest(TestCase): |
michael@0 | 229 | ... |
michael@0 | 230 | ... def test_one(self, MockSomeClass): |
michael@0 | 231 | ... self.assertTrue(mymodule.SomeClass is MockSomeClass) |
michael@0 | 232 | ... |
michael@0 | 233 | ... def test_two(self, MockSomeClass): |
michael@0 | 234 | ... self.assertTrue(mymodule.SomeClass is MockSomeClass) |
michael@0 | 235 | ... |
michael@0 | 236 | ... def not_a_test(self): |
michael@0 | 237 | ... return 'something' |
michael@0 | 238 | ... |
michael@0 | 239 | >>> MyTest('test_one').test_one() |
michael@0 | 240 | >>> MyTest('test_two').test_two() |
michael@0 | 241 | >>> MyTest('test_two').not_a_test() |
michael@0 | 242 | 'something' |
michael@0 | 243 | |
michael@0 | 244 | An alternative way of managing patches is to use the :ref:`start-and-stop`. |
michael@0 | 245 | These allow you to move the patching into your `setUp` and `tearDown` methods. |
michael@0 | 246 | |
michael@0 | 247 | .. doctest:: |
michael@0 | 248 | |
michael@0 | 249 | >>> class MyTest(TestCase): |
michael@0 | 250 | ... def setUp(self): |
michael@0 | 251 | ... self.patcher = patch('mymodule.foo') |
michael@0 | 252 | ... self.mock_foo = self.patcher.start() |
michael@0 | 253 | ... |
michael@0 | 254 | ... def test_foo(self): |
michael@0 | 255 | ... self.assertTrue(mymodule.foo is self.mock_foo) |
michael@0 | 256 | ... |
michael@0 | 257 | ... def tearDown(self): |
michael@0 | 258 | ... self.patcher.stop() |
michael@0 | 259 | ... |
michael@0 | 260 | >>> MyTest('test_foo').run() |
michael@0 | 261 | |
michael@0 | 262 | If you use this technique you must ensure that the patching is "undone" by |
michael@0 | 263 | calling `stop`. This can be fiddlier than you might think, because if an |
michael@0 | 264 | exception is raised in the setUp then tearDown is not called. `unittest2 |
michael@0 | 265 | <http://pypi.python.org/pypi/unittest2>`_ cleanup functions make this simpler: |
michael@0 | 266 | |
michael@0 | 267 | |
michael@0 | 268 | .. doctest:: |
michael@0 | 269 | |
michael@0 | 270 | >>> class MyTest(TestCase): |
michael@0 | 271 | ... def setUp(self): |
michael@0 | 272 | ... patcher = patch('mymodule.foo') |
michael@0 | 273 | ... self.addCleanup(patcher.stop) |
michael@0 | 274 | ... self.mock_foo = patcher.start() |
michael@0 | 275 | ... |
michael@0 | 276 | ... def test_foo(self): |
michael@0 | 277 | ... self.assertTrue(mymodule.foo is self.mock_foo) |
michael@0 | 278 | ... |
michael@0 | 279 | >>> MyTest('test_foo').run() |
michael@0 | 280 | |
michael@0 | 281 | |
michael@0 | 282 | Mocking Unbound Methods |
michael@0 | 283 | ======================= |
michael@0 | 284 | |
michael@0 | 285 | Whilst writing tests today I needed to patch an *unbound method* (patching the |
michael@0 | 286 | method on the class rather than on the instance). I needed self to be passed |
michael@0 | 287 | in as the first argument because I want to make asserts about which objects |
michael@0 | 288 | were calling this particular method. The issue is that you can't patch with a |
michael@0 | 289 | mock for this, because if you replace an unbound method with a mock it doesn't |
michael@0 | 290 | become a bound method when fetched from the instance, and so it doesn't get |
michael@0 | 291 | self passed in. The workaround is to patch the unbound method with a real |
michael@0 | 292 | function instead. The :func:`patch` decorator makes it so simple to |
michael@0 | 293 | patch out methods with a mock that having to create a real function becomes a |
michael@0 | 294 | nuisance. |
michael@0 | 295 | |
michael@0 | 296 | If you pass `autospec=True` to patch then it does the patching with a |
michael@0 | 297 | *real* function object. This function object has the same signature as the one |
michael@0 | 298 | it is replacing, but delegates to a mock under the hood. You still get your |
michael@0 | 299 | mock auto-created in exactly the same way as before. What it means though, is |
michael@0 | 300 | that if you use it to patch out an unbound method on a class the mocked |
michael@0 | 301 | function will be turned into a bound method if it is fetched from an instance. |
michael@0 | 302 | It will have `self` passed in as the first argument, which is exactly what I |
michael@0 | 303 | wanted: |
michael@0 | 304 | |
michael@0 | 305 | .. doctest:: |
michael@0 | 306 | |
michael@0 | 307 | >>> class Foo(object): |
michael@0 | 308 | ... def foo(self): |
michael@0 | 309 | ... pass |
michael@0 | 310 | ... |
michael@0 | 311 | >>> with patch.object(Foo, 'foo', autospec=True) as mock_foo: |
michael@0 | 312 | ... mock_foo.return_value = 'foo' |
michael@0 | 313 | ... foo = Foo() |
michael@0 | 314 | ... foo.foo() |
michael@0 | 315 | ... |
michael@0 | 316 | 'foo' |
michael@0 | 317 | >>> mock_foo.assert_called_once_with(foo) |
michael@0 | 318 | |
michael@0 | 319 | If we don't use `autospec=True` then the unbound method is patched out |
michael@0 | 320 | with a Mock instance instead, and isn't called with `self`. |
michael@0 | 321 | |
michael@0 | 322 | |
michael@0 | 323 | Checking multiple calls with mock |
michael@0 | 324 | ================================= |
michael@0 | 325 | |
michael@0 | 326 | mock has a nice API for making assertions about how your mock objects are used. |
michael@0 | 327 | |
michael@0 | 328 | .. doctest:: |
michael@0 | 329 | |
michael@0 | 330 | >>> mock = Mock() |
michael@0 | 331 | >>> mock.foo_bar.return_value = None |
michael@0 | 332 | >>> mock.foo_bar('baz', spam='eggs') |
michael@0 | 333 | >>> mock.foo_bar.assert_called_with('baz', spam='eggs') |
michael@0 | 334 | |
michael@0 | 335 | If your mock is only being called once you can use the |
michael@0 | 336 | :meth:`assert_called_once_with` method that also asserts that the |
michael@0 | 337 | :attr:`call_count` is one. |
michael@0 | 338 | |
michael@0 | 339 | .. doctest:: |
michael@0 | 340 | |
michael@0 | 341 | >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs') |
michael@0 | 342 | >>> mock.foo_bar() |
michael@0 | 343 | >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs') |
michael@0 | 344 | Traceback (most recent call last): |
michael@0 | 345 | ... |
michael@0 | 346 | AssertionError: Expected to be called once. Called 2 times. |
michael@0 | 347 | |
michael@0 | 348 | Both `assert_called_with` and `assert_called_once_with` make assertions about |
michael@0 | 349 | the *most recent* call. If your mock is going to be called several times, and |
michael@0 | 350 | you want to make assertions about *all* those calls you can use |
michael@0 | 351 | :attr:`~Mock.call_args_list`: |
michael@0 | 352 | |
michael@0 | 353 | .. doctest:: |
michael@0 | 354 | |
michael@0 | 355 | >>> mock = Mock(return_value=None) |
michael@0 | 356 | >>> mock(1, 2, 3) |
michael@0 | 357 | >>> mock(4, 5, 6) |
michael@0 | 358 | >>> mock() |
michael@0 | 359 | >>> mock.call_args_list |
michael@0 | 360 | [call(1, 2, 3), call(4, 5, 6), call()] |
michael@0 | 361 | |
michael@0 | 362 | The :data:`call` helper makes it easy to make assertions about these calls. You |
michael@0 | 363 | can build up a list of expected calls and compare it to `call_args_list`. This |
michael@0 | 364 | looks remarkably similar to the repr of the `call_args_list`: |
michael@0 | 365 | |
michael@0 | 366 | .. doctest:: |
michael@0 | 367 | |
michael@0 | 368 | >>> expected = [call(1, 2, 3), call(4, 5, 6), call()] |
michael@0 | 369 | >>> mock.call_args_list == expected |
michael@0 | 370 | True |
michael@0 | 371 | |
michael@0 | 372 | |
michael@0 | 373 | Coping with mutable arguments |
michael@0 | 374 | ============================= |
michael@0 | 375 | |
michael@0 | 376 | Another situation is rare, but can bite you, is when your mock is called with |
michael@0 | 377 | mutable arguments. `call_args` and `call_args_list` store *references* to the |
michael@0 | 378 | arguments. If the arguments are mutated by the code under test then you can no |
michael@0 | 379 | longer make assertions about what the values were when the mock was called. |
michael@0 | 380 | |
michael@0 | 381 | Here's some example code that shows the problem. Imagine the following functions |
michael@0 | 382 | defined in 'mymodule':: |
michael@0 | 383 | |
michael@0 | 384 | def frob(val): |
michael@0 | 385 | pass |
michael@0 | 386 | |
michael@0 | 387 | def grob(val): |
michael@0 | 388 | "First frob and then clear val" |
michael@0 | 389 | frob(val) |
michael@0 | 390 | val.clear() |
michael@0 | 391 | |
michael@0 | 392 | When we try to test that `grob` calls `frob` with the correct argument look |
michael@0 | 393 | what happens: |
michael@0 | 394 | |
michael@0 | 395 | .. doctest:: |
michael@0 | 396 | |
michael@0 | 397 | >>> with patch('mymodule.frob') as mock_frob: |
michael@0 | 398 | ... val = set([6]) |
michael@0 | 399 | ... mymodule.grob(val) |
michael@0 | 400 | ... |
michael@0 | 401 | >>> val |
michael@0 | 402 | set([]) |
michael@0 | 403 | >>> mock_frob.assert_called_with(set([6])) |
michael@0 | 404 | Traceback (most recent call last): |
michael@0 | 405 | ... |
michael@0 | 406 | AssertionError: Expected: ((set([6]),), {}) |
michael@0 | 407 | Called with: ((set([]),), {}) |
michael@0 | 408 | |
michael@0 | 409 | One possibility would be for mock to copy the arguments you pass in. This |
michael@0 | 410 | could then cause problems if you do assertions that rely on object identity |
michael@0 | 411 | for equality. |
michael@0 | 412 | |
michael@0 | 413 | Here's one solution that uses the :attr:`side_effect` |
michael@0 | 414 | functionality. If you provide a `side_effect` function for a mock then |
michael@0 | 415 | `side_effect` will be called with the same args as the mock. This gives us an |
michael@0 | 416 | opportunity to copy the arguments and store them for later assertions. In this |
michael@0 | 417 | example I'm using *another* mock to store the arguments so that I can use the |
michael@0 | 418 | mock methods for doing the assertion. Again a helper function sets this up for |
michael@0 | 419 | me. |
michael@0 | 420 | |
michael@0 | 421 | .. doctest:: |
michael@0 | 422 | |
michael@0 | 423 | >>> from copy import deepcopy |
michael@0 | 424 | >>> from mock import Mock, patch, DEFAULT |
michael@0 | 425 | >>> def copy_call_args(mock): |
michael@0 | 426 | ... new_mock = Mock() |
michael@0 | 427 | ... def side_effect(*args, **kwargs): |
michael@0 | 428 | ... args = deepcopy(args) |
michael@0 | 429 | ... kwargs = deepcopy(kwargs) |
michael@0 | 430 | ... new_mock(*args, **kwargs) |
michael@0 | 431 | ... return DEFAULT |
michael@0 | 432 | ... mock.side_effect = side_effect |
michael@0 | 433 | ... return new_mock |
michael@0 | 434 | ... |
michael@0 | 435 | >>> with patch('mymodule.frob') as mock_frob: |
michael@0 | 436 | ... new_mock = copy_call_args(mock_frob) |
michael@0 | 437 | ... val = set([6]) |
michael@0 | 438 | ... mymodule.grob(val) |
michael@0 | 439 | ... |
michael@0 | 440 | >>> new_mock.assert_called_with(set([6])) |
michael@0 | 441 | >>> new_mock.call_args |
michael@0 | 442 | call(set([6])) |
michael@0 | 443 | |
michael@0 | 444 | `copy_call_args` is called with the mock that will be called. It returns a new |
michael@0 | 445 | mock that we do the assertion on. The `side_effect` function makes a copy of |
michael@0 | 446 | the args and calls our `new_mock` with the copy. |
michael@0 | 447 | |
michael@0 | 448 | .. note:: |
michael@0 | 449 | |
michael@0 | 450 | If your mock is only going to be used once there is an easier way of |
michael@0 | 451 | checking arguments at the point they are called. You can simply do the |
michael@0 | 452 | checking inside a `side_effect` function. |
michael@0 | 453 | |
michael@0 | 454 | .. doctest:: |
michael@0 | 455 | |
michael@0 | 456 | >>> def side_effect(arg): |
michael@0 | 457 | ... assert arg == set([6]) |
michael@0 | 458 | ... |
michael@0 | 459 | >>> mock = Mock(side_effect=side_effect) |
michael@0 | 460 | >>> mock(set([6])) |
michael@0 | 461 | >>> mock(set()) |
michael@0 | 462 | Traceback (most recent call last): |
michael@0 | 463 | ... |
michael@0 | 464 | AssertionError |
michael@0 | 465 | |
michael@0 | 466 | An alternative approach is to create a subclass of `Mock` or `MagicMock` that |
michael@0 | 467 | copies (using `copy.deepcopy |
michael@0 | 468 | <http://docs.python.org/library/copy.html#copy.deepcopy>`_) the arguments. |
michael@0 | 469 | Here's an example implementation: |
michael@0 | 470 | |
michael@0 | 471 | .. doctest:: |
michael@0 | 472 | |
michael@0 | 473 | >>> from copy import deepcopy |
michael@0 | 474 | >>> class CopyingMock(MagicMock): |
michael@0 | 475 | ... def __call__(self, *args, **kwargs): |
michael@0 | 476 | ... args = deepcopy(args) |
michael@0 | 477 | ... kwargs = deepcopy(kwargs) |
michael@0 | 478 | ... return super(CopyingMock, self).__call__(*args, **kwargs) |
michael@0 | 479 | ... |
michael@0 | 480 | >>> c = CopyingMock(return_value=None) |
michael@0 | 481 | >>> arg = set() |
michael@0 | 482 | >>> c(arg) |
michael@0 | 483 | >>> arg.add(1) |
michael@0 | 484 | >>> c.assert_called_with(set()) |
michael@0 | 485 | >>> c.assert_called_with(arg) |
michael@0 | 486 | Traceback (most recent call last): |
michael@0 | 487 | ... |
michael@0 | 488 | AssertionError: Expected call: mock(set([1])) |
michael@0 | 489 | Actual call: mock(set([])) |
michael@0 | 490 | >>> c.foo |
michael@0 | 491 | <CopyingMock name='mock.foo' id='...'> |
michael@0 | 492 | |
michael@0 | 493 | When you subclass `Mock` or `MagicMock` all dynamically created attributes, |
michael@0 | 494 | and the `return_value` will use your subclass automatically. That means all |
michael@0 | 495 | children of a `CopyingMock` will also have the type `CopyingMock`. |
michael@0 | 496 | |
michael@0 | 497 | |
michael@0 | 498 | Raising exceptions on attribute access |
michael@0 | 499 | ====================================== |
michael@0 | 500 | |
michael@0 | 501 | You can use :class:`PropertyMock` to mimic the behaviour of properties. This |
michael@0 | 502 | includes raising exceptions when an attribute is accessed. |
michael@0 | 503 | |
michael@0 | 504 | Here's an example raising a `ValueError` when the 'foo' attribute is accessed: |
michael@0 | 505 | |
michael@0 | 506 | .. doctest:: |
michael@0 | 507 | |
michael@0 | 508 | >>> m = MagicMock() |
michael@0 | 509 | >>> p = PropertyMock(side_effect=ValueError) |
michael@0 | 510 | >>> type(m).foo = p |
michael@0 | 511 | >>> m.foo |
michael@0 | 512 | Traceback (most recent call last): |
michael@0 | 513 | .... |
michael@0 | 514 | ValueError |
michael@0 | 515 | |
michael@0 | 516 | Because every mock object has its own type, a new subclass of whichever mock |
michael@0 | 517 | class you're using, all mock objects are isolated from each other. You can |
michael@0 | 518 | safely attach properties (or other descriptors or whatever you want in fact) |
michael@0 | 519 | to `type(mock)` without affecting other mock objects. |
michael@0 | 520 | |
michael@0 | 521 | |
michael@0 | 522 | Multiple calls with different effects |
michael@0 | 523 | ===================================== |
michael@0 | 524 | |
michael@0 | 525 | .. note:: |
michael@0 | 526 | |
michael@0 | 527 | In mock 1.0 the handling of iterable `side_effect` was changed. Any |
michael@0 | 528 | exceptions in the iterable will be raised instead of returned. |
michael@0 | 529 | |
michael@0 | 530 | Handling code that needs to behave differently on subsequent calls during the |
michael@0 | 531 | test can be tricky. For example you may have a function that needs to raise |
michael@0 | 532 | an exception the first time it is called but returns a response on the second |
michael@0 | 533 | call (testing retry behaviour). |
michael@0 | 534 | |
michael@0 | 535 | One approach is to use a :attr:`side_effect` function that replaces itself. The |
michael@0 | 536 | first time it is called the `side_effect` sets a new `side_effect` that will |
michael@0 | 537 | be used for the second call. It then raises an exception: |
michael@0 | 538 | |
michael@0 | 539 | .. doctest:: |
michael@0 | 540 | |
michael@0 | 541 | >>> def side_effect(*args): |
michael@0 | 542 | ... def second_call(*args): |
michael@0 | 543 | ... return 'response' |
michael@0 | 544 | ... mock.side_effect = second_call |
michael@0 | 545 | ... raise Exception('boom') |
michael@0 | 546 | ... |
michael@0 | 547 | >>> mock = Mock(side_effect=side_effect) |
michael@0 | 548 | >>> mock('first') |
michael@0 | 549 | Traceback (most recent call last): |
michael@0 | 550 | ... |
michael@0 | 551 | Exception: boom |
michael@0 | 552 | >>> mock('second') |
michael@0 | 553 | 'response' |
michael@0 | 554 | >>> mock.assert_called_with('second') |
michael@0 | 555 | |
michael@0 | 556 | Another perfectly valid way would be to pop return values from a list. If the |
michael@0 | 557 | return value is an exception, raise it instead of returning it: |
michael@0 | 558 | |
michael@0 | 559 | .. doctest:: |
michael@0 | 560 | |
michael@0 | 561 | >>> returns = [Exception('boom'), 'response'] |
michael@0 | 562 | >>> def side_effect(*args): |
michael@0 | 563 | ... result = returns.pop(0) |
michael@0 | 564 | ... if isinstance(result, Exception): |
michael@0 | 565 | ... raise result |
michael@0 | 566 | ... return result |
michael@0 | 567 | ... |
michael@0 | 568 | >>> mock = Mock(side_effect=side_effect) |
michael@0 | 569 | >>> mock('first') |
michael@0 | 570 | Traceback (most recent call last): |
michael@0 | 571 | ... |
michael@0 | 572 | Exception: boom |
michael@0 | 573 | >>> mock('second') |
michael@0 | 574 | 'response' |
michael@0 | 575 | >>> mock.assert_called_with('second') |
michael@0 | 576 | |
michael@0 | 577 | Which approach you prefer is a matter of taste. The first approach is actually |
michael@0 | 578 | a line shorter but maybe the second approach is more readable. |
michael@0 | 579 | |
michael@0 | 580 | |
michael@0 | 581 | Nesting Patches |
michael@0 | 582 | =============== |
michael@0 | 583 | |
michael@0 | 584 | Using patch as a context manager is nice, but if you do multiple patches you |
michael@0 | 585 | can end up with nested with statements indenting further and further to the |
michael@0 | 586 | right: |
michael@0 | 587 | |
michael@0 | 588 | .. doctest:: |
michael@0 | 589 | |
michael@0 | 590 | >>> class MyTest(TestCase): |
michael@0 | 591 | ... |
michael@0 | 592 | ... def test_foo(self): |
michael@0 | 593 | ... with patch('mymodule.Foo') as mock_foo: |
michael@0 | 594 | ... with patch('mymodule.Bar') as mock_bar: |
michael@0 | 595 | ... with patch('mymodule.Spam') as mock_spam: |
michael@0 | 596 | ... assert mymodule.Foo is mock_foo |
michael@0 | 597 | ... assert mymodule.Bar is mock_bar |
michael@0 | 598 | ... assert mymodule.Spam is mock_spam |
michael@0 | 599 | ... |
michael@0 | 600 | >>> original = mymodule.Foo |
michael@0 | 601 | >>> MyTest('test_foo').test_foo() |
michael@0 | 602 | >>> assert mymodule.Foo is original |
michael@0 | 603 | |
michael@0 | 604 | With unittest2_ `cleanup` functions and the :ref:`start-and-stop` we can |
michael@0 | 605 | achieve the same effect without the nested indentation. A simple helper |
michael@0 | 606 | method, `create_patch`, puts the patch in place and returns the created mock |
michael@0 | 607 | for us: |
michael@0 | 608 | |
michael@0 | 609 | .. doctest:: |
michael@0 | 610 | |
michael@0 | 611 | >>> class MyTest(TestCase): |
michael@0 | 612 | ... |
michael@0 | 613 | ... def create_patch(self, name): |
michael@0 | 614 | ... patcher = patch(name) |
michael@0 | 615 | ... thing = patcher.start() |
michael@0 | 616 | ... self.addCleanup(patcher.stop) |
michael@0 | 617 | ... return thing |
michael@0 | 618 | ... |
michael@0 | 619 | ... def test_foo(self): |
michael@0 | 620 | ... mock_foo = self.create_patch('mymodule.Foo') |
michael@0 | 621 | ... mock_bar = self.create_patch('mymodule.Bar') |
michael@0 | 622 | ... mock_spam = self.create_patch('mymodule.Spam') |
michael@0 | 623 | ... |
michael@0 | 624 | ... assert mymodule.Foo is mock_foo |
michael@0 | 625 | ... assert mymodule.Bar is mock_bar |
michael@0 | 626 | ... assert mymodule.Spam is mock_spam |
michael@0 | 627 | ... |
michael@0 | 628 | >>> original = mymodule.Foo |
michael@0 | 629 | >>> MyTest('test_foo').run() |
michael@0 | 630 | >>> assert mymodule.Foo is original |
michael@0 | 631 | |
michael@0 | 632 | |
michael@0 | 633 | Mocking a dictionary with MagicMock |
michael@0 | 634 | =================================== |
michael@0 | 635 | |
michael@0 | 636 | You may want to mock a dictionary, or other container object, recording all |
michael@0 | 637 | access to it whilst having it still behave like a dictionary. |
michael@0 | 638 | |
michael@0 | 639 | We can do this with :class:`MagicMock`, which will behave like a dictionary, |
michael@0 | 640 | and using :data:`~Mock.side_effect` to delegate dictionary access to a real |
michael@0 | 641 | underlying dictionary that is under our control. |
michael@0 | 642 | |
michael@0 | 643 | When the `__getitem__` and `__setitem__` methods of our `MagicMock` are called |
michael@0 | 644 | (normal dictionary access) then `side_effect` is called with the key (and in |
michael@0 | 645 | the case of `__setitem__` the value too). We can also control what is returned. |
michael@0 | 646 | |
michael@0 | 647 | After the `MagicMock` has been used we can use attributes like |
michael@0 | 648 | :data:`~Mock.call_args_list` to assert about how the dictionary was used: |
michael@0 | 649 | |
michael@0 | 650 | .. doctest:: |
michael@0 | 651 | |
michael@0 | 652 | >>> my_dict = {'a': 1, 'b': 2, 'c': 3} |
michael@0 | 653 | >>> def getitem(name): |
michael@0 | 654 | ... return my_dict[name] |
michael@0 | 655 | ... |
michael@0 | 656 | >>> def setitem(name, val): |
michael@0 | 657 | ... my_dict[name] = val |
michael@0 | 658 | ... |
michael@0 | 659 | >>> mock = MagicMock() |
michael@0 | 660 | >>> mock.__getitem__.side_effect = getitem |
michael@0 | 661 | >>> mock.__setitem__.side_effect = setitem |
michael@0 | 662 | |
michael@0 | 663 | .. note:: |
michael@0 | 664 | |
michael@0 | 665 | An alternative to using `MagicMock` is to use `Mock` and *only* provide |
michael@0 | 666 | the magic methods you specifically want: |
michael@0 | 667 | |
michael@0 | 668 | .. doctest:: |
michael@0 | 669 | |
michael@0 | 670 | >>> mock = Mock() |
michael@0 | 671 | >>> mock.__setitem__ = Mock(side_effect=getitem) |
michael@0 | 672 | >>> mock.__getitem__ = Mock(side_effect=setitem) |
michael@0 | 673 | |
michael@0 | 674 | A *third* option is to use `MagicMock` but passing in `dict` as the `spec` |
michael@0 | 675 | (or `spec_set`) argument so that the `MagicMock` created only has |
michael@0 | 676 | dictionary magic methods available: |
michael@0 | 677 | |
michael@0 | 678 | .. doctest:: |
michael@0 | 679 | |
michael@0 | 680 | >>> mock = MagicMock(spec_set=dict) |
michael@0 | 681 | >>> mock.__getitem__.side_effect = getitem |
michael@0 | 682 | >>> mock.__setitem__.side_effect = setitem |
michael@0 | 683 | |
michael@0 | 684 | With these side effect functions in place, the `mock` will behave like a normal |
michael@0 | 685 | dictionary but recording the access. It even raises a `KeyError` if you try |
michael@0 | 686 | to access a key that doesn't exist. |
michael@0 | 687 | |
michael@0 | 688 | .. doctest:: |
michael@0 | 689 | |
michael@0 | 690 | >>> mock['a'] |
michael@0 | 691 | 1 |
michael@0 | 692 | >>> mock['c'] |
michael@0 | 693 | 3 |
michael@0 | 694 | >>> mock['d'] |
michael@0 | 695 | Traceback (most recent call last): |
michael@0 | 696 | ... |
michael@0 | 697 | KeyError: 'd' |
michael@0 | 698 | >>> mock['b'] = 'fish' |
michael@0 | 699 | >>> mock['d'] = 'eggs' |
michael@0 | 700 | >>> mock['b'] |
michael@0 | 701 | 'fish' |
michael@0 | 702 | >>> mock['d'] |
michael@0 | 703 | 'eggs' |
michael@0 | 704 | |
michael@0 | 705 | After it has been used you can make assertions about the access using the normal |
michael@0 | 706 | mock methods and attributes: |
michael@0 | 707 | |
michael@0 | 708 | .. doctest:: |
michael@0 | 709 | |
michael@0 | 710 | >>> mock.__getitem__.call_args_list |
michael@0 | 711 | [call('a'), call('c'), call('d'), call('b'), call('d')] |
michael@0 | 712 | >>> mock.__setitem__.call_args_list |
michael@0 | 713 | [call('b', 'fish'), call('d', 'eggs')] |
michael@0 | 714 | >>> my_dict |
michael@0 | 715 | {'a': 1, 'c': 3, 'b': 'fish', 'd': 'eggs'} |
michael@0 | 716 | |
michael@0 | 717 | |
michael@0 | 718 | Mock subclasses and their attributes |
michael@0 | 719 | ==================================== |
michael@0 | 720 | |
michael@0 | 721 | There are various reasons why you might want to subclass `Mock`. One reason |
michael@0 | 722 | might be to add helper methods. Here's a silly example: |
michael@0 | 723 | |
michael@0 | 724 | .. doctest:: |
michael@0 | 725 | |
michael@0 | 726 | >>> class MyMock(MagicMock): |
michael@0 | 727 | ... def has_been_called(self): |
michael@0 | 728 | ... return self.called |
michael@0 | 729 | ... |
michael@0 | 730 | >>> mymock = MyMock(return_value=None) |
michael@0 | 731 | >>> mymock |
michael@0 | 732 | <MyMock id='...'> |
michael@0 | 733 | >>> mymock.has_been_called() |
michael@0 | 734 | False |
michael@0 | 735 | >>> mymock() |
michael@0 | 736 | >>> mymock.has_been_called() |
michael@0 | 737 | True |
michael@0 | 738 | |
michael@0 | 739 | The standard behaviour for `Mock` instances is that attributes and the return |
michael@0 | 740 | value mocks are of the same type as the mock they are accessed on. This ensures |
michael@0 | 741 | that `Mock` attributes are `Mocks` and `MagicMock` attributes are `MagicMocks` |
michael@0 | 742 | [#]_. So if you're subclassing to add helper methods then they'll also be |
michael@0 | 743 | available on the attributes and return value mock of instances of your |
michael@0 | 744 | subclass. |
michael@0 | 745 | |
michael@0 | 746 | .. doctest:: |
michael@0 | 747 | |
michael@0 | 748 | >>> mymock.foo |
michael@0 | 749 | <MyMock name='mock.foo' id='...'> |
michael@0 | 750 | >>> mymock.foo.has_been_called() |
michael@0 | 751 | False |
michael@0 | 752 | >>> mymock.foo() |
michael@0 | 753 | <MyMock name='mock.foo()' id='...'> |
michael@0 | 754 | >>> mymock.foo.has_been_called() |
michael@0 | 755 | True |
michael@0 | 756 | |
michael@0 | 757 | Sometimes this is inconvenient. For example, `one user |
michael@0 | 758 | <https://code.google.com/p/mock/issues/detail?id=105>`_ is subclassing mock to |
michael@0 | 759 | created a `Twisted adaptor |
michael@0 | 760 | <http://twistedmatrix.com/documents/11.0.0/api/twisted.python.components.html>`_. |
michael@0 | 761 | Having this applied to attributes too actually causes errors. |
michael@0 | 762 | |
michael@0 | 763 | `Mock` (in all its flavours) uses a method called `_get_child_mock` to create |
michael@0 | 764 | these "sub-mocks" for attributes and return values. You can prevent your |
michael@0 | 765 | subclass being used for attributes by overriding this method. The signature is |
michael@0 | 766 | that it takes arbitrary keyword arguments (`**kwargs`) which are then passed |
michael@0 | 767 | onto the mock constructor: |
michael@0 | 768 | |
michael@0 | 769 | .. doctest:: |
michael@0 | 770 | |
michael@0 | 771 | >>> class Subclass(MagicMock): |
michael@0 | 772 | ... def _get_child_mock(self, **kwargs): |
michael@0 | 773 | ... return MagicMock(**kwargs) |
michael@0 | 774 | ... |
michael@0 | 775 | >>> mymock = Subclass() |
michael@0 | 776 | >>> mymock.foo |
michael@0 | 777 | <MagicMock name='mock.foo' id='...'> |
michael@0 | 778 | >>> assert isinstance(mymock, Subclass) |
michael@0 | 779 | >>> assert not isinstance(mymock.foo, Subclass) |
michael@0 | 780 | >>> assert not isinstance(mymock(), Subclass) |
michael@0 | 781 | |
michael@0 | 782 | .. [#] An exception to this rule are the non-callable mocks. Attributes use the |
michael@0 | 783 | callable variant because otherwise non-callable mocks couldn't have callable |
michael@0 | 784 | methods. |
michael@0 | 785 | |
michael@0 | 786 | |
michael@0 | 787 | Mocking imports with patch.dict |
michael@0 | 788 | =============================== |
michael@0 | 789 | |
michael@0 | 790 | One situation where mocking can be hard is where you have a local import inside |
michael@0 | 791 | a function. These are harder to mock because they aren't using an object from |
michael@0 | 792 | the module namespace that we can patch out. |
michael@0 | 793 | |
michael@0 | 794 | Generally local imports are to be avoided. They are sometimes done to prevent |
michael@0 | 795 | circular dependencies, for which there is *usually* a much better way to solve |
michael@0 | 796 | the problem (refactor the code) or to prevent "up front costs" by delaying the |
michael@0 | 797 | import. This can also be solved in better ways than an unconditional local |
michael@0 | 798 | import (store the module as a class or module attribute and only do the import |
michael@0 | 799 | on first use). |
michael@0 | 800 | |
michael@0 | 801 | That aside there is a way to use `mock` to affect the results of an import. |
michael@0 | 802 | Importing fetches an *object* from the `sys.modules` dictionary. Note that it |
michael@0 | 803 | fetches an *object*, which need not be a module. Importing a module for the |
michael@0 | 804 | first time results in a module object being put in `sys.modules`, so usually |
michael@0 | 805 | when you import something you get a module back. This need not be the case |
michael@0 | 806 | however. |
michael@0 | 807 | |
michael@0 | 808 | This means you can use :func:`patch.dict` to *temporarily* put a mock in place |
michael@0 | 809 | in `sys.modules`. Any imports whilst this patch is active will fetch the mock. |
michael@0 | 810 | When the patch is complete (the decorated function exits, the with statement |
michael@0 | 811 | body is complete or `patcher.stop()` is called) then whatever was there |
michael@0 | 812 | previously will be restored safely. |
michael@0 | 813 | |
michael@0 | 814 | Here's an example that mocks out the 'fooble' module. |
michael@0 | 815 | |
michael@0 | 816 | .. doctest:: |
michael@0 | 817 | |
michael@0 | 818 | >>> mock = Mock() |
michael@0 | 819 | >>> with patch.dict('sys.modules', {'fooble': mock}): |
michael@0 | 820 | ... import fooble |
michael@0 | 821 | ... fooble.blob() |
michael@0 | 822 | ... |
michael@0 | 823 | <Mock name='mock.blob()' id='...'> |
michael@0 | 824 | >>> assert 'fooble' not in sys.modules |
michael@0 | 825 | >>> mock.blob.assert_called_once_with() |
michael@0 | 826 | |
michael@0 | 827 | As you can see the `import fooble` succeeds, but on exit there is no 'fooble' |
michael@0 | 828 | left in `sys.modules`. |
michael@0 | 829 | |
michael@0 | 830 | This also works for the `from module import name` form: |
michael@0 | 831 | |
michael@0 | 832 | .. doctest:: |
michael@0 | 833 | |
michael@0 | 834 | >>> mock = Mock() |
michael@0 | 835 | >>> with patch.dict('sys.modules', {'fooble': mock}): |
michael@0 | 836 | ... from fooble import blob |
michael@0 | 837 | ... blob.blip() |
michael@0 | 838 | ... |
michael@0 | 839 | <Mock name='mock.blob.blip()' id='...'> |
michael@0 | 840 | >>> mock.blob.blip.assert_called_once_with() |
michael@0 | 841 | |
michael@0 | 842 | With slightly more work you can also mock package imports: |
michael@0 | 843 | |
michael@0 | 844 | .. doctest:: |
michael@0 | 845 | |
michael@0 | 846 | >>> mock = Mock() |
michael@0 | 847 | >>> modules = {'package': mock, 'package.module': mock.module} |
michael@0 | 848 | >>> with patch.dict('sys.modules', modules): |
michael@0 | 849 | ... from package.module import fooble |
michael@0 | 850 | ... fooble() |
michael@0 | 851 | ... |
michael@0 | 852 | <Mock name='mock.module.fooble()' id='...'> |
michael@0 | 853 | >>> mock.module.fooble.assert_called_once_with() |
michael@0 | 854 | |
michael@0 | 855 | |
michael@0 | 856 | Tracking order of calls and less verbose call assertions |
michael@0 | 857 | ======================================================== |
michael@0 | 858 | |
michael@0 | 859 | The :class:`Mock` class allows you to track the *order* of method calls on |
michael@0 | 860 | your mock objects through the :attr:`~Mock.method_calls` attribute. This |
michael@0 | 861 | doesn't allow you to track the order of calls between separate mock objects, |
michael@0 | 862 | however we can use :attr:`~Mock.mock_calls` to achieve the same effect. |
michael@0 | 863 | |
michael@0 | 864 | Because mocks track calls to child mocks in `mock_calls`, and accessing an |
michael@0 | 865 | arbitrary attribute of a mock creates a child mock, we can create our separate |
michael@0 | 866 | mocks from a parent one. Calls to those child mock will then all be recorded, |
michael@0 | 867 | in order, in the `mock_calls` of the parent: |
michael@0 | 868 | |
michael@0 | 869 | .. doctest:: |
michael@0 | 870 | |
michael@0 | 871 | >>> manager = Mock() |
michael@0 | 872 | >>> mock_foo = manager.foo |
michael@0 | 873 | >>> mock_bar = manager.bar |
michael@0 | 874 | |
michael@0 | 875 | >>> mock_foo.something() |
michael@0 | 876 | <Mock name='mock.foo.something()' id='...'> |
michael@0 | 877 | >>> mock_bar.other.thing() |
michael@0 | 878 | <Mock name='mock.bar.other.thing()' id='...'> |
michael@0 | 879 | |
michael@0 | 880 | >>> manager.mock_calls |
michael@0 | 881 | [call.foo.something(), call.bar.other.thing()] |
michael@0 | 882 | |
michael@0 | 883 | We can then assert about the calls, including the order, by comparing with |
michael@0 | 884 | the `mock_calls` attribute on the manager mock: |
michael@0 | 885 | |
michael@0 | 886 | .. doctest:: |
michael@0 | 887 | |
michael@0 | 888 | >>> expected_calls = [call.foo.something(), call.bar.other.thing()] |
michael@0 | 889 | >>> manager.mock_calls == expected_calls |
michael@0 | 890 | True |
michael@0 | 891 | |
michael@0 | 892 | If `patch` is creating, and putting in place, your mocks then you can attach |
michael@0 | 893 | them to a manager mock using the :meth:`~Mock.attach_mock` method. After |
michael@0 | 894 | attaching calls will be recorded in `mock_calls` of the manager. |
michael@0 | 895 | |
michael@0 | 896 | .. doctest:: |
michael@0 | 897 | |
michael@0 | 898 | >>> manager = MagicMock() |
michael@0 | 899 | >>> with patch('mymodule.Class1') as MockClass1: |
michael@0 | 900 | ... with patch('mymodule.Class2') as MockClass2: |
michael@0 | 901 | ... manager.attach_mock(MockClass1, 'MockClass1') |
michael@0 | 902 | ... manager.attach_mock(MockClass2, 'MockClass2') |
michael@0 | 903 | ... MockClass1().foo() |
michael@0 | 904 | ... MockClass2().bar() |
michael@0 | 905 | ... |
michael@0 | 906 | <MagicMock name='mock.MockClass1().foo()' id='...'> |
michael@0 | 907 | <MagicMock name='mock.MockClass2().bar()' id='...'> |
michael@0 | 908 | >>> manager.mock_calls |
michael@0 | 909 | [call.MockClass1(), |
michael@0 | 910 | call.MockClass1().foo(), |
michael@0 | 911 | call.MockClass2(), |
michael@0 | 912 | call.MockClass2().bar()] |
michael@0 | 913 | |
michael@0 | 914 | If many calls have been made, but you're only interested in a particular |
michael@0 | 915 | sequence of them then an alternative is to use the |
michael@0 | 916 | :meth:`~Mock.assert_has_calls` method. This takes a list of calls (constructed |
michael@0 | 917 | with the :data:`call` object). If that sequence of calls are in |
michael@0 | 918 | :attr:`~Mock.mock_calls` then the assert succeeds. |
michael@0 | 919 | |
michael@0 | 920 | .. doctest:: |
michael@0 | 921 | |
michael@0 | 922 | >>> m = MagicMock() |
michael@0 | 923 | >>> m().foo().bar().baz() |
michael@0 | 924 | <MagicMock name='mock().foo().bar().baz()' id='...'> |
michael@0 | 925 | >>> m.one().two().three() |
michael@0 | 926 | <MagicMock name='mock.one().two().three()' id='...'> |
michael@0 | 927 | >>> calls = call.one().two().three().call_list() |
michael@0 | 928 | >>> m.assert_has_calls(calls) |
michael@0 | 929 | |
michael@0 | 930 | Even though the chained call `m.one().two().three()` aren't the only calls that |
michael@0 | 931 | have been made to the mock, the assert still succeeds. |
michael@0 | 932 | |
michael@0 | 933 | Sometimes a mock may have several calls made to it, and you are only interested |
michael@0 | 934 | in asserting about *some* of those calls. You may not even care about the |
michael@0 | 935 | order. In this case you can pass `any_order=True` to `assert_has_calls`: |
michael@0 | 936 | |
michael@0 | 937 | .. doctest:: |
michael@0 | 938 | |
michael@0 | 939 | >>> m = MagicMock() |
michael@0 | 940 | >>> m(1), m.two(2, 3), m.seven(7), m.fifty('50') |
michael@0 | 941 | (...) |
michael@0 | 942 | >>> calls = [call.fifty('50'), call(1), call.seven(7)] |
michael@0 | 943 | >>> m.assert_has_calls(calls, any_order=True) |
michael@0 | 944 | |
michael@0 | 945 | |
michael@0 | 946 | More complex argument matching |
michael@0 | 947 | ============================== |
michael@0 | 948 | |
michael@0 | 949 | Using the same basic concept as `ANY` we can implement matchers to do more |
michael@0 | 950 | complex assertions on objects used as arguments to mocks. |
michael@0 | 951 | |
michael@0 | 952 | Suppose we expect some object to be passed to a mock that by default |
michael@0 | 953 | compares equal based on object identity (which is the Python default for user |
michael@0 | 954 | defined classes). To use :meth:`~Mock.assert_called_with` we would need to pass |
michael@0 | 955 | in the exact same object. If we are only interested in some of the attributes |
michael@0 | 956 | of this object then we can create a matcher that will check these attributes |
michael@0 | 957 | for us. |
michael@0 | 958 | |
michael@0 | 959 | You can see in this example how a 'standard' call to `assert_called_with` isn't |
michael@0 | 960 | sufficient: |
michael@0 | 961 | |
michael@0 | 962 | .. doctest:: |
michael@0 | 963 | |
michael@0 | 964 | >>> class Foo(object): |
michael@0 | 965 | ... def __init__(self, a, b): |
michael@0 | 966 | ... self.a, self.b = a, b |
michael@0 | 967 | ... |
michael@0 | 968 | >>> mock = Mock(return_value=None) |
michael@0 | 969 | >>> mock(Foo(1, 2)) |
michael@0 | 970 | >>> mock.assert_called_with(Foo(1, 2)) |
michael@0 | 971 | Traceback (most recent call last): |
michael@0 | 972 | ... |
michael@0 | 973 | AssertionError: Expected: call(<__main__.Foo object at 0x...>) |
michael@0 | 974 | Actual call: call(<__main__.Foo object at 0x...>) |
michael@0 | 975 | |
michael@0 | 976 | A comparison function for our `Foo` class might look something like this: |
michael@0 | 977 | |
michael@0 | 978 | .. doctest:: |
michael@0 | 979 | |
michael@0 | 980 | >>> def compare(self, other): |
michael@0 | 981 | ... if not type(self) == type(other): |
michael@0 | 982 | ... return False |
michael@0 | 983 | ... if self.a != other.a: |
michael@0 | 984 | ... return False |
michael@0 | 985 | ... if self.b != other.b: |
michael@0 | 986 | ... return False |
michael@0 | 987 | ... return True |
michael@0 | 988 | ... |
michael@0 | 989 | |
michael@0 | 990 | And a matcher object that can use comparison functions like this for its |
michael@0 | 991 | equality operation would look something like this: |
michael@0 | 992 | |
michael@0 | 993 | .. doctest:: |
michael@0 | 994 | |
michael@0 | 995 | >>> class Matcher(object): |
michael@0 | 996 | ... def __init__(self, compare, some_obj): |
michael@0 | 997 | ... self.compare = compare |
michael@0 | 998 | ... self.some_obj = some_obj |
michael@0 | 999 | ... def __eq__(self, other): |
michael@0 | 1000 | ... return self.compare(self.some_obj, other) |
michael@0 | 1001 | ... |
michael@0 | 1002 | |
michael@0 | 1003 | Putting all this together: |
michael@0 | 1004 | |
michael@0 | 1005 | .. doctest:: |
michael@0 | 1006 | |
michael@0 | 1007 | >>> match_foo = Matcher(compare, Foo(1, 2)) |
michael@0 | 1008 | >>> mock.assert_called_with(match_foo) |
michael@0 | 1009 | |
michael@0 | 1010 | The `Matcher` is instantiated with our compare function and the `Foo` object |
michael@0 | 1011 | we want to compare against. In `assert_called_with` the `Matcher` equality |
michael@0 | 1012 | method will be called, which compares the object the mock was called with |
michael@0 | 1013 | against the one we created our matcher with. If they match then |
michael@0 | 1014 | `assert_called_with` passes, and if they don't an `AssertionError` is raised: |
michael@0 | 1015 | |
michael@0 | 1016 | .. doctest:: |
michael@0 | 1017 | |
michael@0 | 1018 | >>> match_wrong = Matcher(compare, Foo(3, 4)) |
michael@0 | 1019 | >>> mock.assert_called_with(match_wrong) |
michael@0 | 1020 | Traceback (most recent call last): |
michael@0 | 1021 | ... |
michael@0 | 1022 | AssertionError: Expected: ((<Matcher object at 0x...>,), {}) |
michael@0 | 1023 | Called with: ((<Foo object at 0x...>,), {}) |
michael@0 | 1024 | |
michael@0 | 1025 | With a bit of tweaking you could have the comparison function raise the |
michael@0 | 1026 | `AssertionError` directly and provide a more useful failure message. |
michael@0 | 1027 | |
michael@0 | 1028 | As of version 1.5, the Python testing library `PyHamcrest |
michael@0 | 1029 | <http://pypi.python.org/pypi/PyHamcrest>`_ provides similar functionality, |
michael@0 | 1030 | that may be useful here, in the form of its equality matcher |
michael@0 | 1031 | (`hamcrest.library.integration.match_equality |
michael@0 | 1032 | <http://packages.python.org/PyHamcrest/integration.html#hamcrest.library.integration.match_equality>`_). |
michael@0 | 1033 | |
michael@0 | 1034 | |
michael@0 | 1035 | Less verbose configuration of mock objects |
michael@0 | 1036 | ========================================== |
michael@0 | 1037 | |
michael@0 | 1038 | This recipe, for easier configuration of mock objects, is now part of `Mock`. |
michael@0 | 1039 | See the :meth:`~Mock.configure_mock` method. |
michael@0 | 1040 | |
michael@0 | 1041 | |
michael@0 | 1042 | Matching any argument in assertions |
michael@0 | 1043 | =================================== |
michael@0 | 1044 | |
michael@0 | 1045 | This example is now built in to mock. See :data:`ANY`. |
michael@0 | 1046 | |
michael@0 | 1047 | |
michael@0 | 1048 | Mocking Properties |
michael@0 | 1049 | ================== |
michael@0 | 1050 | |
michael@0 | 1051 | This example is now built in to mock. See :class:`PropertyMock`. |
michael@0 | 1052 | |
michael@0 | 1053 | |
michael@0 | 1054 | Mocking open |
michael@0 | 1055 | ============ |
michael@0 | 1056 | |
michael@0 | 1057 | This example is now built in to mock. See :func:`mock_open`. |
michael@0 | 1058 | |
michael@0 | 1059 | |
michael@0 | 1060 | Mocks without some attributes |
michael@0 | 1061 | ============================= |
michael@0 | 1062 | |
michael@0 | 1063 | This example is now built in to mock. See :ref:`deleting-attributes`. |