leaderboard-api / tests /test_app.py
erikjm's picture
Deploy the results API
885c230 verified
Raw History Blame Contribute Delete
15.1 kB
"""Tests of the results API: the runs index, a run's site board, the per-run `/me` payloads of both roles, the
health check from the index, the status codes for an unknown run and a missing token, and an unreadable archive."""
from __future__ import annotations
import json
from pathlib import Path
import httpx
from fastapi.testclient import TestClient
from huggingface_hub.errors import HfHubHTTPError
import app as leaderboard_api
from conftest import PENDING_RUN, RUN_BLOCKS, UNPULLED_RUN, settings
# the pending blocks the API serves for the fixture's index, which has no `intake_done` (an older harness's)
SERVED_PENDING = {**PENDING_RUN, "intake_done": False, "phase": "evaluating"}
SERVED_UNPULLED = {**UNPULLED_RUN, "intake_done": False, "phase": "upcoming"}
def read(archive: Path, path: str):
return json.loads((archive / path).read_text(encoding="utf-8"))
def bearer(token: str) -> dict:
return {"Authorization": f"Bearer {token}"}
def test_the_fixture_archive_holds_two_runs_with_a_site_board(archive: Path) -> None:
with_boards = sorted(path.parent.name for path in archive.glob("leaderboard/*/site.json"))
assert with_boards == ["week_01", "week_02"]
assert [entry["name"] for entry in read(archive, "leaderboard/runs.json")["runs"]] == ["week_00", "week_01",
"week_02"]
def test_runs_gives_the_index_verbatim(client: TestClient, archive: Path) -> None:
"""The index's fields are served as written, with the pending run added under `pending`."""
response = client.get("/runs")
assert response.status_code == 200
assert {key: value for key, value in response.json().items() if key != "pending"} == read(
archive, "leaderboard/runs.json")
assert response.json()["latest"] == "week_02" and "pending" in response.json()
def test_runs_without_an_index_is_no_board(empty_client: TestClient) -> None:
response = empty_client.get("/runs")
assert response.status_code == 503 and response.json() == {"error": "no_board"}
def test_a_malformed_index_is_no_board(archive: Path, userinfo_url: str) -> None:
index = read(archive, "leaderboard/runs.json")
for broken in ({"schema": 1, "latest": "week_02"}, {**index, "runs": [{"name": "Week 2", "date": "2026-10-09"}]},
{**index, "runs": [{"name": "week_02", "date": "9 Oct"}]}, {**index, "latest": "week_09"}):
(archive / "leaderboard" / "runs.json").write_text(json.dumps(broken), encoding="utf-8")
client = TestClient(leaderboard_api.create_app(settings(archive, userinfo_url)))
assert client.get("/runs").status_code == 503, broken
assert client.get("/healthz").json() == {"run": None, "date": None}, broken
assert client.get("/board/week_02").status_code == 404, broken
def test_board_gives_a_runs_site_board_verbatim(client: TestClient, archive: Path) -> None:
for run in ("week_01", "week_02"):
response = client.get(f"/board/{run}")
assert response.status_code == 200
assert response.json() == read(archive, f"leaderboard/{run}/site.json")
assert response.json()["run"] == RUN_BLOCKS[run]
def test_board_is_not_found_for_an_unknown_malformed_or_unindexed_run(client: TestClient) -> None:
"""An unknown run, a name that is not a run name, a run with an internal board but no site board that the index
does not list, and an indexed run without a site board each answer 404."""
for run in ("nope", "Week-01", "week_03", "week_04", "week_00"):
response = client.get(f"/board/{run}")
assert response.status_code == 404 and response.json() == {"error": "not_found"}, run
def test_me_gives_a_participant_their_team_files_for_the_run(client: TestClient, archive: Path) -> None:
latest = client.get("/me", headers=bearer("participant-token"))
assert latest.status_code == 200
payload = latest.json()
assert list(payload) == ["role", "run", "teams", "missing", "running"] and payload["role"] == "participant"
assert payload["running"] == [] # the fixture has no status file for week_02 (test_running.py covers the list)
assert payload["run"] == RUN_BLOCKS["week_02"]
assert payload["teams"] == [read(archive, "leaderboard/week_02/teams/team-a.json")]
assert payload["missing"] == ["team-z"]
earlier = client.get("/me", params={"run": "week_01"}, headers=bearer("participant-token"))
assert earlier.status_code == 200
assert earlier.json()["run"] == RUN_BLOCKS["week_01"]
assert earlier.json()["teams"] == [read(archive, "leaderboard/week_01/teams/team-a.json")]
assert earlier.json()["missing"] == ["team-z"]
def test_me_gives_an_organizer_every_file_of_the_run(client: TestClient, archive: Path) -> None:
for token in ("organizer-token", "member-token"):
latest = client.get("/me", headers=bearer(token))
assert latest.status_code == 200
payload = latest.json()
assert list(payload) == ["role", "run", "board", "teams", "pull", "progress", "failures", "running"]
assert payload["role"] == "organizer" and payload["run"] == RUN_BLOCKS["week_02"]
assert payload["board"] == read(archive, "leaderboard/week_02/2026-10-09.internal.json")
assert set(payload["teams"]) == {"team-a", "team-b"}
assert payload["teams"]["team-b"] == read(archive, "leaderboard/week_02/teams/team-b.json")
assert payload["pull"] == read(archive, "week_02/manifest.json")
assert payload["progress"] == "## submissions\n- [✓] team-a\n" and payload["failures"].startswith("# Failures")
earlier = client.get("/me", params={"run": "week_01"}, headers=bearer("organizer-token"))
assert earlier.status_code == 200
payload = earlier.json()
assert payload["run"] == RUN_BLOCKS["week_01"]
assert payload["board"] == read(archive, "leaderboard/week_01/2026-10-02.internal.json")
assert set(payload["teams"]) == {"team-a"}
assert (payload["pull"], payload["progress"], payload["failures"]) == (None, None, None)
def test_me_answers_404_for_an_unknown_run_and_401_before_it(client: TestClient) -> None:
"""An unknown run, a name that is not a run name, and a run that is neither in the index nor pending each
answer 404; a missing or rejected token answers 401 before the run is looked at."""
for run in ("nope", "Week-01", "week_04"):
response = client.get("/me", params={"run": run}, headers=bearer("participant-token"))
assert response.status_code == 404 and response.json() == {"error": "not_found"}, run
assert client.get("/me", params={"run": "nope"}).status_code == 401
assert client.get("/me", params={"run": "nope"}, headers=bearer("bad-token")).status_code == 401
assert client.get("/me", headers=bearer("bad-token")).json() == {"error": "invalid_token"}
def test_an_indexed_run_without_a_site_board_falls_back_to_the_index_entry(client: TestClient) -> None:
response = client.get("/me", params={"run": "week_00"}, headers=bearer("participant-token"))
assert response.status_code == 200
assert response.json()["run"]["name"] == "week_00" and response.json()["teams"] == []
def test_healthz_names_the_latest_run_of_the_index(client: TestClient, empty_client: TestClient) -> None:
assert client.get("/healthz").json() == {"run": "week_02", "date": "2026-10-09"}
assert empty_client.get("/healthz").json() == {"run": None, "date": None}
assert empty_client.get("/me", headers=bearer("participant-token")).status_code == 503
assert empty_client.get("/me", headers=bearer("participant-token")).json() == {"error": "no_board"}
def test_an_unreadable_archive_is_503_everywhere(archive: Path, userinfo_url: str, monkeypatch) -> None:
def unreadable() -> HfHubHTTPError:
response = httpx.Response(503, request=httpx.Request("GET", "https://huggingface.co/api/datasets/x"))
return HfHubHTTPError("the archive cannot be read", response=response)
class Failing:
def __init__(self, root) -> None:
pass
def read(self, path: str) -> bytes | None:
raise unreadable()
def listing(self, directory: str) -> list[str]:
raise unreadable()
monkeypatch.setattr(leaderboard_api, "DirectoryArchive", Failing)
client = TestClient(leaderboard_api.create_app(settings(archive, userinfo_url)))
assert client.get("/healthz").json() == {"run": None, "date": None}
for request in (client.get("/runs"), client.get("/board/week_01"),
client.get("/me", headers=bearer("participant-token"))):
assert request.status_code == 503 and request.json() == {"error": "archive_unavailable"}
assert client.get("/me").status_code == 401
# ---- the pending run ----------------------------------------------------------------------------------------
def test_runs_names_the_pending_run(client: TestClient, archive: Path, userinfo_url: str) -> None:
"""`/runs` carries the pending run's block, with `intake_done` and the computed `phase`; it is null with the index cleared, with a pending index naming a
run the index lists, and with a malformed pending index."""
response = client.get("/runs")
assert response.status_code == 200
assert response.json()["pending"] == SERVED_PENDING
assert {key: value for key, value in response.json().items() if key != "pending"} == read(archive, "leaderboard/runs.json")
pending = archive / "leaderboard" / "pending.json"
for cleared in ({"schema": 1, "run": None}, {"schema": 1, "run": {**PENDING_RUN, "name": "week_02"}},
{"schema": 1, "run": {**PENDING_RUN, "name": "Week 3"}}, {"schema": 1, "run": {**PENDING_RUN, "models": "m/one"}},
{"schema": 1, "run": {**PENDING_RUN, "pulled": "yes"}}, {"schema": 1}):
pending.write_text(json.dumps(cleared), encoding="utf-8")
assert client.get("/runs").json()["pending"] is None, cleared
assert client.get("/me", params={"run": "week_03"}, headers=bearer("participant-token")).status_code == 404
pending.unlink()
assert client.get("/runs").json()["pending"] is None
def test_me_gives_a_participant_their_pending_files_with_the_evaluation_per_model(client: TestClient,
archive: Path) -> None:
response = client.get("/me", params={"run": "week_03"}, headers=bearer("participant-token"))
assert response.status_code == 200
payload = response.json()
assert list(payload) == ["role", "pending", "pulled", "run", "teams", "missing"]
assert (payload["role"], payload["pending"], payload["pulled"], payload["run"]) == ("participant", True, True,
SERVED_PENDING)
assert payload["missing"] == ["team-z"] and len(payload["teams"]) == 1
team = payload["teams"][0]
assert team["evaluation"] == {"m/one": "completed", "m/two": "in_progress", "m/three": "not_started"}
assert {key: value for key, value in team.items() if key != "evaluation"} == read(
archive, "leaderboard/week_03/pending/team-a.json")
text = response.text
for forbidden in ("team-b", "Team B Secret", "error", "worker", "heartbeat", "traceback", "after", "updated_at"):
assert forbidden not in text, forbidden
other = client.get("/me", params={"run": "week_03"}, headers=bearer("other-token"))
assert other.status_code == 200 and other.json()["teams"] == [] and other.json()["missing"] == ["team-q"]
(archive / "week_03" / "status.json").unlink()
without = client.get("/me", params={"run": "week_03"}, headers=bearer("participant-token")).json()
assert without["teams"][0]["evaluation"] == {model: "not_started" for model in PENDING_RUN["models"]}
def test_me_gives_an_organizer_every_pending_file(client: TestClient, archive: Path) -> None:
response = client.get("/me", params={"run": "week_03"}, headers=bearer("organizer-token"))
assert response.status_code == 200
payload = response.json()
assert list(payload) == ["role", "pending", "pulled", "run", "board", "teams", "pull", "progress", "failures"]
assert (payload["role"], payload["pending"], payload["pulled"], payload["run"], payload["board"]) == (
"organizer", True, True, SERVED_PENDING, None)
assert set(payload["teams"]) == {"team-a", "team-b"}
assert payload["teams"]["team-a"]["evaluation"] == {"m/one": "completed", "m/two": "in_progress",
"m/three": "not_started"}
assert payload["teams"]["team-b"]["evaluation"] == {"m/one": "error", "m/two": "not_started",
"m/three": "not_started"}
assert payload["teams"]["team-b"]["team"] == "Team B Secret"
assert payload["pull"] == read(archive, "week_03/manifest.json")
assert payload["progress"].startswith("## submissions") and payload["failures"].startswith("# Failures")
assert "traceback" not in response.text
def test_the_pending_run_has_no_board_and_is_not_the_default(client: TestClient) -> None:
assert client.get("/board/week_03").status_code == 404
latest = client.get("/me", headers=bearer("participant-token")).json()
assert latest["run"]["name"] == "week_02" and "pending" not in latest
assert client.get("/healthz").json() == {"run": "week_02", "date": "2026-10-09"}
assert client.get("/me", params={"run": "week_03"}).status_code == 401
assert client.get("/me", params={"run": "week_03"}, headers=bearer("bad-token")).status_code == 401
def test_a_pending_run_that_is_not_pulled_has_empty_views(client: TestClient, archive: Path) -> None:
"""Before the pull, `/runs` names the run with `pulled` false, a participant gets no teams and no missing
organizations, and an organizer gets no teams and null files, even where stale pending files exist."""
(archive / "leaderboard" / "pending.json").write_text(json.dumps({"schema": 1, "run": UNPULLED_RUN}),
encoding="utf-8")
assert client.get("/runs").json()["pending"] == SERVED_UNPULLED
participant = client.get("/me", params={"run": "week_03"}, headers=bearer("participant-token"))
assert participant.status_code == 200
assert participant.json() == {"role": "participant", "pending": True, "pulled": False, "run": SERVED_UNPULLED,
"teams": [], "missing": []}
organizer = client.get("/me", params={"run": "week_03"}, headers=bearer("organizer-token"))
assert organizer.status_code == 200
assert organizer.json() == {"role": "organizer", "pending": True, "pulled": False, "run": SERVED_UNPULLED,
"board": None, "teams": {}, "pull": None, "progress": None, "failures": None}
assert "team-a" not in participant.text and "team-a" not in organizer.text
assert client.get("/board/week_03").status_code == 404