rcom/tools/test_import_themes.py

181 lines
8.3 KiB
Python

#!/usr/bin/env python3
"""Offline unit tests for the development-only theme importer."""
import json
import shutil
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
import import_themes
class ImporterTests(unittest.TestCase):
def test_parser_whitelists_colors_and_ignores_non_color_directives(self):
with tempfile.TemporaryDirectory() as root:
path = Path(root) / "fixture.conf"
path.write_text(
"# comment\n"
"foreground #c0ffee\n"
"background #010203\n"
"selection_foreground background\n"
"selection_background none\n"
"tab_bar_background system\n"
"active_border_color #aabbcc\n"
"include $(touch /tmp/must-not-exist)\n"
+ "".join(f"color{index} #102030\n" for index in range(16))
)
colors = import_themes.parse_conf(path)
self.assertEqual(colors["foreground"], (0xC0, 0xFF, 0xEE))
self.assertEqual(colors["active_border_color"], (0xAA, 0xBB, 0xCC))
self.assertNotIn("selection_foreground", colors)
self.assertNotIn("selection_background", colors)
self.assertNotIn("tab_bar_background", colors)
self.assertNotIn("include", colors)
def test_parser_fails_closed_on_missing_malformed_or_unsupported_colors(self):
with tempfile.TemporaryDirectory() as root:
path = Path(root) / "broken.conf"
path.write_text("foreground red\n")
with self.assertRaisesRegex(ValueError, "unsupported foreground"):
import_themes.parse_conf(path)
path.write_text("foreground #000000 extra\n")
with self.assertRaisesRegex(ValueError, "unsupported color syntax"):
import_themes.parse_conf(path)
path.write_text("background #000000\n")
with self.assertRaisesRegex(ValueError, "missing required foreground"):
import_themes.parse_conf(path)
def test_generated_theme_is_repeatable_and_keeps_source_values(self):
colors = {
"foreground": (216, 224, 240),
"background": (11, 16, 32),
"active_border_color": (101, 214, 232),
**{f"color{index}": (index, index + 1, index + 2) for index in range(16)},
}
manifest = {"id": "fixture", "display_name": "Fixture", "mode": "dark"}
first = import_themes.emit_theme(manifest, colors)
second = import_themes.emit_theme(manifest, colors)
self.assertEqual(first, second)
self.assertIn("ThemeOrigin::Kitty", first)
self.assertIn('id: "fixture"', first)
self.assertIn("selection_background: None", first)
self.assertIn("active: Some(Color::Rgb(0x65, 0xd6, 0xe8))", first)
def test_allowlist_has_exactly_nineteen_unique_ids_and_sources(self):
self.assertEqual(len(import_themes.THEMES), 19)
self.assertEqual(len({entry[0] for entry in import_themes.THEMES}), 19)
self.assertEqual(len({entry[1] for entry in import_themes.THEMES}), 19)
self.assertEqual(
sum(entry[3] == "dark" for entry in import_themes.THEMES),
10,
)
self.assertEqual(
sum(entry[3] == "light" for entry in import_themes.THEMES),
9,
)
def test_full_offline_import_is_repeatable_and_matches_committed_output(self):
fixture_root = Path(__file__).parent / "fixtures"
repository = fixture_root.parent.parent
with tempfile.TemporaryDirectory() as first, tempfile.TemporaryDirectory() as second:
for output in [first, second]:
argv = sys.argv
try:
sys.argv = [
"import_themes.py",
str(fixture_root / "kitty-themes"),
str(fixture_root / "theme-license-cache"),
"--output",
output,
]
with mock.patch.object(import_themes, "verify_source_commit"):
import_themes.main()
finally:
sys.argv = argv
for relative in ["src/ui/themes_data.rs", "themes/manifest.json"]:
self.assertEqual(
(Path(first) / relative).read_bytes(),
(Path(second) / relative).read_bytes(),
)
self.assertEqual(
(Path(first) / relative).read_bytes(),
(repository / relative).read_bytes(),
)
notices = sorted((Path(first) / "LICENSES/themes").iterdir())
self.assertEqual(len(notices), 10)
for notice in notices:
self.assertEqual(
notice.read_bytes(),
(repository / "LICENSES/themes" / notice.name).read_bytes(),
)
def test_author_repo_commit_spdx_and_notice_tampering_are_rejected(self):
fixture_root = Path(__file__).parent / "fixtures"
source = fixture_root / "kitty-themes"
for field in ["author", "repo", "commit", "spdx", "notice"]:
with self.subTest(field=field), tempfile.TemporaryDirectory() as root:
cache = Path(root) / "licenses"
shutil.copytree(fixture_root / "theme-license-cache", cache)
metadata = json.loads(source.joinpath("themes.json").read_text())
if field == "author":
metadata[0]["author"] = "wrong"
else:
path = cache / "dracula__kitty.json"
record = json.loads(path.read_text())
if field in {"repo", "commit"}:
record[field] = "wrong"
elif field == "spdx":
record["license"]["spdx_id"] = None
else:
cache.joinpath("dracula__kitty.txt").write_text("wrong")
path.write_text(json.dumps(record))
source_data = {"root": source, "metadata": metadata}
with self.assertRaisesRegex(ValueError, "mismatch"):
import_themes.import_theme(import_themes.THEMES[0], source_data, cache)
# Tokyo must not downgrade its required Apache-2.0 marker to an absent SPDX.
with tempfile.TemporaryDirectory() as root:
cache = Path(root) / "licenses"
shutil.copytree(fixture_root / "theme-license-cache", cache)
path = cache / "folke__tokyonight.nvim.json"
record = json.loads(path.read_text())
record["license"]["spdx_id"] = None
path.write_text(json.dumps(record))
source_data = {
"root": source,
"metadata": json.loads(source.joinpath("themes.json").read_text()),
}
with self.assertRaisesRegex(ValueError, "license mismatch"):
import_themes.import_theme(import_themes.THEMES[7], source_data, cache)
def test_tampered_source_and_wrong_head_are_rejected_before_output(self):
fixture_root = Path(__file__).parent / "fixtures"
with tempfile.TemporaryDirectory() as root:
root = Path(root)
source = root / "source"
shutil.copytree(fixture_root / "kitty-themes", source)
with source.joinpath("themes/Dracula.conf").open("a") as tampered:
tampered.write("\n# tampered\n")
output = root / "output"
source_data = {
"root": source,
"metadata": json.loads(source.joinpath("themes.json").read_text()),
}
with self.assertRaisesRegex(ValueError, "source hash mismatch"):
import_themes.import_theme(
import_themes.THEMES[0],
source_data,
fixture_root / "theme-license-cache",
)
self.assertFalse(output.exists())
completed = subprocess.CompletedProcess(args=[], returncode=0, stdout="wrong-head\n")
with mock.patch.object(import_themes.subprocess, "run", return_value=completed):
with self.assertRaisesRegex(ValueError, "HEAD must be pinned"):
import_themes.verify_source_commit(fixture_root / "kitty-themes")
if __name__ == "__main__":
unittest.main()