Merge pull request #4192 from asottile/fix_recwarn_stacklevel
Fix filename reported by `warnings.warn` when using `recwarn` under python2.
This commit is contained in:
commit
61080da89d
|
@ -0,0 +1 @@
|
|||
Fix filename reported by ``warnings.warn`` when using ``recwarn`` under python2.
|
|
@ -156,7 +156,20 @@ class WarningsRecorder(warnings.catch_warnings):
|
|||
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
|
||||
|
|
|
@ -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(
|
||||
"""
|
||||
|
|
Loading…
Reference in New Issue