Add first test suite; fix Timer resume, scraper silent failure
Deploy with Docker Compose / deploy (push) Successful in 1m0s
Weekly Maintenance / maintenance (push) Successful in 19m9s

- backend/services/auth_test.go: token-version normalisation, the
  revocation rule, GenerateJWT/VerifyJWT claim handling. The happy path
  of AuthenticateTokenWithClaims still needs a DB driver we don't have.
- python/tests: travelodge.py's pure functions and the NDJSON event
  contract. pytest is a commented-out dev dep so the image stays slim.
- Timer.vue: the Paused screen now offers Resume, reaching pauseTimer's
  previously unreachable un-pause branch.
- travelodge.py: warn when upstream parses but yields nothing usable, so
  a field rename is distinguishable from sold-out inventory.
- CoverLetters.vue moved out of views/unused/ — it is live on /cv.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
2026-09-17 02:55:18 +01:00
co-authored by Claude Opus 5
parent 25ac1cde1c
commit 22c6229c42
10 changed files with 815 additions and 4 deletions
+27 -1
View File
@@ -58,6 +58,7 @@ Time budgets
instead of the whole request dying at the nginx 300s proxy timeout.
"""
import logging
import math
import os
import threading
@@ -68,6 +69,11 @@ from datetime import date, datetime, timedelta
import requests
# Every upstream field is read tolerantly, so a Travelodge schema change would
# otherwise be indistinguishable from genuinely sold-out inventory. This logger
# is the only signal that the difference exists - see `hotels_for`.
log = logging.getLogger(__name__)
TL_API = "https://www.travelodge.co.uk/api/v2/hotel"
TL_SITE = "https://www.travelodge.co.uk"
TFL_API = "https://api.tfl.gov.uk/Journey/JourneyResults/{frm}/to/{to}"
@@ -432,7 +438,27 @@ def hotels_for(location, checkin, checkout, rooms, deadline=None):
# The fetch deliberately happens outside any cache lock: a slow upstream
# must not block other threads reading the cache. Two threads racing on the
# same key both fetch and the second write wins, which is harmless.
hotels = [normalise_hotel(h) for h in fetch_hotels(location, checkin, checkout, rooms, deadline=deadline)]
raw = fetch_hotels(location, checkin, checkout, rooms, deadline=deadline)
hotels = [normalise_hotel(h) for h in raw]
# A response that parsed but yielded nothing usable is the fingerprint of a
# renamed upstream field: the tolerant .get()s in `normalise_hotel` turn a
# schema change into "no hotels available", which looks exactly like a
# sold-out search. Genuine sold-out inventory still carries names and codes,
# so warn only when the shape itself came back empty.
if raw and not any(h["code"] and h["name"] for h in hotels):
log.warning(
"Travelodge returned %d hotels for %r (%s..%s) but none had a usable "
"code/name - upstream field names may have changed",
len(raw), location, checkin, checkout,
)
elif raw and not any(h["available"] and h["room_price"] is not None for h in hotels):
log.warning(
"Travelodge returned %d hotels for %r (%s..%s) but none were priced "
"and available - sold out, or minPrice/hasAvailability renamed",
len(raw), location, checkin, checkout,
)
_tl_cache.set(key, hotels)
return hotels
+5
View File
@@ -1,3 +1,8 @@
fastapi==0.115.6
uvicorn[standard]==0.34.0
requests==2.32.3
# Dev only, deliberately commented out so the image stays slim: the test suite
# (python/tests) needs pytest. Install it with `pip install pytest` locally and
# run `python -m pytest` from this directory.
# pytest==9.0.3
+11
View File
@@ -0,0 +1,11 @@
"""Make `python/` importable so `app.travelodge` resolves.
The Docker image runs uvicorn from /python with the app as a package, but
pytest is run from wherever the developer happens to be, so the package root is
put on sys.path explicitly rather than relying on rootdir inference.
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+354
View File
@@ -0,0 +1,354 @@
"""Tests for the NDJSON event contract of the streaming hotel endpoints.
The Vue frontend splits the response on newlines and JSON-parses each line, so
the contract under test is: one complete JSON object per line, the documented
event names, the right payload key per event kind, `exclude_none` dropping
absent keys, and the framing headers that stop nginx buffering the stream.
No scraping and no network happens here: `_run_events` takes the upstream
generator as a callable, so a fake generator stands in for travelodge and the
whole streaming skin can be exercised on its own.
"""
import asyncio
import json
from datetime import date, datetime
import pytest
from pydantic import BaseModel
from app import main, travelodge
@pytest.fixture(autouse=True)
def fresh_cache(monkeypatch):
"""Give every test its own response cache.
The cache is module-global and keyed by request JSON, so without this a
test that finishes a stream would serve the next test's identical request
from cache.
"""
monkeypatch.setattr(main, "_cache", travelodge.TTLCache(main.CACHE_TTL_S, max_entries=main.CACHE_MAX))
class FakeRequest(BaseModel):
"""Stand-in for a validated request: `_run_events` only reads model_dump."""
marker: str = "x"
def search_events(make_gen, req=None):
return list(
main._run_events(
req=req or FakeRequest(),
prefix="search:",
model=main.HotelSearchEvent,
make_gen=make_gen,
first_event="hotels",
list_key="rows",
row_keys={"transport": "row"},
)
)
def scan_events(make_gen, req=None):
return list(
main._run_events(
req=req or FakeRequest(),
prefix="scan:",
model=main.HotelScanEvent,
make_gen=make_gen,
first_event="scan",
list_key="nights",
row_keys={"night": "night", "transport": "transport"},
)
)
def hotel_row(code="LON123", **over):
"""A minimal row in the shape travelodge emits (url and route are required)."""
return dict({"code": code, "url": "https://example.test/h", "route": "pricing…"}, **over)
def search_summary(**over):
return dict(
{
"location": "London",
"checkin": date(2030, 1, 1),
"checkout": date(2030, 1, 2),
"nights": 1,
"rooms": 1,
"adults": 1,
"children": 0,
"railcard_holders": 1,
"origin_name": "London Waterloo",
"origin_lat": 51.5031,
"origin_lon": -0.1132,
"depart": datetime(2030, 1, 1, 18, 30),
"max_travel_min": 60,
"hotels_found": 1,
"hotels_available": 1,
"hotels_priced": 0,
},
**over,
)
def read_lines(response):
"""Drain a StreamingResponse into the lines a client would see."""
async def drain():
return [chunk async for chunk in response.body_iterator]
body = "".join(
c.decode() if isinstance(c, (bytes, bytearray)) else c for c in asyncio.run(drain())
)
return body
# --------------------------------------------------------------------------- #
# Framing
# --------------------------------------------------------------------------- #
def test_ndjson_frames_one_json_object_per_line():
events = [
main.HotelSearchEvent(event="hotels", rows=[]),
main.HotelSearchEvent(event="done", rows=[]),
]
body = read_lines(main._ndjson(iter(events)))
assert body.endswith("\n") # every line is terminated, including the last
lines = body.split("\n")[:-1]
assert [json.loads(line)["event"] for line in lines] == ["hotels", "done"]
# A line must never contain a raw newline or the client's split breaks.
assert all("\n" not in line for line in lines)
def test_ndjson_omits_none_fields():
# The reader treats an absent key as null, so exclude_none is part of the
# contract rather than only a size optimisation.
body = read_lines(main._ndjson(iter([main.HotelSearchEvent(event="error", detail="boom")])))
payload = json.loads(body.strip())
assert payload == {"event": "error", "cached": False, "detail": "boom"}
def test_ndjson_headers_defeat_proxy_buffering():
response = main._ndjson(iter([]))
assert response.media_type == "application/x-ndjson"
# Without X-Accel-Buffering nginx holds the whole response and the stream
# is pointless.
assert response.headers["x-accel-buffering"] == "no"
assert response.headers["cache-control"] == "no-cache"
def test_ndjson_of_no_events_is_an_empty_body():
assert read_lines(main._ndjson(iter([]))) == ""
# --------------------------------------------------------------------------- #
# Search event shapes
# --------------------------------------------------------------------------- #
def test_search_events_carry_the_documented_shapes():
summary = search_summary()
rows = [hotel_row()]
def gen():
yield "hotels", dict(summary), rows
yield "transport", hotel_row(route="tube") # run_search emits a 2-tuple here
yield "done", dict(summary, hotels_priced=1), rows
events = search_events(gen)
assert [e.event for e in events] == ["hotels", "transport", "done"]
opening, transport, done = events
assert opening.rows is not None and opening.row is None
assert opening.summary.hotels_priced == 0
# The 2-tuple is normalised to a None summary, which exclude_none then drops.
assert transport.summary is None
assert transport.row.route == "tube"
assert transport.rows is None
assert "summary" not in json.loads(transport.model_dump_json(exclude_none=True))
assert done.rows is not None and done.summary.hotels_priced == 1
assert all(e.cached is False for e in events)
def test_search_stream_serialises_dates_as_iso_strings():
def gen():
yield "hotels", search_summary(), []
line = json.loads(search_events(gen)[0].model_dump_json(exclude_none=True))
assert line["summary"]["checkin"] == "2030-01-01"
assert line["summary"]["depart"].startswith("2030-01-01T18:30")
# --------------------------------------------------------------------------- #
# Scan event shapes
# --------------------------------------------------------------------------- #
def test_scan_events_carry_the_documented_shapes():
summary = {
"location": "London",
"start": date(2030, 1, 1),
"end": date(2030, 1, 8),
"weekdays": [4],
"nights": 1,
"per_night": 3,
"rooms": 1,
"adults": 1,
"children": 0,
"railcard_holders": 1,
"origin_name": "London Waterloo",
"origin_lat": 51.5031,
"origin_lon": -0.1132,
"depart": datetime(2030, 1, 4, 18, 30),
"max_travel_min": 60,
"nights_candidate": 1,
}
night = {"checkin": date(2030, 1, 4), "checkout": date(2030, 1, 5), "status": "ok", "hotels": [hotel_row()]}
def gen():
yield "scan", dict(summary), [night]
yield "night", dict(summary), night
yield "transport", dict(summary), {"code": "LON123", "route": "bus"}
yield "done", dict(summary), [night]
events = scan_events(gen)
assert [e.event for e in events] == ["scan", "night", "transport", "done"]
opening, one_night, transport, done = events
assert opening.nights is not None and opening.night is None
assert one_night.night.status == "ok" and one_night.nights is None
assert transport.transport.code == "LON123" and transport.nights is None
assert done.nights is not None
# --------------------------------------------------------------------------- #
# Caching
# --------------------------------------------------------------------------- #
def test_a_cached_result_replays_as_the_opening_event_plus_done():
summary = search_summary()
rows = [hotel_row()]
calls = []
def gen():
calls.append(1)
yield "hotels", dict(summary), rows
yield "done", dict(summary), rows
req = FakeRequest(marker="cache-me")
assert [e.event for e in search_events(gen, req)] == ["hotels", "done"]
replay = search_events(gen, req)
assert len(calls) == 1 # the upstream generator was not run again
assert [e.event for e in replay] == ["hotels", "done"]
assert all(e.cached for e in replay)
# The replay carries the finished rows on both lines, so a streaming reader
# needs no special case for a cache hit.
assert replay[0].rows == replay[1].rows
def test_different_requests_do_not_share_a_cache_entry():
def gen():
yield "done", search_summary(), []
search_events(gen, FakeRequest(marker="a"))
assert search_events(gen, FakeRequest(marker="b"))[0].cached is False
def test_search_and_scan_caches_cannot_collide():
# Both key on the same request JSON, so only the prefix separates them.
def search_gen():
yield "done", search_summary(), []
def scan_gen():
yield "done", None, []
req = FakeRequest(marker="same")
search_events(search_gen, req)
assert scan_events(scan_gen, req)[0].cached is False
def test_an_unfinished_stream_is_not_cached():
# Only "done" writes the cache, so a stream that errored part-way must be
# re-run rather than replayed as if it had completed.
def gen():
yield "hotels", search_summary(), []
raise travelodge.UpstreamError("Travelodge search failed")
req = FakeRequest(marker="partial")
assert [e.event for e in search_events(gen, req)] == ["hotels", "error"]
assert [e.event for e in search_events(gen, req)] == ["hotels", "error"]
# --------------------------------------------------------------------------- #
# Errors and the single-search guard
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize(
"exc, want_detail",
[
(travelodge.UpstreamError("Travelodge search failed: 503"), "Travelodge search failed: 503"),
(ValueError("no dates in the range match those weekdays"), "no dates in the range match those weekdays"),
(KeyError("minPrice"), "Unexpected upstream response: 'minPrice'"),
(TypeError("NoneType is not subscriptable"), "Unexpected upstream response: NoneType is not subscriptable"),
],
)
def test_upstream_failures_become_a_final_error_event(exc, want_detail):
def gen():
yield "hotels", search_summary(), []
raise exc
events = search_events(gen)
assert [e.event for e in events] == ["hotels", "error"]
assert events[-1].detail == want_detail
def test_a_failure_while_binding_the_generator_is_also_an_error_event():
# make_gen is called inside the guard precisely so this is a stream event
# rather than a 500 from the endpoint.
def gen():
raise ValueError("bad request")
events = search_events(gen)
assert [e.event for e in events] == ["error"]
assert events[0].detail == "bad request"
def test_only_one_search_runs_at_a_time():
main._search_slot.acquire()
try:
events = search_events(lambda: iter([]))
finally:
main._search_slot.release()
assert [e.event for e in events] == ["error"]
assert events[0].detail == main.ALREADY_RUNNING
def test_the_search_slot_is_released_after_a_failure():
# A leaked semaphore would wedge the endpoint for the life of the process.
def gen():
raise travelodge.UpstreamError("boom")
yield # pragma: no cover - makes gen a generator
search_events(gen, FakeRequest(marker="fail-1"))
assert main._search_slot.acquire(blocking=False)
main._search_slot.release()
def test_an_abandoned_stream_releases_the_search_slot():
# The frontend closes the connection when the user navigates away, so the
# generator is closed part-way; the finally in _guarded must still run.
def gen():
yield "hotels", search_summary(), []
yield "done", search_summary(), []
stream = main._run_events(
req=FakeRequest(marker="abandon"),
prefix="search:",
model=main.HotelSearchEvent,
make_gen=gen,
first_event="hotels",
list_key="rows",
row_keys={"transport": "row"},
)
next(stream)
stream.close()
assert main._search_slot.acquire(blocking=False)
main._search_slot.release()
+192
View File
@@ -0,0 +1,192 @@
"""Tests for travelodge.py's pure functions.
Nothing here touches the network: only the fare rounding, guest parsing,
geometry and row ordering, which are the parts whose behaviour is a decision
rather than an upstream's answer.
"""
import math
import pytest
from app import travelodge as tl
# --------------------------------------------------------------------------- #
# round_5p
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize(
"pence, want",
[
(0, 0),
(100, 100),
(101, 100),
(102, 100),
(103, 105),
# Banker's rounding at the exact half-step: 21.5 and 22.5 both round to
# 22, i.e. 110p. Documented as an ignored sub-penny discrepancy.
(107.5, 110),
(112.5, 110),
# The real use: 1/3 off a rail fare must land on TfL's 5p grid.
(290 * 2 / 3, 195),
(490 * 2 / 3, 325),
],
)
def test_round_5p_snaps_to_the_5p_grid(pence, want):
assert tl.round_5p(pence) == want
def test_round_5p_returns_an_int():
# Fares are integer pence everywhere upstream of the final /100, so this
# must not leak a float back into the arithmetic.
assert isinstance(tl.round_5p(103.0), int)
@pytest.mark.parametrize("pence", [0, 5, 100, 103, 1234.7])
def test_round_5p_result_is_always_a_multiple_of_five(pence):
assert tl.round_5p(pence) % 5 == 0
# --------------------------------------------------------------------------- #
# parse_guests
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize(
"spec, want",
[
("1", [(1, 0)]),
("2", [(2, 0)]),
("2+1", [(2, 1)]),
("2,2+2", [(2, 0), (2, 2)]),
("1,1,1", [(1, 0)] * 3),
(" 2 + 1 ", [(2, 1)]), # int() tolerates the inner spaces
("2,,2", [(2, 0), (2, 0)]), # an empty room is skipped, not an error
("2+0", [(2, 0)]),
],
)
def test_parse_guests(spec, want):
assert tl.parse_guests(spec) == want
def test_parse_guests_preserves_room_order():
# Room order is the rooms[i][...] index in the Travelodge query, so it is
# part of the request rather than cosmetic.
assert tl.parse_guests("3+1,1,2+2") == [(3, 1), (1, 0), (2, 2)]
@pytest.mark.parametrize("spec", ["", " ", ",", ",,"])
def test_parse_guests_rejects_an_empty_spec(spec):
with pytest.raises(ValueError, match="empty"):
tl.parse_guests(spec)
@pytest.mark.parametrize("spec", ["0", "2,0", "0+2"])
def test_parse_guests_rejects_a_room_with_no_adult(spec):
with pytest.raises(ValueError, match="at least one adult"):
tl.parse_guests(spec)
def test_parse_guests_rejects_negative_children():
with pytest.raises(ValueError, match="children cannot be negative"):
tl.parse_guests("2+-1")
@pytest.mark.parametrize("spec", ["two", "2+x", "2.5"])
def test_parse_guests_rejects_non_numeric_parts(spec):
with pytest.raises(ValueError):
tl.parse_guests(spec)
# --------------------------------------------------------------------------- #
# haversine_km
# --------------------------------------------------------------------------- #
def test_haversine_km_is_zero_for_the_same_point():
assert tl.haversine_km((51.5031, -0.1132), (51.5031, -0.1132)) == 0.0
def test_haversine_km_is_symmetric():
a, b = (51.5031, -0.1132), (51.5308, -0.1238)
assert tl.haversine_km(a, b) == pytest.approx(tl.haversine_km(b, a))
def test_haversine_km_matches_a_known_london_distance():
# Waterloo to King's Cross is a little over 3km as the crow flies.
d = tl.haversine_km(tl.ORIGINS["waterloo"][1:], tl.ORIGINS["kings cross"][1:])
assert d == pytest.approx(3.14, abs=0.15)
def test_haversine_km_one_degree_of_latitude_is_about_111km():
# A degree of latitude is the same everywhere, so this pins the radius
# constant independently of any London coordinate.
assert tl.haversine_km((0.0, 0.0), (1.0, 0.0)) == pytest.approx(111.19, abs=0.05)
def test_haversine_km_a_degree_of_longitude_shrinks_with_latitude():
# cos(lat) scaling is the part a sign error in the formula would break.
equator = tl.haversine_km((0.0, 0.0), (0.0, 1.0))
london = tl.haversine_km((51.5, 0.0), (51.5, 1.0))
assert london == pytest.approx(equator * math.cos(math.radians(51.5)), rel=1e-3)
def test_haversine_km_handles_antipodes():
half_circumference = math.pi * 6371.0
assert tl.haversine_km((0.0, 0.0), (0.0, 180.0)) == pytest.approx(half_circumference, rel=1e-9)
def test_estimate_cycle_never_reports_zero_minutes():
# A hotel on top of the origin must still read at least 1 min.
minutes, km = tl.estimate_cycle((51.5031, -0.1132), (51.5031, -0.1132))
assert minutes == 1
assert km == 0.0
# --------------------------------------------------------------------------- #
# sort_rows
# --------------------------------------------------------------------------- #
def row(code, total, room_price):
return {"code": code, "total": total, "room_price": room_price}
def test_sort_rows_orders_by_total_and_sorts_in_place():
rows = [row("c", 90.0, 60.0), row("a", 50.0, 40.0), row("b", 70.0, 65.0)]
assert tl.sort_rows(rows) is None # mutates, returns nothing
assert [r["code"] for r in rows] == ["a", "b", "c"]
def test_sort_rows_puts_unpriced_rows_last():
# An unpriced row must not sort as if it were free, which is what the
# `total is None` leading key prevents.
rows = [row("unpriced", None, 10.0), row("priced", 99.0, 99.0)]
tl.sort_rows(rows)
assert [r["code"] for r in rows] == ["priced", "unpriced"]
def test_sort_rows_breaks_ties_on_room_price():
rows = [row("dear-room", 100.0, 95.0), row("cheap-room", 100.0, 80.0)]
tl.sort_rows(rows)
assert [r["code"] for r in rows] == ["cheap-room", "dear-room"]
def test_sort_rows_orders_unpriced_rows_among_themselves_by_room_price():
rows = [row("b", None, 70.0), row("a", None, 30.0)]
tl.sort_rows(rows)
assert [r["code"] for r in rows] == ["a", "b"]
def test_sort_rows_handles_a_zero_total():
# `or 0` collapses a genuine 0.0 total onto the None fallback value, so a
# free row must still sort ahead of an unpriced one.
rows = [row("unpriced", None, 5.0), row("free", 0.0, 0.0)]
tl.sort_rows(rows)
assert [r["code"] for r in rows] == ["free", "unpriced"]
def test_sort_rows_is_stable_for_fully_equal_rows():
rows = [row("first", 10.0, 10.0), row("second", 10.0, 10.0)]
tl.sort_rows(rows)
assert [r["code"] for r in rows] == ["first", "second"]
def test_sort_rows_on_an_empty_list():
rows = []
tl.sort_rows(rows)
assert rows == []