From 1640f2e4544e63da6bf7c6587040897ca0810770 Mon Sep 17 00:00:00 2001 From: Eric Larson Date: Fri, 23 Feb 2024 01:11:05 -0500 Subject: [PATCH] ENH: Improve warning stacklevel (#12014) * ENH: Improve warning stacklevel * TST: Add test * TST: Ping * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * MAINT: Changelog --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- changelog/12014.bugfix.rst | 1 + src/_pytest/mark/structures.py | 6 +++--- testing/deprecated_test.py | 2 ++ 3 files changed, 6 insertions(+), 3 deletions(-) create mode 100644 changelog/12014.bugfix.rst diff --git a/changelog/12014.bugfix.rst b/changelog/12014.bugfix.rst new file mode 100644 index 000000000..344bf8b7e --- /dev/null +++ b/changelog/12014.bugfix.rst @@ -0,0 +1 @@ +Fix the ``stacklevel`` used when warning about marks used on fixtures. diff --git a/src/_pytest/mark/structures.py b/src/_pytest/mark/structures.py index 5a7f9b202..1da300c82 100644 --- a/src/_pytest/mark/structures.py +++ b/src/_pytest/mark/structures.py @@ -355,7 +355,7 @@ class MarkDecorator: func = args[0] is_class = inspect.isclass(func) if len(args) == 1 and (istestfunc(func) or is_class): - store_mark(func, self.mark) + store_mark(func, self.mark, stacklevel=3) return func return self.with_args(*args, **kwargs) @@ -410,7 +410,7 @@ def normalize_mark_list( yield mark_obj -def store_mark(obj, mark: Mark) -> None: +def store_mark(obj, mark: Mark, *, stacklevel: int = 2) -> None: """Store a Mark on an object. This is used to implement the Mark declarations/decorators correctly. @@ -420,7 +420,7 @@ def store_mark(obj, mark: Mark) -> None: from ..fixtures import getfixturemarker if getfixturemarker(obj) is not None: - warnings.warn(MARKED_FIXTURE, stacklevel=2) + warnings.warn(MARKED_FIXTURE, stacklevel=stacklevel) # Always reassign name to avoid updating pytestmark in a reference that # was only borrowed. diff --git a/testing/deprecated_test.py b/testing/deprecated_test.py index 52752d4e8..a5f513063 100644 --- a/testing/deprecated_test.py +++ b/testing/deprecated_test.py @@ -118,6 +118,8 @@ def test_fixture_disallow_marks_on_fixtures(): raise NotImplementedError() assert len(record) == 2 # one for each mark decorator + # should point to this file + assert all(rec.filename == __file__ for rec in record) def test_fixture_disallowed_between_marks():