|
| 1 | +"""Regression tests for stdout/stderr encoding resilience on Windows consoles.""" |
| 2 | + |
| 3 | +import importlib |
| 4 | +import io |
| 5 | + |
| 6 | +import structlog |
| 7 | +from lfx.log._streams import make_streams_resilient |
| 8 | + |
| 9 | + |
| 10 | +def _cp1252_stream() -> tuple[io.TextIOWrapper, io.BytesIO]: |
| 11 | + """A text stream that behaves like a strict Windows cp1252 console.""" |
| 12 | + raw = io.BytesIO() |
| 13 | + return io.TextIOWrapper(raw, encoding="cp1252"), raw |
| 14 | + |
| 15 | + |
| 16 | +def test_make_streams_resilient_sets_backslashreplace(monkeypatch): |
| 17 | + out, _ = _cp1252_stream() |
| 18 | + err, _ = _cp1252_stream() |
| 19 | + monkeypatch.setattr("sys.stdout", out) |
| 20 | + monkeypatch.setattr("sys.stderr", err) |
| 21 | + |
| 22 | + make_streams_resilient() |
| 23 | + |
| 24 | + assert out.errors == "backslashreplace" |
| 25 | + assert err.errors == "backslashreplace" |
| 26 | + |
| 27 | + |
| 28 | +def test_logging_exception_to_cp1252_stdout_does_not_crash(monkeypatch): |
| 29 | + """A logged traceback must never raise UnicodeEncodeError on a cp1252 console. |
| 30 | +
|
| 31 | + structlog's ConsoleRenderer emits box-drawing glyphs that cp1252 cannot |
| 32 | + encode; without the resilience shim the encode error is raised inside the |
| 33 | + logging call, masking the original error and aborting the request. |
| 34 | + """ |
| 35 | + stream, raw = _cp1252_stream() |
| 36 | + monkeypatch.setattr("sys.stdout", stream) |
| 37 | + |
| 38 | + make_streams_resilient() |
| 39 | + |
| 40 | + logmod = importlib.import_module("lfx.log.logger") |
| 41 | + logmod.configure(log_level="ERROR", cache=False) |
| 42 | + log = structlog.get_logger("test") |
| 43 | + |
| 44 | + msg = "THIS IS A TEST ERROR MESSAGE" |
| 45 | + try: |
| 46 | + raise ValueError(msg) |
| 47 | + except ValueError: |
| 48 | + log.exception("boom") |
| 49 | + |
| 50 | + stream.flush() |
| 51 | + rendered = raw.getvalue().decode("cp1252", errors="replace") |
| 52 | + assert "THIS IS A TEST ERROR MESSAGE" in rendered |
| 53 | + |
| 54 | + |
| 55 | +def test_reconfigure_is_safe_when_stream_is_none(monkeypatch): |
| 56 | + monkeypatch.setattr("sys.stdout", None) |
| 57 | + monkeypatch.setattr("sys.stderr", None) |
| 58 | + monkeypatch.setattr("sys.__stdout__", None) |
| 59 | + monkeypatch.setattr("sys.__stderr__", None) |
| 60 | + |
| 61 | + make_streams_resilient() |
0 commit comments