README.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. ===========
  2. pytest-mock
  3. ===========
  4. This plugin provides a ``mocker`` fixture which is a thin-wrapper around the patching API
  5. provided by the `mock package <http://pypi.python.org/pypi/mock>`_:
  6. .. code-block:: python
  7. import os
  8. class UnixFS:
  9. @staticmethod
  10. def rm(filename):
  11. os.remove(filename)
  12. def test_unix_fs(mocker):
  13. mocker.patch('os.remove')
  14. UnixFS.rm('file')
  15. os.remove.assert_called_once_with('file')
  16. Besides undoing the mocking automatically after the end of the test, it also provides other
  17. nice utilities such as ``spy`` and ``stub``, and uses pytest introspection when
  18. comparing calls.
  19. |python| |version| |anaconda| |ci| |coverage| |black|
  20. .. |version| image:: http://img.shields.io/pypi/v/pytest-mock.svg
  21. :target: https://pypi.python.org/pypi/pytest-mock
  22. .. |anaconda| image:: https://img.shields.io/conda/vn/conda-forge/pytest-mock.svg
  23. :target: https://anaconda.org/conda-forge/pytest-mock
  24. .. |ci| image:: https://github.com/pytest-dev/pytest-mock/workflows/build/badge.svg
  25. :target: https://github.com/pytest-dev/pytest-mock/actions
  26. .. |coverage| image:: https://coveralls.io/repos/github/pytest-dev/pytest-mock/badge.svg?branch=master
  27. :target: https://coveralls.io/github/pytest-dev/pytest-mock?branch=master
  28. .. |python| image:: https://img.shields.io/pypi/pyversions/pytest-mock.svg
  29. :target: https://pypi.python.org/pypi/pytest-mock/
  30. .. |black| image:: https://img.shields.io/badge/code%20style-black-000000.svg
  31. :target: https://github.com/ambv/black
  32. `Professionally supported pytest-mock is now available <https://tidelift.com/subscription/pkg/pypi-pytest_mock?utm_source=pypi-pytest-mock&utm_medium=referral&utm_campaign=readme>`_
  33. Usage
  34. =====
  35. The ``mocker`` fixture has the same API as
  36. `mock.patch <https://docs.python.org/3/library/unittest.mock.html#patch>`_,
  37. supporting the same arguments:
  38. .. code-block:: python
  39. def test_foo(mocker):
  40. # all valid calls
  41. mocker.patch('os.remove')
  42. mocker.patch.object(os, 'listdir', autospec=True)
  43. mocked_isfile = mocker.patch('os.path.isfile')
  44. The supported methods are:
  45. * `mocker.patch <https://docs.python.org/3/library/unittest.mock.html#patch>`_
  46. * `mocker.patch.object <https://docs.python.org/3/library/unittest.mock.html#patch-object>`_
  47. * `mocker.patch.multiple <https://docs.python.org/3/library/unittest.mock.html#patch-multiple>`_
  48. * `mocker.patch.dict <https://docs.python.org/3/library/unittest.mock.html#patch-dict>`_
  49. * `mocker.stopall <https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch.stopall>`_
  50. * ``mocker.resetall()``: calls `reset_mock() <https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.reset_mock>`_ in all mocked objects up to this point.
  51. Also, as a convenience, these names from the ``mock`` module are accessible directly from ``mocker``:
  52. * `Mock <https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock>`_
  53. * `MagicMock <https://docs.python.org/3/library/unittest.mock.html#unittest.mock.MagicMock>`_
  54. * `PropertyMock <https://docs.python.org/3/library/unittest.mock.html#unittest.mock.PropertyMock>`_
  55. * `ANY <https://docs.python.org/3/library/unittest.mock.html#any>`_
  56. * `DEFAULT <https://docs.python.org/3/library/unittest.mock.html#default>`_ *(Version 1.4)*
  57. * `call <https://docs.python.org/3/library/unittest.mock.html#call>`_ *(Version 1.1)*
  58. * `sentinel <https://docs.python.org/3/library/unittest.mock.html#sentinel>`_ *(Version 1.2)*
  59. * `mock_open <https://docs.python.org/3/library/unittest.mock.html#mock-open>`_
  60. Spy
  61. ---
  62. The ``mocker.spy`` object acts exactly like the original method in all cases, except the spy
  63. also tracks method calls, return values and exceptions raised.
  64. .. code-block:: python
  65. def test_spy(mocker):
  66. class Foo(object):
  67. def bar(self, v):
  68. return v * 2
  69. foo = Foo()
  70. spy = mocker.spy(foo, 'bar')
  71. assert foo.bar(21) == 42
  72. spy.assert_called_once_with(21)
  73. assert spy.spy_return == 42
  74. The object returned by ``mocker.spy`` is a ``MagicMock`` object, so all standard checking functions
  75. are available (like ``assert_called_once_with`` in the example above).
  76. In addition, spy objects contain two extra attributes:
  77. * ``spy_return``: contains the returned value of the spied function.
  78. * ``spy_exception``: contain the last exception value raised by the spied function/method when
  79. it was last called, or ``None`` if no exception was raised.
  80. ``mocker.spy`` also works for class and static methods.
  81. .. note::
  82. In versions earlier than ``2.0``, the attributes were called ``return_value`` and
  83. ``side_effect`` respectively, but due to incompatibilities with ``unittest.mock``
  84. they had to be renamed (see `#175`_ for details).
  85. .. _#175: https://github.com/pytest-dev/pytest-mock/issues/175
  86. Stub
  87. ----
  88. The stub is a mock object that accepts any arguments and is useful to test callbacks.
  89. It may receive an optional name that is shown in its ``repr``, useful for debugging.
  90. .. code-block:: python
  91. def test_stub(mocker):
  92. def foo(on_something):
  93. on_something('foo', 'bar')
  94. stub = mocker.stub(name='on_something_stub')
  95. foo(stub)
  96. stub.assert_called_once_with('foo', 'bar')
  97. Improved reporting of mock call assertion errors
  98. ------------------------------------------------
  99. This plugin monkeypatches the mock library to improve pytest output for failures
  100. of mock call assertions like ``Mock.assert_called_with()`` by hiding internal traceback
  101. entries from the ``mock`` module.
  102. It also adds introspection information on differing call arguments when
  103. calling the helper methods. This features catches `AssertionError` raised in
  104. the method, and uses py.test's own `advanced assertions`_ to return a better
  105. diff::
  106. mocker = <pytest_mock.MockFixture object at 0x0381E2D0>
  107. def test(mocker):
  108. m = mocker.Mock()
  109. m('fo')
  110. > m.assert_called_once_with('', bar=4)
  111. E AssertionError: Expected call: mock('', bar=4)
  112. E Actual call: mock('fo')
  113. E
  114. E pytest introspection follows:
  115. E
  116. E Args:
  117. E assert ('fo',) == ('',)
  118. E At index 0 diff: 'fo' != ''
  119. E Use -v to get the full diff
  120. E Kwargs:
  121. E assert {} == {'bar': 4}
  122. E Right contains more items:
  123. E {'bar': 4}
  124. E Use -v to get the full diff
  125. test_foo.py:6: AssertionError
  126. ========================== 1 failed in 0.03 seconds ===========================
  127. This is useful when asserting mock calls with many/nested arguments and trying
  128. to quickly see the difference.
  129. This feature is probably safe, but if you encounter any problems it can be disabled in
  130. your ``pytest.ini`` file:
  131. .. code-block:: ini
  132. [pytest]
  133. mock_traceback_monkeypatch = false
  134. Note that this feature is automatically disabled with the ``--tb=native`` option. The underlying
  135. mechanism used to suppress traceback entries from ``mock`` module does not work with that option
  136. anyway plus it generates confusing messages on Python 3.5 due to exception chaining
  137. .. _advanced assertions: http://pytest.org/latest/assert.html
  138. Use standalone "mock" package
  139. -----------------------------
  140. *New in version 1.4.0.*
  141. Python 3 users might want to use a newest version of the ``mock`` package as published on PyPI
  142. than the one that comes with the Python distribution.
  143. .. code-block:: ini
  144. [pytest]
  145. mock_use_standalone_module = true
  146. This will force the plugin to import ``mock`` instead of the ``unittest.mock`` module bundled with
  147. Python 3.4+. Note that this option is only used in Python 3+, as Python 2 users only have the option
  148. to use the ``mock`` package from PyPI anyway.
  149. Note about usage as context manager
  150. -----------------------------------
  151. Although mocker's API is intentionally the same as ``mock.patch``'s, its use
  152. as context manager and function decorator is **not** supported through the
  153. fixture:
  154. .. code-block:: python
  155. def test_context_manager(mocker):
  156. a = A()
  157. with mocker.patch.object(a, 'doIt', return_value=True, autospec=True): # DO NOT DO THIS
  158. assert a.doIt() == True
  159. The purpose of this plugin is to make the use of context managers and
  160. function decorators for mocking unnecessary.
  161. Requirements
  162. ============
  163. * Python 2.7, Python 3.4+
  164. * pytest
  165. * mock (for Python 2)
  166. Install
  167. =======
  168. Install using `pip <http://pip-installer.org/>`_:
  169. .. code-block:: console
  170. $ pip install pytest-mock
  171. Changelog
  172. =========
  173. Please consult the `changelog page`_.
  174. .. _changelog page: https://github.com/pytest-dev/pytest-mock/blob/master/CHANGELOG.rst
  175. Why bother with a plugin?
  176. =========================
  177. There are a number of different ``patch`` usages in the standard ``mock`` API,
  178. but IMHO they don't scale very well when you have more than one or two
  179. patches to apply.
  180. It may lead to an excessive nesting of ``with`` statements, breaking the flow
  181. of the test:
  182. .. code-block:: python
  183. import mock
  184. def test_unix_fs():
  185. with mock.patch('os.remove'):
  186. UnixFS.rm('file')
  187. os.remove.assert_called_once_with('file')
  188. with mock.patch('os.listdir'):
  189. assert UnixFS.ls('dir') == expected
  190. # ...
  191. with mock.patch('shutil.copy'):
  192. UnixFS.cp('src', 'dst')
  193. # ...
  194. One can use ``patch`` as a decorator to improve the flow of the test:
  195. .. code-block:: python
  196. @mock.patch('os.remove')
  197. @mock.patch('os.listdir')
  198. @mock.patch('shutil.copy')
  199. def test_unix_fs(mocked_copy, mocked_listdir, mocked_remove):
  200. UnixFS.rm('file')
  201. os.remove.assert_called_once_with('file')
  202. assert UnixFS.ls('dir') == expected
  203. # ...
  204. UnixFS.cp('src', 'dst')
  205. # ...
  206. But this poses a few disadvantages:
  207. - test functions must receive the mock objects as parameter, even if you don't plan to
  208. access them directly; also, order depends on the order of the decorated ``patch``
  209. functions;
  210. - receiving the mocks as parameters doesn't mix nicely with pytest's approach of
  211. naming fixtures as parameters, or ``pytest.mark.parametrize``;
  212. - you can't easily undo the mocking during the test execution;
  213. An alternative is to use ``contextlib.ExitStack`` to stack the context managers in a single level of indentation
  214. to improve the flow of the test:
  215. .. code-block:: python
  216. import contextlib
  217. import mock
  218. def test_unix_fs():
  219. with contextlib.ExitStack() as stack:
  220. stack.enter_context(mock.patch('os.remove'))
  221. UnixFS.rm('file')
  222. os.remove.assert_called_once_with('file')
  223. stack.enter_context(mock.patch('os.listdir'))
  224. assert UnixFS.ls('dir') == expected
  225. # ...
  226. stack.enter_context(mock.patch('shutil.copy'))
  227. UnixFS.cp('src', 'dst')
  228. # ...
  229. But this is arguably a little more complex than using ``pytest-mock``.
  230. Contributing
  231. ============
  232. Contributions are welcome! After cloning the repository, create a virtual env
  233. and install ``pytest-mock`` in editable mode with ``dev`` extras:
  234. .. code-block:: console
  235. $ pip install --editable .[dev]
  236. $ pre-commit install
  237. Tests are run with ``tox``, you can run the baseline environments before submitting a PR:
  238. .. code-block:: console
  239. $ tox -e py27,py36,linting
  240. Style checks and formatting are done automatically during commit courtesy of
  241. `pre-commit <https://pre-commit.com>`_.
  242. License
  243. =======
  244. Distributed under the terms of the `MIT`_ license.
  245. Security contact information
  246. ============================
  247. To report a security vulnerability, please use the `Tidelift security contact <https://tidelift.com/security>`__. Tidelift will coordinate the fix and disclosure.
  248. .. _MIT: https://github.com/pytest-dev/pytest-mock/blob/master/LICENSE