python/mock-1.0.0/html/_sources/patch.txt

Wed, 31 Dec 2014 06:55:50 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:55:50 +0100
changeset 2
7e26c7da4463
permissions
-rw-r--r--

Added tag UPSTREAM_283F7C6 for changeset ca08bd8f51b2

michael@0 1 ==================
michael@0 2 Patch Decorators
michael@0 3 ==================
michael@0 4
michael@0 5
michael@0 6 .. currentmodule:: mock
michael@0 7
michael@0 8 .. testsetup::
michael@0 9
michael@0 10 class SomeClass(object):
michael@0 11 static_method = None
michael@0 12 class_method = None
michael@0 13 attribute = None
michael@0 14
michael@0 15 sys.modules['package'] = package = Mock(name='package')
michael@0 16 sys.modules['package.module'] = package.module
michael@0 17
michael@0 18 class TestCase(unittest2.TestCase):
michael@0 19 def run(self):
michael@0 20 result = unittest2.TestResult()
michael@0 21 super(unittest2.TestCase, self).run(result)
michael@0 22 assert result.wasSuccessful()
michael@0 23
michael@0 24 .. testcleanup::
michael@0 25
michael@0 26 patch.TEST_PREFIX = 'test'
michael@0 27
michael@0 28
michael@0 29 The patch decorators are used for patching objects only within the scope of
michael@0 30 the function they decorate. They automatically handle the unpatching for you,
michael@0 31 even if exceptions are raised. All of these functions can also be used in with
michael@0 32 statements or as class decorators.
michael@0 33
michael@0 34
michael@0 35 patch
michael@0 36 =====
michael@0 37
michael@0 38 .. note::
michael@0 39
michael@0 40 `patch` is straightforward to use. The key is to do the patching in the
michael@0 41 right namespace. See the section `where to patch`_.
michael@0 42
michael@0 43 .. function:: patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
michael@0 44
michael@0 45 `patch` acts as a function decorator, class decorator or a context
michael@0 46 manager. Inside the body of the function or with statement, the `target`
michael@0 47 is patched with a `new` object. When the function/with statement exits
michael@0 48 the patch is undone.
michael@0 49
michael@0 50 If `new` is omitted, then the target is replaced with a
michael@0 51 :class:`MagicMock`. If `patch` is used as a decorator and `new` is
michael@0 52 omitted, the created mock is passed in as an extra argument to the
michael@0 53 decorated function. If `patch` is used as a context manager the created
michael@0 54 mock is returned by the context manager.
michael@0 55
michael@0 56 `target` should be a string in the form `'package.module.ClassName'`. The
michael@0 57 `target` is imported and the specified object replaced with the `new`
michael@0 58 object, so the `target` must be importable from the environment you are
michael@0 59 calling `patch` from. The target is imported when the decorated function
michael@0 60 is executed, not at decoration time.
michael@0 61
michael@0 62 The `spec` and `spec_set` keyword arguments are passed to the `MagicMock`
michael@0 63 if patch is creating one for you.
michael@0 64
michael@0 65 In addition you can pass `spec=True` or `spec_set=True`, which causes
michael@0 66 patch to pass in the object being mocked as the spec/spec_set object.
michael@0 67
michael@0 68 `new_callable` allows you to specify a different class, or callable object,
michael@0 69 that will be called to create the `new` object. By default `MagicMock` is
michael@0 70 used.
michael@0 71
michael@0 72 A more powerful form of `spec` is `autospec`. If you set `autospec=True`
michael@0 73 then the mock with be created with a spec from the object being replaced.
michael@0 74 All attributes of the mock will also have the spec of the corresponding
michael@0 75 attribute of the object being replaced. Methods and functions being mocked
michael@0 76 will have their arguments checked and will raise a `TypeError` if they are
michael@0 77 called with the wrong signature. For mocks
michael@0 78 replacing a class, their return value (the 'instance') will have the same
michael@0 79 spec as the class. See the :func:`create_autospec` function and
michael@0 80 :ref:`auto-speccing`.
michael@0 81
michael@0 82 Instead of `autospec=True` you can pass `autospec=some_object` to use an
michael@0 83 arbitrary object as the spec instead of the one being replaced.
michael@0 84
michael@0 85 By default `patch` will fail to replace attributes that don't exist. If
michael@0 86 you pass in `create=True`, and the attribute doesn't exist, patch will
michael@0 87 create the attribute for you when the patched function is called, and
michael@0 88 delete it again afterwards. This is useful for writing tests against
michael@0 89 attributes that your production code creates at runtime. It is off by by
michael@0 90 default because it can be dangerous. With it switched on you can write
michael@0 91 passing tests against APIs that don't actually exist!
michael@0 92
michael@0 93 Patch can be used as a `TestCase` class decorator. It works by
michael@0 94 decorating each test method in the class. This reduces the boilerplate
michael@0 95 code when your test methods share a common patchings set. `patch` finds
michael@0 96 tests by looking for method names that start with `patch.TEST_PREFIX`.
michael@0 97 By default this is `test`, which matches the way `unittest` finds tests.
michael@0 98 You can specify an alternative prefix by setting `patch.TEST_PREFIX`.
michael@0 99
michael@0 100 Patch can be used as a context manager, with the with statement. Here the
michael@0 101 patching applies to the indented block after the with statement. If you
michael@0 102 use "as" then the patched object will be bound to the name after the
michael@0 103 "as"; very useful if `patch` is creating a mock object for you.
michael@0 104
michael@0 105 `patch` takes arbitrary keyword arguments. These will be passed to
michael@0 106 the `Mock` (or `new_callable`) on construction.
michael@0 107
michael@0 108 `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are
michael@0 109 available for alternate use-cases.
michael@0 110
michael@0 111 `patch` as function decorator, creating the mock for you and passing it into
michael@0 112 the decorated function:
michael@0 113
michael@0 114 .. doctest::
michael@0 115
michael@0 116 >>> @patch('__main__.SomeClass')
michael@0 117 ... def function(normal_argument, mock_class):
michael@0 118 ... print mock_class is SomeClass
michael@0 119 ...
michael@0 120 >>> function(None)
michael@0 121 True
michael@0 122
michael@0 123
michael@0 124 Patching a class replaces the class with a `MagicMock` *instance*. If the
michael@0 125 class is instantiated in the code under test then it will be the
michael@0 126 :attr:`~Mock.return_value` of the mock that will be used.
michael@0 127
michael@0 128 If the class is instantiated multiple times you could use
michael@0 129 :attr:`~Mock.side_effect` to return a new mock each time. Alternatively you
michael@0 130 can set the `return_value` to be anything you want.
michael@0 131
michael@0 132 To configure return values on methods of *instances* on the patched class
michael@0 133 you must do this on the `return_value`. For example:
michael@0 134
michael@0 135 .. doctest::
michael@0 136
michael@0 137 >>> class Class(object):
michael@0 138 ... def method(self):
michael@0 139 ... pass
michael@0 140 ...
michael@0 141 >>> with patch('__main__.Class') as MockClass:
michael@0 142 ... instance = MockClass.return_value
michael@0 143 ... instance.method.return_value = 'foo'
michael@0 144 ... assert Class() is instance
michael@0 145 ... assert Class().method() == 'foo'
michael@0 146 ...
michael@0 147
michael@0 148 If you use `spec` or `spec_set` and `patch` is replacing a *class*, then the
michael@0 149 return value of the created mock will have the same spec.
michael@0 150
michael@0 151 .. doctest::
michael@0 152
michael@0 153 >>> Original = Class
michael@0 154 >>> patcher = patch('__main__.Class', spec=True)
michael@0 155 >>> MockClass = patcher.start()
michael@0 156 >>> instance = MockClass()
michael@0 157 >>> assert isinstance(instance, Original)
michael@0 158 >>> patcher.stop()
michael@0 159
michael@0 160 The `new_callable` argument is useful where you want to use an alternative
michael@0 161 class to the default :class:`MagicMock` for the created mock. For example, if
michael@0 162 you wanted a :class:`NonCallableMock` to be used:
michael@0 163
michael@0 164 .. doctest::
michael@0 165
michael@0 166 >>> thing = object()
michael@0 167 >>> with patch('__main__.thing', new_callable=NonCallableMock) as mock_thing:
michael@0 168 ... assert thing is mock_thing
michael@0 169 ... thing()
michael@0 170 ...
michael@0 171 Traceback (most recent call last):
michael@0 172 ...
michael@0 173 TypeError: 'NonCallableMock' object is not callable
michael@0 174
michael@0 175 Another use case might be to replace an object with a `StringIO` instance:
michael@0 176
michael@0 177 .. doctest::
michael@0 178
michael@0 179 >>> from StringIO import StringIO
michael@0 180 >>> def foo():
michael@0 181 ... print 'Something'
michael@0 182 ...
michael@0 183 >>> @patch('sys.stdout', new_callable=StringIO)
michael@0 184 ... def test(mock_stdout):
michael@0 185 ... foo()
michael@0 186 ... assert mock_stdout.getvalue() == 'Something\n'
michael@0 187 ...
michael@0 188 >>> test()
michael@0 189
michael@0 190 When `patch` is creating a mock for you, it is common that the first thing
michael@0 191 you need to do is to configure the mock. Some of that configuration can be done
michael@0 192 in the call to patch. Any arbitrary keywords you pass into the call will be
michael@0 193 used to set attributes on the created mock:
michael@0 194
michael@0 195 .. doctest::
michael@0 196
michael@0 197 >>> patcher = patch('__main__.thing', first='one', second='two')
michael@0 198 >>> mock_thing = patcher.start()
michael@0 199 >>> mock_thing.first
michael@0 200 'one'
michael@0 201 >>> mock_thing.second
michael@0 202 'two'
michael@0 203
michael@0 204 As well as attributes on the created mock attributes, like the
michael@0 205 :attr:`~Mock.return_value` and :attr:`~Mock.side_effect`, of child mocks can
michael@0 206 also be configured. These aren't syntactically valid to pass in directly as
michael@0 207 keyword arguments, but a dictionary with these as keys can still be expanded
michael@0 208 into a `patch` call using `**`:
michael@0 209
michael@0 210 .. doctest::
michael@0 211
michael@0 212 >>> config = {'method.return_value': 3, 'other.side_effect': KeyError}
michael@0 213 >>> patcher = patch('__main__.thing', **config)
michael@0 214 >>> mock_thing = patcher.start()
michael@0 215 >>> mock_thing.method()
michael@0 216 3
michael@0 217 >>> mock_thing.other()
michael@0 218 Traceback (most recent call last):
michael@0 219 ...
michael@0 220 KeyError
michael@0 221
michael@0 222
michael@0 223 patch.object
michael@0 224 ============
michael@0 225
michael@0 226 .. function:: patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
michael@0 227
michael@0 228 patch the named member (`attribute`) on an object (`target`) with a mock
michael@0 229 object.
michael@0 230
michael@0 231 `patch.object` can be used as a decorator, class decorator or a context
michael@0 232 manager. Arguments `new`, `spec`, `create`, `spec_set`, `autospec` and
michael@0 233 `new_callable` have the same meaning as for `patch`. Like `patch`,
michael@0 234 `patch.object` takes arbitrary keyword arguments for configuring the mock
michael@0 235 object it creates.
michael@0 236
michael@0 237 When used as a class decorator `patch.object` honours `patch.TEST_PREFIX`
michael@0 238 for choosing which methods to wrap.
michael@0 239
michael@0 240 You can either call `patch.object` with three arguments or two arguments. The
michael@0 241 three argument form takes the object to be patched, the attribute name and the
michael@0 242 object to replace the attribute with.
michael@0 243
michael@0 244 When calling with the two argument form you omit the replacement object, and a
michael@0 245 mock is created for you and passed in as an extra argument to the decorated
michael@0 246 function:
michael@0 247
michael@0 248 .. doctest::
michael@0 249
michael@0 250 >>> @patch.object(SomeClass, 'class_method')
michael@0 251 ... def test(mock_method):
michael@0 252 ... SomeClass.class_method(3)
michael@0 253 ... mock_method.assert_called_with(3)
michael@0 254 ...
michael@0 255 >>> test()
michael@0 256
michael@0 257 `spec`, `create` and the other arguments to `patch.object` have the same
michael@0 258 meaning as they do for `patch`.
michael@0 259
michael@0 260
michael@0 261 patch.dict
michael@0 262 ==========
michael@0 263
michael@0 264 .. function:: patch.dict(in_dict, values=(), clear=False, **kwargs)
michael@0 265
michael@0 266 Patch a dictionary, or dictionary like object, and restore the dictionary
michael@0 267 to its original state after the test.
michael@0 268
michael@0 269 `in_dict` can be a dictionary or a mapping like container. If it is a
michael@0 270 mapping then it must at least support getting, setting and deleting items
michael@0 271 plus iterating over keys.
michael@0 272
michael@0 273 `in_dict` can also be a string specifying the name of the dictionary, which
michael@0 274 will then be fetched by importing it.
michael@0 275
michael@0 276 `values` can be a dictionary of values to set in the dictionary. `values`
michael@0 277 can also be an iterable of `(key, value)` pairs.
michael@0 278
michael@0 279 If `clear` is True then the dictionary will be cleared before the new
michael@0 280 values are set.
michael@0 281
michael@0 282 `patch.dict` can also be called with arbitrary keyword arguments to set
michael@0 283 values in the dictionary.
michael@0 284
michael@0 285 `patch.dict` can be used as a context manager, decorator or class
michael@0 286 decorator. When used as a class decorator `patch.dict` honours
michael@0 287 `patch.TEST_PREFIX` for choosing which methods to wrap.
michael@0 288
michael@0 289 `patch.dict` can be used to add members to a dictionary, or simply let a test
michael@0 290 change a dictionary, and ensure the dictionary is restored when the test
michael@0 291 ends.
michael@0 292
michael@0 293 .. doctest::
michael@0 294
michael@0 295 >>> from mock import patch
michael@0 296 >>> foo = {}
michael@0 297 >>> with patch.dict(foo, {'newkey': 'newvalue'}):
michael@0 298 ... assert foo == {'newkey': 'newvalue'}
michael@0 299 ...
michael@0 300 >>> assert foo == {}
michael@0 301
michael@0 302 >>> import os
michael@0 303 >>> with patch.dict('os.environ', {'newkey': 'newvalue'}):
michael@0 304 ... print os.environ['newkey']
michael@0 305 ...
michael@0 306 newvalue
michael@0 307 >>> assert 'newkey' not in os.environ
michael@0 308
michael@0 309 Keywords can be used in the `patch.dict` call to set values in the dictionary:
michael@0 310
michael@0 311 .. doctest::
michael@0 312
michael@0 313 >>> mymodule = MagicMock()
michael@0 314 >>> mymodule.function.return_value = 'fish'
michael@0 315 >>> with patch.dict('sys.modules', mymodule=mymodule):
michael@0 316 ... import mymodule
michael@0 317 ... mymodule.function('some', 'args')
michael@0 318 ...
michael@0 319 'fish'
michael@0 320
michael@0 321 `patch.dict` can be used with dictionary like objects that aren't actually
michael@0 322 dictionaries. At the very minimum they must support item getting, setting,
michael@0 323 deleting and either iteration or membership test. This corresponds to the
michael@0 324 magic methods `__getitem__`, `__setitem__`, `__delitem__` and either
michael@0 325 `__iter__` or `__contains__`.
michael@0 326
michael@0 327 .. doctest::
michael@0 328
michael@0 329 >>> class Container(object):
michael@0 330 ... def __init__(self):
michael@0 331 ... self.values = {}
michael@0 332 ... def __getitem__(self, name):
michael@0 333 ... return self.values[name]
michael@0 334 ... def __setitem__(self, name, value):
michael@0 335 ... self.values[name] = value
michael@0 336 ... def __delitem__(self, name):
michael@0 337 ... del self.values[name]
michael@0 338 ... def __iter__(self):
michael@0 339 ... return iter(self.values)
michael@0 340 ...
michael@0 341 >>> thing = Container()
michael@0 342 >>> thing['one'] = 1
michael@0 343 >>> with patch.dict(thing, one=2, two=3):
michael@0 344 ... assert thing['one'] == 2
michael@0 345 ... assert thing['two'] == 3
michael@0 346 ...
michael@0 347 >>> assert thing['one'] == 1
michael@0 348 >>> assert list(thing) == ['one']
michael@0 349
michael@0 350
michael@0 351 patch.multiple
michael@0 352 ==============
michael@0 353
michael@0 354 .. function:: patch.multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
michael@0 355
michael@0 356 Perform multiple patches in a single call. It takes the object to be
michael@0 357 patched (either as an object or a string to fetch the object by importing)
michael@0 358 and keyword arguments for the patches::
michael@0 359
michael@0 360 with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'):
michael@0 361 ...
michael@0 362
michael@0 363 Use :data:`DEFAULT` as the value if you want `patch.multiple` to create
michael@0 364 mocks for you. In this case the created mocks are passed into a decorated
michael@0 365 function by keyword, and a dictionary is returned when `patch.multiple` is
michael@0 366 used as a context manager.
michael@0 367
michael@0 368 `patch.multiple` can be used as a decorator, class decorator or a context
michael@0 369 manager. The arguments `spec`, `spec_set`, `create`, `autospec` and
michael@0 370 `new_callable` have the same meaning as for `patch`. These arguments will
michael@0 371 be applied to *all* patches done by `patch.multiple`.
michael@0 372
michael@0 373 When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX`
michael@0 374 for choosing which methods to wrap.
michael@0 375
michael@0 376 If you want `patch.multiple` to create mocks for you, then you can use
michael@0 377 :data:`DEFAULT` as the value. If you use `patch.multiple` as a decorator
michael@0 378 then the created mocks are passed into the decorated function by keyword.
michael@0 379
michael@0 380 .. doctest::
michael@0 381
michael@0 382 >>> thing = object()
michael@0 383 >>> other = object()
michael@0 384
michael@0 385 >>> @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
michael@0 386 ... def test_function(thing, other):
michael@0 387 ... assert isinstance(thing, MagicMock)
michael@0 388 ... assert isinstance(other, MagicMock)
michael@0 389 ...
michael@0 390 >>> test_function()
michael@0 391
michael@0 392 `patch.multiple` can be nested with other `patch` decorators, but put arguments
michael@0 393 passed by keyword *after* any of the standard arguments created by `patch`:
michael@0 394
michael@0 395 .. doctest::
michael@0 396
michael@0 397 >>> @patch('sys.exit')
michael@0 398 ... @patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
michael@0 399 ... def test_function(mock_exit, other, thing):
michael@0 400 ... assert 'other' in repr(other)
michael@0 401 ... assert 'thing' in repr(thing)
michael@0 402 ... assert 'exit' in repr(mock_exit)
michael@0 403 ...
michael@0 404 >>> test_function()
michael@0 405
michael@0 406 If `patch.multiple` is used as a context manager, the value returned by the
michael@0 407 context manger is a dictionary where created mocks are keyed by name:
michael@0 408
michael@0 409 .. doctest::
michael@0 410
michael@0 411 >>> with patch.multiple('__main__', thing=DEFAULT, other=DEFAULT) as values:
michael@0 412 ... assert 'other' in repr(values['other'])
michael@0 413 ... assert 'thing' in repr(values['thing'])
michael@0 414 ... assert values['thing'] is thing
michael@0 415 ... assert values['other'] is other
michael@0 416 ...
michael@0 417
michael@0 418
michael@0 419 .. _start-and-stop:
michael@0 420
michael@0 421 patch methods: start and stop
michael@0 422 =============================
michael@0 423
michael@0 424 All the patchers have `start` and `stop` methods. These make it simpler to do
michael@0 425 patching in `setUp` methods or where you want to do multiple patches without
michael@0 426 nesting decorators or with statements.
michael@0 427
michael@0 428 To use them call `patch`, `patch.object` or `patch.dict` as normal and keep a
michael@0 429 reference to the returned `patcher` object. You can then call `start` to put
michael@0 430 the patch in place and `stop` to undo it.
michael@0 431
michael@0 432 If you are using `patch` to create a mock for you then it will be returned by
michael@0 433 the call to `patcher.start`.
michael@0 434
michael@0 435 .. doctest::
michael@0 436
michael@0 437 >>> patcher = patch('package.module.ClassName')
michael@0 438 >>> from package import module
michael@0 439 >>> original = module.ClassName
michael@0 440 >>> new_mock = patcher.start()
michael@0 441 >>> assert module.ClassName is not original
michael@0 442 >>> assert module.ClassName is new_mock
michael@0 443 >>> patcher.stop()
michael@0 444 >>> assert module.ClassName is original
michael@0 445 >>> assert module.ClassName is not new_mock
michael@0 446
michael@0 447
michael@0 448 A typical use case for this might be for doing multiple patches in the `setUp`
michael@0 449 method of a `TestCase`:
michael@0 450
michael@0 451 .. doctest::
michael@0 452
michael@0 453 >>> class MyTest(TestCase):
michael@0 454 ... def setUp(self):
michael@0 455 ... self.patcher1 = patch('package.module.Class1')
michael@0 456 ... self.patcher2 = patch('package.module.Class2')
michael@0 457 ... self.MockClass1 = self.patcher1.start()
michael@0 458 ... self.MockClass2 = self.patcher2.start()
michael@0 459 ...
michael@0 460 ... def tearDown(self):
michael@0 461 ... self.patcher1.stop()
michael@0 462 ... self.patcher2.stop()
michael@0 463 ...
michael@0 464 ... def test_something(self):
michael@0 465 ... assert package.module.Class1 is self.MockClass1
michael@0 466 ... assert package.module.Class2 is self.MockClass2
michael@0 467 ...
michael@0 468 >>> MyTest('test_something').run()
michael@0 469
michael@0 470 .. caution::
michael@0 471
michael@0 472 If you use this technique you must ensure that the patching is "undone" by
michael@0 473 calling `stop`. This can be fiddlier than you might think, because if an
michael@0 474 exception is raised in the setUp then tearDown is not called. `unittest2
michael@0 475 <http://pypi.python.org/pypi/unittest2>`_ cleanup functions make this
michael@0 476 easier.
michael@0 477
michael@0 478 .. doctest::
michael@0 479
michael@0 480 >>> class MyTest(TestCase):
michael@0 481 ... def setUp(self):
michael@0 482 ... patcher = patch('package.module.Class')
michael@0 483 ... self.MockClass = patcher.start()
michael@0 484 ... self.addCleanup(patcher.stop)
michael@0 485 ...
michael@0 486 ... def test_something(self):
michael@0 487 ... assert package.module.Class is self.MockClass
michael@0 488 ...
michael@0 489 >>> MyTest('test_something').run()
michael@0 490
michael@0 491 As an added bonus you no longer need to keep a reference to the `patcher`
michael@0 492 object.
michael@0 493
michael@0 494 It is also possible to stop all patches which have been started by using
michael@0 495 `patch.stopall`.
michael@0 496
michael@0 497 .. function:: patch.stopall
michael@0 498
michael@0 499 Stop all active patches. Only stops patches started with `start`.
michael@0 500
michael@0 501
michael@0 502 TEST_PREFIX
michael@0 503 ===========
michael@0 504
michael@0 505 All of the patchers can be used as class decorators. When used in this way
michael@0 506 they wrap every test method on the class. The patchers recognise methods that
michael@0 507 start with `test` as being test methods. This is the same way that the
michael@0 508 `unittest.TestLoader` finds test methods by default.
michael@0 509
michael@0 510 It is possible that you want to use a different prefix for your tests. You can
michael@0 511 inform the patchers of the different prefix by setting `patch.TEST_PREFIX`:
michael@0 512
michael@0 513 .. doctest::
michael@0 514
michael@0 515 >>> patch.TEST_PREFIX = 'foo'
michael@0 516 >>> value = 3
michael@0 517 >>>
michael@0 518 >>> @patch('__main__.value', 'not three')
michael@0 519 ... class Thing(object):
michael@0 520 ... def foo_one(self):
michael@0 521 ... print value
michael@0 522 ... def foo_two(self):
michael@0 523 ... print value
michael@0 524 ...
michael@0 525 >>>
michael@0 526 >>> Thing().foo_one()
michael@0 527 not three
michael@0 528 >>> Thing().foo_two()
michael@0 529 not three
michael@0 530 >>> value
michael@0 531 3
michael@0 532
michael@0 533
michael@0 534 Nesting Patch Decorators
michael@0 535 ========================
michael@0 536
michael@0 537 If you want to perform multiple patches then you can simply stack up the
michael@0 538 decorators.
michael@0 539
michael@0 540 You can stack up multiple patch decorators using this pattern:
michael@0 541
michael@0 542 .. doctest::
michael@0 543
michael@0 544 >>> @patch.object(SomeClass, 'class_method')
michael@0 545 ... @patch.object(SomeClass, 'static_method')
michael@0 546 ... def test(mock1, mock2):
michael@0 547 ... assert SomeClass.static_method is mock1
michael@0 548 ... assert SomeClass.class_method is mock2
michael@0 549 ... SomeClass.static_method('foo')
michael@0 550 ... SomeClass.class_method('bar')
michael@0 551 ... return mock1, mock2
michael@0 552 ...
michael@0 553 >>> mock1, mock2 = test()
michael@0 554 >>> mock1.assert_called_once_with('foo')
michael@0 555 >>> mock2.assert_called_once_with('bar')
michael@0 556
michael@0 557
michael@0 558 Note that the decorators are applied from the bottom upwards. This is the
michael@0 559 standard way that Python applies decorators. The order of the created mocks
michael@0 560 passed into your test function matches this order.
michael@0 561
michael@0 562 Like all context-managers patches can be nested using contextlib's nested
michael@0 563 function; *every* patching will appear in the tuple after "as":
michael@0 564
michael@0 565 .. doctest::
michael@0 566
michael@0 567 >>> from contextlib import nested
michael@0 568 >>> with nested(
michael@0 569 ... patch('package.module.ClassName1'),
michael@0 570 ... patch('package.module.ClassName2')
michael@0 571 ... ) as (MockClass1, MockClass2):
michael@0 572 ... assert package.module.ClassName1 is MockClass1
michael@0 573 ... assert package.module.ClassName2 is MockClass2
michael@0 574 ...
michael@0 575
michael@0 576
michael@0 577 .. _where-to-patch:
michael@0 578
michael@0 579 Where to patch
michael@0 580 ==============
michael@0 581
michael@0 582 `patch` works by (temporarily) changing the object that a *name* points to with
michael@0 583 another one. There can be many names pointing to any individual object, so
michael@0 584 for patching to work you must ensure that you patch the name used by the system
michael@0 585 under test.
michael@0 586
michael@0 587 The basic principle is that you patch where an object is *looked up*, which
michael@0 588 is not necessarily the same place as where it is defined. A couple of
michael@0 589 examples will help to clarify this.
michael@0 590
michael@0 591 Imagine we have a project that we want to test with the following structure::
michael@0 592
michael@0 593 a.py
michael@0 594 -> Defines SomeClass
michael@0 595
michael@0 596 b.py
michael@0 597 -> from a import SomeClass
michael@0 598 -> some_function instantiates SomeClass
michael@0 599
michael@0 600 Now we want to test `some_function` but we want to mock out `SomeClass` using
michael@0 601 `patch`. The problem is that when we import module b, which we will have to
michael@0 602 do then it imports `SomeClass` from module a. If we use `patch` to mock out
michael@0 603 `a.SomeClass` then it will have no effect on our test; module b already has a
michael@0 604 reference to the *real* `SomeClass` and it looks like our patching had no
michael@0 605 effect.
michael@0 606
michael@0 607 The key is to patch out `SomeClass` where it is used (or where it is looked up
michael@0 608 ). In this case `some_function` will actually look up `SomeClass` in module b,
michael@0 609 where we have imported it. The patching should look like:
michael@0 610
michael@0 611 `@patch('b.SomeClass')`
michael@0 612
michael@0 613 However, consider the alternative scenario where instead of `from a import
michael@0 614 SomeClass` module b does `import a` and `some_function` uses `a.SomeClass`. Both
michael@0 615 of these import forms are common. In this case the class we want to patch is
michael@0 616 being looked up on the a module and so we have to patch `a.SomeClass` instead:
michael@0 617
michael@0 618 `@patch('a.SomeClass')`
michael@0 619
michael@0 620
michael@0 621 Patching Descriptors and Proxy Objects
michael@0 622 ======================================
michael@0 623
michael@0 624 Since version 0.6.0 both patch_ and patch.object_ have been able to correctly
michael@0 625 patch and restore descriptors: class methods, static methods and properties.
michael@0 626 You should patch these on the *class* rather than an instance.
michael@0 627
michael@0 628 Since version 0.7.0 patch_ and patch.object_ work correctly with some objects
michael@0 629 that proxy attribute access, like the `django setttings object
michael@0 630 <http://www.voidspace.org.uk/python/weblog/arch_d7_2010_12_04.shtml#e1198>`_.
michael@0 631
michael@0 632 .. note::
michael@0 633
michael@0 634 In django `import settings` and `from django.conf import settings`
michael@0 635 return different objects. If you are using libraries / apps that do both you
michael@0 636 may have to patch both. Grrr...

mercurial