python/mock-1.0.0/docs/getting-started.txt

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/python/mock-1.0.0/docs/getting-started.txt	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,479 @@
     1.4 +===========================
     1.5 + Getting Started with Mock
     1.6 +===========================
     1.7 +
     1.8 +.. _getting-started:
     1.9 +
    1.10 +.. index:: Getting Started
    1.11 +
    1.12 +.. testsetup::
    1.13 +
    1.14 +    class SomeClass(object):
    1.15 +        static_method = None
    1.16 +        class_method = None
    1.17 +        attribute = None
    1.18 +
    1.19 +    sys.modules['package'] = package = Mock(name='package')
    1.20 +    sys.modules['package.module'] = module = package.module
    1.21 +    sys.modules['module'] = package.module
    1.22 +
    1.23 +
    1.24 +Using Mock
    1.25 +==========
    1.26 +
    1.27 +Mock Patching Methods
    1.28 +---------------------
    1.29 +
    1.30 +Common uses for :class:`Mock` objects include:
    1.31 +
    1.32 +* Patching methods
    1.33 +* Recording method calls on objects
    1.34 +
    1.35 +You might want to replace a method on an object to check that
    1.36 +it is called with the correct arguments by another part of the system:
    1.37 +
    1.38 +.. doctest::
    1.39 +
    1.40 +    >>> real = SomeClass()
    1.41 +    >>> real.method = MagicMock(name='method')
    1.42 +    >>> real.method(3, 4, 5, key='value')
    1.43 +    <MagicMock name='method()' id='...'>
    1.44 +
    1.45 +Once our mock has been used (`real.method` in this example) it has methods
    1.46 +and attributes that allow you to make assertions about how it has been used.
    1.47 +
    1.48 +.. note::
    1.49 +
    1.50 +    In most of these examples the :class:`Mock` and :class:`MagicMock` classes
    1.51 +    are interchangeable. As the `MagicMock` is the more capable class it makes
    1.52 +    a sensible one to use by default.
    1.53 +
    1.54 +Once the mock has been called its :attr:`~Mock.called` attribute is set to
    1.55 +`True`. More importantly we can use the :meth:`~Mock.assert_called_with` or
    1.56 +:meth:`~Mock.assert_called_once_with` method to check that it was called with
    1.57 +the correct arguments.
    1.58 +
    1.59 +This example tests that calling `ProductionClass().method` results in a call to
    1.60 +the `something` method:
    1.61 +
    1.62 +.. doctest::
    1.63 +
    1.64 +    >>> from mock import MagicMock
    1.65 +    >>> class ProductionClass(object):
    1.66 +    ...     def method(self):
    1.67 +    ...         self.something(1, 2, 3)
    1.68 +    ...     def something(self, a, b, c):
    1.69 +    ...         pass
    1.70 +    ...
    1.71 +    >>> real = ProductionClass()
    1.72 +    >>> real.something = MagicMock()
    1.73 +    >>> real.method()
    1.74 +    >>> real.something.assert_called_once_with(1, 2, 3)
    1.75 +
    1.76 +
    1.77 +
    1.78 +Mock for Method Calls on an Object
    1.79 +----------------------------------
    1.80 +
    1.81 +In the last example we patched a method directly on an object to check that it
    1.82 +was called correctly. Another common use case is to pass an object into a
    1.83 +method (or some part of the system under test) and then check that it is used
    1.84 +in the correct way.
    1.85 +
    1.86 +The simple `ProductionClass` below has a `closer` method. If it is called with
    1.87 +an object then it calls `close` on it.
    1.88 +
    1.89 +.. doctest::
    1.90 +
    1.91 +    >>> class ProductionClass(object):
    1.92 +    ...     def closer(self, something):
    1.93 +    ...         something.close()
    1.94 +    ...
    1.95 +
    1.96 +So to test it we need to pass in an object with a `close` method and check
    1.97 +that it was called correctly.
    1.98 +
    1.99 +.. doctest::
   1.100 +
   1.101 +    >>> real = ProductionClass()
   1.102 +    >>> mock = Mock()
   1.103 +    >>> real.closer(mock)
   1.104 +    >>> mock.close.assert_called_with()
   1.105 +
   1.106 +We don't have to do any work to provide the 'close' method on our mock.
   1.107 +Accessing close creates it. So, if 'close' hasn't already been called then
   1.108 +accessing it in the test will create it, but :meth:`~Mock.assert_called_with`
   1.109 +will raise a failure exception.
   1.110 +
   1.111 +
   1.112 +Mocking Classes
   1.113 +---------------
   1.114 +
   1.115 +A common use case is to mock out classes instantiated by your code under test.
   1.116 +When you patch a class, then that class is replaced with a mock. Instances
   1.117 +are created by *calling the class*. This means you access the "mock instance"
   1.118 +by looking at the return value of the mocked class.
   1.119 +
   1.120 +In the example below we have a function `some_function` that instantiates `Foo`
   1.121 +and calls a method on it. The call to `patch` replaces the class `Foo` with a
   1.122 +mock. The `Foo` instance is the result of calling the mock, so it is configured
   1.123 +by modifying the mock :attr:`~Mock.return_value`.
   1.124 +
   1.125 +.. doctest::
   1.126 +
   1.127 +    >>> def some_function():
   1.128 +    ...     instance = module.Foo()
   1.129 +    ...     return instance.method()
   1.130 +    ...
   1.131 +    >>> with patch('module.Foo') as mock:
   1.132 +    ...     instance = mock.return_value
   1.133 +    ...     instance.method.return_value = 'the result'
   1.134 +    ...     result = some_function()
   1.135 +    ...     assert result == 'the result'
   1.136 +
   1.137 +
   1.138 +Naming your mocks
   1.139 +-----------------
   1.140 +
   1.141 +It can be useful to give your mocks a name. The name is shown in the repr of
   1.142 +the mock and can be helpful when the mock appears in test failure messages. The
   1.143 +name is also propagated to attributes or methods of the mock:
   1.144 +
   1.145 +.. doctest::
   1.146 +
   1.147 +    >>> mock = MagicMock(name='foo')
   1.148 +    >>> mock
   1.149 +    <MagicMock name='foo' id='...'>
   1.150 +    >>> mock.method
   1.151 +    <MagicMock name='foo.method' id='...'>
   1.152 +
   1.153 +
   1.154 +Tracking all Calls
   1.155 +------------------
   1.156 +
   1.157 +Often you want to track more than a single call to a method. The
   1.158 +:attr:`~Mock.mock_calls` attribute records all calls
   1.159 +to child attributes of the mock - and also to their children.
   1.160 +
   1.161 +.. doctest::
   1.162 +
   1.163 +    >>> mock = MagicMock()
   1.164 +    >>> mock.method()
   1.165 +    <MagicMock name='mock.method()' id='...'>
   1.166 +    >>> mock.attribute.method(10, x=53)
   1.167 +    <MagicMock name='mock.attribute.method()' id='...'>
   1.168 +    >>> mock.mock_calls
   1.169 +    [call.method(), call.attribute.method(10, x=53)]
   1.170 +
   1.171 +If you make an assertion about `mock_calls` and any unexpected methods
   1.172 +have been called, then the assertion will fail. This is useful because as well
   1.173 +as asserting that the calls you expected have been made, you are also checking
   1.174 +that they were made in the right order and with no additional calls:
   1.175 +
   1.176 +You use the :data:`call` object to construct lists for comparing with
   1.177 +`mock_calls`:
   1.178 +
   1.179 +.. doctest::
   1.180 +
   1.181 +    >>> expected = [call.method(), call.attribute.method(10, x=53)]
   1.182 +    >>> mock.mock_calls == expected
   1.183 +    True
   1.184 +
   1.185 +
   1.186 +Setting Return Values and Attributes
   1.187 +------------------------------------
   1.188 +
   1.189 +Setting the return values on a mock object is trivially easy:
   1.190 +
   1.191 +.. doctest::
   1.192 +
   1.193 +    >>> mock = Mock()
   1.194 +    >>> mock.return_value = 3
   1.195 +    >>> mock()
   1.196 +    3
   1.197 +
   1.198 +Of course you can do the same for methods on the mock:
   1.199 +
   1.200 +.. doctest::
   1.201 +
   1.202 +    >>> mock = Mock()
   1.203 +    >>> mock.method.return_value = 3
   1.204 +    >>> mock.method()
   1.205 +    3
   1.206 +
   1.207 +The return value can also be set in the constructor:
   1.208 +
   1.209 +.. doctest::
   1.210 +
   1.211 +    >>> mock = Mock(return_value=3)
   1.212 +    >>> mock()
   1.213 +    3
   1.214 +
   1.215 +If you need an attribute setting on your mock, just do it:
   1.216 +
   1.217 +.. doctest::
   1.218 +
   1.219 +    >>> mock = Mock()
   1.220 +    >>> mock.x = 3
   1.221 +    >>> mock.x
   1.222 +    3
   1.223 +
   1.224 +Sometimes you want to mock up a more complex situation, like for example
   1.225 +`mock.connection.cursor().execute("SELECT 1")`. If we wanted this call to
   1.226 +return a list, then we have to configure the result of the nested call.
   1.227 +
   1.228 +We can use :data:`call` to construct the set of calls in a "chained call" like
   1.229 +this for easy assertion afterwards:
   1.230 +
   1.231 +
   1.232 +.. doctest::
   1.233 +
   1.234 +    >>> mock = Mock()
   1.235 +    >>> cursor = mock.connection.cursor.return_value
   1.236 +    >>> cursor.execute.return_value = ['foo']
   1.237 +    >>> mock.connection.cursor().execute("SELECT 1")
   1.238 +    ['foo']
   1.239 +    >>> expected = call.connection.cursor().execute("SELECT 1").call_list()
   1.240 +    >>> mock.mock_calls
   1.241 +    [call.connection.cursor(), call.connection.cursor().execute('SELECT 1')]
   1.242 +    >>> mock.mock_calls == expected
   1.243 +    True
   1.244 +
   1.245 +It is the call to `.call_list()` that turns our call object into a list of
   1.246 +calls representing the chained calls.
   1.247 +
   1.248 +
   1.249 +
   1.250 +Raising exceptions with mocks
   1.251 +-----------------------------
   1.252 +
   1.253 +A useful attribute is :attr:`~Mock.side_effect`. If you set this to an
   1.254 +exception class or instance then the exception will be raised when the mock
   1.255 +is called.
   1.256 +
   1.257 +.. doctest::
   1.258 +
   1.259 +    >>> mock = Mock(side_effect=Exception('Boom!'))
   1.260 +    >>> mock()
   1.261 +    Traceback (most recent call last):
   1.262 +      ...
   1.263 +    Exception: Boom!
   1.264 +
   1.265 +
   1.266 +Side effect functions and iterables
   1.267 +-----------------------------------
   1.268 +
   1.269 +`side_effect` can also be set to a function or an iterable. The use case for
   1.270 +`side_effect` as an iterable is where your mock is going to be called several
   1.271 +times, and you want each call to return a different value. When you set
   1.272 +`side_effect` to an iterable every call to the mock returns the next value
   1.273 +from the iterable:
   1.274 +
   1.275 +.. doctest::
   1.276 +
   1.277 +    >>> mock = MagicMock(side_effect=[4, 5, 6])
   1.278 +    >>> mock()
   1.279 +    4
   1.280 +    >>> mock()
   1.281 +    5
   1.282 +    >>> mock()
   1.283 +    6
   1.284 +
   1.285 +
   1.286 +For more advanced use cases, like dynamically varying the return values
   1.287 +depending on what the mock is called with, `side_effect` can be a function.
   1.288 +The function will be called with the same arguments as the mock. Whatever the
   1.289 +function returns is what the call returns:
   1.290 +
   1.291 +.. doctest::
   1.292 +
   1.293 +    >>> vals = {(1, 2): 1, (2, 3): 2}
   1.294 +    >>> def side_effect(*args):
   1.295 +    ...     return vals[args]
   1.296 +    ...
   1.297 +    >>> mock = MagicMock(side_effect=side_effect)
   1.298 +    >>> mock(1, 2)
   1.299 +    1
   1.300 +    >>> mock(2, 3)
   1.301 +    2
   1.302 +
   1.303 +
   1.304 +Creating a Mock from an Existing Object
   1.305 +---------------------------------------
   1.306 +
   1.307 +One problem with over use of mocking is that it couples your tests to the
   1.308 +implementation of your mocks rather than your real code. Suppose you have a
   1.309 +class that implements `some_method`. In a test for another class, you
   1.310 +provide a mock of this object that *also* provides `some_method`. If later
   1.311 +you refactor the first class, so that it no longer has `some_method` - then
   1.312 +your tests will continue to pass even though your code is now broken!
   1.313 +
   1.314 +`Mock` allows you to provide an object as a specification for the mock,
   1.315 +using the `spec` keyword argument. Accessing methods / attributes on the
   1.316 +mock that don't exist on your specification object will immediately raise an
   1.317 +attribute error. If you change the implementation of your specification, then
   1.318 +tests that use that class will start failing immediately without you having to
   1.319 +instantiate the class in those tests.
   1.320 +
   1.321 +.. doctest::
   1.322 +
   1.323 +    >>> mock = Mock(spec=SomeClass)
   1.324 +    >>> mock.old_method()
   1.325 +    Traceback (most recent call last):
   1.326 +       ...
   1.327 +    AttributeError: object has no attribute 'old_method'
   1.328 +
   1.329 +If you want a stronger form of specification that prevents the setting
   1.330 +of arbitrary attributes as well as the getting of them then you can use
   1.331 +`spec_set` instead of `spec`.
   1.332 +
   1.333 +
   1.334 +
   1.335 +Patch Decorators
   1.336 +================
   1.337 +
   1.338 +.. note::
   1.339 +
   1.340 +   With `patch` it matters that you patch objects in the namespace where they
   1.341 +   are looked up. This is normally straightforward, but for a quick guide
   1.342 +   read :ref:`where to patch <where-to-patch>`.
   1.343 +
   1.344 +
   1.345 +A common need in tests is to patch a class attribute or a module attribute,
   1.346 +for example patching a builtin or patching a class in a module to test that it
   1.347 +is instantiated. Modules and classes are effectively global, so patching on
   1.348 +them has to be undone after the test or the patch will persist into other
   1.349 +tests and cause hard to diagnose problems.
   1.350 +
   1.351 +mock provides three convenient decorators for this: `patch`, `patch.object` and
   1.352 +`patch.dict`. `patch` takes a single string, of the form
   1.353 +`package.module.Class.attribute` to specify the attribute you are patching. It
   1.354 +also optionally takes a value that you want the attribute (or class or
   1.355 +whatever) to be replaced with. 'patch.object' takes an object and the name of
   1.356 +the attribute you would like patched, plus optionally the value to patch it
   1.357 +with.
   1.358 +
   1.359 +`patch.object`:
   1.360 +
   1.361 +.. doctest::
   1.362 +
   1.363 +    >>> original = SomeClass.attribute
   1.364 +    >>> @patch.object(SomeClass, 'attribute', sentinel.attribute)
   1.365 +    ... def test():
   1.366 +    ...     assert SomeClass.attribute == sentinel.attribute
   1.367 +    ...
   1.368 +    >>> test()
   1.369 +    >>> assert SomeClass.attribute == original
   1.370 +
   1.371 +    >>> @patch('package.module.attribute', sentinel.attribute)
   1.372 +    ... def test():
   1.373 +    ...     from package.module import attribute
   1.374 +    ...     assert attribute is sentinel.attribute
   1.375 +    ...
   1.376 +    >>> test()
   1.377 +
   1.378 +If you are patching a module (including `__builtin__`) then use `patch`
   1.379 +instead of `patch.object`:
   1.380 +
   1.381 +.. doctest::
   1.382 +
   1.383 +    >>> mock = MagicMock(return_value = sentinel.file_handle)
   1.384 +    >>> with patch('__builtin__.open', mock):
   1.385 +    ...     handle = open('filename', 'r')
   1.386 +    ...
   1.387 +    >>> mock.assert_called_with('filename', 'r')
   1.388 +    >>> assert handle == sentinel.file_handle, "incorrect file handle returned"
   1.389 +
   1.390 +The module name can be 'dotted', in the form `package.module` if needed:
   1.391 +
   1.392 +.. doctest::
   1.393 +
   1.394 +    >>> @patch('package.module.ClassName.attribute', sentinel.attribute)
   1.395 +    ... def test():
   1.396 +    ...     from package.module import ClassName
   1.397 +    ...     assert ClassName.attribute == sentinel.attribute
   1.398 +    ...
   1.399 +    >>> test()
   1.400 +
   1.401 +A nice pattern is to actually decorate test methods themselves:
   1.402 +
   1.403 +.. doctest::
   1.404 +
   1.405 +    >>> class MyTest(unittest2.TestCase):
   1.406 +    ...     @patch.object(SomeClass, 'attribute', sentinel.attribute)
   1.407 +    ...     def test_something(self):
   1.408 +    ...         self.assertEqual(SomeClass.attribute, sentinel.attribute)
   1.409 +    ...
   1.410 +    >>> original = SomeClass.attribute
   1.411 +    >>> MyTest('test_something').test_something()
   1.412 +    >>> assert SomeClass.attribute == original
   1.413 +
   1.414 +If you want to patch with a Mock, you can use `patch` with only one argument
   1.415 +(or `patch.object` with two arguments). The mock will be created for you and
   1.416 +passed into the test function / method:
   1.417 +
   1.418 +.. doctest::
   1.419 +
   1.420 +    >>> class MyTest(unittest2.TestCase):
   1.421 +    ...     @patch.object(SomeClass, 'static_method')
   1.422 +    ...     def test_something(self, mock_method):
   1.423 +    ...         SomeClass.static_method()
   1.424 +    ...         mock_method.assert_called_with()
   1.425 +    ...
   1.426 +    >>> MyTest('test_something').test_something()
   1.427 +
   1.428 +You can stack up multiple patch decorators using this pattern:
   1.429 +
   1.430 +.. doctest::
   1.431 +
   1.432 +    >>> class MyTest(unittest2.TestCase):
   1.433 +    ...     @patch('package.module.ClassName1')
   1.434 +    ...     @patch('package.module.ClassName2')
   1.435 +    ...     def test_something(self, MockClass2, MockClass1):
   1.436 +    ...         self.assertTrue(package.module.ClassName1 is MockClass1)
   1.437 +    ...         self.assertTrue(package.module.ClassName2 is MockClass2)
   1.438 +    ...
   1.439 +    >>> MyTest('test_something').test_something()
   1.440 +
   1.441 +When you nest patch decorators the mocks are passed in to the decorated
   1.442 +function in the same order they applied (the normal *python* order that
   1.443 +decorators are applied). This means from the bottom up, so in the example
   1.444 +above the mock for `test_module.ClassName2` is passed in first.
   1.445 +
   1.446 +There is also :func:`patch.dict` for setting values in a dictionary just
   1.447 +during a scope and restoring the dictionary to its original state when the test
   1.448 +ends:
   1.449 +
   1.450 +.. doctest::
   1.451 +
   1.452 +   >>> foo = {'key': 'value'}
   1.453 +   >>> original = foo.copy()
   1.454 +   >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
   1.455 +   ...     assert foo == {'newkey': 'newvalue'}
   1.456 +   ...
   1.457 +   >>> assert foo == original
   1.458 +
   1.459 +`patch`, `patch.object` and `patch.dict` can all be used as context managers.
   1.460 +
   1.461 +Where you use `patch` to create a mock for you, you can get a reference to the
   1.462 +mock using the "as" form of the with statement:
   1.463 +
   1.464 +.. doctest::
   1.465 +
   1.466 +    >>> class ProductionClass(object):
   1.467 +    ...     def method(self):
   1.468 +    ...         pass
   1.469 +    ...
   1.470 +    >>> with patch.object(ProductionClass, 'method') as mock_method:
   1.471 +    ...     mock_method.return_value = None
   1.472 +    ...     real = ProductionClass()
   1.473 +    ...     real.method(1, 2, 3)
   1.474 +    ...
   1.475 +    >>> mock_method.assert_called_with(1, 2, 3)
   1.476 +
   1.477 +
   1.478 +As an alternative `patch`, `patch.object` and `patch.dict` can be used as
   1.479 +class decorators. When used in this way it is the same as applying the
   1.480 +decorator indvidually to every method whose name starts with "test".
   1.481 +
   1.482 +For some more advanced examples, see the :ref:`further-examples` page.

mercurial