Skip to content

Keep spies calling through after spy.reset_mock(side_effect=True) - #647

Open
saifmodan2006 wants to merge 1 commit into
pytest-dev:mainfrom
saifmodan2006:fix/spy-reset-mock-side-effect
Open

saifmodan2006 wants to merge 1 commit into
pytest-dev:mainfrom
saifmodan2006:fix/spy-reset-mock-side-effect

Conversation

@saifmodan2006

Copy link
Copy Markdown

Problem

For spies whose mock is a MagicMock (classmethods, staticmethods, builtins and classes), calling spy.reset_mock(side_effect=True) clears the mock's side_effect. Because the spy relies on side_effect to invoke the wrapped implementation, subsequent calls return a MagicMock rather than calling through to the spied code (#636).

Solution

Override reset_mock on spy objects returned by mocker.spy:

  1. Call the original reset_mock(*args, **kwargs) to reset mock call history.
  2. Reset recorded spy call attributes (spy_return, spy_return_list, etc.).
  3. Restore spy_obj.side_effect = wrapped when side_effect=True is passed, restoring the spied code invocation.

Validation

  • Added parameterized unit tests in tests/test_pytest_mock.py covering classmethod, staticmethod, builtin, and class spies after spy.reset_mock(return_value=..., side_effect=...).
  • Added test verifying custom side_effect override on a spy is cleared by spy.reset_mock(side_effect=True).
  • Added test verifying recorded spy attributes on function/method spies are reset by spy.reset_mock().
  • Added changelog entry in CHANGELOG.rst and updated docs/usage.rst.
  • Verified all 86 spy tests pass.

Closes #636

…test-dev#636)

Spies call the spied code from their side_effect. For spies whose mock is a MagicMock (classmethods, staticmethods, builtins and classes), calling spy.reset_mock(side_effect=True) cleared that side_effect, causing subsequent calls to return a MagicMock rather than calling through.

Override reset_mock on spy objects so that resetting side_effect restores the wrapped function and recorded spy attributes are reset.
@saifmodan2006
saifmodan2006 force-pushed the fix/spy-reset-mock-side-effect branch from 3153fb0 to fd4fe26 Compare October 17, 2026 18:16

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.

spy.reset_mock(side_effect=True) makes spies stop calling the spied code

1 participant