"""A race's circuit is matched on Jolpica's circuitId, never on its name. Standard library only (no models, no numpy), so the merge check runs it as it is. """ import json import unittest from pathlib import Path from types import SimpleNamespace from ergast_service import ErgastService ROOT = Path(__file__).resolve().parent.parent CIRCUITS_JSON = ROOT / "circuits" / "circuits.json" def circuit_data_from_json() -> dict: """circuits.json in the shape ErgastService reads (country → localities → circuits).""" data = json.loads(CIRCUITS_JSON.read_text(encoding="utf-8")) return { country_slug: SimpleNamespace(localities={ locality_slug: SimpleNamespace(circuits={ circuit_slug: SimpleNamespace(name=circuit["name"], ergast_id=circuit.get("ergastId")) for circuit_slug, circuit in locality["circuits"].items() }) for locality_slug, locality in country["localities"].items() }) for country_slug, country in data.items() } def service_with_schedule(races: list[dict]) -> ErgastService: service = ErgastService(SimpleNamespace(circuit_data=circuit_data_from_json())) service._fetch_season_schedule = lambda season: races return service def race(name: str, circuit_id: str, circuit_name: str) -> dict: return {"raceName": name, "Circuit": {"circuitId": circuit_id, "circuitName": circuit_name}} class CircuitsJsonTest(unittest.TestCase): def test_every_circuit_has_one_unique_ergast_id(self): ids = {} for country_slug, country in json.loads(CIRCUITS_JSON.read_text(encoding="utf-8")).items(): for locality_slug, locality in country["localities"].items(): for circuit_slug, circuit in locality["circuits"].items(): where = f"{country_slug}/{locality_slug}/{circuit_slug}" ergast_id = circuit.get("ergastId") self.assertTrue(ergast_id, f"{where} has no ergastId") self.assertNotIn(ergast_id, ids, f"{where} and {ids.get(ergast_id)} share ergastId {ergast_id}") ids[ergast_id] = where class FindSlugsTest(unittest.TestCase): def test_a_renamed_circuit_resolves_by_its_id(self): # Jolpica names it Lusail; circuits.json keeps Losail, its slug and its URLs service = service_with_schedule([race("Qatar Grand Prix", "losail", "Lusail International Circuit")]) self.assertEqual(service.find_slugs_for_grand_prix("Qatar Grand Prix", 2025), ("qatar", "al-daayen", "losail-international-circuit")) def test_a_matching_name_with_an_unknown_id_resolves_to_nothing(self): # Caesars Palace (1981-82) shares the Las Vegas name; only its id tells it apart from the Strip service = service_with_schedule([race("Caesars Palace Grand Prix", "las_vegas", "Las Vegas Street Circuit")]) self.assertEqual(service.find_slugs_for_grand_prix("Caesars Palace Grand Prix", 1981), (None, None, None)) def test_an_unknown_race_resolves_to_nothing(self): service = service_with_schedule([]) self.assertEqual(service.find_slugs_for_grand_prix("Qatar Grand Prix", 2025), (None, None, None)) if __name__ == "__main__": unittest.main()