Skip to content

Commit

Permalink
fix #4243 - support positional argument stacklevel on python2
Browse files Browse the repository at this point in the history
  • Loading branch information
RonnyPfannschmidt committed Oct 26, 2018
1 parent 041044e commit ce0b051
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
1 change: 1 addition & 0 deletions changelog/4243.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix regression when ``stacklevel`` for warnings was passed as positional argument on python2.
18 changes: 12 additions & 6 deletions src/_pytest/recwarn.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,21 +156,27 @@ def __enter__(self):
# trivial patching of `warnings.warn` seems to be enough somehow?
if six.PY2:

def warn(*args, **kwargs):
kwargs.setdefault("stacklevel", 1)
kwargs["stacklevel"] += 1
def warn(message, category=None, stacklevel=1):
# duplicate the stdlib logic due to
# bad handing in the c version of warnings
if isinstance(message, Warning):
category = message.__class__
# Check category argument
if category is None:
category = UserWarning
assert issubclass(category, Warning)

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

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 @@ -46,6 +46,12 @@ def test_recording(self):
assert values is rec.list
pytest.raises(AssertionError, "rec.pop()")

@pytest.mark.issue(4243)
def test_warn_stacklevel(self):
rec = WarningsRecorder()
with rec:
warnings.warn("test", DeprecationWarning, 2)

def test_typechecking(self):
from _pytest.recwarn import WarningsChecker

Expand Down

0 comments on commit ce0b051

Please sign in to comment.