README.txt 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. mock is a library for testing in Python. It allows you to replace parts of
  2. your system under test with mock objects and make assertions about how they
  3. have been used.
  4. mock is now part of the Python standard library, available as `unittest.mock <
  5. http://docs.python.org/py3k/library/unittest.mock.html#module-unittest.mock>`_
  6. in Python 3.3 onwards.
  7. mock provides a core `MagicMock` class removing the need to create a host of
  8. stubs throughout your test suite. After performing an action, you can make
  9. assertions about which methods / attributes were used and arguments they were
  10. called with. You can also specify return values and set needed attributes in
  11. the normal way.
  12. mock is tested on Python versions 2.4-2.7 and Python 3. mock is also tested
  13. with the latest versions of Jython and pypy.
  14. The mock module also provides utility functions / objects to assist with
  15. testing, particularly monkey patching.
  16. * `PDF documentation for 1.0 beta 1
  17. <http://www.voidspace.org.uk/downloads/mock-1.0.0.pdf>`_
  18. * `mock on google code (repository and issue tracker)
  19. <http://code.google.com/p/mock/>`_
  20. * `mock documentation
  21. <http://www.voidspace.org.uk/python/mock/>`_
  22. * `mock on PyPI <http://pypi.python.org/pypi/mock/>`_
  23. * `Mailing list (testing-in-python@lists.idyll.org)
  24. <http://lists.idyll.org/listinfo/testing-in-python>`_
  25. Mock is very easy to use and is designed for use with
  26. `unittest <http://pypi.python.org/pypi/unittest2>`_. Mock is based on
  27. the 'action -> assertion' pattern instead of 'record -> replay' used by many
  28. mocking frameworks. See the `mock documentation`_ for full details.
  29. Mock objects create all attributes and methods as you access them and store
  30. details of how they have been used. You can configure them, to specify return
  31. values or limit what attributes are available, and then make assertions about
  32. how they have been used::
  33. >>> from mock import Mock
  34. >>> real = ProductionClass()
  35. >>> real.method = Mock(return_value=3)
  36. >>> real.method(3, 4, 5, key='value')
  37. 3
  38. >>> real.method.assert_called_with(3, 4, 5, key='value')
  39. `side_effect` allows you to perform side effects, return different values or
  40. raise an exception when a mock is called::
  41. >>> mock = Mock(side_effect=KeyError('foo'))
  42. >>> mock()
  43. Traceback (most recent call last):
  44. ...
  45. KeyError: 'foo'
  46. >>> values = {'a': 1, 'b': 2, 'c': 3}
  47. >>> def side_effect(arg):
  48. ... return values[arg]
  49. ...
  50. >>> mock.side_effect = side_effect
  51. >>> mock('a'), mock('b'), mock('c')
  52. (3, 2, 1)
  53. >>> mock.side_effect = [5, 4, 3, 2, 1]
  54. >>> mock(), mock(), mock()
  55. (5, 4, 3)
  56. Mock has many other ways you can configure it and control its behaviour. For
  57. example the `spec` argument configures the mock to take its specification from
  58. another object. Attempting to access attributes or methods on the mock that
  59. don't exist on the spec will fail with an `AttributeError`.
  60. The `patch` decorator / context manager makes it easy to mock classes or
  61. objects in a module under test. The object you specify will be replaced with a
  62. mock (or other object) during the test and restored when the test ends::
  63. >>> from mock import patch
  64. >>> @patch('test_module.ClassName1')
  65. ... @patch('test_module.ClassName2')
  66. ... def test(MockClass2, MockClass1):
  67. ... test_module.ClassName1()
  68. ... test_module.ClassName2()
  69. ... assert MockClass1.called
  70. ... assert MockClass2.called
  71. ...
  72. >>> test()
  73. .. note::
  74. When you nest patch decorators the mocks are passed in to the decorated
  75. function in the same order they applied (the normal *python* order that
  76. decorators are applied). This means from the bottom up, so in the example
  77. above the mock for `test_module.ClassName2` is passed in first.
  78. With `patch` it matters that you patch objects in the namespace where they
  79. are looked up. This is normally straightforward, but for a quick guide
  80. read `where to patch
  81. <http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch>`_.
  82. As well as a decorator `patch` can be used as a context manager in a with
  83. statement::
  84. >>> with patch.object(ProductionClass, 'method') as mock_method:
  85. ... mock_method.return_value = None
  86. ... real = ProductionClass()
  87. ... real.method(1, 2, 3)
  88. ...
  89. >>> mock_method.assert_called_once_with(1, 2, 3)
  90. There is also `patch.dict` for setting values in a dictionary just during the
  91. scope of a test and restoring the dictionary to its original state when the
  92. test ends::
  93. >>> foo = {'key': 'value'}
  94. >>> original = foo.copy()
  95. >>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
  96. ... assert foo == {'newkey': 'newvalue'}
  97. ...
  98. >>> assert foo == original
  99. Mock supports the mocking of Python magic methods. The easiest way of
  100. using magic methods is with the `MagicMock` class. It allows you to do
  101. things like::
  102. >>> from mock import MagicMock
  103. >>> mock = MagicMock()
  104. >>> mock.__str__.return_value = 'foobarbaz'
  105. >>> str(mock)
  106. 'foobarbaz'
  107. >>> mock.__str__.assert_called_once_with()
  108. Mock allows you to assign functions (or other Mock instances) to magic methods
  109. and they will be called appropriately. The MagicMock class is just a Mock
  110. variant that has all of the magic methods pre-created for you (well - all the
  111. useful ones anyway).
  112. The following is an example of using magic methods with the ordinary Mock
  113. class::
  114. >>> from mock import Mock
  115. >>> mock = Mock()
  116. >>> mock.__str__ = Mock(return_value = 'wheeeeee')
  117. >>> str(mock)
  118. 'wheeeeee'
  119. For ensuring that the mock objects your tests use have the same api as the
  120. objects they are replacing, you can use "auto-speccing". Auto-speccing can
  121. be done through the `autospec` argument to patch, or the `create_autospec`
  122. function. Auto-speccing creates mock objects that have the same attributes
  123. and methods as the objects they are replacing, and any functions and methods
  124. (including constructors) have the same call signature as the real object.
  125. This ensures that your mocks will fail in the same way as your production
  126. code if they are used incorrectly::
  127. >>> from mock import create_autospec
  128. >>> def function(a, b, c):
  129. ... pass
  130. ...
  131. >>> mock_function = create_autospec(function, return_value='fishy')
  132. >>> mock_function(1, 2, 3)
  133. 'fishy'
  134. >>> mock_function.assert_called_once_with(1, 2, 3)
  135. >>> mock_function('wrong arguments')
  136. Traceback (most recent call last):
  137. ...
  138. TypeError: <lambda>() takes exactly 3 arguments (1 given)
  139. `create_autospec` can also be used on classes, where it copies the signature of
  140. the `__init__` method, and on callable objects where it copies the signature of
  141. the `__call__` method.
  142. The distribution contains tests and documentation. The tests require
  143. `unittest2 <http://pypi.python.org/pypi/unittest2>`_ to run.
  144. Docs from the in-development version of `mock` can be found at
  145. `mock.readthedocs.org <http://mock.readthedocs.org>`_.