diff --git a/src/_pytest/recwarn.py b/src/_pytest/recwarn.py index 62c9158fb..5adc42d26 100644 --- a/src/_pytest/recwarn.py +++ b/src/_pytest/recwarn.py @@ -156,6 +156,8 @@ class WarningsRecorder(warnings.catch_warnings): if six.PY2: def warn(*args, **kwargs): + kwargs.setdefault("stacklevel", 1) + kwargs["stacklevel"] += 1 return self._saved_warn(*args, **kwargs) warnings.warn, self._saved_warn = warn, warnings.warn diff --git a/testing/test_recwarn.py b/testing/test_recwarn.py index 3ae543248..e1d44f174 100644 --- a/testing/test_recwarn.py +++ b/testing/test_recwarn.py @@ -6,6 +6,12 @@ import pytest from _pytest.recwarn import WarningsRecorder +def test_recwarn_stacklevel(recwarn): + warnings.warn("hello") + warn = recwarn.pop() + assert warn.filename == __file__ + + def test_recwarn_functional(testdir): testdir.makepyfile( """