From 9a1c8b31c729b72122f4307680f1be274ac7c999 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Tue, 5 Dec 2023 13:39:43 +0100 Subject: [PATCH] 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 cfd16d0dac1c935952b892bfbc225978c9b25de3 where this was originally implemented. --- src/_pytest/fixtures.py | 2 +- testing/python/fixtures.py | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/_pytest/fixtures.py b/src/_pytest/fixtures.py index d56274629..c9a8a75b4 100644 --- a/src/_pytest/fixtures.py +++ b/src/_pytest/fixtures.py @@ -1203,7 +1203,7 @@ class FixtureFunctionMarker: 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"): diff --git a/testing/python/fixtures.py b/testing/python/fixtures.py index 775056a8e..66a5daf50 100644 --- a/testing/python/fixtures.py +++ b/testing/python/fixtures.py @@ -4354,6 +4354,23 @@ def test_call_fixture_function_error(): 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(