Skip to content

terminalwriter: bring back handling of printing characters not supported by stdout #7481

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

Merged
merged 1 commit into from
Jul 11, 2020
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
13 changes: 12 additions & 1 deletion src/_pytest/_io/terminalwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,18 @@ def write(self, msg: str, *, flush: bool = False, **markup: bool) -> None:

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

self._file.write(msg)
try:
self._file.write(msg)
except UnicodeEncodeError:
# Some environments don't support printing general Unicode
# strings, due to misconfiguration or otherwise; in that case,
# print the string escaped to ASCII.
# When the Unicode situation improves we should consider
# letting the error propagate instead of masking it (see #7475
# for one brief attempt).
msg = msg.encode("unicode-escape").decode("ascii")
self._file.write(msg)

if flush:
self.flush()

Expand Down
9 changes: 9 additions & 0 deletions testing/io/test_terminalwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,15 @@ def isatty(self):
assert not tw.hasmarkup


def test_terminalwriter_not_unicode() -> None:
"""If the file doesn't support Unicode, the string is unicode-escaped (#7475)."""
buffer = io.BytesIO()
file = io.TextIOWrapper(buffer, encoding="cp1252")
tw = terminalwriter.TerminalWriter(file)
tw.write("hello 🌀 wôrld אבג", flush=True)
assert buffer.getvalue() == br"hello \U0001f300 w\xf4rld \u05d0\u05d1\u05d2"


win32 = int(sys.platform == "win32")


Expand Down