From 4c3caaf2260f77ed10e855a20207023dded12c07 Mon Sep 17 00:00:00 2001 From: Daniel Hahler Date: Mon, 10 Jul 2017 19:24:21 +0200 Subject: [PATCH] README: extend note about usage as context manager --- README.rst | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index dc5970b..691c2ca 100644 --- a/README.rst +++ b/README.rst @@ -274,9 +274,13 @@ But this poses a few disadvantages: - you can't easily undo the mocking during the test execution; -**Note** +**Note about usage as context manager** -Although mocker's API is intentionally the same as ``mock.patch``'s, its uses as context managers and function decorators are **not** supported. The purpose of this plugin is to make the use of context managers and function decorators for mocking unnecessary. Indeed, trying to use the functionality in ``mocker`` in this manner can lead to non-intuitive errors: +Although mocker's API is intentionally the same as ``mock.patch``'s, its use +as context manager and function decorator is **not** supported through the +fixture. The purpose of this plugin is to make the use of context managers and +function decorators for mocking unnecessary. Indeed, trying to use the +functionality in ``mocker`` in this manner can lead to non-intuitive errors: .. code-block:: python @@ -293,6 +297,23 @@ Although mocker's API is intentionally the same as ``mock.patch``'s, its uses as with mocker.patch.object(a, 'doIt', return_value=True, autospec=True): E AttributeError: __exit__ +You can however use ``mocker.mock_module`` to access the underlying ``mock`` +module, e.g. to return a context manager in a fixture that mocks something +temporarily: + +.. code-block:: python + + @pytest.fixture + def fixture_cm(mocker): + @contextlib.contextmanager + def my_cm(): + def mocked(): + pass + + with mocker.mock_module.patch.object(SomeClass, 'method', mocked): + yield + return my_cm + License =======