Files
mandy/tests/test_tool_stdout_encoding.py
AAyberkU a1343528f7 scripts, viewer: a redirected stdout no longer dies on a path outside the code page
Under `python -I` on Windows a redirected stdout is strict ANSI, so printing a path with a character outside the
code page raised UnicodeEncodeError. tools/ guards against it at the start of every __main__ block and
tests/test_tool_stdout_encoding.py enforces that, but only for tools/. viewer/serve.py died before it started
serving and scripts/audit_shader4_regs.py exited 1 after writing its report; bench_wave64.py and run_gpu_tests.py
print the same kind of output unguarded. All four get the guard, and the check now covers scripts/ and viewer/.

Co-Authored-By: Claude Mythos 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016ABh36DZ2sZNq3ChN6EZJs
2026-11-22 19:55:36 +03:00

108 lines
5.5 KiB
Python

"""Tools must not die printing a path that the console's code page can't write.
On Windows a redirected stdout (tool.py > log.txt, or a pipe from make_game.py) is encoded with the console's ANSI
code page, and `python -I` ignores PYTHONUTF8 and PYTHONIOENCODING. A caller path with a character outside that
code page, such as a Cyrillic, Greek or CJK user name, or a Polish one under a code page without it, reached print()
as UnicodeEncodeError and ended the run. stderr escapes such characters (backslashreplace); stdout was strict. #1406
fixed make_game.py. Every CLI tool now starts its __main__ block by setting errors="replace" on stdout, and so do
the programs under scripts/ and viewer/, which are run the same way.
The paths below use a private-use character that no ANSI code page maps, so before the fix these tools died on any
Windows locale. On a UTF-8 console the character prints, and the test passes either way. Standard library only;
no game files (the inputs are zero bytes or an empty folder).
"""
import os
import re
import subprocess
import sys
import tempfile
import unittest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TOOLS = os.path.join(ROOT, "tools")
PROGRAM_DIRS = ("tools", "scripts", "viewer")
# Still without the guard because other open pull requests change these files; each gets it there or after them.
NOT_YET_GUARDED = {
"scripts/shader_stats.py", # guard added separately, see #2135's file
"scripts/run_wine_tests.py", # guard added separately; open Wine runner pull requests change this file
}
MARK = ""
class EveryToolGuardsStdout(unittest.TestCase):
def test_every_main_block_reconfigures_stdout(self):
missing = []
for folder in PROGRAM_DIRS:
for name in sorted(os.listdir(os.path.join(ROOT, folder))):
rel = folder + "/" + name
if not name.endswith(".py") or rel in NOT_YET_GUARDED:
continue
with open(os.path.join(ROOT, folder, name), encoding="utf-8") as f:
text = f.read()
m = re.search(r"^if __name__ == ['\"]__main__['\"]:\n", text, re.M)
if m and 'sys.stdout.reconfigure(errors="replace")' not in text[m.end():m.end() + 400]:
missing.append(rel)
self.assertEqual(missing, [], "programs whose __main__ block doesn't set errors='replace' on stdout")
class MeasuredCrashes(unittest.TestCase):
# Each of these prints its input path to stdout and died with UnicodeEncodeError on Windows 11 given a zeroed
# input under a private-use-named folder, on every run (audio_wav, hashdict and shader_profile die the same way
# only once their --out already exists, so they are covered by the static check above rather than here).
CASES = [("analyze_4240_full.py", False), ("meshlet_page.py", False)]
def test_a_path_outside_the_code_page_does_not_crash(self):
with tempfile.TemporaryDirectory() as tmp:
folder = os.path.join(tmp, "in-" + MARK)
os.makedirs(folder)
src = os.path.join(folder, "x" + MARK + ".bin")
with open(src, "wb") as f:
f.write(bytes(4096))
out = os.path.join(tmp, "out-" + MARK)
for tool, with_out in self.CASES:
with self.subTest(tool=tool):
argv = [src] + (["--out", out] if with_out else [])
r = subprocess.run([sys.executable, "-I", os.path.join(TOOLS, tool)] + argv,
capture_output=True, cwd=ROOT, timeout=300)
err = r.stderr.decode("utf-8", "replace")
self.assertNotIn("UnicodeEncodeError", err)
class ScriptsAndViewer(unittest.TestCase):
# Both died with UnicodeEncodeError on Windows 11 with stdout redirected: the audit after writing its report
# (exit 1), the viewer before it started serving.
def test_audit_with_a_report_path_outside_the_code_page(self):
with tempfile.TemporaryDirectory() as tmp:
disasm = os.path.join(tmp, "disasm-" + MARK)
os.makedirs(disasm)
report = os.path.join(tmp, "rep-" + MARK + ".json")
r = subprocess.run([sys.executable, "-I", os.path.join(ROOT, "scripts", "audit_shader4_regs.py"),
disasm, "--json", report], capture_output=True, cwd=ROOT, timeout=300)
err = r.stderr.decode("utf-8", "replace")
self.assertNotIn("Traceback", err)
self.assertEqual(r.returncode, 0, err)
self.assertTrue(os.path.isfile(report))
self.assertIn(b"wrote ", r.stdout)
def test_viewer_with_a_world_path_outside_the_code_page(self):
with tempfile.TemporaryDirectory() as tmp:
world = os.path.join(tmp, "world-" + MARK)
os.makedirs(world)
proc = subprocess.Popen([sys.executable, "-I", os.path.join(ROOT, "viewer", "serve.py"),
"--world", world, "--port", "0"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=ROOT)
try:
line = proc.stdout.readline() # the viewer prints this line once it is listening
running = proc.poll() is None
finally:
proc.kill()
_, err = proc.communicate(timeout=60)
err = err.decode("utf-8", "replace")
self.assertNotIn("Traceback", err)
self.assertIn(b"viewer: http://127.0.0.1:", line)
self.assertTrue(running, err)
if __name__ == "__main__":
unittest.main()