Skip to content

Commit 1640f2e

Browse files
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>
1 parent 59e9a58 commit 1640f2e

File tree

3 files changed

+6
-3
lines changed

3 files changed

+6
-3
lines changed

changelog/12014.bugfix.rst

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix the ``stacklevel`` used when warning about marks used on fixtures.

src/_pytest/mark/structures.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,7 @@ def __call__(self, *args: object, **kwargs: object):
355355
func = args[0]
356356
is_class = inspect.isclass(func)
357357
if len(args) == 1 and (istestfunc(func) or is_class):
358-
store_mark(func, self.mark)
358+
store_mark(func, self.mark, stacklevel=3)
359359
return func
360360
return self.with_args(*args, **kwargs)
361361

@@ -410,7 +410,7 @@ def normalize_mark_list(
410410
yield mark_obj
411411

412412

413-
def store_mark(obj, mark: Mark) -> None:
413+
def store_mark(obj, mark: Mark, *, stacklevel: int = 2) -> None:
414414
"""Store a Mark on an object.
415415
416416
This is used to implement the Mark declarations/decorators correctly.
@@ -420,7 +420,7 @@ def store_mark(obj, mark: Mark) -> None:
420420
from ..fixtures import getfixturemarker
421421

422422
if getfixturemarker(obj) is not None:
423-
warnings.warn(MARKED_FIXTURE, stacklevel=2)
423+
warnings.warn(MARKED_FIXTURE, stacklevel=stacklevel)
424424

425425
# Always reassign name to avoid updating pytestmark in a reference that
426426
# was only borrowed.

testing/deprecated_test.py

+2
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,8 @@ def foo():
118118
raise NotImplementedError()
119119

120120
assert len(record) == 2 # one for each mark decorator
121+
# should point to this file
122+
assert all(rec.filename == __file__ for rec in record)
121123

122124

123125
def test_fixture_disallowed_between_marks():

0 commit comments

Comments
 (0)