Skip to content

Add SpyType for mocker.spy results#582

Open
Himanshuagrawal4 wants to merge 1 commit into
pytest-dev:mainfrom
Himanshuagrawal4:PRO/pytest-mock-spy-type-attributes
Open

Add SpyType for mocker.spy results#582
Himanshuagrawal4 wants to merge 1 commit into
pytest-dev:mainfrom
Himanshuagrawal4:PRO/pytest-mock-spy-type-attributes

Conversation

@Himanshuagrawal4
Copy link
Copy Markdown

Summary

  • add a public SpyType for mocker.spy() return values
  • expose the spy-only attributes (spy_return, spy_return_iter, spy_return_list, spy_exception) to type checkers
  • export SpyType from pytest_mock and add a regression test

Closes #547.

Validation

  • pre-commit run --files CHANGELOG.rst src/pytest_mock/__init__.py src/pytest_mock/plugin.py tests/test_pytest_mock.py
  • python -m mypy src tests
  • python -m pytest tests/test_pytest_mock.py::test_spy_type tests/test_pytest_mock.py::test_instance_method_spy tests/test_pytest_mock.py::test_spy_return_iter_resets -q
  • python -m pytest tests -q -k "not introspection"
  • python -m compileall -q src\pytest_mock
  • git diff --check

Notes

The full local python -m pytest tests -q run has four existing assertion-introspection output failures on this Windows/Python 3.13 environment. They appear unrelated to this typing change, so this PR leaves those tests untouched.

@Himanshuagrawal4 Himanshuagrawal4 marked this pull request as ready for review June 3, 2026 07:05
Comment thread tests/test_pytest_mock.py
foo = Foo()
spy: SpyType = mocker.spy(foo, "bar")

assert getattr(spy, "spy_return") is None
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why use getattr instead of accessing the attribute directly?

Comment thread tests/test_pytest_mock.py
spy = mocker.spy(Foo, "bar")
assert spy.spy_return is None
assert spy.spy_return_iter is None
assert getattr(spy, "spy_return") is None
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the purpose of these changes?

If they were required because mypy was complaining, then the SpyType is not working as intended -- the sole purpose of adding it is to avoid typing errors when annotating the object returned by mocker.spy.

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 type is missing extra attributes

2 participants