python/mock-1.0.0/docs/index.txt

Fri, 16 Jan 2015 18:13:44 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Fri, 16 Jan 2015 18:13:44 +0100
branch
TOR_BUG_9701
changeset 14
925c144e1f1f
permissions
-rw-r--r--

Integrate suggestion from review to improve consistency with existing code.

michael@0 1 ====================================
michael@0 2 Mock - Mocking and Testing Library
michael@0 3 ====================================
michael@0 4
michael@0 5 .. currentmodule:: mock
michael@0 6
michael@0 7 :Author: `Michael Foord
michael@0 8 <http://www.voidspace.org.uk/python/weblog/index.shtml>`_
michael@0 9 :Version: |release|
michael@0 10 :Date: 2012/10/07
michael@0 11 :Homepage: `Mock Homepage`_
michael@0 12 :Download: `Mock on PyPI`_
michael@0 13 :Documentation: `PDF Documentation
michael@0 14 <http://www.voidspace.org.uk/downloads/mock-1.0.0.pdf>`_
michael@0 15 :License: `BSD License`_
michael@0 16 :Support: `Mailing list (testing-in-python@lists.idyll.org)
michael@0 17 <http://lists.idyll.org/listinfo/testing-in-python>`_
michael@0 18 :Issue tracker: `Google code project
michael@0 19 <http://code.google.com/p/mock/issues/list>`_
michael@0 20
michael@0 21 .. _Mock Homepage: http://www.voidspace.org.uk/python/mock/
michael@0 22 .. _BSD License: http://www.voidspace.org.uk/python/license.shtml
michael@0 23
michael@0 24
michael@0 25 .. currentmodule:: mock
michael@0 26
michael@0 27 .. module:: mock
michael@0 28 :synopsis: Mock object and testing library.
michael@0 29
michael@0 30 .. index:: introduction
michael@0 31
michael@0 32 mock is a library for testing in Python. It allows you to replace parts of
michael@0 33 your system under test with mock objects and make assertions about how they
michael@0 34 have been used.
michael@0 35
michael@0 36 mock is now part of the Python standard library, available as `unittest.mock
michael@0 37 <http://docs.python.org/py3k/library/unittest.mock.html#module-unittest.mock>`_
michael@0 38 in Python 3.3 onwards.
michael@0 39
michael@0 40 mock provides a core :class:`Mock` class removing the need to create a host
michael@0 41 of stubs throughout your test suite. After performing an action, you can make
michael@0 42 assertions about which methods / attributes were used and arguments they were
michael@0 43 called with. You can also specify return values and set needed attributes in
michael@0 44 the normal way.
michael@0 45
michael@0 46 Additionally, mock provides a :func:`patch` decorator that handles patching
michael@0 47 module and class level attributes within the scope of a test, along with
michael@0 48 :const:`sentinel` for creating unique objects. See the `quick guide`_ for
michael@0 49 some examples of how to use :class:`Mock`, :class:`MagicMock` and
michael@0 50 :func:`patch`.
michael@0 51
michael@0 52 Mock is very easy to use and is designed for use with
michael@0 53 `unittest <http://pypi.python.org/pypi/unittest2>`_. Mock is based on
michael@0 54 the 'action -> assertion' pattern instead of `'record -> replay'` used by many
michael@0 55 mocking frameworks.
michael@0 56
michael@0 57 mock is tested on Python versions 2.4-2.7, Python 3 plus the latest versions of
michael@0 58 Jython and PyPy.
michael@0 59
michael@0 60
michael@0 61 .. testsetup::
michael@0 62
michael@0 63 class ProductionClass(object):
michael@0 64 def method(self, *args):
michael@0 65 pass
michael@0 66
michael@0 67 module = sys.modules['module'] = ProductionClass
michael@0 68 ProductionClass.ClassName1 = ProductionClass
michael@0 69 ProductionClass.ClassName2 = ProductionClass
michael@0 70
michael@0 71
michael@0 72
michael@0 73 API Documentation
michael@0 74 =================
michael@0 75
michael@0 76 .. toctree::
michael@0 77 :maxdepth: 2
michael@0 78
michael@0 79 mock
michael@0 80 patch
michael@0 81 helpers
michael@0 82 sentinel
michael@0 83 magicmock
michael@0 84
michael@0 85
michael@0 86 User Guide
michael@0 87 ==========
michael@0 88
michael@0 89 .. toctree::
michael@0 90 :maxdepth: 2
michael@0 91
michael@0 92 getting-started
michael@0 93 examples
michael@0 94 compare
michael@0 95 changelog
michael@0 96
michael@0 97
michael@0 98 .. index:: installing
michael@0 99
michael@0 100 Installing
michael@0 101 ==========
michael@0 102
michael@0 103 The current version is |release|. Mock is stable and widely used. If you do
michael@0 104 find any bugs, or have suggestions for improvements / extensions
michael@0 105 then please contact us.
michael@0 106
michael@0 107 * `mock on PyPI <http://pypi.python.org/pypi/mock>`_
michael@0 108 * `mock documentation as PDF
michael@0 109 <http://www.voidspace.org.uk/downloads/mock-1.0.0.pdf>`_
michael@0 110 * `Google Code Home & Mercurial Repository <http://code.google.com/p/mock/>`_
michael@0 111
michael@0 112 .. index:: repository
michael@0 113 .. index:: hg
michael@0 114
michael@0 115 You can checkout the latest development version from the Google Code Mercurial
michael@0 116 repository with the following command:
michael@0 117
michael@0 118 ``hg clone https://mock.googlecode.com/hg/ mock``
michael@0 119
michael@0 120
michael@0 121 .. index:: pip
michael@0 122 .. index:: easy_install
michael@0 123 .. index:: setuptools
michael@0 124
michael@0 125 If you have pip, setuptools or distribute you can install mock with:
michael@0 126
michael@0 127 | ``easy_install -U mock``
michael@0 128 | ``pip install -U mock``
michael@0 129
michael@0 130 Alternatively you can download the mock distribution from PyPI and after
michael@0 131 unpacking run:
michael@0 132
michael@0 133 ``python setup.py install``
michael@0 134
michael@0 135
michael@0 136 Quick Guide
michael@0 137 ===========
michael@0 138
michael@0 139 :class:`Mock` and :class:`MagicMock` objects create all attributes and
michael@0 140 methods as you access them and store details of how they have been used. You
michael@0 141 can configure them, to specify return values or limit what attributes are
michael@0 142 available, and then make assertions about how they have been used:
michael@0 143
michael@0 144 .. doctest::
michael@0 145
michael@0 146 >>> from mock import MagicMock
michael@0 147 >>> thing = ProductionClass()
michael@0 148 >>> thing.method = MagicMock(return_value=3)
michael@0 149 >>> thing.method(3, 4, 5, key='value')
michael@0 150 3
michael@0 151 >>> thing.method.assert_called_with(3, 4, 5, key='value')
michael@0 152
michael@0 153 :attr:`side_effect` allows you to perform side effects, including raising an
michael@0 154 exception when a mock is called:
michael@0 155
michael@0 156 .. doctest::
michael@0 157
michael@0 158 >>> mock = Mock(side_effect=KeyError('foo'))
michael@0 159 >>> mock()
michael@0 160 Traceback (most recent call last):
michael@0 161 ...
michael@0 162 KeyError: 'foo'
michael@0 163
michael@0 164 >>> values = {'a': 1, 'b': 2, 'c': 3}
michael@0 165 >>> def side_effect(arg):
michael@0 166 ... return values[arg]
michael@0 167 ...
michael@0 168 >>> mock.side_effect = side_effect
michael@0 169 >>> mock('a'), mock('b'), mock('c')
michael@0 170 (1, 2, 3)
michael@0 171 >>> mock.side_effect = [5, 4, 3, 2, 1]
michael@0 172 >>> mock(), mock(), mock()
michael@0 173 (5, 4, 3)
michael@0 174
michael@0 175 Mock has many other ways you can configure it and control its behaviour. For
michael@0 176 example the `spec` argument configures the mock to take its specification
michael@0 177 from another object. Attempting to access attributes or methods on the mock
michael@0 178 that don't exist on the spec will fail with an `AttributeError`.
michael@0 179
michael@0 180 The :func:`patch` decorator / context manager makes it easy to mock classes or
michael@0 181 objects in a module under test. The object you specify will be replaced with a
michael@0 182 mock (or other object) during the test and restored when the test ends:
michael@0 183
michael@0 184 .. doctest::
michael@0 185
michael@0 186 >>> from mock import patch
michael@0 187 >>> @patch('module.ClassName2')
michael@0 188 ... @patch('module.ClassName1')
michael@0 189 ... def test(MockClass1, MockClass2):
michael@0 190 ... module.ClassName1()
michael@0 191 ... module.ClassName2()
michael@0 192
michael@0 193 ... assert MockClass1 is module.ClassName1
michael@0 194 ... assert MockClass2 is module.ClassName2
michael@0 195 ... assert MockClass1.called
michael@0 196 ... assert MockClass2.called
michael@0 197 ...
michael@0 198 >>> test()
michael@0 199
michael@0 200 .. note::
michael@0 201
michael@0 202 When you nest patch decorators the mocks are passed in to the decorated
michael@0 203 function in the same order they applied (the normal *python* order that
michael@0 204 decorators are applied). This means from the bottom up, so in the example
michael@0 205 above the mock for `module.ClassName1` is passed in first.
michael@0 206
michael@0 207 With `patch` it matters that you patch objects in the namespace where they
michael@0 208 are looked up. This is normally straightforward, but for a quick guide
michael@0 209 read :ref:`where to patch <where-to-patch>`.
michael@0 210
michael@0 211 As well as a decorator `patch` can be used as a context manager in a with
michael@0 212 statement:
michael@0 213
michael@0 214 .. doctest::
michael@0 215
michael@0 216 >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method:
michael@0 217 ... thing = ProductionClass()
michael@0 218 ... thing.method(1, 2, 3)
michael@0 219 ...
michael@0 220 >>> mock_method.assert_called_once_with(1, 2, 3)
michael@0 221
michael@0 222
michael@0 223 There is also :func:`patch.dict` for setting values in a dictionary just
michael@0 224 during a scope and restoring the dictionary to its original state when the test
michael@0 225 ends:
michael@0 226
michael@0 227 .. doctest::
michael@0 228
michael@0 229 >>> foo = {'key': 'value'}
michael@0 230 >>> original = foo.copy()
michael@0 231 >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
michael@0 232 ... assert foo == {'newkey': 'newvalue'}
michael@0 233 ...
michael@0 234 >>> assert foo == original
michael@0 235
michael@0 236 Mock supports the mocking of Python :ref:`magic methods <magic-methods>`. The
michael@0 237 easiest way of using magic methods is with the :class:`MagicMock` class. It
michael@0 238 allows you to do things like:
michael@0 239
michael@0 240 .. doctest::
michael@0 241
michael@0 242 >>> mock = MagicMock()
michael@0 243 >>> mock.__str__.return_value = 'foobarbaz'
michael@0 244 >>> str(mock)
michael@0 245 'foobarbaz'
michael@0 246 >>> mock.__str__.assert_called_with()
michael@0 247
michael@0 248 Mock allows you to assign functions (or other Mock instances) to magic methods
michael@0 249 and they will be called appropriately. The `MagicMock` class is just a Mock
michael@0 250 variant that has all of the magic methods pre-created for you (well, all the
michael@0 251 useful ones anyway).
michael@0 252
michael@0 253 The following is an example of using magic methods with the ordinary Mock
michael@0 254 class:
michael@0 255
michael@0 256 .. doctest::
michael@0 257
michael@0 258 >>> mock = Mock()
michael@0 259 >>> mock.__str__ = Mock(return_value='wheeeeee')
michael@0 260 >>> str(mock)
michael@0 261 'wheeeeee'
michael@0 262
michael@0 263 For ensuring that the mock objects in your tests have the same api as the
michael@0 264 objects they are replacing, you can use :ref:`auto-speccing <auto-speccing>`.
michael@0 265 Auto-speccing can be done through the `autospec` argument to patch, or the
michael@0 266 :func:`create_autospec` function. Auto-speccing creates mock objects that
michael@0 267 have the same attributes and methods as the objects they are replacing, and
michael@0 268 any functions and methods (including constructors) have the same call
michael@0 269 signature as the real object.
michael@0 270
michael@0 271 This ensures that your mocks will fail in the same way as your production
michael@0 272 code if they are used incorrectly:
michael@0 273
michael@0 274 .. doctest::
michael@0 275
michael@0 276 >>> from mock import create_autospec
michael@0 277 >>> def function(a, b, c):
michael@0 278 ... pass
michael@0 279 ...
michael@0 280 >>> mock_function = create_autospec(function, return_value='fishy')
michael@0 281 >>> mock_function(1, 2, 3)
michael@0 282 'fishy'
michael@0 283 >>> mock_function.assert_called_once_with(1, 2, 3)
michael@0 284 >>> mock_function('wrong arguments')
michael@0 285 Traceback (most recent call last):
michael@0 286 ...
michael@0 287 TypeError: <lambda>() takes exactly 3 arguments (1 given)
michael@0 288
michael@0 289 `create_autospec` can also be used on classes, where it copies the signature of
michael@0 290 the `__init__` method, and on callable objects where it copies the signature of
michael@0 291 the `__call__` method.
michael@0 292
michael@0 293
michael@0 294 .. index:: references
michael@0 295 .. index:: articles
michael@0 296
michael@0 297 References
michael@0 298 ==========
michael@0 299
michael@0 300 Articles, blog entries and other stuff related to testing with Mock:
michael@0 301
michael@0 302 * `Imposing a No DB Discipline on Django unit tests
michael@0 303 <https://github.com/carljm/django-testing-slides/blob/master/models/30_no_database.md>`_
michael@0 304 * `mock-django: tools for mocking the Django ORM and models
michael@0 305 <https://github.com/dcramer/mock-django>`_
michael@0 306 * `PyCon 2011 Video: Testing with mock <https://blip.tv/file/4881513>`_
michael@0 307 * `Mock objects in Python
michael@0 308 <http://noopenblockers.com/2012/01/06/mock-objects-in-python/>`_
michael@0 309 * `Python: Injecting Mock Objects for Powerful Testing
michael@0 310 <http://blueprintforge.com/blog/2012/01/08/python-injecting-mock-objects-for-powerful-testing/>`_
michael@0 311 * `Python Mock: How to assert a substring of logger output
michael@0 312 <http://www.michaelpollmeier.com/python-mock-how-to-assert-a-substring-of-logger-output/>`_
michael@0 313 * `Mocking Django <http://www.mattjmorrison.com/2011/09/mocking-django.html>`_
michael@0 314 * `Mocking dates and other classes that can't be modified
michael@0 315 <http://williamjohnbert.com/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/>`_
michael@0 316 * `Mock recipes <http://konryd.blogspot.com/2010/06/mock-recipies.html>`_
michael@0 317 * `Mockity mock mock - some love for the mock module
michael@0 318 <http://konryd.blogspot.com/2010/05/mockity-mock-mock-some-love-for-mock.html>`_
michael@0 319 * `Coverage and Mock (with django)
michael@0 320 <http://mattsnider.com/python/mock-and-coverage/>`_
michael@0 321 * `Python Unit Testing with Mock <http://www.insomnihack.com/?p=194>`_
michael@0 322 * `Getting started with Python Mock
michael@0 323 <http://myadventuresincoding.wordpress.com/2011/02/26/python-python-mock-cheat-sheet/>`_
michael@0 324 * `Smart Parameter Checks with mock
michael@0 325 <http://tobyho.com/2011/03/24/smart-parameter-checks-in/>`_
michael@0 326 * `Python mock testing techniques and tools
michael@0 327 <http://agiletesting.blogspot.com/2009/07/python-mock-testing-techniques-and.html>`_
michael@0 328 * `How To Test Django Template Tags
michael@0 329 <http://techblog.ironfroggy.com/2008/10/how-to-test.html>`_
michael@0 330 * `A presentation on Unit Testing with Mock
michael@0 331 <http://pypap.blogspot.com/2008/10/newbie-nugget-unit-testing-with-mock.html>`_
michael@0 332 * `Mocking with Django and Google AppEngine
michael@0 333 <http://michael-a-nelson.blogspot.com/2008/09/mocking-with-django-and-google-app.html>`_
michael@0 334
michael@0 335
michael@0 336 .. index:: tests
michael@0 337 .. index:: unittest2
michael@0 338
michael@0 339 Tests
michael@0 340 =====
michael@0 341
michael@0 342 Mock uses `unittest2 <http://pypi.python.org/pypi/unittest2>`_ for its own
michael@0 343 test suite. In order to run it, use the `unit2` script that comes with
michael@0 344 `unittest2` module on a checkout of the source repository:
michael@0 345
michael@0 346 `unit2 discover`
michael@0 347
michael@0 348 If you have `setuptools <http://pypi.python.org/pypi/distribute>`_ as well as
michael@0 349 unittest2 you can run:
michael@0 350
michael@0 351 ``python setup.py test``
michael@0 352
michael@0 353 On Python 3.2 you can use ``unittest`` module from the standard library.
michael@0 354
michael@0 355 ``python3.2 -m unittest discover``
michael@0 356
michael@0 357 .. index:: Python 3
michael@0 358
michael@0 359 On Python 3 the tests for unicode are skipped as they are not relevant. On
michael@0 360 Python 2.4 tests that use the with statements are skipped as the with statement
michael@0 361 is invalid syntax on Python 2.4.
michael@0 362
michael@0 363
michael@0 364 .. index:: older versions
michael@0 365
michael@0 366 Older Versions
michael@0 367 ==============
michael@0 368
michael@0 369 Documentation for older versions of mock:
michael@0 370
michael@0 371 * `mock 0.8 <http://www.voidspace.org.uk/python/mock/0.8/>`_
michael@0 372 * `mock 0.7 <http://www.voidspace.org.uk/python/mock/0.7/>`_
michael@0 373 * `mock 0.6 <http://www.voidspace.org.uk/python/mock/0.6.0/>`_
michael@0 374
michael@0 375 Docs from the in-development version of `mock` can be found at
michael@0 376 `mock.readthedocs.org <http://mock.readthedocs.org>`_.
michael@0 377
michael@0 378
michael@0 379 Terminology
michael@0 380 ===========
michael@0 381
michael@0 382 Terminology for objects used to replace other ones can be confusing. Terms
michael@0 383 like double, fake, mock, stub, and spy are all used with varying meanings.
michael@0 384
michael@0 385 In `classic mock terminology
michael@0 386 <http://xunitpatterns.com/Mocks,%20Fakes,%20Stubs%20and%20Dummies.html>`_
michael@0 387 :class:`mock.Mock` is a `spy <http://xunitpatterns.com/Test%20Spy.html>`_ that
michael@0 388 allows for *post-mortem* examination. This is what I call the "action ->
michael@0 389 assertion" [#]_ pattern of testing.
michael@0 390
michael@0 391 I'm not however a fan of this "statically typed mocking terminology"
michael@0 392 promulgated by `Martin Fowler
michael@0 393 <http://martinfowler.com/articles/mocksArentStubs.html>`_. It confuses usage
michael@0 394 patterns with implementation and prevents you from using natural terminology
michael@0 395 when discussing mocking.
michael@0 396
michael@0 397 I much prefer duck typing, if an object used in your test suite looks like a
michael@0 398 mock object and quacks like a mock object then it's fine to call it a mock, no
michael@0 399 matter what the implementation looks like.
michael@0 400
michael@0 401 This terminology is perhaps more useful in less capable languages where
michael@0 402 different usage patterns will *require* different implementations.
michael@0 403 `mock.Mock()` is capable of being used in most of the different roles
michael@0 404 described by Fowler, except (annoyingly / frustratingly / ironically) a Mock
michael@0 405 itself!
michael@0 406
michael@0 407 How about a simpler definition: a "mock object" is an object used to replace a
michael@0 408 real one in a system under test.
michael@0 409
michael@0 410 .. [#] This pattern is called "AAA" by some members of the testing community;
michael@0 411 "Arrange - Act - Assert".

mercurial