### Install pre-commit hooks Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/contributing.md Install the pre-commit framework to automatically run style checks and formatting during commits. ```console pre-commit install ``` -------------------------------- ### Install pytest-mock Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/index.md Install the pytest-mock package using pip. ```console $ pip install pytest-mock ``` -------------------------------- ### Basic Patching Example Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/index.md Demonstrates how to use the mocker fixture to patch a module function and assert its call. ```python import os class UnixFS: @staticmethod def rm(filename): os.remove(filename) def test_unix_fs(mocker): mocker.patch('os.remove') UnixFS.rm('file') os.remove.assert_called_once_with('file') ``` -------------------------------- ### Install pytest-mock in editable mode with dev extras Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/contributing.md Install the project in editable mode and include development dependencies. This is typically done after cloning the repository. ```console pip install --editable .[dev] ``` -------------------------------- ### Example of Improved Mock Call Assertion Error Reporting Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/configuration.md This example demonstrates the enhanced pytest output for a failed mock call assertion (assert_called_once_with). It shows detailed introspection on differing call arguments. ```default mocker = def test(mocker): m = mocker.Mock() m('fo') > m.assert_called_once_with('', bar=4) E AssertionError: Expected call: mock('', bar=4) E Actual call: mock('fo') E E pytest introspection follows: E E Args: E assert ('fo',) == ('',) E At index 0 diff: 'fo' != '' E Use -v to get the full diff E Kwargs: E assert {} == {'bar': 4} E Right contains more items: E {'bar': 4} E Use -v to get the full diff test_foo.py:6: AssertionError ========================== 1 failed in 0.03 seconds =========================== ``` -------------------------------- ### Type Annotating with MockerFixture Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/remarks.md Use MockerFixture for static type checking in your tests. Ensure pytest-mock is installed and imported. ```python from pytest_mock import MockerFixture def test_foo(mocker: MockerFixture) -> None: ... ``` -------------------------------- ### Patching with mocker Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/usage.md Demonstrates basic usage of `mocker.patch` and `mocker.patch.object` for mocking functions and methods. ```python def test_foo(mocker): # all valid calls mocker.patch('os.remove') mocker.patch.object(os, 'listdir', autospec=True) mocked_isfile = mocker.patch('os.path.isfile') ``` -------------------------------- ### Using a stub for callbacks Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/usage.md Shows how to use `mocker.stub` to create a mock object for testing callback functions. ```python def test_stub(mocker): def foo(on_something): on_something('foo', 'bar') stub = mocker.stub(name='on_something_stub') foo(stub) stub.assert_called_once_with('foo', 'bar') ``` -------------------------------- ### Unsupported Context Manager Usage Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/usage.md Demonstrates the incorrect way to use mocker as a context manager. This pattern is discouraged and will trigger a warning. ```python def test_context_manager(mocker): a = A() with mocker.patch.object(a, 'doIt', return_value=True, autospec=True): # DO NOT DO THIS assert a.doIt() == True ``` -------------------------------- ### Patching with contextlib.ExitStack Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/remarks.md Shows an alternative to nested 'with' statements using 'contextlib.ExitStack' to manage multiple patch context managers. This improves indentation but can be more complex. ```python import contextlib import mock def test_unix_fs(): with contextlib.ExitStack() as stack: stack.enter_context(mock.patch('os.remove')) UnixFS.rm('file') os.remove.assert_called_once_with('file') stack.enter_context(mock.patch('os.listdir')) assert UnixFS.ls('dir') == expected # ... stack.enter_context(mock.patch('shutil.copy')) UnixFS.cp('src', 'dst') # ... ``` -------------------------------- ### Patching with Decorators Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/remarks.md Illustrates using 'mock.patch' as decorators for applying multiple patches. Note the disadvantages regarding parameter handling and dynamic unmocking. ```python @mock.patch('os.remove') @mock.patch('os.listdir') @mock.patch('shutil.copy') def test_unix_fs(mocked_copy, mocked_listdir, mocked_remove): UnixFS.rm('file') os.remove.assert_called_once_with('file') assert UnixFS.ls('dir') == expected # ... UnixFS.cp('src', 'dst') # ... ``` -------------------------------- ### Run tests with tox for Python 3.8 Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/contributing.md Execute tests using tox for a specific Python environment (Python 3.8 in this case). This is a baseline check before submitting a Pull Request. ```console tox -e py38 ``` -------------------------------- ### Enable Standalone Mock Package Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/configuration.md Configure pytest to use the standalone 'mock' package from PyPI instead of the bundled unittest.mock. Add this to your pytest.ini file. ```ini [pytest] mock_use_standalone_module = true ``` -------------------------------- ### Stopping a spy with mocker.stop Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/usage.md Illustrates how to selectively stop a spy using `mocker.stop()` after it has been used. ```python def test_with_unspy(mocker): class Foo: def bar(self): return 42 spy = mocker.spy(Foo, "bar") foo = Foo() assert foo.bar() == 42 assert spy.call_count == 1 mocker.stop(spy) assert foo.bar() == 42 assert spy.call_count == 1 ``` -------------------------------- ### Spying on a class method Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/usage.md Shows how to use `mocker.spy` to track calls to a class method while still executing the original method. ```python def test_spy_method(mocker): class Foo(object): def bar(self, v): return v * 2 foo = Foo() spy = mocker.spy(foo, 'bar') assert foo.bar(21) == 42 spy.assert_called_once_with(21) assert spy.spy_return == 42 ``` -------------------------------- ### Type Hinting with MockerFixture Source: https://github.com/pytest-dev/pytest-mock/blob/main/CHANGELOG.rst Use MockerFixture for type annotations in tests. This is the recommended approach for new code. ```python from pytest_mock import MockerFixture def test_foo(mocker: MockerFixture) -> None: ... ``` -------------------------------- ### Nested Patching with Mock Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/remarks.md Demonstrates excessive nesting of 'with' statements when using the standard 'mock' library for multiple patches. This can harm test readability. ```python import mock def test_unix_fs(): with mock.patch('os.remove'): UnixFS.rm('file') os.remove.assert_called_once_with('file') with mock.patch('os.listdir'): assert UnixFS.ls('dir') == expected # ... with mock.patch('shutil.copy'): UnixFS.cp('src', 'dst') # ... ``` -------------------------------- ### Spying on a module function Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/usage.md Demonstrates spying on a function within a module to track its calls and return values. ```python def test_spy_function(mocker): # mymodule declares `myfunction` which just returns 42 import mymodule spy = mocker.spy(mymodule, "myfunction") assert mymodule.myfunction() == 42 assert spy.call_count == 1 assert spy.spy_return == 42 ``` -------------------------------- ### Disable Improved Mock Call Reporting Source: https://github.com/pytest-dev/pytest-mock/blob/main/docs/configuration.md Disable the feature that enhances pytest output for mock call assertion errors. Add this to your pytest.ini file if you encounter issues. ```ini [pytest] mock_traceback_monkeypatch = false ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.