1Metadata-Version: 2.1 2Name: pytest-mock 3Version: 1.10.4 4Summary: Thin-wrapper around the mock package for easier use with py.test 5Home-page: https://github.com/pytest-dev/pytest-mock/ 6Author: Bruno Oliveira 7Author-email: nicoddemus@gmail.com 8License: MIT 9Description: =========== 10 pytest-mock 11 =========== 12 13 This plugin installs a ``mocker`` fixture which is a thin-wrapper around the patching API 14 provided by the `mock package <http://pypi.python.org/pypi/mock>`_, 15 but with the benefit of not having to worry about undoing patches at the end 16 of a test: 17 18 .. code-block:: python 19 20 import os 21 22 class UnixFS: 23 24 @staticmethod 25 def rm(filename): 26 os.remove(filename) 27 28 def test_unix_fs(mocker): 29 mocker.patch('os.remove') 30 UnixFS.rm('file') 31 os.remove.assert_called_once_with('file') 32 33 34 35 |python| |version| |anaconda| |ci| |appveyor| |coverage| |black| 36 37 .. |version| image:: http://img.shields.io/pypi/v/pytest-mock.svg 38 :target: https://pypi.python.org/pypi/pytest-mock 39 40 .. |anaconda| image:: https://img.shields.io/conda/vn/conda-forge/pytest-mock.svg 41 :target: https://anaconda.org/conda-forge/pytest-mock 42 43 .. |ci| image:: http://img.shields.io/travis/pytest-dev/pytest-mock.svg 44 :target: https://travis-ci.org/pytest-dev/pytest-mock 45 46 .. |appveyor| image:: https://ci.appveyor.com/api/projects/status/pid1t7iuwhkm9eh6/branch/master?svg=true 47 :target: https://ci.appveyor.com/project/pytestbot/pytest-mock 48 49 .. |coverage| image:: http://img.shields.io/coveralls/pytest-dev/pytest-mock.svg 50 :target: https://coveralls.io/r/pytest-dev/pytest-mock 51 52 .. |python| image:: https://img.shields.io/pypi/pyversions/pytest-mock.svg 53 :target: https://pypi.python.org/pypi/pytest-mock/ 54 55 .. |black| image:: https://img.shields.io/badge/code%20style-black-000000.svg 56 :target: https://github.com/ambv/black 57 58 `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>`_ 59 60 Usage 61 ===== 62 63 The ``mocker`` fixture has the same API as 64 `mock.patch <https://docs.python.org/3/library/unittest.mock.html#patch>`_, 65 supporting the same arguments: 66 67 .. code-block:: python 68 69 def test_foo(mocker): 70 # all valid calls 71 mocker.patch('os.remove') 72 mocker.patch.object(os, 'listdir', autospec=True) 73 mocked_isfile = mocker.patch('os.path.isfile') 74 75 The supported methods are: 76 77 * `mocker.patch <https://docs.python.org/3/library/unittest.mock.html#patch>`_ 78 * `mocker.patch.object <https://docs.python.org/3/library/unittest.mock.html#patch-object>`_ 79 * `mocker.patch.multiple <https://docs.python.org/3/library/unittest.mock.html#patch-multiple>`_ 80 * `mocker.patch.dict <https://docs.python.org/3/library/unittest.mock.html#patch-dict>`_ 81 * `mocker.stopall <https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch.stopall>`_ 82 * ``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. 83 84 These objects from the ``mock`` module are accessible directly from ``mocker`` for convenience: 85 86 * `Mock <https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock>`_ 87 * `MagicMock <https://docs.python.org/3/library/unittest.mock.html#unittest.mock.MagicMock>`_ 88 * `PropertyMock <https://docs.python.org/3/library/unittest.mock.html#unittest.mock.PropertyMock>`_ 89 * `ANY <https://docs.python.org/3/library/unittest.mock.html#any>`_ 90 * `DEFAULT <https://docs.python.org/3/library/unittest.mock.html#default>`_ *(Version 1.4)* 91 * `call <https://docs.python.org/3/library/unittest.mock.html#call>`_ *(Version 1.1)* 92 * `sentinel <https://docs.python.org/3/library/unittest.mock.html#sentinel>`_ *(Version 1.2)* 93 * `mock_open <https://docs.python.org/3/library/unittest.mock.html#mock-open>`_ 94 95 96 Spy 97 --- 98 99 The spy acts exactly like the original method in all cases, except it allows use of `mock` 100 features with it, like retrieving call count. It also works for class and static methods. 101 102 103 .. code-block:: python 104 105 def test_spy(mocker): 106 class Foo(object): 107 def bar(self): 108 return 42 109 110 foo = Foo() 111 mocker.spy(foo, 'bar') 112 assert foo.bar() == 42 113 assert foo.bar.call_count == 1 114 115 Stub 116 ---- 117 118 119 The stub is a mock object that accepts any arguments and is useful to test callbacks, for instance. 120 May be passed a name to be used by the constructed stub object in its repr (useful for debugging). 121 122 .. code-block:: python 123 124 def test_stub(mocker): 125 def foo(on_something): 126 on_something('foo', 'bar') 127 128 stub = mocker.stub(name='on_something_stub') 129 130 foo(stub) 131 stub.assert_called_once_with('foo', 'bar') 132 133 134 Improved reporting of mock call assertion errors 135 ------------------------------------------------ 136 137 138 This plugin monkeypatches the mock library to improve pytest output for failures 139 of mock call assertions like ``Mock.assert_called_with()`` by hiding internal traceback 140 entries from the ``mock`` module. 141 142 It also adds introspection information on differing call arguments when 143 calling the helper methods. This features catches `AssertionError` raised in 144 the method, and uses py.test's own `advanced assertions`_ to return a better 145 diff:: 146 147 148 mocker = <pytest_mock.MockFixture object at 0x0381E2D0> 149 150 def test(mocker): 151 m = mocker.Mock() 152 m('fo') 153 > m.assert_called_once_with('', bar=4) 154 E AssertionError: Expected call: mock('', bar=4) 155 E Actual call: mock('fo') 156 E 157 E pytest introspection follows: 158 E 159 E Args: 160 E assert ('fo',) == ('',) 161 E At index 0 diff: 'fo' != '' 162 E Use -v to get the full diff 163 E Kwargs: 164 E assert {} == {'bar': 4} 165 E Right contains more items: 166 E {'bar': 4} 167 E Use -v to get the full diff 168 169 170 test_foo.py:6: AssertionError 171 ========================== 1 failed in 0.03 seconds =========================== 172 173 174 This is useful when asserting mock calls with many/nested arguments and trying 175 to quickly see the difference. 176 177 This feature is probably safe, but if you encounter any problems it can be disabled in 178 your ``pytest.ini`` file: 179 180 .. code-block:: ini 181 182 [pytest] 183 mock_traceback_monkeypatch = false 184 185 Note that this feature is automatically disabled with the ``--tb=native`` option. The underlying 186 mechanism used to suppress traceback entries from ``mock`` module does not work with that option 187 anyway plus it generates confusing messages on Python 3.5 due to exception chaining 188 189 .. _advanced assertions: http://pytest.org/latest/assert.html 190 191 192 Use standalone "mock" package 193 ----------------------------- 194 195 *New in version 1.4.0.* 196 197 Python 3 users might want to use a newest version of the ``mock`` package as published on PyPI 198 than the one that comes with the Python distribution. 199 200 .. code-block:: ini 201 202 [pytest] 203 mock_use_standalone_module = true 204 205 This will force the plugin to import ``mock`` instead of the ``unittest.mock`` module bundled with 206 Python 3.4+. Note that this option is only used in Python 3+, as Python 2 users only have the option 207 to use the ``mock`` package from PyPI anyway. 208 209 210 Requirements 211 ============ 212 213 * Python 2.7, Python 3.4+ 214 * pytest 215 * mock (for Python 2) 216 217 218 Install 219 ======= 220 221 Install using `pip <http://pip-installer.org/>`_: 222 223 .. code-block:: console 224 225 $ pip install pytest-mock 226 227 Changelog 228 ========= 229 230 Please consult the `changelog page`_. 231 232 .. _changelog page: https://github.com/pytest-dev/pytest-mock/blob/master/CHANGELOG.rst 233 234 Why bother with a plugin? 235 ========================= 236 237 There are a number of different ``patch`` usages in the standard ``mock`` API, 238 but IMHO they don't scale very well when you have more than one or two 239 patches to apply. 240 241 It may lead to an excessive nesting of ``with`` statements, breaking the flow 242 of the test: 243 244 .. code-block:: python 245 246 import mock 247 248 def test_unix_fs(): 249 with mock.patch('os.remove'): 250 UnixFS.rm('file') 251 os.remove.assert_called_once_with('file') 252 253 with mock.patch('os.listdir'): 254 assert UnixFS.ls('dir') == expected 255 # ... 256 257 with mock.patch('shutil.copy'): 258 UnixFS.cp('src', 'dst') 259 # ... 260 261 262 One can use ``patch`` as a decorator to improve the flow of the test: 263 264 .. code-block:: python 265 266 @mock.patch('os.remove') 267 @mock.patch('os.listdir') 268 @mock.patch('shutil.copy') 269 def test_unix_fs(mocked_copy, mocked_listdir, mocked_remove): 270 UnixFS.rm('file') 271 os.remove.assert_called_once_with('file') 272 273 assert UnixFS.ls('dir') == expected 274 # ... 275 276 UnixFS.cp('src', 'dst') 277 # ... 278 279 But this poses a few disadvantages: 280 281 - test functions must receive the mock objects as parameter, even if you don't plan to 282 access them directly; also, order depends on the order of the decorated ``patch`` 283 functions; 284 - receiving the mocks as parameters doesn't mix nicely with pytest's approach of 285 naming fixtures as parameters, or ``pytest.mark.parametrize``; 286 - you can't easily undo the mocking during the test execution; 287 288 289 **Note about usage as context manager** 290 291 Although mocker's API is intentionally the same as ``mock.patch``'s, its use 292 as context manager and function decorator is **not** supported through the 293 fixture. The purpose of this plugin is to make the use of context managers and 294 function decorators for mocking unnecessary. Indeed, trying to use the 295 functionality in ``mocker`` in this manner can lead to non-intuitive errors: 296 297 .. code-block:: python 298 299 def test_context_manager(mocker): 300 a = A() 301 with mocker.patch.object(a, 'doIt', return_value=True, autospec=True): 302 assert a.doIt() == True 303 304 .. code-block:: console 305 306 ================================== FAILURES =================================== 307 ____________________________ test_context_manager _____________________________ 308 in test_context_manager 309 with mocker.patch.object(a, 'doIt', return_value=True, autospec=True): 310 E AttributeError: __exit__ 311 312 You can however use ``mocker.mock_module`` to access the underlying ``mock`` 313 module, e.g. to return a context manager in a fixture that mocks something 314 temporarily: 315 316 .. code-block:: python 317 318 @pytest.fixture 319 def fixture_cm(mocker): 320 @contextlib.contextmanager 321 def my_cm(): 322 def mocked(): 323 pass 324 325 with mocker.mock_module.patch.object(SomeClass, 'method', mocked): 326 yield 327 return my_cm 328 329 330 Contributing 331 ============ 332 333 Contributions are welcome! After cloning the repository, create a virtual env 334 and install ``pytest-mock`` in editable mode with ``dev`` extras: 335 336 .. code-block:: console 337 338 $ pip install --editable .[dev] 339 $ pre-commit install 340 341 Tests are run with ``tox``, you can run the baseline environments before submitting a PR: 342 343 .. code-block:: console 344 345 $ tox -e py27,py36,linting 346 347 Style checks and formatting are done automatically during commit courtesy of 348 `pre-commit <https://pre-commit.com>`_. 349 350 License 351 ======= 352 353 Distributed under the terms of the `MIT`_ license. 354 355 .. _MIT: https://github.com/pytest-dev/pytest-mock/blob/master/LICENSE 356 357Keywords: pytest mock 358Platform: any 359Classifier: Development Status :: 5 - Production/Stable 360Classifier: Framework :: Pytest 361Classifier: Intended Audience :: Developers 362Classifier: License :: OSI Approved :: MIT License 363Classifier: Operating System :: OS Independent 364Classifier: Programming Language :: Python :: 2 365Classifier: Programming Language :: Python :: 2.7 366Classifier: Programming Language :: Python :: 3 367Classifier: Programming Language :: Python :: 3.4 368Classifier: Programming Language :: Python :: 3.5 369Classifier: Programming Language :: Python :: 3.6 370Classifier: Programming Language :: Python :: 3.7 371Classifier: Programming Language :: Python :: 3.8 372Classifier: Topic :: Software Development :: Testing 373Requires-Python: >=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.* 374Provides-Extra: dev 375