gutendex: add Project Gutenberg pack (find books, read full text)
This commit is contained in:
commit
9a41f66fd6
11 files changed
+885
No files matched your search
@@ -0,0 +1,188 @@
|
||||
"""Hermetic mechanics test for gutendex.find_books.
|
||||
|
||||
Run from this folder: `python skill.test.py`. No external network: a loopback
|
||||
http.server plays the public Gutendex `/books` route and asserts the query the
|
||||
body built. This proves the body reads its base URL from config, extracts search
|
||||
terms, picks the search/topic parameter via a SemIf decision, and reports real
|
||||
failures and empty results honestly. It does NOT prove the live integration —
|
||||
only a real run against Gutendex does.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
from semif_agent.decisions import DecisionResult, Request
|
||||
from semif_agent.skills import ActionContext
|
||||
|
||||
import skill
|
||||
|
||||
|
||||
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],
|
||||
)
|
||||
|
||||
|
||||
FIXTURE_BOOKS = [
|
||||
{
|
||||
"id": 98,
|
||||
"title": "A Tale of Two Cities",
|
||||
"authors": [{"name": "Charles Dickens", "birth_year": 1812, "death_year": 1870}],
|
||||
"subjects": ["France -- History -- Revolution, 1789-1799 -- Fiction"],
|
||||
"formats": {"text/plain; charset=utf-8": "https://example.org/98.txt"},
|
||||
},
|
||||
{
|
||||
"id": 1400,
|
||||
"title": "Great Expectations",
|
||||
"authors": [{"name": "Charles Dickens", "birth_year": 1812, "death_year": 1870}],
|
||||
"subjects": ["England -- Fiction"],
|
||||
"formats": {"text/plain; charset=utf-8": "https://example.org/1400.txt"},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def _send(self, payload, status):
|
||||
raw = json.dumps(payload).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
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)
|
||||
if self.server.status != 200:
|
||||
self._send({"detail": "boom"}, self.server.status)
|
||||
return
|
||||
if self.path.startswith("/books"):
|
||||
self._send(
|
||||
{
|
||||
"count": self.server.count,
|
||||
"next": None,
|
||||
"previous": None,
|
||||
"results": self.server.results,
|
||||
},
|
||||
200,
|
||||
)
|
||||
return
|
||||
self._send({"detail": "not found"}, 404)
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
|
||||
def start_server(status=200, results=None, count=None):
|
||||
handler = type("Handler", (Handler,), {"status": status, "seen": []})
|
||||
server = ThreadingHTTPServer(("127.0.0.1", 0), handler)
|
||||
server.seen = handler.seen
|
||||
server.status = status
|
||||
server.results = FIXTURE_BOOKS if results is None else results
|
||||
server.count = len(server.results) if count is None else count
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
return server, f"http://127.0.0.1:{server.server_address[1]}"
|
||||
|
||||
|
||||
def run(url, text, selected="search"):
|
||||
engine = FakeEngine(selected)
|
||||
ctx = ActionContext(engine=engine, config={"gutendex_base_url": url})
|
||||
return skill.act(ctx, Request(text)), engine
|
||||
|
||||
|
||||
def test_searches_by_author_or_title():
|
||||
server, url = start_server()
|
||||
try:
|
||||
action, engine = run(url, "find books by charles dickens", selected="search")
|
||||
assert len(engine.calls) == 1, "one mode decision"
|
||||
assert any(
|
||||
path.startswith("/books?") and "search=charles+dickens" in path
|
||||
for path in server.seen
|
||||
), server.seen
|
||||
assert "A Tale of Two Cities" in action.action_log, action.action_log
|
||||
assert action.new_state == action.action_log
|
||||
assert action.decisions and action.decisions[0][1].selected == "search"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_searches_by_genre_via_topic():
|
||||
server, url = start_server()
|
||||
try:
|
||||
action, _engine = run(url, "find science fiction books", selected="topic")
|
||||
assert any(
|
||||
path.startswith("/books?") and "topic=science+fiction" in path
|
||||
for path in server.seen
|
||||
), server.seen
|
||||
assert "Found 2" in action.action_log, action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_empty_result_is_reported_plainly():
|
||||
server, url = start_server(results=[], count=0)
|
||||
try:
|
||||
action, _engine = run(url, "find books by nobody at all")
|
||||
assert "No Project Gutenberg books matched" in action.action_log, action.action_log
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_http_failure_is_reported_honestly():
|
||||
server, url = start_server(status=503)
|
||||
try:
|
||||
action, _engine = run(url, "find books by charles dickens")
|
||||
assert "503" in action.action_log, action.action_log
|
||||
assert action.new_state == "find books by charles dickens"
|
||||
print(action.action_log)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def test_missing_query_asks_for_one():
|
||||
server, url = start_server()
|
||||
try:
|
||||
action, engine = run(url, "find books")
|
||||
assert action.needs_input, "a nameless request must ask for search terms"
|
||||
assert not engine.calls, "no decision without a query"
|
||||
assert server.seen == [], "no request without a query"
|
||||
print(action.needs_input)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def main():
|
||||
test_searches_by_author_or_title()
|
||||
test_searches_by_genre_via_topic()
|
||||
test_empty_result_is_reported_plainly()
|
||||
test_http_failure_is_reported_honestly()
|
||||
test_missing_query_asks_for_one()
|
||||
print("ok")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print(f"FAILED: {exc}")
|
||||
sys.exit(1)
|
||||
Reference in new issue
Block a user