Skip to content

Keep the context manager warning after resetall(side_effect=True) - #646

Open
Parsiffall1 wants to merge 2 commits into
pytest-dev:mainfrom
Parsiffall1:fix-resetall-enter-warning
Open

Parsiffall1 wants to merge 2 commits into
pytest-dev:mainfrom
Parsiffall1:fix-resetall-enter-warning

Conversation

@Parsiffall1

Copy link
Copy Markdown

Fixes #637.

mocker.patch and friends install a side_effect on the mock's __enter__ that warns about using the mock as a context manager. mocker.resetall(side_effect=True) resets the side_effect of child mocks too, so after it the warning was gone:

def test_cm(mocker):
    mocked = mocker.patch("json.loads")
    mocker.resetall(side_effect=True)
    with mocked:  # no PytestMockWarning
        pass

_start_patch now records the original __enter__ child and its warning hook on the cache item, and resetall puts the hook back after resetting, the same way it already restores the side_effect of spies. Because the original child is kept rather than looked up again, a __enter__ the user deleted or replaced is left alone. patch.context_manager never had the hook, so nothing changes there.

Tests added to TestContextManagerWarnings:

  • the warning survives resetall(return_value=True, side_effect=True) for mocker.patch;
  • the same for a spy backed by a MagicMock, which still calls through;
  • patch.context_manager still does not warn after resetall;
  • resetall(side_effect=True) does not fail after del mocked.__enter__.

The first two fail on main; the last one covers the deleted __enter__ case of the fix itself. tox -e py313,py314,norewrite passes (172 passed; norewrite 155 passed, 17 expected skips), and pre-commit passes on the changed files. A changelog entry is included.

resetall(side_effect=True) also resets the side_effect of child mocks,
which removed the hook on __enter__ that warns about using mocks from
mocker.patch and friends as context managers. Remember the original
__enter__ child and its hook, and reinstall the hook after the reset,
like the side_effect of spies. A deleted or replaced __enter__ is left
alone.

Fixes pytest-dev#637

This branch has not been deployed

No deployments
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 this pull request may close these issues.

resetall(side_effect=True) removes the warning about using mocks as context managers

1 participant