Skip to content

Commit 113339b

Browse files
committed
terminalwriter: bring back handling of printing characters not supported by stdout
1 parent d466cc2 commit 113339b

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

src/_pytest/_io/terminalwriter.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,18 @@ def write(self, msg: str, *, flush: bool = False, **markup: bool) -> None:
149149

150150
msg = self.markup(msg, **markup)
151151

152-
self._file.write(msg)
152+
try:
153+
self._file.write(msg)
154+
except UnicodeEncodeError:
155+
# Some environments don't support printing general Unicode
156+
# strings, due to misconfiguration or otherwise; in that case,
157+
# print the string escaped to ASCII.
158+
# When the Unicode situation improves we should consider
159+
# letting the error propagate instead of masking it (see #7475
160+
# for one brief attempt).
161+
msg = msg.encode("unicode-escape").decode("ascii")
162+
self._file.write(msg)
163+
153164
if flush:
154165
self.flush()
155166

testing/io/test_terminalwriter.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,15 @@ def isatty(self):
4949
assert not tw.hasmarkup
5050

5151

52+
def test_terminalwriter_not_unicode() -> None:
53+
"""If the file doesn't support Unicode, the string is unicode-escaped (#7475)."""
54+
buffer = io.BytesIO()
55+
file = io.TextIOWrapper(buffer, encoding="cp1252")
56+
tw = terminalwriter.TerminalWriter(file)
57+
tw.write("hello 🌀 wôrld אבג", flush=True)
58+
assert buffer.getvalue() == br"hello \U0001f300 w\xf4rld \u05d0\u05d1\u05d2"
59+
60+
5261
win32 = int(sys.platform == "win32")
5362

5463

0 commit comments

Comments
 (0)