python/mock-1.0.0/docs/index.txt

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

mercurial