Skip to content

Commit

Permalink
Merge pull request #4192 from asottile/fix_recwarn_stacklevel
Browse files Browse the repository at this point in the history
Fix filename reported by `warnings.warn` when using `recwarn` under python2.
  • Loading branch information
asottile committed Oct 18, 2018
2 parents e4871f7 + cdd0e18 commit 61080da
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/4192.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix filename reported by ``warnings.warn`` when using ``recwarn`` under python2.
15 changes: 14 additions & 1 deletion src/_pytest/recwarn.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,20 @@ def __enter__(self):
if six.PY2:

def warn(*args, **kwargs):
return self._saved_warn(*args, **kwargs)
kwargs.setdefault("stacklevel", 1)
kwargs["stacklevel"] += 1

# emulate resetting the warn registry
f_globals = sys._getframe(kwargs["stacklevel"] - 1).f_globals
if "__warningregistry__" in f_globals:
orig = f_globals["__warningregistry__"]
f_globals["__warningregistry__"] = None
try:
return self._saved_warn(*args, **kwargs)
finally:
f_globals["__warningregistry__"] = orig
else:
return self._saved_warn(*args, **kwargs)

warnings.warn, self._saved_warn = warn, warnings.warn
return self
Expand Down
6 changes: 6 additions & 0 deletions testing/test_recwarn.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@
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(
"""
Expand Down

0 comments on commit 61080da

Please sign in to comment.