python/mock-1.0.0/docs/patch.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/patch.txt	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,636 @@
     1.4 +==================
     1.5 + Patch Decorators
     1.6 +==================
     1.7 +
     1.8 +
     1.9 +.. currentmodule:: mock
    1.10 +
    1.11 +.. testsetup::
    1.12 +
    1.13 +    class SomeClass(object):
    1.14 +        static_method = None
    1.15 +        class_method = None
    1.16 +        attribute = None
    1.17 +
    1.18 +    sys.modules['package'] = package = Mock(name='package')
    1.19 +    sys.modules['package.module'] = package.module
    1.20 +
    1.21 +    class TestCase(unittest2.TestCase):
    1.22 +        def run(self):
    1.23 +            result = unittest2.TestResult()
    1.24 +            super(unittest2.TestCase, self).run(result)
    1.25 +            assert result.wasSuccessful()
    1.26 +
    1.27 +.. testcleanup::
    1.28 +
    1.29 +    patch.TEST_PREFIX = 'test'
    1.30 +
    1.31 +
    1.32 +The patch decorators are used for patching objects only within the scope of
    1.33 +the function they decorate. They automatically handle the unpatching for you,
    1.34 +even if exceptions are raised. All of these functions can also be used in with
    1.35 +statements or as class decorators.
    1.36 +
    1.37 +
    1.38 +patch
    1.39 +=====
    1.40 +
    1.41 +.. note::
    1.42 +
    1.43 +    `patch` is straightforward to use. The key is to do the patching in the
    1.44 +    right namespace. See the section `where to patch`_.
    1.45 +
    1.46 +.. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
    1.47 +
    1.48 +    `patch` acts as a function decorator, class decorator or a context
    1.49 +    manager. Inside the body of the function or with statement, the `target`
    1.50 +    is patched with a `new` object. When the function/with statement exits
    1.51 +    the patch is undone.
    1.52 +
    1.53 +    If `new` is omitted, then the target is replaced with a
    1.54 +    :class:`MagicMock`. If `patch` is used as a decorator and `new` is
    1.55 +    omitted, the created mock is passed in as an extra argument to the
    1.56 +    decorated function. If `patch` is used as a context manager the created
    1.57 +    mock is returned by the context manager.
    1.58 +
    1.59 +    `target` should be a string in the form `'package.module.ClassName'`. The
    1.60 +    `target` is imported and the specified object replaced with the `new`
    1.61 +    object, so the `target` must be importable from the environment you are
    1.62 +    calling `patch` from. The target is imported when the decorated function
    1.63 +    is executed, not at decoration time.
    1.64 +
    1.65 +    The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
    1.66 +    if patch is creating one for you.
    1.67 +
    1.68 +    In addition you can pass `spec=True` or `spec_set=True`, which causes
    1.69 +    patch to pass in the object being mocked as the spec/spec_set object.
    1.70 +
    1.71 +    `new_callable` allows you to specify a different class, or callable object,
    1.72 +    that will be called to create the `new` object. By default `MagicMock` is
    1.73 +    used.
    1.74 +
    1.75 +    A more powerful form of `spec` is `autospec`. If you set `autospec=True`
    1.76 +    then the mock with be created with a spec from the object being replaced.
    1.77 +    All attributes of the mock will also have the spec of the corresponding
    1.78 +    attribute of the object being replaced. Methods and functions being mocked
    1.79 +    will have their arguments checked and will raise a `TypeError` if they are
    1.80 +    called with the wrong signature. For mocks
    1.81 +    replacing a class, their return value (the 'instance') will have the same
    1.82 +    spec as the class. See the :func:`create_autospec` function and
    1.83 +    :ref:`auto-speccing`.
    1.84 +
    1.85 +    Instead of `autospec=True` you can pass `autospec=some_object` to use an
    1.86 +    arbitrary object as the spec instead of the one being replaced.
    1.87 +
    1.88 +    By default `patch` will fail to replace attributes that don't exist. If
    1.89 +    you pass in `create=True`, and the attribute doesn't exist, patch will
    1.90 +    create the attribute for you when the patched function is called, and
    1.91 +    delete it again afterwards. This is useful for writing tests against
    1.92 +    attributes that your production code creates at runtime. It is off by by
    1.93 +    default because it can be dangerous. With it switched on you can write
    1.94 +    passing tests against APIs that don't actually exist!
    1.95 +
    1.96 +    Patch can be used as a `TestCase` class decorator. It works by
    1.97 +    decorating each test method in the class. This reduces the boilerplate
    1.98 +    code when your test methods share a common patchings set. `patch` finds
    1.99 +    tests by looking for method names that start with `patch.TEST_PREFIX`.
   1.100 +    By default this is `test`, which matches the way `unittest` finds tests.
   1.101 +    You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
   1.102 +
   1.103 +    Patch can be used as a context manager, with the with statement. Here the
   1.104 +    patching applies to the indented block after the with statement. If you
   1.105 +    use "as" then the patched object will be bound to the name after the
   1.106 +    "as"; very useful if `patch` is creating a mock object for you.
   1.107 +
   1.108 +    `patch` takes arbitrary keyword arguments. These will be passed to
   1.109 +    the `Mock` (or `new_callable`) on construction.
   1.110 +
   1.111 +    `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
   1.112 +    available for alternate use-cases.
   1.113 +
   1.114 +`patch` as function decorator, creating the mock for you and passing it into
   1.115 +the decorated function:
   1.116 +
   1.117 +.. doctest::
   1.118 +
   1.119 +    >>> @patch('__main__.SomeClass')
   1.120 +    ... def function(normal_argument, mock_class):
   1.121 +    ...     print mock_class is SomeClass
   1.122 +    ...
   1.123 +    >>> function(None)
   1.124 +    True
   1.125 +
   1.126 +
   1.127 +Patching a class replaces the class with a `MagicMock` *instance*. If the
   1.128 +class is instantiated in the code under test then it will be the
   1.129 +:attr:`~Mock.return_value` of the mock that will be used.
   1.130 +
   1.131 +If the class is instantiated multiple times you could use
   1.132 +:attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
   1.133 +can set the `return_value` to be anything you want.
   1.134 +
   1.135 +To configure return values on methods of *instances* on the patched class
   1.136 +you must do this on the `return_value`. For example:
   1.137 +
   1.138 +.. doctest::
   1.139 +
   1.140 +    >>> class Class(object):
   1.141 +    ...     def method(self):
   1.142 +    ...         pass
   1.143 +    ...
   1.144 +    >>> with patch('__main__.Class') as MockClass:
   1.145 +    ...     instance = MockClass.return_value
   1.146 +    ...     instance.method.return_value = 'foo'
   1.147 +    ...     assert Class() is instance
   1.148 +    ...     assert Class().method() == 'foo'
   1.149 +    ...
   1.150 +
   1.151 +If you use `spec` or `spec_set` and `patch` is replacing a *class*, then the
   1.152 +return value of the created mock will have the same spec.
   1.153 +
   1.154 +.. doctest::
   1.155 +
   1.156 +    >>> Original = Class
   1.157 +    >>> patcher = patch('__main__.Class', spec=True)
   1.158 +    >>> MockClass = patcher.start()
   1.159 +    >>> instance = MockClass()
   1.160 +    >>> assert isinstance(instance, Original)
   1.161 +    >>> patcher.stop()
   1.162 +
   1.163 +The `new_callable` argument is useful where you want to use an alternative
   1.164 +class to the default :class:`MagicMock` for the created mock. For example, if
   1.165 +you wanted a :class:`NonCallableMock` to be used:
   1.166 +
   1.167 +.. doctest::
   1.168 +
   1.169 +    >>> thing = object()
   1.170 +    >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
   1.171 +    ...     assert thing is mock_thing
   1.172 +    ...     thing()
   1.173 +    ...
   1.174 +    Traceback (most recent call last):
   1.175 +      ...
   1.176 +    TypeError: 'NonCallableMock' object is not callable
   1.177 +
   1.178 +Another use case might be to replace an object with a `StringIO` instance:
   1.179 +
   1.180 +.. doctest::
   1.181 +
   1.182 +    >>> from StringIO import StringIO
   1.183 +    >>> def foo():
   1.184 +    ...     print 'Something'
   1.185 +    ...
   1.186 +    >>> @patch('sys.stdout', new_callable=StringIO)
   1.187 +    ... def test(mock_stdout):
   1.188 +    ...     foo()
   1.189 +    ...     assert mock_stdout.getvalue() == 'Something\n'
   1.190 +    ...
   1.191 +    >>> test()
   1.192 +
   1.193 +When `patch` is creating a mock for you, it is common that the first thing
   1.194 +you need to do is to configure the mock. Some of that configuration can be done
   1.195 +in the call to patch. Any arbitrary keywords you pass into the call will be
   1.196 +used to set attributes on the created mock:
   1.197 +
   1.198 +.. doctest::
   1.199 +
   1.200 +    >>> patcher = patch('__main__.thing', first='one', second='two')
   1.201 +    >>> mock_thing = patcher.start()
   1.202 +    >>> mock_thing.first
   1.203 +    'one'
   1.204 +    >>> mock_thing.second
   1.205 +    'two'
   1.206 +
   1.207 +As well as attributes on the created mock attributes, like the
   1.208 +:attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
   1.209 +also be configured. These aren't syntactically valid to pass in directly as
   1.210 +keyword arguments, but a dictionary with these as keys can still be expanded
   1.211 +into a `patch` call using `**`:
   1.212 +
   1.213 +.. doctest::
   1.214 +
   1.215 +    >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
   1.216 +    >>> patcher = patch('__main__.thing', **config)
   1.217 +    >>> mock_thing = patcher.start()
   1.218 +    >>> mock_thing.method()
   1.219 +    3
   1.220 +    >>> mock_thing.other()
   1.221 +    Traceback (most recent call last):
   1.222 +      ...
   1.223 +    KeyError
   1.224 +
   1.225 +
   1.226 +patch.object
   1.227 +============
   1.228 +
   1.229 +.. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
   1.230 +
   1.231 +    patch the named member (`attribute`) on an object (`target`) with a mock
   1.232 +    object.
   1.233 +
   1.234 +    `patch.object` can be used as a decorator, class decorator or a context
   1.235 +    manager. Arguments `new`, `spec`, `create`, `spec_set`, `autospec` and
   1.236 +    `new_callable` have the same meaning as for `patch`. Like `patch`,
   1.237 +    `patch.object` takes arbitrary keyword arguments for configuring the mock
   1.238 +    object it creates.
   1.239 +
   1.240 +    When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
   1.241 +    for choosing which methods to wrap.
   1.242 +
   1.243 +You can either call `patch.object` with three arguments or two arguments. The
   1.244 +three argument form takes the object to be patched, the attribute name and the
   1.245 +object to replace the attribute with.
   1.246 +
   1.247 +When calling with the two argument form you omit the replacement object, and a
   1.248 +mock is created for you and passed in as an extra argument to the decorated
   1.249 +function:
   1.250 +
   1.251 +.. doctest::
   1.252 +
   1.253 +    >>> @patch.object(SomeClass, 'class_method')
   1.254 +    ... def test(mock_method):
   1.255 +    ...     SomeClass.class_method(3)
   1.256 +    ...     mock_method.assert_called_with(3)
   1.257 +    ...
   1.258 +    >>> test()
   1.259 +
   1.260 +`spec`, `create` and the other arguments to `patch.object` have the same
   1.261 +meaning as they do for `patch`.
   1.262 +
   1.263 +
   1.264 +patch.dict
   1.265 +==========
   1.266 +
   1.267 +.. function:: patch.dict(in_dict, values=(), clear=False, **kwargs)
   1.268 +
   1.269 +    Patch a dictionary, or dictionary like object, and restore the dictionary
   1.270 +    to its original state after the test.
   1.271 +
   1.272 +    `in_dict` can be a dictionary or a mapping like container. If it is a
   1.273 +    mapping then it must at least support getting, setting and deleting items
   1.274 +    plus iterating over keys.
   1.275 +
   1.276 +    `in_dict` can also be a string specifying the name of the dictionary, which
   1.277 +    will then be fetched by importing it.
   1.278 +
   1.279 +    `values` can be a dictionary of values to set in the dictionary. `values`
   1.280 +    can also be an iterable of `(key, value)` pairs.
   1.281 +
   1.282 +    If `clear` is True then the dictionary will be cleared before the new
   1.283 +    values are set.
   1.284 +
   1.285 +    `patch.dict` can also be called with arbitrary keyword arguments to set
   1.286 +    values in the dictionary.
   1.287 +
   1.288 +    `patch.dict` can be used as a context manager, decorator or class
   1.289 +    decorator. When used as a class decorator `patch.dict` honours
   1.290 +    `patch.TEST_PREFIX` for choosing which methods to wrap.
   1.291 +
   1.292 +`patch.dict` can be used to add members to a dictionary, or simply let a test
   1.293 +change a dictionary, and ensure the dictionary is restored when the test
   1.294 +ends.
   1.295 +
   1.296 +.. doctest::
   1.297 +
   1.298 +    >>> from mock import patch
   1.299 +    >>> foo = {}
   1.300 +    >>> with patch.dict(foo, {'newkey': 'newvalue'}):
   1.301 +    ...     assert foo == {'newkey': 'newvalue'}
   1.302 +    ...
   1.303 +    >>> assert foo == {}
   1.304 +
   1.305 +    >>> import os
   1.306 +    >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
   1.307 +    ...     print os.environ['newkey']
   1.308 +    ...
   1.309 +    newvalue
   1.310 +    >>> assert 'newkey' not in os.environ
   1.311 +
   1.312 +Keywords can be used in the `patch.dict` call to set values in the dictionary:
   1.313 +
   1.314 +.. doctest::
   1.315 +
   1.316 +    >>> mymodule = MagicMock()
   1.317 +    >>> mymodule.function.return_value = 'fish'
   1.318 +    >>> with patch.dict('sys.modules', mymodule=mymodule):
   1.319 +    ...     import mymodule
   1.320 +    ...     mymodule.function('some', 'args')
   1.321 +    ...
   1.322 +    'fish'
   1.323 +
   1.324 +`patch.dict` can be used with dictionary like objects that aren't actually
   1.325 +dictionaries. At the very minimum they must support item getting, setting,
   1.326 +deleting and either iteration or membership test. This corresponds to the
   1.327 +magic methods `__getitem__`, `__setitem__`, `__delitem__` and either
   1.328 +`__iter__` or `__contains__`.
   1.329 +
   1.330 +.. doctest::
   1.331 +
   1.332 +    >>> class Container(object):
   1.333 +    ...     def __init__(self):
   1.334 +    ...         self.values = {}
   1.335 +    ...     def __getitem__(self, name):
   1.336 +    ...         return self.values[name]
   1.337 +    ...     def __setitem__(self, name, value):
   1.338 +    ...         self.values[name] = value
   1.339 +    ...     def __delitem__(self, name):
   1.340 +    ...         del self.values[name]
   1.341 +    ...     def __iter__(self):
   1.342 +    ...         return iter(self.values)
   1.343 +    ...
   1.344 +    >>> thing = Container()
   1.345 +    >>> thing['one'] = 1
   1.346 +    >>> with patch.dict(thing, one=2, two=3):
   1.347 +    ...     assert thing['one'] == 2
   1.348 +    ...     assert thing['two'] == 3
   1.349 +    ...
   1.350 +    >>> assert thing['one'] == 1
   1.351 +    >>> assert list(thing) == ['one']
   1.352 +
   1.353 +
   1.354 +patch.multiple
   1.355 +==============
   1.356 +
   1.357 +.. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
   1.358 +
   1.359 +    Perform multiple patches in a single call. It takes the object to be
   1.360 +    patched (either as an object or a string to fetch the object by importing)
   1.361 +    and keyword arguments for the patches::
   1.362 +
   1.363 +        with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
   1.364 +            ...
   1.365 +
   1.366 +    Use :data:`DEFAULT` as the value if you want `patch.multiple` to create
   1.367 +    mocks for you. In this case the created mocks are passed into a decorated
   1.368 +    function by keyword, and a dictionary is returned when `patch.multiple` is
   1.369 +    used as a context manager.
   1.370 +
   1.371 +    `patch.multiple` can be used as a decorator, class decorator or a context
   1.372 +    manager. The arguments `spec`, `spec_set`, `create`, `autospec` and
   1.373 +    `new_callable` have the same meaning as for `patch`. These arguments will
   1.374 +    be applied to *all* patches done by `patch.multiple`.
   1.375 +
   1.376 +    When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
   1.377 +    for choosing which methods to wrap.
   1.378 +
   1.379 +If you want `patch.multiple` to create mocks for you, then you can use
   1.380 +:data:`DEFAULT` as the value. If you use `patch.multiple` as a decorator
   1.381 +then the created mocks are passed into the decorated function by keyword.
   1.382 +
   1.383 +.. doctest::
   1.384 +
   1.385 +    >>> thing = object()
   1.386 +    >>> other = object()
   1.387 +
   1.388 +    >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
   1.389 +    ... def test_function(thing, other):
   1.390 +    ...     assert isinstance(thing, MagicMock)
   1.391 +    ...     assert isinstance(other, MagicMock)
   1.392 +    ...
   1.393 +    >>> test_function()
   1.394 +
   1.395 +`patch.multiple` can be nested with other `patch` decorators, but put arguments
   1.396 +passed by keyword *after* any of the standard arguments created by `patch`:
   1.397 +
   1.398 +.. doctest::
   1.399 +
   1.400 +    >>> @patch('sys.exit')
   1.401 +    ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
   1.402 +    ... def test_function(mock_exit, other, thing):
   1.403 +    ...     assert 'other' in repr(other)
   1.404 +    ...     assert 'thing' in repr(thing)
   1.405 +    ...     assert 'exit' in repr(mock_exit)
   1.406 +    ...
   1.407 +    >>> test_function()
   1.408 +
   1.409 +If `patch.multiple` is used as a context manager, the value returned by the
   1.410 +context manger is a dictionary where created mocks are keyed by name:
   1.411 +
   1.412 +.. doctest::
   1.413 +
   1.414 +    >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
   1.415 +    ...     assert 'other' in repr(values['other'])
   1.416 +    ...     assert 'thing' in repr(values['thing'])
   1.417 +    ...     assert values['thing'] is thing
   1.418 +    ...     assert values['other'] is other
   1.419 +    ...
   1.420 +
   1.421 +
   1.422 +.. _start-and-stop:
   1.423 +
   1.424 +patch methods: start and stop
   1.425 +=============================
   1.426 +
   1.427 +All the patchers have `start` and `stop` methods. These make it simpler to do
   1.428 +patching in `setUp` methods or where you want to do multiple patches without
   1.429 +nesting decorators or with statements.
   1.430 +
   1.431 +To use them call `patch`, `patch.object` or `patch.dict` as normal and keep a
   1.432 +reference to the returned `patcher` object. You can then call `start` to put
   1.433 +the patch in place and `stop` to undo it.
   1.434 +
   1.435 +If you are using `patch` to create a mock for you then it will be returned by
   1.436 +the call to `patcher.start`.
   1.437 +
   1.438 +.. doctest::
   1.439 +
   1.440 +    >>> patcher = patch('package.module.ClassName')
   1.441 +    >>> from package import module
   1.442 +    >>> original = module.ClassName
   1.443 +    >>> new_mock = patcher.start()
   1.444 +    >>> assert module.ClassName is not original
   1.445 +    >>> assert module.ClassName is new_mock
   1.446 +    >>> patcher.stop()
   1.447 +    >>> assert module.ClassName is original
   1.448 +    >>> assert module.ClassName is not new_mock
   1.449 +
   1.450 +
   1.451 +A typical use case for this might be for doing multiple patches in the `setUp`
   1.452 +method of a `TestCase`:
   1.453 +
   1.454 +.. doctest::
   1.455 +
   1.456 +    >>> class MyTest(TestCase):
   1.457 +    ...     def setUp(self):
   1.458 +    ...         self.patcher1 = patch('package.module.Class1')
   1.459 +    ...         self.patcher2 = patch('package.module.Class2')
   1.460 +    ...         self.MockClass1 = self.patcher1.start()
   1.461 +    ...         self.MockClass2 = self.patcher2.start()
   1.462 +    ...
   1.463 +    ...     def tearDown(self):
   1.464 +    ...         self.patcher1.stop()
   1.465 +    ...         self.patcher2.stop()
   1.466 +    ...
   1.467 +    ...     def test_something(self):
   1.468 +    ...         assert package.module.Class1 is self.MockClass1
   1.469 +    ...         assert package.module.Class2 is self.MockClass2
   1.470 +    ...
   1.471 +    >>> MyTest('test_something').run()
   1.472 +
   1.473 +.. caution::
   1.474 +
   1.475 +    If you use this technique you must ensure that the patching is "undone" by
   1.476 +    calling `stop`. This can be fiddlier than you might think, because if an
   1.477 +    exception is raised in the setUp then tearDown is not called. `unittest2
   1.478 +    <http://pypi.python.org/pypi/unittest2>`_ cleanup functions make this
   1.479 +    easier.
   1.480 +
   1.481 +    .. doctest::
   1.482 +
   1.483 +        >>> class MyTest(TestCase):
   1.484 +        ...     def setUp(self):
   1.485 +        ...         patcher = patch('package.module.Class')
   1.486 +        ...         self.MockClass = patcher.start()
   1.487 +        ...         self.addCleanup(patcher.stop)
   1.488 +        ...
   1.489 +        ...     def test_something(self):
   1.490 +        ...         assert package.module.Class is self.MockClass
   1.491 +        ...
   1.492 +        >>> MyTest('test_something').run()
   1.493 +
   1.494 +    As an added bonus you no longer need to keep a reference to the `patcher`
   1.495 +    object.
   1.496 +
   1.497 +It is also possible to stop all patches which have been started by using
   1.498 +`patch.stopall`.
   1.499 +
   1.500 +.. function:: patch.stopall
   1.501 +
   1.502 +    Stop all active patches. Only stops patches started with `start`.
   1.503 +
   1.504 +
   1.505 +TEST_PREFIX
   1.506 +===========
   1.507 +
   1.508 +All of the patchers can be used as class decorators. When used in this way
   1.509 +they wrap every test method on the class. The patchers recognise methods that
   1.510 +start with `test` as being test methods. This is the same way that the
   1.511 +`unittest.TestLoader` finds test methods by default.
   1.512 +
   1.513 +It is possible that you want to use a different prefix for your tests. You can
   1.514 +inform the patchers of the different prefix by setting `patch.TEST_PREFIX`:
   1.515 +
   1.516 +.. doctest::
   1.517 +
   1.518 +    >>> patch.TEST_PREFIX = 'foo'
   1.519 +    >>> value = 3
   1.520 +    >>>
   1.521 +    >>> @patch('__main__.value', 'not three')
   1.522 +    ... class Thing(object):
   1.523 +    ...     def foo_one(self):
   1.524 +    ...         print value
   1.525 +    ...     def foo_two(self):
   1.526 +    ...         print value
   1.527 +    ...
   1.528 +    >>>
   1.529 +    >>> Thing().foo_one()
   1.530 +    not three
   1.531 +    >>> Thing().foo_two()
   1.532 +    not three
   1.533 +    >>> value
   1.534 +    3
   1.535 +
   1.536 +
   1.537 +Nesting Patch Decorators
   1.538 +========================
   1.539 +
   1.540 +If you want to perform multiple patches then you can simply stack up the
   1.541 +decorators.
   1.542 +
   1.543 +You can stack up multiple patch decorators using this pattern:
   1.544 +
   1.545 +.. doctest::
   1.546 +
   1.547 +    >>> @patch.object(SomeClass, 'class_method')
   1.548 +    ... @patch.object(SomeClass, 'static_method')
   1.549 +    ... def test(mock1, mock2):
   1.550 +    ...     assert SomeClass.static_method is mock1
   1.551 +    ...     assert SomeClass.class_method is mock2
   1.552 +    ...     SomeClass.static_method('foo')
   1.553 +    ...     SomeClass.class_method('bar')
   1.554 +    ...     return mock1, mock2
   1.555 +    ...
   1.556 +    >>> mock1, mock2 = test()
   1.557 +    >>> mock1.assert_called_once_with('foo')
   1.558 +    >>> mock2.assert_called_once_with('bar')
   1.559 +
   1.560 +
   1.561 +Note that the decorators are applied from the bottom upwards. This is the
   1.562 +standard way that Python applies decorators. The order of the created mocks
   1.563 +passed into your test function matches this order.
   1.564 +
   1.565 +Like all context-managers patches can be nested using contextlib's nested
   1.566 +function; *every* patching will appear in the tuple after "as":
   1.567 +
   1.568 +.. doctest::
   1.569 +
   1.570 +    >>> from contextlib import nested
   1.571 +    >>> with nested(
   1.572 +    ...         patch('package.module.ClassName1'),
   1.573 +    ...         patch('package.module.ClassName2')
   1.574 +    ...     ) as (MockClass1, MockClass2):
   1.575 +    ...     assert package.module.ClassName1 is MockClass1
   1.576 +    ...     assert package.module.ClassName2 is MockClass2
   1.577 +    ...
   1.578 +
   1.579 +
   1.580 +.. _where-to-patch:
   1.581 +
   1.582 +Where to patch
   1.583 +==============
   1.584 +
   1.585 +`patch` works by (temporarily) changing the object that a *name* points to with
   1.586 +another one. There can be many names pointing to any individual object, so
   1.587 +for patching to work you must ensure that you patch the name used by the system
   1.588 +under test.
   1.589 +
   1.590 +The basic principle is that you patch where an object is *looked up*, which
   1.591 +is not necessarily the same place as where it is defined. A couple of
   1.592 +examples will help to clarify this.
   1.593 +
   1.594 +Imagine we have a project that we want to test with the following structure::
   1.595 +
   1.596 +    a.py
   1.597 +        -> Defines SomeClass
   1.598 +
   1.599 +    b.py
   1.600 +        -> from a import SomeClass
   1.601 +        -> some_function instantiates SomeClass
   1.602 +
   1.603 +Now we want to test `some_function` but we want to mock out `SomeClass` using
   1.604 +`patch`. The problem is that when we import module b, which we will have to
   1.605 +do then it imports `SomeClass` from module a. If we use `patch` to mock out
   1.606 +`a.SomeClass` then it will have no effect on our test; module b already has a
   1.607 +reference to the *real* `SomeClass` and it looks like our patching had no
   1.608 +effect.
   1.609 +
   1.610 +The key is to patch out `SomeClass` where it is used (or where it is looked up
   1.611 +). In this case `some_function` will actually look up `SomeClass` in module b,
   1.612 +where we have imported it. The patching should look like:
   1.613 +
   1.614 +    `@patch('b.SomeClass')`
   1.615 +
   1.616 +However, consider the alternative scenario where instead of `from a import
   1.617 +SomeClass` module b does `import a` and `some_function` uses `a.SomeClass`. Both
   1.618 +of these import forms are common. In this case the class we want to patch is
   1.619 +being looked up on the a module and so we have to patch `a.SomeClass` instead:
   1.620 +
   1.621 +    `@patch('a.SomeClass')`
   1.622 +
   1.623 +
   1.624 +Patching Descriptors and Proxy Objects
   1.625 +======================================
   1.626 +
   1.627 +Since version 0.6.0 both patch_ and patch.object_ have been able to correctly
   1.628 +patch and restore descriptors: class methods, static methods and properties.
   1.629 +You should patch these on the *class* rather than an instance.
   1.630 +
   1.631 +Since version 0.7.0 patch_ and patch.object_ work correctly with some objects
   1.632 +that proxy attribute access, like the `django setttings object
   1.633 +<http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
   1.634 +
   1.635 +.. note::
   1.636 +
   1.637 +    In django `import settings` and `from django.conf import settings`
   1.638 +    return different objects. If you are using libraries / apps that do both you
   1.639 +    may have to patch both. Grrr...

mercurial