1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/python/mock-1.0.0/html/_sources/examples.txt Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,1063 @@ 1.4 +.. _further-examples: 1.5 + 1.6 +================== 1.7 + Further Examples 1.8 +================== 1.9 + 1.10 +.. currentmodule:: mock 1.11 + 1.12 +.. testsetup:: 1.13 + 1.14 + from datetime import date 1.15 + 1.16 + BackendProvider = Mock() 1.17 + sys.modules['mymodule'] = mymodule = Mock(name='mymodule') 1.18 + 1.19 + def grob(val): 1.20 + "First frob and then clear val" 1.21 + mymodule.frob(val) 1.22 + val.clear() 1.23 + 1.24 + mymodule.frob = lambda val: val 1.25 + mymodule.grob = grob 1.26 + mymodule.date = date 1.27 + 1.28 + class TestCase(unittest2.TestCase): 1.29 + def run(self): 1.30 + result = unittest2.TestResult() 1.31 + out = unittest2.TestCase.run(self, result) 1.32 + assert result.wasSuccessful() 1.33 + 1.34 + from mock import inPy3k 1.35 + 1.36 + 1.37 + 1.38 +For comprehensive examples, see the unit tests included in the full source 1.39 +distribution. 1.40 + 1.41 +Here are some more examples for some slightly more advanced scenarios than in 1.42 +the :ref:`getting started <getting-started>` guide. 1.43 + 1.44 + 1.45 +Mocking chained calls 1.46 +===================== 1.47 + 1.48 +Mocking chained calls is actually straightforward with mock once you 1.49 +understand the :attr:`~Mock.return_value` attribute. When a mock is called for 1.50 +the first time, or you fetch its `return_value` before it has been called, a 1.51 +new `Mock` is created. 1.52 + 1.53 +This means that you can see how the object returned from a call to a mocked 1.54 +object has been used by interrogating the `return_value` mock: 1.55 + 1.56 +.. doctest:: 1.57 + 1.58 + >>> mock = Mock() 1.59 + >>> mock().foo(a=2, b=3) 1.60 + <Mock name='mock().foo()' id='...'> 1.61 + >>> mock.return_value.foo.assert_called_with(a=2, b=3) 1.62 + 1.63 +From here it is a simple step to configure and then make assertions about 1.64 +chained calls. Of course another alternative is writing your code in a more 1.65 +testable way in the first place... 1.66 + 1.67 +So, suppose we have some code that looks a little bit like this: 1.68 + 1.69 +.. doctest:: 1.70 + 1.71 + >>> class Something(object): 1.72 + ... def __init__(self): 1.73 + ... self.backend = BackendProvider() 1.74 + ... def method(self): 1.75 + ... response = self.backend.get_endpoint('foobar').create_call('spam', 'eggs').start_call() 1.76 + ... # more code 1.77 + 1.78 +Assuming that `BackendProvider` is already well tested, how do we test 1.79 +`method()`? Specifically, we want to test that the code section `# more 1.80 +code` uses the response object in the correct way. 1.81 + 1.82 +As this chain of calls is made from an instance attribute we can monkey patch 1.83 +the `backend` attribute on a `Something` instance. In this particular case 1.84 +we are only interested in the return value from the final call to 1.85 +`start_call` so we don't have much configuration to do. Let's assume the 1.86 +object it returns is 'file-like', so we'll ensure that our response object 1.87 +uses the builtin `file` as its `spec`. 1.88 + 1.89 +To do this we create a mock instance as our mock backend and create a mock 1.90 +response object for it. To set the response as the return value for that final 1.91 +`start_call` we could do this: 1.92 + 1.93 + `mock_backend.get_endpoint.return_value.create_call.return_value.start_call.return_value = mock_response`. 1.94 + 1.95 +We can do that in a slightly nicer way using the :meth:`~Mock.configure_mock` 1.96 +method to directly set the return value for us: 1.97 + 1.98 +.. doctest:: 1.99 + 1.100 + >>> something = Something() 1.101 + >>> mock_response = Mock(spec=file) 1.102 + >>> mock_backend = Mock() 1.103 + >>> config = {'get_endpoint.return_value.create_call.return_value.start_call.return_value': mock_response} 1.104 + >>> mock_backend.configure_mock(**config) 1.105 + 1.106 +With these we monkey patch the "mock backend" in place and can make the real 1.107 +call: 1.108 + 1.109 +.. doctest:: 1.110 + 1.111 + >>> something.backend = mock_backend 1.112 + >>> something.method() 1.113 + 1.114 +Using :attr:`~Mock.mock_calls` we can check the chained call with a single 1.115 +assert. A chained call is several calls in one line of code, so there will be 1.116 +several entries in `mock_calls`. We can use :meth:`call.call_list` to create 1.117 +this list of calls for us: 1.118 + 1.119 +.. doctest:: 1.120 + 1.121 + >>> chained = call.get_endpoint('foobar').create_call('spam', 'eggs').start_call() 1.122 + >>> call_list = chained.call_list() 1.123 + >>> assert mock_backend.mock_calls == call_list 1.124 + 1.125 + 1.126 +Partial mocking 1.127 +=============== 1.128 + 1.129 +In some tests I wanted to mock out a call to `datetime.date.today() 1.130 +<http://docs.python.org/library/datetime.html#datetime.date.today>`_ to return 1.131 +a known date, but I didn't want to prevent the code under test from 1.132 +creating new date objects. Unfortunately `datetime.date` is written in C, and 1.133 +so I couldn't just monkey-patch out the static `date.today` method. 1.134 + 1.135 +I found a simple way of doing this that involved effectively wrapping the date 1.136 +class with a mock, but passing through calls to the constructor to the real 1.137 +class (and returning real instances). 1.138 + 1.139 +The :func:`patch decorator <patch>` is used here to 1.140 +mock out the `date` class in the module under test. The :attr:`side_effect` 1.141 +attribute on the mock date class is then set to a lambda function that returns 1.142 +a real date. When the mock date class is called a real date will be 1.143 +constructed and returned by `side_effect`. 1.144 + 1.145 +.. doctest:: 1.146 + 1.147 + >>> from datetime import date 1.148 + >>> with patch('mymodule.date') as mock_date: 1.149 + ... mock_date.today.return_value = date(2010, 10, 8) 1.150 + ... mock_date.side_effect = lambda *args, **kw: date(*args, **kw) 1.151 + ... 1.152 + ... assert mymodule.date.today() == date(2010, 10, 8) 1.153 + ... assert mymodule.date(2009, 6, 8) == date(2009, 6, 8) 1.154 + ... 1.155 + 1.156 +Note that we don't patch `datetime.date` globally, we patch `date` in the 1.157 +module that *uses* it. See :ref:`where to patch <where-to-patch>`. 1.158 + 1.159 +When `date.today()` is called a known date is returned, but calls to the 1.160 +`date(...)` constructor still return normal dates. Without this you can find 1.161 +yourself having to calculate an expected result using exactly the same 1.162 +algorithm as the code under test, which is a classic testing anti-pattern. 1.163 + 1.164 +Calls to the date constructor are recorded in the `mock_date` attributes 1.165 +(`call_count` and friends) which may also be useful for your tests. 1.166 + 1.167 +An alternative way of dealing with mocking dates, or other builtin classes, 1.168 +is discussed in `this blog entry 1.169 +<http://williamjohnbert.com/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/>`_. 1.170 + 1.171 + 1.172 +Mocking a Generator Method 1.173 +========================== 1.174 + 1.175 +A Python generator is a function or method that uses the `yield statement 1.176 +<http://docs.python.org/reference/simple_stmts.html#the-yield-statement>`_ to 1.177 +return a series of values when iterated over [#]_. 1.178 + 1.179 +A generator method / function is called to return the generator object. It is 1.180 +the generator object that is then iterated over. The protocol method for 1.181 +iteration is `__iter__ 1.182 +<http://docs.python.org/library/stdtypes.html#container.__iter__>`_, so we can 1.183 +mock this using a `MagicMock`. 1.184 + 1.185 +Here's an example class with an "iter" method implemented as a generator: 1.186 + 1.187 +.. doctest:: 1.188 + 1.189 + >>> class Foo(object): 1.190 + ... def iter(self): 1.191 + ... for i in [1, 2, 3]: 1.192 + ... yield i 1.193 + ... 1.194 + >>> foo = Foo() 1.195 + >>> list(foo.iter()) 1.196 + [1, 2, 3] 1.197 + 1.198 + 1.199 +How would we mock this class, and in particular its "iter" method? 1.200 + 1.201 +To configure the values returned from the iteration (implicit in the call to 1.202 +`list`), we need to configure the object returned by the call to `foo.iter()`. 1.203 + 1.204 +.. doctest:: 1.205 + 1.206 + >>> mock_foo = MagicMock() 1.207 + >>> mock_foo.iter.return_value = iter([1, 2, 3]) 1.208 + >>> list(mock_foo.iter()) 1.209 + [1, 2, 3] 1.210 + 1.211 +.. [#] There are also generator expressions and more `advanced uses 1.212 + <http://www.dabeaz.com/coroutines/index.html>`_ of generators, but we aren't 1.213 + concerned about them here. A very good introduction to generators and how 1.214 + powerful they are is: `Generator Tricks for Systems Programmers 1.215 + <http://www.dabeaz.com/generators/>`_. 1.216 + 1.217 + 1.218 +Applying the same patch to every test method 1.219 +============================================ 1.220 + 1.221 +If you want several patches in place for multiple test methods the obvious way 1.222 +is to apply the patch decorators to every method. This can feel like unnecessary 1.223 +repetition. For Python 2.6 or more recent you can use `patch` (in all its 1.224 +various forms) as a class decorator. This applies the patches to all test 1.225 +methods on the class. A test method is identified by methods whose names start 1.226 +with `test`: 1.227 + 1.228 +.. doctest:: 1.229 + 1.230 + >>> @patch('mymodule.SomeClass') 1.231 + ... class MyTest(TestCase): 1.232 + ... 1.233 + ... def test_one(self, MockSomeClass): 1.234 + ... self.assertTrue(mymodule.SomeClass is MockSomeClass) 1.235 + ... 1.236 + ... def test_two(self, MockSomeClass): 1.237 + ... self.assertTrue(mymodule.SomeClass is MockSomeClass) 1.238 + ... 1.239 + ... def not_a_test(self): 1.240 + ... return 'something' 1.241 + ... 1.242 + >>> MyTest('test_one').test_one() 1.243 + >>> MyTest('test_two').test_two() 1.244 + >>> MyTest('test_two').not_a_test() 1.245 + 'something' 1.246 + 1.247 +An alternative way of managing patches is to use the :ref:`start-and-stop`. 1.248 +These allow you to move the patching into your `setUp` and `tearDown` methods. 1.249 + 1.250 +.. doctest:: 1.251 + 1.252 + >>> class MyTest(TestCase): 1.253 + ... def setUp(self): 1.254 + ... self.patcher = patch('mymodule.foo') 1.255 + ... self.mock_foo = self.patcher.start() 1.256 + ... 1.257 + ... def test_foo(self): 1.258 + ... self.assertTrue(mymodule.foo is self.mock_foo) 1.259 + ... 1.260 + ... def tearDown(self): 1.261 + ... self.patcher.stop() 1.262 + ... 1.263 + >>> MyTest('test_foo').run() 1.264 + 1.265 +If you use this technique you must ensure that the patching is "undone" by 1.266 +calling `stop`. This can be fiddlier than you might think, because if an 1.267 +exception is raised in the setUp then tearDown is not called. `unittest2 1.268 +<http://pypi.python.org/pypi/unittest2>`_ cleanup functions make this simpler: 1.269 + 1.270 + 1.271 +.. doctest:: 1.272 + 1.273 + >>> class MyTest(TestCase): 1.274 + ... def setUp(self): 1.275 + ... patcher = patch('mymodule.foo') 1.276 + ... self.addCleanup(patcher.stop) 1.277 + ... self.mock_foo = patcher.start() 1.278 + ... 1.279 + ... def test_foo(self): 1.280 + ... self.assertTrue(mymodule.foo is self.mock_foo) 1.281 + ... 1.282 + >>> MyTest('test_foo').run() 1.283 + 1.284 + 1.285 +Mocking Unbound Methods 1.286 +======================= 1.287 + 1.288 +Whilst writing tests today I needed to patch an *unbound method* (patching the 1.289 +method on the class rather than on the instance). I needed self to be passed 1.290 +in as the first argument because I want to make asserts about which objects 1.291 +were calling this particular method. The issue is that you can't patch with a 1.292 +mock for this, because if you replace an unbound method with a mock it doesn't 1.293 +become a bound method when fetched from the instance, and so it doesn't get 1.294 +self passed in. The workaround is to patch the unbound method with a real 1.295 +function instead. The :func:`patch` decorator makes it so simple to 1.296 +patch out methods with a mock that having to create a real function becomes a 1.297 +nuisance. 1.298 + 1.299 +If you pass `autospec=True` to patch then it does the patching with a 1.300 +*real* function object. This function object has the same signature as the one 1.301 +it is replacing, but delegates to a mock under the hood. You still get your 1.302 +mock auto-created in exactly the same way as before. What it means though, is 1.303 +that if you use it to patch out an unbound method on a class the mocked 1.304 +function will be turned into a bound method if it is fetched from an instance. 1.305 +It will have `self` passed in as the first argument, which is exactly what I 1.306 +wanted: 1.307 + 1.308 +.. doctest:: 1.309 + 1.310 + >>> class Foo(object): 1.311 + ... def foo(self): 1.312 + ... pass 1.313 + ... 1.314 + >>> with patch.object(Foo, 'foo', autospec=True) as mock_foo: 1.315 + ... mock_foo.return_value = 'foo' 1.316 + ... foo = Foo() 1.317 + ... foo.foo() 1.318 + ... 1.319 + 'foo' 1.320 + >>> mock_foo.assert_called_once_with(foo) 1.321 + 1.322 +If we don't use `autospec=True` then the unbound method is patched out 1.323 +with a Mock instance instead, and isn't called with `self`. 1.324 + 1.325 + 1.326 +Checking multiple calls with mock 1.327 +================================= 1.328 + 1.329 +mock has a nice API for making assertions about how your mock objects are used. 1.330 + 1.331 +.. doctest:: 1.332 + 1.333 + >>> mock = Mock() 1.334 + >>> mock.foo_bar.return_value = None 1.335 + >>> mock.foo_bar('baz', spam='eggs') 1.336 + >>> mock.foo_bar.assert_called_with('baz', spam='eggs') 1.337 + 1.338 +If your mock is only being called once you can use the 1.339 +:meth:`assert_called_once_with` method that also asserts that the 1.340 +:attr:`call_count` is one. 1.341 + 1.342 +.. doctest:: 1.343 + 1.344 + >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs') 1.345 + >>> mock.foo_bar() 1.346 + >>> mock.foo_bar.assert_called_once_with('baz', spam='eggs') 1.347 + Traceback (most recent call last): 1.348 + ... 1.349 + AssertionError: Expected to be called once. Called 2 times. 1.350 + 1.351 +Both `assert_called_with` and `assert_called_once_with` make assertions about 1.352 +the *most recent* call. If your mock is going to be called several times, and 1.353 +you want to make assertions about *all* those calls you can use 1.354 +:attr:`~Mock.call_args_list`: 1.355 + 1.356 +.. doctest:: 1.357 + 1.358 + >>> mock = Mock(return_value=None) 1.359 + >>> mock(1, 2, 3) 1.360 + >>> mock(4, 5, 6) 1.361 + >>> mock() 1.362 + >>> mock.call_args_list 1.363 + [call(1, 2, 3), call(4, 5, 6), call()] 1.364 + 1.365 +The :data:`call` helper makes it easy to make assertions about these calls. You 1.366 +can build up a list of expected calls and compare it to `call_args_list`. This 1.367 +looks remarkably similar to the repr of the `call_args_list`: 1.368 + 1.369 +.. doctest:: 1.370 + 1.371 + >>> expected = [call(1, 2, 3), call(4, 5, 6), call()] 1.372 + >>> mock.call_args_list == expected 1.373 + True 1.374 + 1.375 + 1.376 +Coping with mutable arguments 1.377 +============================= 1.378 + 1.379 +Another situation is rare, but can bite you, is when your mock is called with 1.380 +mutable arguments. `call_args` and `call_args_list` store *references* to the 1.381 +arguments. If the arguments are mutated by the code under test then you can no 1.382 +longer make assertions about what the values were when the mock was called. 1.383 + 1.384 +Here's some example code that shows the problem. Imagine the following functions 1.385 +defined in 'mymodule':: 1.386 + 1.387 + def frob(val): 1.388 + pass 1.389 + 1.390 + def grob(val): 1.391 + "First frob and then clear val" 1.392 + frob(val) 1.393 + val.clear() 1.394 + 1.395 +When we try to test that `grob` calls `frob` with the correct argument look 1.396 +what happens: 1.397 + 1.398 +.. doctest:: 1.399 + 1.400 + >>> with patch('mymodule.frob') as mock_frob: 1.401 + ... val = set([6]) 1.402 + ... mymodule.grob(val) 1.403 + ... 1.404 + >>> val 1.405 + set([]) 1.406 + >>> mock_frob.assert_called_with(set([6])) 1.407 + Traceback (most recent call last): 1.408 + ... 1.409 + AssertionError: Expected: ((set([6]),), {}) 1.410 + Called with: ((set([]),), {}) 1.411 + 1.412 +One possibility would be for mock to copy the arguments you pass in. This 1.413 +could then cause problems if you do assertions that rely on object identity 1.414 +for equality. 1.415 + 1.416 +Here's one solution that uses the :attr:`side_effect` 1.417 +functionality. If you provide a `side_effect` function for a mock then 1.418 +`side_effect` will be called with the same args as the mock. This gives us an 1.419 +opportunity to copy the arguments and store them for later assertions. In this 1.420 +example I'm using *another* mock to store the arguments so that I can use the 1.421 +mock methods for doing the assertion. Again a helper function sets this up for 1.422 +me. 1.423 + 1.424 +.. doctest:: 1.425 + 1.426 + >>> from copy import deepcopy 1.427 + >>> from mock import Mock, patch, DEFAULT 1.428 + >>> def copy_call_args(mock): 1.429 + ... new_mock = Mock() 1.430 + ... def side_effect(*args, **kwargs): 1.431 + ... args = deepcopy(args) 1.432 + ... kwargs = deepcopy(kwargs) 1.433 + ... new_mock(*args, **kwargs) 1.434 + ... return DEFAULT 1.435 + ... mock.side_effect = side_effect 1.436 + ... return new_mock 1.437 + ... 1.438 + >>> with patch('mymodule.frob') as mock_frob: 1.439 + ... new_mock = copy_call_args(mock_frob) 1.440 + ... val = set([6]) 1.441 + ... mymodule.grob(val) 1.442 + ... 1.443 + >>> new_mock.assert_called_with(set([6])) 1.444 + >>> new_mock.call_args 1.445 + call(set([6])) 1.446 + 1.447 +`copy_call_args` is called with the mock that will be called. It returns a new 1.448 +mock that we do the assertion on. The `side_effect` function makes a copy of 1.449 +the args and calls our `new_mock` with the copy. 1.450 + 1.451 +.. note:: 1.452 + 1.453 + If your mock is only going to be used once there is an easier way of 1.454 + checking arguments at the point they are called. You can simply do the 1.455 + checking inside a `side_effect` function. 1.456 + 1.457 + .. doctest:: 1.458 + 1.459 + >>> def side_effect(arg): 1.460 + ... assert arg == set([6]) 1.461 + ... 1.462 + >>> mock = Mock(side_effect=side_effect) 1.463 + >>> mock(set([6])) 1.464 + >>> mock(set()) 1.465 + Traceback (most recent call last): 1.466 + ... 1.467 + AssertionError 1.468 + 1.469 +An alternative approach is to create a subclass of `Mock` or `MagicMock` that 1.470 +copies (using `copy.deepcopy 1.471 +<http://docs.python.org/library/copy.html#copy.deepcopy>`_) the arguments. 1.472 +Here's an example implementation: 1.473 + 1.474 +.. doctest:: 1.475 + 1.476 + >>> from copy import deepcopy 1.477 + >>> class CopyingMock(MagicMock): 1.478 + ... def __call__(self, *args, **kwargs): 1.479 + ... args = deepcopy(args) 1.480 + ... kwargs = deepcopy(kwargs) 1.481 + ... return super(CopyingMock, self).__call__(*args, **kwargs) 1.482 + ... 1.483 + >>> c = CopyingMock(return_value=None) 1.484 + >>> arg = set() 1.485 + >>> c(arg) 1.486 + >>> arg.add(1) 1.487 + >>> c.assert_called_with(set()) 1.488 + >>> c.assert_called_with(arg) 1.489 + Traceback (most recent call last): 1.490 + ... 1.491 + AssertionError: Expected call: mock(set([1])) 1.492 + Actual call: mock(set([])) 1.493 + >>> c.foo 1.494 + <CopyingMock name='mock.foo' id='...'> 1.495 + 1.496 +When you subclass `Mock` or `MagicMock` all dynamically created attributes, 1.497 +and the `return_value` will use your subclass automatically. That means all 1.498 +children of a `CopyingMock` will also have the type `CopyingMock`. 1.499 + 1.500 + 1.501 +Raising exceptions on attribute access 1.502 +====================================== 1.503 + 1.504 +You can use :class:`PropertyMock` to mimic the behaviour of properties. This 1.505 +includes raising exceptions when an attribute is accessed. 1.506 + 1.507 +Here's an example raising a `ValueError` when the 'foo' attribute is accessed: 1.508 + 1.509 +.. doctest:: 1.510 + 1.511 + >>> m = MagicMock() 1.512 + >>> p = PropertyMock(side_effect=ValueError) 1.513 + >>> type(m).foo = p 1.514 + >>> m.foo 1.515 + Traceback (most recent call last): 1.516 + .... 1.517 + ValueError 1.518 + 1.519 +Because every mock object has its own type, a new subclass of whichever mock 1.520 +class you're using, all mock objects are isolated from each other. You can 1.521 +safely attach properties (or other descriptors or whatever you want in fact) 1.522 +to `type(mock)` without affecting other mock objects. 1.523 + 1.524 + 1.525 +Multiple calls with different effects 1.526 +===================================== 1.527 + 1.528 +.. note:: 1.529 + 1.530 + In mock 1.0 the handling of iterable `side_effect` was changed. Any 1.531 + exceptions in the iterable will be raised instead of returned. 1.532 + 1.533 +Handling code that needs to behave differently on subsequent calls during the 1.534 +test can be tricky. For example you may have a function that needs to raise 1.535 +an exception the first time it is called but returns a response on the second 1.536 +call (testing retry behaviour). 1.537 + 1.538 +One approach is to use a :attr:`side_effect` function that replaces itself. The 1.539 +first time it is called the `side_effect` sets a new `side_effect` that will 1.540 +be used for the second call. It then raises an exception: 1.541 + 1.542 +.. doctest:: 1.543 + 1.544 + >>> def side_effect(*args): 1.545 + ... def second_call(*args): 1.546 + ... return 'response' 1.547 + ... mock.side_effect = second_call 1.548 + ... raise Exception('boom') 1.549 + ... 1.550 + >>> mock = Mock(side_effect=side_effect) 1.551 + >>> mock('first') 1.552 + Traceback (most recent call last): 1.553 + ... 1.554 + Exception: boom 1.555 + >>> mock('second') 1.556 + 'response' 1.557 + >>> mock.assert_called_with('second') 1.558 + 1.559 +Another perfectly valid way would be to pop return values from a list. If the 1.560 +return value is an exception, raise it instead of returning it: 1.561 + 1.562 +.. doctest:: 1.563 + 1.564 + >>> returns = [Exception('boom'), 'response'] 1.565 + >>> def side_effect(*args): 1.566 + ... result = returns.pop(0) 1.567 + ... if isinstance(result, Exception): 1.568 + ... raise result 1.569 + ... return result 1.570 + ... 1.571 + >>> mock = Mock(side_effect=side_effect) 1.572 + >>> mock('first') 1.573 + Traceback (most recent call last): 1.574 + ... 1.575 + Exception: boom 1.576 + >>> mock('second') 1.577 + 'response' 1.578 + >>> mock.assert_called_with('second') 1.579 + 1.580 +Which approach you prefer is a matter of taste. The first approach is actually 1.581 +a line shorter but maybe the second approach is more readable. 1.582 + 1.583 + 1.584 +Nesting Patches 1.585 +=============== 1.586 + 1.587 +Using patch as a context manager is nice, but if you do multiple patches you 1.588 +can end up with nested with statements indenting further and further to the 1.589 +right: 1.590 + 1.591 +.. doctest:: 1.592 + 1.593 + >>> class MyTest(TestCase): 1.594 + ... 1.595 + ... def test_foo(self): 1.596 + ... with patch('mymodule.Foo') as mock_foo: 1.597 + ... with patch('mymodule.Bar') as mock_bar: 1.598 + ... with patch('mymodule.Spam') as mock_spam: 1.599 + ... assert mymodule.Foo is mock_foo 1.600 + ... assert mymodule.Bar is mock_bar 1.601 + ... assert mymodule.Spam is mock_spam 1.602 + ... 1.603 + >>> original = mymodule.Foo 1.604 + >>> MyTest('test_foo').test_foo() 1.605 + >>> assert mymodule.Foo is original 1.606 + 1.607 +With unittest2_ `cleanup` functions and the :ref:`start-and-stop` we can 1.608 +achieve the same effect without the nested indentation. A simple helper 1.609 +method, `create_patch`, puts the patch in place and returns the created mock 1.610 +for us: 1.611 + 1.612 +.. doctest:: 1.613 + 1.614 + >>> class MyTest(TestCase): 1.615 + ... 1.616 + ... def create_patch(self, name): 1.617 + ... patcher = patch(name) 1.618 + ... thing = patcher.start() 1.619 + ... self.addCleanup(patcher.stop) 1.620 + ... return thing 1.621 + ... 1.622 + ... def test_foo(self): 1.623 + ... mock_foo = self.create_patch('mymodule.Foo') 1.624 + ... mock_bar = self.create_patch('mymodule.Bar') 1.625 + ... mock_spam = self.create_patch('mymodule.Spam') 1.626 + ... 1.627 + ... assert mymodule.Foo is mock_foo 1.628 + ... assert mymodule.Bar is mock_bar 1.629 + ... assert mymodule.Spam is mock_spam 1.630 + ... 1.631 + >>> original = mymodule.Foo 1.632 + >>> MyTest('test_foo').run() 1.633 + >>> assert mymodule.Foo is original 1.634 + 1.635 + 1.636 +Mocking a dictionary with MagicMock 1.637 +=================================== 1.638 + 1.639 +You may want to mock a dictionary, or other container object, recording all 1.640 +access to it whilst having it still behave like a dictionary. 1.641 + 1.642 +We can do this with :class:`MagicMock`, which will behave like a dictionary, 1.643 +and using :data:`~Mock.side_effect` to delegate dictionary access to a real 1.644 +underlying dictionary that is under our control. 1.645 + 1.646 +When the `__getitem__` and `__setitem__` methods of our `MagicMock` are called 1.647 +(normal dictionary access) then `side_effect` is called with the key (and in 1.648 +the case of `__setitem__` the value too). We can also control what is returned. 1.649 + 1.650 +After the `MagicMock` has been used we can use attributes like 1.651 +:data:`~Mock.call_args_list` to assert about how the dictionary was used: 1.652 + 1.653 +.. doctest:: 1.654 + 1.655 + >>> my_dict = {'a': 1, 'b': 2, 'c': 3} 1.656 + >>> def getitem(name): 1.657 + ... return my_dict[name] 1.658 + ... 1.659 + >>> def setitem(name, val): 1.660 + ... my_dict[name] = val 1.661 + ... 1.662 + >>> mock = MagicMock() 1.663 + >>> mock.__getitem__.side_effect = getitem 1.664 + >>> mock.__setitem__.side_effect = setitem 1.665 + 1.666 +.. note:: 1.667 + 1.668 + An alternative to using `MagicMock` is to use `Mock` and *only* provide 1.669 + the magic methods you specifically want: 1.670 + 1.671 + .. doctest:: 1.672 + 1.673 + >>> mock = Mock() 1.674 + >>> mock.__setitem__ = Mock(side_effect=getitem) 1.675 + >>> mock.__getitem__ = Mock(side_effect=setitem) 1.676 + 1.677 + A *third* option is to use `MagicMock` but passing in `dict` as the `spec` 1.678 + (or `spec_set`) argument so that the `MagicMock` created only has 1.679 + dictionary magic methods available: 1.680 + 1.681 + .. doctest:: 1.682 + 1.683 + >>> mock = MagicMock(spec_set=dict) 1.684 + >>> mock.__getitem__.side_effect = getitem 1.685 + >>> mock.__setitem__.side_effect = setitem 1.686 + 1.687 +With these side effect functions in place, the `mock` will behave like a normal 1.688 +dictionary but recording the access. It even raises a `KeyError` if you try 1.689 +to access a key that doesn't exist. 1.690 + 1.691 +.. doctest:: 1.692 + 1.693 + >>> mock['a'] 1.694 + 1 1.695 + >>> mock['c'] 1.696 + 3 1.697 + >>> mock['d'] 1.698 + Traceback (most recent call last): 1.699 + ... 1.700 + KeyError: 'd' 1.701 + >>> mock['b'] = 'fish' 1.702 + >>> mock['d'] = 'eggs' 1.703 + >>> mock['b'] 1.704 + 'fish' 1.705 + >>> mock['d'] 1.706 + 'eggs' 1.707 + 1.708 +After it has been used you can make assertions about the access using the normal 1.709 +mock methods and attributes: 1.710 + 1.711 +.. doctest:: 1.712 + 1.713 + >>> mock.__getitem__.call_args_list 1.714 + [call('a'), call('c'), call('d'), call('b'), call('d')] 1.715 + >>> mock.__setitem__.call_args_list 1.716 + [call('b', 'fish'), call('d', 'eggs')] 1.717 + >>> my_dict 1.718 + {'a': 1, 'c': 3, 'b': 'fish', 'd': 'eggs'} 1.719 + 1.720 + 1.721 +Mock subclasses and their attributes 1.722 +==================================== 1.723 + 1.724 +There are various reasons why you might want to subclass `Mock`. One reason 1.725 +might be to add helper methods. Here's a silly example: 1.726 + 1.727 +.. doctest:: 1.728 + 1.729 + >>> class MyMock(MagicMock): 1.730 + ... def has_been_called(self): 1.731 + ... return self.called 1.732 + ... 1.733 + >>> mymock = MyMock(return_value=None) 1.734 + >>> mymock 1.735 + <MyMock id='...'> 1.736 + >>> mymock.has_been_called() 1.737 + False 1.738 + >>> mymock() 1.739 + >>> mymock.has_been_called() 1.740 + True 1.741 + 1.742 +The standard behaviour for `Mock` instances is that attributes and the return 1.743 +value mocks are of the same type as the mock they are accessed on. This ensures 1.744 +that `Mock` attributes are `Mocks` and `MagicMock` attributes are `MagicMocks` 1.745 +[#]_. So if you're subclassing to add helper methods then they'll also be 1.746 +available on the attributes and return value mock of instances of your 1.747 +subclass. 1.748 + 1.749 +.. doctest:: 1.750 + 1.751 + >>> mymock.foo 1.752 + <MyMock name='mock.foo' id='...'> 1.753 + >>> mymock.foo.has_been_called() 1.754 + False 1.755 + >>> mymock.foo() 1.756 + <MyMock name='mock.foo()' id='...'> 1.757 + >>> mymock.foo.has_been_called() 1.758 + True 1.759 + 1.760 +Sometimes this is inconvenient. For example, `one user 1.761 +<https://code.google.com/p/mock/issues/detail?id=105>`_ is subclassing mock to 1.762 +created a `Twisted adaptor 1.763 +<http://twistedmatrix.com/documents/11.0.0/api/twisted.python.components.html>`_. 1.764 +Having this applied to attributes too actually causes errors. 1.765 + 1.766 +`Mock` (in all its flavours) uses a method called `_get_child_mock` to create 1.767 +these "sub-mocks" for attributes and return values. You can prevent your 1.768 +subclass being used for attributes by overriding this method. The signature is 1.769 +that it takes arbitrary keyword arguments (`**kwargs`) which are then passed 1.770 +onto the mock constructor: 1.771 + 1.772 +.. doctest:: 1.773 + 1.774 + >>> class Subclass(MagicMock): 1.775 + ... def _get_child_mock(self, **kwargs): 1.776 + ... return MagicMock(**kwargs) 1.777 + ... 1.778 + >>> mymock = Subclass() 1.779 + >>> mymock.foo 1.780 + <MagicMock name='mock.foo' id='...'> 1.781 + >>> assert isinstance(mymock, Subclass) 1.782 + >>> assert not isinstance(mymock.foo, Subclass) 1.783 + >>> assert not isinstance(mymock(), Subclass) 1.784 + 1.785 +.. [#] An exception to this rule are the non-callable mocks. Attributes use the 1.786 + callable variant because otherwise non-callable mocks couldn't have callable 1.787 + methods. 1.788 + 1.789 + 1.790 +Mocking imports with patch.dict 1.791 +=============================== 1.792 + 1.793 +One situation where mocking can be hard is where you have a local import inside 1.794 +a function. These are harder to mock because they aren't using an object from 1.795 +the module namespace that we can patch out. 1.796 + 1.797 +Generally local imports are to be avoided. They are sometimes done to prevent 1.798 +circular dependencies, for which there is *usually* a much better way to solve 1.799 +the problem (refactor the code) or to prevent "up front costs" by delaying the 1.800 +import. This can also be solved in better ways than an unconditional local 1.801 +import (store the module as a class or module attribute and only do the import 1.802 +on first use). 1.803 + 1.804 +That aside there is a way to use `mock` to affect the results of an import. 1.805 +Importing fetches an *object* from the `sys.modules` dictionary. Note that it 1.806 +fetches an *object*, which need not be a module. Importing a module for the 1.807 +first time results in a module object being put in `sys.modules`, so usually 1.808 +when you import something you get a module back. This need not be the case 1.809 +however. 1.810 + 1.811 +This means you can use :func:`patch.dict` to *temporarily* put a mock in place 1.812 +in `sys.modules`. Any imports whilst this patch is active will fetch the mock. 1.813 +When the patch is complete (the decorated function exits, the with statement 1.814 +body is complete or `patcher.stop()` is called) then whatever was there 1.815 +previously will be restored safely. 1.816 + 1.817 +Here's an example that mocks out the 'fooble' module. 1.818 + 1.819 +.. doctest:: 1.820 + 1.821 + >>> mock = Mock() 1.822 + >>> with patch.dict('sys.modules', {'fooble': mock}): 1.823 + ... import fooble 1.824 + ... fooble.blob() 1.825 + ... 1.826 + <Mock name='mock.blob()' id='...'> 1.827 + >>> assert 'fooble' not in sys.modules 1.828 + >>> mock.blob.assert_called_once_with() 1.829 + 1.830 +As you can see the `import fooble` succeeds, but on exit there is no 'fooble' 1.831 +left in `sys.modules`. 1.832 + 1.833 +This also works for the `from module import name` form: 1.834 + 1.835 +.. doctest:: 1.836 + 1.837 + >>> mock = Mock() 1.838 + >>> with patch.dict('sys.modules', {'fooble': mock}): 1.839 + ... from fooble import blob 1.840 + ... blob.blip() 1.841 + ... 1.842 + <Mock name='mock.blob.blip()' id='...'> 1.843 + >>> mock.blob.blip.assert_called_once_with() 1.844 + 1.845 +With slightly more work you can also mock package imports: 1.846 + 1.847 +.. doctest:: 1.848 + 1.849 + >>> mock = Mock() 1.850 + >>> modules = {'package': mock, 'package.module': mock.module} 1.851 + >>> with patch.dict('sys.modules', modules): 1.852 + ... from package.module import fooble 1.853 + ... fooble() 1.854 + ... 1.855 + <Mock name='mock.module.fooble()' id='...'> 1.856 + >>> mock.module.fooble.assert_called_once_with() 1.857 + 1.858 + 1.859 +Tracking order of calls and less verbose call assertions 1.860 +======================================================== 1.861 + 1.862 +The :class:`Mock` class allows you to track the *order* of method calls on 1.863 +your mock objects through the :attr:`~Mock.method_calls` attribute. This 1.864 +doesn't allow you to track the order of calls between separate mock objects, 1.865 +however we can use :attr:`~Mock.mock_calls` to achieve the same effect. 1.866 + 1.867 +Because mocks track calls to child mocks in `mock_calls`, and accessing an 1.868 +arbitrary attribute of a mock creates a child mock, we can create our separate 1.869 +mocks from a parent one. Calls to those child mock will then all be recorded, 1.870 +in order, in the `mock_calls` of the parent: 1.871 + 1.872 +.. doctest:: 1.873 + 1.874 + >>> manager = Mock() 1.875 + >>> mock_foo = manager.foo 1.876 + >>> mock_bar = manager.bar 1.877 + 1.878 + >>> mock_foo.something() 1.879 + <Mock name='mock.foo.something()' id='...'> 1.880 + >>> mock_bar.other.thing() 1.881 + <Mock name='mock.bar.other.thing()' id='...'> 1.882 + 1.883 + >>> manager.mock_calls 1.884 + [call.foo.something(), call.bar.other.thing()] 1.885 + 1.886 +We can then assert about the calls, including the order, by comparing with 1.887 +the `mock_calls` attribute on the manager mock: 1.888 + 1.889 +.. doctest:: 1.890 + 1.891 + >>> expected_calls = [call.foo.something(), call.bar.other.thing()] 1.892 + >>> manager.mock_calls == expected_calls 1.893 + True 1.894 + 1.895 +If `patch` is creating, and putting in place, your mocks then you can attach 1.896 +them to a manager mock using the :meth:`~Mock.attach_mock` method. After 1.897 +attaching calls will be recorded in `mock_calls` of the manager. 1.898 + 1.899 +.. doctest:: 1.900 + 1.901 + >>> manager = MagicMock() 1.902 + >>> with patch('mymodule.Class1') as MockClass1: 1.903 + ... with patch('mymodule.Class2') as MockClass2: 1.904 + ... manager.attach_mock(MockClass1, 'MockClass1') 1.905 + ... manager.attach_mock(MockClass2, 'MockClass2') 1.906 + ... MockClass1().foo() 1.907 + ... MockClass2().bar() 1.908 + ... 1.909 + <MagicMock name='mock.MockClass1().foo()' id='...'> 1.910 + <MagicMock name='mock.MockClass2().bar()' id='...'> 1.911 + >>> manager.mock_calls 1.912 + [call.MockClass1(), 1.913 + call.MockClass1().foo(), 1.914 + call.MockClass2(), 1.915 + call.MockClass2().bar()] 1.916 + 1.917 +If many calls have been made, but you're only interested in a particular 1.918 +sequence of them then an alternative is to use the 1.919 +:meth:`~Mock.assert_has_calls` method. This takes a list of calls (constructed 1.920 +with the :data:`call` object). If that sequence of calls are in 1.921 +:attr:`~Mock.mock_calls` then the assert succeeds. 1.922 + 1.923 +.. doctest:: 1.924 + 1.925 + >>> m = MagicMock() 1.926 + >>> m().foo().bar().baz() 1.927 + <MagicMock name='mock().foo().bar().baz()' id='...'> 1.928 + >>> m.one().two().three() 1.929 + <MagicMock name='mock.one().two().three()' id='...'> 1.930 + >>> calls = call.one().two().three().call_list() 1.931 + >>> m.assert_has_calls(calls) 1.932 + 1.933 +Even though the chained call `m.one().two().three()` aren't the only calls that 1.934 +have been made to the mock, the assert still succeeds. 1.935 + 1.936 +Sometimes a mock may have several calls made to it, and you are only interested 1.937 +in asserting about *some* of those calls. You may not even care about the 1.938 +order. In this case you can pass `any_order=True` to `assert_has_calls`: 1.939 + 1.940 +.. doctest:: 1.941 + 1.942 + >>> m = MagicMock() 1.943 + >>> m(1), m.two(2, 3), m.seven(7), m.fifty('50') 1.944 + (...) 1.945 + >>> calls = [call.fifty('50'), call(1), call.seven(7)] 1.946 + >>> m.assert_has_calls(calls, any_order=True) 1.947 + 1.948 + 1.949 +More complex argument matching 1.950 +============================== 1.951 + 1.952 +Using the same basic concept as `ANY` we can implement matchers to do more 1.953 +complex assertions on objects used as arguments to mocks. 1.954 + 1.955 +Suppose we expect some object to be passed to a mock that by default 1.956 +compares equal based on object identity (which is the Python default for user 1.957 +defined classes). To use :meth:`~Mock.assert_called_with` we would need to pass 1.958 +in the exact same object. If we are only interested in some of the attributes 1.959 +of this object then we can create a matcher that will check these attributes 1.960 +for us. 1.961 + 1.962 +You can see in this example how a 'standard' call to `assert_called_with` isn't 1.963 +sufficient: 1.964 + 1.965 +.. doctest:: 1.966 + 1.967 + >>> class Foo(object): 1.968 + ... def __init__(self, a, b): 1.969 + ... self.a, self.b = a, b 1.970 + ... 1.971 + >>> mock = Mock(return_value=None) 1.972 + >>> mock(Foo(1, 2)) 1.973 + >>> mock.assert_called_with(Foo(1, 2)) 1.974 + Traceback (most recent call last): 1.975 + ... 1.976 + AssertionError: Expected: call(<__main__.Foo object at 0x...>) 1.977 + Actual call: call(<__main__.Foo object at 0x...>) 1.978 + 1.979 +A comparison function for our `Foo` class might look something like this: 1.980 + 1.981 +.. doctest:: 1.982 + 1.983 + >>> def compare(self, other): 1.984 + ... if not type(self) == type(other): 1.985 + ... return False 1.986 + ... if self.a != other.a: 1.987 + ... return False 1.988 + ... if self.b != other.b: 1.989 + ... return False 1.990 + ... return True 1.991 + ... 1.992 + 1.993 +And a matcher object that can use comparison functions like this for its 1.994 +equality operation would look something like this: 1.995 + 1.996 +.. doctest:: 1.997 + 1.998 + >>> class Matcher(object): 1.999 + ... def __init__(self, compare, some_obj): 1.1000 + ... self.compare = compare 1.1001 + ... self.some_obj = some_obj 1.1002 + ... def __eq__(self, other): 1.1003 + ... return self.compare(self.some_obj, other) 1.1004 + ... 1.1005 + 1.1006 +Putting all this together: 1.1007 + 1.1008 +.. doctest:: 1.1009 + 1.1010 + >>> match_foo = Matcher(compare, Foo(1, 2)) 1.1011 + >>> mock.assert_called_with(match_foo) 1.1012 + 1.1013 +The `Matcher` is instantiated with our compare function and the `Foo` object 1.1014 +we want to compare against. In `assert_called_with` the `Matcher` equality 1.1015 +method will be called, which compares the object the mock was called with 1.1016 +against the one we created our matcher with. If they match then 1.1017 +`assert_called_with` passes, and if they don't an `AssertionError` is raised: 1.1018 + 1.1019 +.. doctest:: 1.1020 + 1.1021 + >>> match_wrong = Matcher(compare, Foo(3, 4)) 1.1022 + >>> mock.assert_called_with(match_wrong) 1.1023 + Traceback (most recent call last): 1.1024 + ... 1.1025 + AssertionError: Expected: ((<Matcher object at 0x...>,), {}) 1.1026 + Called with: ((<Foo object at 0x...>,), {}) 1.1027 + 1.1028 +With a bit of tweaking you could have the comparison function raise the 1.1029 +`AssertionError` directly and provide a more useful failure message. 1.1030 + 1.1031 +As of version 1.5, the Python testing library `PyHamcrest 1.1032 +<http://pypi.python.org/pypi/PyHamcrest>`_ provides similar functionality, 1.1033 +that may be useful here, in the form of its equality matcher 1.1034 +(`hamcrest.library.integration.match_equality 1.1035 +<http://packages.python.org/PyHamcrest/integration.html#hamcrest.library.integration.match_equality>`_). 1.1036 + 1.1037 + 1.1038 +Less verbose configuration of mock objects 1.1039 +========================================== 1.1040 + 1.1041 +This recipe, for easier configuration of mock objects, is now part of `Mock`. 1.1042 +See the :meth:`~Mock.configure_mock` method. 1.1043 + 1.1044 + 1.1045 +Matching any argument in assertions 1.1046 +=================================== 1.1047 + 1.1048 +This example is now built in to mock. See :data:`ANY`. 1.1049 + 1.1050 + 1.1051 +Mocking Properties 1.1052 +================== 1.1053 + 1.1054 +This example is now built in to mock. See :class:`PropertyMock`. 1.1055 + 1.1056 + 1.1057 +Mocking open 1.1058 +============ 1.1059 + 1.1060 +This example is now built in to mock. See :func:`mock_open`. 1.1061 + 1.1062 + 1.1063 +Mocks without some attributes 1.1064 +============================= 1.1065 + 1.1066 +This example is now built in to mock. See :ref:`deleting-attributes`.