From ce8c2a525153bea41a3cc49d3c0daedf6b5e5cd5 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 5 Dec 2026 11:39:29 -0600 Subject: [PATCH] docs(game): Add The Last Beacon walkthrough why: Users need an end-to-end interactive terminal walkthrough showing open_pty(), DECCKM cursor keys, bracketed paste, ?2026 synchronized redraws, TIOCSWINSZ resize, FlightRecorder capture, and offline bytewise replay. what: - Add stdlib game examples/last_beacon/game.py, PTY tour/replay script examples/last_beacon/tour.py (full-span bold-green victory validation, DECCKM verification, FlightRecorder imported from libvt.recorder), and examples/last_beacon/walkthrough.json. - Add docs/topics/interactive-game.md with -O-safe doctests, update docs/topics/index.md, link from README.md under Features, and record at the top of Documentation in CHANGES. - Add tests/test_example_last_beacon.py guarding live-vs-bundled walkthrough parity, assert_victory() edge cases, schema rejection, Editor split-byte sequences, and win32 guards. Fixes #116 --- CHANGES | 6 + README.md | 4 +- docs/topics/index.md | 14 +- docs/topics/interactive-game.md | 134 ++++++++++++++ examples/last_beacon/game.py | 246 ++++++++++++++++++++++++++ examples/last_beacon/tour.py | 218 +++++++++++++++++++++++ examples/last_beacon/walkthrough.json | 37 ++++ tests/test_example_last_beacon.py | 173 ++++++++++++++++++ 8 files changed, 828 insertions(+), 4 deletions(-) create mode 100644 docs/topics/interactive-game.md create mode 100644 examples/last_beacon/game.py create mode 100644 examples/last_beacon/tour.py create mode 100644 examples/last_beacon/walkthrough.json create mode 100644 tests/test_example_last_beacon.py diff --git a/CHANGES b/CHANGES index 2d784d2b..453a9b1c 100644 --- a/CHANGES +++ b/CHANGES @@ -79,6 +79,12 @@ Deleting an attribute on {class}`~libvt.snapshot.Snapshot` now raises ### Documentation +#### Play and replay The Last Beacon (#140) + +The {ref}`game walkthrough ` drives a playable +terminal game, checks its winning screen after resizing, and replays a +saved run from the command line. + #### Observe a pane and its attached tmux client (#141) The {ref}`tmux screen guide ` compares pane captures, diff --git a/README.md b/README.md index cb4cfd0f..15d18be0 100644 --- a/README.md +++ b/README.md @@ -246,7 +246,8 @@ styles: Read `tmux` captures as screen cells and decode control-mode output with [`libvt.contrib.tmux`][contrib_tmux]. See [Which screen am I testing?][tmux_screens] for attached-client and copy-mode -checks. Full guides and API reference are at +checks, or [play, test, and replay The Last Beacon][interactive_game] for a +complete PTY walkthrough. Full guides and API reference are at [libvt.git-pull.com](https://libvt.git-pull.com/). ## License @@ -272,3 +273,4 @@ MIT License. See [LICENSE](LICENSE). [fzf_cookbook]: https://libvt.git-pull.com/topics/testing/#topics-testing-fzf [contrib_tmux]: https://libvt.git-pull.com/api/contrib/tmux/ [tmux_screens]: https://libvt.git-pull.com/topics/tmux-screens/ +[interactive_game]: https://libvt.git-pull.com/topics/interactive-game/ diff --git a/docs/topics/index.md b/docs/topics/index.md index de4a5d18..55760d5e 100644 --- a/docs/topics/index.md +++ b/docs/topics/index.md @@ -3,9 +3,9 @@ # Topics Guides covering `libvt`'s parser and screen design, immutable snapshots, -terminal testing systems, tmux screen and attached-client observation, -synchronized redraws and `asyncio` adapters, terminal protocols and input -encoding, and migrating from `pyte`. +terminal testing systems, tmux screen and attached-client observation, an +interactive terminal game walkthrough, synchronized redraws and `asyncio` +adapters, terminal protocols and input encoding, and migrating from `pyte`. ::::{grid} 1 1 2 2 :gutter: 2 2 3 3 @@ -35,6 +35,13 @@ Compare a tmux pane with an attached client in copy mode and route a mouse click after a resize. ::: +:::{grid-item-card} Test an Interactive Game +:link: interactive-game +:link-type: doc +Drive a text adventure on a PTY, verify its window size, and replay the +winning screen. +::: + :::{grid-item-card} Synchronized Output & `asyncio` :link: sync-and-asyncio :link-type: doc @@ -64,6 +71,7 @@ architecture snapshots testing tmux-screens +interactive-game sync-and-asyncio protocols-and-input migrating-from-pyte diff --git a/docs/topics/interactive-game.md b/docs/topics/interactive-game.md new file mode 100644 index 00000000..89bfc909 --- /dev/null +++ b/docs/topics/interactive-game.md @@ -0,0 +1,134 @@ +(topics-interactive-game)= + +# Test an interactive game + +In *The Last Beacon*, the harbor is dark. Find the brass key at Lantern Quay, +go north, and light the beacon. The game uses only the standard library. +Run the commands from the repository root with `libvt` installed. + +## Play the game + +On a POSIX terminal, run the game to explore with the arrow keys. Type +`help` for commands and `quit` to leave. + +```console +$ python examples/last_beacon/game.py +``` + +Use `--transcript` for line-by-line play on any platform. Enter `north` +and try to light the beacon without the key. + +```python +>>> import subprocess +>>> import sys +>>> game = subprocess.run( +... [sys.executable, "examples/last_beacon/game.py", "--transcript"], +... input="north\nlight beacon\nquit\n", +... text=True, +... capture_output=True, +... check=True, +... ) +>>> "You need the brass key." in game.stdout +True +``` + +## Drive the game from a test + +On POSIX, run the tour to play through a real pseudo-terminal. + +```console +$ python examples/last_beacon/tour.py +``` + +The tour opens the child with {func}`~libvt.aio.open_pty`. It pastes +`take key`, submits it with Enter, and sends Up using the cursor-key mode +requested by the child. It waits for the room heading to confirm movement, +then resizes to 45 columns by 10 rows. The new size in the title comes from +the child's terminal, so it confirms the resize reached the application. + +The tour checks the victory message for bold green text and keeps the arrival +{class}`~libvt.snapshot.Snapshot` to verify that it still shows the quay at +the original width. Capture the winning screen before quitting because the +child restores the primary screen as it exits. + +```python +>>> import os +>>> import pathlib +>>> import subprocess +>>> import sys +>>> import tempfile +>>> if os.name == "posix": +... with tempfile.TemporaryDirectory() as directory: +... trace = pathlib.Path(directory) / "beacon.json" +... tour = [sys.executable, "examples/last_beacon/tour.py"] +... live = subprocess.check_output([*tour, "--record", str(trace)], timeout=30) +... saved = subprocess.check_output([*tour, "--replay", str(trace)], timeout=30) +... matched = b"The beacon is lit!" in live and live == saved +... else: # doctest: +HIDE +... matched = True # doctest: +HIDE +>>> matched +True +``` + +## Replay the winning screen + +The bundled recording stores output bytes and viewport sizes at each +checkpoint. Replay applies the sizes and feeds the bytes to a fresh +{class}`~libvt.terminal.Terminal`. Each checkpoint is compared with its +original {func}`~libvt.testing.serialize_vt_snapshot` output. Feeding one +byte at a time exercises escape sequences split across reads. + +```console +$ python examples/last_beacon/tour.py --replay --chunk-size 1 +``` + +```python +>>> import subprocess +>>> import sys +>>> replay = subprocess.run( +... [sys.executable, "examples/last_beacon/tour.py", "--replay", "--chunk-size", "1"], +... capture_output=True, encoding="utf-8", check=True, +... ) +>>> replay.stdout.splitlines()[0] +'size=45x10 cursor=(9,2,vis=True) alt=True modes=[DECCKM,BRACKETED_PASTE]' +>>> "r8[0..18]: bold fg=green" in replay.stdout +True +``` + +Replay stops at the first checkpoint whose saved screen differs. The error +names the checkpoint. You can check a recording from an optimized interpreter +as well. + +```python +>>> import json +>>> import pathlib +>>> import subprocess +>>> import sys +>>> import tempfile +>>> example = pathlib.Path("examples/last_beacon") +>>> frames = json.loads((example / "walkthrough.json").read_text(encoding="utf-8")) +>>> frames[1]["screen"] = frames[0]["screen"] +>>> with tempfile.TemporaryDirectory() as directory: +... trace = pathlib.Path(directory) / "changed.json" +... _ = trace.write_text(json.dumps(frames), encoding="utf-8") +... result = subprocess.run( +... [sys.executable, "-O", str(example / "tour.py"), "--replay", str(trace)], +... capture_output=True, text=True, check=False, +... ) +>>> result.returncode, result.stderr.strip() +(1, "tour.py: Screen differs at checkpoint 'key'") +``` + +On POSIX, use `--record` to save a fresh run. The bounded +{class}`~libvt.recorder.FlightRecorder` supplies the bytes received from +the child. A fresh trace can include an intermediate redraw between paste +and Enter. The completed checkpoints still match. Replay runs on any +supported platform without starting the game. + +```console +$ python examples/last_beacon/tour.py --record beacon.json +``` + +```console +$ python examples/last_beacon/tour.py --replay beacon.json +``` diff --git a/examples/last_beacon/game.py b/examples/last_beacon/game.py new file mode 100644 index 00000000..4a906c76 --- /dev/null +++ b/examples/last_beacon/game.py @@ -0,0 +1,246 @@ +"""Play The Last Beacon, an original game written for libvt's examples.""" + +from __future__ import annotations + +import argparse +import collections.abc +import contextlib +import os +import select +import signal +import sys +from dataclasses import dataclass + +TITLE = "THE LAST BEACON" +QUAY, HALL, CHART = "Lantern Quay", "Beacon Hall", "Chart Room" +ROOMS = { + QUAY: ("The shore light has gone dark.", {"north": HALL, "east": CHART}), + HALL: ("A brass lock holds the wick.", {"south": QUAY}), + CHART: ("A chalk arrow points north from the quay.", {"west": QUAY}), +} +WIN = "The beacon is lit!" +HELP = "take key / north / light beacon / quit" +QUIT = {"quit", "exit"} + + +@dataclass +class Game: + """Track the room, brass key, and the last action's result.""" + + room: str = QUAY + has_key: bool = False + lit: bool = False + message: str = "Find the brass key and light the beacon." + + def move(self, direction: str) -> None: + """Move through an exit from the current room.""" + destination = ROOMS[self.room][1].get(direction) + if destination is None: + self.message = "There is no passage that way." + else: + self.room = destination + self.message = f"You go {direction}." + + def act(self, command: str) -> None: + """Apply a typed command or an arrow movement.""" + match " ".join(command.lower().split()).removeprefix("go "): + case "north" | "south" | "east" | "west" as direction: + self.move(direction) + case "take key" if self.has_key: + self.message = "You already carry the brass key." + case "take key" if self.room == QUAY: + self.has_key = True + self.message = "You take the brass key." + case "take key": + self.message = "There is no brass key here." + case "light beacon" if self.room != HALL: + self.message = "The lamp is in Beacon Hall." + case "light beacon" if not self.has_key: + self.message = "You need the brass key." + case "light beacon": + self.lit = True + self.message = WIN + case "help": + self.message = HELP + case _: + self.message = "Unknown command. Type help." + + def lines(self) -> tuple[str, ...]: + """Return the room, exits, visible key, and inventory.""" + description, exits = ROOMS[self.room] + key_here = self.room == QUAY and not self.has_key + return ( + self.room, + description, + "Exits: " + ", ".join(exits), + "On the stones: " + ("a brass key" if key_here else "nothing"), + "Pack: " + ("brass key" if self.has_key else "empty"), + "Beacon: " + ("lit" if self.lit else "dark"), + ) + + +class Editor: + """Read ASCII commands, application arrows, and bracketed paste.""" + + def __init__(self) -> None: + self.text = "" + self.escape = "" + self.pasting = False + + def feed(self, data: bytes) -> collections.abc.Iterator[str]: + """Yield each complete command while retaining a partly typed line.""" + for char in data.decode("ascii", errors="ignore"): + if char == "\x1b": + self.escape = char + elif self.escape: + self.escape += char + if self.escape in {"\x1b[", "\x1bO"}: + continue + if not "@" <= char <= "~" and len(self.escape) < 16: + continue + sequence, self.escape = self.escape, "" + match sequence: + case "\x1b[200~": + self.pasting = True + case "\x1b[201~": + self.pasting = False + case _ if not self.pasting and not self.text: + directions = { + "A": "north", + "B": "south", + "C": "east", + "D": "west", + } + if sequence[:-1] in {"\x1b[", "\x1bO"} and char in directions: + yield directions[char] + elif self.pasting: + if len(self.text) < 120 and (char.isprintable() or char.isspace()): + self.text += char if char.isprintable() else " " + elif char in "\x03\x04": + yield "quit" + elif char in "\r\n": + command, self.text = self.text.strip(), "" + if command: + yield command + elif char in "\b\x7f": + self.text = self.text[:-1] + elif char.isprintable() and len(self.text) < 120: + self.text += char + + +def redraw(game: Game, draft: str, size: os.terminal_size) -> None: + """Redraw the alternate screen with dimensions read by the child.""" + columns, rows = size + columns, rows = columns or 80, rows or 24 + header = f"{TITLE} | {columns}x{rows}" + lines = [("1;36", header), ("1;33", game.room)] + lines.extend(("0", line) for line in game.lines()[1:]) + lines.append(("2", "Arrows move. Type help or quit.")) + display = [ + f"\x1b[{row};1H\x1b[{style}m{text[:columns]}\x1b[0m" + for row, (style, text) in enumerate(lines[: max(0, rows - 2)], 1) + ] + if rows > 1: + style = "1;32" if game.message == WIN else "0" + display.append( + f"\x1b[{rows - 1};1H\x1b[{style}m{game.message[:columns]}\x1b[0m" + ) + prompt = ("> " + draft[-max(1, columns - 3) :])[:columns] + display.append(f"\x1b[{rows};1H\x1b[1;36m{prompt}\x1b[0m") + sys.stdout.write("\x1b[?2026h\x1b[H\x1b[2J" + "".join(display) + "\x1b[?2026l") + sys.stdout.flush() + + +@contextlib.contextmanager +def raw_terminal() -> collections.abc.Generator[None]: + """Restore terminal modes and the primary screen on exit.""" + if sys.platform == "win32": + message = "Full-screen play requires a POSIX terminal" + raise NotImplementedError(message) + + import termios + import tty + + fd = sys.stdin.fileno() + saved = termios.tcgetattr(fd) + + def stop(*_args: object) -> None: + raise SystemExit(0) + + previous = signal.signal(signal.SIGTERM, stop) + try: + tty.setraw(fd) + sys.stdout.write("\x1b[?1049h\x1b[?1h\x1b[?2004h") + sys.stdout.flush() + yield + finally: + try: + sys.stdout.write("\x1b[?2026l\x1b[0m\x1b[?2004l\x1b[?1l\x1b[?1049l") + sys.stdout.flush() + finally: + termios.tcsetattr(fd, termios.TCSANOW, saved) + signal.signal(signal.SIGTERM, previous) + + +def play() -> None: + """Play on a local POSIX terminal with arrows and a command prompt.""" + game, editor = Game(), Editor() + fd = sys.stdin.fileno() + with raw_terminal(): + size = os.get_terminal_size(sys.stdout.fileno()) + redraw(game, editor.text, size) + while True: + ready, _, _ = select.select([fd], [], [], 0.1) + if ready: + data = os.read(fd, 4096) + if not data: + return + for command in editor.feed(data): + if command.lower() in QUIT: + return + game.act(command) + current_size = os.get_terminal_size(sys.stdout.fileno()) + if ready or current_size != size: + size = current_size + redraw(game, editor.text, size) + + +def transcript() -> None: + """Play by typing one command per line on any supported Python.""" + game = Game() + sys.stdout.write(TITLE + "\n") + while True: + sys.stdout.write("\n".join((*game.lines(), game.message)) + "\n") + sys.stdout.flush() + try: + command = input("> ").strip() + except EOFError: + return + if command.lower() in QUIT: + return + game.act(command) + + +def main() -> None: + """Use a full-screen POSIX terminal, with line input elsewhere.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--transcript", action="store_true", help="use one command per line" + ) + args = parser.parse_args() + try: + if ( + args.transcript + or os.name != "posix" + or not sys.stdin.isatty() + or not sys.stdout.isatty() + ): + transcript() + else: + play() + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/examples/last_beacon/tour.py b/examples/last_beacon/tour.py new file mode 100644 index 00000000..e71af004 --- /dev/null +++ b/examples/last_beacon/tour.py @@ -0,0 +1,218 @@ +"""Win The Last Beacon on a PTY or replay its captured screens offline.""" + +from __future__ import annotations + +import argparse +import asyncio +import base64 +import json +import pathlib +import sys +import typing as t + +from libvt import Limits, Snapshot, Terminal +from libvt.aio import open_pty +from libvt.modes import Mode +from libvt.recorder import FlightRecorder +from libvt.style import AnsiColor +from libvt.testing import serialize_vt_snapshot + +HERE = pathlib.Path(__file__).resolve().parent +RECORDING = HERE / "walkthrough.json" +START_ROWS, START_COLS = 14, 60 +WIN_ROWS, WIN_COLS = 10, 45 +VICTORY = "The beacon is lit!" + + +class Frame(t.TypedDict): + """A viewport checkpoint and the bytes received since the last one.""" + + name: str + rows: int + cols: int + output: str + screen: str + + +def assert_victory(view: Snapshot) -> None: + """Check the message, style, and command prompt at the end of the game.""" + if view.rows < 2: + msg = f"Expected at least 2 rows in the victory frame, got {view.rows}" + raise ValueError(msg) + if view.lines[-2] != VICTORY: + msg = f"Expected {VICTORY!r} in the victory frame, got {view.lines[-2]!r}" + raise ValueError(msg) + message_cells = view[view.rows - 2][: len(VICTORY)] + for cell in message_cells: + if not cell.style.bold or cell.style.fg != AnsiColor.GREEN: + msg = f"Victory message has the wrong style: {cell.style}" + raise ValueError(msg) + if (view.cursor.row, view.cursor.col) != (view.rows - 1, 2): + msg = "Victory frame cursor moved away from the command prompt" + raise ValueError(msg) + + +async def play(destination: pathlib.Path | None) -> Snapshot: + """Drive the real child and optionally save its output and size changes.""" + frames: list[Frame] = [] + offset = 0 + async with open_pty( + (sys.executable, str(HERE / "game.py")), + rows=START_ROWS, + cols=START_COLS, + limits=Limits(max_recorder_bytes=16 * 1024), + ) as player: + recorder = player.terminal.recorder + if not isinstance(recorder, FlightRecorder): + msg = "Recording requires a FlightRecorder" + raise TypeError(msg) + + async def capture( + name: str, room: str, message: str, rows: int, cols: int + ) -> Snapshot: + nonlocal offset + view = await player.wait_for( + lambda screen: ( + screen.lines[0] == f"THE LAST BEACON | {cols}x{rows}" + and screen.lines[1] == room + and screen.lines[-2] == message + ), + timeout=5, + ) + if (view.rows, view.cols) != (rows, cols): + msg = f"Expected {cols}x{rows} at checkpoint {name!r}" + raise ValueError(msg) + if destination is not None: + raw = recorder.tail(recorder.total_bytes) + if len(raw) != recorder.total_bytes: + msg = "The recording buffer filled before the checkpoint" + raise ValueError(msg) + frames.append( + { + "name": name, + "rows": rows, + "cols": cols, + "output": base64.b64encode(raw[offset:]).decode("ascii"), + "screen": serialize_vt_snapshot(view), + } + ) + offset = len(raw) + return view + + arrival = await capture( + "arrival", + "Lantern Quay", + "Find the brass key and light the beacon.", + START_ROWS, + START_COLS, + ) + if Mode.DECCKM not in arrival.modes: + msg = "Expected DECCKM cursor-key mode to be enabled by the game" + raise ValueError(msg) + player.paste("take key") + player.send_key("enter") + await capture( + "key", "Lantern Quay", "You take the brass key.", START_ROWS, START_COLS + ) + + player.send_key("up") + await capture("hall", "Beacon Hall", "You go north.", START_ROWS, START_COLS) + + player.resize(rows=WIN_ROWS, cols=WIN_COLS) + await capture("resize", "Beacon Hall", "You go north.", WIN_ROWS, WIN_COLS) + + player.paste("light beacon") + player.send_key("enter") + victory = await capture("win", "Beacon Hall", VICTORY, WIN_ROWS, WIN_COLS) + assert_victory(victory) + if arrival.lines[1] != "Lantern Quay" or arrival.cols != START_COLS: + msg = "The saved arrival frame changed during the game" + raise ValueError(msg) + player.send_key("ctrl+d") + status = await asyncio.wait_for(player.process.wait(), timeout=5) + if status: + msg = f"The game exited with status {status}" + raise ChildProcessError(msg) + + if destination is not None: + destination.write_text( + json.dumps(frames, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + return victory + + +def _is_frame(value: object) -> t.TypeGuard[Frame]: + if not isinstance(value, dict): + return False + return ( + isinstance(value.get("name"), str) + and isinstance(value.get("output"), str) + and isinstance(value.get("screen"), str) + and type(value.get("rows")) is int + and value["rows"] > 0 + and type(value.get("cols")) is int + and value["cols"] > 0 + ) + + +def replay(source: pathlib.Path, chunk_size: int) -> Snapshot: + """Feed the captured output in chunks, checking each recorded checkpoint.""" + if chunk_size < 1: + message = "chunk size must be positive" + raise ValueError(message) + frames: object = json.loads(source.read_text(encoding="utf-8")) + if not isinstance(frames, list) or not frames: + msg = "A recording must contain at least one checkpoint" + raise ValueError(msg) + terminal = Terminal(rows=START_ROWS, cols=START_COLS) + for number, frame in enumerate(frames, 1): + if not _is_frame(frame): + msg = f"Invalid checkpoint {number} in {source}" + raise ValueError(msg) + rows, cols = frame["rows"], frame["cols"] + if (terminal.rows, terminal.cols) != (rows, cols): + terminal.resize(rows=rows, cols=cols) + chunk = base64.b64decode(frame["output"], validate=True) + for offset in range(0, len(chunk), chunk_size): + terminal.feed(chunk[offset : offset + chunk_size]) + if serialize_vt_snapshot(terminal.committed) != frame["screen"]: + msg = f"Screen differs at checkpoint {frame['name']!r}" + raise ValueError(msg) + victory = terminal.committed + assert_victory(victory) + return victory + + +def main() -> None: + """Run the live game, save a recording, or replay a recording.""" + parser = argparse.ArgumentParser(description=__doc__) + modes = parser.add_mutually_exclusive_group() + modes.add_argument("--record", type=pathlib.Path, help="save a live game to FILE") + modes.add_argument( + "--replay", + nargs="?", + const=RECORDING, + type=pathlib.Path, + metavar="FILE", + help="replay FILE or the bundled recording", + ) + parser.add_argument( + "--chunk-size", type=int, default=17, help="bytes per replay feed" + ) + args = parser.parse_args() + if args.replay is not None: + if args.chunk_size < 1: + parser.error("--chunk-size must be positive") + try: + view = replay(args.replay, args.chunk_size) + except (OSError, ValueError) as error: + parser.exit(1, f"{parser.prog}: {error}\n") + else: + if sys.platform == "win32": + parser.error("live play requires a POSIX PTY; use --replay") + view = asyncio.run(play(args.record)) + sys.stdout.buffer.write((serialize_vt_snapshot(view) + "\n").encode("utf-8")) + + +if __name__ == "__main__": + main() diff --git a/examples/last_beacon/walkthrough.json b/examples/last_beacon/walkthrough.json new file mode 100644 index 00000000..e3f1ea19 --- /dev/null +++ b/examples/last_beacon/walkthrough.json @@ -0,0 +1,37 @@ +[ + { + "name": "arrival", + "rows": 14, + "cols": 60, + "output": "G1s/MTA0OWgbWz8xaBtbPzIwMDRoG1s/MjAyNmgbW0gbWzJKG1sxOzFIG1sxOzM2bVRIRSBMQVNUIEJFQUNPTiAgfCAgNjB4MTQbWzBtG1syOzFIG1sxOzMzbUxhbnRlcm4gUXVheRtbMG0bWzM7MUgbWzBtVGhlIHNob3JlIGxpZ2h0IGhhcyBnb25lIGRhcmsuG1swbRtbNDsxSBtbMG1FeGl0czogbm9ydGgsIGVhc3QbWzBtG1s1OzFIG1swbU9uIHRoZSBzdG9uZXM6IGEgYnJhc3Mga2V5G1swbRtbNjsxSBtbMG1QYWNrOiBlbXB0eRtbMG0bWzc7MUgbWzBtQmVhY29uOiBkYXJrG1swbRtbODsxSBtbMm1BcnJvd3MgbW92ZS4gVHlwZSBoZWxwIG9yIHF1aXQuG1swbRtbMTM7MUgbWzBtRmluZCB0aGUgYnJhc3Mga2V5IGFuZCBsaWdodCB0aGUgYmVhY29uLhtbMG0bWzE0OzFIG1sxOzM2bT4gG1swbRtbPzIwMjZs", + "screen": "size=60x14 cursor=(13,2,vis=True) alt=True modes=[DECCKM,BRACKETED_PASTE]\n┌────────────────────────────────────────────────────────────┐\n│THE LAST BEACON | 60x14 │\n│Lantern Quay │\n│The shore light has gone dark. │\n│Exits: north, east │\n│On the stones: a brass key │\n│Pack: empty │\n│Beacon: dark │\n│Arrows move. Type help or quit. │\n│ │\n│ │\n│ │\n│ │\n│Find the brass key and light the beacon. │\n│> │\n└────────────────────────────────────────────────────────────┘\nstyles:\n r0[0..25]: bold fg=cyan\n r1[0..12]: bold fg=yellow\n r7[0..31]: dim\n r13[0..2]: bold fg=cyan" + }, + { + "name": "key", + "rows": 14, + "cols": 60, + "output": "G1s/MjAyNmgbW0gbWzJKG1sxOzFIG1sxOzM2bVRIRSBMQVNUIEJFQUNPTiAgfCAgNjB4MTQbWzBtG1syOzFIG1sxOzMzbUxhbnRlcm4gUXVheRtbMG0bWzM7MUgbWzBtVGhlIHNob3JlIGxpZ2h0IGhhcyBnb25lIGRhcmsuG1swbRtbNDsxSBtbMG1FeGl0czogbm9ydGgsIGVhc3QbWzBtG1s1OzFIG1swbU9uIHRoZSBzdG9uZXM6IG5vdGhpbmcbWzBtG1s2OzFIG1swbVBhY2s6IGJyYXNzIGtleRtbMG0bWzc7MUgbWzBtQmVhY29uOiBkYXJrG1swbRtbODsxSBtbMm1BcnJvd3MgbW92ZS4gVHlwZSBoZWxwIG9yIHF1aXQuG1swbRtbMTM7MUgbWzBtWW91IHRha2UgdGhlIGJyYXNzIGtleS4bWzBtG1sxNDsxSBtbMTszNm0+IBtbMG0bWz8yMDI2bA==", + "screen": "size=60x14 cursor=(13,2,vis=True) alt=True modes=[DECCKM,BRACKETED_PASTE]\n┌────────────────────────────────────────────────────────────┐\n│THE LAST BEACON | 60x14 │\n│Lantern Quay │\n│The shore light has gone dark. │\n│Exits: north, east │\n│On the stones: nothing │\n│Pack: brass key │\n│Beacon: dark │\n│Arrows move. Type help or quit. │\n│ │\n│ │\n│ │\n│ │\n│You take the brass key. │\n│> │\n└────────────────────────────────────────────────────────────┘\nstyles:\n r0[0..25]: bold fg=cyan\n r1[0..12]: bold fg=yellow\n r7[0..31]: dim\n r13[0..2]: bold fg=cyan" + }, + { + "name": "hall", + "rows": 14, + "cols": 60, + "output": "G1s/MjAyNmgbW0gbWzJKG1sxOzFIG1sxOzM2bVRIRSBMQVNUIEJFQUNPTiAgfCAgNjB4MTQbWzBtG1syOzFIG1sxOzMzbUJlYWNvbiBIYWxsG1swbRtbMzsxSBtbMG1BIGJyYXNzIGxvY2sgaG9sZHMgdGhlIHdpY2suG1swbRtbNDsxSBtbMG1FeGl0czogc291dGgbWzBtG1s1OzFIG1swbU9uIHRoZSBzdG9uZXM6IG5vdGhpbmcbWzBtG1s2OzFIG1swbVBhY2s6IGJyYXNzIGtleRtbMG0bWzc7MUgbWzBtQmVhY29uOiBkYXJrG1swbRtbODsxSBtbMm1BcnJvd3MgbW92ZS4gVHlwZSBoZWxwIG9yIHF1aXQuG1swbRtbMTM7MUgbWzBtWW91IGdvIG5vcnRoLhtbMG0bWzE0OzFIG1sxOzM2bT4gG1swbRtbPzIwMjZs", + "screen": "size=60x14 cursor=(13,2,vis=True) alt=True modes=[DECCKM,BRACKETED_PASTE]\n┌────────────────────────────────────────────────────────────┐\n│THE LAST BEACON | 60x14 │\n│Beacon Hall │\n│A brass lock holds the wick. │\n│Exits: south │\n│On the stones: nothing │\n│Pack: brass key │\n│Beacon: dark │\n│Arrows move. Type help or quit. │\n│ │\n│ │\n│ │\n│ │\n│You go north. │\n│> │\n└────────────────────────────────────────────────────────────┘\nstyles:\n r0[0..25]: bold fg=cyan\n r1[0..11]: bold fg=yellow\n r7[0..31]: dim\n r13[0..2]: bold fg=cyan" + }, + { + "name": "resize", + "rows": 10, + "cols": 45, + "output": "G1s/MjAyNmgbW0gbWzJKG1sxOzFIG1sxOzM2bVRIRSBMQVNUIEJFQUNPTiAgfCAgNDV4MTAbWzBtG1syOzFIG1sxOzMzbUJlYWNvbiBIYWxsG1swbRtbMzsxSBtbMG1BIGJyYXNzIGxvY2sgaG9sZHMgdGhlIHdpY2suG1swbRtbNDsxSBtbMG1FeGl0czogc291dGgbWzBtG1s1OzFIG1swbU9uIHRoZSBzdG9uZXM6IG5vdGhpbmcbWzBtG1s2OzFIG1swbVBhY2s6IGJyYXNzIGtleRtbMG0bWzc7MUgbWzBtQmVhY29uOiBkYXJrG1swbRtbODsxSBtbMm1BcnJvd3MgbW92ZS4gVHlwZSBoZWxwIG9yIHF1aXQuG1swbRtbOTsxSBtbMG1Zb3UgZ28gbm9ydGguG1swbRtbMTA7MUgbWzE7MzZtPiAbWzBtG1s/MjAyNmw=", + "screen": "size=45x10 cursor=(9,2,vis=True) alt=True modes=[DECCKM,BRACKETED_PASTE]\n┌─────────────────────────────────────────────┐\n│THE LAST BEACON | 45x10 │\n│Beacon Hall │\n│A brass lock holds the wick. │\n│Exits: south │\n│On the stones: nothing │\n│Pack: brass key │\n│Beacon: dark │\n│Arrows move. Type help or quit. │\n│You go north. │\n│> │\n└─────────────────────────────────────────────┘\nstyles:\n r0[0..25]: bold fg=cyan\n r1[0..11]: bold fg=yellow\n r7[0..31]: dim\n r9[0..2]: bold fg=cyan" + }, + { + "name": "win", + "rows": 10, + "cols": 45, + "output": "G1s/MjAyNmgbW0gbWzJKG1sxOzFIG1sxOzM2bVRIRSBMQVNUIEJFQUNPTiAgfCAgNDV4MTAbWzBtG1syOzFIG1sxOzMzbUJlYWNvbiBIYWxsG1swbRtbMzsxSBtbMG1BIGJyYXNzIGxvY2sgaG9sZHMgdGhlIHdpY2suG1swbRtbNDsxSBtbMG1FeGl0czogc291dGgbWzBtG1s1OzFIG1swbU9uIHRoZSBzdG9uZXM6IG5vdGhpbmcbWzBtG1s2OzFIG1swbVBhY2s6IGJyYXNzIGtleRtbMG0bWzc7MUgbWzBtQmVhY29uOiBkYXJrG1swbRtbODsxSBtbMm1BcnJvd3MgbW92ZS4gVHlwZSBoZWxwIG9yIHF1aXQuG1swbRtbOTsxSBtbMG1Zb3UgZ28gbm9ydGguG1swbRtbMTA7MUgbWzE7MzZtPiBsaWdodCBiZWFjb24bWzBtG1s/MjAyNmwbWz8yMDI2aBtbSBtbMkobWzE7MUgbWzE7MzZtVEhFIExBU1QgQkVBQ09OICB8ICA0NXgxMBtbMG0bWzI7MUgbWzE7MzNtQmVhY29uIEhhbGwbWzBtG1szOzFIG1swbUEgYnJhc3MgbG9jayBob2xkcyB0aGUgd2ljay4bWzBtG1s0OzFIG1swbUV4aXRzOiBzb3V0aBtbMG0bWzU7MUgbWzBtT24gdGhlIHN0b25lczogbm90aGluZxtbMG0bWzY7MUgbWzBtUGFjazogYnJhc3Mga2V5G1swbRtbNzsxSBtbMG1CZWFjb246IGxpdBtbMG0bWzg7MUgbWzJtQXJyb3dzIG1vdmUuIFR5cGUgaGVscCBvciBxdWl0LhtbMG0bWzk7MUgbWzE7MzJtVGhlIGJlYWNvbiBpcyBsaXQhG1swbRtbMTA7MUgbWzE7MzZtPiAbWzBtG1s/MjAyNmw=", + "screen": "size=45x10 cursor=(9,2,vis=True) alt=True modes=[DECCKM,BRACKETED_PASTE]\n┌─────────────────────────────────────────────┐\n│THE LAST BEACON | 45x10 │\n│Beacon Hall │\n│A brass lock holds the wick. │\n│Exits: south │\n│On the stones: nothing │\n│Pack: brass key │\n│Beacon: lit │\n│Arrows move. Type help or quit. │\n│The beacon is lit! │\n│> │\n└─────────────────────────────────────────────┘\nstyles:\n r0[0..25]: bold fg=cyan\n r1[0..11]: bold fg=yellow\n r7[0..31]: dim\n r8[0..18]: bold fg=green\n r9[0..2]: bold fg=cyan" + } +] diff --git a/tests/test_example_last_beacon.py b/tests/test_example_last_beacon.py new file mode 100644 index 00000000..d50c7397 --- /dev/null +++ b/tests/test_example_last_beacon.py @@ -0,0 +1,173 @@ +"""Tests for the bundled ``examples/last_beacon`` interactive walkthrough.""" + +from __future__ import annotations + +import importlib.util +import json +import os +import pathlib +import subprocess +import sys +import types + +import pytest + +from libvt import Terminal +from libvt.input import KeyEvent +from libvt.modes import Mode + +_EXAMPLE_DIR = pathlib.Path(__file__).resolve().parents[1] / "examples" / "last_beacon" + + +def _load_example(name: str) -> types.ModuleType: + module_name = f"_last_beacon_{name}" + path = _EXAMPLE_DIR / f"{name}.py" + spec = importlib.util.spec_from_file_location(module_name, path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + previous = sys.modules.get(module_name) + sys.modules[module_name] = module + try: + spec.loader.exec_module(module) + finally: + if previous is None: + sys.modules.pop(module_name, None) + else: + sys.modules[module_name] = previous + return module + + +def test_last_beacon_replay_assert_victory_and_validation( + tmp_path: pathlib.Path, +) -> None: + """Exercise replay determinism, full-span victory checks, and schema rejection.""" + tour = _load_example("tour") + bundled = _EXAMPLE_DIR / "walkthrough.json" + + snap_1 = tour.replay(bundled, chunk_size=1) + snap_17 = tour.replay(bundled, chunk_size=17) + assert snap_1.lines == snap_17.lines + assert (snap_1.rows, snap_1.cols) == (10, 45) + assert Mode.DECCKM in snap_1.modes + + # 1-row snapshot raises ValueError instead of uncaught IndexError. + tiny = Terminal(rows=1, cols=20) + tiny.feed(b"The beacon is lit!") + with pytest.raises(ValueError, match="at least 2 rows"): + tour.assert_victory(tiny.committed) + + # Wrong text, red style, partial-span style, and moved cursor all fail. + bad_wrong = Terminal(rows=3, cols=24) + bad_wrong.feed(b"\x1b[2;1H\x1b[1;32mNot lit!\x1b[0m\x1b[3;3H") + with pytest.raises(ValueError, match="Expected 'The beacon is lit!'"): + tour.assert_victory(bad_wrong.committed) + + bad_red = Terminal(rows=3, cols=24) + bad_red.feed(b"\x1b[2;1H\x1b[1;31mThe beacon is lit!\x1b[0m\x1b[3;3H") + with pytest.raises(ValueError, match="wrong style"): + tour.assert_victory(bad_red.committed) + + bad_partial = Terminal(rows=3, cols=24) + bad_partial.feed(b"\x1b[2;1H\x1b[1;32mT\x1b[0mhe beacon is lit!\x1b[3;3H") + with pytest.raises(ValueError, match="wrong style"): + tour.assert_victory(bad_partial.committed) + + bad_cursor = Terminal(rows=3, cols=24) + bad_cursor.feed(b"\x1b[2;1H\x1b[1;32mThe beacon is lit!\x1b[0m\x1b[3;1H") + with pytest.raises(ValueError, match="cursor moved"): + tour.assert_victory(bad_cursor.committed) + + # Invalid chunk_size and malformed recordings are rejected cleanly. + with pytest.raises(ValueError, match="positive"): + tour.replay(bundled, chunk_size=0) + + for payload in ( + "[]", + "{}", + "[{}]", + json.dumps( + [{"name": "a", "rows": True, "cols": 10, "output": "", "screen": ""}] + ), + json.dumps( + [{"name": "a", "rows": 2, "cols": 10, "output": "!!!", "screen": ""}] + ), + ): + bad_file = tmp_path / "bad.json" + bad_file.write_text(payload, encoding="utf-8") + with pytest.raises(ValueError): # noqa: PT011 - covers JSON/base64/schema errors + tour.replay(bad_file, chunk_size=1) + + cli_bad_chunk = subprocess.run( + [ + sys.executable, + str(_EXAMPLE_DIR / "tour.py"), + "--replay", + "--chunk-size", + "0", + ], + capture_output=True, + text=True, + check=False, + ) + assert cli_bad_chunk.returncode == 2 + assert "--chunk-size must be positive" in cli_bad_chunk.stderr + + +def test_last_beacon_game_editor_and_win32_guards( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Exercise split-byte CSI/SS3/paste input and Windows raw_terminal guard.""" + game = _load_example("game") + editor = game.Editor() + + # Split SS3 Up (\x1bOA) and CSI Down (\x1b[B) one byte at a time. + commands: list[str] = [] + for byte in b"\x1bOA\x1b[B": + commands.extend(editor.feed(bytes([byte]))) + assert commands == ["north", "south"] + + # Bracketed paste, backspace, enter, and Ctrl-D. + pasted = list(editor.feed(b"\x1b[200~take keyx\x1b[201~\x7f\r\x04")) + assert pasted == ["take key", "quit"] + + # Windows guard rejects raw_terminal() cleanly. + monkeypatch.setattr(sys, "platform", "win32") + with ( + pytest.raises(NotImplementedError, match="POSIX terminal"), + game.raw_terminal(), + ): + pass + + +@pytest.mark.skipif(os.name != "posix", reason="live PTY tour requires POSIX") +def test_last_beacon_live_matches_bundled_walkthrough(tmp_path: pathlib.Path) -> None: + """Verify live game.py matches bundled walkthrough.json and DECCKM encoding.""" + # Verify libvt encodes Up as SS3 (\x1bOA) when DECCKM is enabled. + term = Terminal(rows=14, cols=60) + term.feed(b"\x1b[?1h") + assert term.encode(KeyEvent("up")) == b"\x1bOA" + + trace = tmp_path / "recorded.json" + run = subprocess.run( + [ + sys.executable, + "-O", + str(_EXAMPLE_DIR / "tour.py"), + "--record", + str(trace), + ], + capture_output=True, + text=True, + timeout=30, + check=False, + ) + assert run.returncode == 0, run.stdout + run.stderr + assert "The beacon is lit!" in run.stdout + + recorded = json.loads(trace.read_text(encoding="utf-8")) + bundled = json.loads( + (_EXAMPLE_DIR / "walkthrough.json").read_text(encoding="utf-8") + ) + assert [(f["name"], f["rows"], f["cols"], f["screen"]) for f in recorded] == [ + (f["name"], f["rows"], f["cols"], f["screen"]) for f in bundled + ]