ckb/tests/unit/test_windows.py
Michał Kopeć aab4b9e5e2 Template 2.0.3: Windows encoding, line endings, BOM, paths, hooks
Fixes F7-F11 from the 2.0.0 script review:
- UTF-8 stdout/stderr in every script; UTF-8 decoding of git/rg/yt-dlp
  output and of hook stdin
- utf-8-sig reads, so BOM files keep their frontmatter
- fingerprints match LF or CRLF checkouts (lint, lint_quick.sh,
  consolidate); prefix match on the full digest; short ones reported
- POSIX paths in lint output; rg --path-separator /
- hook installers default to the running interpreter, quote paths,
  --check reports a missing interpreter, odd settings are an error

New tests/unit/test_windows.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:32:26 +01:00

159 lines
7.3 KiB
Python

"""What a Windows checkout looks like to the scripts — a non-UTF-8 console,
CRLF line endings from core.autocrlf, files saved with a BOM, Polish names,
interpreter paths with spaces — tested on any OS."""
import json
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
FIX = ROOT / "tests/fixtures/minimal-kb"
S = ROOT / ".agents/skills"
LINT = S / "ckb-lint/scripts/lint_report.py"
QUICK = S / "ckb-lint/scripts/lint_quick.sh"
START = S / "ckb-lint/scripts/session_start.py"
START_HOOK = S / "ckb-lint/scripts/start_hook.py"
AUTOSAVE_HOOK = S / "ckb-add-conversation/scripts/autosave_hook.py"
RETRIEVE = S / "ckb-retrieve/scripts/retrieve_candidates.py"
CONSOLIDATE = S / "ckb-consolidate/scripts/consolidate.py"
DEDUP = S / "ckb-ingest/scripts/dedup_inbox.py"
TODAY = "2026-11-11"
def run(cwd, *cmd, env_extra=None, stdin=None):
env = dict(os.environ, PYTHONIOENCODING="cp1252", **(env_extra or {}))
return subprocess.run([str(c) for c in cmd], cwd=str(cwd), env=env, input=stdin,
capture_output=True)
class KB(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.kb = Path(self.tmp.name) / "kb"
shutil.copytree(str(FIX), str(self.kb))
def tearDown(self):
self.tmp.cleanup()
def assertClean(self, r, what):
err = r.stderr.decode("utf-8", "replace")
self.assertNotIn("Traceback", err, f"{what}:\n{err}")
self.assertNotIn("UnicodeEncodeError", err)
class Cp1252Console(KB):
"""Polish text and arrows printed through a cp1252 console must not crash."""
def setUp(self):
super().setUp()
(self.kb / "workload").mkdir(exist_ok=True)
(self.kb / "workload" / f"{TODAY}_michal-kopec_summary.md").write_text(
"---\ntype: session\nauthor: Michał Kopeć\ndate: 2026-11-11\n---\n\n## Żółw → łoś\n\n"
"### Open threads\n- [ ] Sprawdzić źródła\n", encoding="utf-8")
(self.kb / "wiki/entities/żółw.md").write_text(
"---\ntype: entity\ntldr: Żółw, który czyta [[Brak łącza]]\n---\n\n# Żółw\n", encoding="utf-8")
def test_scripts_survive_a_cp1252_console(self):
for cmd in ([sys.executable, START, "--today", TODAY, "--no-git"],
[sys.executable, LINT, "--today", TODAY],
[sys.executable, LINT, "--quick", "--today", TODAY],
[sys.executable, RETRIEVE, "żółw łoś", "--today", TODAY],
[sys.executable, CONSOLIDATE, "--today", TODAY],
[sys.executable, DEDUP]):
r = run(self.kb, *cmd)
self.assertClean(r, cmd[1].name)
r.stdout.decode("utf-8") # output is UTF-8, whatever the console
def test_polish_git_name_gives_the_right_slug(self):
subprocess.run(["git", "init", "-q", str(self.kb)], check=True)
subprocess.run(["git", "-C", str(self.kb), "config", "user.name", "Łukasz Michał"], check=True)
subprocess.run(["git", "-C", str(self.kb), "config", "user.email", "l@example.com"], check=True)
r = run(self.kb, sys.executable, START, "--today", TODAY)
self.assertClean(r, "session_start")
self.assertIn("Łukasz Michał", r.stdout.decode("utf-8"))
class LineEndingsAndBom(KB):
def cited_sources(self):
return [p for p in (self.kb / "raw").rglob("*") if p.is_file() and p.suffix in (".md", ".txt")]
def lint(self):
r = run(self.kb, sys.executable, LINT, "--json", "--today", TODAY)
self.assertClean(r, "lint")
return json.loads(r.stdout.decode("utf-8"))["trees"][0]
def test_crlf_checkout_is_not_source_drift(self):
for p in self.cited_sources():
p.write_bytes(p.read_bytes().replace(b"\r\n", b"\n").replace(b"\n", b"\r\n"))
self.assertEqual([f for f in self.lint()["evidence"] if "CHANGED" in f], [])
if shutil.which("bash"):
py = run(self.kb, sys.executable, LINT, "--quick", "--today", TODAY).stdout.decode()
sh = run(self.kb, "bash", QUICK, "--today", TODAY).stdout.decode().split(" (fallback:")[0]
self.assertEqual(py.strip(), sh.strip())
def test_real_change_is_still_drift(self):
p = self.cited_sources()[0]
p.write_bytes(p.read_bytes() + b"\nA new line.\n")
self.assertTrue(any("CHANGED" in f for f in self.lint()["evidence"]))
def test_short_but_correct_fingerprint_is_not_drift(self):
changed = 0
for page in (self.kb / "wiki").rglob("*.md"):
text = page.read_text(encoding="utf-8")
import re
new = re.sub(r"sha256:([0-9a-f]{6})[0-9a-f]{2}\b", r"sha256:\1", text)
if new != text:
page.write_text(new, encoding="utf-8")
changed += 1
self.assertGreater(changed, 0)
self.assertEqual([f for f in self.lint()["evidence"] if "CHANGED" in f], [])
def test_bom_page_has_frontmatter(self):
page = self.kb / "wiki/entities/notepad.md"
page.write_bytes("\ufeff---\ntype: entity\ntldr: Saved by Notepad with zebrafish\n---\n\n# Notepad\n"
.encode("utf-8"))
tree = self.lint()
self.assertEqual([f for f in tree["conformance"] if "notepad" in f], [])
r = run(self.kb, sys.executable, RETRIEVE, "zebrafish", "--json", "--today", TODAY)
self.assertClean(r, "retrieve")
self.assertIn("notepad", r.stdout.decode("utf-8"))
class Hooks(KB):
def settings(self):
return json.loads((self.kb / ".claude/settings.local.json").read_text(encoding="utf-8"))
def commands(self, event):
return [h["command"] for g in self.settings()["hooks"][event] for h in g["hooks"]]
def test_interpreter_path_with_spaces_is_quoted_and_checked(self):
(self.kb / "ckb.yaml").write_text("session:\n start_hook: true\n", encoding="utf-8")
r = run(self.kb, sys.executable, START_HOOK, "--install", "--python", r"C:\Program Files\Python312\python.exe")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn('"C:/Program Files/Python312/python.exe" ', self.commands("SessionStart")[0])
r = run(self.kb, sys.executable, START_HOOK, "--check")
self.assertEqual(r.returncode, 1)
self.assertIn("not found", r.stdout.decode("utf-8"))
def test_default_interpreter_is_the_running_one_and_checks_clean(self):
(self.kb / "ckb.yaml").write_text("conversations:\n autosave: true\n", encoding="utf-8")
self.assertEqual(run(self.kb, sys.executable, AUTOSAVE_HOOK, "--install").returncode, 0)
self.assertIn(Path(sys.executable).as_posix(), self.commands("Stop")[0])
r = run(self.kb, sys.executable, AUTOSAVE_HOOK, "--check")
self.assertEqual(r.returncode, 0, r.stdout)
def test_odd_settings_shape_is_an_error_not_a_crash(self):
(self.kb / ".claude").mkdir()
for body in ("[]", '{"hooks": []}', "\ufeff" + '{"hooks": {"Stop": ["x", {"hooks": ["y"]}]}}'):
(self.kb / ".claude/settings.local.json").write_text(body, encoding="utf-8")
for script in (START_HOOK, AUTOSAVE_HOOK):
r = run(self.kb, sys.executable, script, "--check")
self.assertClean(r, f"{script.name} on {body!r}")
if __name__ == "__main__":
unittest.main()