|
mocked.__enter__.side_effect = lambda: warnings.warn( |
|
"Mocks returned by pytest-mock do not need to be used as context managers. " |
|
"The mocker fixture automatically undoes mocking at the end of a test. " |
|
"This warning can be ignored if it was triggered by mocking a context manager. " |
|
"https://github.com/pytest-dev/pytest-mock#note-about-usage-as-context-manager", |
|
PytestMockWarning, |
|
stacklevel=depth, |
|
) |
|
return mocked |
Leads to the now not-existing section of the README.rst:
|
**Note about usage as context manager** |
|
|
|
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 |
|
|
|
def test_context_manager(mocker): |
|
a = A() |
|
with mocker.patch.object(a, 'doIt', return_value=True, autospec=True): |
|
assert a.doIt() == True |
|
|
|
.. code-block:: console |
|
|
|
================================== FAILURES =================================== |
|
____________________________ test_context_manager _____________________________ |
|
in test_context_manager |
|
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 |
pytest-mock/src/pytest_mock/plugin.py
Lines 212 to 220 in 35e2dca
Leads to the now not-existing section of the README.rst:
pytest-mock/README.rst
Lines 277 to 315 in 4c3caaf