"""Exercise tools/prepare-voidlibrary with Git and source stores owned by the fixture.""" from concurrent.futures import ThreadPoolExecutor, wait import hashlib import json import os from pathlib import Path import runpy import shlex import shutil import signal import stat import subprocess import tempfile import time import unittest from unittest.mock import patch TOOL = Path(__file__).resolve().parents[2] / "tools/prepare-voidlibrary" HEADERS = """ Async/Task Configuration/Argparse Core/Hash Crypto/Crypto Data/StrictJson Functional/Result Math/Numeric System/Process Testing/Test Testing/Detail/Registry Text/Url Time/Clock Unicode/Utf Detail/Enum Log/Log Stacktrace/Color """.split() SOURCES = "Configuration/Argparse Crypto/Crypto LogState/State System/Process Testing/Main".split() INCLUDED = ({f"include/Void/{name}.hpp" for name in HEADERS} | {f"src/{name}.cpp" for name in SOURCES} | {"src/Crypto/BuiltinHash.hpp"}) EXCLUDED = { ".gitattributes", "src/Core/module.cmake", "include/Void/Core/.private.hpp", "include/Void/Other/Header.hpp", "include/Void/System/AsyncProcess.hpp", "README.md", } JSON_HEADER = "include/Void/Data/StrictJson.hpp" class PreparationTests(unittest.TestCase): def setUp(self): temp = tempfile.TemporaryDirectory() self.addCleanup(temp.cleanup) self.root = Path(temp.name) self.tool = self.root / "project/tools/prepare-voidlibrary" self.tool.parent.mkdir(parents=True) shutil.copy2(TOOL, self.tool) self.store = self.tool.parents[1] / "build/voidlibrary" self.current = self.store / "current" self.source = self.root / "checkout" self.source.mkdir() self.env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_") and k != "VLS_VOID_SOURCE_DIR"} self.env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull) self.git("init", "--quiet", "--template=") for name in INCLUDED | EXCLUDED: self.write(name, f"// {name}\n") self.write(".gitattributes", "*.hpp filter=fixture\n") self.git("add", "--", *sorted(INCLUDED | EXCLUDED)) self.git("commit", "-qm", "synthetic recipe inputs") self.revision = self.git("rev-parse", "HEAD").strip() def git(self, *args): return subprocess.check_output( ["git", "-c", "core.hooksPath=/dev/null", "-c", "user.name=Fixture", "-c", "user.email=fixture@invalid", "-C", self.source, *args], text=True, env=self.env, ) def write(self, path, data): dest = self.source / path dest.parent.mkdir(parents=True, exist_ok=True) dest.write_text(data, encoding="utf-8") def cli(self, *args, env=None): return subprocess.run([self.tool, *args], env=self.env | (env or {}), capture_output=True, text=True, timeout=30) def prepare(self, source=None): result = self.cli("--source", source or self.source) self.assertEqual(result.returncode, 0, result.stderr) return Path(result.stdout.strip()) def failed_update(self, target): result = self.cli("--source", self.source) self.assertNotEqual(result.returncode, 0) self.assertEqual(self.current.resolve(strict=True), target) return result.stderr def check_generation(self, target): metadata = (target / "provenance.json").read_bytes() self.assertEqual(target.name, hashlib.sha256(metadata).hexdigest()) self.assertEqual(target.parent, self.store / "sources") self.assertLessEqual(len(metadata), 32768) self.assertTrue((target / "src/Core").is_dir()) self.assertFalse(os.path.lexists(target / "build.cpp")) return json.loads(metadata) def test_allowlist_provenance_and_duplicate(self): self.git("config", "filter.fixture.clean", "false") self.git("config", "filter.fixture.smudge", "false") self.git("config", "filter.fixture.required", "true") self.write("src/System/Untracked.cpp", "untracked canary") self.write("build.cpp", "untracked descriptor") index = self.source / ".git/index" before = (index.stat().st_mtime_ns, index.read_bytes()) target = self.prepare() self.assertEqual(os.readlink(self.current), f"sources/{target.name}") info = self.check_generation(target) self.assertEqual(info["source_kind"], "local") self.assertEqual(info["source_path"], str(self.source)) self.assertEqual(info["revision"], self.revision) self.assertFalse(info["dirty"]) files = {p.relative_to(target).as_posix() for p in target.rglob("*") if p.is_file()} self.assertEqual(files, INCLUDED | {"provenance.json"}) digest = hashlib.sha256() for name in sorted(INCLUDED): entry = target / name self.assertEqual(stat.S_IMODE(entry.stat().st_mode), 0o444) digest.update(name.encode() + b"\0" + hashlib.sha256(entry.read_bytes()).digest()) self.assertEqual(digest.hexdigest(), info["content_sha256"]) self.assertEqual(stat.S_IMODE(target.stat().st_mode), 0o555) again = self.cli(env={"VLS_VOID_SOURCE_DIR": str(self.source)}) self.assertEqual(again.returncode, 0, again.stderr) self.assertEqual(Path(again.stdout.strip()), target) self.write(JSON_HEADER, "raw edited header with rejecting Git filters") self.assertTrue(self.check_generation(self.prepare())["dirty"]) self.assertEqual((index.stat().st_mtime_ns, index.read_bytes()), before) def test_dirty_sources_staged_additions_and_prior_build(self): previous = self.prepare().resolve(strict=True) old_data = (previous / JSON_HEADER).read_bytes() self.write(JSON_HEADER, "// tracked local edit\n") self.write("src/System/Platform/Extension.cpp", "// staged local source\n") self.git("add", "--", "src/System/Platform/Extension.cpp") target = self.prepare() info = self.check_generation(target) self.assertTrue(info["dirty"]) self.assertEqual(info["revision"], self.revision) self.assertNotEqual(info["content_sha256"], self.check_generation(previous)["content_sha256"]) self.assertEqual((target / JSON_HEADER).read_text(), "// tracked local edit\n") self.assertTrue((target / "src/System/Platform/Extension.cpp").is_file()) self.assertFalse((previous / "src/System/Platform/Extension.cpp").exists()) self.assertEqual((previous / JSON_HEADER).read_bytes(), old_data) def test_unsupported_tracked_translation_unit_preserves_previous_generation(self): previous = self.prepare() name = "src/System/Window Helpers.cpp" self.write(name, "// valid source with an unsupported spelling\n") self.git("add", "--", name) self.assertIn("unsupported tracked translation unit", self.failed_update(previous)) def test_descriptor_rejected_in_index_and_head(self): previous = self.prepare() self.write("build.cpp", "synthetic descriptor") self.git("add", "--", "build.cpp") self.assertIn("tracked root build.cpp", self.failed_update(previous)) self.git("commit", "-qm", "synthetic descriptor") self.git("rm", "-q", "--", "build.cpp") self.assertIn("tracked root build.cpp", self.failed_update(previous)) def test_rejects_links_missing_inputs_and_unstable_capture(self): previous = self.prepare() data = self.source / "include/Void/Data" moved = self.root / "moved" data.rename(moved) data.symlink_to(moved, target_is_directory=True) self.failed_update(previous) data.unlink() moved.rename(data) leaf = self.source / JSON_HEADER leaf.unlink() self.failed_update(previous) leaf.symlink_to(self.root / "absent") self.failed_update(previous) self.git("add", "--", JSON_HEADER) self.assertIn("link", self.failed_update(previous)) leaf.unlink() self.write(JSON_HEADER, "regular again") self.git("update-index", "--cacheinfo", f"160000,{self.revision},{JSON_HEADER}") self.assertIn("link", self.failed_update(previous)) oid = self.git("rev-parse", "HEAD:" + JSON_HEADER).strip() self.git("update-index", "--cacheinfo", f"100644,{oid},{JSON_HEADER}") mod = runpy.run_path(str(self.tool)) read_local = mod["local_file"] def changing_file(root, path): result = read_local(root, path) if path == JSON_HEADER and result[0] == b"regular again": self.write(path, "changed after the first read") return result with patch.dict(mod["prepare"].__globals__, local_file=changing_file): with self.assertRaisesRegex(mod["PreparationError"], "changed during preparation"): mod["prepare"](self.source) self.assertEqual(self.current.resolve(strict=True), previous) def test_concurrent_publications_and_failed_fetch(self): first = self.prepare() second_source = self.root / "second-checkout" shutil.copytree(self.source, second_source) (second_source / JSON_HEADER).write_text("second source") with ThreadPoolExecutor(max_workers=4) as pool: pending = [pool.submit(self.prepare, src) for src in [self.source, second_source] * 4] while True: self.check_generation(self.current.resolve(strict=True)) if not wait(pending, timeout=0.005).not_done: break targets = {future.result() for future in pending} self.assertEqual(len(targets), 2) self.assertEqual(set((self.store / "sources").iterdir()), targets) self.assertIn(first, targets) previous = self.current.resolve(strict=True) trap = self.root / "offline" trap.mkdir() shim = trap / "git" shim.write_text("#!/bin/sh\nfor arg do\n if [ \"$arg\" = fetch ]; then\n" " echo synthetic-fetch-diagnostic >&2\n exit 76\n fi\ndone\n" f"exec {shlex.quote(shutil.which('git'))} \"$@\"\n") shim.chmod(0o755) result = self.cli(env={"PATH": f"{trap}:{self.env['PATH']}"}) self.assertNotEqual(result.returncode, 0) self.assertIn("git fetch failed (exit 76)", result.stderr) self.assertNotIn("synthetic-fetch-diagnostic", result.stderr) self.assertEqual(self.current.resolve(strict=True), previous) self.check_generation(first) def test_interrupted_capture_can_retry(self): previous = self.prepare() self.write(JSON_HEADER, "new generation") trap = self.root / "interruption" trap.mkdir() first, ready = trap / "first", trap / "ready" # Pause the second index read, after the new files are staged and before # publication. Terminate the whole fixture process group at that point. shim = trap / "git" shim.write_text("#!/bin/sh\nfor arg do\n if [ \"$arg\" = ls-files ]; then\n" f" if [ -f {shlex.quote(str(first))} ]; then\n" f" touch {shlex.quote(str(ready))}\n exec sleep 20\n fi\n" f" touch {shlex.quote(str(first))}\n fi\ndone\n" f"exec {shlex.quote(shutil.which('git'))} \"$@\"\n") shim.chmod(0o755) with subprocess.Popen([self.tool, "--source", self.source], start_new_session=True, env=self.env | {"PATH": f"{trap}:{self.env['PATH']}"}) as proc: try: timeout = time.monotonic() + 5 while not ready.exists() and proc.poll() is None and time.monotonic() < timeout: time.sleep(0.005) self.assertTrue(ready.exists()) finally: if proc.poll() is None: os.killpg(proc.pid, signal.SIGKILL) self.assertEqual(proc.wait(timeout=5), -signal.SIGKILL) self.assertEqual(self.current.resolve(strict=True), previous) self.assertTrue(self.check_generation(self.prepare())["dirty"]) self.assertFalse(self.check_generation(previous)["dirty"]) def test_rejects_unowned_layout_or_damaged_generation(self): previous = self.prepare() # Simulate a damaged store in an isolated fixture. previous.chmod(0o755) (previous / "build.cpp").write_text("unexpected fixture entry") previous.chmod(0o555) self.assertIn("unexpected entries", self.failed_update(previous)) sources = self.store / "sources" moved = self.root / "moved-sources" sources.rename(moved) sources.symlink_to(moved, target_is_directory=True) result = self.cli("--source", self.source) self.assertNotEqual(result.returncode, 0) self.assertIn("owned directory", result.stderr) if __name__ == "__main__": unittest.main()