Backtestspytestrun-20261106-234554#14765
Extend self deprecation to module/package/session scoped fixtures inside classes
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches extend the warning to module/package/session scopes and both pass the independent tests for the issue's core scenarios (warn on `self` fixtures in test classes, no warn on `@staticmethod`). The decisive difference is a regression in Patch A: it changes the condition to `fixturedef._scope >= Scope.Class` and warns whenever the fixture function is bound to a non-type instance, without checking that the fixture lives on a test class. Session/module-scoped fixtures defined as instance methods on plugin objects registered via `pluginmanager.register(Plugin())` are a legitimate, long-supported pattern where `self` works correctly because the plugin instance is long-lived. Patch A emits the deprecation for them, and the independent test `test_session_fixture_on_plugin_object_does_not_warn` fails under A (errors=1 instead of passed=1). Patch B guards with `isinstance(fixturedef.node, _pytest.python.Class)`, so only fixtures collected from test classes warn, and it adds a regression test for the plugin case. Patch B also ships a dedicated, scope-aware warning message ("once per module/session" rather than A's now-inaccurate "once per class" text for session scope, and A's message still says "Use a @classmethod" even though the issue asks for `@staticmethod`), a documented deprecation section with before/after examples, and tests that assert the full message text. Patch A's test diff is broader (parametrizes over all scopes including `Scope.Class` and `@staticmethod`), but that does not offset the false-positive warning on plugin fixtures. Minor nit for B: the local `import _pytest.python` inside the function is slightly awkward, but it is a common circular-import workaround in pytest and does not affect correctness.
Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.
Solve
10m 59s
Wall-clock time in the container
Full test suite
No new failures
1,099 passed · 14 skipped · 1,113 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
181vs 85 merged
Changed lines, ours vs merged
The issue
View on GitHub#14071 added a deprecation warning for:
import pytest
class TestFixture:
@pytest.fixture(scope="class")
# without @classmethod
def fixt(self):
self.x = 23
def test_fixt(self, fixt):
print(self.x)
because that doesn't work which might be surprising to people.
However, the same issue exists with scopes module, package and session as well. We should extend the deprecation to those, and require that those are @staticmethod.
The two patches
changelog/14765.deprecation.rstnew file mode 100644index 000000000..65ab1c4f0@@ -0,0 +1,4 @@+Defining a ``module``, ``package`` or ``session`` scoped fixture as an instance method (taking ``self``) inside a test class is now deprecated, extending the existing deprecation for ``class`` scoped fixtures.+Attributes set on ``self`` in such fixtures are not visible to test methods; use ``@staticmethod`` instead.++See :ref:`higher-scoped-fixture-as-instance-method` for details.doc/en/deprecations.rstindex feaeaa097..9ae744578 100644@@ -277,6 +277,47 @@ Using ``@classmethod`` ensures attributes are set on the class itself, making th to all test methods. +.. _higher-scoped-fixture-as-instance-method:++Module, package or session-scoped fixture as instance method+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~++.. deprecated:: 9.1++For the same reason as :ref:`class-scoped fixtures <class-scoped-fixture-as-instance-method>`,+defining a fixture with ``module``, ``package`` or ``session`` scope as an instance method+(taking ``self``) inside a test class is deprecated and will be removed in pytest 10.0.++The fixture runs only once, on an instance of the class which no test method ever sees,+so any attributes set on ``self`` will not be visible to tests.++**Before** (deprecated):++.. code-block:: python++ class TestExample:+ @pytest.fixture(scope="module")+ def database(self):+ self.connection = connect() # This won't be visible to tests!+ return self.connection++**After** (recommended):++.. code-block:: python++ class TestExample:+ @pytest.fixture(scope="module")+ @staticmethod+ def database():+ return connect()++ def test_something(self, database):+ assert database.is_connected()++Use the fixture's return value to pass data to tests instead of setting attributes.+Fixtures defined as instance methods on plugin objects (rather than test classes) are not affected.++ .. _monkeypatch-fixup-namespace-packages: ``monkeypatch.syspath_prepend`` with legacy namespace packagessrc/_pytest/deprecated.pyindex f46b036af..29eeec6b8 100644@@ -43,6 +43,15 @@ CLASS_FIXTURE_INSTANCE_METHOD = UnformattedWarning( "See https://docs.pytest.org/en/stable/deprecations.html#class-scoped-fixture-as-instance-method", ) +HIGHER_SCOPED_FIXTURE_INSTANCE_METHOD = UnformattedWarning(+ PytestRemovedIn10Warning,+ "{scope}-scoped fixtures defined as instance methods in a class are deprecated.\n"+ "Instance attributes set in the {fixturename!r} fixture will NOT be visible to test methods,\n"+ "as each test gets a new instance while the fixture runs only once per {scope_lower}.\n"+ "Use a @staticmethod decorator below @pytest.fixture instead.\n"+ "See https://docs.pytest.org/en/stable/deprecations.html#higher-scoped-fixture-as-instance-method",+)+ # This deprecation is never really meant to be removed. PRIVATE = PytestDeprecationWarning("A private pytest class or function was used.") src/_pytest/fixtures.pyindex 3f1964f2d..6026b91f0 100644@@ -61,6 +61,7 @@ from _pytest.deprecated import FIXTURE_BASEID_DEPRECATED from _pytest.deprecated import FIXTURE_GETFIXTUREVALUE_DURING_TEARDOWN from _pytest.deprecated import FIXTURE_NODEID_DEPRECATED from _pytest.deprecated import FIXTUREDEF_HAS_LOCATION_DEPRECATED+from _pytest.deprecated import HIGHER_SCOPED_FIXTURE_INSTANCE_METHOD from _pytest.deprecated import PARSEFACTORIES_NODEID_DEPRECATED from _pytest.deprecated import YIELD_FIXTURE from _pytest.main import Session@@ -1297,6 +1298,27 @@ def resolve_fixture_function( ), stacklevel=2, )+ elif fixturedef._scope in (Scope.Module, Scope.Package, Scope.Session):+ # Fixtures with a scope higher than class defined as instance methods+ # in a test class have the same problem as class-scoped ones: the+ # fixture runs once on an instance no test method ever sees.+ # Fixtures in non-test classes (e.g. plugin objects, see #2270) are+ # fine, as there the instance is long-lived.+ import _pytest.python++ if (+ isinstance(fixturedef.node, _pytest.python.Class)+ and hasattr(fixturefunc, "__self__")+ and not isinstance(fixturefunc.__self__, type)+ ):+ warnings.warn(+ HIGHER_SCOPED_FIXTURE_INSTANCE_METHOD.format(+ scope=fixturedef._scope.value.capitalize(),+ scope_lower=fixturedef._scope.value,+ fixturename=request.fixturename,+ ),+ stacklevel=2,+ ) if instance is not None: # Handle the case where fixture is defined not in a test class, but some other classtesting/deprecated_test.pyindex 8eed1fb31..d5e4c89f3 100644@@ -130,6 +130,94 @@ def test_class_scope_classmethod_fixture_not_deprecated(pytester: Pytester) -> N result.assert_outcomes(passed=1) +@pytest.mark.parametrize("scope", ["module", "package", "session"])+def test_higher_scope_instance_method_is_deprecated(+ pytester: Pytester, scope: str+) -> None:+ pytester.makepyfile(+ f"""+ import pytest++ class TestClass:+ @pytest.fixture(scope="{scope}")+ def fix(self):+ self.attr = True++ def test_foo(self, fix):+ pass+ """+ )+ result = pytester.runpytest("-Werror::pytest.PytestRemovedIn10Warning")+ result.assert_outcomes(errors=1)+ result.stdout.fnmatch_lines(+ [+ f"*PytestRemovedIn10Warning: {scope.capitalize()}-scoped fixtures defined "+ "as instance methods in a class are deprecated.",+ "*Instance attributes set in the 'fix' fixture will NOT be visible*",+ f"*fixture runs only once per {scope}.",+ "*Use a @staticmethod decorator below @pytest.fixture instead.",+ ]+ )+++@pytest.mark.parametrize("scope", ["module", "package", "session"])+def test_higher_scope_staticmethod_fixture_not_deprecated(+ pytester: Pytester, scope: str+) -> None:+ """A higher-scoped fixture in a class defined as @staticmethod does NOT warn."""+ pytester.makepyfile(+ f"""+ import pytest++ class TestClass:+ @pytest.fixture(scope="{scope}")+ @staticmethod+ def fix():+ return 42++ def test_foo(self, fix):+ assert fix == 42+ """+ )+ result = pytester.runpytest("-Werror::pytest.PytestRemovedIn10Warning")+ result.assert_outcomes(passed=1)+++def test_higher_scope_plugin_instance_method_fixture_not_deprecated(+ pytester: Pytester,+) -> None:+ """Instance-method fixtures on plugin objects (not test classes) do NOT warn,+ as the plugin instance is long-lived (#2270)."""+ pytester.makeconftest(+ """+ import pytest++ class Plugin:+ def __init__(self):+ self.value = 42++ @pytest.fixture(scope="session")+ def fix(self):+ return self.value++ def pytest_configure(config):+ config.pluginmanager.register(Plugin(), "my-plugin")+ """+ )+ pytester.makepyfile(+ """+ def test_foo(fix):+ assert fix == 42++ class TestClass:+ def test_bar(self, fix):+ assert fix == 42+ """+ )+ result = pytester.runpytest("-Werror::pytest.PytestRemovedIn10Warning")+ result.assert_outcomes(passed=2)++ class TestFixtureNodeidDeprecations: """Tests for deprecated baseid/nodeid string APIs in fixture registration. testing/python/fixtures.pyindex 69044226b..7327eab09 100644@@ -1292,7 +1292,8 @@ class TestRequestBasic: class TestRequestSessionScoped: @pytest.fixture(scope="session")- def session_request(self, request):+ @staticmethod+ def session_request(request): return request @pytest.mark.parametrize("name", ["path", "module"])testing/test_conftest.pyindex 38363a3ba..b5df08c78 100644@@ -43,7 +43,8 @@ def conftest_setinitial( @pytest.mark.usefixtures("_sys_snapshot") class TestConftestValueAccessGlobal: @pytest.fixture(scope="module", params=["global", "inpackage"])- def basedir(self, request, tmp_path_factory: TempPathFactory) -> Generator[Path]:+ @staticmethod+ def basedir(request, tmp_path_factory: TempPathFactory) -> Generator[Path]: tmp_path = tmp_path_factory.mktemp("basedir", numbered=True) tmp_path.joinpath("adir/b").mkdir(parents=True) tmp_path.joinpath("adir/conftest.py").write_text(testing/test_legacypath.pyindex 3e71e6b19..c80ec89a8 100644@@ -102,7 +102,8 @@ def test_fixturerequest_getmodulepath(pytester: pytest.Pytester) -> None: class TestFixtureRequestSessionScoped: @pytest.fixture(scope="session")- def session_request(self, request):+ @staticmethod+ def session_request(request): return request def test_session_scoped_unavailable_attributes(self, session_request):testing/test_pathlib.pyindex bd85b7e8f..8ece5942d 100644@@ -129,9 +129,10 @@ class TestImportPath: """ @pytest.fixture(scope="session")- def path1(self, tmp_path_factory: TempPathFactory) -> Generator[Path]:+ @staticmethod+ def path1(tmp_path_factory: TempPathFactory) -> Generator[Path]: path = tmp_path_factory.mktemp("path")- self.setuptestfs(path)+ TestImportPath.setuptestfs(path) yield path assert path.joinpath("samplefile").exists() @@ -141,7 +142,8 @@ class TestImportPath: with unittest.mock.patch.object(sys, "path", list(sys.path)): yield - def setuptestfs(self, path: Path) -> None:+ @staticmethod+ def setuptestfs(path: Path) -> None: # print "setting up test fs for", repr(path) samplefile = path / "samplefile" samplefile.write_text("samplefile\n", encoding="utf-8")
changelog/14774.deprecation.rstnew file mode 100644index 000000000..fa9c6ca4c@@ -0,0 +1,6 @@+Similarly to the deprecation of class-scoped fixtures defined as instance methods in pytest 9.1,+*all* higher-scoped fixtures (``module``, ``package``, and ``session``) defined+as instance methods are now deprecated.++They suffer from the same issue the original deprecation only fixed for+class-scoped fixtures, see :issue:`10819` and :issue:`14011`.doc/en/deprecations.rstindex feaeaa097..005d50081 100644@@ -276,6 +276,11 @@ test class for each test method, while the fixture runs only once per class on a Using ``@classmethod`` ensures attributes are set on the class itself, making them accessible to all test methods. +.. deprecated:: 9.2++Similarly, using a scope higher than ``class`` (``module``, ``package`` or ``session``)+without using ``@classmethod`` (or ``@staticmethod``) is deprecated and will be+removed in pytest 10.0. .. _monkeypatch-fixup-namespace-packages: src/_pytest/deprecated.pyindex f46b036af..860ec4065 100644@@ -36,7 +36,7 @@ YIELD_FIXTURE = PytestDeprecationWarning( CLASS_FIXTURE_INSTANCE_METHOD = UnformattedWarning( PytestRemovedIn10Warning,- "Class-scoped fixtures defined as instance methods are deprecated.\n"+ "{scope}-scoped fixtures defined as instance methods are deprecated.\n" "Instance attributes set in the {fixturename!r} fixture will NOT be visible to test methods,\n" "as each test gets a new instance while the fixture runs only once per class.\n" "Use a @classmethod decorator below @pytest.fixture and set attributes on cls instead.\n"src/_pytest/fixtures.pyindex 3f1964f2d..288bb7b20 100644@@ -1284,7 +1284,7 @@ def resolve_fixture_function( # as expected. instance = request.instance - if fixturedef._scope is Scope.Class:+ if fixturedef._scope >= Scope.Class: # Check if fixture is an instance method (bound to instance, not class) if hasattr(fixturefunc, "__self__"): bound_to = fixturefunc.__self__@@ -1293,7 +1293,8 @@ def resolve_fixture_function( if not isinstance(bound_to, type): warnings.warn( CLASS_FIXTURE_INSTANCE_METHOD.format(- fixturename=request.fixturename+ scope=fixturedef._scope.name.capitalize(),+ fixturename=request.fixturename, ), stacklevel=2, )testing/deprecated_test.pyindex 8eed1fb31..637a5c698 100644@@ -3,6 +3,7 @@ from __future__ import annotations from _pytest import deprecated from _pytest.pytester import Pytester+from _pytest.scope import Scope import pytest from pytest import PytestDeprecationWarning @@ -87,13 +88,18 @@ def test_private_is_deprecated() -> None: PrivateInit(10, _ispytest=True) -def test_class_scope_instance_method_is_deprecated(pytester: Pytester) -> None:+@pytest.mark.parametrize(+ "scope", [Scope.Class, Scope.Module, Scope.Package, Scope.Session]+)+def test_higher_scope_instance_method_is_deprecated(+ pytester: Pytester, scope: Scope+) -> None: pytester.makepyfile(- """+ f""" import pytest class TestClass:- @pytest.fixture(scope="class")+ @pytest.fixture(scope="{scope.value}") def fix(self): self.attr = True @@ -104,20 +110,23 @@ def test_class_scope_instance_method_is_deprecated(pytester: Pytester) -> None: result = pytester.runpytest("-Werror::pytest.PytestRemovedIn10Warning") result.assert_outcomes(errors=1) result.stdout.fnmatch_lines(- [- "*PytestRemovedIn10Warning: Class-scoped fixtures defined as instance methods*"- ]+ ["*PytestRemovedIn10Warning: *-scoped fixtures defined as instance methods*"] ) -def test_class_scope_classmethod_fixture_not_deprecated(pytester: Pytester) -> None:- """A class-scoped fixture defined as @classmethod does NOT warn."""+@pytest.mark.parametrize(+ "scope", [Scope.Class, Scope.Module, Scope.Package, Scope.Session]+)+def test_higher_scope_classmethod_fixture_not_deprecated(+ pytester: Pytester, scope: Scope+) -> None:+ """A higher-scoped fixture defined as @classmethod does NOT warn.""" pytester.makepyfile(- """+ f""" import pytest class TestClass:- @pytest.fixture(scope="class")+ @pytest.fixture(scope="{scope.value}") @classmethod def fix(cls): cls.attr = True@@ -130,6 +139,27 @@ def test_class_scope_classmethod_fixture_not_deprecated(pytester: Pytester) -> N result.assert_outcomes(passed=1) +@pytest.mark.parametrize("scope", list(Scope))+def test_staticmethod_fixture_not_deprecated(pytester: Pytester, scope: Scope) -> None:+ """A fixture at any scope defined as @staticmethod does NOT warn."""+ pytester.makepyfile(+ f"""+ import pytest++ class TestClass:+ @pytest.fixture(scope="{scope.value}")+ @staticmethod+ def fix():+ pass++ def test_foo(self, fix):+ pass+ """+ )+ result = pytester.runpytest("-Werror::pytest.PytestRemovedIn10Warning")+ result.assert_outcomes(passed=1)++ class TestFixtureNodeidDeprecations: """Tests for deprecated baseid/nodeid string APIs in fixture registration. testing/python/fixtures.pyindex 69044226b..7327eab09 100644@@ -1292,7 +1292,8 @@ class TestRequestBasic: class TestRequestSessionScoped: @pytest.fixture(scope="session")- def session_request(self, request):+ @staticmethod+ def session_request(request): return request @pytest.mark.parametrize("name", ["path", "module"])testing/test_conftest.pyindex 38363a3ba..b5df08c78 100644@@ -43,7 +43,8 @@ def conftest_setinitial( @pytest.mark.usefixtures("_sys_snapshot") class TestConftestValueAccessGlobal: @pytest.fixture(scope="module", params=["global", "inpackage"])- def basedir(self, request, tmp_path_factory: TempPathFactory) -> Generator[Path]:+ @staticmethod+ def basedir(request, tmp_path_factory: TempPathFactory) -> Generator[Path]: tmp_path = tmp_path_factory.mktemp("basedir", numbered=True) tmp_path.joinpath("adir/b").mkdir(parents=True) tmp_path.joinpath("adir/conftest.py").write_text(testing/test_legacypath.pyindex 3e71e6b19..c80ec89a8 100644@@ -102,7 +102,8 @@ def test_fixturerequest_getmodulepath(pytester: pytest.Pytester) -> None: class TestFixtureRequestSessionScoped: @pytest.fixture(scope="session")- def session_request(self, request):+ @staticmethod+ def session_request(request): return request def test_session_scoped_unavailable_attributes(self, session_request):testing/test_pathlib.pyindex bd85b7e8f..787d3e5e8 100644@@ -129,9 +129,10 @@ class TestImportPath: """ @pytest.fixture(scope="session")- def path1(self, tmp_path_factory: TempPathFactory) -> Generator[Path]:+ @classmethod+ def path1(cls, tmp_path_factory: TempPathFactory) -> Generator[Path]: path = tmp_path_factory.mktemp("path")- self.setuptestfs(path)+ cls.setuptestfs(path) yield path assert path.joinpath("samplefile").exists() @@ -141,7 +142,8 @@ class TestImportPath: with unittest.mock.patch.object(sys, "path", list(sys.path)): yield - def setuptestfs(self, path: Path) -> None:+ @staticmethod+ def setuptestfs(path: Path) -> None: # print "setting up test fs for", repr(path) samplefile = path / "samplefile" samplefile.write_text("samplefile\n", encoding="utf-8")