From 79478225bec51c7a2447f197ba1d00dc00667cb6 Mon Sep 17 00:00:00 2001 From: Krzysztof kuhy Rudnicki Date: Mon, 16 Nov 2026 10:07:38 +0100 Subject: [PATCH] Add icon word ledger and API Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WzxdWYNS1qAMRdgAtbr5Rq --- DOCS-web-control-api.md | 11 + steam_backlog_enforcer/_icon_ledger.py | 139 ++++++++++++ steam_backlog_enforcer/_web_build.py | 9 +- steam_backlog_enforcer/_web_icon_words.py | 168 ++++++++++++++ steam_backlog_enforcer/_web_routes.py | 11 +- steam_backlog_enforcer/_web_server.py | 12 +- .../tests/_icon_registry.py | 23 ++ .../tests/_isolate_control_plane.py | 9 +- .../tests/test_icon_ledger.py | 180 +++++++++++++++ .../tests/test_web_build.py | 16 ++ .../tests/test_web_icon_words.py | 212 ++++++++++++++++++ .../tests/test_web_icon_words_http.py | 161 +++++++++++++ 12 files changed, 941 insertions(+), 10 deletions(-) create mode 100644 steam_backlog_enforcer/_icon_ledger.py create mode 100644 steam_backlog_enforcer/_web_icon_words.py create mode 100644 steam_backlog_enforcer/tests/_icon_registry.py create mode 100644 steam_backlog_enforcer/tests/test_icon_ledger.py create mode 100644 steam_backlog_enforcer/tests/test_web_icon_words.py create mode 100644 steam_backlog_enforcer/tests/test_web_icon_words_http.py diff --git a/DOCS-web-control-api.md b/DOCS-web-control-api.md index f884b9b..3e1ff1d 100644 --- a/DOCS-web-control-api.md +++ b/DOCS-web-control-api.md @@ -243,3 +243,14 @@ hard-codes it. to anything pytest did not spawn and Steam/kill argv in real `Popen`, and fails any test that hits it (a stale demo test once killed the live game). + +## Icon words (`/api/icon-words`) + +`GET /api/icon-words` → `IconLedger`; `POST` or `PUT /api/icon-words/{icon_id}` with `{word?, glyph?}` → `IconLedger` (200). Writes need Host, Origin and `X-SBE-Token` like every non-GET. TS mirror: `web/src/api/iconWordsContract.ts`. + +- **Ledger** `web/src/ui/icon_words.json` (a repo file the user commits; `SBE_ICON_WORDS` overrides the path): `{"version":1,"icons":{"":{"word":""|null,"glyph":""|null}}}`. Absent id = unanswered; no `word` key = only a glyph chosen; `word: null` = skipped (no label); `glyph: null` = default. The server reads it per request and never builds from it (`_web_build` ignores it); writes go to a sibling temp file, then rename. +- **Registry** `web/src/icons/registry.json`: id → default glyph, spoken name, description, 3 suggested words, 3 alternative glyphs (`registry.ts` types it). +- **`word`**: any text; casing kept, whitespace runs collapsed; 1–40 characters, no control characters, else `invalid_params`. `null` skips. **`glyph`**: the default or one of the icon's 3 alternatives (the default is stored as `null`), else `invalid_params`. Unknown id → `not_found`; empty body or unknown key → `invalid_params`. +- Every served `.html` page carries the ledger as `'.encode() + match = _HEAD_TAG.search(html) + if match is None: + return tag + html + return html[: match.end()] + tag + html[match.end() :] diff --git a/steam_backlog_enforcer/_web_routes.py b/steam_backlog_enforcer/_web_routes.py index e088597..b6e5e57 100644 --- a/steam_backlog_enforcer/_web_routes.py +++ b/steam_backlog_enforcer/_web_routes.py @@ -14,6 +14,7 @@ from typing import TYPE_CHECKING, Final from steam_backlog_enforcer import ( _web_art, _web_daemon, + _web_icon_words, _web_jobs, _web_library, _web_process, @@ -29,6 +30,8 @@ if TYPE_CHECKING: type Route = Callable[[Request], Reply] _ID = r"([0-9A-Za-z_-]{1,64})" +# Icon ids are dotted (``job.state.waiting_input``); the registry re-checks them. +_ICON = r"([a-z][a-z0-9_.-]{0,63})" # Matched before the table by the server: it streams instead of replying. EVENTS_PATH: Final = re.compile(rf"^/api/jobs/{_ID}/events$") @@ -43,8 +46,9 @@ class _Entry: def _r(method: str, path: str, route: Route) -> _Entry: - """Build an entry; ``{id}`` in *path* captures one id segment.""" - return _Entry(method, re.compile("^" + path.replace("{id}", _ID) + "$"), route) + """Build an entry; ``{id}`` / ``{icon}`` in *path* capture one segment.""" + pattern = path.replace("{id}", _ID).replace("{icon}", _ICON) + return _Entry(method, re.compile("^" + pattern + "$"), route) ROUTES: Final[tuple[_Entry, ...]] = ( @@ -71,6 +75,9 @@ ROUTES: Final[tuple[_Entry, ...]] = ( _r("POST", "/api/pending/{id}/heartbeat", _web_daemon.heartbeat_view), _r("POST", "/api/pending/{id}/commit", _web_daemon.commit_view), _r("DELETE", "/api/pending/{id}", _web_daemon.cancel_pending_view), + _r("GET", "/api/icon-words", _web_icon_words.icon_words_view), + _r("POST", "/api/icon-words/{icon}", _web_icon_words.set_icon_word_view), + _r("PUT", "/api/icon-words/{icon}", _web_icon_words.set_icon_word_view), ) diff --git a/steam_backlog_enforcer/_web_server.py b/steam_backlog_enforcer/_web_server.py index 0a1e575..0372c45 100644 --- a/steam_backlog_enforcer/_web_server.py +++ b/steam_backlog_enforcer/_web_server.py @@ -5,7 +5,7 @@ DNS-rebinding guard, :mod:`._web_auth`), fails closed on stale code (:mod:`._serve_stale`), checks ``Origin`` and the per-launch token on anything that is not a GET (and on the SSE stream), then hands off to a route from :mod:`._web_routes`, the SSE streamer (:mod:`._web_sse`) or the -static bundle (``web/dist``, with the token injected into every ``.html`` page). +static bundle (``web/dist``; ``.html`` pages get the token and icon words). Binds to loopback only; never serves secrets and never sends CORS headers. In development the Vite dev server proxies ``/api`` here; in production the @@ -21,7 +21,7 @@ import mimetypes from pathlib import Path from urllib.parse import parse_qs, urlsplit -from steam_backlog_enforcer import _web_auth, _web_process +from steam_backlog_enforcer import _web_auth, _web_icon_words, _web_process from steam_backlog_enforcer._fail_safe import FAIL_SAFE_ERRORS from steam_backlog_enforcer._serve_stale import outdated_source from steam_backlog_enforcer._web_errors import ApiError, not_found @@ -88,6 +88,10 @@ class _Handler(BaseHTTPRequestHandler): """Handle a DELETE.""" self._handle("DELETE") + def do_PUT(self) -> None: + """Handle a PUT (``/api/icon-words/{icon}`` takes PUT or POST).""" + self._handle("PUT") + def _handle(self, method: str) -> None: """Run the checks, then dispatch; every refusal is a JSON error.""" split = urlsplit(self.path) @@ -184,9 +188,9 @@ class _Handler(BaseHTTPRequestHandler): body = candidate.read_bytes() headers: dict[str, str] = {} if candidate.suffix == ".html": - # Carries this launch's token: never cache it. body = _web_auth.inject_token(body, self.server.token) - headers["Cache-Control"] = "no-store" + body = _web_icon_words.inject_icon_words(body) + headers["Cache-Control"] = "no-store" # carries token + icon words send_bytes(self, status, body, ctype, headers) diff --git a/steam_backlog_enforcer/tests/_icon_registry.py b/steam_backlog_enforcer/tests/_icon_registry.py new file mode 100644 index 0000000..f299886 --- /dev/null +++ b/steam_backlog_enforcer/tests/_icon_registry.py @@ -0,0 +1,23 @@ +"""A two-icon registry the icon-word tests use instead of the real one.""" + +from __future__ import annotations + +REGISTRY: dict[str, object] = { + "version": 1, + "icons": { + "nav.dashboard": { + "glyph": "🏠", + "spoken": "Dashboard", + "desc": "d", + "words": ["home", "dashboard", "overview"], + "alts": ["🏡", "🧭", "📟"], + }, + "cmd.done": { + "glyph": "🏆", + "spoken": "Done", + "desc": "d", + "words": ["done", "finished", "next"], + "alts": ["🥇", "🎉", "🏁"], + }, + }, +} diff --git a/steam_backlog_enforcer/tests/_isolate_control_plane.py b/steam_backlog_enforcer/tests/_isolate_control_plane.py index de42a5f..9cce26e 100644 --- a/steam_backlog_enforcer/tests/_isolate_control_plane.py +++ b/steam_backlog_enforcer/tests/_isolate_control_plane.py @@ -1,9 +1,9 @@ """Autouse isolation of the control plane and the HLTB endpoint memo. Redirects the web cover-art caches, the daemon control socket, restart -markers, backups and web job store (all under ``/var/lib``, ``/run`` or the -real ``~/.local/state``) into ``tmp_path``, and forgets the remembered HLTB -search URL around every test. +markers, backups, web job store (all under ``/var/lib``, ``/run`` or the +real ``~/.local/state``) and the repo's icon-word ledger into +``tmp_path``, and forgets the remembered HLTB search URL around every test. Split out of ``conftest.py`` to keep every file inside the 250-line cap; ``conftest`` imports the fixtures by name, which is what registers them. @@ -18,6 +18,7 @@ import pytest from steam_backlog_enforcer._hltb_failures import reset_failures from steam_backlog_enforcer._hltb_search_api import forget_hltb_search_url +from steam_backlog_enforcer._icon_ledger import LEDGER_ENV if TYPE_CHECKING: from collections.abc import Iterator @@ -38,6 +39,8 @@ def _isolate_control_plane( """ state = tmp_path / "ctl_state" monkeypatch.setenv("XDG_RUNTIME_DIR", str(tmp_path / "xdg_runtime")) + # The icon-word ledger is a committed repo file: never write the real one. + monkeypatch.setenv(LEDGER_ENV, str(tmp_path / "icon_words.json")) with ( patch("steam_backlog_enforcer._ctl_gap.RESTART_EXIT_FILE", state / "exit.json"), patch( diff --git a/steam_backlog_enforcer/tests/test_icon_ledger.py b/steam_backlog_enforcer/tests/test_icon_ledger.py new file mode 100644 index 0000000..34494fd --- /dev/null +++ b/steam_backlog_enforcer/tests/test_icon_ledger.py @@ -0,0 +1,180 @@ +"""Tests for _icon_ledger: the icon-word ledger file (load, atomic save, corrupt).""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +import stat +from unittest.mock import patch + +import pytest + +from steam_backlog_enforcer import _icon_ledger as mod + +_GOOD = { + "version": 1, + "icons": { + "nav.dashboard": {"word": "Home", "glyph": None}, + "cmd.done": {"word": None, "glyph": "🥇"}, + "cmd.scan": {"glyph": "📡"}, + }, +} + + +@pytest.fixture(name="home") +def fixture_home(tmp_path: Path) -> Path: + """An empty directory of its own (conftest fixtures also use tmp_path).""" + path = tmp_path / "ledger_home" + path.mkdir() + return path + + +def _write(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +class TestPath: + """Where the ledger lives.""" + + def test_default_is_the_repo_file(self, monkeypatch: pytest.MonkeyPatch) -> None: + """Without the env override the ledger is web/src/ui/icon_words.json.""" + monkeypatch.delenv(mod.LEDGER_ENV, raising=False) + repo = Path(mod.__file__).resolve().parent.parent + assert repo / "web" / "src" / "ui" / "icon_words.json" == mod.DEFAULT_LEDGER + assert mod.ledger_path() == mod.DEFAULT_LEDGER + + def test_env_override_wins( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + """SBE_ICON_WORDS points the server at another file (scratch copies).""" + monkeypatch.setenv(mod.LEDGER_ENV, str(tmp_path / "copy.json")) + assert mod.ledger_path() == tmp_path / "copy.json" + + def test_tests_never_see_the_repo_file(self) -> None: + """The autouse isolation redirects the ledger into tmp_path.""" + assert mod.ledger_path() != mod.DEFAULT_LEDGER + + @pytest.mark.parametrize( + ("name", "expected"), + [ + ("icon_words.json", True), + ("icon_words.json.corrupt", True), + (".icon_words.json.x1y2.tmp", True), + ("icon_words.ts", False), + ("registry.json", False), + ], + ) + def test_is_ledger_file(self, name: str, *, expected: bool) -> None: + """The ledger, its temp files and corrupt copies are runtime data.""" + assert mod.is_ledger_file(Path("/x") / name) is expected + + +class TestLoad: + """load_ledger: missing, valid and corrupt files.""" + + def test_missing_file_is_an_empty_ledger(self, home: Path) -> None: + """No file yet means nothing answered.""" + assert mod.load_ledger(home / "none.json") == {"version": 1, "icons": {}} + + def test_valid_file_round_trips(self, home: Path) -> None: + """A valid file loads as written, a missing word key included.""" + path = home / "l.json" + _write(path, json.dumps(_GOOD)) + assert mod.load_ledger(path) == _GOOD + + @pytest.mark.parametrize( + "text", + [ + "{not json", + "[]", + '{"version": 2, "icons": {}}', + '{"version": 1, "icons": []}', + '{"version": 1, "icons": {"a.b": "word"}}', + '{"version": 1, "icons": {"a.b": {"word": 5}}}', + '{"version": 1, "icons": {"a.b": {"glyph": ["x"]}}}', + '{"version": 1, "icons": {"a.b": {"word": "x", "extra": 1}}}', + ], + ) + def test_corrupt_file_is_kept_aside_and_fails_loudly( + self, home: Path, text: str + ) -> None: + """Bad JSON or schema: copied to .corrupt, original untouched, raises.""" + path = home / "l.json" + _write(path, text) + with pytest.raises(mod.LedgerCorruptError) as err: + mod.load_ledger(path) + kept = home / "l.json.corrupt" + assert err.value.kept == kept + assert kept.read_text("utf-8") == text + assert path.read_text("utf-8") == text + assert str(kept) in str(err.value) + + def test_same_corrupt_bytes_are_kept_once(self, home: Path) -> None: + """Re-reading the same broken file does not pile up copies.""" + path = home / "l.json" + _write(path, "{bad") + for _ in range(2): + with pytest.raises(mod.LedgerCorruptError): + mod.load_ledger(path) + assert sorted(p.name for p in home.iterdir()) == [ + "l.json", + "l.json.corrupt", + ] + + def test_older_corrupt_copy_is_never_overwritten(self, home: Path) -> None: + """A different broken file gets its own copy; the first one survives.""" + path = home / "l.json" + _write(home / "l.json.corrupt", "{first") + _write(path, "{second") + with pytest.raises(mod.LedgerCorruptError) as err: + mod.load_ledger(path) + assert (home / "l.json.corrupt").read_text("utf-8") == "{first" + assert err.value.kept.name.startswith("l.json.corrupt.") + assert err.value.kept.read_text("utf-8") == "{second" + + +class TestSave: + """save_ledger: atomic, stable, readable.""" + + def test_writes_sorted_indented_json_with_newline(self, home: Path) -> None: + """Stable output so the user's commits diff cleanly; emoji kept raw.""" + path = home / "l.json" + mod.save_ledger(path, _GOOD) + text = path.read_text("utf-8") + assert text.endswith("}\n") + assert "🥇" in text + assert json.loads(text) == _GOOD + assert text.index('"cmd.done"') < text.index('"nav.dashboard"') + assert stat.S_IMODE(path.stat().st_mode) == mod.FILE_MODE + + def test_replace_failure_leaves_the_old_file_and_no_temp(self, home: Path) -> None: + """A failed rename keeps the previous ledger intact and cleans up.""" + path = home / "l.json" + _write(path, json.dumps({"version": 1, "icons": {}})) + with ( + patch.object(mod.os, "replace", side_effect=OSError("disk")), + pytest.raises(OSError, match="disk"), + ): + mod.save_ledger(path, _GOOD) + assert json.loads(path.read_text("utf-8")) == {"version": 1, "icons": {}} + assert [p.name for p in home.iterdir()] == ["l.json"] + + def test_goes_through_a_temp_file_in_the_same_dir(self, home: Path) -> None: + """The new content lands by rename from a sibling temp file.""" + path = home / mod.LEDGER_NAME + seen: list[tuple[str, str]] = [] + real = os.replace + + def spy(src: str, dst: str) -> None: + seen.append((src, dst)) + real(src, dst) + + with patch.object(mod.os, "replace", side_effect=spy): + mod.save_ledger(path, _GOOD) + assert len(seen) == 1 + src, dst = seen[0] + assert Path(dst) == path + assert Path(src).parent == home + assert mod.is_ledger_file(Path(src)) diff --git a/steam_backlog_enforcer/tests/test_web_build.py b/steam_backlog_enforcer/tests/test_web_build.py index ff352e7..67f9da2 100644 --- a/steam_backlog_enforcer/tests/test_web_build.py +++ b/steam_backlog_enforcer/tests/test_web_build.py @@ -108,6 +108,22 @@ class TestFrontendIsStale: _touch(web / "dist" / "index.html", 2000.0) assert _web_build.frontend_is_stale() is False + def test_icon_word_ledger_is_runtime_data_not_a_build_input( + self, web: Path + ) -> None: + # The server reads the ledger per page; a pick must not make the + # next `serve` rebuild (a unit without pnpm on PATH would crash-loop). + """The ledger, its temp files and corrupt copies never mark dist stale.""" + _touch(web / "src" / "app.tsx", 1000.0) + _touch(web / "dist" / "index.html", 2000.0) + for name in ( + "icon_words.json", + ".icon_words.json.ab.tmp", + "icon_words.json.corrupt", + ): + _touch(web / "src" / "ui" / name, 3000.0) + assert _web_build.frontend_is_stale() is False + def test_directories_in_src_are_skipped(self, web: Path) -> None: # A directory's own mtime bumps whenever a file inside it is added or # removed, so counting it would report staleness after a build. diff --git a/steam_backlog_enforcer/tests/test_web_icon_words.py b/steam_backlog_enforcer/tests/test_web_icon_words.py new file mode 100644 index 0000000..8cdabd1 --- /dev/null +++ b/steam_backlog_enforcer/tests/test_web_icon_words.py @@ -0,0 +1,212 @@ +"""Tests for _web_icon_words: the icon-word endpoints and the page injection.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING +from unittest.mock import patch + +import pytest + +from steam_backlog_enforcer import _icon_ledger, _web_icon_words, _web_routes +from steam_backlog_enforcer._web_errors import ApiError +from steam_backlog_enforcer.tests._icon_registry import REGISTRY +from steam_backlog_enforcer.tests._web_request import make_request, payload_of + +if TYPE_CHECKING: + from collections.abc import Iterator + from pathlib import Path + + +@pytest.fixture(autouse=True, name="registry") +def fixture_registry(tmp_path: Path) -> Iterator[Path]: + """A two-icon registry instead of the real one.""" + path = tmp_path / "registry.json" + path.write_text(json.dumps(REGISTRY), encoding="utf-8") + with patch.object(_web_icon_words, "REGISTRY_FILE", path): + yield path + + +def _set(icon: str, **body: object) -> dict[str, object]: + reply = _web_icon_words.set_icon_word_view( + make_request(icon, body=body, method="POST") + ) + return payload_of(reply) + + +def _stored() -> dict[str, dict[str, object]]: + return json.loads(_icon_ledger.ledger_path().read_text("utf-8"))["icons"] + + +def _refused(icon: str, code: str, **body: object) -> ApiError: + with pytest.raises(ApiError) as err: + _set(icon, **body) + assert err.value.code == code + return err.value + + +class TestWords: + """POST /api/icon-words/ with a word.""" + + def test_suggestion_is_saved_and_the_ledger_returned(self) -> None: + """A picked word is stored and the whole ledger comes back.""" + out = _set("nav.dashboard", word="home") + assert out == { + "version": 1, + "icons": {"nav.dashboard": {"word": "home", "glyph": None}}, + } + assert _stored() == {"nav.dashboard": {"word": "home", "glyph": None}} + + def test_manual_multi_word_keeps_casing_and_collapses_spaces(self) -> None: + """Any words are accepted; whitespace runs become one space.""" + _set("cmd.done", word=" I got\tan HLTB\n win ") + assert _stored()["cmd.done"] == {"word": "I got an HLTB win", "glyph": None} + + def test_forty_characters_is_the_limit(self) -> None: + """40 characters pass; 41 are refused.""" + _set("cmd.done", word="x" * 40) + _refused("cmd.done", "invalid_params", word="x" * 41) + assert _stored()["cmd.done"]["word"] == "x" * 40 + + @pytest.mark.parametrize( + "word", ["", " ", "bad\x00word", "esc\x1b", "del\x7f", 5, ["a"]] + ) + def test_bad_words_are_refused(self, word: object) -> None: + """Empty, control characters and non-strings are invalid_params (400).""" + err = _refused("cmd.done", "invalid_params", word=word) + assert err.status == 400 + assert not _icon_ledger.ledger_path().exists() + + def test_skip_stores_null(self) -> None: + """word: null means skipped (no label), and counts as answered.""" + _set("cmd.done", word=None) + assert _stored()["cmd.done"] == {"word": None, "glyph": None} + + +class TestGlyphs: + """POST /api/icon-words/ with a glyph.""" + + def test_alternative_is_saved_without_answering_the_word(self) -> None: + """A glyph alone leaves the word unanswered (no word key).""" + _set("cmd.done", glyph="🎉") + assert _stored()["cmd.done"] == {"glyph": "🎉"} + + def test_word_survives_a_later_glyph_choice(self) -> None: + """Word and glyph are independent.""" + _set("cmd.done", word="won") + _set("cmd.done", glyph="🏁") + assert _stored()["cmd.done"] == {"word": "won", "glyph": "🏁"} + + @pytest.mark.parametrize("glyph", ["🏆", None]) + def test_default_or_null_resets_to_default(self, glyph: object) -> None: + """Choosing the default glyph is stored as null (keep default).""" + _set("cmd.done", glyph="🎉") + _set("cmd.done", glyph=glyph) + assert _stored()["cmd.done"] == {"glyph": None} + + @pytest.mark.parametrize("glyph", ["🍕", "🏡", "", 3]) + def test_unregistered_glyph_is_refused(self, glyph: object) -> None: + """Only the default or this icon's own 3 alternatives are accepted.""" + _refused("cmd.done", "invalid_params", glyph=glyph) + + +class TestRequestShape: + """Unknown ids, empty and unknown bodies.""" + + def test_unknown_id_is_not_found(self) -> None: + """An id the registry lacks is a 404.""" + assert _refused("cmd.nope", "not_found", word="x").status == 404 + + def test_empty_body_is_refused(self) -> None: + """Neither word nor glyph: nothing to save.""" + _refused("cmd.done", "invalid_params") + + def test_unknown_key_is_refused(self) -> None: + """A typo'd key is never silently ignored.""" + _refused("cmd.done", "invalid_params", word="x", colour="red") + + def test_missing_registry_fails_loudly(self, registry: Path) -> None: + """Without the registry no glyph or id can be checked: op_failed.""" + registry.unlink() + assert _refused("cmd.done", "op_failed", word="x").status == 500 + + +class TestCorruptLedger: + """A corrupt ledger is kept aside, reads and writes fail loudly.""" + + def test_get_and_post_fail_and_the_file_is_untouched(self) -> None: + """Nothing is overwritten while the ledger does not parse.""" + path = _icon_ledger.ledger_path() + path.write_text("{broken", encoding="utf-8") + with pytest.raises(ApiError) as err: + _web_icon_words.icon_words_view(make_request()) + assert (err.value.code, err.value.status) == ("op_failed", 500) + assert ".corrupt" in err.value.message + _refused("cmd.done", "op_failed", word="x") + assert path.read_text("utf-8") == "{broken" + assert path.with_name(path.name + ".corrupt").read_text("utf-8") == "{broken" + + +class TestGetAndInject: + """GET /api/icon-words and the ledger carried by every served page.""" + + def test_get_returns_the_ledger(self) -> None: + """GET serves the stored ledger, ids the registry lacks included.""" + ledger = {"version": 1, "icons": {"old.id": {"word": "kept", "glyph": None}}} + _icon_ledger.save_ledger(_icon_ledger.ledger_path(), ledger) + assert payload_of(_web_icon_words.icon_words_view(make_request())) == ledger + + def test_page_carries_the_ledger_with_script_breakouts_escaped(self) -> None: + """Words are free text: '<' is escaped so a word cannot close the script.""" + _set("cmd.done", word="x") + html = _web_icon_words.inject_icon_words( + b"t" + ) + text = html.decode("utf-8") + start = text.index( + f'", 1)[0] + assert "<" not in body + assert json.loads(body)["icons"]["cmd.done"]["word"] == "x" + + def test_page_carries_the_error_when_corrupt(self) -> None: + """A corrupt ledger never breaks the page: it carries the error instead.""" + _icon_ledger.ledger_path().write_text("{broken", encoding="utf-8") + html = _web_icon_words.inject_icon_words(b"").decode("utf-8") + body = html.split('">', 1)[1].split("", 1)[0] + assert json.loads(body)["error"] == "op_failed" + + def test_page_without_head_gets_the_script_first(self) -> None: + """A fragment without still carries the ledger.""" + html = _web_icon_words.inject_icon_words(b"

x

").decode("utf-8") + assert html.startswith( + f'", 1)[0] + assert json.loads(payload)["icons"]["cmd.done"]["word"] == "Yay" + assert f'content="{server.token}"' in html