Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

tools: validate race calendar API data before writing

Sandiv Dathunarachchide8a18b34fb5
diff --git a/tests/test_race_calendar_refusals.py b/tests/test_race_calendar_refusals.py
index 349e601d3..4c5e00f0e 100644
--- a/tests/test_race_calendar_refusals.py
+++ b/tests/test_race_calendar_refusals.py
@@ -35,6 +35,12 @@ RACES = {"MRData": {"RaceTable": {"season": "2026", "Races": [{
"round": "1", "raceName": "Example Grand Prix", "date": "2026-01-04", "time": "14:00:00Z",
}]}}}
RESPONSE = json.dumps(RACES).encode("utf-8")
+THEME = {
+ "greeting_name": "客廳",
+ "custom": {"label": "夜晚", "values": [True, None, {"amount": 7}]},
+ "race_calendar": [{"name": "old calendar"}],
+}
+THEME_BYTES = (json.dumps(THEME, ensure_ascii=False, indent=2) + "\n").replace("\n", "\r\n").encode("utf-8-sig")
class FixedDatetime(datetime.datetime):
@@ -110,6 +116,136 @@ class RefusalTest(unittest.TestCase):
self.assertIn(needle, stderr)
self.assertTrue(any("Nothing was written" in line for line in stderr.splitlines()), stderr)
+ def assert_api_leaves_config(self, payload, expected_status, *needles):
+ for existing in (False, True):
+ with self.subTest(existing=existing):
+ self.config.unlink(missing_ok=True)
+ if existing:
+ self.config.write_bytes(THEME_BYTES)
+ for stream in (self.err, self.out):
+ stream.seek(0)
+ stream.truncate(0)
+ self.stub(body=json.dumps(payload).encode("utf-8"))
+ try:
+ status, stderr = self.run_main(str(self.theme))
+ if expected_status == 2:
+ self.assert_refused(status, stderr, "Jolpica", *needles)
+ else:
+ self.assertEqual(status, expected_status, stderr)
+ for needle in needles:
+ self.assertIn(needle, stderr)
+ self.assertEqual(self.out.getvalue(), "")
+ self.urlopen.assert_called_once()
+ finally:
+ # Check even when the old code raises: a missing season used to fail AFTER writing.
+ if existing:
+ self.assertEqual(self.config.read_bytes(), THEME_BYTES)
+ else:
+ self.assertFalse(self.config.exists(), "the refused response created config.json")
+
+ def test_api_missing_season_never_writes(self):
+ for upcoming in (True, False):
+ with self.subTest(upcoming=upcoming):
+ payload = json.loads(RESPONSE)
+ table = payload["MRData"]["RaceTable"]
+ del table["season"]
+ if not upcoming:
+ table["Races"] = []
+ self.assert_api_leaves_config(payload, 2, "season")
+
+ def test_api_invalid_season_never_writes(self):
+ for value in (None, [], "2026x"):
+ with self.subTest(season=value):
+ payload = json.loads(RESPONSE)
+ payload["MRData"]["RaceTable"]["season"] = value
+ self.assert_api_leaves_config(payload, 2, "season")
+
+ def test_api_invalid_containers_never_write(self):
+ for field in ("RaceTable", "Races"):
+ for value in (None, [], {}) if field == "RaceTable" else (None, {}, "races"):
+ with self.subTest(field=field, value=value):
+ payload = json.loads(RESPONSE)
+ if field == "RaceTable":
+ payload["MRData"][field] = value
+ else:
+ payload["MRData"]["RaceTable"][field] = value
+ self.assert_api_leaves_config(payload, 2, field)
+
+ def test_api_invalid_circuit_or_location_never_writes(self):
+ for circuit, field in ((None, "Circuit"), ([], "Circuit"), ({"Location": None}, "Location")):
+ with self.subTest(circuit=circuit):
+ payload = json.loads(RESPONSE)
+ payload["MRData"]["RaceTable"]["Races"][0]["Circuit"] = circuit
+ self.assert_api_leaves_config(payload, 2, field)
+
+ def test_api_nonobject_race_after_valid_race_never_partially_writes(self):
+ for value in (None, [], "race", 42):
+ with self.subTest(race=value):
+ payload = json.loads(RESPONSE)
+ payload["MRData"]["RaceTable"]["Races"].append(value)
+ self.assert_api_leaves_config(payload, 2, "Races")
+
+ def test_api_missing_name_or_nonnumeric_round_never_writes(self):
+ for field in ("raceName", "round"):
+ with self.subTest(field=field):
+ payload = json.loads(RESPONSE)
+ race = payload["MRData"]["RaceTable"]["Races"][0]
+ if field == "raceName":
+ del race[field]
+ else:
+ race[field] = "one"
+ self.assert_api_leaves_config(payload, 2, field)
+ if field == "round":
+ self.assertNotIn("timestamp", self.err.getvalue())
+
+ def test_api_valid_years_optional_fields_and_unpublished_sessions(self):
+ for year in ("2026", 2026):
+ for optional in ("present", "no Location", "no Circuit"):
+ with self.subTest(year=year, optional=optional):
+ payload = json.loads(RESPONSE)
+ table = payload["MRData"]["RaceTable"]
+ table["season"] = year
+ race = table["Races"][0]
+ race["FirstPractice"] = {"date": "2026-01-02"}
+ race["Qualifying"] = {"date": "2026-01-03", "time": None}
+ if optional == "present":
+ race["Circuit"] = {"Location": {"locality": "Example"}}
+ elif optional == "no Location":
+ race["Circuit"] = {}
+ self.config.write_bytes(THEME_BYTES)
+ for stream in (self.err, self.out):
+ stream.seek(0)
+ stream.truncate(0)
+ self.stub(body=json.dumps(payload).encode("utf-8"))
+ status, stderr = self.run_main(str(self.theme))
+ self.assertEqual(status, 0, stderr)
+ self.assertEqual(stderr, "")
+ self.assertIn("1 races from the 2026 season", self.out.getvalue())
+ self.urlopen.assert_called_once()
+ updated = json.loads(self.config.read_bytes().decode("utf-8"))
+ self.assertEqual({k: v for k, v in updated.items() if k != "race_calendar"},
+ {k: v for k, v in THEME.items() if k != "race_calendar"})
+ self.assertEqual(updated["race_calendar"], [{
+ "round": 1, "name": "Example Grand Prix",
+ "place": "Example" if optional == "present" else "",
+ "sessions": [{"name": "RACE", "start": "2026-01-04T14:00:00Z"}],
+ }])
+
+ def test_api_empty_past_or_unpublished_calendar_leaves_config_unchanged(self):
+ for kind in ("empty", "past", "missing time", "unpublished time"):
+ with self.subTest(kind=kind):
+ payload = json.loads(RESPONSE)
+ races = payload["MRData"]["RaceTable"]["Races"]
+ if kind == "empty":
+ races.clear()
+ elif kind == "past":
+ races[0]["date"] = "2025-01-04"
+ elif kind == "missing time":
+ del races[0]["time"]
+ else:
+ races[0]["time"] = None
+ self.assert_api_leaves_config(payload, 1, "no upcoming races in the 2026 calendar")
+
def test_a_season_that_is_not_a_year_never_reaches_the_api(self):
self.stub()
status, stderr = self.run_main(str(self.theme), "--season", "2027x")
diff --git a/tools/race_calendar.py b/tools/race_calendar.py
index 44f578da3..3798b7eea 100644
--- a/tools/race_calendar.py
+++ b/tools/race_calendar.py
@@ -43,14 +43,20 @@ SESSIONS = (
def instant(block):
""""2026-10-23" + "17:30:00Z" as one UTC timestamp; None when the time is not published yet."""
+ if not isinstance(block, dict):
+ raise TypeError("a session is not an object")
if not block.get("date") or not block.get("time"):
return None
+ if not isinstance(block["date"], str) or not isinstance(block["time"], str):
+ raise ValueError("session date and time must be strings")
return f"{block['date']}T{block['time']}" if block["time"].endswith("Z") else f"{block['date']}T{block['time']}Z"
def calendar(races, now):
out = []
for race in races:
+ if not isinstance(race, dict):
+ raise TypeError("Races contains a race that is not an object")
sessions = []
for key, name in SESSIONS:
if key in race and (start := instant(race[key])):
@@ -62,10 +68,26 @@ def calendar(races, now):
# The launcher keeps a weekend on screen for four hours after the start; a day covers that.
if datetime.datetime.fromisoformat(start.replace("Z", "+00:00")) < now - datetime.timedelta(days=1):
continue
+ try:
+ number = int(race["round"])
+ except (TypeError, ValueError, OverflowError):
+ raise TypeError("race round is not a number") from None
+ name = race["raceName"]
+ if not isinstance(name, str):
+ raise TypeError("raceName is not a string")
+ circuit = race.get("Circuit", {})
+ if not isinstance(circuit, dict):
+ raise TypeError("Circuit is not an object")
+ location = circuit.get("Location", {})
+ if not isinstance(location, dict):
+ raise TypeError("Circuit.Location is not an object")
+ place = location.get("locality", "")
+ if not isinstance(place, str):
+ raise TypeError("Circuit.Location.locality is not a string")
out.append({
- "round": int(race["round"]),
- "name": race["raceName"],
- "place": race.get("Circuit", {}).get("Location", {}).get("locality", ""),
+ "round": number,
+ "name": name,
+ "place": place,
"sessions": sessions,
})
return out
@@ -163,16 +185,32 @@ def main():
now = datetime.datetime.now(datetime.timezone.utc)
try:
table = payload["MRData"]["RaceTable"]
- races = calendar(table["Races"], now)
+ if not isinstance(table, dict):
+ raise TypeError("RaceTable is not an object")
except (KeyError, TypeError):
- return refuse(f"the answer for the {args.season} season has no MRData.RaceTable in it. Nothing "
+ return refuse(f"Jolpica's answer for the {args.season} season has no MRData.RaceTable in it. Nothing "
f"was written: run it again, or pass --season with a year.")
+ # Resolve the response's year before writing: even the success message needs it.
+ response_season = table.get("season")
+ if type(response_season) is int:
+ response_season = str(response_season)
+ if (not isinstance(response_season, str) or len(response_season) != 4
+ or not response_season.isdecimal() or int(response_season) < FIRST_SEASON):
+ return refuse("Jolpica's RaceTable.season is missing or is not a championship year. Nothing "
+ "was written: run it again, or pass --season with a year.")
+ try:
+ if not isinstance(table.get("Races"), list):
+ raise TypeError("RaceTable.Races is not an array")
+ races = calendar(table["Races"], now)
+ except (KeyError, TypeError) as e:
+ return refuse(f"Jolpica's {response_season} calendar has invalid race data ({e}). Nothing was "
+ f"written: run it again when the API serves a complete calendar.")
except ValueError as e:
- return refuse(f"a session time in the {args.season} calendar is not a timestamp this script "
+ return refuse(f"a session time in the {response_season} calendar is not a timestamp this script "
f"understands ({e}). Nothing was written: the API has changed how it writes a "
f"session's time.")
if not races:
- sys.stderr.write(f"no upcoming races in the {table['season']} calendar; try --season with next "
+ sys.stderr.write(f"no upcoming races in the {response_season} calendar; try --season with next "
f"year\n")
return 1
theme["race_calendar"] = races
@@ -184,11 +222,11 @@ def main():
try:
config.write_text(text, encoding="utf-8")
except OSError as e:
- return refuse(f"could not write {config} ({e.strerror or e}). The {table['season']} calendar was "
+ return refuse(f"could not write {config} ({e.strerror or e}). The {response_season} calendar was "
f"fetched but is not in the theme: check the folder's permissions, or move what is "
f"at that path aside, and run it again.")
first = races[0]
- print(f"{len(races)} races from the {table['season']} season -> {config}")
+ print(f"{len(races)} races from the {response_season} season -> {config}")
print(f"next: round {first['round']} {first['name']}, race {first['sessions'][-1]['start']}")
return 0