Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix #4243 - support positional argument stacklevel on python2 #4244

Merged
merged 1 commit into from
Oct 26, 2018
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/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