1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/python/mock-1.0.0/docs/index.txt Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,411 @@ 1.4 +==================================== 1.5 + Mock - Mocking and Testing Library 1.6 +==================================== 1.7 + 1.8 +.. currentmodule:: mock 1.9 + 1.10 +:Author: `Michael Foord 1.11 + <http://www.voidspace.org.uk/python/weblog/index.shtml>`_ 1.12 +:Version: |release| 1.13 +:Date: 2012/10/07 1.14 +:Homepage: `Mock Homepage`_ 1.15 +:Download: `Mock on PyPI`_ 1.16 +:Documentation: `PDF Documentation 1.17 + <http://www.voidspace.org.uk/downloads/mock-1.0.0.pdf>`_ 1.18 +:License: `BSD License`_ 1.19 +:Support: `Mailing list (testing-in-python@lists.idyll.org) 1.20 + <http://lists.idyll.org/listinfo/testing-in-python>`_ 1.21 +:Issue tracker: `Google code project 1.22 + <http://code.google.com/p/mock/issues/list>`_ 1.23 + 1.24 +.. _Mock Homepage: http://www.voidspace.org.uk/python/mock/ 1.25 +.. _BSD License: http://www.voidspace.org.uk/python/license.shtml 1.26 + 1.27 + 1.28 +.. currentmodule:: mock 1.29 + 1.30 +.. module:: mock 1.31 + :synopsis: Mock object and testing library. 1.32 + 1.33 +.. index:: introduction 1.34 + 1.35 +mock is a library for testing in Python. It allows you to replace parts of 1.36 +your system under test with mock objects and make assertions about how they 1.37 +have been used. 1.38 + 1.39 +mock is now part of the Python standard library, available as `unittest.mock 1.40 +<http://docs.python.org/py3k/library/unittest.mock.html#module-unittest.mock>`_ 1.41 +in Python 3.3 onwards. 1.42 + 1.43 +mock provides a core :class:`Mock` class removing the need to create a host 1.44 +of stubs throughout your test suite. After performing an action, you can make 1.45 +assertions about which methods / attributes were used and arguments they were 1.46 +called with. You can also specify return values and set needed attributes in 1.47 +the normal way. 1.48 + 1.49 +Additionally, mock provides a :func:`patch` decorator that handles patching 1.50 +module and class level attributes within the scope of a test, along with 1.51 +:const:`sentinel` for creating unique objects. See the `quick guide`_ for 1.52 +some examples of how to use :class:`Mock`, :class:`MagicMock` and 1.53 +:func:`patch`. 1.54 + 1.55 +Mock is very easy to use and is designed for use with 1.56 +`unittest <http://pypi.python.org/pypi/unittest2>`_. Mock is based on 1.57 +the 'action -> assertion' pattern instead of `'record -> replay'` used by many 1.58 +mocking frameworks. 1.59 + 1.60 +mock is tested on Python versions 2.4-2.7, Python 3 plus the latest versions of 1.61 +Jython and PyPy. 1.62 + 1.63 + 1.64 +.. testsetup:: 1.65 + 1.66 + class ProductionClass(object): 1.67 + def method(self, *args): 1.68 + pass 1.69 + 1.70 + module = sys.modules['module'] = ProductionClass 1.71 + ProductionClass.ClassName1 = ProductionClass 1.72 + ProductionClass.ClassName2 = ProductionClass 1.73 + 1.74 + 1.75 + 1.76 +API Documentation 1.77 +================= 1.78 + 1.79 +.. toctree:: 1.80 + :maxdepth: 2 1.81 + 1.82 + mock 1.83 + patch 1.84 + helpers 1.85 + sentinel 1.86 + magicmock 1.87 + 1.88 + 1.89 +User Guide 1.90 +========== 1.91 + 1.92 +.. toctree:: 1.93 + :maxdepth: 2 1.94 + 1.95 + getting-started 1.96 + examples 1.97 + compare 1.98 + changelog 1.99 + 1.100 + 1.101 +.. index:: installing 1.102 + 1.103 +Installing 1.104 +========== 1.105 + 1.106 +The current version is |release|. Mock is stable and widely used. If you do 1.107 +find any bugs, or have suggestions for improvements / extensions 1.108 +then please contact us. 1.109 + 1.110 +* `mock on PyPI <http://pypi.python.org/pypi/mock>`_ 1.111 +* `mock documentation as PDF 1.112 + <http://www.voidspace.org.uk/downloads/mock-1.0.0.pdf>`_ 1.113 +* `Google Code Home & Mercurial Repository <http://code.google.com/p/mock/>`_ 1.114 + 1.115 +.. index:: repository 1.116 +.. index:: hg 1.117 + 1.118 +You can checkout the latest development version from the Google Code Mercurial 1.119 +repository with the following command: 1.120 + 1.121 + ``hg clone https://mock.googlecode.com/hg/ mock`` 1.122 + 1.123 + 1.124 +.. index:: pip 1.125 +.. index:: easy_install 1.126 +.. index:: setuptools 1.127 + 1.128 +If you have pip, setuptools or distribute you can install mock with: 1.129 + 1.130 + | ``easy_install -U mock`` 1.131 + | ``pip install -U mock`` 1.132 + 1.133 +Alternatively you can download the mock distribution from PyPI and after 1.134 +unpacking run: 1.135 + 1.136 + ``python setup.py install`` 1.137 + 1.138 + 1.139 +Quick Guide 1.140 +=========== 1.141 + 1.142 +:class:`Mock` and :class:`MagicMock` objects create all attributes and 1.143 +methods as you access them and store details of how they have been used. You 1.144 +can configure them, to specify return values or limit what attributes are 1.145 +available, and then make assertions about how they have been used: 1.146 + 1.147 +.. doctest:: 1.148 + 1.149 + >>> from mock import MagicMock 1.150 + >>> thing = ProductionClass() 1.151 + >>> thing.method = MagicMock(return_value=3) 1.152 + >>> thing.method(3, 4, 5, key='value') 1.153 + 3 1.154 + >>> thing.method.assert_called_with(3, 4, 5, key='value') 1.155 + 1.156 +:attr:`side_effect` allows you to perform side effects, including raising an 1.157 +exception when a mock is called: 1.158 + 1.159 +.. doctest:: 1.160 + 1.161 + >>> mock = Mock(side_effect=KeyError('foo')) 1.162 + >>> mock() 1.163 + Traceback (most recent call last): 1.164 + ... 1.165 + KeyError: 'foo' 1.166 + 1.167 + >>> values = {'a': 1, 'b': 2, 'c': 3} 1.168 + >>> def side_effect(arg): 1.169 + ... return values[arg] 1.170 + ... 1.171 + >>> mock.side_effect = side_effect 1.172 + >>> mock('a'), mock('b'), mock('c') 1.173 + (1, 2, 3) 1.174 + >>> mock.side_effect = [5, 4, 3, 2, 1] 1.175 + >>> mock(), mock(), mock() 1.176 + (5, 4, 3) 1.177 + 1.178 +Mock has many other ways you can configure it and control its behaviour. For 1.179 +example the `spec` argument configures the mock to take its specification 1.180 +from another object. Attempting to access attributes or methods on the mock 1.181 +that don't exist on the spec will fail with an `AttributeError`. 1.182 + 1.183 +The :func:`patch` decorator / context manager makes it easy to mock classes or 1.184 +objects in a module under test. The object you specify will be replaced with a 1.185 +mock (or other object) during the test and restored when the test ends: 1.186 + 1.187 +.. doctest:: 1.188 + 1.189 + >>> from mock import patch 1.190 + >>> @patch('module.ClassName2') 1.191 + ... @patch('module.ClassName1') 1.192 + ... def test(MockClass1, MockClass2): 1.193 + ... module.ClassName1() 1.194 + ... module.ClassName2() 1.195 + 1.196 + ... assert MockClass1 is module.ClassName1 1.197 + ... assert MockClass2 is module.ClassName2 1.198 + ... assert MockClass1.called 1.199 + ... assert MockClass2.called 1.200 + ... 1.201 + >>> test() 1.202 + 1.203 +.. note:: 1.204 + 1.205 + When you nest patch decorators the mocks are passed in to the decorated 1.206 + function in the same order they applied (the normal *python* order that 1.207 + decorators are applied). This means from the bottom up, so in the example 1.208 + above the mock for `module.ClassName1` is passed in first. 1.209 + 1.210 + With `patch` it matters that you patch objects in the namespace where they 1.211 + are looked up. This is normally straightforward, but for a quick guide 1.212 + read :ref:`where to patch <where-to-patch>`. 1.213 + 1.214 +As well as a decorator `patch` can be used as a context manager in a with 1.215 +statement: 1.216 + 1.217 +.. doctest:: 1.218 + 1.219 + >>> with patch.object(ProductionClass, 'method', return_value=None) as mock_method: 1.220 + ... thing = ProductionClass() 1.221 + ... thing.method(1, 2, 3) 1.222 + ... 1.223 + >>> mock_method.assert_called_once_with(1, 2, 3) 1.224 + 1.225 + 1.226 +There is also :func:`patch.dict` for setting values in a dictionary just 1.227 +during a scope and restoring the dictionary to its original state when the test 1.228 +ends: 1.229 + 1.230 +.. doctest:: 1.231 + 1.232 + >>> foo = {'key': 'value'} 1.233 + >>> original = foo.copy() 1.234 + >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True): 1.235 + ... assert foo == {'newkey': 'newvalue'} 1.236 + ... 1.237 + >>> assert foo == original 1.238 + 1.239 +Mock supports the mocking of Python :ref:`magic methods <magic-methods>`. The 1.240 +easiest way of using magic methods is with the :class:`MagicMock` class. It 1.241 +allows you to do things like: 1.242 + 1.243 +.. doctest:: 1.244 + 1.245 + >>> mock = MagicMock() 1.246 + >>> mock.__str__.return_value = 'foobarbaz' 1.247 + >>> str(mock) 1.248 + 'foobarbaz' 1.249 + >>> mock.__str__.assert_called_with() 1.250 + 1.251 +Mock allows you to assign functions (or other Mock instances) to magic methods 1.252 +and they will be called appropriately. The `MagicMock` class is just a Mock 1.253 +variant that has all of the magic methods pre-created for you (well, all the 1.254 +useful ones anyway). 1.255 + 1.256 +The following is an example of using magic methods with the ordinary Mock 1.257 +class: 1.258 + 1.259 +.. doctest:: 1.260 + 1.261 + >>> mock = Mock() 1.262 + >>> mock.__str__ = Mock(return_value='wheeeeee') 1.263 + >>> str(mock) 1.264 + 'wheeeeee' 1.265 + 1.266 +For ensuring that the mock objects in your tests have the same api as the 1.267 +objects they are replacing, you can use :ref:`auto-speccing <auto-speccing>`. 1.268 +Auto-speccing can be done through the `autospec` argument to patch, or the 1.269 +:func:`create_autospec` function. Auto-speccing creates mock objects that 1.270 +have the same attributes and methods as the objects they are replacing, and 1.271 +any functions and methods (including constructors) have the same call 1.272 +signature as the real object. 1.273 + 1.274 +This ensures that your mocks will fail in the same way as your production 1.275 +code if they are used incorrectly: 1.276 + 1.277 +.. doctest:: 1.278 + 1.279 + >>> from mock import create_autospec 1.280 + >>> def function(a, b, c): 1.281 + ... pass 1.282 + ... 1.283 + >>> mock_function = create_autospec(function, return_value='fishy') 1.284 + >>> mock_function(1, 2, 3) 1.285 + 'fishy' 1.286 + >>> mock_function.assert_called_once_with(1, 2, 3) 1.287 + >>> mock_function('wrong arguments') 1.288 + Traceback (most recent call last): 1.289 + ... 1.290 + TypeError: <lambda>() takes exactly 3 arguments (1 given) 1.291 + 1.292 +`create_autospec` can also be used on classes, where it copies the signature of 1.293 +the `__init__` method, and on callable objects where it copies the signature of 1.294 +the `__call__` method. 1.295 + 1.296 + 1.297 +.. index:: references 1.298 +.. index:: articles 1.299 + 1.300 +References 1.301 +========== 1.302 + 1.303 +Articles, blog entries and other stuff related to testing with Mock: 1.304 + 1.305 +* `Imposing a No DB Discipline on Django unit tests 1.306 + <https://github.com/carljm/django-testing-slides/blob/master/models/30_no_database.md>`_ 1.307 +* `mock-django: tools for mocking the Django ORM and models 1.308 + <https://github.com/dcramer/mock-django>`_ 1.309 +* `PyCon 2011 Video: Testing with mock <https://blip.tv/file/4881513>`_ 1.310 +* `Mock objects in Python 1.311 + <http://noopenblockers.com/2012/01/06/mock-objects-in-python/>`_ 1.312 +* `Python: Injecting Mock Objects for Powerful Testing 1.313 + <http://blueprintforge.com/blog/2012/01/08/python-injecting-mock-objects-for-powerful-testing/>`_ 1.314 +* `Python Mock: How to assert a substring of logger output 1.315 + <http://www.michaelpollmeier.com/python-mock-how-to-assert-a-substring-of-logger-output/>`_ 1.316 +* `Mocking Django <http://www.mattjmorrison.com/2011/09/mocking-django.html>`_ 1.317 +* `Mocking dates and other classes that can't be modified 1.318 + <http://williamjohnbert.com/2011/07/how-to-unit-testing-in-django-with-mocking-and-patching/>`_ 1.319 +* `Mock recipes <http://konryd.blogspot.com/2010/06/mock-recipies.html>`_ 1.320 +* `Mockity mock mock - some love for the mock module 1.321 + <http://konryd.blogspot.com/2010/05/mockity-mock-mock-some-love-for-mock.html>`_ 1.322 +* `Coverage and Mock (with django) 1.323 + <http://mattsnider.com/python/mock-and-coverage/>`_ 1.324 +* `Python Unit Testing with Mock <http://www.insomnihack.com/?p=194>`_ 1.325 +* `Getting started with Python Mock 1.326 + <http://myadventuresincoding.wordpress.com/2011/02/26/python-python-mock-cheat-sheet/>`_ 1.327 +* `Smart Parameter Checks with mock 1.328 + <http://tobyho.com/2011/03/24/smart-parameter-checks-in/>`_ 1.329 +* `Python mock testing techniques and tools 1.330 + <http://agiletesting.blogspot.com/2009/07/python-mock-testing-techniques-and.html>`_ 1.331 +* `How To Test Django Template Tags 1.332 + <http://techblog.ironfroggy.com/2008/10/how-to-test.html>`_ 1.333 +* `A presentation on Unit Testing with Mock 1.334 + <http://pypap.blogspot.com/2008/10/newbie-nugget-unit-testing-with-mock.html>`_ 1.335 +* `Mocking with Django and Google AppEngine 1.336 + <http://michael-a-nelson.blogspot.com/2008/09/mocking-with-django-and-google-app.html>`_ 1.337 + 1.338 + 1.339 +.. index:: tests 1.340 +.. index:: unittest2 1.341 + 1.342 +Tests 1.343 +===== 1.344 + 1.345 +Mock uses `unittest2 <http://pypi.python.org/pypi/unittest2>`_ for its own 1.346 +test suite. In order to run it, use the `unit2` script that comes with 1.347 +`unittest2` module on a checkout of the source repository: 1.348 + 1.349 + `unit2 discover` 1.350 + 1.351 +If you have `setuptools <http://pypi.python.org/pypi/distribute>`_ as well as 1.352 +unittest2 you can run: 1.353 + 1.354 + ``python setup.py test`` 1.355 + 1.356 +On Python 3.2 you can use ``unittest`` module from the standard library. 1.357 + 1.358 + ``python3.2 -m unittest discover`` 1.359 + 1.360 +.. index:: Python 3 1.361 + 1.362 +On Python 3 the tests for unicode are skipped as they are not relevant. On 1.363 +Python 2.4 tests that use the with statements are skipped as the with statement 1.364 +is invalid syntax on Python 2.4. 1.365 + 1.366 + 1.367 +.. index:: older versions 1.368 + 1.369 +Older Versions 1.370 +============== 1.371 + 1.372 +Documentation for older versions of mock: 1.373 + 1.374 +* `mock 0.8 <http://www.voidspace.org.uk/python/mock/0.8/>`_ 1.375 +* `mock 0.7 <http://www.voidspace.org.uk/python/mock/0.7/>`_ 1.376 +* `mock 0.6 <http://www.voidspace.org.uk/python/mock/0.6.0/>`_ 1.377 + 1.378 +Docs from the in-development version of `mock` can be found at 1.379 +`mock.readthedocs.org <http://mock.readthedocs.org>`_. 1.380 + 1.381 + 1.382 +Terminology 1.383 +=========== 1.384 + 1.385 +Terminology for objects used to replace other ones can be confusing. Terms 1.386 +like double, fake, mock, stub, and spy are all used with varying meanings. 1.387 + 1.388 +In `classic mock terminology 1.389 +<http://xunitpatterns.com/Mocks,%20Fakes,%20Stubs%20and%20Dummies.html>`_ 1.390 +:class:`mock.Mock` is a `spy <http://xunitpatterns.com/Test%20Spy.html>`_ that 1.391 +allows for *post-mortem* examination. This is what I call the "action -> 1.392 +assertion" [#]_ pattern of testing. 1.393 + 1.394 +I'm not however a fan of this "statically typed mocking terminology" 1.395 +promulgated by `Martin Fowler 1.396 +<http://martinfowler.com/articles/mocksArentStubs.html>`_. It confuses usage 1.397 +patterns with implementation and prevents you from using natural terminology 1.398 +when discussing mocking. 1.399 + 1.400 +I much prefer duck typing, if an object used in your test suite looks like a 1.401 +mock object and quacks like a mock object then it's fine to call it a mock, no 1.402 +matter what the implementation looks like. 1.403 + 1.404 +This terminology is perhaps more useful in less capable languages where 1.405 +different usage patterns will *require* different implementations. 1.406 +`mock.Mock()` is capable of being used in most of the different roles 1.407 +described by Fowler, except (annoyingly / frustratingly / ironically) a Mock 1.408 +itself! 1.409 + 1.410 +How about a simpler definition: a "mock object" is an object used to replace a 1.411 +real one in a system under test. 1.412 + 1.413 +.. [#] This pattern is called "AAA" by some members of the testing community; 1.414 + "Arrange - Act - Assert".