fix #13564 - warn when fixtures get wrapped with a decorator#13745
fix #13564 - warn when fixtures get wrapped with a decorator#13745RonnyPfannschmidt wants to merge 11 commits into
Conversation
RonnyPfannschmidt
commented
Sep 22, 2025
- closes Fixture definition check in parsefactories is too strict #13564
c879256 to
9e7e132
Compare
b79b0ed to
59a31ca
Compare
There was a problem hiding this comment.
Pull Request Overview
This PR adds a warning mechanism to detect when pytest fixtures are wrapped with custom decorators, which prevents pytest from discovering them during collection. The warning helps developers understand why their fixtures might not be working as expected.
Key Changes:
- Added a warning system that detects fixtures wrapped in decorators using
functools.wraps - Implemented safe wrapper chain traversal with loop detection and special object handling
- Added comprehensive test coverage for the new warning functionality
Reviewed Changes
Copilot reviewed 3 out of 4 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
src/_pytest/fixtures.py |
Implements the core detection logic for wrapped fixtures and issues warnings when found |
testing/python/fixtures.py |
Adds test case to verify the warning is correctly issued for decorated fixtures |
changelog/13564.improvement.rst |
Documents the new warning feature for wrapped fixtures |
Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.
2510a6a to
3f27e81
Compare
| seen: set[int] = set() | ||
|
|
||
| for _ in range(100): | ||
| if current is None: | ||
| break | ||
|
|
||
| current_id = id(current) | ||
| if current_id in seen: | ||
| return None |
There was a problem hiding this comment.
| seen: set[int] = set() | |
| for _ in range(100): | |
| if current is None: | |
| break | |
| current_id = id(current) | |
| if current_id in seen: | |
| return None | |
| seen: set[int] = {id(None)} | |
| for _ in range(100): | |
| current_id = id(current) | |
| if current_id in seen: | |
| break |
| from types import FunctionType | ||
|
|
||
| from _pytest.warning_types import PytestWarning | ||
| from _pytest.warning_types import warn_explicit_for |
There was a problem hiding this comment.
I'd prefer to make these module-level imports, at least for the stdlib which can't cause import cycles
Refactor the wrapped fixture detection logic to safely handle: - Mock objects (which have _mock_name attribute) - Proxy objects with problematic __class__ properties - Wrapper loops (like in mock.call) - Objects that raise exceptions during isinstance checks The new _find_wrapped_fixture_def() method walks the wrapper chain more safely and avoids infinite loops and errors from special objects. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
Prevent OOM crash when encountering objects with self-referential __wrapped__ attributes. The loop detection logic now checks object IDs at the start of each iteration and includes a maximum depth limit as an additional safeguard. The original code had a timing issue where it checked id(wrapped) against seen after fetching __wrapped__ but before updating current, which failed to detect self-referential objects properly. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
- Clarify mock object skip comment to explain why (avoid false positives) - Use unambiguous pytest#214 reference instead of bare "issue pytest-dev#214" - Simplify loop: use safe_getattr directly for __wrapped__ traversal, the None check at loop start already handles termination - Remove narrating comments, add type annotation to seen set - Inline _issue_fixture_wrapped_warning into _check_for_wrapped_fixture and drop unused nodeid parameter from both helpers - Guard warn_explicit_for with isinstance check for FunctionType Co-authored-by: Cursor AI <ai@cursor.sh> Co-authored-by: Anthropic Claude Opus 4 <claude@anthropic.com>
The path is already ignored earlier in .gitignore. Co-authored-by: Cursor AI <ai@cursor.sh> Co-authored-by: Cursor Grok 4.5 <grok@x.ai>
3f27e81 to
a9f519e
Compare
Simplify None/loop handling in the wrapper walk and use module-level imports. Co-authored-by: Cursor AI <ai@cursor.sh> Co-authored-by: Cursor Grok 4.5 <grok@x.ai>
| # Global plugin autouse fixtures go under Session. | ||
| self._node_autousenames.setdefault(self.session, []).append(name) | ||
|
|
||
| def _find_wrapped_fixture_def( |
There was a problem hiding this comment.
This seems to be mostly reimplementing Python's inspect.unwrap()?
| fixture_func = fixture_def._get_wrapped_function() | ||
| if isinstance(fixture_func, types.FunctionType): | ||
| msg = f"cannot discover {name} due to being wrapped in decorators" | ||
| warn_explicit_for(fixture_func, PytestWarning(msg)) |
There was a problem hiding this comment.
If I'm understanding this properly, we end up warning about this rather than making it work. Is this a reasonable course of action? Especially for the very common case of an user doing:
import pytest
class TestFixture:
# @classmethod
@pytest.fixture(scope="class")
def fixt(cls):
...
def test_fixt(self, fixt):
passand pytest telling them to add @classmethod, I don't think this warning message will actually help them realize what's going on there.
However this also doesn't actually seem to be working with @classmethod, see my other comment.
There was a problem hiding this comment.
no magic fixing - we have to warn/error
| return wrapper | ||
|
|
||
| class TestClass: | ||
| @custom_deco |
There was a problem hiding this comment.
Please add a test using @classmethod (#13507), I don't see any warning with:
import pytest
class TestFixture:
@classmethod
@pytest.fixture(scope="class")
def fixt(cls):
...
def test_fixt(self, fixt):
passDetect fixtures hidden by decorators via inspect.unwrap(stop=...), looking up raw class MRO __dict__ entries so classmethod/staticmethod wrappers are not hidden by getattr. Warn for @classmethod above @pytest.fixture and for @staticmethod when self/cls would become a fixture dependency. Co-authored-by: Cursor AI <ai@cursor.sh> Co-authored-by: Cursor Grok 4.5 <grok@x.ai>
Use exact-type checks instead of isinstance for FixtureFunctionDefinition so proxies that raise from __class__ do not break collection. Skip registration when the raw attribute is classmethod(...), since Python 3.9-3.12 descriptor chaining would otherwise still discover the fixture. Co-authored-by: Cursor AI <ai@cursor.sh> Co-authored-by: Cursor Grok 4.5 <grok@x.ai>
After safe_isclass, __mro__ is always present. Callers never pass None into the wrap check, and signature() is safe once we know we have a FunctionType. Co-authored-by: Cursor AI <ai@cursor.sh> Co-authored-by: Cursor Grok 4.5 <grok@x.ai>
When @pytest.fixture wraps a classmethod/staticmethod, warn_explicit_for needs the underlying function. Cover that path with a wraps+fixture+classmethod test and pragma the remaining non-function guard. Co-authored-by: Cursor AI <ai@cursor.sh> Co-authored-by: Cursor Grok 4.5 <grok@x.ai>
Remove the dynamic-getattr wrap check (fixtures live in __dict__) and tighten _lookup_in_type_dict to class/module owners so the dead non-type return is gone. Co-authored-by: Cursor AI <ai@cursor.sh> Co-authored-by: Cursor Grok 4.5 <grok@x.ai>