Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh my, not sure if the medicine might be worse than the disease... 😛

(Not to bad talk your implementation, I just fear this might pop other bugs)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeahhhhhhh. I had a similar feeling. That said, this is basically what the warnings module itself does. And this only would be for python 2

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


# 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