gutendex: send a User-Agent (Cloudflare 403s the default urllib agent)

Gutendex.com sits behind Cloudflare, which rejects urllib's default
`Python-urllib/<ver>` User-Agent with HTTP 403. Both skills therefore failed
on their first real call ("could not reach the Gutendex catalog ... HTTP Error
403"); the hermetic loopback tests cannot catch this by design.

Send an identifying `USER_AGENT` on every request (the /books catalog lookup
and the plain-text download) and assert it in each skill's test so the
regression is caught locally.

Verified with a real run: find_books returned 41 live results for
"jane austen"; read_book downloaded and saved Pride and Prejudice (1342).
This commit is contained in:
gabby committed 2026-10-17 08:18:13 +00:00
1 parent b775069613
commit 52346baf52
4 files changed
+67 -5

No files matched your search

+26 -1
View File
@@ -53,6 +53,7 @@ class Handler(BaseHTTPRequestHandler):
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)
@@ -94,10 +95,11 @@ def book(book_id, title, author, url, mime="text/plain; charset=utf-8"):
def start_server():
handler = type("Handler", (Handler,), {"seen": []})
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 = []
@@ -206,6 +208,28 @@ def test_missing_plain_text_format_is_reported():
shutil.rmtree(output_dir, ignore_errors=True)
def test_sends_an_identifying_user_agent():
# Gutendex's Cloudflare front 403s the default `Python-urllib/<ver>` 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()
@@ -230,6 +254,7 @@ def main():
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()
print("ok")