Skip to content

Commit 78a1938

Browse files
committed
Extend instance method fixture deprecation to all higher scopes
The original deprecation in #14071 only targetted class-scoped fixtures, but the same issue exists if someone implements a module/package/session-scoped fixture as an instance method. Closes #14765
1 parent ced9022 commit 78a1938

9 files changed

Lines changed: 66 additions & 19 deletions

File tree

‎changelog/14774.deprecation.rst‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Similarly to the deprecation of class-scoped fixtures defined as instance methods in pytest 9.1,
2+
*all* higher-scoped fixtures (``module``, ``package``, and ``session``) defined
3+
as instance methods are now deprecated.
4+
5+
They suffer from the same issue the original deprecation only fixed for
6+
class-scoped fixtures, see :issue:`10819` and :issue:`14011`.

‎doc/en/deprecations.rst‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,11 @@ test class for each test method, while the fixture runs only once per class on a
276276
Using ``@classmethod`` ensures attributes are set on the class itself, making them accessible
277277
to all test methods.
278278

279+
.. deprecated:: 9.2
280+
281+
Similarly, using a scope higher than ``class`` (``module``, ``package`` or ``session``)
282+
without using ``@classmethod`` (or ``@staticmethod``) is deprecated and will be
283+
removed in pytest 10.0.
279284

280285
.. _monkeypatch-fixup-namespace-packages:
281286

‎src/_pytest/deprecated.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636

3737
CLASS_FIXTURE_INSTANCE_METHOD = UnformattedWarning(
3838
PytestRemovedIn10Warning,
39-
"Class-scoped fixtures defined as instance methods are deprecated.\n"
39+
"{scope}-scoped fixtures defined as instance methods are deprecated.\n"
4040
"Instance attributes set in the {fixturename!r} fixture will NOT be visible to test methods,\n"
4141
"as each test gets a new instance while the fixture runs only once per class.\n"
4242
"Use a @classmethod decorator below @pytest.fixture and set attributes on cls instead.\n"

‎src/_pytest/fixtures.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1284,7 +1284,7 @@ def __tracebackhide__(e):
12841284
# as expected.
12851285
instance = request.instance
12861286

1287-
if fixturedef._scope is Scope.Class:
1287+
if fixturedef._scope >= Scope.Class:
12881288
# Check if fixture is an instance method (bound to instance, not class)
12891289
if hasattr(fixturefunc, "__self__"):
12901290
bound_to = fixturefunc.__self__
@@ -1293,7 +1293,8 @@ def __tracebackhide__(e):
12931293
if not isinstance(bound_to, type):
12941294
warnings.warn(
12951295
CLASS_FIXTURE_INSTANCE_METHOD.format(
1296-
fixturename=request.fixturename
1296+
scope=fixturedef._scope.name.capitalize(),
1297+
fixturename=request.fixturename,
12971298
),
12981299
stacklevel=2,
12991300
)

‎testing/deprecated_test.py‎

Lines changed: 40 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from _pytest import deprecated
55
from _pytest.pytester import Pytester
6+
from _pytest.scope import Scope
67
import pytest
78
from pytest import PytestDeprecationWarning
89

@@ -87,13 +88,18 @@ def __init__(self, foo: int, *, _ispytest: bool = False) -> None:
8788
PrivateInit(10, _ispytest=True)
8889

8990

90-
def test_class_scope_instance_method_is_deprecated(pytester: Pytester) -> None:
91+
@pytest.mark.parametrize(
92+
"scope", [Scope.Class, Scope.Module, Scope.Package, Scope.Session]
93+
)
94+
def test_higher_scope_instance_method_is_deprecated(
95+
pytester: Pytester, scope: Scope
96+
) -> None:
9197
pytester.makepyfile(
92-
"""
98+
f"""
9399
import pytest
94100
95101
class TestClass:
96-
@pytest.fixture(scope="class")
102+
@pytest.fixture(scope="{scope.value}")
97103
def fix(self):
98104
self.attr = True
99105
@@ -104,20 +110,23 @@ def test_foo(self, fix):
104110
result = pytester.runpytest("-Werror::pytest.PytestRemovedIn10Warning")
105111
result.assert_outcomes(errors=1)
106112
result.stdout.fnmatch_lines(
107-
[
108-
"*PytestRemovedIn10Warning: Class-scoped fixtures defined as instance methods*"
109-
]
113+
["*PytestRemovedIn10Warning: *-scoped fixtures defined as instance methods*"]
110114
)
111115

112116

113-
def test_class_scope_classmethod_fixture_not_deprecated(pytester: Pytester) -> None:
114-
"""A class-scoped fixture defined as @classmethod does NOT warn."""
117+
@pytest.mark.parametrize(
118+
"scope", [Scope.Class, Scope.Module, Scope.Package, Scope.Session]
119+
)
120+
def test_higher_scope_classmethod_fixture_not_deprecated(
121+
pytester: Pytester, scope: Scope
122+
) -> None:
123+
"""A higher-scoped fixture defined as @classmethod does NOT warn."""
115124
pytester.makepyfile(
116-
"""
125+
f"""
117126
import pytest
118127
119128
class TestClass:
120-
@pytest.fixture(scope="class")
129+
@pytest.fixture(scope="{scope.value}")
121130
@classmethod
122131
def fix(cls):
123132
cls.attr = True
@@ -130,6 +139,27 @@ def test_foo(self, fix):
130139
result.assert_outcomes(passed=1)
131140

132141

142+
@pytest.mark.parametrize("scope", list(Scope))
143+
def test_staticmethod_fixture_not_deprecated(pytester: Pytester, scope: Scope) -> None:
144+
"""A fixture at any scope defined as @staticmethod does NOT warn."""
145+
pytester.makepyfile(
146+
f"""
147+
import pytest
148+
149+
class TestClass:
150+
@pytest.fixture(scope="{scope.value}")
151+
@staticmethod
152+
def fix():
153+
pass
154+
155+
def test_foo(self, fix):
156+
pass
157+
"""
158+
)
159+
result = pytester.runpytest("-Werror::pytest.PytestRemovedIn10Warning")
160+
result.assert_outcomes(passed=1)
161+
162+
133163
class TestFixtureNodeidDeprecations:
134164
"""Tests for deprecated baseid/nodeid string APIs in fixture registration.
135165

‎testing/python/fixtures.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1292,7 +1292,8 @@ def test_1(arg):
12921292

12931293
class TestRequestSessionScoped:
12941294
@pytest.fixture(scope="session")
1295-
def session_request(self, request):
1295+
@staticmethod
1296+
def session_request(request):
12961297
return request
12971298

12981299
@pytest.mark.parametrize("name", ["path", "module"])

‎testing/test_conftest.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,8 @@ def conftest_setinitial(
4343
@pytest.mark.usefixtures("_sys_snapshot")
4444
class TestConftestValueAccessGlobal:
4545
@pytest.fixture(scope="module", params=["global", "inpackage"])
46-
def basedir(self, request, tmp_path_factory: TempPathFactory) -> Generator[Path]:
46+
@staticmethod
47+
def basedir(request, tmp_path_factory: TempPathFactory) -> Generator[Path]:
4748
tmp_path = tmp_path_factory.mktemp("basedir", numbered=True)
4849
tmp_path.joinpath("adir/b").mkdir(parents=True)
4950
tmp_path.joinpath("adir/conftest.py").write_text(

‎testing/test_legacypath.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,8 @@ def test_fixturerequest_getmodulepath(pytester: pytest.Pytester) -> None:
102102

103103
class TestFixtureRequestSessionScoped:
104104
@pytest.fixture(scope="session")
105-
def session_request(self, request):
105+
@staticmethod
106+
def session_request(request):
106107
return request
107108

108109
def test_session_scoped_unavailable_attributes(self, session_request):

‎testing/test_pathlib.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,10 @@ class TestImportPath:
129129
"""
130130

131131
@pytest.fixture(scope="session")
132-
def path1(self, tmp_path_factory: TempPathFactory) -> Generator[Path]:
132+
@classmethod
133+
def path1(cls, tmp_path_factory: TempPathFactory) -> Generator[Path]:
133134
path = tmp_path_factory.mktemp("path")
134-
self.setuptestfs(path)
135+
cls.setuptestfs(path)
135136
yield path
136137
assert path.joinpath("samplefile").exists()
137138

@@ -141,7 +142,8 @@ def preserve_sys(self):
141142
with unittest.mock.patch.object(sys, "path", list(sys.path)):
142143
yield
143144

144-
def setuptestfs(self, path: Path) -> None:
145+
@staticmethod
146+
def setuptestfs(path: Path) -> None:
145147
# print "setting up test fs for", repr(path)
146148
samplefile = path / "samplefile"
147149
samplefile.write_text("samplefile\n", encoding="utf-8")

0 commit comments

Comments
 (0)