Skip to content

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

tools: race_calendar.py refuses a theme config.json it cannot use

xbsheng7b7394cf15b2
diff --git a/tests/test_race_calendar.py b/tests/test_race_calendar.py
index bd356ee84..42b3d0e38 100644
--- a/tests/test_race_calendar.py
+++ b/tests/test_race_calendar.py
@@ -40,8 +40,9 @@ class CalendarConfigTest(unittest.TestCase):
timezone=datetime.timezone)
with mock.patch.object(sys, "argv", ["race_calendar.py", str(self.theme), "--season", "2026"]), \
mock.patch.object(race_calendar, "datetime", clock), \
- contextlib.redirect_stdout(io.StringIO()):
- race_calendar.main()
+ contextlib.redirect_stdout(io.StringIO()), \
+ contextlib.redirect_stderr(io.StringIO()):
+ return race_calendar.main()
def test_utf8_theme_keeps_other_keys_when_calendar_is_updated(self):
original = {
@@ -68,13 +69,15 @@ class CalendarConfigTest(unittest.TestCase):
self.assertEqual(updated["race_calendar"][0]["name"], "Example Grand Prix")
def test_malformed_theme_is_unchanged_and_never_fetches(self):
+ # It used to be a traceback: a trailing comma in the theme's own config.json ended the run in
+ # JSONDecodeError, and Python's exit code for that is 1 - the code this script keeps for "this
+ # season has no race left to show". It is now the refusal every other bad input gets.
for encoding in ("utf-8", "utf-8-sig"):
with self.subTest(encoding=encoding):
data = '{"greeting_name":"客廳 Trịnh",'.encode(encoding)
self.config.write_bytes(data)
self.urlopen.reset_mock()
- with self.assertRaises(json.JSONDecodeError):
- self.run_main()
+ self.assertEqual(self.run_main(), 2)
self.urlopen.assert_not_called()
self.assertEqual(self.config.read_bytes(), data)
diff --git a/tests/test_race_calendar_refusals.py b/tests/test_race_calendar_refusals.py
index 46b4e3c18..53b5fa44e 100644
--- a/tests/test_race_calendar_refusals.py
+++ b/tests/test_race_calendar_refusals.py
@@ -133,6 +133,65 @@ class RefusalTest(unittest.TestCase):
self.assert_refused(status, stderr, "there is no theme folder at", str(picture))
self.urlopen.assert_not_called()
+ def test_a_config_json_that_is_not_json_is_named_and_never_fetches(self):
+ # The theme's own config.json is hand-written, and a typo in it was a JSONDecodeError traceback
+ # whose exit code, 1, is this script's "no race left this season" - so the reader was sent to
+ # --season next year over a missing brace. An empty file is the same shape.
+ self.stub() # a fetch would succeed, so only the read can stop the run
+ for data in ('{"columns": 5,}', '{"columns": 5', "", '{"greeting_name": "Olohuone" "columns": 5}'):
+ with self.subTest(data=data):
+ self.config.write_text(data, encoding="utf-8")
+ status, stderr = self.run_main(str(self.theme), "--season", "2026")
+ self.assert_refused(status, stderr, "not the JSON a theme's config.json has to be",
+ str(self.config))
+ self.urlopen.assert_not_called()
+ self.assertEqual(self.config.read_text(encoding="utf-8"), data)
+
+ def test_a_config_json_that_is_not_utf8_is_the_same_refusal(self):
+ self.stub()
+ data = b'{"greeting_name": "\xff\xfe"}'
+ self.config.write_bytes(data)
+ status, stderr = self.run_main(str(self.theme), "--season", "2026")
+ self.assert_refused(status, stderr, str(self.config), "utf-8")
+ self.urlopen.assert_not_called()
+ self.assertEqual(self.config.read_bytes(), data)
+
+ def test_a_config_json_that_is_not_an_object_is_named(self):
+ # Valid JSON, and `theme["race_calendar"] = races` met it with a TypeError after the fetch.
+ for data, kind in (("[1, 2, 3]", "array"), ('"a theme"', "string"), ("12", "number"), ("null", "null")):
+ with self.subTest(data=data):
+ self.stub() # a fetch would succeed, so only the read can stop the run
+ self.config.write_text(data, encoding="utf-8")
+ status, stderr = self.run_main(str(self.theme), "--season", "2026")
+ self.assert_refused(status, stderr, f"holds a JSON {kind}, not an object", str(self.config))
+ self.urlopen.assert_not_called()
+ self.assertEqual(self.config.read_text(encoding="utf-8"), data)
+
+ def test_a_config_json_that_is_a_folder_is_named(self):
+ self.stub()
+ self.config.mkdir()
+ status, stderr = self.run_main(str(self.theme), "--season", "2026")
+ self.assert_refused(status, stderr, f"{self.config} is not a file")
+ self.urlopen.assert_not_called()
+
+ def test_a_config_json_that_cannot_be_written_is_named_after_the_fetch(self):
+ # The other half of the same file: the fetch happens first, so this one is not "nothing was
+ # written" - it says the calendar is not in the theme, which is what the reader has to fix.
+ self.stub()
+ original = json.dumps({"columns": 5})
+ self.config.write_text(original, encoding="utf-8")
+ refusal = OSError(28, "No space left on device")
+ with mock.patch.object(Path, "write_text", side_effect=refusal):
+ status, stderr = self.run_main(str(self.theme), "--season", "2026")
+ self.assertEqual(status, 2, stderr)
+ self.assertNotIn("Traceback", stderr)
+ self.assertIn("could not write", stderr)
+ self.assertIn(str(self.config), stderr)
+ self.assertIn("No space left on device", stderr)
+ self.assertIn("is not in the theme", stderr)
+ self.urlopen.assert_called_once()
+ self.assertEqual(self.config.read_text(encoding="utf-8"), original)
+
def test_a_fetch_that_cannot_connect_says_which_url_and_why(self):
self.stub(raises=urllib.error.URLError(ConnectionRefusedError(111, "Connection refused")))
status, stderr = self.run_main(str(self.theme), "--season", "2026")
diff --git a/tools/race_calendar.py b/tools/race_calendar.py
index 2c90dbbec..bbf487d5c 100644
--- a/tools/race_calendar.py
+++ b/tools/race_calendar.py
@@ -12,8 +12,9 @@ season starts. Races that are already over are left out. The theme folder has to
created if it is not there yet).
Exit status: 0 the calendar is in the theme, 1 the season has no race left to show, 2 this run could not do
-its job - the folder is not there, --season is not a year, or the fetch failed - and says why on stderr.
-Nothing is written on 1 or 2: the theme stays as it was.
+its job - the folder is not there, its config.json is not the JSON object a theme has (or cannot be read or
+written), --season is not a year, or the fetch failed - and says why on stderr. Nothing is written on 1 or
+2: the theme stays as it was.
"""
import argparse
import datetime
@@ -104,7 +105,31 @@ def main():
f"folder of its own under themes/, so check the name you passed - this run will not "
f"create one for you.")
config = folder / "config.json"
- theme = json.loads(config.read_text(encoding="utf-8-sig")) if config.is_file() else {}
+ # The theme's own config.json is hand-written, and it was the one input this script still answered
+ # with a traceback: a trailing comma ended the run in `JSONDecodeError` with exit 1, which is the
+ # code this script keeps for a real answer ("this season has no race left to show", where it sends
+ # the reader to --season next year), so a typo in their own file read as a season with nothing left.
+ # Three shapes of that file are refused here, before the fetch: a path that is not a file (a stray
+ # copy of the folder), text that is not JSON as UTF-8, and JSON that is not an object - `[1, 2]`
+ # parsed fine and then met `theme["race_calendar"]` with a TypeError.
+ if config.exists() and not config.is_file():
+ return refuse(f"{config} is not a file. Nothing was written: a theme's config.json is one JSON "
+ f"object, so move whatever sits at that path aside and run it again.")
+ try:
+ theme = json.loads(config.read_text(encoding="utf-8-sig")) if config.is_file() else {}
+ except ValueError as e:
+ return refuse(f"{config} is not the JSON a theme's config.json has to be, as UTF-8 ({e}). Nothing "
+ f"was written: fix the file - a trailing comma or a missing brace is the usual cause "
+ f"- or move it aside, and run it again.")
+ except OSError as e:
+ return refuse(f"could not read {config} ({e.strerror or e}). Nothing was written: check the "
+ f"folder's permissions and run it again.")
+ if not isinstance(theme, dict):
+ kind = {list: "array", str: "string", bool: "true/false", int: "number", float: "number",
+ type(None): "null"}.get(type(theme), type(theme).__name__)
+ return refuse(f"{config} holds a JSON {kind}, not an object. Nothing was written: "
+ f"a theme's config.json is one JSON object of keys, so wrap it in {{}} or start the "
+ f"file again and run it.")
endpoint = API.format(season=args.season)
request = urllib.request.Request(endpoint, headers={"User-Agent": "cleanyourtv"})
# The one online step in this repository, on a laptop that may be offline, behind a proxy that
@@ -140,7 +165,17 @@ def main():
f"year\n")
return 1
theme["race_calendar"] = races
- config.write_text(json.dumps(theme, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ text = json.dumps(theme, indent=2, ensure_ascii=False) + "\n"
+ # The write is the other half of the same file, and a write that could not start (a read-only
+ # checkout, a folder of another user's, config.json a symlink into a folder that is not there) used
+ # to be an OSError traceback with exit 1, after the fetch - so a run that did nothing reported the
+ # code this script keeps for an answer.
+ 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 "
+ 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"next: round {first['round']} {first['name']}, race {first['sessions'][-1]['start']}")