Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#note-about-usage-as-context-manager leads to no message #312

Closed
stdedos opened this issue Sep 9, 2022 · 1 comment · Fixed by #313
Closed

#note-about-usage-as-context-manager leads to no message #312

stdedos opened this issue Sep 9, 2022 · 1 comment · Fixed by #313

Comments

@stdedos
Copy link

stdedos commented Sep 9, 2022

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:

pytest-mock/README.rst

Lines 277 to 315 in 4c3caaf

**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

@nicoddemus
Copy link
Member

Fixed, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants