Skip to content

Commit 2378a99

Browse files
Raises an error when a fixture conflict for the same file
1 parent 28e1e25 commit 2378a99

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

changelog/12953.improvement.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
When creating a fixture with the same name in different ways in the same file, an error is now raised.

src/_pytest/fixtures.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1728,6 +1728,20 @@ def _register_fixture(
17281728
)
17291729

17301730
faclist = self._arg2fixturedefs.setdefault(name, [])
1731+
1732+
by_plugin = fixture_def.baseid == ""
1733+
1734+
if not by_plugin and faclist:
1735+
# If the fixture from a plugin, no conflict detection is performed.
1736+
if faclist[-1].baseid == fixture_def.baseid:
1737+
# The same file may create two fixtures with the same name (#12952).
1738+
msg = (
1739+
f"Fixture definition conflict: {name!r} has multiple implementations,"
1740+
f"namely {faclist[-1].func!r} and {func} (from: {nodeid!r})."
1741+
)
1742+
print(msg)
1743+
raise ValueError(msg)
1744+
17311745
if fixture_def.has_location:
17321746
faclist.append(fixture_def)
17331747
else:

testing/python/fixtures.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5009,3 +5009,26 @@ def test_result():
50095009
)
50105010
result = pytester.runpytest()
50115011
assert result.ret == 0
5012+
5013+
5014+
def test_fixture_name_conflict(pytester: Pytester) -> None:
5015+
"""The same file may create two fixtures with the same name, but not override(#12952)."""
5016+
pytester.makepyfile(
5017+
"""
5018+
import pytest
5019+
5020+
@pytest.fixture(name="cache")
5021+
def c1(): # Create first, but register later
5022+
return 1
5023+
5024+
@pytest.fixture(name="cache") # Create later, but register first
5025+
def c0():
5026+
return 0
5027+
5028+
def test_value(cache):
5029+
assert cache == 0 # Failed, `cache` from c1
5030+
"""
5031+
)
5032+
5033+
result = pytester.runpytest()
5034+
result.stdout.fnmatch_lines(["E ValueError: Fixture definition conflict:*"])

0 commit comments

Comments
 (0)