Skip to content

Commit

Permalink
Improve error message when using @pytest.fixture twice (#11670)
Browse files Browse the repository at this point in the history
* Improve error message when using @pytest.fixture twice

While obvious in hindsight, this error message confused me. I thought my fixture
function was used in a test function twice, since the wording is ambiguous.

Also, the error does not tell me *which* function is the culprit.

Finally, this adds a test, which wasn't done in
cfd16d0 where this was originally implemented.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
The-Compiler and pre-commit-ci[bot] committed Feb 9, 2024
1 parent 29a5f94 commit 7690a0d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/_pytest/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -1188,7 +1188,7 @@ def __call__(self, function: FixtureFunction) -> FixtureFunction:

if getattr(function, "_pytestfixturefunction", False):
raise ValueError(
"fixture is being applied more than once to the same function"
f"@pytest.fixture is being applied more than once to the same function {function.__name__!r}"
)

if hasattr(function, "pytestmark"):
Expand Down
21 changes: 21 additions & 0 deletions testing/python/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -4353,6 +4353,27 @@ def fix():
assert fix() == 1


def test_fixture_double_decorator(pytester: Pytester) -> None:
"""Check if an error is raised when using @pytest.fixture twice."""
pytester.makepyfile(
"""
import pytest
@pytest.fixture
@pytest.fixture
def fixt():
pass
"""
)
result = pytester.runpytest()
result.assert_outcomes(errors=1)
result.stdout.fnmatch_lines(
[
"E * ValueError: @pytest.fixture is being applied more than once to the same function 'fixt'"
]
)


def test_fixture_param_shadowing(pytester: Pytester) -> None:
"""Parametrized arguments would be shadowed if a fixture with the same name also exists (#5036)"""
pytester.makepyfile(
Expand Down

0 comments on commit 7690a0d

Please sign in to comment.