Skip to content

Commit

Permalink
Raises an error when a fixture conflict for the same file
Browse files Browse the repository at this point in the history
  • Loading branch information
dongfangtianyu committed Dec 13, 2024
1 parent 28e1e25 commit 2378a99
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/12953.improvement.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
When creating a fixture with the same name in different ways in the same file, an error is now raised.
14 changes: 14 additions & 0 deletions src/_pytest/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -1728,6 +1728,20 @@ def _register_fixture(
)

faclist = self._arg2fixturedefs.setdefault(name, [])

by_plugin = fixture_def.baseid == ""

if not by_plugin and faclist:
# If the fixture from a plugin, no conflict detection is performed.
if faclist[-1].baseid == fixture_def.baseid:
# The same file may create two fixtures with the same name (#12952).
msg = (

Check warning on line 1738 in src/_pytest/fixtures.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/fixtures.py#L1738

Added line #L1738 was not covered by tests
f"Fixture definition conflict: {name!r} has multiple implementations,"
f"namely {faclist[-1].func!r} and {func} (from: {nodeid!r})."
)
print(msg)
raise ValueError(msg)

Check warning on line 1743 in src/_pytest/fixtures.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/fixtures.py#L1742-L1743

Added lines #L1742 - L1743 were not covered by tests

if fixture_def.has_location:
faclist.append(fixture_def)
else:
Expand Down
23 changes: 23 additions & 0 deletions testing/python/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -5009,3 +5009,26 @@ def test_result():
)
result = pytester.runpytest()
assert result.ret == 0


def test_fixture_name_conflict(pytester: Pytester) -> None:
"""The same file may create two fixtures with the same name, but not override(#12952)."""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(name="cache")
def c1(): # Create first, but register later
return 1
@pytest.fixture(name="cache") # Create later, but register first
def c0():
return 0
def test_value(cache):
assert cache == 0 # Failed, `cache` from c1
"""
)

result = pytester.runpytest()
result.stdout.fnmatch_lines(["E ValueError: Fixture definition conflict:*"])

0 comments on commit 2378a99

Please sign in to comment.