diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 6b97052..3cfe123 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -20,10 +20,10 @@ jobs: SETUPTOOLS_SCM_PRETEND_VERSION: ${{ github.event.inputs.version }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Build and Check Package - uses: hynek/build-and-inspect-python-package@v2.12.0 + uses: hynek/build-and-inspect-python-package@v2.13.0 with: attest-build-provenance-github: 'true' @@ -37,16 +37,16 @@ jobs: contents: write # For tag and release notes. steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Download Package - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v5 with: name: Packages path: dist - name: Publish package to PyPI - uses: pypa/gh-action-pypi-publish@v1.12.4 + uses: pypa/gh-action-pypi-publish@v1.13.0 with: attestations: true diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6443b3b..a5682d4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -21,9 +21,9 @@ jobs: id-token: write attestations: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Build and Check Package - uses: hynek/build-and-inspect-python-package@v2.12.0 + uses: hynek/build-and-inspect-python-package@v2.13.0 with: # Disabling because this is failing currently, see #466. attest-build-provenance-github: 'false' @@ -37,7 +37,7 @@ jobs: strategy: fail-fast: false matrix: - python: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13", "3.14-dev"] + python: ["3.9", "3.10", "3.11", "3.12", "3.13", "3.14"] os: [ubuntu-latest, windows-latest] tox_env: ["py"] include: @@ -52,10 +52,10 @@ jobs: tox_env: "norewrite" steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - name: Download Package - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v5 with: name: Packages path: dist @@ -64,6 +64,7 @@ jobs: uses: actions/setup-python@v5 with: python-version: ${{ matrix.python }} + allow-prereleases: true - name: Install tox run: | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index da96096..f416f4b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -9,13 +9,13 @@ repos: language: python additional_dependencies: [pygments, restructuredtext_lint] - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.11.10 + rev: v0.12.11 hooks: - id: ruff args: ["--fix"] - id: ruff-format - repo: https://github.com/pre-commit/mirrors-mypy - rev: v1.15.0 + rev: v1.17.1 hooks: - id: mypy files: ^(src|tests) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index a826133..0cde5ad 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,7 +1,15 @@ Releases ======== -3.14.1 (2025-08-26) +3.15.0 +------ + +*2025-09-04* + +* Python 3.8 (EOL) is no longer supported. +* `#524 `_: Added ``spy_return_iter`` to ``mocker.spy``, which contains a duplicate of the return value of the spied method if it is an ``Iterator``. + +3.14.1 (2025-05-26) ------------------- * `#503 `_: Python 3.14 is now officially supported. diff --git a/RELEASING.rst b/RELEASING.rst index 2c734f1..7269d56 100644 --- a/RELEASING.rst +++ b/RELEASING.rst @@ -3,10 +3,8 @@ Here are the steps on how to make a new release. 1. Create a ``release-VERSION`` branch from ``upstream/main``. 2. Update ``CHANGELOG.rst``. 3. Push the branch to ``upstream``. -4. Once all tests pass, start the ``deploy`` workflow manually or via: +4. Once all tests pass, start the ``deploy`` workflow manually or via:: - ``` - gh workflow run deploy.yml --repo pytest-dev/pytest-mock --ref release-VERSION -f version=VERSION - ``` + gh workflow run deploy.yml --repo pytest-dev/pytest-mock --ref release-VERSION -f version=VERSION 5. Merge the PR. diff --git a/docs/usage.rst b/docs/usage.rst index 339746a..587fcb3 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -81,6 +81,7 @@ are available (like ``assert_called_once_with`` or ``call_count`` in the example In addition, spy objects contain two extra attributes: * ``spy_return``: contains the last returned value of the spied function. +* ``spy_return_iter``: contains a duplicate of the last returned value of the spied function if the value was an iterator. Uses `tee `__) to duplicate the iterator. * ``spy_return_list``: contains a list of all returned values of the spied function (new in ``3.13``). * ``spy_exception``: contain the last exception value raised by the spied function/method when it was last called, or ``None`` if no exception was raised. diff --git a/pyproject.toml b/pyproject.toml index f73f8ff..f00d66e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,7 +15,7 @@ dependencies = [ "pytest>=6.2.5", ] dynamic = ["version"] -requires-python = ">=3.8" +requires-python = ">=3.9" readme = "README.rst" license = {text = "MIT"} keywords = ["pytest", "mock"] @@ -27,7 +27,6 @@ classifiers = [ "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", diff --git a/src/pytest_mock/_util.py b/src/pytest_mock/_util.py index d3a732a..ad830ca 100644 --- a/src/pytest_mock/_util.py +++ b/src/pytest_mock/_util.py @@ -15,7 +15,7 @@ def get_mock_module(config): config.getini("mock_use_standalone_module") ) if use_standalone_module: - import mock + from unittest import mock _mock_module = mock else: diff --git a/src/pytest_mock/plugin.py b/src/pytest_mock/plugin.py index 50dc06a..f4dbfc3 100644 --- a/src/pytest_mock/plugin.py +++ b/src/pytest_mock/plugin.py @@ -1,21 +1,18 @@ import builtins import functools import inspect +import itertools import unittest.mock import warnings +from collections.abc import Generator +from collections.abc import Iterable +from collections.abc import Iterator +from collections.abc import Mapping from dataclasses import dataclass from dataclasses import field from typing import Any from typing import Callable -from typing import Dict -from typing import Generator -from typing import Iterable -from typing import Iterator -from typing import List -from typing import Mapping from typing import Optional -from typing import Tuple -from typing import Type from typing import TypeVar from typing import Union from typing import cast @@ -52,7 +49,7 @@ class MockCache: Cache MagicMock and Patcher instances so we can undo them later. """ - cache: List[MockCacheItem] = field(default_factory=list) + cache: list[MockCacheItem] = field(default_factory=list) def _find(self, mock: MockType) -> MockCacheItem: for mock_item in self.cache: @@ -124,7 +121,7 @@ def resetall( :param bool return_value: Reset the return_value of mocks. :param bool side_effect: Reset the side_effect of mocks. """ - supports_reset_mock_with_args: Tuple[Type[Any], ...] + supports_reset_mock_with_args: tuple[type[Any], ...] if hasattr(self, "AsyncMock"): supports_reset_mock_with_args = (self.Mock, self.AsyncMock) else: @@ -137,6 +134,8 @@ def resetall( # NOTE: The mock may be a dictionary if hasattr(mock_item.mock, "spy_return_list"): mock_item.mock.spy_return_list = [] + if hasattr(mock_item.mock, "spy_return_iter"): + mock_item.mock.spy_return_iter = None if isinstance(mock_item.mock, supports_reset_mock_with_args): mock_item.mock.reset_mock( return_value=return_value, side_effect=side_effect @@ -178,6 +177,12 @@ def wrapper(*args, **kwargs): spy_obj.spy_exception = e raise else: + if isinstance(r, Iterator): + r, duplicated_iterator = itertools.tee(r, 2) + spy_obj.spy_return_iter = duplicated_iterator + else: + spy_obj.spy_return_iter = None + spy_obj.spy_return = r spy_obj.spy_return_list.append(r) return r @@ -204,6 +209,7 @@ async def async_wrapper(*args, **kwargs): spy_obj = self.patch.object(obj, name, side_effect=wrapped, autospec=autospec) spy_obj.spy_return = None + spy_obj.spy_return_iter = None spy_obj.spy_return_list = [] spy_obj.spy_exception = None return spy_obj @@ -338,7 +344,7 @@ def multiple( autospec: Optional[builtins.object] = None, new_callable: Optional[builtins.object] = None, **kwargs: Any, - ) -> Dict[str, MockType]: + ) -> dict[str, MockType]: """API to mock.patch.multiple""" return self._start_patch( self.mock_module.patch.multiple, @@ -355,7 +361,7 @@ def multiple( def dict( self, in_dict: Union[Mapping[Any, Any], str], - values: Union[Mapping[Any, Any], Iterable[Tuple[Any, Any]]] = (), + values: Union[Mapping[Any, Any], Iterable[tuple[Any, Any]]] = (), clear: bool = False, **kwargs: Any, ) -> Any: @@ -467,8 +473,8 @@ def _mocker(pytestconfig: Any) -> Generator[MockerFixture, None, None]: session_mocker = pytest.fixture(scope="session")(_mocker) -_mock_module_patches = [] # type: List[Any] -_mock_module_originals = {} # type: Dict[str, Any] +_mock_module_patches: list[Any] = [] +_mock_module_originals: dict[str, Any] = {} def assert_wrapper( diff --git a/tests/test_pytest_mock.py b/tests/test_pytest_mock.py index 1a51636..e9b06c8 100644 --- a/tests/test_pytest_mock.py +++ b/tests/test_pytest_mock.py @@ -3,12 +3,12 @@ import re import sys import warnings +from collections.abc import Generator +from collections.abc import Iterable +from collections.abc import Iterator from contextlib import contextmanager from typing import Any from typing import Callable -from typing import Generator -from typing import Tuple -from typing import Type from unittest.mock import AsyncMock from unittest.mock import MagicMock @@ -100,15 +100,15 @@ def check(mocked_rm, mocked_ls): return check -def mock_using_patch_object(mocker: MockerFixture) -> Tuple[MagicMock, MagicMock]: +def mock_using_patch_object(mocker: MockerFixture) -> tuple[MagicMock, MagicMock]: return mocker.patch.object(os, "remove"), mocker.patch.object(os, "listdir") -def mock_using_patch(mocker: MockerFixture) -> Tuple[MagicMock, MagicMock]: +def mock_using_patch(mocker: MockerFixture) -> tuple[MagicMock, MagicMock]: return mocker.patch("os.remove"), mocker.patch("os.listdir") -def mock_using_patch_multiple(mocker: MockerFixture) -> Tuple[MagicMock, MagicMock]: +def mock_using_patch_multiple(mocker: MockerFixture) -> tuple[MagicMock, MagicMock]: r = mocker.patch.multiple("os", remove=mocker.DEFAULT, listdir=mocker.DEFAULT) return r["remove"], r["listdir"] @@ -210,10 +210,7 @@ def test_mocker_resetall(mocker: MockerFixture) -> None: assert isinstance(listdir.return_value, mocker.Mock) assert open.side_effect is None - if sys.version_info >= (3, 9): - # The reset on child mocks have been implemented in 3.9 - # https://bugs.python.org/issue38932 - assert mocked_object.run.return_value != "mocked" + assert mocked_object.run.return_value != "mocked" class TestMockerStub: @@ -265,12 +262,14 @@ def bar(self, arg): assert other.bar(arg=10) == 20 foo.bar.assert_called_once_with(arg=10) # type:ignore[attr-defined] assert foo.bar.spy_return == 20 # type:ignore[attr-defined] + assert foo.bar.spy_return_iter is None # type:ignore[attr-defined] assert foo.bar.spy_return_list == [20] # type:ignore[attr-defined] spy.assert_called_once_with(arg=10) assert spy.spy_return == 20 assert foo.bar(arg=11) == 22 assert foo.bar(arg=12) == 24 assert spy.spy_return == 24 + assert spy.spy_return_iter is None assert spy.spy_return_list == [20, 22, 24] @@ -287,7 +286,7 @@ def bar(self, arg): ), ) def test_instance_method_spy_exception( - exc_cls: Type[BaseException], + exc_cls: type[BaseException], mocker: MockerFixture, ) -> None: class Foo: @@ -349,11 +348,13 @@ def bar(self, x): spy = mocker.spy(Foo, "bar") assert spy.spy_return is None + assert spy.spy_return_iter is None assert spy.spy_return_list == [] assert spy.spy_exception is None Foo().bar(10) assert spy.spy_return == 30 + assert spy.spy_return_iter is None assert spy.spy_return_list == [30] assert spy.spy_exception is None @@ -363,11 +364,13 @@ def bar(self, x): with pytest.raises(ValueError): Foo().bar(0) assert spy.spy_return is None + assert spy.spy_return_iter is None assert spy.spy_return_list == [] assert str(spy.spy_exception) == "invalid x" Foo().bar(15) assert spy.spy_return == 45 + assert spy.spy_return_iter is None assert spy.spy_return_list == [45] assert spy.spy_exception is None @@ -404,6 +407,7 @@ class Foo(Base): calls = [mocker.call(foo, arg=10), mocker.call(other, arg=10)] assert spy.call_args_list == calls assert spy.spy_return == 20 + assert spy.spy_return_iter is None assert spy.spy_return_list == [20, 20] @@ -418,9 +422,11 @@ def bar(cls, arg): assert Foo.bar(arg=10) == 20 Foo.bar.assert_called_once_with(arg=10) # type:ignore[attr-defined] assert Foo.bar.spy_return == 20 # type:ignore[attr-defined] + assert Foo.bar.spy_return_iter is None # type:ignore[attr-defined] assert Foo.bar.spy_return_list == [20] # type:ignore[attr-defined] spy.assert_called_once_with(arg=10) assert spy.spy_return == 20 + assert spy.spy_return_iter is None assert spy.spy_return_list == [20] @@ -438,9 +444,11 @@ class Foo(Base): assert Foo.bar(arg=10) == 20 Foo.bar.assert_called_once_with(arg=10) # type:ignore[attr-defined] assert Foo.bar.spy_return == 20 # type:ignore[attr-defined] + assert Foo.bar.spy_return_iter is None # type:ignore[attr-defined] assert Foo.bar.spy_return_list == [20] # type:ignore[attr-defined] spy.assert_called_once_with(arg=10) assert spy.spy_return == 20 + assert spy.spy_return_iter is None assert spy.spy_return_list == [20] @@ -460,9 +468,11 @@ def bar(cls, arg): assert Foo.bar(arg=10) == 20 Foo.bar.assert_called_once_with(arg=10) # type:ignore[attr-defined] assert Foo.bar.spy_return == 20 # type:ignore[attr-defined] + assert Foo.bar.spy_return_iter is None # type:ignore[attr-defined] assert Foo.bar.spy_return_list == [20] # type:ignore[attr-defined] spy.assert_called_once_with(arg=10) assert spy.spy_return == 20 + assert spy.spy_return_iter is None assert spy.spy_return_list == [20] @@ -477,9 +487,11 @@ def bar(arg): assert Foo.bar(arg=10) == 20 Foo.bar.assert_called_once_with(arg=10) # type:ignore[attr-defined] assert Foo.bar.spy_return == 20 # type:ignore[attr-defined] + assert Foo.bar.spy_return_iter is None # type:ignore[attr-defined] assert Foo.bar.spy_return_list == [20] # type:ignore[attr-defined] spy.assert_called_once_with(arg=10) assert spy.spy_return == 20 + assert spy.spy_return_iter is None assert spy.spy_return_list == [20] @@ -497,9 +509,11 @@ class Foo(Base): assert Foo.bar(arg=10) == 20 Foo.bar.assert_called_once_with(arg=10) # type:ignore[attr-defined] assert Foo.bar.spy_return == 20 # type:ignore[attr-defined] + assert Foo.bar.spy_return_iter is None # type:ignore[attr-defined] assert Foo.bar.spy_return_list == [20] # type:ignore[attr-defined] spy.assert_called_once_with(arg=10) assert spy.spy_return == 20 + assert spy.spy_return_iter is None assert spy.spy_return_list == [20] @@ -521,9 +535,69 @@ def __call__(self, x): uut.call_like(10) spy.assert_called_once_with(10) assert spy.spy_return == 20 + assert spy.spy_return_iter is None assert spy.spy_return_list == [20] +@pytest.mark.parametrize("iterator", [(i for i in range(3)), iter([0, 1, 2])]) +def test_spy_return_iter(mocker: MockerFixture, iterator: Iterator[int]) -> None: + class Foo: + def bar(self) -> Iterator[int]: + return iterator + + foo = Foo() + spy = mocker.spy(foo, "bar") + result = list(foo.bar()) + + assert result == [0, 1, 2] + assert spy.spy_return is not None + assert spy.spy_return_iter is not None + assert list(spy.spy_return_iter) == result + + [return_value] = spy.spy_return_list + assert isinstance(return_value, Iterator) + + +@pytest.mark.parametrize("iterable", [(0, 1, 2), [0, 1, 2], range(3)]) +def test_spy_return_iter_ignore_plain_iterable( + mocker: MockerFixture, iterable: Iterable[int] +) -> None: + class Foo: + def bar(self) -> Iterable[int]: + return iterable + + foo = Foo() + spy = mocker.spy(foo, "bar") + result = foo.bar() + + assert result == iterable + assert spy.spy_return == result + assert spy.spy_return_iter is None + assert spy.spy_return_list == [result] + + +def test_spy_return_iter_resets(mocker: MockerFixture) -> None: + class Foo: + iterables: Any = [ + (i for i in range(3)), + 99, + ] + + def bar(self) -> Any: + return self.iterables.pop(0) + + foo = Foo() + spy = mocker.spy(foo, "bar") + result_iterator = list(foo.bar()) + + assert result_iterator == [0, 1, 2] + assert list(spy.spy_return_iter) == result_iterator + + assert foo.bar() == 99 + assert spy.spy_return_iter is None + + +@pytest.mark.asyncio async def test_instance_async_method_spy(mocker: MockerFixture) -> None: class Foo: async def bar(self, arg): diff --git a/tox.ini b/tox.ini index f1c0e98..92bcba7 100644 --- a/tox.ini +++ b/tox.ini @@ -1,11 +1,10 @@ [tox] minversion = 3.5.3 -envlist = py{38,39,310,311,312,313,314}, norewrite, pytest6 +envlist = py{39,310,311,312,313,314}, norewrite, pytest6 [testenv] deps = coverage - mock pytest-asyncio pytest6: pytest==6.2.5 commands =