diff --git a/.github/workflows/check-script-cache-drift.yml b/.github/workflows/check-script-cache-drift.yml
index e0939e52..0670df44 100644
--- a/.github/workflows/check-script-cache-drift.yml
+++ b/.github/workflows/check-script-cache-drift.yml
@@ -5,6 +5,15 @@
# (tools/ci/check_cache_drift.py). On drift the job fails, uploads the
# evidence, saves the cold cache over the stale one, and the report job opens
# or updates the `cache-drift` issue.
+#
+# Pull requests do not run this workflow (too slow, and drift depends on the
+# cache's history). tools/tests/test_check_cache_drift.py in
+# verify-scripts.yml unit-tests the driver instead, with the generator, the
+# audit and git mocked: which generator exits count as a result, the diffs,
+# affected libraries and evidence, status.json, the GITHUB_OUTPUT flags and
+# the issue body. Not covered there: real generator runs, the driver's
+# --out handling, and this file's step conditions, artifacts and report job;
+# those still need a workflow_dispatch run to check.
name: Check Script Cache Drift
env:
diff --git a/tools/ci/check_cache_drift.py b/tools/ci/check_cache_drift.py
index e0807ee7..16f07f44 100644
--- a/tools/ci/check_cache_drift.py
+++ b/tools/ci/check_cache_drift.py
@@ -303,7 +303,12 @@ def summarize(src, run_url):
continue
lines = report.read_text(encoding="utf-8").splitlines()
if len(lines) > ISSUE_DIFF_LINES:
- lines = lines[:ISSUE_DIFF_LINES] + ["```", "(truncated)"]
+ lines = lines[:ISSUE_DIFF_LINES]
+ # Close the ```diff block only when the cut falls inside one:
+ # an unpaired fence would turn the rest of the issue into code.
+ if sum(l.startswith("```") for l in lines) % 2:
+ lines.append("```")
+ lines.append("(truncated)")
block = ["", "{}: diff excerpt
".format(
s["os"]), ""] + lines + ["", " "]
text = "\n".join(block)
diff --git a/tools/gen_exports.py b/tools/gen_exports.py
index 482695d0..5321deab 100644
--- a/tools/gen_exports.py
+++ b/tools/gen_exports.py
@@ -2083,8 +2083,11 @@ def main() -> int:
for line in problems:
print("facade: " + line)
if problems:
- print("error: {} facade problem(s)".format(len(problems)),
- file=sys.stderr)
+ # stdout, not stderr: tools/ci/check_cache_drift.py reads this as
+ # the last line of the merged output to tell a facade-only failure
+ # from a crash. Piped stdout is block-buffered and flushed at exit,
+ # so on stderr this line would come out before the facade: lines.
+ print("error: {} facade problem(s)".format(len(problems)))
return 1
return rc
diff --git a/tools/tests/test_check_cache_drift.py b/tools/tests/test_check_cache_drift.py
new file mode 100644
index 00000000..56feb5c9
--- /dev/null
+++ b/tools/tests/test_check_cache_drift.py
@@ -0,0 +1,637 @@
+"""tools/ci/check_cache_drift.py: the nightly driver that compares a cached
+regeneration (A), a cold one (B) and the committed files (C).
+
+The generator, the audit and the git steps are mocked out: these tests need
+neither clang nor the MinGW sysroot. What they pin down is which generator
+exits count as a result, and the verdict, above all the ``cache_drift``
+output the workflow reads to decide whether the cold cache replaces the
+restored one."""
+import io
+import json
+import os
+import shutil
+import sys
+import tempfile
+import unittest
+from contextlib import redirect_stderr, redirect_stdout
+from pathlib import Path
+from unittest import mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "ci"))
+
+import ast_json
+import boost_common
+import check_cache_drift as ccd
+import gen_exports
+import verify_generated
+
+
+def api_surface(**libs):
+ return json.dumps({"libraries": libs}).encode()
+
+
+class TempDirTest(unittest.TestCase):
+ def setUp(self):
+ tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(tmp.cleanup)
+ self.tmp = Path(tmp.name)
+
+
+class DiffFilesTests(unittest.TestCase):
+ def test_identical_trees_do_not_differ(self):
+ tree = {"a": b"1", "b": b"2"}
+ self.assertEqual(ccd.diff_files(tree, dict(tree)), [])
+ self.assertEqual(ccd.diff_files({}, {}), [])
+
+ def test_changed_content(self):
+ self.assertEqual(ccd.diff_files({"a": b"1", "b": b"2"},
+ {"a": b"1", "b": b"3"}), ["b"])
+
+ def test_file_on_one_side_only(self):
+ self.assertEqual(ccd.diff_files({"z": b"", "a": b"1"}, {"a": b"1"}),
+ ["z"])
+ self.assertEqual(ccd.diff_files({"a": b"1"}, {"a": b"1", "m": b""}),
+ ["m"])
+
+ def test_sorted(self):
+ self.assertEqual(ccd.diff_files({"c": b"1", "a": b"1"},
+ {"b": b"1"}), ["a", "b", "c"])
+
+
+class AffectedLibsTests(unittest.TestCase):
+ def test_export_lists(self):
+ paths = ["generated/exports/heap.inc", "generated/exports/heap.deps",
+ "generated/exports/asio.inc"]
+ self.assertEqual(ccd.affected_libs(paths, {}, {}), ["asio", "heap"])
+
+ def test_audit_reports(self):
+ self.assertEqual(ccd.affected_libs(
+ ["target/gen/audit/core.txt", "target/gen/audit/heap.txt"],
+ {}, {}), ["core", "heap"])
+
+ def test_api_surface_names_only_the_changed_entries(self):
+ p = "generated/meta/api-surface.json"
+ old = {p: api_surface(core=[1], heap=[1], asio=[1])}
+ new = {p: api_surface(core=[1], heap=[2], json=[1])}
+ self.assertEqual(ccd.affected_libs([p], old, new),
+ ["asio", "heap", "json"])
+
+ def test_api_surface_missing_on_one_side(self):
+ p = "generated/meta/api-surface.json"
+ both = {p: api_surface(core=[1], heap=[1])}
+ self.assertEqual(ccd.affected_libs([p], {}, both), ["core", "heap"])
+ self.assertEqual(ccd.affected_libs([p], both, {}), ["core", "heap"])
+
+ def test_export_list_missing_on_one_side(self):
+ p = "generated/exports/heap.inc"
+ self.assertEqual(ccd.affected_libs([p], {p: b"x"}, {}), ["heap"])
+ self.assertEqual(ccd.affected_libs([p], {}, {p: b"x"}), ["heap"])
+
+ def test_other_files_name_no_library(self):
+ self.assertEqual(ccd.affected_libs(
+ ["generated/meta/skipped.txt"], {}, {}), [])
+
+
+class UnifiedTests(TempDirTest):
+ OLD = {"f": "\n".join("line {}".format(i) for i in range(20)).encode()}
+ NEW = {"f": "\n".join("LINE {}".format(i) for i in range(20)).encode()}
+
+ def test_headers_name_both_sides(self):
+ lines = ccd.unified("f", {"f": b"x"}, {"f": b"y"}, "cold", "cached", 0)
+ self.assertEqual(lines[:2], ["--- cold/f", "+++ cached/f"])
+ self.assertEqual(lines[-2:], ["-x", "+y"])
+
+ def test_limit_truncates_and_counts_the_rest(self):
+ full = ccd.unified("f", self.OLD, self.NEW, "a", "b", 0)
+ cut = ccd.unified("f", self.OLD, self.NEW, "a", "b", 10)
+ self.assertEqual(cut[:10], full[:10])
+ self.assertEqual(cut[10:], ["... ({} more diff lines)".format(
+ len(full) - 10)])
+
+ def test_within_the_limit_is_untouched(self):
+ full = ccd.unified("f", self.OLD, self.NEW, "a", "b", 0)
+ self.assertEqual(ccd.unified("f", self.OLD, self.NEW, "a", "b",
+ len(full)), full)
+
+ def test_missing_side_reads_as_empty(self):
+ self.assertEqual(ccd.unified("f", {}, {"f": b"x\ny"}, "a", "b", 0)[2:],
+ ["@@ -0,0 +1,2 @@", "+x", "+y"])
+ self.assertEqual(ccd.unified("f", {"f": b"x"}, {}, "a", "b", 0)[2:],
+ ["@@ -1 +0,0 @@", "-x"])
+
+ def test_write_diff_is_never_truncated(self):
+ out = self.tmp / "d.diff"
+ old = dict(self.OLD, g=b"gone")
+ ccd.write_diff(out, ["f", "g"], old, self.NEW, "a", "b")
+ text = out.read_bytes().decode()
+ self.assertNotIn("more diff lines", text)
+ self.assertNotIn("\r", text)
+ self.assertEqual(text, "\n".join(
+ ccd.unified("f", old, self.NEW, "a", "b", 0) +
+ ccd.unified("g", old, self.NEW, "a", "b", 0)) + "\n")
+ self.assertIn("-gone", text)
+
+
+class CopyEntriesTests(TempDirTest):
+ def test_only_the_affected_libraries(self):
+ src = self.tmp / "src"
+ src.mkdir()
+ for lib in ("heap", "core"):
+ for kind in ("skip", "gate", "audit"):
+ (src / "{}.{}.json".format(lib, kind)).write_text(lib + kind)
+ (src / "heap.bundle.cpp").write_text("not an entry")
+ dst = self.tmp / "dst"
+ ccd.copy_entries(src, dst, ["heap"])
+ self.assertEqual(sorted(p.name for p in dst.iterdir()),
+ ["heap.audit.json", "heap.gate.json",
+ "heap.skip.json"])
+ self.assertEqual((dst / "heap.gate.json").read_text(), "heapgate")
+
+ def test_missing_entries_are_skipped(self):
+ src = self.tmp / "src"
+ src.mkdir()
+ (src / "heap.skip.json").write_text("{}")
+ dst = self.tmp / "dst"
+ ccd.copy_entries(src, dst, ["heap", "asio"])
+ self.assertEqual([p.name for p in dst.iterdir()], ["heap.skip.json"])
+
+ def test_nothing_to_copy_creates_nothing(self):
+ dst = self.tmp / "dst"
+ ccd.copy_entries(self.tmp / "absent", dst, ["heap"])
+ ccd.copy_entries(self.tmp, dst, [])
+ self.assertFalse(dst.exists())
+
+
+def status(os_name, cache=(), audit=(), committed=(), restored=3):
+ return {"os": os_name,
+ "cache_drift": ["generated/exports/{}.inc".format(l)
+ for l in cache],
+ "cache_drift_libs": list(cache),
+ "audit_drift": ["target/gen/audit/{}.txt".format(l)
+ for l in audit],
+ "audit_drift_libs": list(audit),
+ "committed_drift": ["generated/exports/{}.inc".format(l)
+ for l in committed],
+ "committed_drift_libs": list(committed),
+ "restored_entries": restored}
+
+
+class SummarizeTests(TempDirTest):
+ def leg(self, name, s, report=None):
+ d = self.tmp / name
+ d.mkdir()
+ (d / "status.json").write_text(json.dumps(s), encoding="utf-8")
+ if report is not None:
+ (d / "report.md").write_text("\n".join(report) + "\n",
+ encoding="utf-8")
+
+ def rows(self, body):
+ return [l for l in body.splitlines()
+ if l.startswith("| ") and not l.startswith("| Platform")]
+
+ def test_no_drift_is_empty(self):
+ self.leg("cache-drift-Linux", status("Linux"))
+ self.leg("cache-drift-macOS", status("macOS"))
+ self.assertEqual(ccd.summarize(self.tmp, "URL"), "")
+ self.assertEqual(ccd.summarize(self.tmp / "absent", "URL"), "")
+
+ def test_each_kind_of_drift_alone(self):
+ for kind, row in (("cache", "| Linux | heap | - | - | 3 |"),
+ ("audit", "| Linux | - | heap | - | 3 |"),
+ ("committed", "| Linux | - | - | heap | 3 |")):
+ with self.subTest(kind):
+ shutil.rmtree(self.tmp / "cache-drift-Linux",
+ ignore_errors=True)
+ self.leg("cache-drift-Linux", status("Linux", **{kind: ["heap"]}))
+ body = ccd.summarize(self.tmp, "https://run")
+ self.assertTrue(body.startswith(ccd.MARKER + "\n"))
+ self.assertIn("Run: https://run", body)
+ self.assertEqual(self.rows(body), [row])
+
+ def test_only_drifting_platforms_are_listed(self):
+ self.leg("cache-drift-Linux", status("Linux", cache=["heap", "core"]))
+ self.leg("cache-drift-Windows", status("Windows"))
+ self.leg("cache-drift-macOS", status("macOS", committed=["asio"],
+ restored=0),
+ report=["## Committed", "macos excerpt"])
+ body = ccd.summarize(self.tmp, "URL")
+ self.assertEqual(self.rows(body), ["| Linux | heap, core | - | - | 3 |",
+ "| macOS | - | - | asio | 0 |"])
+ self.assertNotIn("Windows", body)
+ # Only a leg with a report.md gets an excerpt.
+ self.assertEqual(body.count(""), 1)
+ self.assertIn("macOS: diff excerpt
\n\n"
+ "## Committed\nmacos excerpt\n\n ", body)
+
+ @staticmethod
+ def section(title, lib, diff_lines):
+ """One section of report.md, laid out as check() writes it."""
+ return ([title, "", "Libraries: " + lib, "", "```diff"] +
+ ["+line {}".format(i) for i in range(diff_lines)] +
+ ["```", ""])
+
+ def excerpt(self, report):
+ self.leg("cache-drift-Linux", status("Linux", cache=["heap"]),
+ report=report)
+ body = ccd.summarize(self.tmp, "URL")
+ excerpt = body.split("", 1)[1]
+ # Every fence is paired, so the issue text after it stays text.
+ self.assertEqual(sum(l.startswith("```")
+ for l in excerpt.splitlines()) % 2, 0)
+ return excerpt
+
+ def test_long_report_cut_inside_a_diff_block(self):
+ n = ccd.ISSUE_DIFF_LINES
+ report = self.section("## Cache drift (A != B)", "heap", n + 50)
+ excerpt = self.excerpt(report)
+ last = report[n - 1]
+ self.assertIn("\n{}\n```\n(truncated)\n\n ".format(last),
+ excerpt)
+ self.assertNotIn("\n{}\n".format(report[n]), excerpt)
+
+ def test_long_report_cut_between_diff_blocks(self):
+ n = ccd.ISSUE_DIFF_LINES
+ # The first section ends 4 lines before the cut, which falls between
+ # the second section's "Libraries:" line and its ```diff fence.
+ report = (self.section("## Cache drift (A != B)", "heap", n - 11) +
+ self.section("## Audit cache drift (A != B)", "core", 50))
+ self.assertEqual(report[n - 4:n + 1],
+ ["## Audit cache drift (A != B)", "",
+ "Libraries: core", "", "```diff"])
+ excerpt = self.excerpt(report)
+ self.assertIn("\nLibraries: core\n\n(truncated)\n\n ",
+ excerpt)
+
+ def test_length_budget_omits_further_excerpts(self):
+ line = "x" * 400
+ for name in ("a-Linux", "b-Windows", "c-macOS"):
+ self.leg(name, status(name, cache=["heap"]),
+ report=[line] * ccd.ISSUE_DIFF_LINES)
+ body = ccd.summarize(self.tmp, "URL")
+ self.assertEqual(len(self.rows(body)), 3)
+ # One excerpt is ~48 KB: the second would pass the 60 KB budget.
+ self.assertEqual(body.count(""), 1)
+ self.assertIn("a-Linux: diff excerpt", body)
+ self.assertTrue(body.endswith(
+ "\n(further excerpts omitted: see the artifacts)\n"))
+ self.assertLess(len(body), 60000)
+
+ def test_main_prints_the_summary(self):
+ self.leg("cache-drift-Linux", status("Linux", audit=["heap"]))
+ out = io.StringIO()
+ with mock.patch("sys.argv", ["check_cache_drift.py", "--summarize",
+ str(self.tmp), "--run-url", "U"]), \
+ mock.patch.object(ccd, "check") as check, \
+ redirect_stdout(out):
+ self.assertEqual(ccd.main(), 0)
+ check.assert_not_called()
+ self.assertEqual(out.getvalue(), ccd.summarize(self.tmp, "U"))
+
+
+class FakeProc:
+ """What generate() and audit() use of a subprocess.Popen."""
+
+ def __init__(self, lines, rc):
+ self.stdout = iter(lines)
+ self.rc = rc
+
+ def wait(self):
+ return self.rc
+
+
+class GenerateTests(TempDirTest):
+ """generate() with gen_exports.py, its snapshot and git mocked: which
+ exits it lets through and what it does with the output."""
+
+ FILES = {"generated/exports/heap.inc": b"heap\n"}
+
+ def run_generate(self, lines, rc):
+ self.commands = []
+
+ def popen(command, **kwargs):
+ self.commands.append((command, kwargs))
+ return FakeProc(lines, rc)
+
+ with mock.patch.object(ccd.subprocess, "Popen", side_effect=popen), \
+ mock.patch.object(gen_exports, "_snapshot",
+ return_value=dict(self.FILES)) as snap, \
+ mock.patch.object(verify_generated, "git") as git, \
+ redirect_stdout(io.StringIO()):
+ self.snap, self.git = snap, git
+ return ccd.generate("A-cached", self.tmp)
+
+ def assert_restored(self):
+ self.snap.assert_called_once_with(ccd.ROOT)
+ self.assertEqual([c.args for c in self.git.call_args_list],
+ [("checkout", "--", "generated"),
+ ("clean", "-fdq", "--", "generated")])
+
+ def assert_fails(self, lines, rc):
+ with self.assertRaises(SystemExit) as cm:
+ self.run_generate(lines, rc)
+ self.assertEqual(str(cm.exception), "[A-cached] gen_exports.py "
+ "failed with exit code {}".format(rc))
+ # Partial output is neither read nor taken for drift.
+ self.snap.assert_not_called()
+
+ def test_success(self):
+ lines = ["heap: 12 exported\n", "wrote generated/exports\n"]
+ self.assertEqual(self.run_generate(lines, 0), (self.FILES, 0))
+ [(command, kwargs)] = self.commands
+ self.assertEqual(command, [sys.executable,
+ str(ccd.TOOLS / "gen_exports.py")])
+ self.assertEqual(kwargs["cwd"], ccd.ROOT)
+ self.assert_restored()
+ self.assertEqual((self.tmp / "logs" / "A-cached.log")
+ .read_text(encoding="utf-8"), "".join(lines))
+
+ def test_facade_problems_are_let_through(self):
+ # gen_exports.py's last words when only facades are wrong; trailing
+ # blank lines do not count.
+ lines = ["wrote generated/exports\n",
+ "facade: boost/heap.cppm: missing import\n",
+ "error: 1 facade problem(s)\n", "\n", " \n"]
+ self.assertEqual(self.run_generate(lines, 1), (self.FILES, 1))
+ self.assert_restored()
+
+ def test_other_failure_stops_the_run(self):
+ self.assert_fails(["Traceback (most recent call last):\n",
+ "KeyError: 'heap'\n"], 1)
+ self.assert_fails([], 2)
+
+ def test_facade_message_must_be_the_last_line(self):
+ self.assert_fails(["error: 1 facade problem(s)\n",
+ "Traceback (most recent call last):\n",
+ "OSError: disk full\n"], 1)
+
+
+class AuditTests(TempDirTest):
+ """audit() with gen_audit.py mocked."""
+
+ def run_audit(self, rc):
+ self.commands = []
+
+ def popen(command, **kwargs):
+ self.commands.append((command, kwargs))
+ dest = Path(command[command.index("--out") + 1])
+ dest.mkdir(parents=True)
+ for lib in ("heap", "core"):
+ (dest / (lib + ".txt")).write_bytes(lib.encode() + b" ok\n")
+ (dest / "notes.log").write_text("not a report")
+ return FakeProc(["audited 2 libraries\n"], rc)
+
+ # check() always runs generate(), which creates logs/, first.
+ (self.tmp / "logs").mkdir(exist_ok=True)
+ with mock.patch.object(ccd.subprocess, "Popen", side_effect=popen), \
+ redirect_stdout(io.StringIO()):
+ return ccd.audit("B-cold", self.tmp)
+
+ def test_reports(self):
+ dest = self.tmp / "work" / "audit-B-cold"
+ dest.mkdir(parents=True)
+ (dest / "stale.txt").write_text("from an earlier run")
+ self.assertEqual(self.run_audit(0), {
+ "target/gen/audit/core.txt": b"core ok\n",
+ "target/gen/audit/heap.txt": b"heap ok\n"})
+ [(command, kwargs)] = self.commands
+ self.assertEqual(command, [sys.executable,
+ str(ccd.TOOLS / "gen_audit.py"),
+ "--out", str(dest)])
+ self.assertEqual(kwargs["cwd"], ccd.ROOT)
+ self.assertEqual((self.tmp / "logs" / "B-cold-audit.log")
+ .read_text(encoding="utf-8"),
+ "audited 2 libraries\n")
+
+ def test_failure_stops_the_run(self):
+ with self.assertRaises(SystemExit) as cm:
+ self.run_audit(1)
+ self.assertEqual(str(cm.exception),
+ "[B-cold] gen_audit.py failed with exit code 1")
+
+
+COMMITTED = {
+ "generated/exports/heap.inc": b"heap\n",
+ "generated/exports/core.inc": b"core\n",
+ "generated/meta/api-surface.json": api_surface(heap=[1], core=[1]),
+}
+AUDIT = {"target/gen/audit/heap.txt": b"ok\n",
+ "target/gen/audit/core.txt": b"ok\n"}
+
+
+class CheckTests(TempDirTest):
+ """check() with generate, audit and the git and sysroot steps mocked:
+ each test chooses what A (cached), B (cold) and C (committed) are."""
+
+ def setUp(self):
+ super().setUp()
+ self.out = self.tmp / "out"
+ self.cache = self.tmp / "exports-cache"
+ self.gh_output = self.tmp / "github_output"
+ self.gh_output.write_text("earlier=1\n", encoding="utf-8")
+ self.calls = []
+
+ def restore_cache(self, *libs):
+ """The cache entries actions/cache restored."""
+ self.cache.mkdir(parents=True)
+ self.restored = {}
+ for lib in libs:
+ for kind in ("skip", "gate", "audit"):
+ name = "{}.{}.json".format(lib, kind)
+ self.restored[name] = "restored " + lib
+ (self.cache / name).write_text(self.restored[name],
+ encoding="utf-8")
+
+ def run_check(self, cached=COMMITTED, cold=COMMITTED,
+ committed=COMMITTED, audit_cached=AUDIT, audit_cold=AUDIT,
+ rc=(0, 0), env=None):
+ runs = {"A-cached": (dict(cached), rc[0]),
+ "B-cold": (dict(cold), rc[1])}
+ audits = {"A-cached": dict(audit_cached), "B-cold": dict(audit_cold)}
+
+ def generate(label, out):
+ self.assertEqual(out, self.out)
+ self.calls.append((label, self.cache.is_dir()))
+ if label == "B-cold":
+ # A cold run fills the cache it found empty (the calls
+ # record says whether it was).
+ self.cache.mkdir(parents=True, exist_ok=True)
+ for lib in ("heap", "core"):
+ for kind in ("skip", "gate", "audit"):
+ (self.cache / "{}.{}.json".format(lib, kind)) \
+ .write_text("cold " + lib, encoding="utf-8")
+ # The work tree has the restored cache as it was before A.
+ if label == "A-cached" and self.cache.is_dir():
+ copy = self.out / "work" / "cache-restored"
+ self.assertEqual({p.name: p.read_text(encoding="utf-8")
+ for p in copy.iterdir()}, self.restored)
+ return runs[label]
+
+ def audit(label, out):
+ self.calls.append((label + "-audit", self.cache.is_dir()))
+ return audits[label]
+
+ if env is None:
+ env = {"GITHUB_OUTPUT": str(self.gh_output), "RUNNER_OS": "Linux"}
+ stdout, stderr = io.StringIO(), io.StringIO()
+ with mock.patch.object(ccd, "generate", side_effect=generate), \
+ mock.patch.object(ccd, "audit", side_effect=audit), \
+ mock.patch.object(boost_common, "CACHE_DIR", self.cache), \
+ mock.patch.object(gen_exports, "_snapshot",
+ return_value=dict(committed)), \
+ mock.patch.object(verify_generated, "assert_clean") as clean, \
+ mock.patch.object(verify_generated, "run_step") as step, \
+ mock.patch.object(ast_json, "clang_version",
+ return_value="clang version 22.1.8"), \
+ mock.patch.object(ast_json, "clang_command",
+ return_value=["clang++", "-x"]), \
+ mock.patch.dict(os.environ, env, clear=False), \
+ redirect_stdout(stdout), redirect_stderr(stderr):
+ if "GITHUB_OUTPUT" not in env:
+ os.environ.pop("GITHUB_OUTPUT", None)
+ rc_check = ccd.check(self.out)
+ clean.assert_called_once_with("initial checkout")
+ self.assertEqual([c.args for c in step.call_args_list],
+ [("fetch_mingw_sysroot.py",), ("apply_patches.py",)])
+ self.stdout, self.stderr = stdout.getvalue(), stderr.getvalue()
+ self.status = json.loads((self.out / "status.json")
+ .read_text(encoding="utf-8"))
+ return rc_check
+
+ def outputs(self):
+ lines = self.gh_output.read_text(encoding="utf-8").splitlines()
+ self.assertEqual(lines[0], "earlier=1") # appended, not overwritten
+ return dict(l.split("=", 1) for l in lines[1:])
+
+ def test_no_drift(self):
+ self.restore_cache("heap", "core")
+ self.assertEqual(self.run_check(rc=(1, 1)), 0)
+ self.assertEqual(self.outputs(), {"cache_drift": "false",
+ "committed_drift": "false"})
+ for key in ("cache_drift", "cache_drift_libs", "audit_drift",
+ "audit_drift_libs", "committed_drift",
+ "committed_drift_libs"):
+ self.assertEqual(self.status[key], [], key)
+ self.assertEqual(self.status["os"].split(" ")[0], "Linux")
+ self.assertEqual(self.status["clang"], "clang version 22.1.8")
+ self.assertEqual(self.status["clang_command"], ["clang++", "-x"])
+ self.assertEqual(self.status["restored_entries"], 2)
+ # A facade problem fails gen_exports.py without making it drift
+ # (generate() lets that exit through: GenerateTests).
+ self.assertEqual(self.status["exit_codes"],
+ {"A-cached": 1, "B-cold": 1})
+ # A runs on the restored cache, B on an empty one.
+ self.assertEqual(self.calls, [("A-cached", True),
+ ("A-cached-audit", True),
+ ("B-cold", False),
+ ("B-cold-audit", True)])
+ self.assertEqual(sorted(p.name for p in self.out.iterdir()),
+ ["status.json"])
+ self.assertIn("no drift", self.stdout)
+
+ def test_no_restored_cache(self):
+ self.assertEqual(self.run_check(), 0)
+ self.assertEqual(self.status["restored_entries"], 0)
+ self.assertEqual(self.calls[0], ("A-cached", False))
+
+ def test_cache_drift(self):
+ self.restore_cache("heap", "core")
+ cached = dict(COMMITTED, **{"generated/exports/heap.inc": b"stale\n"})
+ self.assertEqual(self.run_check(cached=cached), 1)
+ self.assertEqual(self.outputs(), {"cache_drift": "true",
+ "committed_drift": "false"})
+ self.assertEqual(self.status["cache_drift"],
+ ["generated/exports/heap.inc"])
+ self.assertEqual(self.status["cache_drift_libs"], ["heap"])
+ self.assertEqual(self.status["audit_drift"], [])
+ self.assertEqual(self.status["committed_drift"], [])
+ diff = (self.out / "cache-vs-cold.diff").read_text(encoding="utf-8")
+ self.assertIn("--- cold/generated/exports/heap.inc", diff)
+ self.assertIn("+stale", diff)
+ # Both versions of the drifting library's entries, and only those.
+ for side, text in (("restored", "restored heap"),
+ ("cold", "cold heap")):
+ d = self.out / "evidence" / side
+ self.assertEqual(sorted(p.name for p in d.iterdir()),
+ ["heap.audit.json", "heap.gate.json",
+ "heap.skip.json"])
+ self.assertEqual((d / "heap.skip.json").read_text(), text)
+ report = (self.out / "report.md").read_text(encoding="utf-8")
+ self.assertIn("## Cache drift (A != B)\n\nLibraries: heap\n", report)
+ self.assertNotIn("Committed", report)
+ self.assertFalse((self.out / "work").exists())
+ self.assertIn("drift detected", self.stderr)
+
+ def test_audit_drift(self):
+ self.restore_cache("heap", "core")
+ audit_cached = dict(AUDIT, **{"target/gen/audit/core.txt": b"old\n"})
+ self.assertEqual(self.run_check(audit_cached=audit_cached), 1)
+ self.assertEqual(self.outputs(), {"cache_drift": "true",
+ "committed_drift": "false"})
+ self.assertEqual(self.status["cache_drift"], [])
+ self.assertEqual(self.status["audit_drift"],
+ ["target/gen/audit/core.txt"])
+ self.assertEqual(self.status["audit_drift_libs"], ["core"])
+ self.assertTrue((self.out / "audit-cache-vs-cold.diff").is_file())
+ self.assertFalse((self.out / "cache-vs-cold.diff").exists())
+ # Both versions of the drifting library's entries, and only those.
+ for side, text in (("restored", "restored core"),
+ ("cold", "cold core")):
+ d = self.out / "evidence" / side
+ self.assertEqual(sorted(p.name for p in d.iterdir()),
+ ["core.audit.json", "core.gate.json",
+ "core.skip.json"])
+ for p in d.iterdir():
+ self.assertEqual(p.read_text(encoding="utf-8"), text, p.name)
+ self.assertIn("## Audit cache drift (A != B)",
+ (self.out / "report.md").read_text(encoding="utf-8"))
+
+ def test_committed_drift(self):
+ self.restore_cache("heap", "core")
+ cold = dict(COMMITTED, **{
+ "generated/meta/api-surface.json": api_surface(heap=[2], core=[1])})
+ self.assertEqual(self.run_check(cached=cold, cold=cold), 1)
+ # The cache replayed the cold run: nothing to save over it.
+ self.assertEqual(self.outputs(), {"cache_drift": "false",
+ "committed_drift": "true"})
+ self.assertEqual(self.status["cache_drift"], [])
+ self.assertEqual(self.status["audit_drift"], [])
+ self.assertEqual(self.status["committed_drift"],
+ ["generated/meta/api-surface.json"])
+ self.assertEqual(self.status["committed_drift_libs"], ["heap"])
+ diff = (self.out / "committed-vs-cold.diff").read_text(
+ encoding="utf-8")
+ self.assertIn("--- committed/generated/meta/api-surface.json", diff)
+ self.assertIn("+++ cold/generated/meta/api-surface.json", diff)
+ self.assertFalse((self.out / "evidence").exists())
+ self.assertIn("## Committed output differs from a cold run (B != C)",
+ (self.out / "report.md").read_text(encoding="utf-8"))
+
+ def test_every_kind_at_once(self):
+ self.restore_cache("heap", "core")
+ cold = dict(COMMITTED, **{"generated/exports/core.inc": b"new\n"})
+ cached = dict(COMMITTED, **{"generated/exports/heap.inc": b"stale\n"})
+ audit_cached = dict(AUDIT, **{"target/gen/audit/heap.txt": b"old\n"})
+ self.assertEqual(self.run_check(cached=cached, cold=cold,
+ audit_cached=audit_cached), 1)
+ self.assertEqual(self.outputs(), {"cache_drift": "true",
+ "committed_drift": "true"})
+ self.assertEqual(self.status["cache_drift_libs"], ["core", "heap"])
+ self.assertEqual(self.status["audit_drift_libs"], ["heap"])
+ self.assertEqual(self.status["committed_drift_libs"], ["core"])
+ report = (self.out / "report.md").read_text(encoding="utf-8")
+ self.assertLess(report.index("## Cache drift"),
+ report.index("## Audit cache drift"))
+ self.assertLess(report.index("## Audit cache drift"),
+ report.index("## Committed output"))
+
+ def test_without_github_output(self):
+ self.restore_cache("heap")
+ cached = dict(COMMITTED, **{"generated/exports/heap.inc": b"stale\n"})
+ self.assertEqual(self.run_check(cached=cached,
+ env={"RUNNER_OS": "Linux"}), 1)
+ self.assertEqual(self.gh_output.read_text(encoding="utf-8"),
+ "earlier=1\n")
+
+
+if __name__ == "__main__":
+ unittest.main()