"""Hermetic mechanics test for gutendex.read_book. Run from this folder: `python skill.test.py`. No external network: a loopback http.server plays the Gutendex `/books` and `/books/` routes plus the plain-text download. This proves the body resolves a book (by name or id), selects among several candidates with a SemIf decision, downloads the real text into `output_dir`, and reports real failures honestly. It does NOT prove the live integration — only a real run against Gutendex does. """ import json import os import shutil import sys import tempfile import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from semif_agent.decisions import DecisionResult, Request from semif_agent.skills import ActionContext import skill TEXT_BODY = "It is a truth universally acknowledged...\n\nCHAPTER I.\n" class FakeEngine: """Test-only stand-in that always selects one declared option.""" def __init__(self, selected): self.selected = selected self.calls = [] def call(self, decision): self.calls.append(decision) ids = [option.id for option in decision.options] return DecisionResult( request=decision, option_ids=ids, probabilities=[1.0 if oid == self.selected else 0.0 for oid in ids], ) class Handler(BaseHTTPRequestHandler): def _send(self, payload, status, content_type="application/json"): raw = payload if isinstance(payload, bytes) else json.dumps(payload).encode("utf-8") self.send_response(status) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(raw))) self.end_headers() self.wfile.write(raw) def do_GET(self): self.server.seen.append(self.path) self.server.user_agents.append(self.headers.get("User-Agent")) if self.path.startswith("/books/"): book_id = self.path.rsplit("/", 1)[-1].split("?")[0] book = self.server.by_id.get(book_id) if book is None: self._send({"detail": "not found"}, 404) return self._send(book, 200) return if self.path.startswith("/books"): self._send( { "count": len(self.server.search_results), "next": None, "previous": None, "results": self.server.search_results, }, 200, ) return if self.path.startswith("/text/"): if self.server.text_status != 200: self._send({"detail": "boom"}, self.server.text_status) return self._send(self.server.text_body.encode("utf-8"), 200, "text/plain") return self._send({"detail": "not found"}, 404) def log_message(self, *args): pass def book(book_id, title, author, url, mime="text/plain; charset=utf-8"): return { "id": book_id, "title": title, "authors": [{"name": author, "birth_year": 1775, "death_year": 1817}], "formats": {mime: f"{url}/text/{book_id}.txt"}, } def start_server(): handler = type("Handler", (Handler,), {"seen": [], "user_agents": []}) server = ThreadingHTTPServer(("127.0.0.1", 0), handler) url = f"http://127.0.0.1:{server.server_address[1]}" server.seen = handler.seen server.user_agents = handler.user_agents server.text_body = TEXT_BODY server.text_status = 200 server.search_results = [] server.by_id = {} threading.Thread(target=server.serve_forever, daemon=True).start() return server, url def run(url, output_dir, text, selected="1"): engine = FakeEngine(selected) ctx = ActionContext( engine=engine, config={"gutendex_base_url": url, "output_dir": output_dir} ) return skill.act(ctx, Request(text)), engine class FakeSpeech: """A speech-channel double: records read-aloud requests, speaks nothing.""" def __init__(self, stream_sources=("voice", "lxmf")): self.reads = [] self.stream_sources = set(stream_sources) def supports(self, source): return str(source or "").split(":", 1)[0] in self.stream_sources def read_aloud(self, **kwargs): self.reads.append(kwargs) return kwargs def run_voice(url, output_dir, text, source="voice:mic", selected="1"): engine = FakeEngine(selected) speech = FakeSpeech() ctx = ActionContext( engine=engine, config={"gutendex_base_url": url, "output_dir": output_dir}, speech=speech, ) request = Request(text, source=source, origin_source=source) return skill.act(ctx, request), engine, speech def save_library(output_dir, book_id, slug, text): """Pre-save a book into the local library (as a previous run would).""" path = Path(output_dir) / f"gutenberg-{book_id}-{slug}.txt" path.write_text(text, encoding="utf-8") return path def test_reads_a_named_book(): server, url = start_server() output_dir = tempfile.mkdtemp() try: pride = book(1342, "Pride and Prejudice", "Jane Austen", url) server.search_results = [pride] server.by_id["1342"] = pride action, engine = run(url, output_dir, "read pride and prejudice") assert not engine.calls, "a single match needs no decision" files = os.listdir(output_dir) assert len(files) == 1, files saved = os.path.join(output_dir, files[0]) assert Path(saved).read_text(encoding="utf-8") == TEXT_BODY assert "Pride and Prejudice" in action.action_log, action.action_log assert saved in action.action_log, action.action_log print(action.action_log) finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_reads_by_gutenberg_id(): server, url = start_server() output_dir = tempfile.mkdtemp() try: pride = book(1342, "Pride and Prejudice", "Jane Austen", url) server.by_id["1342"] = pride action, _engine = run(url, output_dir, "read gutenberg book 1342") assert any(path == "/books/1342" for path in server.seen), server.seen assert os.listdir(output_dir), "the text must be saved" assert "1342" in action.action_log, action.action_log print(action.action_log) finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_picks_among_candidates(): server, url = start_server() output_dir = tempfile.mkdtemp() try: first = book(98, "A Tale of Two Cities", "Charles Dickens", url) second = book(1400, "Great Expectations", "Charles Dickens", url) server.search_results = [first, second] server.by_id["98"] = first server.by_id["1400"] = second action, engine = run(url, output_dir, "read a tale of two cities", selected="98") assert len(engine.calls) == 1, "several matches need a decision" assert engine.calls[0].options[0].id == "98" assert "A Tale of Two Cities" in action.action_log, action.action_log print(action.action_log) finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_no_match_asks_for_a_book(): server, url = start_server() output_dir = tempfile.mkdtemp() try: action, _engine = run(url, output_dir, "read zzzz nonexistent zzzz") assert action.needs_input, "no match must ask which book" assert os.listdir(output_dir) == [] print(action.needs_input) finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_missing_plain_text_format_is_reported(): server, url = start_server() output_dir = tempfile.mkdtemp() try: html_only = book( 7, "Only HTML", "Someone", url, mime="text/html; charset=utf-8" ) server.search_results = [html_only] server.by_id["7"] = html_only action, _engine = run(url, output_dir, "read only html") assert "plain-text" in action.action_log, action.action_log assert os.listdir(output_dir) == [] print(action.action_log) finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_sends_an_identifying_user_agent(): # Gutendex's Cloudflare front 403s the default `Python-urllib/` agent, # so both the catalog lookup and the text download must identify themselves. server, url = start_server() output_dir = tempfile.mkdtemp() try: pride = book(1342, "Pride and Prejudice", "Jane Austen", url) server.search_results = [pride] server.by_id["1342"] = pride run(url, output_dir, "read pride and prejudice") assert server.user_agents, "no request was made" assert all(ua == skill.USER_AGENT for ua in server.user_agents), server.user_agents assert not any( str(ua).startswith("Python-urllib") for ua in server.user_agents ), server.user_agents print("user-agents:", server.user_agents) finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_download_failure_is_reported_honestly(): server, url = start_server() output_dir = tempfile.mkdtemp() try: server.text_status = 502 pride = book(1342, "Pride and Prejudice", "Jane Austen", url) server.search_results = [pride] server.by_id["1342"] = pride action, _engine = run(url, output_dir, "read pride and prejudice") assert "502" in action.action_log, action.action_log assert os.listdir(output_dir) == [] print(action.action_log) finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_voice_reads_aloud_and_records_a_start(): # Over the voice gateway the saved book is registered for read-aloud, not # reported as a file path: the front end streams it until the user stops. server, url = start_server() output_dir = tempfile.mkdtemp() try: pride = book(1342, "Pride and Prejudice", "Jane Austen", url) server.search_results = [pride] server.by_id["1342"] = pride action, _engine, speech = run_voice(url, output_dir, "read pride and prejudice") assert len(speech.reads) == 1, speech.reads read = speech.reads[0] assert read["key"] == "gutenberg-1342", read assert read["start"] == 0, read assert read["source"] == "voice:mic", read assert read["path"].endswith(".txt"), read assert read["bookmarks_path"].endswith("bookmarks.json"), read assert "Reading" in action.action_log, action.action_log assert os.listdir(output_dir), "the text must still be saved" print(action.action_log) finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_voice_resumes_from_a_bookmark(): server, url = start_server() output_dir = tempfile.mkdtemp() try: pride = book(1342, "Pride and Prejudice", "Jane Austen", url) server.search_results = [pride] server.by_id["1342"] = pride bookmarks = os.path.join(output_dir, "bookmarks.json") with open(bookmarks, "w", encoding="utf-8") as handle: json.dump({"gutenberg-1342": {"offset": 12}}, handle) action, _engine, speech = run_voice(url, output_dir, "read pride and prejudice") assert speech.reads[0]["start"] == 12, speech.reads assert "Resuming" in action.action_log, action.action_log print(action.action_log) finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_voice_finished_book_starts_over(): # A bookmark at (or past) the end means the book was finished; a new request # starts from the beginning rather than replaying the final chunk. server, url = start_server() output_dir = tempfile.mkdtemp() try: pride = book(1342, "Pride and Prejudice", "Jane Austen", url) server.search_results = [pride] server.by_id["1342"] = pride bookmarks = os.path.join(output_dir, "bookmarks.json") with open(bookmarks, "w", encoding="utf-8") as handle: json.dump({"gutenberg-1342": {"offset": len(TEXT_BODY)}}, handle) _action, _engine, speech = run_voice(url, output_dir, "read pride and prejudice") assert speech.reads[0]["start"] == 0, speech.reads finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_non_voice_source_does_not_read_aloud(): # A typed (or messenger) request still gets the saved-file summary; only the # voice gateway reads aloud. server, url = start_server() output_dir = tempfile.mkdtemp() try: pride = book(1342, "Pride and Prejudice", "Jane Austen", url) server.search_results = [pride] server.by_id["1342"] = pride _action, _engine, speech = run_voice( url, output_dir, "read pride and prejudice", source="typed" ) assert speech.reads == [], speech.reads finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_uses_the_local_library_by_name_without_network(): # A book already saved is read from disk: the catalog is never contacted. server, url = start_server() output_dir = tempfile.mkdtemp() try: saved = save_library(output_dir, 1342, "pride-and-prejudice", TEXT_BODY) action, _engine = run(url, output_dir, "read pride and prejudice") assert server.seen == [], f"the catalog must not be contacted: {server.seen}" assert "library" in action.action_log, action.action_log assert str(saved) in action.action_log, action.action_log assert Path(saved).read_text(encoding="utf-8") == TEXT_BODY print(action.action_log) finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_uses_the_local_library_by_id_without_network(): server, url = start_server() output_dir = tempfile.mkdtemp() try: save_library(output_dir, 1342, "pride-and-prejudice", TEXT_BODY) action, _engine = run(url, output_dir, "read gutenberg book 1342") assert server.seen == [], f"the catalog must not be contacted: {server.seen}" assert "library" in action.action_log, action.action_log print(action.action_log) finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_ambiguous_local_match_falls_back_to_the_catalog(): # Two saved books match the name; the human picks through the catalog. server, url = start_server() output_dir = tempfile.mkdtemp() try: save_library(output_dir, 98, "a-tale-of-two-cities", "OLD") save_library(output_dir, 1400, "tale-of-two-cities-notes", "OLD") first = book(98, "A Tale of Two Cities", "Charles Dickens", url) server.search_results = [first] server.by_id["98"] = first action, _engine = run(url, output_dir, "read a tale of two cities") assert any(path.startswith("/books") for path in server.seen), server.seen assert "A Tale of Two Cities" in action.action_log, action.action_log finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_reuses_a_saved_book_resolved_from_the_catalog(): # The catalog resolves the id, but the text is already saved: reuse it # rather than downloading the text again. server, url = start_server() output_dir = tempfile.mkdtemp() try: save_library(output_dir, 1342, "pride-and-prejudice", TEXT_BODY) # A name that does not match the saved slug forces the catalog lookup. pride = book(1342, "Pride and Prejudice", "Jane Austen", url) server.search_results = [pride] server.by_id["1342"] = pride action, _engine = run(url, output_dir, "read austen novel") assert any(path.startswith("/books") for path in server.seen), server.seen assert not any(path.startswith("/text/") for path in server.seen), server.seen assert "library" in action.action_log, action.action_log print(action.action_log) finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_voice_reads_from_the_local_library(): server, url = start_server() output_dir = tempfile.mkdtemp() try: saved = save_library(output_dir, 1342, "pride-and-prejudice", TEXT_BODY) _action, _engine, speech = run_voice(url, output_dir, "read pride and prejudice") assert server.seen == [], f"the catalog must not be contacted: {server.seen}" assert len(speech.reads) == 1, speech.reads assert speech.reads[0]["path"] == str(saved), speech.reads assert "library" in _action.action_log, _action.action_log finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def test_reads_aloud_over_a_voice_messenger_too(): # The read-aloud path is not voice-gateway-specific: any front end the # scheduler reports as streamable (here the LXMF voice gateway) gets it. server, url = start_server() output_dir = tempfile.mkdtemp() try: save_library(output_dir, 1342, "pride-and-prejudice", TEXT_BODY) action, _engine, speech = run_voice( url, output_dir, "read pride and prejudice", source="lxmf:ab" * 1 ) assert len(speech.reads) == 1, speech.reads assert speech.reads[0]["source"].startswith("lxmf:"), speech.reads assert "Reading" in action.action_log, action.action_log finally: server.shutdown() server.server_close() shutil.rmtree(output_dir, ignore_errors=True) def main(): test_reads_a_named_book() test_reads_by_gutenberg_id() test_picks_among_candidates() test_no_match_asks_for_a_book() test_missing_plain_text_format_is_reported() test_sends_an_identifying_user_agent() test_download_failure_is_reported_honestly() test_voice_reads_aloud_and_records_a_start() test_voice_resumes_from_a_bookmark() test_voice_finished_book_starts_over() test_non_voice_source_does_not_read_aloud() test_uses_the_local_library_by_name_without_network() test_uses_the_local_library_by_id_without_network() test_ambiguous_local_match_falls_back_to_the_catalog() test_reuses_a_saved_book_resolved_from_the_catalog() test_voice_reads_from_the_local_library() test_reads_aloud_over_a_voice_messenger_too() print("ok") if __name__ == "__main__": try: main() except AssertionError as exc: print(f"FAILED: {exc}") sys.exit(1)