Skip to content

Commit 1803521

Browse files
committed
Use safe_str() to format warning message about unicode in Python 2
Fix pytest-dev#3691
1 parent e4871f7 commit 1803521

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

changelog/3691.bugfix.rst

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Python 2: safely format warning message about passing unicode strings to ``warnings.warn``, which may cause
2+
surprising ``MemoryError`` exception when monkey patching ``warnings.warn`` itself.

src/_pytest/warnings.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ def warning_record_to_str(warning_message):
123123
if unicode_warning:
124124
warnings.warn(
125125
"Warning is using unicode non convertible to ascii, "
126-
"converting to a safe representation:\n %s" % msg,
126+
"converting to a safe representation:\n {!r}".format(compat.safe_str(msg)),
127127
UnicodeWarning,
128128
)
129129
return msg

testing/test_warnings.py

+29
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33

44
import sys
55

6+
import six
7+
68
import pytest
79

810

@@ -562,3 +564,30 @@ def test_hidden_by_system(self, testdir, monkeypatch):
562564
monkeypatch.setenv(str("PYTHONWARNINGS"), str("once::UserWarning"))
563565
result = testdir.runpytest_subprocess()
564566
assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()
567+
568+
569+
@pytest.mark.skipif(six.PY3, reason="Python 2 only issue")
570+
def test_infinite_loop_warning_against_unicode_usage_py2(testdir):
571+
"""
572+
We need to be careful when raising the warning about unicode usage with "warnings.warn"
573+
because it might be overwritten by users and this itself causes another warning (#3691).
574+
"""
575+
testdir.makepyfile(
576+
"""
577+
# -*- coding: utf8 -*-
578+
from __future__ import unicode_literals
579+
import warnings
580+
import pytest
581+
582+
def _custom_showwarning(message, *a, **b):
583+
return "WARNING: {}".format(message)
584+
585+
warnings.formatwarning = _custom_showwarning
586+
587+
@pytest.mark.filterwarnings("default")
588+
def test_custom_warning_formatter():
589+
warnings.warn("¥")
590+
"""
591+
)
592+
result = testdir.runpytest_subprocess()
593+
result.stdout.fnmatch_lines(["*1 passed, * warnings in*"])

0 commit comments

Comments
 (0)