File size: 2,244 Bytes
ff8b94c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""Entry-point scripts must not die on a non-UTF-8 console."""

from __future__ import annotations

import io
import os
import runpy
import sys

import pytest

_SCRIPTS = ["train", "eval_only"]
_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


@pytest.mark.parametrize("script", _SCRIPTS)
def test_script_reconfigures_streams_to_utf8(script: str, monkeypatch) -> None:
    """Progress output uses arrows and box-drawing characters.

    A cp1252 console raises UnicodeEncodeError partway through a run, after
    real work has been done, so the scripts force UTF-8 at import time.
    """
    recorded: list[dict] = []

    class _Stream(io.StringIO):
        encoding = "cp1252"

        def reconfigure(self, **kwargs):
            recorded.append(kwargs)

    monkeypatch.setattr(sys, "stdout", _Stream())
    monkeypatch.setattr(sys, "stderr", _Stream())
    monkeypatch.setattr(sys, "argv", [script])

    # run_name is not "__main__", so main() never runs; stream setup happens
    # at import time, which is the point.
    runpy.run_path(os.path.join(_ROOT, "scripts", f"{script}.py"), run_name="not_main")

    assert {"encoding": "utf-8", "errors": "replace"} in recorded


def test_cp1252_console_survives_arrow_output() -> None:
    """The characters that used to crash a run must now be writable."""
    buf = io.TextIOWrapper(io.BytesIO(), encoding="cp1252", errors="strict")
    buf.reconfigure(encoding="utf-8", errors="replace")
    buf.write("[2/6 REFLECT] failure=0→0 groups — SkillOpt")
    buf.flush()


@pytest.mark.parametrize(
    ("encoding", "expect_reconfigure"),
    [("cp1252", True), ("utf-8", False), ("utf_8", False), ("UTF8", False)],
)
def test_helper_skips_streams_already_utf8(encoding, expect_reconfigure, monkeypatch) -> None:
    from skillopt.utils.console import force_utf8_stdout_stderr

    recorded: list[dict] = []

    class _Stream:
        def __init__(self, enc):
            self.encoding = enc

        def reconfigure(self, **kwargs):
            recorded.append(kwargs)

    monkeypatch.setattr(sys, "stdout", _Stream(encoding))
    monkeypatch.setattr(sys, "stderr", _Stream(encoding))
    force_utf8_stdout_stderr()

    assert bool(recorded) is expect_reconfigure