"""Offline integrity tests for the canonical package-to-web-assets export.""" from __future__ import annotations import importlib.util import json from pathlib import Path import subprocess import sys import tempfile import unittest import warnings import zipfile import hashlib _SPEC = importlib.util.spec_from_file_location( "export_web_assets", Path(__file__).with_name("export-web-assets.py") ) exporter = importlib.util.module_from_spec(_SPEC) _SPEC.loader.exec_module(exporter) # Independent fixture contract: do not populate it from the implementation's constants. TOKENS = { "--paper": "#f4f4f1", "--card": "#ffffff", "--ink": "#1b1d21", "--ink-soft": "#5a6066", "--ink-faint": "#626970", "--rule": "#e4e4df", "--accent": "#2f5fd0", "--accent-deep": "#1e3f99", "--on-accent": "#ffffff", "--accent-tint": "#eef2fc", "--accent-border": "#cdd9f7", "--accent-focus": "#2f5fd0", "--ok-ink": "#236f34", "--warn-ink": "#855000", "--bad-ink": "#b42121", "--idle-ink": "#535d66", "--ok-bg": "#e9f6ec", "--warn-bg": "#fdf1dd", "--bad-bg": "#fceaea", "--idle-bg": "#eef0f2", "--info-ink": "#1e3f99", "--info-bg": "#e7ecfb", "--info-border": "#cdd9f7", "--active-bg": "var(--accent-tint)", "--bs-primary": "var(--accent)", "--sans": "'IBM Plex Sans', system-ui, sans-serif", "--mono": "'IBM Plex Mono', monospace", "--future-token": "var(--paper)", } ASSETS = { "css/theme.css": b"", "css/layout.css": b"/* layout bytes preserved */\r\n.page { min-width: 0; }\r\n", "fonts/ibm-plex-sans-400.woff2": b"wOF2\x00regular\xff", "fonts/ibm-plex-sans-600.woff2": b"wOF2\x00semibold\xfe", "fonts/ibm-plex-mono-500.woff2": b"wOF2\x00mono\xfd", } REVISION = "a" * 40 def css_for(tokens=None): tokens = TOKENS if tokens is None else tokens declarations = "\n".join(f" {key}: {value};" for key, value in tokens.items()) return ("/* discarded from token parsing, retained in output */\n" "@font-face { font-family: 'Fixture'; src: url('../fonts/fixture.woff2'); }\n" ":root {\n" + declarations + "\n}\nbody { color: var(--ink); }\n").encode() class ExportWebAssetsTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.addCleanup(self.tmp.cleanup) self.root = Path(self.tmp.name) self.package = self.root / "input.nupkg" self.output = self.root / "export.zip" def make_package(self, *, package_id="ZB.MOM.WW.Theme", version="1.0.0", css=None, missing=None, extras=(), nuspec_override=None): payloads = dict(ASSETS) payloads["css/theme.css"] = css_for() if css is None else css nuspec = (f'' f'{package_id}{version}') with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) with zipfile.ZipFile(self.package, "w") as archive: archive.writestr("ZB.MOM.WW.Theme.nuspec", nuspec if nuspec_override is None else nuspec_override) for name, data in payloads.items(): if name != missing: archive.writestr("staticwebassets/" + name, data) archive.writestr("lib/net10.0/fixture.dll", b"not exported") for name, data in extras: archive.writestr(name, data) return payloads def export(self, output=None): return exporter.export_package(self.package, output or self.output, source_revision=REVISION, source_tag="untagged") def test_exact_asset_bytes_and_complete_token_references_are_preserved(self): expected = self.make_package() self.export() with zipfile.ZipFile(self.output) as archive: self.assertEqual(set(expected) | {"tokens.json", "manifest.json"}, set(archive.namelist())) for name, data in expected.items(): self.assertEqual(data, archive.read(name), name) tokens = json.loads(archive.read("tokens.json")) self.assertEqual({"schemaVersion": 1, "themeVersion": "1.0.0", "tokens": TOKENS}, tokens) def test_manifest_identifies_exact_package_and_hashes_every_payload_once(self): self.make_package(version="1.2.3-preview.4") self.export(self.root / "not-a-version-name.zip") with zipfile.ZipFile(self.root / "not-a-version-name.zip") as archive: manifest = json.loads(archive.read("manifest.json")) self.assertEqual(1, manifest["schemaVersion"]) self.assertEqual("1.2.3-preview.4", manifest["themeVersion"]) self.assertEqual("ZB.MOM.WW.Theme", manifest["sourcePackage"]) self.assertEqual(hashlib.sha256(self.package.read_bytes()).hexdigest(), manifest["sourcePackageSha256"]) self.assertEqual(REVISION, manifest["sourceRevision"]) self.assertEqual("untagged", manifest["sourceTag"]) self.assertEqual(set(archive.namelist()) - {"manifest.json"}, set(manifest["files"])) for name, digest in manifest["files"].items(): self.assertEqual(hashlib.sha256(archive.read(name)).hexdigest(), digest) def test_identical_inputs_produce_identical_zip_bytes_with_stable_entries(self): self.make_package() self.export() second = self.root / "second.zip" self.export(second) self.assertEqual(self.output.read_bytes(), second.read_bytes()) with zipfile.ZipFile(second) as archive: self.assertEqual(sorted(archive.namelist()), archive.namelist()) self.assertTrue(all(i.date_time == (1980, 1, 1, 0, 0, 0) for i in archive.infolist())) def test_changed_css_byte_changes_asset_and_package_hash(self): self.make_package() self.export() with zipfile.ZipFile(self.output) as archive: first = json.loads(archive.read("manifest.json")) self.make_package(css=css_for() + b"\n") self.export() with zipfile.ZipFile(self.output) as archive: second = json.loads(archive.read("manifest.json")) self.assertNotEqual(first["files"]["css/theme.css"], second["files"]["css/theme.css"]) self.assertNotEqual(first["sourcePackageSha256"], second["sourcePackageSha256"]) def test_each_required_asset_is_required_without_partial_output(self): for name in ASSETS: with self.subTest(asset=name): self.make_package(missing=name) with self.assertRaises(ValueError): self.export() self.assertFalse(self.output.exists()) def test_required_semantic_token_cannot_be_missing_or_empty(self): for name in ("--paper", "--ok-ink", "--warn-ink", "--bad-ink", "--idle-ink", "--info-ink", "--on-accent"): for empty in (False, True): with self.subTest(token=name, empty=empty): tokens = dict(TOKENS) if empty: tokens[name] = "" else: del tokens[name] self.make_package(css=css_for(tokens)) with self.assertRaises(ValueError): self.export() self.assertFalse(self.output.exists()) def test_comments_quotes_and_function_values_do_not_create_phantom_tokens(self): tokens = dict(TOKENS, **{"--text": "'literal ; :root { /* text */ }'", "--complex": "var(--paper, rgb(1, 2, 3))"}) css = css_for(tokens).replace(b":root {\n", b":root { /* --phantom: #000; */\n") self.make_package(css=css) self.export() with zipfile.ZipFile(self.output) as archive: self.assertEqual(tokens, json.loads(archive.read("tokens.json"))["tokens"]) def test_malformed_or_ambiguous_canonical_css_is_refused(self): good = css_for() bad_cases = [good + b"/* unclosed", good + b"}", good.replace(b":root {", b":root"), good.replace(b"--paper: #f4f4f1;", b"--paper #f4f4f1;"), good.replace(b"--paper: #f4f4f1;", b"--paper: var(--card;"), good.replace(b"--paper: #f4f4f1;", b"--paper: 'unclosed;"), good + b":root { --paper: #fff; }", good.replace(b"--paper: #f4f4f1;", b"--paper: #fff; --paper: #000;"), good.replace(b"--paper: #f4f4f1;", b"body { color: red; }")] for css in bad_cases: with self.subTest(css=css[-80:]): self.make_package(css=css) with self.assertRaises(ValueError): self.export() self.assertFalse(self.output.exists()) def test_wrong_package_id_and_malformed_metadata_are_refused(self): for kwargs in ({"package_id": "Other.Theme"}, {"version": ""}, {"nuspec_override": ""}, {"extras": [("other.nuspec", b"")]}): with self.subTest(kwargs=kwargs): self.make_package(**kwargs) with self.assertRaises(ValueError): self.export() def test_duplicate_package_entries_are_refused(self): for name in ("staticwebassets/css/theme.css", "ZB.MOM.WW.Theme.nuspec"): with self.subTest(name=name): self.make_package(extras=[(name, b"duplicate")]) with self.assertRaises(ValueError): self.export() def test_unsafe_package_entries_are_refused_even_when_not_exported(self): for name in ("../escape", "/absolute", "staticwebassets/../escape", "C:/escape", r"..\escape", "./alias"): with self.subTest(name=name): self.make_package(extras=[(name, b"unsafe")]) with self.assertRaises(ValueError): self.export() self.assertFalse((self.root.parent / "escape").exists()) def test_rejection_preserves_existing_output_and_cannot_replace_input_package(self): self.output.write_bytes(b"old export") self.make_package(missing="css/layout.css") with self.assertRaises(ValueError): self.export() self.assertEqual(b"old export", self.output.read_bytes()) self.make_package() original = self.package.read_bytes() with self.assertRaises(ValueError): self.export(self.package) self.assertEqual(original, self.package.read_bytes()) def test_existing_hardlink_alias_cannot_replace_package_inode(self): self.make_package() original = self.package.read_bytes() alias = self.root / "linked-input.zip" alias.hardlink_to(self.package) with self.assertRaises(ValueError): self.export(alias) self.assertEqual(original, self.package.read_bytes()) self.assertEqual(original, alias.read_bytes()) def test_existing_case_alias_cannot_overwrite_package_on_case_insensitive_filesystems(self): self.make_package() original = self.package.read_bytes() alias = self.root / self.package.name.upper() if not alias.exists() or not alias.samefile(self.package): self.skipTest("Case alias requires a case-insensitive filesystem") with self.assertRaises(ValueError): self.export(alias) self.assertEqual(original, self.package.read_bytes()) self.assertEqual(original, alias.read_bytes()) def test_cli_requires_explicit_provenance_and_builds_verified_output(self): self.make_package() cli = Path(__file__).with_name("export-web-assets.py") args = [sys.executable, str(cli), "--package", str(self.package), "--output", str(self.output)] missing = subprocess.run(args, capture_output=True) self.assertNotEqual(0, missing.returncode) self.assertFalse(self.output.exists()) ok = subprocess.run(args + ["--source-revision", REVISION, "--source-tag", "untagged"], capture_output=True) self.assertEqual(0, ok.returncode, ok.stderr.decode()) self.assertTrue(zipfile.is_zipfile(self.output)) if __name__ == "__main__": unittest.main()