Skip to content

Commit f160963

Browse files
feat: issue PytestCollectionWarning when tests used pytest.fixrure
1 parent 949c771 commit f160963

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

changelog/12989.improvement.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
A warning is now issued when tests incorrectly use :class:`@pytest.fixture`, whereas this was previously silently ignored.

src/_pytest/python.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,16 @@ def classnamefilter(self, name: str) -> bool:
354354

355355
def istestfunction(self, obj: object, name: str) -> bool:
356356
if self.funcnamefilter(name) or self.isnosetest(obj):
357+
if isinstance(obj, fixtures.FixtureFunctionDefinition):
358+
self.warn(
359+
PytestCollectionWarning(
360+
f"cannot collect test function {name!r},"
361+
f"because it used the '@pytest.fixture' than becomes a fixture "
362+
f"(from: {self.nodeid})"
363+
)
364+
)
365+
return False
366+
357367
if isinstance(obj, (staticmethod, classmethod)):
358368
# staticmethods and classmethods need to be unwrapped.
359369
obj = safe_getattr(obj, "__func__", False)

testing/python/collect.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -783,6 +783,26 @@ def test_function_with_square_brackets(self, pytester: Pytester) -> None:
783783
]
784784
)
785785

786+
@pytest.mark.filterwarnings("default::UserWarning")
787+
def test_function_used_fixture(self, pytester: Pytester):
788+
pytester.makeini("[pytest]")
789+
pytester.makepyfile(
790+
"""
791+
import pytest
792+
@pytest.fixture
793+
def test_function():
794+
pass
795+
"""
796+
)
797+
result = pytester.runpytest()
798+
result.stdout.fnmatch_lines(
799+
[
800+
"collected 0 items",
801+
"*== warnings summary ==*",
802+
"*because it used the '@pytest.fixture' than becomes a fixture*",
803+
]
804+
)
805+
786806

787807
class TestSorting:
788808
def test_check_equality(self, pytester: Pytester) -> None:

0 commit comments

Comments
 (0)