Skip to content

Fix duplicate_iterators for async spies - #604

Open
lprnmns wants to merge 2 commits into
pytest-dev:mainfrom
lprnmns:fix/async-spy-duplicate-iterators
Open

Fix duplicate_iterators for async spies#604
lprnmns wants to merge 2 commits into
pytest-dev:mainfrom
lprnmns:fix/async-spy-duplicate-iterators

Conversation

@lprnmns

@lprnmns lprnmns commented Aug 31, 2026

Copy link
Copy Markdown

Problem

mocker.spy supports async functions and documents spy_return_iter for iterator returns when duplicate_iterators=True. The synchronous spy wrapper honors that option, but the async wrapper returned the original iterator without creating the duplicate, leaving spy_return_iter as None.

Fix

Apply the existing itertools.tee handling in the async spy wrapper when duplicate_iterators=True and the awaited result is an iterator.

The unreleased changelog now records the behavior correction.

Tests

  • ./.venv/bin/python -m pytest tests/test_pytest_mock.py::test_async_spy_return_iter_duplicates_iterator_when_enabled -q - failed before the fix as expected; passed after the fix
  • ./.venv/bin/tox run -e py312 - passed; 92 tests
  • ./.venv/bin/tox run -e norewrite - passed; 88 passed, 4 expected skips
  • ./.venv/bin/pre-commit run --all-files - passed
  • ./.venv/bin/python -m compileall -q src tests/test_pytest_mock.py - passed
  • git diff HEAD^ HEAD --check - passed

Compatibility

The change affects only the existing opt-in duplicate_iterators=True path for async functions. Non-iterable async results and duplicate_iterators=False retain their prior behavior.

Related issue

Independent reproduction; no issue is claimed. Open issue #519 concerns a separate Python-version-specific unittest.mock autospec behavior and was not reproduced on the available Python 3.12 runtime.

@lprnmns
lprnmns marked this pull request as ready for review August 31, 2026 13:02
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.

1 participant