summaryrefslogtreecommitdiff
path: root/.github/scripts/tests
diff options
context:
space:
mode:
authorDave Hibberd <hibby@debian.org>2026-10-20 22:35:06 +0100
committerDave Hibberd <hibby@debian.org>2026-10-20 22:35:06 +0100
commit82ebb1ed1af30cee4dfbb1c628431d32885a00e0 (patch)
tree1a1f782d3e576b758be0bc61171574a7cd8f2376 /.github/scripts/tests
parent061658210acb6425517733ea012dda803a7f72a1 (diff)
parent61d684922b0f1c8455cc60eb3d123df058c9e1f5 (diff)
Merge tag 'debian/3.3.0_beta2+dfsg-1' into hibbian/trixie-backports
tagging wsjtx 3.3.0~beta2+dfsg-1
Diffstat (limited to '.github/scripts/tests')
-rw-r--r--.github/scripts/tests/test_armhf_cross_configuration.py59
-rw-r--r--.github/scripts/tests/test_armhf_sysroot_symlinks.py2
-rw-r--r--.github/scripts/tests/test_beta_scheduler.py1368
-rw-r--r--.github/scripts/tests/test_check_candidate_tag.py2
-rw-r--r--.github/scripts/tests/test_generate_change_list.py263
-rwxr-xr-x.github/scripts/tests/test_ghcr_retention.py11
-rw-r--r--.github/scripts/tests/test_linux_ccache_policy.py189
-rw-r--r--.github/scripts/tests/test_linux_image_publication_policy.py252
-rw-r--r--.github/scripts/tests/test_native_cache_policy.py86
-rw-r--r--.github/scripts/tests/test_package_cli_tools.py745
-rw-r--r--.github/scripts/tests/test_release_linux_images.py158
-rw-r--r--.github/scripts/tests/test_release_policy.py1156
-rw-r--r--.github/scripts/tests/test_release_workflow_policy.py202
13 files changed, 4419 insertions, 74 deletions
diff --git a/.github/scripts/tests/test_armhf_cross_configuration.py b/.github/scripts/tests/test_armhf_cross_configuration.py
index 0893e99a..5bf78800 100644
--- a/.github/scripts/tests/test_armhf_cross_configuration.py
+++ b/.github/scripts/tests/test_armhf_cross_configuration.py
@@ -30,7 +30,7 @@ class ArmhfCrossConfigurationTests(unittest.TestCase):
self.assertIn(setting, config)
self.assertNotIn("CT_CC_GCC_LIBQUADMATH=y", config)
- image_config = self.read(".github/scripts/armhf-ci-image-config.sh")
+ image_config = self.read(".github/scripts/armhf-toolchain-config.sh")
self.assertIn("ARMHF_GCC_VERSION=13.4.0", image_config)
self.assertIn("ARMHF_GLIBC_VERSION=2.36", image_config)
self.assertIn("ARMHF_TARGET_TRIPLET=arm-linux-gnueabihf", image_config)
@@ -42,6 +42,44 @@ class ArmhfCrossConfigurationTests(unittest.TestCase):
self.assertIn("reject_private_glibc_dependency", verifier)
self.assertIn("private glibc symbol", audit)
+ def test_toolchain_stage_is_independent_of_image_refresh_inputs(self):
+ builder = self.read(".github/images/linux-ci/Dockerfile.armhf-cross")
+ toolchain, image = builder.split("FROM debian:bookworm AS cross_builder", 1)
+ self.assertRegex(
+ toolchain.splitlines()[0],
+ r"^FROM debian:bookworm@sha256:[0-9a-f]{64} AS toolchain$",
+ )
+ for unrelated_input in (
+ "IMAGE_REFRESH_EPOCH",
+ "IMAGE_RECIPE_SHA256",
+ "IMAGE_GENERATION",
+ "armhf-ci-image-config.sh",
+ "linux-ci-image-config.sh",
+ "build-hamlib-armhf-cross.sh",
+ ):
+ self.assertNotIn(unrelated_input, toolchain)
+ self.assertLess(
+ toolchain.index('test -n "$ARMHF_TOOLCHAIN_REBUILD_REVISION"'),
+ toolchain.index("run-apt-get update"),
+ )
+ self.assertIn("armhf-cross-toolchain.config", toolchain)
+ self.assertNotIn("target=/tmp/wsjtx-ctng-build", toolchain)
+ self.assertIn('mkdir "$build_dir"', toolchain)
+ self.assertIn('rm -rf "$build_dir"', toolchain)
+ self.assertIn(
+ "COPY --from=toolchain /opt/wsjtx/armhf-toolchain "
+ "/opt/wsjtx/armhf-toolchain", image,
+ )
+ self.assertIn("IMAGE_REFRESH_EPOCH", image)
+ self.assertIn("IMAGE_RECIPE_SHA256", image)
+
+ def test_shared_toolchain_config_is_copied_to_both_image_roles(self):
+ config = self.read(".github/scripts/armhf-ci-image-config.sh")
+ self.assertIn('. "$_armhf_config_dir/armhf-toolchain-config.sh"', config)
+ for role in ("cross", "runtime"):
+ dockerfile = self.read(f".github/images/linux-ci/Dockerfile.armhf-{role}")
+ self.assertIn(".github/scripts/armhf-toolchain-config.sh", dockerfile)
+
def test_armhf_cache_identity_parsing_fails_closed(self):
workflow = self.read(".github/workflows/build-linux.yml")
self.assertIn(
@@ -84,7 +122,7 @@ class ArmhfCrossConfigurationTests(unittest.TestCase):
def test_builder_and_runtime_keep_distinct_native_architectures(self):
builder = self.read(".github/images/linux-ci/Dockerfile.armhf-cross")
runtime = self.read(".github/images/linux-ci/Dockerfile.armhf-runtime")
- self.assertTrue(builder.startswith("FROM debian:bookworm\n"))
+ self.assertIn("FROM debian:bookworm AS cross_builder\n", builder)
self.assertIn("--architectures=armhf", builder)
self.assertIn("qemu-user-static", builder)
self.assertIn("normalize-armhf-sysroot-symlinks.sh", builder)
@@ -108,12 +146,19 @@ class ArmhfCrossConfigurationTests(unittest.TestCase):
self.assertIn("cpack -G RPM", runtime_package)
self.assertIn("CPACK_INSTALL_CMAKE_PROJECTS=", runtime_package)
self.assertIn("CPACK_INSTALLED_DIRECTORIES=/work/AppDir;/", runtime_package)
- self.assertIn('"$ARMHF_QEMU_EXECUTABLE"', runtime_package)
- self.assertIn(
- 'LINUX_APPIMAGE_RUNNER="$ARMHF_QEMU_EXECUTABLE"', runtime_package
- )
+ self.assertNotIn("qemu", runtime_package.lower())
+ self.assertNotIn("LINUX_APPIMAGE_RUNNER", runtime_package)
+ self.assertIn(" ./linuxdeploy.AppImage --appimage-extract-and-run \\\n", runtime_package)
+ self.assertIn('./"$OUTPUT" --appimage-extract >/dev/null', runtime_package)
+ self.assertIn("-o linuxdeploy-plugin-qt.AppImage", runtime_package)
self.assertIn("armhf-static-ldd.sh", runtime_package)
self.assertIn('PATH="/work/wsjtx-build/appimage-tools:$PATH"', runtime_package)
+ packaging = runtime_package[runtime_package.index("Package release tarballs"):]
+ self.assertLess(runtime_package.index("--output appimage"), runtime_package.index("package-cli-tools.sh"))
+ self.assertIn('PATH="/work/wsjtx-build/appimage-tools:$PATH" .github/scripts/package-cli-tools.sh', packaging)
+ self.assertIn("--linuxdeploy /work/linuxdeploy.AppImage", packaging)
+ self.assertIn(".github/scripts/smoke-release-tarballs.sh", packaging)
+ self.assertNotIn("--ldd", packaging)
def test_hybrid_is_the_only_armhf_build_implementation(self):
workflow = self.read(".github/workflows/build-linux.yml")
@@ -169,7 +214,7 @@ class ArmhfCrossConfigurationTests(unittest.TestCase):
properties = q65.split(
"set_tests_properties (test_q65_decode_pipeline", 1
)[1].split(")", 1)[0]
- self.assertIn("TIMEOUT 180", properties)
+ self.assertIn("TIMEOUT 360", properties)
if __name__ == "__main__":
diff --git a/.github/scripts/tests/test_armhf_sysroot_symlinks.py b/.github/scripts/tests/test_armhf_sysroot_symlinks.py
index 991971f6..42647345 100644
--- a/.github/scripts/tests/test_armhf_sysroot_symlinks.py
+++ b/.github/scripts/tests/test_armhf_sysroot_symlinks.py
@@ -23,7 +23,7 @@ class ArmhfSysrootSymlinkTests(unittest.TestCase):
subprocess.run(["bash", str(NORMALIZER), str(sysroot)], check=True)
self.assertFalse(os.readlink(link).startswith("/"))
- self.assertEqual(link.resolve(), target)
+ self.assertEqual(link.resolve(), target.resolve())
def test_relative_links_remain_unchanged(self):
with tempfile.TemporaryDirectory() as temporary:
diff --git a/.github/scripts/tests/test_beta_scheduler.py b/.github/scripts/tests/test_beta_scheduler.py
new file mode 100644
index 00000000..47f74d60
--- /dev/null
+++ b/.github/scripts/tests/test_beta_scheduler.py
@@ -0,0 +1,1368 @@
+#!/usr/bin/env python3
+"""Scheduled beta state machine, continuation, alerts, git mechanics and workflow wiring."""
+import importlib.util
+import io
+import itertools
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import subprocess
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest.mock import patch
+import urllib.error
+import urllib.parse
+import zipfile
+
+ROOT = Path(__file__).resolve().parents[3]
+SPEC = importlib.util.spec_from_file_location("beta_scheduler", Path(__file__).parents[1] / "beta-scheduler.py")
+beta = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(beta)
+
+BOT = "wsjtx-release-bot[bot]"
+BOT_EMAIL = f"41+{BOT}@users.noreply.github.com"
+MAINTAINER = "maintainer@example.invalid"
+LINE = "release/3.3"
+TIP = "1" * 40
+OLD_LINE_TIP = "2" * 40
+DEVELOP = "d" * 40
+GREEN = "e" * 40
+CUT = "c" * 40
+RECIPES = {key: str(index) * 64 for index, key in enumerate(beta.images.IMAGES, start=3)}
+DRIFTED = {key: "f" * 64 for key in beta.images.IMAGES}
+STATE = beta.STATE_FILE
+LOCK = beta.LOCK_FILE
+RUN_IDS = itertools.count(1000)
+
+
+def state(channel="BETA", number=2, version="3.3.0"):
+ lines = [f"version={version}", f"channel={channel}", f"prerelease={number if channel in ('BETA', 'RC') else ''}",
+ "revision=$Format:%H$"]
+ if channel == "BETA":
+ lines.append("windows_signing=unsigned")
+ return ("\n".join(lines) + "\n").encode()
+
+
+OLD_CONTRACT = b"version=3.2.0\nchannel=RC\nrc=1\nrevision=$Format:%H$\nwindows_signing=unsigned\n"
+
+
+def lock(recipes=RECIPES, generation="validated-build-20260929-600-1"):
+ return (json.dumps({"schema": 1, "generation": generation, "images": {
+ key: {"reference": f"{beta.images.PUBLIC}/{spec[0]}@sha256:{'a' * 64}", "recipe_sha256": recipes[key]}
+ for key, spec in beta.images.IMAGES.items()
+ }}, indent=2) + "\n").encode()
+
+
+def run(workflow, *, status="completed", conclusion="success", sha=TIP, branch=LINE, event="push", title=None,
+ created="2026-10-06T18:00:00Z", actor=BOT, triggering_actor=None, run_id=None):
+ run_id = next(RUN_IDS) if run_id is None else run_id
+ return {
+ "id": run_id, "path": f".github/workflows/{workflow}", "status": status,
+ "conclusion": conclusion if status == "completed" else None, "head_sha": sha, "head_branch": branch,
+ "event": event, "display_title": title or workflow, "created_at": created,
+ "actor": {"login": actor, "type": "Bot" if actor.endswith("[bot]") else "User"},
+ "triggering_actor": {"login": triggering_actor or actor},
+ "html_url": f"https://example.invalid/runs/{run_id}",
+ }
+
+
+def candidate(version="3.3.0-beta2", operation="create", **fields):
+ fields.setdefault("event", "workflow_dispatch")
+ return run(beta.CANDIDATE, title=f"Prepare Release Candidate build/v{version} ({operation})", **fields)
+
+
+def preparation(generation, **fields):
+ fields.setdefault("event", "workflow_dispatch")
+ fields.setdefault("branch", "develop")
+ fields.setdefault("sha", DEVELOP)
+ return run(beta.PREPARATION, title=f"Prepare Release Dependencies develop {generation}", **fields)
+
+
+class FakeRepository:
+ def __init__(self):
+ self.heads = {}
+ self.files = {}
+ self.tags = {}
+ self.ancestors = set()
+ self.absent = set()
+ self.missing = []
+ self.recipes = {}
+ self.conflicts = []
+ self.validation_error = None
+ self.push_error = None
+ self.merge = None
+ self.written = None
+ self.committed = None
+ self.pushed = []
+ self.discarded = []
+ self.synced = []
+
+ def sync(self, *, shallow=False):
+ self.synced.append(shallow)
+
+ def release_heads(self):
+ return dict(self.heads)
+
+ def develop(self):
+ return DEVELOP
+
+ def tag(self, name):
+ return self.tags.get(name)
+
+ def read(self, commit, path):
+ return self.files.get((commit, path))
+
+ def contains(self, commit):
+ return commit not in self.absent
+
+ def is_ancestor(self, ancestor, descendant):
+ return ancestor == descendant or (ancestor, descendant) in self.ancestors
+
+ def commits_missing_from_develop(self, tip):
+ return list(self.missing)
+
+ def fingerprints(self, commit):
+ return self.recipes.get(commit)
+
+ def start_merge(self, tip, commit, name, email):
+ self.merge = (tip, commit)
+ return Path("merge-worktree"), list(self.conflicts)
+
+ def write(self, worktree, files):
+ self.written = dict(files)
+
+ def validate_lock(self, worktree):
+ if self.validation_error:
+ raise RuntimeError(self.validation_error)
+
+ def commit(self, worktree, name, email, message):
+ self.committed = (name, email, message)
+ return CUT
+
+ def push(self, commit, branch):
+ if self.push_error:
+ raise RuntimeError(self.push_error)
+ self.pushed.append((commit, branch))
+
+ def discard(self, worktree):
+ self.discarded.append(worktree)
+
+
+class FakeGitHub:
+ def __init__(self):
+ self.workflow_runs = {}
+ self.queries = []
+ self.dispatches = []
+ self.published = set()
+ self.artifacts = {}
+ self.job_lists = {}
+
+ def add(self, *runs):
+ for item in runs:
+ self.workflow_runs.setdefault(Path(item["path"]).name, []).append(item)
+
+ def runs(self, workflow, **filters):
+ self.queries.append(workflow)
+ selected = []
+ for item in self.workflow_runs.get(workflow, []):
+ if "branch" in filters and item["head_branch"] != filters["branch"]:
+ continue
+ if "event" in filters and item["event"] != filters["event"]:
+ continue
+ if "head_sha" in filters and item["head_sha"] != filters["head_sha"]:
+ continue
+ if "status" in filters and filters["status"] not in (item["status"], item["conclusion"]):
+ continue
+ selected.append(item)
+ return selected
+
+ def jobs(self, run_id):
+ return self.job_lists.get(run_id, [])
+
+ def dispatch(self, workflow, ref, inputs):
+ self.dispatches.append((workflow, ref, inputs))
+
+ def release_published(self, tag):
+ return tag in self.published
+
+ def artifact_file(self, run_id, name, member):
+ return self.artifacts.get(run_id) if (name, member) == (beta.PREPARED_ARTIFACT, LOCK) else None
+
+
+class FakePackages:
+ def __init__(self):
+ self.tags = {package: set() for package in beta.IMAGE_PACKAGES}
+ self.calls = []
+
+ def list_versions(self, owner, package):
+ self.calls.append((owner, package))
+ return [SimpleNamespace(tags=tuple(sorted(self.tags[package]))), SimpleNamespace(tags=("stable",))]
+
+
+class SchedulerTestCase(unittest.TestCase):
+ """A published beta2 on release/3.3; develop moved to a green commit with unchanged recipes."""
+
+ def setUp(self):
+ self.build()
+
+ def build(self):
+ self.repo = FakeRepository()
+ self.internal = FakeGitHub()
+ self.public = FakeGitHub()
+ self.packages = FakePackages()
+ self.repo.heads = {"release/3.2": OLD_LINE_TIP, LINE: TIP}
+ self.repo.files[(OLD_LINE_TIP, STATE)] = OLD_CONTRACT
+ self.repo.files[(TIP, STATE)] = state(number=2)
+ self.repo.files[(TIP, LOCK)] = lock()
+ self.repo.tags["build/v3.3.0-beta2"] = TIP
+ self.public.published.add("v3.3.0-beta2")
+ self.repo.ancestors.add((GREEN, DEVELOP))
+ self.repo.recipes[GREEN] = dict(RECIPES)
+ self.repo.recipes[DEVELOP] = dict(RECIPES)
+ self.repo.missing = [
+ beta.Commit(TIP, BOT_EMAIL, ("CMakeLists.txt", STATE)),
+ beta.Commit("3" * 40, MAINTAINER, (LOCK, STATE)),
+ ]
+ self.internal.add(run(beta.CI, sha=GREEN, branch="develop", created="2026-10-06T10:00:00Z", actor="k1jt"))
+
+ def cut(self):
+ return beta.Scheduler(self.repo, self.internal, self.public, self.packages,
+ bot_login=BOT, bot_email=BOT_EMAIL).cut()
+
+ def stop(self):
+ with self.assertRaises(beta.Stop) as raised:
+ self.cut()
+ return raised.exception
+
+ def assertNothingDone(self):
+ self.assertEqual(self.internal.dispatches, [])
+ self.assertEqual(self.repo.pushed, [])
+
+
+class BetaLineTest(SchedulerTestCase):
+ def test_no_beta_line_between_a_freeze_and_the_next_line_is_a_quiet_skip(self):
+ self.repo.files[(TIP, STATE)] = state("RC", 1)
+ with self.assertRaisesRegex(beta.Skip, "No release/X.Y branch is in BETA state"):
+ self.cut()
+ self.assertNothingDone()
+
+ def test_lines_without_state_with_the_old_contract_or_another_name_are_not_beta(self):
+ self.repo.heads.update({"release/3.0": "5" * 40, "release/3.4-hotfix": "6" * 40})
+ self.repo.files[("6" * 40, STATE)] = state(version="3.4.0", number=1)
+ self.cut()
+ self.assertEqual(self.repo.pushed, [(CUT, LINE)])
+
+ def test_several_beta_lines_stop(self):
+ self.repo.heads["release/3.4"] = "6" * 40
+ self.repo.files[("6" * 40, STATE)] = state(version="3.4.0", number=1)
+ stop = self.stop()
+ self.assertEqual(stop.stage, "line")
+ self.assertIn("release/3.3, release/3.4", str(stop))
+ self.assertNothingDone()
+
+ def test_an_invalid_beta_state_stops_instead_of_reading_as_no_line(self):
+ self.repo.files[(TIP, STATE)] = b"version=3.3.0\nchannel=BETA\nprerelease=2\nrevision=$Format:%H$\n"
+ stop = self.stop()
+ self.assertEqual(stop.stage, "line")
+ self.assertIn(f"{LINE}'s {STATE} says channel=BETA but does not validate", str(stop))
+ self.assertNothingDone()
+
+ def test_beta_state_for_another_line_stops(self):
+ self.repo.files[(TIP, STATE)] = state(version="3.4.0")
+ self.assertEqual(self.stop().stage, "line")
+ self.assertNothingDone()
+
+
+class RetryCutTest(SchedulerTestCase):
+ def setUp(self):
+ super().setUp()
+ del self.repo.tags["build/v3.3.0-beta2"]
+ self.public.published.clear()
+
+ def expected_candidate(self, version="3.3.0-beta2"):
+ return [(beta.CANDIDATE, LINE, {"version": version, "expected_sha": TIP, "operation": "create"})]
+
+ def test_new_line_first_run_cuts_beta1_at_its_tip_without_a_merge(self):
+ self.repo.files[(TIP, STATE)] = state(number=1)
+ self.repo.missing = [beta.Commit(TIP, MAINTAINER, (LOCK, STATE))]
+ self.repo.ancestors.add((GREEN, TIP))
+ self.internal.add(run(beta.CI, sha=TIP, actor="k1jt"))
+ self.cut()
+ self.assertEqual(self.internal.dispatches, self.expected_candidate("3.3.0-beta1"))
+ self.assertIsNone(self.repo.merge)
+ self.assertEqual(self.repo.pushed, [])
+
+ def test_retry_waits_while_the_tip_ci_runs(self):
+ self.internal.add(run(beta.CI, sha=TIP, conclusion="failure"), run(beta.CI, sha=TIP, status="in_progress"))
+ with self.assertRaisesRegex(beta.Skip, "still running"):
+ self.cut()
+ self.assertNothingDone()
+
+ def test_failed_tip_ci_recuts_the_same_number_from_newer_green_develop(self):
+ self.internal.add(run(beta.CI, sha=TIP),
+ run(beta.CI, sha=TIP, conclusion="failure", created="2026-10-06T19:00:00Z"))
+ message = self.cut()
+ self.assertEqual(self.repo.merge, (TIP, GREEN))
+ self.assertEqual(self.repo.written, {STATE: beta.render_state("3.3.0", 2).encode(), LOCK: lock()})
+ self.assertEqual(self.repo.committed[:2], (BOT, BOT_EMAIL))
+ self.assertTrue(self.repo.committed[2].startswith("Cut 3.3.0-beta2 from develop\n\n"))
+ self.assertEqual(self.repo.pushed, [(CUT, LINE)])
+ self.assertEqual(self.internal.dispatches, [])
+ self.assertIn("3.3.0-beta2", message)
+
+ def test_failed_tip_ci_without_newer_green_develop_stops(self):
+ failed = run(beta.CI, sha=TIP, conclusion="failure", created="2026-10-06T19:00:00Z")
+ for name, setup in (
+ ("develop already merged", lambda: self.repo.ancestors.add((GREEN, TIP))),
+ ("no green develop", lambda: self.internal.workflow_runs.update({beta.CI: []})),
+ ):
+ with self.subTest(name=name):
+ self.setUp()
+ setup()
+ self.internal.add(run(beta.CI, sha=TIP), failed)
+ stop = self.stop()
+ self.assertEqual((stop.stage, stop.link), ("ci", failed["html_url"]))
+ self.assertIsNone(self.repo.merge)
+ self.assertNothingDone()
+
+ def test_recut_after_failed_tip_ci_follows_the_lock_and_conflict_rules(self):
+ self.internal.add(run(beta.CI, sha=TIP, conclusion="cancelled"))
+ self.repo.recipes[GREEN] = dict(DRIFTED)
+ self.repo.recipes[DEVELOP] = dict(DRIFTED)
+ self.repo.recipes["a5" * 20] = dict(DRIFTED)
+ self.internal.add(run(beta.WARMER, sha="a5" * 20, branch="develop", actor="k1jt", run_id=713))
+ for package in beta.IMAGE_PACKAGES:
+ self.packages.tags[package].add("validated-build-20261001-713-1")
+ with self.assertRaisesRegex(beta.Skip, "Dispatched Prepare Release Dependencies"):
+ self.cut()
+ self.assertEqual([workflow for workflow, _ref, _inputs in self.internal.dispatches], [beta.PREPARATION])
+ self.assertEqual(self.repo.pushed, [])
+ self.setUp()
+ self.internal.add(run(beta.CI, sha=TIP, conclusion="failure"))
+ self.repo.conflicts = ["CMakeLists.txt"]
+ self.assertEqual(self.stop().stage, "merge")
+ self.assertNothingDone()
+
+ def test_retry_stops_without_a_tip_ci_run(self):
+ self.assertEqual(self.stop().stage, "ci")
+ self.assertNothingDone()
+
+ def test_a_running_tip_ci_or_candidate_a_person_started_alerts_because_nothing_resumes_the_cut(self):
+ for stage, runs in (
+ ("ci", lambda: [run(beta.CI, sha=TIP, status="in_progress", actor="k1jt")]),
+ ("candidate", lambda: [run(beta.CI, sha=TIP), candidate(status="queued", actor="k1jt")]),
+ ):
+ with self.subTest(stage=stage):
+ self.setUp()
+ added = runs()
+ self.internal.add(*added)
+ stop = self.stop()
+ self.assertEqual((stop.stage, stop.link), (stage, added[-1]["html_url"]))
+ self.assertIn("dispatch Scheduled Beta Cut after it does", str(stop))
+ self.assertNothingDone()
+
+ def test_retry_waits_for_a_running_candidate(self):
+ self.internal.add(run(beta.CI, sha=TIP), candidate(status="queued"))
+ with self.assertRaisesRegex(beta.Skip, "candidate"):
+ self.cut()
+ self.assertNothingDone()
+
+ def test_failed_candidate_is_retried_with_the_same_number(self):
+ self.internal.add(
+ run(beta.CI, sha=TIP),
+ candidate(conclusion="failure"),
+ candidate(operation="validate", status="in_progress", actor="k1jt"),
+ candidate("3.3.0-beta1", status="in_progress"),
+ )
+ self.cut()
+ self.assertEqual(self.internal.dispatches, self.expected_candidate())
+
+ def test_retry_stops_on_a_fix_committed_only_to_the_release_branch(self):
+ self.internal.add(run(beta.CI, sha=TIP))
+ self.repo.missing.append(beta.Commit("4" * 40, MAINTAINER, ("main.cpp",)))
+ stop = self.stop()
+ self.assertEqual(stop.stage, "fixes")
+ self.assertIn("4" * 40, str(stop))
+ self.assertNothingDone()
+
+
+class UnpublishedBetaTest(SchedulerTestCase):
+ def setUp(self):
+ super().setUp()
+ self.public.published.clear()
+ self.ci = run(beta.CI, sha=TIP)
+ self.candidate = candidate()
+ self.promotion = run(beta.PROMOTION, event="workflow_dispatch")
+ self.publication = run(beta.PUBLICATION, branch="v3.3.0-beta2", actor="KJ5HST")
+
+ def test_unpublished_beta_waits_quietly_while_any_of_its_runs_is_in_progress(self):
+ for stage, running in (
+ ("CI", lambda: run(beta.CI, status="waiting")),
+ ("candidate", lambda: candidate(status="waiting")),
+ ("promotion", lambda: run(beta.PROMOTION, event="workflow_dispatch", status="waiting")),
+ ("public release", lambda: run(beta.PUBLICATION, branch="v3.3.0-beta2", status="waiting")),
+ ):
+ with self.subTest(stage=stage):
+ self.setUp()
+ self.internal.add(self.ci, self.candidate)
+ target = self.public if stage == "public release" else self.internal
+ target.add(running())
+ with self.assertRaisesRegex(beta.Skip, f"its {stage} run is still in progress"):
+ self.cut()
+ self.assertNothingDone()
+
+ def test_unpublished_beta_alerts_on_a_running_run_a_person_started_but_waits_for_the_public_release(self):
+ for stage, running, alerts in (
+ ("ci", lambda: run(beta.CI, status="in_progress", actor="k1jt"), True),
+ ("candidate", lambda: candidate(status="in_progress", actor="k1jt"), True),
+ ("promotion", lambda: run(beta.PROMOTION, event="workflow_dispatch", status="in_progress", actor="k1jt"),
+ True),
+ ("public release", lambda: run(beta.PUBLICATION, branch="v3.3.0-beta2", status="in_progress",
+ actor="KJ5HST"), False),
+ ):
+ with self.subTest(stage=stage):
+ self.setUp()
+ self.internal.add(self.ci, self.candidate)
+ added = running()
+ (self.public if stage == "public release" else self.internal).add(added)
+ if alerts:
+ stop = self.stop()
+ self.assertEqual((stop.stage, stop.link), (stage, added["html_url"]))
+ else:
+ with self.assertRaisesRegex(beta.Skip, "public release run is still in progress"):
+ self.cut()
+ self.assertNothingDone()
+
+ def test_candidate_failed_after_its_tag_spends_the_number_and_cuts_the_next_from_green_develop(self):
+ self.internal.add(self.ci, candidate(conclusion="failure"))
+ scheduler = beta.Scheduler(self.repo, self.internal, self.public, self.packages,
+ bot_login=BOT, bot_email=BOT_EMAIL)
+ scheduler.cut()
+ self.assertEqual(self.repo.merge, (TIP, GREEN))
+ self.assertEqual(self.repo.written[STATE], beta.render_state("3.3.0", 3).encode())
+ self.assertTrue(self.repo.committed[2].startswith("Cut 3.3.0-beta3 from develop\n\n"))
+ self.assertEqual(self.repo.pushed, [(CUT, LINE)])
+ self.assertTrue(any("3.3.0-beta2 is spent" in note for note in scheduler.notes))
+
+ def test_spent_number_without_newer_green_develop_alerts_with_the_failed_run(self):
+ failed = candidate(conclusion="failure")
+ self.internal.add(self.ci, failed)
+ self.repo.ancestors.add((GREEN, TIP))
+ stop = self.stop()
+ self.assertEqual((stop.stage, stop.link), ("candidate", failed["html_url"]))
+ self.assertIn("3.3.0-beta2 is spent", str(stop))
+ self.assertIn("3.3.0-beta3", str(stop))
+ self.assertNothingDone()
+
+ def test_a_successful_candidate_at_the_tag_outweighs_a_newer_failed_duplicate(self):
+ self.internal.add(self.ci, self.candidate,
+ candidate(conclusion="failure", created="2026-10-06T19:00:00Z"))
+ stop = self.stop()
+ self.assertEqual((stop.stage, stop.link), ("promotion", self.candidate["html_url"]))
+ self.assertNothingDone()
+
+ def test_a_promoted_beta_is_never_spent_even_if_its_candidate_run_now_reads_failed(self):
+ failed_publication = run(beta.PUBLICATION, branch="v3.3.0-beta2", conclusion="failure")
+ self.internal.add(self.ci, candidate(conclusion="failure"), self.promotion)
+ self.public.add(failed_publication)
+ stop = self.stop()
+ self.assertEqual((stop.stage, stop.link), ("publication", failed_publication["html_url"]))
+ self.assertNothingDone()
+
+ def test_candidate_and_promotion_runs_of_other_commits_do_not_count(self):
+ elsewhere = {"sha": GREEN}
+ for name, runs, stage in (
+ ("successful candidate elsewhere", (candidate(conclusion="failure"), candidate(**elsewhere)), None),
+ ("running candidate elsewhere", (candidate(conclusion="failure"), candidate(status="queued", **elsewhere)),
+ None),
+ ("promotion elsewhere", (self.candidate, run(beta.PROMOTION, event="workflow_dispatch", **elsewhere)),
+ "promotion"),
+ ):
+ with self.subTest(name=name):
+ self.build()
+ self.public.published.clear()
+ self.internal.add(self.ci, *runs)
+ if stage is None:
+ self.cut()
+ self.assertEqual(self.repo.written[STATE], beta.render_state("3.3.0", 3).encode())
+ else:
+ stop = self.stop()
+ self.assertEqual((stop.stage, stop.link), (stage, self.candidate["html_url"]))
+ self.assertNothingDone()
+
+ def test_unpublished_beta_alerts_at_its_first_missing_or_failed_stage(self):
+ failed_promotion = run(beta.PROMOTION, event="workflow_dispatch", conclusion="failure")
+ failed_publication = run(beta.PUBLICATION, branch="v3.3.0-beta2", conclusion="failure")
+ promoted = (self.ci, self.candidate, self.promotion)
+ for internal, public, stage, link in (
+ ((self.ci,), (), "candidate", None),
+ ((self.ci, self.candidate), (), "promotion", self.candidate["html_url"]),
+ ((self.ci, self.candidate, failed_promotion), (), "promotion", failed_promotion["html_url"]),
+ (promoted, (), "publication", self.promotion["html_url"]),
+ (promoted, (failed_publication,), "publication", failed_publication["html_url"]),
+ (promoted, (self.publication,), "publication", self.publication["html_url"]),
+ ):
+ with self.subTest(stage=stage, link=link):
+ self.build()
+ self.public.published.clear()
+ self.internal.add(*internal)
+ self.public.add(*public)
+ stop = self.stop()
+ self.assertEqual((stop.stage, stop.link), (stage, link))
+ self.assertNothingDone()
+
+
+class NextCutTest(SchedulerTestCase):
+ def test_published_beta_merges_the_newest_green_develop_as_the_next_number(self):
+ self.internal.add(
+ run(beta.CI, sha="9" * 40, branch="develop", conclusion="failure", created="2026-10-06T11:00:00Z"),
+ run(beta.CI, sha="8" * 40, branch="develop", created="2026-10-05T11:00:00Z"),
+ run(beta.CI, sha="7" * 40, branch="topic", created="2026-10-06T12:00:00Z"),
+ )
+ self.repo.ancestors.update({("9" * 40, DEVELOP), ("8" * 40, DEVELOP), ("7" * 40, DEVELOP)})
+ message = self.cut()
+ self.assertEqual(self.repo.merge, (TIP, GREEN))
+ self.assertEqual(self.repo.written, {STATE: beta.render_state("3.3.0", 3).encode(), LOCK: lock()})
+ name, email, commit_message = self.repo.committed
+ self.assertEqual((name, email), (BOT, BOT_EMAIL))
+ self.assertTrue(commit_message.startswith("Cut 3.3.0-beta3 from develop\n\n"))
+ self.assertIn(GREEN, commit_message)
+ self.assertTrue(all(len(line) <= 72 for line in commit_message.splitlines()))
+ self.assertEqual(self.repo.pushed, [(CUT, LINE)])
+ self.assertEqual(self.repo.discarded, [Path("merge-worktree")])
+ self.assertEqual(self.internal.dispatches, [])
+ self.assertIn(CUT, message)
+
+ def test_cut_fetches_develop_and_the_release_branches_in_full(self):
+ self.cut()
+ self.assertEqual(self.repo.synced, [False])
+
+ def test_green_runs_for_commits_not_on_develop_or_not_fetched_are_passed_over(self):
+ not_on_develop, not_fetched = "9" * 40, "8" * 40
+ self.internal.add(
+ run(beta.CI, sha=not_on_develop, branch="develop", created="2026-10-06T12:00:00Z"),
+ run(beta.CI, sha=not_fetched, branch="develop", created="2026-10-06T11:00:00Z"),
+ )
+ self.repo.ancestors.add((not_fetched, DEVELOP))
+ self.repo.absent.add(not_fetched)
+ self.cut()
+ self.assertEqual(self.repo.merge, (TIP, GREEN))
+
+ def test_cut_state_is_a_valid_beta_state_that_keeps_the_line_version(self):
+ self.assertEqual(beta.policy.parse_state(beta.render_state("3.3.0", 3)), {
+ "version": "3.3.0", "channel": "BETA", "prerelease": "3",
+ "revision": "$Format:%H$", "windows_signing": "unsigned",
+ })
+
+ def test_unchanged_develop_skips_without_an_alert(self):
+ self.repo.ancestors.add((GREEN, TIP))
+ with self.assertRaisesRegex(beta.Skip, "develop has not moved"):
+ self.cut()
+ self.assertNothingDone()
+
+ def test_no_green_develop_stops(self):
+ self.internal.workflow_runs[beta.CI] = [run(beta.CI, sha=GREEN, branch="develop", conclusion="failure")]
+ self.assertEqual(self.stop().stage, "develop")
+ self.assertNothingDone()
+
+
+class FixesOnDevelopTest(SchedulerTestCase):
+ def test_bot_merges_and_metadata_only_commits_are_not_fixes(self):
+ self.repo.missing += [beta.Commit("7" * 40, MAINTAINER, (LOCK,)), beta.Commit("8" * 40, MAINTAINER, ())]
+ self.cut()
+ self.assertEqual(self.repo.pushed, [(CUT, LINE)])
+
+ def test_release_branch_commits_missing_from_develop_stop_the_cut(self):
+ for files, email in (
+ (("main.cpp",), MAINTAINER),
+ (("main.cpp", STATE), MAINTAINER),
+ (("CMakeLists.txt", STATE, LOCK), "someone-else@example.invalid"),
+ ):
+ with self.subTest(files=files, email=email):
+ self.build()
+ self.repo.missing.append(beta.Commit("4" * 40, email, files))
+ stop = self.stop()
+ self.assertEqual(stop.stage, "fixes")
+ self.assertIn("4" * 40, str(stop))
+ self.assertNothingDone()
+
+
+class ImageLockTest(SchedulerTestCase):
+ def setUp(self):
+ super().setUp()
+ self.repo.recipes[GREEN] = dict(DRIFTED)
+ self.repo.recipes[DEVELOP] = dict(DRIFTED)
+
+ def publish_generation(self, run_id, sha, recipes, *, created="2026-10-01T00:00:00Z", attempt=1,
+ packages=beta.IMAGE_PACKAGES, status="completed"):
+ generation = f"validated-build-20261001-{run_id}-{attempt}"
+ for package in packages:
+ self.packages.tags[package].add(generation)
+ self.repo.recipes[sha] = dict(recipes)
+ self.internal.add(run(beta.WARMER, sha=sha, branch="develop", created=created, actor="k1jt",
+ status=status, run_id=run_id))
+ return generation
+
+ def test_unchanged_recipes_keep_the_branch_lock_without_image_lookups(self):
+ self.repo.recipes[GREEN] = dict(RECIPES)
+ self.cut()
+ self.assertEqual(self.repo.written[LOCK], lock())
+ self.assertEqual(self.packages.calls, [])
+ self.assertNotIn(beta.WARMER, self.internal.queries)
+ self.assertNotIn(beta.PREPARATION, self.internal.queries)
+
+ def test_recipe_drift_prepares_the_newest_generation_built_for_those_recipes(self):
+ self.publish_generation(702, "a2" * 20, DRIFTED, created="2026-10-01T00:00:00Z")
+ newest = self.publish_generation(703, "a3" * 20, DRIFTED, created="2026-10-03T00:00:00Z")
+ rerun = newest.removesuffix("-1") + "-2"
+ for package in beta.IMAGE_PACKAGES:
+ self.packages.tags[package].add(rerun)
+ self.publish_generation(704, "a4" * 20, RECIPES, created="2026-10-04T00:00:00Z")
+ self.internal.add(preparation("validated-build-20261001-702-1", status="in_progress"))
+ with self.assertRaisesRegex(beta.Skip, "Dispatched Prepare Release Dependencies"):
+ self.cut()
+ self.assertEqual(self.internal.dispatches, [
+ (beta.PREPARATION, "develop", {"source_branch": "develop", "generation": rerun}),
+ ])
+ self.assertEqual(self.repo.pushed, [])
+
+ def assertRefreshAlert(self, refresh):
+ stop = self.stop()
+ self.assertEqual((stop.stage, stop.link), ("lock", refresh["html_url"]))
+ self.assertIn("still being refreshed", str(stop))
+ self.assertIn("dispatch Scheduled Beta Cut after it does", str(stop))
+ self.assertNothingDone()
+
+ def test_recipe_drift_alerts_while_the_image_refresh_runs_because_nothing_resumes_the_cut(self):
+ self.publish_generation(705, "b1" * 20, RECIPES)
+ self.repo.recipes["b2" * 20] = dict(DRIFTED)
+ refresh = run(beta.WARMER, sha="b2" * 20, branch="develop", status="in_progress", actor="k1jt")
+ self.internal.add(refresh)
+ self.assertRefreshAlert(refresh)
+
+ def test_only_a_warmer_run_that_refreshes_the_images_holds_the_cut(self):
+ detect = {"name": "detect", "status": "completed", "conclusion": "success"}
+ for name, jobs, waits in (
+ ("refresh skipped", [detect, {"name": "refresh-linux-images", "status": "completed",
+ "conclusion": "skipped"}], False),
+ ("TSan image only", [detect, {"name": "refresh-linux-images / build-normal", "status": "completed",
+ "conclusion": "skipped"}], False),
+ ("normal images building", [detect, {"name": "refresh-linux-images / build-normal",
+ "status": "in_progress", "conclusion": None}], True),
+ ("built, not yet promoted", [detect, {"name": "refresh-linux-images / build-normal",
+ "status": "completed", "conclusion": "success"}], True),
+ ("refresh pending", [detect, {"name": "refresh-linux-images", "status": "queued",
+ "conclusion": None}], True),
+ ("not yet decided", [{"name": "detect", "status": "in_progress", "conclusion": None}], True),
+ ):
+ with self.subTest(name=name):
+ self.setUp()
+ self.publish_generation(720, "c1" * 20, RECIPES)
+ self.repo.recipes["c2" * 20] = dict(DRIFTED)
+ warmer = run(beta.WARMER, sha="c2" * 20, branch="develop", status="in_progress", actor="k1jt")
+ self.internal.add(warmer)
+ self.internal.job_lists[warmer["id"]] = jobs
+ if waits:
+ self.assertRefreshAlert(warmer)
+ else:
+ stop = self.stop()
+ self.assertEqual((stop.stage, stop.link), ("lock", None))
+ self.assertIn("No validated Linux image generation", str(stop))
+ self.assertNothingDone()
+
+ def test_a_generation_promoted_by_a_run_still_in_progress_is_used(self):
+ generation = self.publish_generation(722, "c4" * 20, DRIFTED, status="in_progress")
+ with self.assertRaisesRegex(beta.Skip, "Dispatched"):
+ self.cut()
+ self.assertEqual(self.internal.dispatches[0][2]["generation"], generation)
+
+ def test_generations_from_a_direct_image_publication_on_develop_count(self):
+ generation = "validated-build-20261002-723-1"
+ for package in beta.IMAGE_PACKAGES:
+ self.packages.tags[package].add(generation)
+ self.repo.recipes["c5" * 20] = dict(DRIFTED)
+ self.internal.add(run(beta.PUBLISHER, sha="c5" * 20, branch="develop", event="workflow_dispatch",
+ actor="dchristle", run_id=723))
+ with self.assertRaisesRegex(beta.Skip, "Dispatched"):
+ self.cut()
+ self.assertEqual(self.internal.dispatches[0][2]["generation"], generation)
+ self.setUp()
+ building = run(beta.PUBLISHER, sha="c5" * 20, branch="develop", event="workflow_dispatch",
+ status="in_progress", actor="dchristle")
+ self.repo.recipes["c5" * 20] = dict(DRIFTED)
+ self.internal.add(building)
+ self.internal.job_lists[building["id"]] = [{"name": "build-normal", "status": "in_progress",
+ "conclusion": None}]
+ self.assertRefreshAlert(building)
+
+ def test_generation_reruns_are_ordered_by_attempt_number(self):
+ generation = self.publish_generation(721, "c3" * 20, DRIFTED, attempt=9)
+ tenth = generation.removesuffix("-9") + "-10"
+ for package in beta.IMAGE_PACKAGES:
+ self.packages.tags[package].add(tenth)
+ with self.assertRaisesRegex(beta.Skip, "Dispatched"):
+ self.cut()
+ self.assertEqual(self.internal.dispatches[0][2]["generation"], tenth)
+
+ def test_recipe_drift_without_a_generation_or_refresh_stops(self):
+ self.publish_generation(706, "b3" * 20, RECIPES)
+ self.publish_generation(707, "b4" * 20, DRIFTED, packages=beta.IMAGE_PACKAGES[:3])
+ self.repo.recipes["b5" * 20] = dict(RECIPES)
+ self.internal.add(run(beta.WARMER, sha="b5" * 20, branch="develop", status="in_progress", actor="k1jt"))
+ self.assertEqual(self.stop().stage, "lock")
+ self.assertNothingDone()
+
+ def test_recipe_drift_waits_for_a_running_preparation(self):
+ generation = self.publish_generation(708, "b6" * 20, DRIFTED)
+ self.internal.add(preparation(generation, status="in_progress"))
+ with self.assertRaisesRegex(beta.Skip, "Prepare Release Dependencies"):
+ self.cut()
+ self.assertNothingDone()
+
+ def test_recipe_drift_commits_the_prepared_lock_in_the_cut(self):
+ generation = self.publish_generation(709, "b7" * 20, DRIFTED)
+ prepared = preparation(generation, created="2026-10-06T08:00:00Z")
+ failed_earlier = preparation(generation, created="2026-10-06T07:00:00Z", conclusion="failure")
+ self.internal.add(prepared, failed_earlier)
+ self.internal.artifacts[prepared["id"]] = lock(DRIFTED, generation)
+ self.cut()
+ self.assertEqual(self.repo.written[LOCK], lock(DRIFTED, generation))
+ self.assertIn(generation, self.repo.committed[2])
+ self.assertEqual(self.repo.pushed, [(CUT, LINE)])
+ self.assertEqual(self.internal.dispatches, [])
+
+ def test_prepared_lock_for_other_recipes_or_generation_is_prepared_again(self):
+ generation = self.publish_generation(710, "b8" * 20, DRIFTED)
+ for prepared_lock in (lock(RECIPES, generation), lock(DRIFTED, "validated-build-20261001-1-1"), None):
+ with self.subTest(prepared_lock=prepared_lock):
+ self.internal.dispatches.clear()
+ stale = preparation(generation)
+ self.internal.add(stale)
+ self.internal.artifacts[stale["id"]] = prepared_lock
+ with self.assertRaisesRegex(beta.Skip, "Dispatched"):
+ self.cut()
+ self.assertEqual(self.internal.dispatches, [
+ (beta.PREPARATION, "develop", {"source_branch": "develop", "generation": generation}),
+ ])
+
+ def test_failed_preparation_stops_with_its_run(self):
+ generation = self.publish_generation(711, "b9" * 20, DRIFTED)
+ failed = preparation(generation, conclusion="failure")
+ self.internal.add(failed)
+ stop = self.stop()
+ self.assertEqual((stop.stage, stop.link), ("lock", failed["html_url"]))
+ self.assertNothingDone()
+
+ def test_a_develop_tip_with_other_recipes_alerts_instead_of_preparing_a_lock_that_would_fail(self):
+ generation = self.publish_generation(724, "c6" * 20, DRIFTED)
+ self.repo.recipes[DEVELOP] = {key: "9" * 64 for key in beta.images.IMAGES}
+ stop = self.stop()
+ self.assertEqual(stop.stage, "lock")
+ self.assertIn(f"develop's tip {DEVELOP} has other Linux image recipes", str(stop))
+ self.assertIn(generation, str(stop))
+ self.assertNothingDone()
+
+ def test_a_running_preparation_someone_else_started_alerts(self):
+ generation = self.publish_generation(725, "c7" * 20, DRIFTED)
+ running = preparation(generation, status="in_progress", actor="dchristle")
+ self.internal.add(running)
+ stop = self.stop()
+ self.assertEqual((stop.stage, stop.link), ("lock", running["html_url"]))
+ self.assertNothingDone()
+
+ def test_missing_branch_lock_is_prepared(self):
+ self.repo.recipes[GREEN] = dict(RECIPES)
+ self.repo.recipes[DEVELOP] = dict(RECIPES)
+ del self.repo.files[(TIP, LOCK)]
+ generation = self.publish_generation(712, "ba" * 20, RECIPES)
+ with self.assertRaisesRegex(beta.Skip, "Dispatched"):
+ self.cut()
+ self.assertEqual(self.internal.dispatches[0][2]["generation"], generation)
+
+
+class MergeTest(SchedulerTestCase):
+ def test_metadata_conflicts_are_resolved_by_the_bot(self):
+ self.repo.conflicts = [STATE, LOCK]
+ self.cut()
+ self.assertEqual(self.repo.written[STATE], beta.render_state("3.3.0", 3).encode())
+ self.assertEqual(self.repo.pushed, [(CUT, LINE)])
+
+ def test_other_conflicts_stop_without_a_push(self):
+ self.repo.conflicts = [STATE, "CMakeLists.txt"]
+ stop = self.stop()
+ self.assertEqual(stop.stage, "merge")
+ self.assertIn("CMakeLists.txt", str(stop))
+ self.assertIsNone(self.repo.written)
+ self.assertEqual(self.repo.discarded, [Path("merge-worktree")])
+ self.assertNothingDone()
+
+ def test_lock_that_fails_validation_stops_without_a_push(self):
+ self.repo.validation_error = "Stale recipe for x86_64"
+ stop = self.stop()
+ self.assertEqual(stop.stage, "lock")
+ self.assertIn("Stale recipe", str(stop))
+ self.assertIsNone(self.repo.committed)
+ self.assertNothingDone()
+
+ def test_rejected_push_stops(self):
+ self.repo.push_error = "non-fast-forward"
+ self.assertEqual(self.stop().stage, "merge")
+ self.assertEqual(self.repo.discarded, [Path("merge-worktree")])
+
+
+class ContinueTest(SchedulerTestCase):
+ def setUp(self):
+ super().setUp()
+ self.repo.files[(TIP, STATE)] = state(number=3)
+
+ def proceed(self, event_run):
+ return beta.Scheduler(self.repo, self.internal, bot_login=BOT).continue_after(event_run)
+
+ def skipped(self, event_run):
+ with self.assertRaises(beta.Skip):
+ self.proceed(event_run)
+ self.assertEqual(self.internal.dispatches, [])
+
+ def stopped(self, event_run):
+ with self.assertRaises(beta.Stop) as raised:
+ self.proceed(event_run)
+ self.assertEqual(self.internal.dispatches, [])
+ return raised.exception
+
+ def test_green_cut_ci_dispatches_candidate_creation(self):
+ self.proceed(run(beta.CI))
+ self.assertEqual(self.internal.dispatches, [
+ (beta.CANDIDATE, LINE, {"version": "3.3.0-beta3", "expected_sha": TIP, "operation": "create"}),
+ ])
+ self.assertEqual(self.repo.synced, [True])
+
+ def test_runs_not_started_by_the_release_bot_do_nothing(self):
+ for actor in ("k1jt", "dependabot[bot]", "github-actions[bot]"):
+ with self.subTest(actor=actor):
+ self.skipped(run(beta.CI, actor=actor))
+ self.assertEqual(self.repo.synced, [])
+
+ def test_a_person_rerunning_a_release_bot_run_resumes_the_beta(self):
+ self.proceed(run(beta.CI, triggering_actor="k1jt"))
+ self.repo.tags["build/v3.3.0-beta3"] = TIP
+ rerun = candidate("3.3.0-beta3", triggering_actor="dchristle")
+ self.proceed(rerun)
+ self.assertEqual([workflow for workflow, _ref, _inputs in self.internal.dispatches],
+ [beta.CANDIDATE, beta.PROMOTION])
+
+ def test_green_cut_ci_waits_for_a_candidate_already_running(self):
+ self.internal.add(candidate("3.3.0-beta3", status="in_progress"))
+ self.skipped(run(beta.CI))
+
+ def test_runs_away_from_the_beta_line_tip_do_nothing(self):
+ for fields in ({"sha": GREEN}, {"branch": "release/3.2", "sha": OLD_LINE_TIP}, {"branch": "release/3.2"},
+ {"event": "pull_request"}):
+ with self.subTest(fields=fields):
+ self.skipped(run(beta.CI, **fields))
+
+ def test_failed_cut_ci_alerts(self):
+ failed = run(beta.CI, conclusion="failure")
+ stop = self.stopped(failed)
+ self.assertEqual((stop.stage, stop.link), ("ci", failed["html_url"]))
+
+ def test_existing_candidate_tag_is_not_created_again(self):
+ self.repo.tags["build/v3.3.0-beta3"] = TIP
+ self.skipped(run(beta.CI))
+
+ def test_successful_candidate_dispatches_promotion(self):
+ self.repo.tags["build/v3.3.0-beta3"] = TIP
+ done = candidate("3.3.0-beta3")
+ self.proceed(done)
+ self.assertEqual(self.internal.dispatches, [(beta.PROMOTION, LINE, {
+ "version": "3.3.0-beta3", "candidate_run_id": str(done["id"]), "operation": "promote",
+ })])
+
+ def test_failed_candidate_alerts_that_a_rerun_resumes_or_the_next_cut_moves_on(self):
+ self.repo.tags["build/v3.3.0-beta3"] = TIP
+ failed = candidate("3.3.0-beta3", conclusion="failure")
+ stop = self.stopped(failed)
+ self.assertEqual((stop.stage, stop.link), ("candidate", failed["html_url"]))
+ self.assertIn("Re-run it if the failure is transient", str(stop))
+ self.assertIn("moves on to BETA 4", str(stop))
+
+ def test_candidate_refused_before_its_tag_alerts_that_the_next_cut_retries_the_number(self):
+ failed = candidate("3.3.0-beta3", conclusion="failure")
+ stop = self.stopped(failed)
+ self.assertEqual((stop.stage, stop.link), ("candidate", failed["html_url"]))
+ self.assertIn("the next scheduled cut retries 3.3.0-beta3", str(stop))
+ self.assertNotIn("BETA 4", str(stop))
+
+ def test_candidate_without_its_tag_at_the_tip_alerts(self):
+ for tag_sha in (None, GREEN):
+ with self.subTest(tag_sha=tag_sha):
+ self.repo.tags["build/v3.3.0-beta3"] = tag_sha
+ self.assertEqual(self.stopped(candidate("3.3.0-beta3")).stage, "candidate")
+
+ def test_other_candidate_runs_do_nothing(self):
+ for other in (
+ candidate("3.3.0-beta3", "validate"),
+ candidate("3.3.0-beta2"),
+ run(beta.CANDIDATE, event="workflow_dispatch", title="Prepare Release Candidate"),
+ ):
+ with self.subTest(title=other["display_title"]):
+ self.repo.tags["build/v3.3.0-beta3"] = TIP
+ self.skipped(other)
+
+ def test_failed_promotion_alerts_so_a_rerun_can_resume(self):
+ failed = run(beta.PROMOTION, event="workflow_dispatch", conclusion="failure")
+ stop = self.stopped(failed)
+ self.assertEqual((stop.stage, stop.link), ("promotion", failed["html_url"]))
+
+ def test_successful_promotion_leaves_publication_to_the_public_release_run(self):
+ self.skipped(run(beta.PROMOTION, event="workflow_dispatch"))
+
+ def test_successful_bot_preparation_dispatches_the_beta_cut_on_develop(self):
+ self.proceed(preparation("validated-build-20261001-714-1"))
+ self.assertEqual(self.internal.dispatches, [(beta.BETA_CUT, "develop", {})])
+ self.assertEqual(self.repo.synced, [])
+
+ def test_other_preparation_and_develop_runs_do_nothing(self):
+ for other in (
+ preparation("validated-build-20261001-714-1", actor="dchristle"),
+ preparation("validated-build-20261001-714-1", branch=LINE),
+ preparation("validated-build-20261001-714-1", event="push"),
+ run(beta.PREPARATION, event="workflow_dispatch", branch="develop", sha=DEVELOP,
+ title="Prepare Release Dependencies release/3.2 validated-build-20260918-35390550558-1"),
+ run(beta.PREPARATION, event="workflow_dispatch", branch="develop", sha=DEVELOP,
+ title="Prepare Release Dependencies"),
+ run(beta.CI, branch="develop", sha=DEVELOP),
+ ):
+ with self.subTest(path=other["path"], title=other["display_title"], branch=other["head_branch"],
+ event=other["event"], actor=other["actor"]["login"]):
+ self.skipped(other)
+
+ def test_failed_bot_preparation_alerts(self):
+ failed = preparation("validated-build-20261001-714-1", conclusion="failure")
+ stop = self.stopped(failed)
+ self.assertEqual((stop.stage, stop.link), ("lock", failed["html_url"]))
+
+
+class StepReportTest(unittest.TestCase):
+ def outcome(self, action):
+ return beta.run_step("cut", action, ["Beta line: release/3.3."])
+
+ def test_actions_and_skips_report_without_an_alert(self):
+ status, summary, alert = self.outcome(lambda: "Dispatched the candidate.")
+ self.assertEqual((status, alert), (0, None))
+ self.assertIn("- Beta line: release/3.3.", summary)
+ self.assertIn("Dispatched the candidate.", summary)
+
+ def skip():
+ raise beta.Skip("develop has not moved")
+ status, summary, alert = self.outcome(skip)
+ self.assertEqual((status, alert), (0, None))
+ self.assertIn("develop has not moved", summary)
+
+ def test_stops_and_unexpected_errors_alert_and_fail(self):
+ def stop():
+ raise beta.Stop("fixes", "release/3.3 holds a fix.", "https://example.invalid/runs/1")
+
+ def crash():
+ raise RuntimeError("API outage")
+ status, summary, alert = self.outcome(stop)
+ self.assertEqual((status, alert), (1, ("fixes", "release/3.3 holds a fix.", "https://example.invalid/runs/1")))
+ self.assertIn("release/3.3 holds a fix.", summary)
+ with patch("traceback.print_exc"):
+ status, summary, alert = self.outcome(crash)
+ self.assertEqual((status, alert), (1, ("cut", "Unexpected error: API outage", None)))
+
+
+class EntryPointTest(unittest.TestCase):
+ ENV = {"GITHUB_REPOSITORY": "example/internal", "GITHUB_RUN_ID": "5", "GITHUB_TOKEN": "workflow-token",
+ "RELEASE_BOT_TOKEN": "bot-token", "RELEASE_BOT_SLUG": "wsjtx-release-bot",
+ "PUBLIC_READ_TOKEN": "public-token"}
+
+ def test_scheduler_acts_as_the_release_bot(self):
+ with patch.object(beta.GitHub, "user_id", lambda github, login: 41):
+ cut = beta.build_scheduler("cut", self.ENV, [])
+ proceed = beta.build_scheduler("continue", self.ENV, [])
+ self.assertEqual((cut.bot_login, cut.bot_email), (BOT, BOT_EMAIL))
+ self.assertEqual((proceed.bot_login, proceed.bot_email), (BOT, None))
+ self.assertEqual(cut.public.repository, beta.PUBLIC_REPOSITORY)
+
+ def main(self, outcome):
+ posted = []
+ with tempfile.TemporaryDirectory() as directory:
+ output, summary = Path(directory, "output"), Path(directory, "summary")
+ output.touch()
+ env = {**self.ENV, "GITHUB_OUTPUT": str(output), "GITHUB_STEP_SUMMARY": str(summary)}
+ with patch.dict(os.environ, env), \
+ patch.object(beta, "build_scheduler", lambda command, environ, notes: SimpleNamespace(cut=outcome)), \
+ patch.object(beta.Alerts, "post", lambda alerts, *alert: posted.append(alert)), \
+ patch("sys.stdout", io.StringIO()):
+ status = beta.main(["cut"])
+ return status, posted, output.read_text(), summary.read_text()
+
+ def test_a_stop_is_posted_once_and_recorded_so_the_fallback_alert_stays_silent(self):
+ def stop():
+ raise beta.Stop("candidate", "The candidate failed.", "https://example.invalid/runs/2")
+ status, posted, output, summary = self.main(stop)
+ self.assertEqual(status, 1)
+ self.assertEqual(posted, [("candidate", "The candidate failed.", "https://example.invalid/runs/2")])
+ self.assertEqual(output, "alerted=true\n")
+ self.assertIn("The candidate failed.", summary)
+
+ def test_a_skip_posts_nothing(self):
+ def skip():
+ raise beta.Skip("develop has not moved")
+ status, posted, output, summary = self.main(skip)
+ self.assertEqual((status, posted, output), (0, [], ""))
+ self.assertIn("develop has not moved", summary)
+
+
+class FakeIssuesApi:
+ repository = "example/internal"
+
+ def __init__(self, issues):
+ self.issues = issues
+ self.calls = []
+
+ def call(self, method, path, *, params=None, body=None, missing_ok=False):
+ self.calls.append((method, path, params, body))
+ return self.issues if method == "GET" else {}
+
+
+class AlertsTest(unittest.TestCase):
+ RUN = "https://example.invalid/runs/1"
+
+ def test_first_alert_opens_the_tracking_issue(self):
+ api = FakeIssuesApi([
+ {"number": 5, "title": beta.ALERT_TITLE + " (old)", "user": {"login": beta.ALERT_CREATOR}},
+ {"number": 6, "title": beta.ALERT_TITLE, "user": {"login": "k1jt"}},
+ {"number": 7, "title": beta.ALERT_TITLE, "user": {"login": beta.ALERT_CREATOR}, "pull_request": {}},
+ ])
+ beta.Alerts(api, self.RUN).post("candidate", "The candidate failed.", "https://example.invalid/runs/2")
+ self.assertEqual(api.calls[0][:3], ("GET", "/repos/example/internal/issues",
+ {"state": "open", "creator": beta.ALERT_CREATOR, "per_page": 100}))
+ method, path, _params, body = api.calls[-1]
+ self.assertEqual((method, path, body["title"]), ("POST", "/repos/example/internal/issues", beta.ALERT_TITLE))
+ for text in ("**Stage:** candidate", "**Reason:** The candidate failed.",
+ "**Run:** https://example.invalid/runs/2", f"**Reported by:** {self.RUN}"):
+ self.assertIn(text, body["body"])
+
+ def test_later_alerts_comment_on_the_open_tracking_issue(self):
+ api = FakeIssuesApi([
+ {"number": 12, "title": beta.ALERT_TITLE, "user": {"login": beta.ALERT_CREATOR}},
+ {"number": 9, "title": beta.ALERT_TITLE, "user": {"login": beta.ALERT_CREATOR}},
+ ])
+ beta.Alerts(api, self.RUN).post("lock", "No generation.")
+ method, path, _params, body = api.calls[-1]
+ self.assertEqual((method, path), ("POST", "/repos/example/internal/issues/9/comments"))
+ self.assertIn(f"**Run:** {self.RUN}", body["body"])
+ self.assertNotIn("Reported by", body["body"])
+
+
+class FakeResponse(io.BytesIO):
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+
+class GitHubClientTest(unittest.TestCase):
+ def test_missing_release_is_unpublished_and_other_errors_raise(self):
+ github = beta.GitHub("token", "example/public")
+
+ def missing(request, timeout):
+ raise urllib.error.HTTPError(request.full_url, 404, "Not Found", {}, None)
+ with patch("urllib.request.urlopen", missing):
+ self.assertFalse(github.release_published("v3.3.0-beta2"))
+ with patch("urllib.request.urlopen", lambda request, timeout: FakeResponse(b'{"draft": false}')):
+ self.assertTrue(github.release_published("v3.3.0-beta2"))
+
+ def denied(request, timeout):
+ raise urllib.error.HTTPError(request.full_url, 403, "Forbidden", {}, None)
+ with patch("urllib.request.urlopen", denied), self.assertRaisesRegex(RuntimeError, "HTTP 403"):
+ github.release_published("v3.3.0-beta2")
+
+ def test_run_and_job_listings_send_their_filters(self):
+ requests = []
+
+ def urlopen(request, timeout):
+ requests.append(request)
+ return FakeResponse(json.dumps({"workflow_runs": [{"id": 1}], "jobs": [{"id": 2}]}).encode())
+
+ github = beta.GitHub("token", "example/internal")
+ with patch("urllib.request.urlopen", urlopen):
+ self.assertEqual(github.runs(beta.CI, branch="develop", event="push", status="success",
+ head_sha="ab" * 20), [{"id": 1}])
+ self.assertEqual(github.jobs(77), [{"id": 2}])
+ runs, jobs = (urllib.parse.urlsplit(request.full_url) for request in requests)
+ self.assertEqual(runs.path, f"/repos/example/internal/actions/workflows/{beta.CI}/runs")
+ self.assertEqual(urllib.parse.parse_qs(runs.query), {
+ "per_page": ["100"], "branch": ["develop"], "event": ["push"], "status": ["success"],
+ "head_sha": ["ab" * 20],
+ })
+ self.assertEqual((jobs.path, urllib.parse.parse_qs(jobs.query)),
+ ("/repos/example/internal/actions/runs/77/jobs", {"per_page": ["100"]}))
+
+ def test_artifact_download_follows_the_redirect_without_the_token(self):
+ bundle = io.BytesIO()
+ with zipfile.ZipFile(bundle, "w") as archive:
+ archive.writestr(LOCK, lock())
+ requests = []
+
+ class Opener:
+ def open(self, request, timeout):
+ requests.append(request)
+ location = {"Location": "https://blob.example.invalid/a"}
+ raise urllib.error.HTTPError(request.full_url, 302, "Found", location, None)
+
+ def urlopen(request, timeout):
+ requests.append(request)
+ if isinstance(request, str):
+ return FakeResponse(bundle.getvalue())
+ return FakeResponse(json.dumps({"artifacts": [
+ {"id": 9, "name": beta.PREPARED_ARTIFACT, "expired": True},
+ {"id": 8, "name": beta.PREPARED_ARTIFACT, "expired": False},
+ ]}).encode())
+
+ github = beta.GitHub("token", "example/internal")
+ with patch("urllib.request.urlopen", urlopen), patch("urllib.request.build_opener", lambda *handlers: Opener()):
+ self.assertEqual(github.artifact_file(77, beta.PREPARED_ARTIFACT, LOCK), lock())
+ self.assertIn("/actions/runs/77/artifacts?", requests[0].full_url)
+ self.assertTrue(requests[1].full_url.endswith("/actions/artifacts/8/zip"))
+ self.assertEqual(requests[1].get_header("Authorization"), "Bearer token")
+ self.assertEqual(requests[2], "https://blob.example.invalid/a")
+
+
+class RepositoryTest(unittest.TestCase):
+ """The git layer against a local origin, with no global git identity, as on a runner."""
+
+ def setUp(self):
+ directory = tempfile.TemporaryDirectory()
+ self.addCleanup(directory.cleanup)
+ self.root = Path(directory.name)
+ environment = patch.dict(os.environ, {"GIT_CONFIG_GLOBAL": str(self.root / "no-global-config"),
+ "GIT_CONFIG_NOSYSTEM": "1", "GIT_CONFIG_COUNT": "1",
+ "GIT_CONFIG_KEY_0": "user.useConfigOnly",
+ "GIT_CONFIG_VALUE_0": "true"})
+ environment.start()
+ self.addCleanup(environment.stop)
+ self.origin = self.root / "origin.git"
+ self.work = self.root / "work"
+ self.git(self.root, "init", "--bare", "--initial-branch=develop", str(self.origin))
+ self.git(self.root, "init", "--initial-branch=develop", str(self.work))
+ # Background auto-maintenance would race the directory's removal.
+ for repository in (self.origin, self.work):
+ self.git(repository, "config", "maintenance.auto", "false")
+ (self.work / "app.txt").write_text("one\n")
+ (self.work / STATE).write_bytes(state("DEVEL", version="9.1.0"))
+ self.base = self.commit("develop base")
+ (self.work / STATE).write_bytes(state(number=1, version="9.1.0"))
+ (self.work / LOCK).write_bytes(lock())
+ self.line_start = self.commit("open 9.1 beta line")
+ self.git(self.work, "push", str(self.origin), f"{self.line_start}:refs/heads/release/9.1")
+ self.git(self.work, "checkout", "--quiet", "--detach", self.base)
+ (self.work / "app.txt").write_text("two\n")
+ self.develop = self.commit("develop work")
+ self.git(self.work, "push", str(self.origin), f"{self.develop}:refs/heads/develop")
+ self.checkout = self.root / "checkout"
+ self.git(self.root, "clone", "--quiet", "--config", "maintenance.auto=false",
+ str(self.origin), str(self.checkout))
+ self.repository = beta.Repository(self.checkout, str(self.origin))
+ self.repository.sync()
+
+ def git(self, cwd, *arguments):
+ return subprocess.run(["git", *arguments], cwd=cwd, check=True, capture_output=True, text=True).stdout.strip()
+
+ def commit(self, message, author=MAINTAINER):
+ self.git(self.work, "add", "--all")
+ self.git(self.work, "-c", "user.name=Maintainer", "-c", f"user.email={author}",
+ "commit", "--quiet", "-m", message)
+ return self.git(self.work, "rev-parse", "HEAD")
+
+ def origin_git(self, *arguments):
+ return self.git(self.origin, *arguments)
+
+ def test_reads_refs_files_tags_and_ancestry(self):
+ self.assertEqual(self.repository.release_heads(), {"release/9.1": self.line_start})
+ self.assertEqual(self.repository.develop(), self.develop)
+ self.assertEqual(self.repository.read(self.line_start, STATE), state(number=1, version="9.1.0"))
+ self.assertIsNone(self.repository.read(self.base, LOCK))
+ self.assertTrue(self.repository.contains(self.develop))
+ self.assertFalse(self.repository.contains("0" * 40))
+ self.assertTrue(self.repository.is_ancestor(self.base, self.develop))
+ self.assertFalse(self.repository.is_ancestor(self.line_start, self.develop))
+ self.assertIsNone(self.repository.tag("build/v9.1.0-beta1"))
+ self.git(self.work, "push", str(self.origin), f"{self.line_start}:refs/tags/build/v9.1.0-beta1")
+ self.git(self.work, "-c", "user.name=Maintainer", "-c", f"user.email={MAINTAINER}",
+ "tag", "-a", "-m", "annotated", "annotated", self.base)
+ self.git(self.work, "push", str(self.origin), "refs/tags/annotated")
+ self.assertEqual(self.repository.tag("build/v9.1.0-beta1"), self.line_start)
+ self.assertEqual(self.repository.tag("annotated"), self.base)
+
+ def test_cut_merges_develop_writes_metadata_and_pushes_as_the_bot(self):
+ self.assertEqual(self.repository.commits_missing_from_develop(self.line_start),
+ [beta.Commit(self.line_start, MAINTAINER, (LOCK, STATE))])
+ worktree, conflicts = self.repository.start_merge(self.line_start, self.develop, BOT, BOT_EMAIL)
+ self.assertEqual(conflicts, [])
+ self.repository.write(worktree, {STATE: beta.render_state("9.1.0", 2).encode(), LOCK: lock(DRIFTED)})
+ cut = self.repository.commit(worktree, BOT, BOT_EMAIL, "Cut 9.1.0-beta2 from develop\n")
+ self.repository.push(cut, "release/9.1")
+ self.repository.discard(worktree)
+ self.assertFalse(worktree.exists())
+ self.assertEqual(self.origin_git("rev-parse", "refs/heads/release/9.1"), cut)
+ self.assertEqual(self.origin_git("show", "-s", "--format=%P%n%an <%ae>%n%cn <%ce>", cut).splitlines(), [
+ f"{self.line_start} {self.develop}", f"{BOT} <{BOT_EMAIL}>", f"{BOT} <{BOT_EMAIL}>",
+ ])
+ self.assertEqual(self.origin_git("show", f"{cut}:app.txt"), "two")
+ self.assertEqual(self.origin_git("show", f"{cut}:{STATE}") + "\n", beta.render_state("9.1.0", 2))
+ self.assertEqual((self.origin_git("show", f"{cut}:{LOCK}") + "\n").encode(), lock(DRIFTED))
+ self.repository.sync()
+ self.assertEqual(self.repository.commits_missing_from_develop(cut), [
+ beta.Commit(cut, BOT_EMAIL, ("app.txt", LOCK, STATE)),
+ beta.Commit(self.line_start, MAINTAINER, (LOCK, STATE)),
+ ])
+
+ def test_fix_detection_reads_the_author_not_the_committer(self):
+ self.git(self.work, "checkout", "--quiet", "--detach", self.line_start)
+ (self.work / "app.txt").write_text("release fix\n")
+ self.git(self.work, "add", "--all")
+ subprocess.run(["git", "-c", "user.name=Maintainer", "-c", f"user.email={MAINTAINER}",
+ "commit", "--quiet", "-m", "fix committed by the bot"], cwd=self.work, check=True,
+ env={**os.environ, "GIT_COMMITTER_NAME": BOT, "GIT_COMMITTER_EMAIL": BOT_EMAIL})
+ fixed = self.git(self.work, "rev-parse", "HEAD")
+ self.git(self.work, "push", str(self.origin), f"{fixed}:refs/heads/release/9.1")
+ self.repository.sync()
+ self.assertEqual(self.repository.commits_missing_from_develop(fixed)[0],
+ beta.Commit(fixed, MAINTAINER, ("app.txt",)))
+
+ def test_full_sync_forgets_deleted_release_branches(self):
+ self.git(self.work, "push", str(self.origin), f"{self.line_start}:refs/heads/release/9.2")
+ self.repository.sync()
+ self.assertIn("release/9.2", self.repository.release_heads())
+ self.git(self.work, "push", str(self.origin), ":refs/heads/release/9.2")
+ self.repository.sync()
+ self.assertEqual(self.repository.release_heads(), {"release/9.1": self.line_start})
+
+ def test_merge_reports_conflicts_and_push_refuses_to_rewind(self):
+ self.git(self.work, "checkout", "--quiet", "--detach", self.line_start)
+ (self.work / "app.txt").write_text("release fix\n")
+ fixed = self.commit("fix on the release branch")
+ self.git(self.work, "push", str(self.origin), f"{fixed}:refs/heads/release/9.1")
+ self.repository.sync()
+ worktree, conflicts = self.repository.start_merge(fixed, self.develop, BOT, BOT_EMAIL)
+ self.addCleanup(self.repository.discard, worktree)
+ self.assertEqual(conflicts, ["app.txt"])
+ with self.assertRaisesRegex(RuntimeError, "git push"):
+ self.repository.push(self.line_start, "release/9.1")
+
+ def test_fingerprints_run_each_commits_own_recipe_scripts(self):
+ shutil.copytree(ROOT / ".github", self.work / ".github")
+ recipes = self.commit("add the pipeline")
+ self.git(self.work, "push", str(self.origin), f"{recipes}:refs/heads/develop")
+ dockerfile = self.work / ".github/images/linux-ci/Dockerfile.noble"
+ dockerfile.write_text(dockerfile.read_text() + "# drift\n")
+ drifted = self.commit("drift the noble recipe")
+ self.git(self.work, "push", str(self.origin), f"{drifted}:refs/heads/develop")
+ self.repository.sync()
+ expected = {
+ key: subprocess.run(["bash", ".github/scripts/linux-ci-image-fingerprint.sh", spec[1]], cwd=ROOT,
+ check=True, capture_output=True, text=True).stdout.strip()
+ for key, spec in beta.images.IMAGES.items()
+ }
+ self.assertEqual(self.repository.fingerprints(recipes), expected)
+ changed = self.repository.fingerprints(drifted)
+ self.assertNotEqual(changed["x86_64"], expected["x86_64"])
+ self.assertEqual(changed["armhf_runtime"], expected["armhf_runtime"])
+ self.assertIsNone(self.repository.fingerprints("0" * 40))
+
+ def test_lock_validation_runs_the_merged_trees_validator(self):
+ shutil.copytree(ROOT / ".github", self.work / ".github")
+ (self.work / LOCK).write_text('{"schema": 2}\n')
+ self.commit("add the pipeline")
+ with self.assertRaisesRegex(RuntimeError, "Unsupported Linux image selection schema"):
+ self.repository.validate_lock(self.work)
+
+
+class WorkflowWiringTest(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.CUT = (ROOT / ".github/workflows/beta-cut.yml").read_text()
+ cls.CONTINUE = (ROOT / ".github/workflows/beta-continue.yml").read_text()
+
+ @staticmethod
+ def jobs(workflow):
+ body = workflow.split("\njobs:\n", 1)[1]
+ names = re.findall(r"^ ([A-Za-z0-9_-]+):$", body, re.M)
+ blocks = re.split(r"^ [A-Za-z0-9_-]+:$", body, flags=re.M)[1:]
+ return dict(zip(names, blocks))
+
+ def test_candidate_run_name_is_what_the_continuation_parses(self):
+ helper = (ROOT / ".github/workflows/release-tag-helper.yml").read_text()
+ run_name = re.search(r"^run-name: (.+)$", helper, re.M).group(1)
+ rendered = run_name.replace("${{ inputs.version }}", "3.3.0-beta2").replace("${{ inputs.operation }}", "create")
+ self.assertEqual(beta.candidate_of({"display_title": rendered}), ("3.3.0-beta2", "create"))
+
+ def test_preparation_run_name_is_what_the_scheduler_parses(self):
+ workflow = (ROOT / ".github/workflows/prepare-release-dependencies.yml").read_text()
+ run_name = re.search(r"^run-name: (.+)$", workflow, re.M).group(1)
+ rendered = run_name.replace("${{ inputs.source_branch }}", "develop").replace(
+ "${{ inputs.generation }}", "validated-build-20261001-1-1")
+ self.assertEqual(beta.preparation_of({"display_title": rendered}), ("develop", "validated-build-20261001-1-1"))
+
+ def test_beta_workflows_act_only_when_beta_automation_is_exactly_enabled(self):
+ for workflow in (self.CUT, self.CONTINUE):
+ jobs = self.jobs(workflow)
+ gate = jobs["gate"]
+ self.assertIn("BETA_AUTOMATION: ${{ vars.BETA_AUTOMATION }}", gate)
+ self.assertRegex(
+ gate, r'if \[ "\$BETA_AUTOMATION" = enabled \]; then\s+echo "enabled=true" >> "\$GITHUB_OUTPUT"')
+ self.assertIn('>> "$GITHUB_STEP_SUMMARY"', gate)
+ # Expression comparisons ignore case, so the variable is compared only in the shell.
+ self.assertEqual(workflow.count("vars.BETA_AUTOMATION"), 1)
+ acting = [name for name, block in jobs.items() if "environment: beta-automation" in block]
+ self.assertEqual(len(acting), 1)
+ self.assertIn("needs: gate", jobs[acting[0]])
+ # Neither a manual dispatch nor always() may bypass the pause.
+ self.assertRegex(jobs[acting[0]], r"\n if: needs\.gate\.outputs\.enabled == 'true'\n")
+
+ def test_beta_cut_runs_weekly_on_tuesday_at_2000_utc_and_on_dispatch(self):
+ triggers = re.search(r"^on:\n((?: .*\n)+)", self.CUT, re.M).group(1)
+ self.assertEqual(triggers, ' schedule:\n - cron: "0 20 * * 2"\n workflow_dispatch:\n')
+
+ def test_cut_and_continuation_act_one_at_a_time(self):
+ for workflow in (self.CUT, self.CONTINUE):
+ # A workflow-level group would also hold the gate runs, whose arrival cancels a pending acting run.
+ self.assertNotRegex(workflow, r"(?m)^concurrency:")
+ acting = [block for block in self.jobs(workflow).values() if "environment: beta-automation" in block]
+ self.assertIn(" concurrency:\n group: beta-scheduler\n cancel-in-progress: false\n", acting[0])
+
+ def test_beta_continue_follows_beta_runs_and_preparations_from_develop(self):
+ self.assertIn(
+ 'on:\n workflow_run:\n'
+ ' workflows: ["CI", "Prepare Release Candidate", "Prepare Release Dependencies", "Promote Release Source"]\n'
+ ' types: [completed]\n branches: ["release/**", "develop"]\n', self.CONTINUE)
+ # Every other run on develop, such as a person's push CI, skips the gate and starts no job.
+ self.assertIn(
+ " if: >-\n"
+ " github.event.workflow_run.actor.type == 'Bot' &&\n"
+ " (github.event.workflow_run.head_branch != 'develop' ||\n"
+ " github.event.workflow_run.path == '.github/workflows/prepare-release-dependencies.yml')\n",
+ self.jobs(self.CONTINUE)["gate"])
+
+ def test_release_bot_token_is_minted_only_in_the_beta_automation_job(self):
+ for workflow in (self.CUT, self.CONTINUE):
+ for name, block in self.jobs(workflow).items():
+ minted = "actions/create-github-app-token@" in block
+ self.assertEqual(minted, "environment: beta-automation" in block, name)
+ if minted:
+ self.assertRegex(block, r"uses: actions/create-github-app-token@[0-9a-f]{40} # v\d")
+ self.assertIn("client-id: ${{ vars.RELEASE_BOT_APP_ID }}", block)
+ self.assertIn("private-key: ${{ secrets.RELEASE_BOT_PRIVATE_KEY }}", block)
+ self.assertIn("persist-credentials: false", block)
+ self.assertIn("issues: write", block)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.github/scripts/tests/test_check_candidate_tag.py b/.github/scripts/tests/test_check_candidate_tag.py
index cf44ccf4..9212c4ec 100644
--- a/.github/scripts/tests/test_check_candidate_tag.py
+++ b/.github/scripts/tests/test_check_candidate_tag.py
@@ -14,6 +14,8 @@ class CheckCandidateTagTest(unittest.TestCase):
self.addCleanup(self.directory.cleanup)
self.repo = Path(self.directory.name)
self.git("init", "-q")
+ # Background auto-maintenance would race the directory's removal.
+ self.git("config", "maintenance.auto", "false")
self.git(
"-c", "user.name=Test", "-c", "user.email=test@example.com",
"commit", "--allow-empty", "-qm", "first",
diff --git a/.github/scripts/tests/test_generate_change_list.py b/.github/scripts/tests/test_generate_change_list.py
new file mode 100644
index 00000000..6d2e707c
--- /dev/null
+++ b/.github/scripts/tests/test_generate_change_list.py
@@ -0,0 +1,263 @@
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+
+SCRIPT = Path(__file__).resolve().parents[1] / "generate-change-list.py"
+REPO = "WSJTX/wsjtx"
+
+
+class ChangeListTest(unittest.TestCase):
+ def setUp(self):
+ self.directory = tempfile.TemporaryDirectory()
+ self.addCleanup(self.directory.cleanup)
+ self.repo = Path(self.directory.name)
+ self.env = {
+ **{key: value for key, value in os.environ.items() if not key.startswith("GIT_")},
+ "GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1",
+ "GIT_AUTHOR_EMAIL": "author@example.com",
+ "GIT_COMMITTER_NAME": "Committer", "GIT_COMMITTER_EMAIL": "committer@example.com",
+ }
+ self.git("init", "-q", "-b", "develop")
+ # Background auto-maintenance would race the directory's removal.
+ self.git("config", "maintenance.auto", "false")
+ self.commit("chore: start")
+
+ def stamp(self, author="Test Author"):
+ # Distinct dates, so a cherry-pick onto the same parent is a real copy.
+ self.clock = getattr(self, "clock", 0) + 1
+ date = f"@{1_700_000_000 + self.clock} +0000"
+ return {**self.env, "GIT_AUTHOR_NAME": author, "GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date}
+
+ def git(self, *args):
+ return subprocess.run(
+ ["git", *args], cwd=self.repo, env=self.stamp(), text=True, capture_output=True, check=True,
+ ).stdout.strip()
+
+ def commit(self, subject, author="Test Author", change=None):
+ # A distinct change per commit: git treats all empty commits as cherry-picks of each other.
+ self.changes = getattr(self, "changes", 0) + 1
+ change = change or f"change-{self.changes}.txt"
+ (self.repo / change).write_text(subject + "\n")
+ self.git("add", change)
+ subprocess.run(
+ ["git", "commit", "-qm", subject],
+ cwd=self.repo, env=self.stamp(author), check=True, capture_output=True,
+ )
+ return self.git("rev-parse", "HEAD")
+
+ def merge(self, ref, subject):
+ self.git("merge", "--no-ff", "-qm", subject, ref)
+
+ def notes(self, tag):
+ result = subprocess.run(
+ [sys.executable, str(SCRIPT), REPO, tag],
+ cwd=self.repo, env=self.env, text=True, capture_output=True,
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ return result.stdout
+
+ def test_a_later_beta_lists_the_changes_since_the_previous_beta_in_commit_order(self):
+ self.git("checkout", "-qb", "release/3.3")
+ self.commit("feat: old feature")
+ self.git("tag", "v3.3.0-beta1")
+ self.commit("feat(decoder): new mode", author="Joe Taylor")
+ self.commit("fix(wav): keep the dial context", author="David Christle")
+ self.commit("fix: a later fix")
+ self.git("tag", "v3.3.0-beta2")
+ notes = self.notes("v3.3.0-beta2")
+ self.assertTrue(notes.startswith("## Changes since v3.3.0-beta1\n"))
+ self.assertIn("### New features\n- decoder: new mode (Joe Taylor)\n", notes)
+ self.assertIn("### Fixes\n- wav: keep the dial context (David Christle)\n- a later fix (Test Author)\n", notes)
+ self.assertNotIn("old feature", notes)
+ self.assertIn(f"[Full comparison](https://github.com/{REPO}/compare/v3.3.0-beta1...v3.3.0-beta2).", notes)
+
+ def test_a_spent_beta_number_falls_back_to_the_newest_published_tag(self):
+ self.git("checkout", "-qb", "release/3.3")
+ self.git("tag", "v3.3.0-beta1")
+ self.commit("fix: carried by the unpublished beta2")
+ self.commit("fix: new in beta3")
+ self.git("tag", "v3.3.0-beta3")
+ notes = self.notes("v3.3.0-beta3")
+ self.assertTrue(notes.startswith("## Changes since v3.3.0-beta1\n"))
+ self.assertIn("- carried by the unpublished beta2", notes)
+ self.assertIn("- new in beta3", notes)
+
+ def test_a_release_candidate_follows_the_last_beta_of_its_line(self):
+ self.git("checkout", "-qb", "release/3.3")
+ self.git("tag", "v3.3.0-beta4")
+ self.commit("fix: freeze-time fix")
+ self.git("tag", "v3.3.0-rc1")
+ notes = self.notes("v3.3.0-rc1")
+ self.assertTrue(notes.startswith("## Changes since v3.3.0-beta4\n"))
+ self.assertIn("- freeze-time fix", notes)
+
+ def test_a_lines_first_release_leaves_out_what_the_previous_line_shipped(self):
+ self.commit("feat: in 3.2 already")
+ self.git("tag", "v3.0.2")
+ self.git("checkout", "-qb", "release/3.0", "HEAD~1")
+ self.commit("fix: only on the old line")
+ self.git("tag", "v3.0.3")
+ self.git("checkout", "-q", "develop")
+ self.git("checkout", "-qb", "release/3.2")
+ self.commit("fix: only on release/3.2")
+ self.git("checkout", "-q", "develop")
+ picked = self.commit("fix(gui): picked into 3.2", change="gui.txt")
+ self.git("checkout", "-q", "release/3.2")
+ self.git("cherry-pick", picked)
+ self.git("tag", "v3.2.0-rc1")
+ self.git("checkout", "-q", "develop")
+ self.merge("v3.0.3", "Merge 3.0.3 into develop")
+ self.commit("feat: new on develop")
+ self.git("checkout", "-qb", "release/3.3")
+ self.commit("build(release): start 3.3 at BETA 1")
+ self.git("tag", "v3.3.0-beta1")
+ notes = self.notes("v3.3.0-beta1")
+ self.assertTrue(notes.startswith("## Changes since v3.2.0-rc1\n"))
+ self.assertIn("- new on develop", notes)
+ for shipped in ("in 3.2 already", "only on release/3.2", "picked into 3.2", "only on the old line"):
+ self.assertNotIn(shipped, notes)
+ self.assertIn(f"/compare/v3.2.0-rc1...v3.3.0-beta1", notes)
+
+ def test_a_beta_after_the_previous_ga_is_merged_back_lists_only_new_changes(self):
+ self.git("checkout", "-qb", "release/3.2")
+ self.git("tag", "v3.2.0-rc1")
+ self.git("checkout", "-q", "develop")
+ original = self.commit("fix(gui): first on develop", change="gui.txt")
+ self.git("checkout", "-qb", "release/3.3")
+ self.git("tag", "v3.3.0-beta1")
+ self.git("checkout", "-q", "release/3.2")
+ self.git("cherry-pick", original)
+ self.commit("fix: only on release/3.2")
+ self.git("tag", "v3.2.0")
+ self.git("checkout", "-q", "develop")
+ self.merge("v3.2.0", "Merge 3.2.0 into develop")
+ self.commit("fix: new on develop")
+ self.git("checkout", "-q", "release/3.3")
+ self.merge("develop", "Merge develop into release/3.3")
+ self.git("tag", "v3.3.0-beta2")
+ notes = self.notes("v3.3.0-beta2")
+ self.assertTrue(notes.startswith("## Changes since v3.3.0-beta1\n"))
+ self.assertIn("### Fixes\n- new on develop (Test Author)\n\n", notes)
+ self.assertNotIn("first on develop", notes)
+ self.assertNotIn("only on release/3.2", notes)
+
+ def test_copies_that_a_merged_back_ga_shipped_are_not_listed_again(self):
+ self.git("checkout", "-qb", "release/3.2")
+ self.commit("fix: on release/3.2 before the picks")
+ self.git("tag", "v3.2.0-rc1")
+ self.git("checkout", "-q", "develop")
+ self.git("checkout", "-qb", "release/3.3")
+ self.git("tag", "v3.3.0-beta1")
+ self.git("checkout", "-q", "develop")
+ original = self.commit("fix(gui): develop original shipped in 3.2.0", change="gui.txt")
+ self.git("checkout", "-q", "release/3.2")
+ self.git("cherry-pick", original)
+ port = self.commit("fix(cat): made on release/3.2 first", change="cat.txt")
+ self.git("tag", "v3.2.0")
+ self.git("checkout", "-q", "develop")
+ self.git("cherry-pick", port)
+ self.merge("v3.2.0", "Merge 3.2.0 into develop")
+ self.commit("fix: new on develop")
+ self.git("checkout", "-q", "release/3.3")
+ self.merge("develop", "Merge develop into release/3.3")
+ self.git("tag", "v3.3.0-beta2")
+ self.git("tag", "v3.3.0")
+ for tag in ("v3.3.0-beta2", "v3.3.0"):
+ notes = self.notes(tag)
+ self.assertIn("### Fixes\n- new on develop (Test Author)\n\n", notes, tag)
+ self.assertNotIn("develop original", notes, tag)
+ self.assertNotIn("made on release/3.2 first", notes, tag)
+
+ def test_a_ga_lists_everything_since_the_previous_ga(self):
+ self.git("tag", "v3.2.0")
+ self.git("checkout", "-qb", "release/3.3")
+ self.commit("feat: from beta1")
+ self.git("tag", "v3.3.0-beta1")
+ self.commit("fix: from rc1")
+ self.git("tag", "v3.3.0-rc1")
+ self.commit("fix: from GA")
+ self.git("tag", "v3.3.0")
+ notes = self.notes("v3.3.0")
+ self.assertTrue(notes.startswith("## Changes since v3.2.0\n"))
+ for change in ("from beta1", "from rc1", "from GA"):
+ self.assertIn(change, notes)
+ self.commit("fix: patch")
+ self.git("tag", "v3.3.1-rc1")
+ self.git("tag", "v3.3.1")
+ patch = self.notes("v3.3.1")
+ self.assertTrue(patch.startswith("## Changes since v3.3.0\n"))
+ self.assertIn("- patch", patch)
+ self.assertNotIn("from GA", patch)
+ self.assertEqual(self.notes("v3.3.0"), notes)
+
+ def test_entries_are_grouped_cleaned_and_counted(self):
+ self.git("tag", "v3.3.0-beta1")
+ self.commit("feat(jtty)!: change the macro syntax")
+ self.commit("Fix(gui): uppercase type (#458)")
+ self.commit("fix: address PR #569 review for @k1jt")
+ self.commit("perf(fft): use SIMD")
+ self.commit("fix(gui): uppercase type (#458)")
+ self.commit("fix(jtty, tests): user-facing despite a test scope")
+ self.commit("fix(release): pipeline change")
+ self.commit("feat(ci, tests): pipeline feature")
+ self.commit("test: cover the decoder")
+ self.commit("Untyped subject that mentions fix")
+ self.git("checkout", "-qb", "topic")
+ self.commit("docs: topic change")
+ self.git("checkout", "-q", "develop")
+ self.merge("topic", "Merge pull request #12 from topic")
+ self.git("tag", "v3.3.0-beta2")
+ notes = self.notes("v3.3.0-beta2")
+ self.assertIn("### New features\n- jtty: change the macro syntax (breaking) (Test Author)\n\n", notes)
+ self.assertIn(
+ "### Fixes\n"
+ "- gui: uppercase type (Test Author)\n"
+ "- address PR `#569` review for `@k1jt` (Test Author)\n"
+ "- jtty, tests: user-facing despite a test scope (Test Author)\n\n",
+ notes,
+ )
+ self.assertIn("### Performance\n- fft: use SIMD (Test Author)\n", notes)
+ self.assertNotIn("pipeline", notes)
+ self.assertNotIn("Merge pull request", notes)
+ self.assertIn("Plus 5 other commits: [full comparison]", notes)
+
+ def test_references_are_neutralized_outside_code_spans_only(self):
+ self.git("tag", "v3.3.0-beta1")
+ for subject in (
+ "fix: mail ops@example.com about C# and see https://example.com/docs/#anchor",
+ "fix: link WSJTX/wsjtx-internal#569, GH-12 and Hamlib/Hamlib#1940",
+ "fix: keep `a #12 @b` and <CR> literal",
+ "fix(@team): scope reference",
+ "fix: handle a lone ` in macros, see #12 and @k1jt",
+ ):
+ self.commit(subject)
+ self.git("tag", "v3.3.0-beta2")
+ notes = self.notes("v3.3.0-beta2")
+ self.assertIn("- mail ops@example.com about C# and see https://example.com/docs/#anchor (Test Author)\n", notes)
+ self.assertIn("- link `WSJTX/wsjtx-internal#569`, `GH-12` and `Hamlib/Hamlib#1940` (Test Author)\n", notes)
+ self.assertIn("- keep `a #12 @b` and &lt;CR> literal (Test Author)\n", notes)
+ self.assertIn("- `@team`: scope reference (Test Author)\n", notes)
+ self.assertIn("- handle a lone ` in macros, see `#12` and `@k1jt` (Test Author)\n", notes)
+
+ def test_a_range_without_listed_changes_says_so(self):
+ self.git("tag", "v3.3.0-beta1")
+ self.commit("test: only tests")
+ self.git("tag", "v3.3.0-beta2")
+ self.assertIn("\nNo user-facing changes; 1 other commit: [full comparison]", self.notes("v3.3.0-beta2"))
+ self.git("tag", "v3.3.0-beta3")
+ notes = self.notes("v3.3.0-beta3")
+ self.assertTrue(notes.startswith("## Changes since v3.3.0-beta2\n"))
+ self.assertIn("No source changes since v3.3.0-beta2.", notes)
+
+ def test_no_earlier_release_tag_prints_nothing(self):
+ for tag in ("not-a-release", "build/v3.2.0-rc1", "v3.2", "v3.2.0-alpha1", "v3.3.0-beta1"):
+ self.git("tag", tag)
+ self.assertEqual(self.notes("v3.3.0-beta1"), "")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.github/scripts/tests/test_ghcr_retention.py b/.github/scripts/tests/test_ghcr_retention.py
index 9bffad2d..57232eba 100755
--- a/.github/scripts/tests/test_ghcr_retention.py
+++ b/.github/scripts/tests/test_ghcr_retention.py
@@ -51,11 +51,22 @@ class RetentionPlanTests(unittest.TestCase):
version(1, 100, ("stable", "build-20260101-1-1"), self.now),
version(2, 100, ("debug",), self.now),
version(3, 100, (), self.now),
+ version(4, 100, ("buildcache",), self.now),
]
plan = self.plan(versions, keep=1)
self.assertEqual(plan[1].reason, "stable")
self.assertEqual(plan[2].reason, "unknown-or-untagged")
self.assertEqual(plan[3].reason, "unknown-or-untagged")
+ self.assertEqual(plan[4].reason, "unknown-or-untagged")
+ self.assertFalse(plan[4].delete)
+
+ def test_prepared_release_tags_are_not_disposable_generations(self):
+ plan = self.plan([
+ version(1, 100, ("release-deps-validated-build-20260101-1-1",), self.now),
+ version(2, 100, ("build-20260101-2-1", "release-deps-validated-build-20260101-2-1"), self.now),
+ ], keep=0)
+ self.assertFalse(plan[1].delete)
+ self.assertFalse(plan[2].delete)
def test_exact_sixty_day_boundary_is_kept(self):
plan = self.plan([version(1, 60, ("candidate-1-1",), self.now)], keep=1)
diff --git a/.github/scripts/tests/test_linux_ccache_policy.py b/.github/scripts/tests/test_linux_ccache_policy.py
index 42c97e01..4a6ff3d8 100644
--- a/.github/scripts/tests/test_linux_ccache_policy.py
+++ b/.github/scripts/tests/test_linux_ccache_policy.py
@@ -1,4 +1,5 @@
import pathlib
+import re
import unittest
@@ -9,6 +10,32 @@ class LinuxCcachePolicyTests(unittest.TestCase):
def read(self, relative_path):
return (REPOSITORY / relative_path).read_text(encoding="utf-8")
+ def sanitizer_step(self, name):
+ action = self.read(".github/actions/build-linux-sanitizers/action.yml")
+ match = re.search(
+ rf"^ - name: {re.escape(name)}\n(?P<body>.*?)(?=^ - |\Z)",
+ action,
+ re.MULTILINE | re.DOTALL,
+ )
+ self.assertIsNotNone(match, name)
+ return match.group("body")
+
+ def armhf_job(self, name):
+ workflow = self.read(".github/workflows/build-linux.yml")
+ body = workflow.split(f"\n {name}:\n", 1)[1]
+ following = re.search(r"\n [A-Za-z0-9_-]+:\n", body)
+ return body[:following.start() + 1] if following else body
+
+ def armhf_step(self, name, job="build-armhf"):
+ workflow = self.armhf_job(job)
+ match = re.search(
+ rf"^ - name: {re.escape(name)}\n(?P<body>.*?)(?=^ - |\Z)",
+ workflow,
+ re.MULTILINE | re.DOTALL,
+ )
+ self.assertIsNotNone(match, name)
+ return match.group("body")
+
def assert_cache_tiers(self, text, prefix):
primary = (
f"{prefix}${{{{ steps.image.outputs.ccache_compatibility_id }}}}-"
@@ -42,6 +69,63 @@ class LinuxCcachePolicyTests(unittest.TestCase):
action,
)
+ def test_sanitizer_save_requires_trusted_successful_build(self):
+ action = self.read(".github/actions/build-linux-sanitizers/action.yml")
+ save = self.sanitizer_step("Save sanitizer objects")
+ for condition in (
+ "inputs.save_ccache == 'true'",
+ "github.ref == 'refs/heads/develop'",
+ "steps.image.outputs.recipe_match == 'true'",
+ "steps.ccache.outputs.cache-hit != 'true'",
+ ):
+ self.assertIn(condition, save)
+ self.assertNotIn("always()", save)
+ self.assertNotIn("!cancelled()", save)
+ self.assertIn("key: ${{ steps.ccache.outputs.cache-primary-key }}", save)
+ self.assertIn("path: ${{ steps.sanitizer.outputs.ccache_dir }}", save)
+ self.assertLess(
+ action.index("- name: Require sanitizer tests to pass"),
+ action.index("- name: Save sanitizer objects"),
+ )
+
+ def test_sanitizer_tests_remain_enabled_by_default(self):
+ workflow = self.read(".github/workflows/build-linux-sanitizers.yml")
+ action = self.read(".github/actions/build-linux-sanitizers/action.yml")
+ self.assertRegex(
+ workflow,
+ r" run_tests:\n(?: .*\n)*? type: boolean\n default: true",
+ )
+ self.assertRegex(
+ action,
+ r' run_tests:\n(?: .*\n)*? default: "true"',
+ )
+ self.assertIn("run_tests: ${{ inputs.run_tests }}", workflow)
+ self.assertIn("inputs.sanitizer == 'tsan' && 180 || 60", workflow)
+
+ def test_build_only_sanitizer_keeps_test_targets_and_instrumentation(self):
+ configure = self.sanitizer_step("Configure sanitizer build")
+ self.assertIn("-DWSJT_ENABLE_TESTS=ON", configure)
+ self.assertIn("-DWSJT_ENABLE_GUI_SMOKE_TESTS=ON", configure)
+ for name in (
+ "Configure sanitizer build",
+ "Build sanitizer targets",
+ "Verify sanitizer instrumentation",
+ ):
+ self.assertNotIn("inputs.run_tests", self.sanitizer_step(name))
+ for name in (
+ "Prepare test scratch directory",
+ "Run tests",
+ "Publish test summary",
+ "Upload test results",
+ "Require sanitizer tests to pass",
+ ):
+ with self.subTest(step=name):
+ self.assertIn("inputs.run_tests == 'true'", self.sanitizer_step(name))
+ enforce = self.sanitizer_step("Require sanitizer tests to pass")
+ self.assertIn("always()", enforce)
+ self.assertIn('steps.ctest.outcome }}" != "success"', enforce)
+ self.assertIn("exit 1", enforce)
+
def test_sanitizer_cache_keeps_profile_and_generation(self):
action = self.read(".github/actions/build-linux-sanitizers/action.yml")
self.assert_cache_tiers(
@@ -52,10 +136,6 @@ class LinuxCcachePolicyTests(unittest.TestCase):
'export CCACHE_COMPILERCHECK="${{ steps.image.outputs.ccache_compiler_check }}"',
action,
)
- self.assertIn(
- "if: inputs.save_ccache == 'true' && steps.image.outputs.recipe_match == 'true' && steps.ccache.outputs.cache-hit != 'true'",
- action,
- )
def test_armhf_verifies_and_forwards_cache_identity(self):
workflow = self.read(".github/workflows/build-linux.yml")
@@ -72,7 +152,7 @@ class LinuxCcachePolicyTests(unittest.TestCase):
workflow.count(
"RUNTIME_IMAGE: ${{ needs.resolve-image.outputs.image_reference }}"
),
- 2,
+ 4,
)
self.assertIn("build-linux-armhf-cross.sh", workflow)
self.assertIn("validate-linux-armhf-runtime.sh", workflow)
@@ -83,16 +163,109 @@ class LinuxCcachePolicyTests(unittest.TestCase):
self.assertIn("cross_recipe_match", workflow)
self.assertIn("runtime_recipe_match", workflow)
self.assertIn(
- "if: inputs.save_ccache && steps.image.outputs.recipe_match == 'true' && steps.ccache.outputs.cache-hit != 'true'",
+ "if: inputs.save_ccache && (!inputs.armhf_build_only || github.ref == 'refs/heads/develop') && steps.image.outputs.recipe_match == 'true' && steps.ccache.outputs.cache-hit != 'true'",
workflow,
)
- def test_release_accepts_separately_promoted_armhf_recipe(self):
+ def test_armhf_build_only_preserves_compilation_audits_and_pair_verification(self):
+ workflow = self.read(".github/workflows/build-linux.yml")
+ self.assertEqual(len(re.findall(
+ r" armhf_build_only:\n(?: .*\n)*? type: boolean\n default: false",
+ workflow,
+ )), 2)
+ self.assertIn('if [ "$ARMHF_BUILD_ONLY" = true ] && [ "$ARCH" != armhf ]; then', workflow)
+ for name in ("Inspect ARMHF image pair", "Cross-build ARMHF binaries"):
+ self.assertNotIn("if:", self.armhf_step(name))
+ compile_step = self.armhf_step("Cross-build ARMHF binaries")
+ self.assertIn("ARMHF_BUILD_ONLY: ${{ inputs.armhf_build_only }}", compile_step)
+ self.assertIn("-e ARMHF_BUILD_ONLY", compile_step)
+ script = self.read(".github/scripts/build-linux-armhf-cross.sh")
+ self.assertIn("-DWSJT_ENABLE_TESTS=ON", script)
+ skip_install = script.index('if [ "$ARMHF_BUILD_ONLY" = true ]; then', script.index("cmake --build"))
+ for audit in ("validate_linux_build_executables", ".github/scripts/audit-armhf-cross-build.sh"):
+ self.assertLess(script.index(audit), skip_install)
+ self.assertLess(skip_install, script.index("cmake --install"))
+ self.assertIn("exit 0", script[skip_install:script.index("cmake --install")])
+
+ def test_armhf_build_only_skips_runtime_and_artifact_steps(self):
+ test_job = self.armhf_job("test-armhf")
+ self.assertIn(" if: inputs.arch == 'armhf' && !inputs.armhf_build_only\n", test_job)
+ for name in (
+ "Test and package on native ARMv7", "Publish armhf test summary",
+ "Upload armhf AppImage startup diagnostics", "Upload .deb", "Upload RPM",
+ "Upload AppImage", "Upload build artifacts", "Upload test results",
+ "Upload release tarballs",
+ ):
+ with self.subTest(step=name):
+ self.assertIn(f" - name: {name}\n", test_job)
+ self.assertNotIn(f" - name: {name}\n", self.armhf_job("build-armhf"))
+ for name in ("Pack ARMHF build tree", "Upload ARMHF build tree"):
+ with self.subTest(step=name):
+ self.assertIn("if: ${{ !inputs.armhf_build_only }}", self.armhf_step(name))
+
+ def test_armhf_runtime_runs_natively_on_an_arm_runner_from_the_cross_build_tree(self):
+ build_job = self.armhf_job("build-armhf")
+ test_job = self.armhf_job("test-armhf")
+ self.assertIn(" runs-on: ubuntu-24.04\n", build_job)
+ self.assertIn(" runs-on: ubuntu-24.04-arm\n", test_job)
+ self.assertIn(" needs: [resolve-image, build-armhf]\n", test_job)
+ self.assertNotIn("setup-qemu-action", test_job)
+ self.assertNotIn("validate-linux-armhf-runtime.sh", build_job)
+ self.assertIn("bash .github/scripts/validate-linux-armhf-runtime.sh", self.armhf_step("Test and package on native ARMv7", "test-armhf"))
+ pack = self.armhf_step("Pack ARMHF build tree")
+ self.assertIn(
+ "sudo tar --create --file armhf-build-tree.tar --exclude='wsjtx-build/*.o' --exclude='wsjtx-build/*.a' wsjtx-build AppDir\n",
+ pack,
+ )
+ self.assertLess(build_job.index("- name: Save armhf ccache"), build_job.index("- name: Pack ARMHF build tree"))
+ for step in ("actions/checkout@", "docker/login-action@"):
+ self.assertIn(step, test_job)
+ self.assertLess(test_job.index("docker/login-action@"), test_job.index("- name: Require native 32-bit ARM execution"))
+ self.assertLess(test_job.index("- name: Require native 32-bit ARM execution"), test_job.index("- name: Download ARMHF build tree"))
+ preflight = self.armhf_step("Require native 32-bit ARM execution", "test-armhf")
+ self.assertIn("grep -Eq '^CPU op-mode\\(s\\):.*32-bit'", preflight)
+ self.assertIn("/proc/sys/fs/binfmt_misc/qemu-arm", preflight)
+ self.assertIn('docker run --rm --platform linux/arm/v7 "$RUNTIME_IMAGE" getconf LONG_BIT', preflight)
+ runtime_step = self.armhf_step("Test and package on native ARMv7", "test-armhf")
+ for fragment in ("docker run --rm --platform linux/arm/v7", '-v "${GITHUB_WORKSPACE}:/work"', "-w /work", "-e ARMHF_RUNTIME_PHASE"):
+ self.assertIn(fragment, runtime_step)
+ for name in ("Publish armhf test summary", "Upload test results"):
+ self.assertIn(" if: always()\n", self.armhf_step(name, "test-armhf"))
+ for name, artifact in (
+ ("Upload .deb", "wsjtx-${{ inputs.version }}-linux-armhf-deb"),
+ ("Upload RPM", "wsjtx-${{ inputs.version }}-linux-armhf-rpm"),
+ ("Upload AppImage", "wsjtx-${{ inputs.version }}-linux-armhf-AppImage"),
+ ):
+ self.assertIn(f" name: {artifact}\n", self.armhf_step(name, "test-armhf"))
+ self.assertIn("name: armhf-build-tree\n", self.armhf_step("Upload ARMHF build tree"))
+ self.assertIn("name: armhf-build-tree\n", self.armhf_step("Download ARMHF build tree", "test-armhf"))
+ self.assertIn("tar --extract --file armhf-build-tree.tar", self.armhf_step("Unpack ARMHF build tree", "test-armhf"))
+ self.assertLess(test_job.index("- name: Unpack ARMHF build tree"), test_job.index("- name: Test and package on native ARMv7"))
+ runtime = self.read(".github/scripts/validate-linux-armhf-runtime.sh")
+ self.assertIn("ctest --parallel 3 --output-on-failure", runtime)
+ self.assertNotIn("--exclude-regex", runtime)
+
+ def test_armhf_build_only_save_requires_trusted_successful_audits(self):
+ save = self.armhf_step("Save armhf ccache")
+ self.assertIn("(!inputs.armhf_build_only || github.ref == 'refs/heads/develop')", save)
+ self.assertIn("inputs.save_ccache", save)
+ self.assertIn("steps.image.outputs.recipe_match == 'true'", save)
+ self.assertIn("steps.ccache.outputs.cache-hit != 'true'", save)
+ self.assertIn("key: ${{ steps.ccache.outputs.cache-primary-key }}", save)
+ self.assertNotIn("always()", save)
+ self.assertNotIn("!cancelled()", save)
+ build_job = self.armhf_job("build-armhf")
+ self.assertLess(build_job.index("- name: Cross-build ARMHF binaries"), build_job.index("- name: Save armhf ccache"))
+
+ def test_release_requires_pinned_armhf_pair_without_stale_recipe_fallback(self):
workflow = self.read(".github/workflows/release.yml")
armhf_job = workflow.split(" linux-armhf:\n", 1)[1].split(
"\n windows:\n", 1
)[0]
- self.assertIn("allow_stale_image: true", armhf_job)
+ self.assertNotIn("allow_stale_image: true", armhf_job)
+ self.assertIn("image_source: public-release", armhf_job)
+ self.assertIn("image_digest: ${{ needs.prepare.outputs.armhf_digest }}", armhf_job)
+ self.assertIn("armhf_cross_image_digest: ${{ needs.prepare.outputs.armhf_cross_digest }}", armhf_job)
if __name__ == "__main__":
diff --git a/.github/scripts/tests/test_linux_image_publication_policy.py b/.github/scripts/tests/test_linux_image_publication_policy.py
index cb88ac95..57d0ce1f 100644
--- a/.github/scripts/tests/test_linux_image_publication_policy.py
+++ b/.github/scripts/tests/test_linux_image_publication_policy.py
@@ -1,5 +1,10 @@
+import fnmatch
+import os
import pathlib
import re
+import subprocess
+import tempfile
+import textwrap
import unittest
@@ -10,10 +15,10 @@ WARM = (ROOT / ".github/workflows/warm-dependency-caches.yml").read_text()
CLASSIFIER = (ROOT / ".github/scripts/is-linux-ci-image-input.sh").read_text()
-def job(name: str) -> str:
+def job(name: str, workflow: str = PUBLISH) -> str:
match = re.search(
rf"^ {re.escape(name)}:\n(?P<body>.*?)(?=^ [a-z][a-z0-9-]*:\n|\Z)",
- PUBLISH,
+ workflow,
re.MULTILINE | re.DOTALL,
)
if not match:
@@ -22,6 +27,219 @@ def job(name: str) -> str:
class LinuxImagePublicationPolicyTests(unittest.TestCase):
+ def test_armhf_cross_cache_import_and_export_share_registry_destination(self):
+ metadata = job("metadata")
+ for package_root in ("ghcr.io/wsjtx/wsjtx", "ghcr.io/wsjtx/wsjtx-internal"):
+ self.assertIn(
+ f"armhf_cross_cache_from=type=registry,ref={package_root}/linux-armhf-cross-bookworm:buildcache",
+ metadata,
+ )
+ cross = job("build-armhf-cross")
+ self.assertIn("cache-from: ${{ needs.metadata.outputs.armhf_cross_cache_from }}", cross)
+ self.assertIn(
+ "cache-to: type=registry,ref=${{ needs.metadata.outputs.package_root }}/linux-armhf-cross-bookworm:buildcache,mode=max",
+ cross,
+ )
+
+ def select_warmers(self, event, *, target="", schedule="", paths=()):
+ selector = re.search(
+ r" run: \|\n(?P<body>.*?)(?=^ refresh-linux-images:)",
+ WARM,
+ re.MULTILINE | re.DOTALL,
+ ).group("body")
+ git_stub = """
+git() {
+ case "$1" in
+ cat-file) return 0 ;;
+ diff) printf '%s\\n' "$CHANGED_PATHS" ;;
+ *) return 2 ;;
+ esac
+}
+"""
+ with tempfile.TemporaryDirectory() as directory:
+ output = pathlib.Path(directory) / "output"
+ result = subprocess.run(
+ ["bash", "-c", git_stub + textwrap.dedent(selector)],
+ cwd=ROOT,
+ env={
+ **os.environ,
+ "EVENT_NAME": event,
+ "TARGETS": target,
+ "SCHEDULE": schedule,
+ "BEFORE_SHA": "previous",
+ "CURRENT_SHA": "current",
+ "CHANGED_PATHS": "\n".join(paths),
+ "HAMLIB_BRANCH": "4.7.2",
+ "GITHUB_OUTPUT": str(output),
+ "GITHUB_STEP_SUMMARY": str(pathlib.Path(directory) / "summary"),
+ },
+ capture_output=True,
+ text=True,
+ timeout=10,
+ )
+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+ return dict(line.split("=", 1) for line in output.read_text().splitlines())
+
+ def test_macos_warmer_selection_routes_both_architectures(self):
+ cases = [
+ ({"event": "workflow_dispatch", "target": "macos-x86_64"}, "false", "true"),
+ ({"event": "workflow_dispatch", "target": "macos-arm64"}, "true", "false"),
+ ({"event": "workflow_dispatch", "target": "macos"}, "true", "true"),
+ ({"event": "workflow_dispatch", "target": "all"}, "true", "true"),
+ ({"event": "workflow_dispatch", "target": "linux"}, "false", "false"),
+ ({"event": "schedule", "schedule": "23 10 * * 1"}, "true", "true"),
+ ]
+ for path in (
+ ".github/workflows/build-macos.yml", ".github/actions/warm-macos-deps/action.yml",
+ ".github/scripts/install-xpack-gfortran-macos.sh", ".github/scripts/build-qt-macos.sh",
+ ".github/scripts/macos-qt-cache-key.sh", ".github/scripts/verify-macos-static-archives.sh",
+ ".github/workflows/ci.yml", ".github/workflows/release.yml",
+ ):
+ cases.append(({"event": "push", "paths": [path]}, "true", "true"))
+ for inputs, arm, intel in cases:
+ with self.subTest(inputs=inputs):
+ outputs = self.select_warmers(**inputs)
+ self.assertEqual(outputs["macos_arm64"], arm)
+ self.assertEqual(outputs["macos_x86_64"], intel)
+
+ def test_asan_warmer_selection(self):
+ cases = [
+ ({"event": "schedule", "schedule": "23 10 * * 1"}, "true", "none"),
+ ({"event": "workflow_dispatch", "target": "linux-asan-ubsan"}, "true", "none"),
+ ({"event": "workflow_dispatch", "target": "all"}, "true", "normal"),
+ ({"event": "workflow_dispatch", "target": "linux-tsan"}, "false", "tsan"),
+ ({"event": "push", "paths": [".github/scripts/build-hamlib-linux.sh"]}, "false", "normal"),
+ ({"event": "push", "paths": [".github/scripts/build-qt-tsan-linux.sh"]}, "false", "tsan"),
+ ({"event": "push", "paths": ["CMakeLists.txt", ".github/scripts/verify-linux-ci-image.sh"]}, "true", "normal-and-tsan"),
+ ({"event": "push", "paths": ["mainwindow.cpp"]}, "false", "none"),
+ ]
+ for arguments, selected, image_set in cases:
+ with self.subTest(arguments=arguments):
+ outputs = self.select_warmers(**arguments)
+ self.assertEqual(outputs["linux_asan_ubsan"], selected)
+ self.assertEqual(outputs["image_set"], image_set)
+
+ def test_armhf_warmer_selection(self):
+ cases = [
+ ({"event": "schedule", "schedule": "23 10 * * 1"}, "true", "none"),
+ ({"event": "workflow_dispatch", "target": "linux-armhf"}, "true", "none"),
+ ({"event": "workflow_dispatch", "target": "all"}, "true", "normal"),
+ ({"event": "workflow_dispatch", "target": "linux-tsan"}, "false", "tsan"),
+ ({"event": "push", "paths": [".github/images/linux-ci/Dockerfile.armhf-cross"]}, "false", "normal"),
+ ({"event": "push", "paths": ["mainwindow.cpp"]}, "false", "none"),
+ ]
+ for arguments, selected, image_set in cases:
+ with self.subTest(arguments=arguments):
+ outputs = self.select_warmers(**arguments)
+ self.assertEqual(outputs["linux_armhf"], selected)
+ self.assertEqual(outputs["image_set"], image_set)
+
+ def test_armhf_build_inputs_select_warming(self):
+ push_filters = re.findall(r'^ - "([^"]+)"$', WARM.split(" schedule:", 1)[0], re.MULTILINE)
+ for path in (
+ ".github/workflows/build-linux.yml",
+ ".github/scripts/build-linux-armhf-cross.sh",
+ ".github/scripts/audit-armhf-cross-build.sh",
+ ".github/cmake/armhf-toolchain.cmake",
+ ".github/scripts/linux-artifact-validation.sh",
+ "CMakeLists.txt", "CMake/Sources.cmake", "tests/unit/CMakeLists.txt",
+ ):
+ with self.subTest(path=path):
+ self.assertTrue(any(fnmatch.fnmatchcase(path, pattern) for pattern in push_filters))
+ outputs = self.select_warmers("push", paths=[path])
+ self.assertEqual(outputs["linux_armhf"], "true")
+ self.assertEqual(outputs["image_set"], "none")
+
+ def test_armhf_warmers_share_configuration_and_serialize(self):
+ standalone = job("warm-linux-armhf-ccache", WARM)
+ published = job("warm-armhf-ccache")
+ for warmer in (standalone, published):
+ for required in (
+ "github.ref == 'refs/heads/develop'",
+ "uses: ./.github/workflows/build-linux.yml", "arch: armhf",
+ "armhf_build_only: true", "allow_stale_image: false",
+ "recache: false", "save_ccache: true",
+ "group: armhf-ccache-develop", "cancel-in-progress: false",
+ "contents: read", "packages: read",
+ ):
+ self.assertIn(required, warmer)
+ self.assertNotIn("packages: write", warmer)
+ for condition in (
+ "needs.detect.outputs.linux_armhf == 'true'",
+ "needs.detect.outputs.image_set != 'normal'",
+ "needs.detect.outputs.image_set != 'normal-and-tsan'",
+ ):
+ self.assertIn(condition, standalone)
+ self.assertIn("- warm-linux-armhf-ccache", job("summary", WARM))
+ for condition in (
+ "needs.promote.result == 'success'", "inputs.publication_target == 'internal'",
+ "inputs.mode == 'refresh'", "inputs.promote", "inputs.include_armhf",
+ "(inputs.image_set == 'normal' || inputs.image_set == 'normal-and-tsan')",
+ "image_tag: ${{ needs.metadata.outputs.build_tag }}",
+ ):
+ self.assertIn(condition, published)
+ self.assertIn("- metadata", published)
+ self.assertIn("- promote", published)
+ self.assertNotIn("warm-armhf-ccache", job("promote"))
+
+ def test_sanitizer_build_inputs_select_warming(self):
+ push_filters = re.findall(
+ r'^ - "([^"]+)"$',
+ WARM.split(" schedule:", 1)[0],
+ re.MULTILINE,
+ )
+ for path in (
+ ".github/workflows/build-linux-sanitizers.yml",
+ ".github/actions/build-linux-sanitizers/action.yml",
+ ".github/scripts/verify-sanitizer-instrumentation.py",
+ "CMakeLists.txt",
+ "CMake/Sources.cmake",
+ "tests/CMakeLists.txt",
+ "tests/unit/CMakeLists.txt",
+ ):
+ with self.subTest(path=path):
+ self.assertTrue(any(fnmatch.fnmatchcase(path, pattern) for pattern in push_filters))
+ outputs = self.select_warmers("push", paths=[path])
+ self.assertEqual(outputs["linux_asan_ubsan"], "true")
+ self.assertEqual(outputs["image_set"], "none")
+
+ def test_asan_warmers_share_configuration_and_serialize(self):
+ standalone = job("warm-linux-asan-ubsan-ccache", WARM)
+ published = job("warm-asan-ubsan-ccache")
+ for warmer in (standalone, published):
+ with self.subTest(warmer=warmer):
+ for required in (
+ "github.ref == 'refs/heads/develop'",
+ "uses: ./.github/workflows/build-linux-sanitizers.yml",
+ "sanitizer: asan-ubsan",
+ "run_tests: false",
+ "recache: false",
+ "save_ccache: true",
+ "allow_stale_image: false",
+ "group: asan-ubsan-ccache-develop",
+ "cancel-in-progress: false",
+ "contents: read",
+ "packages: read",
+ ):
+ self.assertIn(required, warmer)
+ self.assertNotIn("packages: write", warmer)
+ self.assertIn("needs.detect.outputs.linux_asan_ubsan == 'true'", standalone)
+ self.assertIn("needs.detect.outputs.image_set != 'normal'", standalone)
+ self.assertIn("needs.detect.outputs.image_set != 'normal-and-tsan'", standalone)
+ self.assertIn("- warm-linux-asan-ubsan-ccache", job("summary", WARM))
+
+ def test_asan_warming_follows_internal_promotion_without_gating_it(self):
+ warm = job("warm-asan-ubsan-ccache")
+ self.assertIn("metadata", warm)
+ self.assertIn("promote", warm)
+ self.assertIn("needs.promote.result == 'success'", warm)
+ self.assertIn("inputs.publication_target == 'internal'", warm)
+ self.assertIn("inputs.mode == 'refresh'", warm)
+ self.assertIn("inputs.promote", warm)
+ self.assertIn("(inputs.image_set == 'normal' || inputs.image_set == 'normal-and-tsan')", warm)
+ self.assertIn("image_tag: ${{ needs.metadata.outputs.build_tag }}", warm)
+ self.assertNotIn("warm-asan-ubsan-ccache", job("promote"))
+
def test_public_release_publication_is_tag_scoped_and_complete(self):
validate = job("validate-inputs")
self.assertIn('[ "$REQUEST_REPOSITORY" != WSJTX/wsjtx ]', validate)
@@ -177,5 +395,35 @@ class LinuxImagePublicationPolicyTests(unittest.TestCase):
self.assertIn("stable_packages+=(linux-noble)", rollback)
+ def test_release_paths_consume_the_same_committed_selection(self):
+ candidate = (ROOT / ".github/workflows/release.yml").read_text()
+ public = (ROOT / ".github/workflows/public-release.yml").read_text()
+ tagging = (ROOT / ".github/workflows/release-tag-helper.yml").read_text()
+ promotion = (ROOT / ".github/workflows/promote-release.yml").read_text()
+ for workflow in (candidate, public):
+ self.assertIn("release-linux-images.py validate release-linux-images.json", workflow)
+ self.assertIn('--check-remote --github-output "$GITHUB_OUTPUT"', workflow)
+ self.assertEqual(workflow.count("image_source: public-release"), 3)
+ for output in ("x86_64_digest", "aarch64_digest", "armhf_digest", "armhf_cross_digest"):
+ self.assertIn("needs.prepare.outputs." + output, workflow)
+ self.assertNotIn("allow_stale_image: true", workflow)
+ self.assertNotIn("resolve-linux-ci-image-tag.py", workflow)
+ self.assertNotIn("publish-linux-ci-images.yml", public)
+ self.assertNotIn("packages: write", public)
+ self.assertIn(
+ "environment: ${{ needs.prepare.outputs.release_channel == 'BETA' && 'beta-release' || 'public-release' }}",
+ public,
+ )
+ self.assertIn("linux_images: $linux_images", candidate)
+ self.assertIn("release-linux-images.py provenance release-linux-images.json", candidate)
+ self.assertIn("release-linux-images.py verify-provenance", promotion)
+ self.assertLess(tagging.index("release-linux-images.py validate"), tagging.index("- name: Create candidate tag"))
+
+ def test_prepared_image_consumption_keeps_source_and_recipe_guards(self):
+ self.assertIn("WSJTX/wsjtx:refs/tags/v*|WSJTX/wsjtx-internal:refs/heads/release/*", BUILD)
+ self.assertIn('if [ "$ALLOW_STALE_IMAGE" = true ]; then', BUILD)
+ self.assertIn("Prepared public images require strict recipe verification", BUILD)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/.github/scripts/tests/test_native_cache_policy.py b/.github/scripts/tests/test_native_cache_policy.py
new file mode 100644
index 00000000..274344c6
--- /dev/null
+++ b/.github/scripts/tests/test_native_cache_policy.py
@@ -0,0 +1,86 @@
+import importlib.util
+import pathlib
+import os
+import subprocess
+import sys
+import re
+import unittest
+
+ROOT = pathlib.Path(__file__).resolve().parents[3]
+SPEC = importlib.util.spec_from_file_location(
+ "summary", ROOT / ".github/scripts/summarize-native-caches.py")
+summary = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(summary)
+
+
+class NativeCachePolicyTests(unittest.TestCase):
+ def test_compiler_only_command(self):
+ result = subprocess.run(
+ [sys.executable, str(SPEC.origin), "--compiler"],
+ env={**os.environ, "CACHE_STEPS": "{}", "COLD_BUILD": "true"},
+ capture_output=True, text=True, check=True)
+ self.assertIn("| Compiler objects | bypassed (cold build) | not run |", result.stdout)
+
+ def test_unknown_dependency_is_rejected(self):
+ result = subprocess.run(
+ [sys.executable, str(SPEC.origin), "unknown"],
+ env={**os.environ, "CACHE_STEPS": "{}"},
+ capture_output=True, text=True)
+ self.assertEqual(result.returncode, 2)
+ self.assertIn("unknown dependency: unknown", result.stderr)
+
+ def test_restore_outcomes(self):
+ cases = [
+ ({}, "not run"),
+ ({"outcome": "failure"}, "failure"),
+ ({"outcome": "cancelled"}, "cancelled"),
+ ({"outcome": "success", "outputs": {"cache-hit": "true"}}, "exact hit"),
+ ({"outcome": "success", "outputs": {"cache-hit": "false", "cache-matched-key": "older"}}, "fallback restore"),
+ ({"outcome": "success", "outputs": {"cache-hit": ""}}, "miss"),
+ ]
+ for step, expected in cases:
+ with self.subTest(expected=expected):
+ self.assertEqual(summary.restore_status(step, False), expected)
+ self.assertEqual(summary.restore_status({}, True), "bypassed (cold build)")
+
+ def test_failed_rebuild_and_forced_recompilation_are_distinct(self):
+ report = summary.render({
+ "qt-cache": {"outcome": "success"},
+ "qt-build": {"outcome": "failure"},
+ "ccache": {"outcome": "success", "outputs": {"cache-hit": "true"}},
+ "compile": {"outcome": "skipped"},
+ }, ["qt"], recache=True, compiler=True)
+ self.assertIn("| Qt | miss | failure |", report)
+ self.assertIn("| Compiler objects | exact hit | not run; forced recompilation requested |", report)
+
+ def test_cold_build_blocks_every_workflow_cache_restore_and_save(self):
+ for platform in ["macos", "windows"]:
+ text = (ROOT / f".github/workflows/build-{platform}.yml").read_text()
+ self.assertEqual(len(re.findall(r"^ cold_build:", text, re.M)), 2)
+ for step in re.split(r"^ - ", text, flags=re.M)[1:]:
+ if "uses: actions/cache/" in step:
+ self.assertIn("!inputs.cold_build", step)
+ self.assertIn("CCACHE_DIR=$(mktemp -d", text)
+ self.assertIn("id: compile", text)
+ windows = (ROOT / ".github/workflows/build-windows.yml").read_text()
+ self.assertIn("cache: ${{ !inputs.cold_build }}", windows)
+ self.assertIn("cold_build: ${{ inputs.cold_build }}", windows)
+ action = (ROOT / ".github/actions/build-windows-deps/action.yml").read_text()
+ for step in re.split(r"^ - ", action, flags=re.M)[1:]:
+ if "uses: actions/cache/" in step:
+ self.assertIn("inputs.cold_build != 'true'", step)
+
+ def test_summaries_run_after_failures(self):
+ paths = [".github/workflows/build-macos.yml", ".github/workflows/build-windows.yml",
+ ".github/actions/warm-macos-deps/action.yml", ".github/actions/build-windows-deps/action.yml"]
+ for path in paths:
+ text = (ROOT / path).read_text()
+ for step in re.split(r"^\s+- name: ", text, flags=re.M)[1:]:
+ if step.startswith("Summarize"):
+ self.assertIn("if: always()", step)
+ warmer = (ROOT / ".github/workflows/warm-dependency-caches.yml").read_text()
+ self.assertIn(" summary:\n if: always()", warmer)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.github/scripts/tests/test_package_cli_tools.py b/.github/scripts/tests/test_package_cli_tools.py
new file mode 100644
index 00000000..45e94497
--- /dev/null
+++ b/.github/scripts/tests/test_package_cli_tools.py
@@ -0,0 +1,745 @@
+import os
+import pathlib
+import subprocess
+import tarfile
+import tempfile
+import unittest
+
+
+ROOT = pathlib.Path(__file__).resolve().parents[3]
+SCRIPT = ROOT / ".github/scripts/package-cli-tools.sh"
+SMOKE = ROOT / ".github/scripts/smoke-release-tarballs.sh"
+BUILD_MACOS = ROOT / ".github/workflows/build-macos.yml"
+
+
+OTOOL_STUB = """#!/bin/sh
+case "$1" in -L) kind=refs ;; -l) kind=load ;; -D) kind=id ;; *) exit 2 ;; esac
+echo "$2:"
+fixture="$STUB_FIXTURES/otool.$kind.$(basename "$2")"
+if [ -f "$fixture" ]; then cat "$fixture"; fi
+"""
+
+OBJDUMP_STUB = """#!/bin/sh
+fixture="$STUB_FIXTURES/objdump.$(basename "$2")"
+[ -f "$fixture.fail" ] && exit 1
+if [ -f "$fixture" ]; then cat "$fixture"; fi
+"""
+
+READELF_STUB = """#!/bin/sh
+case "$1" in -dW) kind=d ;; -VW) kind=V ;; *) exit 2 ;; esac
+fixture="$STUB_FIXTURES/readelf.$kind.$(basename "$2")"
+if [ -f "$fixture" ]; then cat "$fixture"; fi
+"""
+
+# Copies each --executable into the AppDir, and into usr/lib the libraries
+# $STUB_FIXTURES/deploys.<program> names, as linuxdeploy deploys them.
+LINUXDEPLOY_STUB = """#!/bin/sh
+printf '%s\\n' "$*" "token=${GITHUB_TOKEN-unset}" "extract=${APPIMAGE_EXTRACT_AND_RUN-unset}" >> "$STUB_FIXTURES/linuxdeploy.log"
+[ -f "$STUB_FIXTURES/linuxdeploy.fail" ] && exit 1
+appdir=""
+while [ "$#" -gt 0 ]; do
+ case "$1" in
+ --appdir) appdir="$2"; shift 2 ;;
+ --executable)
+ mkdir -p "$appdir/usr/bin" "$appdir/usr/lib"
+ [ -f "$STUB_FIXTURES/linuxdeploy.skip-programs" ] || cp "$2" "$appdir/usr/bin/"
+ while read -r library; do cp "$STUB_FIXTURES/appdir-lib/$library" "$appdir/usr/lib/"; done < "$STUB_FIXTURES/deploys.$(basename "$2")"
+ shift 2 ;;
+ *) shift ;;
+ esac
+done
+mkdir -p "$appdir/usr/share/doc/libqt5core5t64"
+echo copyright > "$appdir/usr/share/doc/libqt5core5t64/copyright"
+"""
+
+
+def needed(*libraries, runpath=None):
+ lines = [f" 0x0000000000000001 (NEEDED) Shared library: [{library}]" for library in libraries]
+ if runpath is not None:
+ lines.append(f" 0x000000000000001d (RUNPATH) Library runpath: [{runpath}]")
+ return lines
+
+
+def versions(*names):
+ return [
+ "Version symbols section '.gnu.version' contains 9 entries:",
+ " 000: 0 (*local*) 2 (GLIBC_9.99)",
+ "Version needs section '.gnu.version_r' contains 1 entry:",
+ " 000000: Version: 1 File: libc.so.6 Cnt: 1",
+ *(f" 0x0010: Name: {name} Flags: none Version: 2" for name in names),
+ ]
+
+
+def rpath(path):
+ return ["Load command 12", " cmd LC_RPATH", " cmdsize 32", f" path {path} (offset 12)"]
+
+
+def minos(version):
+ return ["Load command 9", " cmd LC_BUILD_VERSION", " cmdsize 32", " platform 1", f" minos {version}"]
+
+
+def version_min_macosx(version):
+ return ["Load command 9", " cmd LC_VERSION_MIN_MACOSX", " cmdsize 16", f" version {version}", " sdk 15.0"]
+
+
+MINOS = minos("11.0")
+
+
+class PackageCliToolsTests(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = pathlib.Path(temporary.name)
+ self.bin = self.root / "bin"
+ self.fixtures = self.root / "fixtures"
+ self.source = self.root / "build"
+ self.out = self.root / "out"
+ for directory in (self.bin, self.fixtures, self.source):
+ directory.mkdir()
+ for name, body in (
+ ("otool", OTOOL_STUB), ("objdump", OBJDUMP_STUB), ("readelf", READELF_STUB),
+ ("linuxdeploy", LINUXDEPLOY_STUB),
+ ):
+ (self.bin / name).write_text(body, encoding="utf-8")
+ (self.bin / name).chmod(0o755)
+
+ def fixture(self, name, lines):
+ (self.fixtures / name).write_text("".join(f"{line}\n" for line in lines), encoding="utf-8")
+
+ def files(self, directory, names):
+ directory.mkdir(parents=True, exist_ok=True)
+ for name in names:
+ (directory / name).write_text(name, encoding="utf-8")
+
+ def package(self, platform, groups, *arguments, newline="\n"):
+ groups_file = self.root / "release-tarballs.txt"
+ groups_file.write_bytes(("# comment" + newline + newline.join(groups) + newline).encode())
+ return subprocess.run(
+ [
+ "bash", str(SCRIPT), "--platform", platform, "--version", "9.9.9", "--arch", "x86_64",
+ "--groups", str(groups_file), "--source", str(self.source), "--out", str(self.out), *arguments,
+ ],
+ env=dict(
+ os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", TMPDIR=str(self.root),
+ STUB_FIXTURES=str(self.fixtures), GITHUB_TOKEN="secret",
+ ),
+ text=True,
+ capture_output=True,
+ check=False,
+ )
+
+ def members(self, name):
+ with tarfile.open(self.out / f"{name}.tar.gz") as archive:
+ tops = {member.name.split("/", 1)[0] for member in archive.getmembers()}
+ self.assertEqual(tops, {name})
+ return sorted(member.name.split("/", 1)[1] for member in archive.getmembers() if member.isfile())
+
+ def text(self, name, member):
+ with tarfile.open(self.out / f"{name}.tar.gz") as archive:
+ return archive.extractfile(f"{name}/{member}").read().decode()
+
+ def assert_failed(self, result, *messages):
+ self.assertEqual(result.returncode, 1, result.stderr)
+ for message in messages:
+ self.assertIn(message, result.stderr)
+ self.assertFalse(self.out.exists() and any(self.out.iterdir()))
+
+ # macOS: the CLI assets directory as deploy-macos-cli-tools.sh leaves it.
+ # Fixture names differ by more than case: macOS file systems ignore it.
+ def macos_assets(self):
+ self.files(self.source, ["jt9", "jt9stream", "wsprd", "encode77"])
+ self.files(self.source / "lib", ["QtCore", "libfftw3f.3.dylib", "libfftw3f_threads.3.dylib", "libmystery.dylib"])
+ for program in ("jt9", "jt9stream", "encode77"):
+ self.fixture(f"otool.load.{program}", rpath("@loader_path/lib") + MINOS)
+ self.fixture("otool.load.wsprd", rpath("@loader_path") + rpath("@loader_path/lib") + MINOS)
+ for library in ("QtCore", "libfftw3f.3.dylib", "libfftw3f_threads.3.dylib"):
+ self.fixture(f"otool.load.{library}", MINOS)
+ self.fixture(f"otool.id.{library}", [f"@rpath/{library}"])
+ self.fixture("otool.id.libfftw3f.3.dylib", ["/Users/runner/work/fftw-prefix/lib/libfftw3f.3.dylib"])
+ self.fixture("otool.refs.jt9", [
+ "\t@rpath/libfftw3f_threads.3.dylib (compatibility version 9.0.0, current version 9.10.0)",
+ "\t@rpath/QtCore (compatibility version 5.15.0, current version 5.15.18)",
+ "\t/usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 1900.180.0)",
+ ])
+ self.fixture("otool.refs.jt9stream", ["\t@rpath/libfftw3f_threads.3.dylib (compatibility version 9.0.0)"])
+ self.fixture("otool.refs.wsprd", ["\t@rpath/libfftw3f.3.dylib (compatibility version 9.0.0)"])
+ self.fixture("otool.refs.encode77", ["\t/usr/lib/libSystem.B.dylib (compatibility version 1.0.0)"])
+ self.fixture("otool.refs.QtCore", [
+ "\t@rpath/QtCore (compatibility version 5.15.0)",
+ "\t/System/Library/Frameworks/IOKit.framework/Versions/A/IOKit (compatibility version 1.0.0)",
+ ])
+ self.fixture("otool.refs.libfftw3f_threads.3.dylib", [
+ "\t@rpath/libfftw3f_threads.3.dylib (compatibility version 9.0.0)",
+ "\t@rpath/libfftw3f.3.dylib (compatibility version 9.0.0)",
+ ])
+ self.fixture("otool.refs.libfftw3f.3.dylib", ["\t/Users/runner/work/fftw-prefix/lib/libfftw3f.3.dylib (compatibility version 9.0.0)"])
+
+ MACOS_GROUPS = ["jt9 jt9", "jt9stream jt9stream", "wsprd wsprd", "utilities encode77"]
+
+ def test_macos_tarballs_hold_each_group_and_the_dylibs_it_reaches(self):
+ self.macos_assets()
+ result = self.package("macos", self.MACOS_GROUPS)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ documents = ["COPYING", "README.txt", "THIRD-PARTY.txt"]
+ self.assertEqual(
+ self.members("wsjtx-9.9.9-x86_64-macOS-jt9"),
+ sorted([*documents, "jt9", "lib/QtCore", "lib/libfftw3f.3.dylib", "lib/libfftw3f_threads.3.dylib"]),
+ )
+ self.assertEqual(
+ self.members("wsjtx-9.9.9-x86_64-macOS-jt9stream"),
+ sorted([*documents, "jt9stream", "lib/libfftw3f.3.dylib", "lib/libfftw3f_threads.3.dylib"]),
+ )
+ self.assertEqual(
+ self.members("wsjtx-9.9.9-x86_64-macOS-wsprd"), sorted([*documents, "wsprd", "lib/libfftw3f.3.dylib"])
+ )
+ self.assertEqual(self.members("wsjtx-9.9.9-x86_64-macOS-utilities"), sorted([*documents, "encode77"]))
+ readme = self.text("wsjtx-9.9.9-x86_64-macOS-jt9", "README.txt")
+ self.assertIn("They require macOS 11.0 or later.", readme)
+ self.assertIn("xattr -d com.apple.quarantine", readme)
+ self.assertIn("wsjtx-9.9.9-src.tar.gz", readme)
+ self.assertIn("GNU General Public License version 3 (COPYING)", readme)
+ self.assertIn("are Copyright (C) 2001-", readme)
+ self.assertIn("Joseph Taylor, K1JT;", readme)
+ self.assertTrue(readme.rstrip().endswith("other members of the WSJT Development Group."), readme)
+ self.assertNotIn("_{prog}_", readme)
+ self.assertIn("jt9stream, in its own tarball, is the same decoder", readme)
+ self.assertNotIn("mingw-w64", self.text("wsjtx-9.9.9-x86_64-macOS-jt9", "THIRD-PARTY.txt"))
+ notices = self.text("wsjtx-9.9.9-x86_64-macOS-jt9", "THIRD-PARTY.txt")
+ self.assertIn("Files: QtCore", notices)
+ self.assertIn("Files: libfftw3f.3.dylib libfftw3f_threads.3.dylib", notices)
+ utilities = self.text("wsjtx-9.9.9-x86_64-macOS-utilities", "THIRD-PARTY.txt")
+ self.assertIn("GCC runtime libraries\n License: GPL-3.0-or-later WITH GCC-exception-3.1\n", utilities)
+ self.assertIn(" Linked statically into the programs\n", utilities)
+ self.assertNotIn("Files:", utilities)
+ self.assertEqual(
+ self.text("wsjtx-9.9.9-x86_64-macOS-wsprd", "COPYING"), (ROOT / "COPYING").read_text(encoding="utf-8")
+ )
+
+ def test_macos_unresolved_rpath_reference_fails_naming_it(self):
+ self.macos_assets()
+ with (self.fixtures / "otool.refs.wsprd").open("a", encoding="utf-8") as stream:
+ stream.write("\t@rpath/libmissing.dylib (compatibility version 1.0.0)\n")
+ self.assert_failed(self.package("macos", self.MACOS_GROUPS), "@rpath/libmissing.dylib(wsprd)")
+
+ def test_macos_build_tree_reference_fails(self):
+ self.macos_assets()
+ self.fixture("otool.refs.encode77", ["\t/opt/homebrew/lib/libgfortran.5.dylib (compatibility version 6.0.0)"])
+ self.assert_failed(self.package("macos", self.MACOS_GROUPS), "/opt/homebrew/lib/libgfortran.5.dylib(encode77)")
+
+ def test_macos_absolute_rpath_fails(self):
+ self.macos_assets()
+ self.fixture("otool.load.libfftw3f.3.dylib", rpath("/Users/runner/work/fftw-prefix/lib") + MINOS)
+ self.assert_failed(
+ self.package("macos", self.MACOS_GROUPS),
+ "lib/libfftw3f.3.dylib has an absolute LC_RPATH: /Users/runner/work/fftw-prefix/lib",
+ )
+
+ def test_macos_program_with_absolute_rpath_fails(self):
+ self.macos_assets()
+ self.fixture("otool.load.wsprd", rpath("@loader_path/lib") + rpath("/opt/homebrew/lib") + MINOS)
+ self.assert_failed(self.package("macos", self.MACOS_GROUPS), "wsprd has an absolute LC_RPATH: /opt/homebrew/lib")
+
+ def test_macos_library_missing_from_notices_table_fails(self):
+ self.macos_assets()
+ self.fixture("otool.refs.encode77", ["\t@rpath/libmystery.dylib (compatibility version 1.0.0)"])
+ self.assert_failed(
+ self.package("macos", ["utilities encode77", "jt9 jt9"]),
+ "bundled libraries missing from third-party-libraries.tsv: libmystery.dylib",
+ )
+
+ def test_macos_dylib_outside_lib_fails(self):
+ self.macos_assets()
+ self.files(self.source, ["libfftw3f_top.dylib"])
+ self.fixture("otool.refs.wsprd", ["\t@rpath/libfftw3f_top.dylib (compatibility version 1.0.0)"])
+ self.assert_failed(self.package("macos", self.MACOS_GROUPS), "@rpath/libfftw3f_top.dylib(wsprd)")
+
+ def test_macos_rpath_references_resolve_through_their_own_program(self):
+ self.macos_assets()
+ self.files(self.source, ["wsprcode"])
+ self.files(self.source / "lib/extra", ["libfftw3f_extra.dylib"])
+ self.fixture("otool.load.wsprcode", rpath("@executable_path/lib/extra") + rpath("@loader_path/lib") + MINOS)
+ self.fixture("otool.load.libfftw3f_extra.dylib", MINOS)
+ self.fixture("otool.refs.wsprcode", ["\t@rpath/libfftw3f_extra.dylib (compatibility version 1.0.0)"])
+ result = self.package("macos", ["utilities wsprcode"])
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn("lib/extra/libfftw3f_extra.dylib", self.members("wsjtx-9.9.9-x86_64-macOS-utilities"))
+ self.out.joinpath("wsjtx-9.9.9-x86_64-macOS-utilities.tar.gz").unlink()
+ self.fixture("otool.refs.encode77", ["\t@rpath/libfftw3f_extra.dylib (compatibility version 1.0.0)"])
+ self.assert_failed(self.package("macos", ["utilities wsprcode encode77"]), "@rpath/libfftw3f_extra.dylib(encode77)")
+
+ def test_macos_loader_path_references_resolve_beside_the_dylib(self):
+ self.macos_assets()
+ self.fixture("otool.refs.libfftw3f_threads.3.dylib", ["\t@loader_path/libfftw3f.3.dylib (compatibility version 9.0.0)"])
+ result = self.package("macos", self.MACOS_GROUPS)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn("lib/libfftw3f.3.dylib", self.members("wsjtx-9.9.9-x86_64-macOS-jt9stream"))
+
+ def test_macos_reference_escaping_the_source_fails(self):
+ self.macos_assets()
+ self.files(self.root, ["outside.dylib"])
+ self.fixture("otool.refs.libfftw3f_threads.3.dylib", ["\t@loader_path/../../outside.dylib (compatibility version 1.0.0)"])
+ self.assert_failed(self.package("macos", self.MACOS_GROUPS), "@loader_path/../../outside.dylib(lib/libfftw3f_threads.3.dylib)")
+
+ def test_macos_program_rpath_outside_its_directory_fails(self):
+ self.macos_assets()
+ self.fixture("otool.load.jt9", rpath("@loader_path/../lib") + MINOS)
+ self.assert_failed(self.package("macos", self.MACOS_GROUPS), "jt9 has an LC_RPATH outside its directory: @loader_path/../lib")
+
+ def test_macos_floor_is_the_highest_minos(self):
+ self.macos_assets()
+ self.fixture("otool.load.QtCore", minos("13.0"))
+ self.fixture("otool.load.libfftw3f.3.dylib", minos("9.5"))
+ result = self.package("macos", self.MACOS_GROUPS)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn("They require macOS 13.0 or later.", self.text("wsjtx-9.9.9-x86_64-macOS-jt9", "README.txt"))
+ self.assertIn("They require macOS 11.0 or later.", self.text("wsjtx-9.9.9-x86_64-macOS-wsprd", "README.txt"))
+
+ def test_macos_legacy_minimum_version_is_recorded_for_every_tarball(self):
+ self.macos_assets()
+ source_version = ["Load command 10", " cmd LC_SOURCE_VERSION", " cmdsize 16", " version 99.0"]
+ for program in ("jt9", "jt9stream", "wsprd", "encode77"):
+ self.fixture(
+ f"otool.load.{program}",
+ source_version + rpath("@loader_path/lib") + version_min_macosx("10.13") + source_version,
+ )
+ for library in ("QtCore", "libfftw3f.3.dylib", "libfftw3f_threads.3.dylib"):
+ self.fixture(f"otool.load.{library}", version_min_macosx("10.13") + source_version)
+ result = self.package("macos", self.MACOS_GROUPS)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ for group in ("jt9", "jt9stream", "wsprd", "utilities"):
+ self.assertIn(
+ "They require macOS 10.13 or later.",
+ self.text(f"wsjtx-9.9.9-x86_64-macOS-{group}", "README.txt"),
+ )
+
+ def test_macos_floor_is_the_highest_across_both_version_commands(self):
+ self.macos_assets()
+ for modern, expected in (("10.12", "10.13"), ("13.0", "13.0")):
+ with self.subTest(modern=modern):
+ self.fixture("otool.load.jt9", rpath("@loader_path/lib") + minos(modern))
+ self.fixture("otool.load.QtCore", version_min_macosx("10.13"))
+ for library in ("libfftw3f.3.dylib", "libfftw3f_threads.3.dylib"):
+ self.fixture(f"otool.load.{library}", minos(modern))
+ result = self.package("macos", ["jt9 jt9"])
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn(
+ f"They require macOS {expected} or later.",
+ self.text("wsjtx-9.9.9-x86_64-macOS-jt9", "README.txt"),
+ )
+
+ def test_macos_minimum_does_not_read_fields_from_other_load_commands(self):
+ self.macos_assets()
+ for command in ("LC_BUILD_VERSION", "LC_VERSION_MIN_MACOSX"):
+ with self.subTest(command=command):
+ self.fixture("otool.load.encode77", [
+ "Load command 9", f" cmd {command}", " cmdsize 16",
+ "Load command 10", " cmd LC_SOURCE_VERSION", " cmdsize 16", " version 99.0",
+ ])
+ self.assert_failed(
+ self.package("macos", ["utilities encode77"]),
+ "no minimum macOS version recorded in wsjtx-9.9.9-x86_64-macOS-utilities",
+ )
+
+ def test_macos_without_a_minimum_version_fails(self):
+ self.macos_assets()
+ self.fixture("otool.load.encode77", rpath("@loader_path/lib"))
+ self.assert_failed(self.package("macos", self.MACOS_GROUPS), "no minimum macOS version recorded in wsjtx-9.9.9-x86_64-macOS-utilities")
+
+ def test_tarball_named_twice_fails(self):
+ self.macos_assets()
+ self.assert_failed(self.package("macos", ["wsprd wsprd", "jt9 jt9", "wsprd jt9stream"]), "release tarball wsprd is named twice")
+
+ def test_tarball_without_readme_description_fails(self):
+ self.macos_assets()
+ self.assert_failed(self.package("macos", ["extra encode77"]), "no README description for release tarball extra")
+
+ def test_missing_program_fails_naming_it(self):
+ self.macos_assets()
+ (self.source / "jt9stream").unlink()
+ self.assert_failed(self.package("macos", self.MACOS_GROUPS), "missing under", "jt9stream")
+
+ def test_group_without_programs_fails(self):
+ self.macos_assets()
+ self.assert_failed(self.package("macos", ["jt9 jt9", "utilities"]), "release tarball utilities names no programs")
+
+ # Windows
+ def windows_build(self, failing=()):
+ self.files(self.source, ["jt9.exe", "encode77.exe", "wsjtx.exe"])
+ self.files(self.root / "dlls", ["libfftw3f-3.dll", "LIBGFORTRAN-5.DLL", "unused.dll"])
+ self.files(self.root / "system", ["KERNEL32.dll", "msvcrt.dll"])
+ self.fixture("objdump.jt9.exe", ["\tDLL Name: libfftw3f-3.dll", "\tDLL Name: KERNEL32.dll"])
+ self.fixture("objdump.libfftw3f-3.dll", ["\tDLL Name: libgfortran-5.dll"])
+ self.fixture("objdump.LIBGFORTRAN-5.DLL", ["\tDLL Name: KERNEL32.dll"])
+ self.fixture("objdump.encode77.exe", ["\tDLL Name: msvcrt.dll"])
+ for name in failing:
+ self.fixture(f"objdump.{name}.fail", [])
+ return self.package(
+ "windows", ["jt9 jt9", "utilities encode77"],
+ "--dll-dir", str(self.root / "dlls"), "--system-dir", str(self.root / "system"), newline="\r\n",
+ )
+
+ def test_windows_tarballs_hold_each_group_and_its_dll_closure(self):
+ result = self.windows_build()
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(
+ self.members("wsjtx-9.9.9-windows-x86_64-jt9"),
+ ["COPYING", "LIBGFORTRAN-5.DLL", "README.txt", "THIRD-PARTY.txt", "jt9.exe", "libfftw3f-3.dll"],
+ )
+ self.assertEqual(
+ self.members("wsjtx-9.9.9-windows-x86_64-utilities"), ["COPYING", "README.txt", "THIRD-PARTY.txt", "encode77.exe"]
+ )
+ self.assertIn("no Authenticode signature", self.text("wsjtx-9.9.9-windows-x86_64-jt9", "README.txt"))
+ notices = self.text("wsjtx-9.9.9-windows-x86_64-jt9", "THIRD-PARTY.txt")
+ self.assertIn("FFTW 3\n License: GPL-2.0-or-later\n", notices)
+ self.assertIn("GCC runtime libraries\n License: GPL-3.0-or-later WITH GCC-exception-3.1\n", notices)
+ self.assertIn(" Files: LIBGFORTRAN-5.DLL\n", notices)
+ self.assertIn("mingw-w64 runtime\n", notices)
+ self.assertEqual(notices.count(" Linked statically into the programs"), 1)
+ self.assertNotIn("libquadmath", notices)
+
+ def test_windows_import_outside_dll_and_system_dirs_fails(self):
+ (self.root / "system").mkdir()
+ self.fixture("objdump.encode77.exe", ["\tDLL Name: libmissing.dll"])
+ self.files(self.source, ["jt9.exe", "encode77.exe"])
+ self.files(self.root / "dlls", [])
+ self.fixture("objdump.jt9.exe", [])
+ result = self.package(
+ "windows", ["jt9 jt9", "utilities encode77"],
+ "--dll-dir", str(self.root / "dlls"), "--system-dir", str(self.root / "system"),
+ )
+ self.assert_failed(result, "libmissing.dll(encode77.exe)")
+
+ def test_windows_objdump_failure_fails_naming_the_file(self):
+ self.assert_failed(self.windows_build(failing=["libfftw3f-3.dll"]), "objdump failed on libfftw3f-3.dll")
+
+ # Linux: linuxdeploy and readelf are stubbed; the excludelist is the committed one.
+ def linux_build(self):
+ self.files(self.source, ["jt9", "jt9stream", "wsjtx"])
+ self.files(self.fixtures / "appdir-lib", ["libQt5Core.so.5", "libicuuc.so.74", "libgfortran.so.5"])
+ self.fixture("deploys.jt9", ["libQt5Core.so.5", "libicuuc.so.74", "libgfortran.so.5"])
+ self.fixture("deploys.jt9stream", ["libgfortran.so.5"])
+ self.fixture("readelf.d.jt9", needed("libQt5Core.so.5", "libgfortran.so.5", "libc.so.6", runpath="$ORIGIN/../lib"))
+ self.fixture("readelf.V.jt9", versions("GLIBC_2.34", "GLIBC_2.2.5"))
+ self.fixture("readelf.d.jt9stream", needed("libgfortran.so.5", "libm.so.6", runpath="${ORIGIN}/../lib"))
+ self.fixture("readelf.V.jt9stream", versions("GLIBC_2.29"))
+ self.fixture("readelf.d.libQt5Core.so.5", needed("libicuuc.so.74", "libstdc++.so.6", runpath="$ORIGIN"))
+ self.fixture("readelf.V.libQt5Core.so.5", versions("GLIBC_2.38", "GLIBCXX_3.4.9", "GLIBCXX_3.4.30", "CXXABI_1.3.13"))
+ self.fixture("readelf.d.libicuuc.so.74", needed("libstdc++.so.6", runpath="${ORIGIN}"))
+ self.fixture("readelf.d.libgfortran.so.5", needed("libc.so.6", "ld-linux-aarch64.so.1", runpath="$ORIGIN"))
+
+ def linux_package(self, groups=("jt9 jt9", "jt9stream jt9stream")):
+ return self.package("linux", list(groups), "--linuxdeploy", str(self.bin / "linuxdeploy"))
+
+ def test_linux_tarballs_bundle_deployed_libraries_and_state_host_requirements(self):
+ self.linux_build()
+ result = self.linux_package()
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(
+ self.members("wsjtx-9.9.9-linux-x86_64-jt9"),
+ [
+ "COPYING", "README.txt", "THIRD-PARTY.txt", "bin/jt9", "lib/libQt5Core.so.5", "lib/libgfortran.so.5",
+ "lib/libicuuc.so.74", "share/doc/libqt5core5t64/copyright",
+ ],
+ )
+ readme = self.text("wsjtx-9.9.9-linux-x86_64-jt9", "README.txt")
+ self.assertIn("glibc 2.38 or later, libstdc++ with GLIBCXX_3.4.30 or later", readme)
+ self.assertIn("these libraries: ld-linux-aarch64.so.1 libc.so.6 libstdc++.so.6.", readme)
+ self.assertIn("ICU 74\n", self.text("wsjtx-9.9.9-linux-x86_64-jt9", "THIRD-PARTY.txt"))
+ self.assertIn("without it", readme)
+ self.assertIn("glibc 2.29 or later, and these libraries", self.text("wsjtx-9.9.9-linux-x86_64-jt9stream", "README.txt"))
+ self.assertIn("share/doc/", self.text("wsjtx-9.9.9-linux-x86_64-jt9", "THIRD-PARTY.txt"))
+ log = (self.fixtures / "linuxdeploy.log").read_text(encoding="utf-8").splitlines()
+ self.assertTrue(log[0].startswith("--appimage-extract-and-run --appdir "), log[0])
+ self.assertTrue(log[0].endswith(f"--executable {self.source}/jt9"), log[0])
+ self.assertEqual(log[1:3], ["token=unset", "extract=1"])
+
+ def test_linux_library_neither_bundled_nor_excluded_fails(self):
+ self.linux_build()
+ self.fixture("readelf.d.jt9stream", needed("libfftw3f.so.3", runpath="$ORIGIN/../lib"))
+ self.assert_failed(self.linux_package(), "libfftw3f.so.3(bin/jt9stream)")
+
+ def test_linux_runpath_is_not_inherited_by_bundled_libraries(self):
+ self.linux_build()
+ self.fixture("readelf.d.libQt5Core.so.5", needed("libicuuc.so.74"))
+ self.assert_failed(self.linux_package(), "libicuuc.so.74(lib/libQt5Core.so.5)")
+
+ def test_linux_runpath_outside_origin_fails(self):
+ self.linux_build()
+ self.fixture("readelf.d.jt9", needed("libc.so.6", runpath="$ORIGIN/../lib:/work/wsjtx-build"))
+ self.assert_failed(self.linux_package(), "bin/jt9 has a RUNPATH entry not relative to $ORIGIN: /work/wsjtx-build")
+
+ def test_linux_empty_runpath_entry_fails(self):
+ self.linux_build()
+ self.fixture("readelf.d.jt9", needed("libc.so.6", runpath="$ORIGIN/../lib:"))
+ self.assert_failed(self.linux_package(), "bin/jt9 has an empty RUNPATH entry: $ORIGIN/../lib:")
+
+ def test_linux_program_linuxdeploy_did_not_deploy_fails(self):
+ self.linux_build()
+ self.fixture("linuxdeploy.skip-programs", [])
+ self.assert_failed(self.linux_package(), "linuxdeploy did not deploy jt9")
+
+ def test_linux_linuxdeploy_failure_fails(self):
+ self.linux_build()
+ self.fixture("linuxdeploy.fail", [])
+ self.assert_failed(self.linux_package(), "linuxdeploy failed for wsjtx-9.9.9-linux-x86_64-jt9")
+
+ def test_linux_requires_linuxdeploy(self):
+ self.linux_build()
+ result = self.package("linux", ["jt9 jt9"])
+ self.assertEqual(result.returncode, 2)
+ self.assertIn("--linuxdeploy is required", result.stderr)
+
+
+class LinuxdeployExcludelistTests(unittest.TestCase):
+ def test_excludelist_belongs_to_the_pinned_linuxdeploy(self):
+ excludelist = (ROOT / ".github/scripts/linuxdeploy-excludelist.txt").read_text(encoding="utf-8")
+ tag = excludelist.split("compiled into linuxdeploy ", 1)[1].split(",", 1)[0]
+ self.assertIn(
+ f'LINUXDEPLOY_TAG: "{tag}"', (ROOT / ".github/actions/build-linux-payload/action.yml").read_text(encoding="utf-8")
+ )
+ self.assertIn(f"LINUXDEPLOY_TAG={tag}\n", (ROOT / ".github/scripts/package-linux-armhf.sh").read_text(encoding="utf-8"))
+ names = [line for line in excludelist.splitlines() if line and not line.startswith("#")]
+ self.assertEqual(len(names), 52)
+ for name in ("libc.so.6", "libstdc++.so.6", "libgcc_s.so.1", "libz.so.1", "libm.so.6"):
+ self.assertIn(name, names)
+ for name in ("libgfortran.so.5", "libgomp.so.1", "libQt5Core.so.5", "libfftw3f.so.3"):
+ self.assertNotIn(name, names)
+
+
+class SmokeReleaseTarballsTests(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = pathlib.Path(temporary.name)
+ self.dir = self.root / "tarballs"
+ self.bin = self.root / "bin"
+ self.log = self.root / "smoke.log"
+ self.dir.mkdir()
+ self.bin.mkdir()
+ (self.bin / "timeout").write_text(
+ f'#!/bin/sh\necho "$1" >> "{self.root}/timeout.log"\nshift\nexec "$@"\n', encoding="utf-8"
+ )
+ (self.bin / "timeout").chmod(0o755)
+
+ def tarball(self, group, programs, layout="bin/", failing=(), libraries=(), target="linux-x86_64", top=None):
+ name = f"wsjtx-9.9.9-{target}-{group}"
+ tree = self.root / "trees" / name
+ for program in programs:
+ path = tree / f"{layout}{program}"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ status = 3 if program in failing else 0
+ path.write_text(
+ f'#!/bin/sh\necho "{program} $* lib=${{LD_LIBRARY_PATH-unset}} cwd=$(pwd)" >> "{self.log}"\nexit {status}\n',
+ encoding="utf-8",
+ )
+ path.chmod(0o755)
+ for library in libraries:
+ (tree / "lib").mkdir(parents=True, exist_ok=True)
+ (tree / "lib" / library).write_text(library, encoding="utf-8")
+ with tarfile.open(self.dir / f"{name}.tar.gz", "w:gz") as archive:
+ archive.add(tree, arcname=top or name)
+
+ def smoke(self, groups, *arguments, platform="linux", target="linux-x86_64", script=SMOKE):
+ groups_file = self.root / "release-tarballs.txt"
+ groups_file.write_text("# comment\n" + "".join(f"{line}\n" for line in groups), encoding="utf-8")
+ return subprocess.run(
+ [
+ "bash", str(script), "--platform", platform, "--version", "9.9.9", "--target", target,
+ "--groups", str(groups_file), "--dir", str(self.dir), *arguments,
+ ],
+ env=dict(os.environ, PATH=f"{self.bin}:{os.environ['PATH']}", TMPDIR=str(self.root), LD_LIBRARY_PATH="/bogus"),
+ text=True, capture_output=True, check=False,
+ )
+
+ def test_every_program_runs_from_its_own_tarball_without_library_path(self):
+ self.tarball("jt9", ["jt9"])
+ self.tarball("wsprd", ["wsprd"])
+ self.tarball("utilities", ["encode77", "ft4sim"])
+ result = self.smoke(["jt9 jt9", "wsprd wsprd", "utilities encode77 ft4sim"])
+ self.assertEqual(result.returncode, 0, result.stderr)
+ lines = self.log.read_text(encoding="utf-8").splitlines()
+ self.assertEqual([line.split(" ", 1)[0] for line in lines], ["jt9", "wsprd", "encode77", "ft4sim"])
+ self.assertTrue(lines[0].startswith("jt9 --help lib=unset"), lines[0])
+ self.assertRegex(lines[1], r"^wsprd -a \S+/run-wsprd \S+/samples/WSPR/150426_0918\.wav lib=unset cwd=\S+/run-wsprd$")
+ self.assertTrue(lines[2].startswith("encode77 CQ K1ABC FN42 lib=unset"), lines[2])
+ self.assertTrue(lines[3].startswith("ft4sim lib=unset"), lines[3])
+ self.assertEqual((self.root / "timeout.log").read_text(encoding="utf-8").split(), ["120"] * 4)
+
+ def scripts_copy(self):
+ scripts = self.root / "repo/.github/scripts"
+ scripts.mkdir(parents=True)
+ (scripts / SMOKE.name).write_bytes(SMOKE.read_bytes())
+ (scripts / "smoke-launch-windows.sh").write_text(
+ f'#!/bin/sh\necho "launch $(basename "$1") cwd=$(pwd) args=$*" >> "{self.log}"\n'
+ 'case "$1" in *ft4sim.exe) exit 1 ;; esac\n',
+ encoding="utf-8",
+ )
+ (scripts / "smoke-launch-windows.sh").chmod(0o755)
+ sample = self.root / "repo/samples/WSPR/150426_0918.wav"
+ sample.parent.mkdir(parents=True)
+ sample.write_bytes(b"RIFF")
+ return scripts / SMOKE.name
+
+ def test_windows_programs_launch_through_the_clean_path_launcher(self):
+ script = self.scripts_copy()
+ self.tarball("jt9", ["jt9.exe"], layout="", target="windows-x86_64")
+ self.tarball("utilities", ["encode77.exe"], layout="", target="windows-x86_64")
+ result = self.smoke(["jt9 jt9", "utilities encode77"], platform="windows", target="windows-x86_64", script=script)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ lines = self.log.read_text(encoding="utf-8").splitlines()
+ self.assertRegex(lines[0], r"^launch jt9\.exe cwd=\S+/run-jt9 args=\S+/wsjtx-9\.9\.9-windows-x86_64-jt9/jt9\.exe --help$")
+ self.assertRegex(lines[1], r"^launch encode77\.exe cwd=\S+/run-encode77 args=\S+ CQ K1ABC FN42$")
+
+ def test_windows_launch_failure_fails(self):
+ script = self.scripts_copy()
+ self.tarball("utilities", ["ft4sim.exe"], layout="", target="windows-x86_64")
+ result = self.smoke(["utilities ft4sim"], platform="windows", target="windows-x86_64", script=script)
+ self.assertEqual(result.returncode, 1)
+ self.assertIn("ft4sim from wsjtx-9.9.9-windows-x86_64-utilities failed", result.stderr)
+
+ def test_macos_programs_run_from_the_top_of_their_tarball(self):
+ script = self.scripts_copy()
+ self.tarball("wsprd", ["wsprd"], layout="", target="arm64-macOS")
+ result = self.smoke(["wsprd wsprd"], platform="macos", target="arm64-macOS", script=script)
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertRegex(self.log.read_text(encoding="utf-8"), r"wsprd -a \S+/run-wsprd \S+/repo/\.github/scripts/\.\./\.\./samples/WSPR/150426_0918\.wav ")
+ self.assertFalse((self.root / "timeout.log").exists())
+
+ def test_tarball_with_another_top_directory_fails(self):
+ self.tarball("jt9", ["jt9"], top="jt9")
+ result = self.smoke(["jt9 jt9"])
+ self.assertEqual(result.returncode, 1)
+ self.assertIn("wsjtx-9.9.9-linux-x86_64-jt9.tar.gz does not extract to wsjtx-9.9.9-linux-x86_64-jt9/", result.stderr)
+
+ def test_failing_program_fails_naming_it(self):
+ self.tarball("utilities", ["encode77", "ft4sim"], failing=["ft4sim"])
+ result = self.smoke(["utilities encode77 ft4sim"])
+ self.assertEqual(result.returncode, 1)
+ self.assertIn("ft4sim from wsjtx-9.9.9-linux-x86_64-utilities failed", result.stderr)
+
+ def test_program_missing_from_its_tarball_fails(self):
+ self.tarball("jt9", ["jt9stream"])
+ result = self.smoke(["jt9 jt9"])
+ self.assertEqual(result.returncode, 1)
+ self.assertIn("jt9 is not in wsjtx-9.9.9-linux-x86_64-jt9", result.stderr)
+
+ def test_program_without_a_smoke_invocation_fails(self):
+ self.tarball("extra", ["newtool"])
+ result = self.smoke(["extra newtool"])
+ self.assertEqual(result.returncode, 1)
+ self.assertIn("no smoke invocation for newtool", result.stderr)
+
+ def ldd_stub(self, resolution, status=0):
+ (self.bin / "ldd").write_text(
+ "#!/bin/sh\n"
+ f'[ "${{LD_LIBRARY_PATH-unset}}" = unset ] || exit 9\n'
+ 'tree=$(dirname "$(dirname "$1")")\n'
+ "printf '\\tlinux-vdso.so.1 (0x1)\\n'\n"
+ f"printf '\\tlibQt5Core.so.5 => %s (0x2)\\n' \"{resolution}\"\n"
+ "printf '\\tlibc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x3)\\n'\n"
+ f"exit {status}\n",
+ encoding="utf-8",
+ )
+ (self.bin / "ldd").chmod(0o755)
+
+ def test_ldd_reports_a_library_not_found(self):
+ self.tarball("jt9", ["jt9"], libraries=["libQt5Core.so.5"])
+ self.ldd_stub("not found")
+ result = self.smoke(["jt9 jt9"], "--ldd")
+ self.assertEqual(result.returncode, 1)
+ self.assertIn("libQt5Core.so.5(bin/jt9): not found", result.stderr)
+
+ def test_ldd_failure_fails(self):
+ self.tarball("jt9", ["jt9"], libraries=["libQt5Core.so.5"])
+ self.ldd_stub("$tree/lib/libQt5Core.so.5", status=1)
+ result = self.smoke(["jt9 jt9"], "--ldd")
+ self.assertEqual(result.returncode, 1)
+ self.assertIn("ldd failed on bin/jt9", result.stderr)
+
+ def test_ldd_accepts_a_library_without_dependencies(self):
+ # ICU's data library needs nothing; ldd says so and exits 0.
+ self.tarball("jt9", ["jt9"], libraries=["libicudata.so.74"])
+ (self.bin / "ldd").write_text("#!/bin/sh\necho '\tstatically linked'\n", encoding="utf-8")
+ (self.bin / "ldd").chmod(0o755)
+ result = self.smoke(["jt9 jt9"], "--ldd")
+ self.assertEqual(result.returncode, 0, result.stderr)
+
+ def test_ldd_accepts_bundled_copies_through_origin(self):
+ self.tarball("jt9", ["jt9"], libraries=["libQt5Core.so.5"])
+ self.ldd_stub("$tree/bin/../lib/libQt5Core.so.5")
+ result = self.smoke(["jt9 jt9"], "--ldd")
+ self.assertEqual(result.returncode, 0, result.stderr)
+
+ def test_ldd_rejects_a_system_copy_of_a_bundled_library(self):
+ self.tarball("jt9", ["jt9"], libraries=["libQt5Core.so.5"])
+ self.ldd_stub("/usr/lib/x86_64-linux-gnu/libQt5Core.so.5")
+ result = self.smoke(["jt9 jt9"], "--ldd")
+ self.assertEqual(result.returncode, 1)
+ self.assertIn("libQt5Core.so.5(bin/jt9): /usr/lib/x86_64-linux-gnu/libQt5Core.so.5", result.stderr)
+
+
+class MacosPostinstallTests(unittest.TestCase):
+ def setUp(self):
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.root = pathlib.Path(temporary.name) / "volume"
+ self.scripts = pathlib.Path(temporary.name) / "scripts"
+ self.scripts.mkdir()
+ lines = BUILD_MACOS.read_text(encoding="utf-8").splitlines()
+ start = next(i for i, line in enumerate(lines) if line.strip() == 'cat > "${SCRIPTS}/postinstall" << \'SCRIPT\'')
+ indent = len(lines[start]) - len(lines[start].lstrip())
+ end = next(i for i in range(start + 1, len(lines)) if lines[i] == " " * indent + "SCRIPT")
+ body = [line[indent:] for line in lines[start + 1:end]]
+ self.assertFalse(any("launchctl" in line or "sysctl" in line for line in body))
+ self.assertTrue(any(line.startswith('root="${3%/}"') for line in body))
+ for line in body:
+ for prefix in line.split("/usr/local")[:-1]:
+ self.assertTrue(prefix.endswith(("$root", '"$root"')), line)
+ self.postinstall = self.scripts / "postinstall"
+ self.postinstall.write_text("\n".join(body) + "\n", encoding="utf-8")
+ (self.scripts / "installed-cli-tools.txt").write_text("jt9\nwsprd\n", encoding="utf-8")
+
+ def executable(self, path):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("#!/bin/sh\n", encoding="utf-8")
+ path.chmod(0o755)
+
+ def run_postinstall(self):
+ return subprocess.run(
+ ["bash", str(self.postinstall), "pkg", "/", str(self.root), "/"],
+ stdin=subprocess.DEVNULL, text=True, capture_output=True, check=False,
+ )
+
+ def test_upgrade_removes_unshipped_programs_and_their_links(self):
+ programs = self.root / "usr/local/wsjtx"
+ links = self.root / "usr/local/bin"
+ for name in ("jt9", "wsprd", "wsprcode"):
+ self.executable(programs / name)
+ links.mkdir(parents=True)
+ (links / "wsprcode").symlink_to(programs / "wsprcode")
+ result = self.run_postinstall()
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertEqual(sorted(path.name for path in programs.iterdir()), ["jt9", "wsprd"])
+ self.assertEqual(sorted(path.name for path in links.iterdir()), ["jt9", "wsprd"])
+
+ def test_symlinked_program_directory_is_not_cleaned(self):
+ elsewhere = self.root / "Users/someone/bin"
+ for name in ("jt9", "backup.sh"):
+ self.executable(elsewhere / name)
+ (self.root / "usr/local").mkdir(parents=True)
+ (self.root / "usr/local/wsjtx").symlink_to(elsewhere)
+ result = self.run_postinstall()
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertTrue((elsewhere / "backup.sh").exists())
+
+ def test_trailing_non_executable_entry_does_not_fail_the_install(self):
+ programs = self.root / "usr/local/wsjtx"
+ self.executable(programs / "jt9")
+ (programs / "zz-notes.txt").write_text("notes", encoding="utf-8")
+ result = self.run_postinstall()
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertTrue((self.root / "usr/local/bin/jt9").is_symlink())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.github/scripts/tests/test_release_linux_images.py b/.github/scripts/tests/test_release_linux_images.py
new file mode 100644
index 00000000..10a3fd0f
--- /dev/null
+++ b/.github/scripts/tests/test_release_linux_images.py
@@ -0,0 +1,158 @@
+#!/usr/bin/env python3
+"""Release dependency selection and registry-copy regression checks."""
+import hashlib
+import importlib.util
+import json
+from pathlib import Path
+import subprocess
+import tempfile
+import unittest
+from unittest.mock import patch
+
+SPEC = importlib.util.spec_from_file_location("release_linux_images", Path(__file__).parents[1] / "release-linux-images.py")
+images = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(images)
+GENERATION = "validated-build-20260925-123-1"
+DIGEST = "sha256:" + "a" * 64
+RECIPE = "b" * 64
+
+
+def selection():
+ return {"schema": 1, "generation": GENERATION, "images": {
+ key: {"reference": f"{images.PUBLIC}/{spec[0]}@{DIGEST}", "recipe_sha256": RECIPE}
+ for key, spec in images.IMAGES.items()
+ }}
+
+
+def manifests():
+ common = {"generation": GENERATION.removeprefix("validated-"), "recipe_sha256": RECIPE,
+ "toolchain_id": "gcc13-armhf-abc", "runtime_sha256": "c" * 64}
+ runtime = dict(common)
+ runtime.update({"cross_" + key: common[key] for key in ("generation", "recipe_sha256", "toolchain_id")})
+ return [dict(common), dict(common), dict(common), runtime]
+
+
+class SelectionTests(unittest.TestCase):
+ def setUp(self):
+ self.fingerprint = patch.object(images, "fingerprint", return_value=RECIPE)
+ self.fingerprint.start()
+ self.addCleanup(self.fingerprint.stop)
+
+ def test_complete_selection_and_anonymous_reads(self):
+ with patch.object(images, "anonymous_digest", return_value=DIGEST) as remote:
+ self.assertEqual(images.validate(selection(), True), selection())
+ self.assertEqual(remote.call_count, 4)
+
+ def test_missing_malformed_and_untrusted_selection(self):
+ cases = []
+ lock = selection(); del lock["images"]["armhf_cross"]; cases.append(lock)
+ lock = selection(); lock["images"]["x86_64"] = None; cases.append(lock)
+ lock = selection(); lock["generation"] = "stable"; cases.append(lock)
+ lock = selection(); lock["images"]["x86_64"]["reference"] = f"{images.PRIVATE}/linux-noble@{DIGEST}"; cases.append(lock)
+ lock = selection(); lock["images"]["x86_64"]["reference"] = f"{images.PUBLIC}/linux-noble:stable"; cases.append(lock)
+ lock = selection(); lock["images"]["aarch64"]["recipe_sha256"] = "c" * 64; cases.append(lock)
+ for lock in cases:
+ with self.subTest(lock=lock), self.assertRaises(ValueError):
+ images.validate(lock)
+
+ def test_remote_digest_mismatch(self):
+ with patch.object(images, "anonymous_digest", return_value="sha256:" + "c" * 64), self.assertRaisesRegex(ValueError, "digest mismatch"):
+ images.validate(selection(), True)
+
+ def test_provenance_binds_exact_lock_bytes_and_four_builders(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "lock.json"
+ path.write_text(json.dumps(selection()))
+ first = images.provenance(path)
+ self.assertEqual(first["builders"], dict.fromkeys(images.IMAGES, DIGEST))
+ path.write_text(json.dumps(selection(), indent=2))
+ self.assertNotEqual(first["lock_sha256"], images.provenance(path)["lock_sha256"])
+
+ def test_candidate_provenance_mismatch_fails(self):
+ with tempfile.TemporaryDirectory() as directory:
+ lock = Path(directory) / "lock.json"
+ record = Path(directory) / "provenance.json"
+ lock.write_text(json.dumps(selection()))
+ expected = images.provenance(lock)
+ record.write_text(json.dumps({"linux_images": expected}))
+ with patch("sys.argv", ["helper", "verify-provenance", str(lock), str(record)]):
+ images.main()
+ expected["builders"]["armhf_cross"] = "sha256:" + "c" * 64
+ record.write_text(json.dumps({"linux_images": expected}))
+ with self.assertRaisesRegex(ValueError, "provenance does not match"):
+ images.main()
+
+ def test_existing_output_is_never_reused(self):
+ with tempfile.TemporaryDirectory() as directory:
+ with patch("sys.argv", ["helper", "prepare", GENERATION, "--output-directory", directory]), \
+ patch.object(images, "prepare") as prepare, \
+ self.assertRaisesRegex(ValueError, "must not already exist"):
+ images.main()
+ prepare.assert_not_called()
+
+ def prepare(self, existing=None, manifest_values=None):
+ def inspect(reference, anonymous=False, missing_ok=False):
+ return existing if missing_ok else DIGEST
+ with patch.object(images, "inspect", side_effect=inspect), \
+ patch.object(images, "image_manifest", side_effect=manifest_values or manifests()), \
+ patch.object(images, "anonymous_digest", return_value=DIGEST), \
+ patch.object(images, "run") as command:
+ result = images.prepare(GENERATION)
+ return result, command.call_args_list
+
+ def test_copy_preserves_all_manifests_and_digest(self):
+ (lock, _), commands = self.prepare()
+ self.assertEqual(lock, selection())
+ self.assertEqual(len(commands), 4)
+ for call in commands:
+ args = call.args[0]
+ self.assertEqual(args[:4], ["skopeo", "copy", "--all", "--preserve-digests"])
+ self.assertIn("@" + DIGEST, args[4])
+ self.assertTrue(args[5].endswith(":release-deps-" + GENERATION))
+
+ def test_identical_rerun_skips_copy(self):
+ _, commands = self.prepare(existing=DIGEST)
+ self.assertEqual(commands, [])
+
+ def test_conflicting_retained_tag_fails(self):
+ with self.assertRaisesRegex(ValueError, "Conflicting retained"):
+ self.prepare(existing="sha256:" + "c" * 64)
+
+ def test_mixed_armhf_pair_fails_before_copy(self):
+ for field in ("cross_generation", "cross_recipe_sha256", "cross_toolchain_id", "runtime_sha256"):
+ values = manifests()
+ values[-1][field] = "wrong"
+ with self.subTest(field=field), self.assertRaisesRegex(ValueError, "pair mismatch"):
+ self.prepare(manifest_values=values)
+
+ def test_partial_copy_failure_emits_no_selection(self):
+ with tempfile.TemporaryDirectory() as directory:
+ output = Path(directory) / "output"
+ with patch("sys.argv", ["helper", "prepare", GENERATION, "--output-directory", str(output)]), \
+ patch.object(images, "inspect", side_effect=lambda ref, anonymous=False, missing_ok=False: None if missing_ok else DIGEST), \
+ patch.object(images, "image_manifest", side_effect=manifests()), \
+ patch.object(images, "run", side_effect=["", subprocess.CalledProcessError(1, "copy", stderr="denied")]), \
+ self.assertRaises(subprocess.CalledProcessError):
+ images.main()
+ self.assertFalse(output.exists())
+
+ def test_registry_inspection_hashes_exact_manifest_without_platform_selection(self):
+ raw = b'{"mediaType":"application/vnd.oci.image.index.v1+json","manifests":[]}\n'
+ result = subprocess.CompletedProcess([], 0, stdout=raw)
+ with patch.object(images.subprocess, "run", return_value=result) as command:
+ digest = images.inspect("ghcr.io/wsjtx/wsjtx/linux-armv7-bookworm:test", anonymous=True)
+ self.assertEqual(digest, "sha256:" + hashlib.sha256(raw).hexdigest())
+ self.assertIn("--raw", command.call_args.args[0])
+ self.assertIn("--no-creds", command.call_args.args[0])
+
+ def test_authentication_error_is_not_missing_tag(self):
+ with patch.object(images.subprocess, "run", side_effect=subprocess.CalledProcessError(1, "inspect", stderr=b"unauthorized")), self.assertRaises(subprocess.CalledProcessError):
+ images.inspect("test", missing_ok=True)
+
+ def test_only_manifest_unknown_allows_first_copy(self):
+ with patch.object(images.subprocess, "run", side_effect=subprocess.CalledProcessError(1, "inspect", stderr=b"manifest unknown")):
+ self.assertIsNone(images.inspect("test", missing_ok=True))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.github/scripts/tests/test_release_policy.py b/.github/scripts/tests/test_release_policy.py
index a7929484..7a1c6b1e 100644
--- a/.github/scripts/tests/test_release_policy.py
+++ b/.github/scripts/tests/test_release_policy.py
@@ -1,5 +1,6 @@
import importlib.util
import json
+import re
import io
import shutil
import subprocess
@@ -19,15 +20,763 @@ SPEC.loader.exec_module(release_policy)
class ReleasePolicyTest(unittest.TestCase):
- def test_classifies_ga_and_rc(self):
- self.assertEqual(release_policy.classify("3.2.0")["channel"], "GA")
+ def test_candidate_and_public_inventories_require_both_macos_architectures(self):
+ version = "3.2.0-rc1"
+ for distribution in (False, True):
+ mode = "distribution" if distribution else "validation"
+ suffix = "macOS.pkg" if distribution else "macOS-unsigned.pkg"
+ required = {f"wsjtx-{version}-{arch}-{suffix}" for arch in ("arm64", "x86_64")}
+ for inventory in (
+ release_policy.expected_assets(version, distribution),
+ release_policy.public_expected_assets(version, mode),
+ ):
+ with self.subTest(mode=mode, inventory=inventory):
+ self.assertEqual({name for name in inventory if name.endswith(suffix)}, required)
+
+ def test_newest_ga_line_uses_immutable_ga_tags_not_release_order_or_rc_line(self):
+ refs = {
+ "refs/tags/v2.7.0": "a" * 40,
+ "refs/tags/v3.0.2": "b" * 40,
+ "refs/tags/v3.2.0-rc1": "c" * 40,
+ }
+ newest = release_policy.public_release_line_policy("3.2.0", refs)
+ latest_ga_patch = release_policy.public_release_line_policy("3.0.3", refs)
+ self.assertEqual(newest["newest_ga_line"], "3.0")
+ self.assertTrue(newest["ga_line_is_newest"])
+ self.assertTrue(newest["legacy_tag_only"])
+ self.assertTrue(latest_ga_patch["ga_line_is_newest"])
+
+ def test_public_release_line_rejects_missing_or_ambiguous_history(self):
+ with self.assertRaisesRegex(ValueError, "no immutable public vX.Y.Z GA tags"):
+ release_policy.public_release_line_policy("3.2.0", {})
+ with self.assertRaisesRegex(ValueError, "no immutable public vX.Y.Z GA tags"):
+ release_policy.public_release_line_policy("3.2.0", {
+ "refs/tags/v3.2.0-rc1": "a" * 40,
+ "refs/tags/v3.3.0-beta1": "c" * 40,
+ "refs/heads/release/3.2": "b" * 40,
+ })
+ for refs in (
+ {"refs/heads/release/next": "a" * 40},
+ {"refs/tags/v3.2.0-beta0": "a" * 40},
+ {"refs/tags/v3.2.0-alpha1": "a" * 40},
+ ):
+ with self.subTest(refs=refs), self.assertRaisesRegex(ValueError, "malformed"):
+ release_policy.public_release_line_policy("3.2.0", refs)
+
+ def test_latest_line_tag_orders_beta_below_rc_below_ga_and_numbers_numerically(self):
+ for tags, latest in (
+ (("v3.3.0-beta9", "v3.3.0-beta10"), "v3.3.0-beta10"),
+ (("v3.3.0-beta10", "v3.3.0-rc1"), "v3.3.0-rc1"),
+ (("v3.3.0-rc2", "v3.3.0"), "v3.3.0"),
+ (("v3.3.0", "v3.3.1-beta1"), "v3.3.1-beta1"),
+ ):
+ refs = {"refs/tags/v3.0.2": "a" * 40}
+ refs.update({f"refs/tags/{tag}": "b" * 40 for tag in tags})
+ with self.subTest(tags=tags):
+ policy = release_policy.public_release_line_policy("3.3.2", refs)
+ self.assertEqual(policy["latest_public_tag_on_candidate_line"], latest)
+
+ def test_public_ref_listing_resolves_annotated_tags_and_hashes_the_snapshot(self):
+ refs, digest = release_policy.parse_public_ref_listing(
+ "".join((
+ f"{'a' * 40} refs/heads/master\n",
+ f"{'b' * 40} refs/tags/v2.7.0\n",
+ f"{'c' * 40} refs/tags/v2.7.0^{{}}\n",
+ ))
+ )
+ self.assertEqual(refs["refs/heads/master"], "a" * 40)
+ self.assertEqual(refs["refs/tags/v2.7.0"], "c" * 40)
+ line_policy = release_policy.public_release_line_policy("2.7.1", refs)
+ self.assertEqual(line_policy["latest_public_tag_on_candidate_line"], "v2.7.0")
+ self.assertEqual(line_policy["latest_public_tag_sha_on_candidate_line"], "c" * 40)
+ self.assertEqual(len(digest), 64)
+
+ def test_first_public_promotion_creates_release_branch_and_tag_without_master(self):
+ master = "a" * 40
+ candidate = "b" * 40
+ plan = release_policy.plan_public_promotion(
+ "3.2.0-rc1",
+ candidate,
+ {
+ "refs/heads/master": master,
+ "refs/tags/v3.0.2": master,
+ },
+ lambda ancestor, descendant: ancestor == master and descendant == candidate,
+ )
+ self.assertEqual(
+ plan["updates"],
+ ["refs/heads/release/3.2", "refs/tags/v3.2.0-rc1"],
+ )
+ self.assertIsNone(plan["prior_release_branch"])
+ self.assertFalse(plan["advance_master"])
+
+ def test_first_branch_initialization_requires_latest_same_line_tag_ancestry(self):
+ baseline = "a" * 40
+ candidate = "b" * 40
+ refs = {
+ "refs/heads/master": "c" * 40,
+ "refs/tags/v3.0.2": "c" * 40,
+ "refs/tags/v3.2.0-rc1": baseline,
+ }
+ plan = release_policy.plan_public_promotion(
+ "3.2.0-rc2",
+ candidate,
+ refs,
+ lambda ancestor, descendant: (ancestor, descendant) == (baseline, candidate),
+ )
+ self.assertEqual(plan["updates"], [
+ "refs/heads/release/3.2", "refs/tags/v3.2.0-rc2"
+ ])
+ with self.assertRaisesRegex(ValueError, "disconnected branch initialization"):
+ release_policy.plan_public_promotion(
+ "3.2.0-rc2",
+ candidate,
+ refs,
+ lambda ancestor, descendant: False,
+ )
+
+ def test_newest_ga_advances_release_branch_tag_and_master(self):
+ branch = "a" * 40
+ master = "b" * 40
+ candidate = "c" * 40
+ plan = release_policy.plan_public_promotion(
+ "3.2.0",
+ candidate,
+ {
+ "refs/heads/master": master,
+ "refs/heads/release/3.2": branch,
+ "refs/tags/v3.0.2": master,
+ "refs/tags/v3.2.0-rc1": branch,
+ },
+ lambda ancestor, descendant: (ancestor, descendant) in {
+ (branch, candidate),
+ (master, candidate),
+ },
+ )
+ self.assertEqual(
+ plan["updates"],
+ ["refs/heads/release/3.2", "refs/tags/v3.2.0", "refs/heads/master"],
+ )
+ self.assertTrue(plan["advance_master"])
+
+ def test_newer_patch_on_current_ga_line_advances_master(self):
+ current = "a" * 40
+ candidate = "b" * 40
+ plan = release_policy.plan_public_promotion(
+ "3.2.2",
+ candidate,
+ {
+ "refs/heads/master": current,
+ "refs/heads/release/3.2": current,
+ "refs/tags/v3.0.2": current,
+ "refs/tags/v3.2.1": current,
+ },
+ lambda ancestor, descendant: ancestor == current and descendant == candidate,
+ )
+ self.assertTrue(plan["ga_release_is_latest"])
+ self.assertEqual(
+ plan["updates"],
+ ["refs/heads/release/3.2", "refs/tags/v3.2.2", "refs/heads/master"],
+ )
+
+ def test_same_sha_public_promotion_skips_existing_tag_and_is_idempotent(self):
+ candidate = "c" * 40
+ plan = release_policy.plan_public_promotion(
+ "3.2.0",
+ candidate,
+ {
+ "refs/heads/master": candidate,
+ "refs/heads/release/3.2": candidate,
+ "refs/tags/v3.2.0": candidate,
+ "refs/tags/v3.2.0-rc1": "a" * 40,
+ },
+ lambda ancestor, descendant: ancestor == descendant,
+ )
+ self.assertTrue(plan["tag_exists"])
+ self.assertEqual(
+ plan["updates"],
+ ["refs/heads/release/3.2", "refs/heads/master"],
+ )
+
+ def test_public_promotion_rejects_conflicting_tag_and_non_fast_forward_branch(self):
+ candidate = "c" * 40
+ refs = {
+ "refs/heads/master": "a" * 40,
+ "refs/tags/v3.0.2": "a" * 40,
+ "refs/tags/v3.2.0-rc1": "b" * 40,
+ }
+ with self.assertRaisesRegex(ValueError, "tags are never moved"):
+ release_policy.plan_public_promotion(
+ "3.2.0-rc1", candidate,
+ {**refs, "refs/tags/v3.2.0-rc1": "d" * 40},
+ lambda ancestor, descendant: True,
+ )
+ with self.assertRaisesRegex(ValueError, "non-fast-forward"):
+ release_policy.plan_public_promotion(
+ "3.2.0-rc2", candidate,
+ {**refs, "refs/heads/release/3.2": "d" * 40},
+ lambda ancestor, descendant: False,
+ )
+
+ def test_older_line_ga_advances_only_its_release_branch(self):
+ old_branch = "a" * 40
+ newest = "b" * 40
+ candidate = "c" * 40
+ plan = release_policy.plan_public_promotion(
+ "3.0.3",
+ candidate,
+ {
+ "refs/heads/master": newest,
+ "refs/heads/release/3.0": old_branch,
+ "refs/heads/release/3.2": newest,
+ "refs/tags/v3.0.2": old_branch,
+ "refs/tags/v3.2.0": newest,
+ },
+ lambda ancestor, descendant: (ancestor, descendant) == (old_branch, candidate),
+ )
+ self.assertEqual(
+ plan["updates"],
+ ["refs/heads/release/3.0", "refs/tags/v3.0.3"],
+ )
+ self.assertFalse(plan["advance_master"])
+
+ def test_newest_ga_requires_master_history_bridge(self):
+ with self.assertRaisesRegex(ValueError, "history bridge"):
+ release_policy.plan_public_promotion(
+ "3.2.0",
+ "c" * 40,
+ {
+ "refs/heads/master": "d" * 40,
+ "refs/heads/release/3.2": "a" * 40,
+ "refs/tags/v3.0.2": "d" * 40,
+ "refs/tags/v3.2.0-rc1": "a" * 40,
+ },
+ lambda ancestor, descendant: (ancestor, descendant) == ("a" * 40, "c" * 40),
+ )
+
+ def test_lower_ga_patch_on_current_line_cannot_be_promoted_as_latest(self):
+ current = "a" * 40
+ candidate = "b" * 40
+ refs = {
+ "refs/heads/master": current,
+ "refs/heads/release/3.2": current,
+ "refs/tags/v3.0.2": current,
+ "refs/tags/v3.2.1": current,
+ }
+ decision = release_policy.public_release_line_policy("3.2.0", refs)
+ self.assertFalse(decision["ga_release_is_latest"])
+ with self.assertRaisesRegex(ValueError, "lower GA version cannot advance"):
+ release_policy.plan_public_promotion(
+ "3.2.0",
+ candidate,
+ refs,
+ lambda ancestor, descendant: ancestor == current,
+ )
+
+ def test_lower_ga_patch_on_older_line_cannot_be_promoted(self):
+ current = "a" * 40
+ with self.assertRaisesRegex(ValueError, "lower GA version cannot advance"):
+ release_policy.plan_public_promotion(
+ "3.0.1",
+ "b" * 40,
+ {
+ "refs/heads/master": current,
+ "refs/tags/v3.0.2": current,
+ "refs/tags/v3.2.0": current,
+ },
+ lambda ancestor, descendant: True,
+ )
+
+ def test_first_beta_promotion_creates_line_branch_and_tag_without_master(self):
+ master = "a" * 40
+ plan = release_policy.plan_public_promotion(
+ "3.3.0-beta1",
+ "b" * 40,
+ {
+ "refs/heads/master": master,
+ "refs/tags/v3.0.2": master,
+ "refs/heads/release/3.2": "c" * 40,
+ "refs/tags/v3.2.0-rc1": "c" * 40,
+ },
+ lambda ancestor, descendant: False,
+ )
+ self.assertEqual(plan["channel"], "BETA")
+ self.assertEqual(plan["updates"], ["refs/heads/release/3.3", "refs/tags/v3.3.0-beta1"])
+ self.assertFalse(plan["advance_master"])
+ self.assertFalse(plan["ga_release_is_latest"])
+
+ def test_beta_on_the_newest_line_never_advances_master(self):
+ master = "a" * 40
+ beta1 = "b" * 40
+ candidate = "c" * 40
+ plan = release_policy.plan_public_promotion(
+ "3.3.0-beta2",
+ candidate,
+ {
+ "refs/heads/master": master,
+ "refs/tags/v3.2.0": master,
+ "refs/heads/release/3.3": beta1,
+ "refs/tags/v3.3.0-beta1": beta1,
+ },
+ lambda ancestor, descendant: (ancestor, descendant) in {(beta1, candidate), (master, candidate)},
+ )
+ self.assertTrue(plan["ga_line_is_newest"])
+ self.assertFalse(plan["advance_master"])
+ self.assertFalse(plan["ga_release_is_latest"])
+ self.assertEqual(plan["updates"], ["refs/heads/release/3.3", "refs/tags/v3.3.0-beta2"])
+
+ def test_promotion_requires_the_candidate_to_sort_above_the_latest_line_tag(self):
+ def refs(latest: str) -> dict:
+ line = latest[1:].rsplit(".", 1)[0]
+ return {
+ "refs/heads/master": "c" * 40,
+ "refs/tags/v3.0.2": "c" * 40,
+ f"refs/heads/release/{line}": "a" * 40,
+ f"refs/tags/{latest}": "a" * 40,
+ }
+
+ for version, latest in (
+ ("3.2.0-rc1", "v3.2.0-rc2"),
+ ("3.2.0-rc3", "v3.2.0"),
+ ("3.3.0-beta2", "v3.3.0-rc1"),
+ ("3.3.0-beta9", "v3.3.0-beta10"),
+ ):
+ with self.subTest(version=version, latest=latest), self.assertRaisesRegex(
+ ValueError, f"{latest} is the latest public tag on this line; v{version} must sort above it"
+ ):
+ release_policy.plan_public_promotion(
+ version, "b" * 40, refs(latest), lambda ancestor, descendant: True
+ )
+ for version, latest in (
+ ("3.3.0-beta10", "v3.3.0-beta9"),
+ ("3.3.0-rc1", "v3.3.0-beta5"),
+ ("3.3.0", "v3.3.0-rc2"),
+ ("3.3.1-beta1", "v3.3.0"),
+ ):
+ with self.subTest(version=version, latest=latest):
+ plan = release_policy.plan_public_promotion(
+ version, "b" * 40, refs(latest), lambda ancestor, descendant: True
+ )
+ self.assertIn(f"refs/tags/v{version}", plan["updates"])
+
+ def test_same_sha_beta_repromotion_is_idempotent(self):
+ candidate = "c" * 40
+ plan = release_policy.plan_public_promotion(
+ "3.3.0-beta1",
+ candidate,
+ {
+ "refs/heads/master": "a" * 40,
+ "refs/tags/v3.0.2": "a" * 40,
+ "refs/heads/release/3.3": candidate,
+ "refs/tags/v3.3.0-beta1": candidate,
+ },
+ lambda ancestor, descendant: ancestor == descendant,
+ )
+ self.assertTrue(plan["tag_exists"])
+ self.assertEqual(plan["updates"], ["refs/heads/release/3.3"])
+
+ def test_old_line_ga_and_rc_plans_with_public_beta_tags(self):
+ master = "a" * 40
+ rc1 = "b" * 40
+ beta1 = "d" * 40
+ candidate = "c" * 40
+ refs = {
+ "refs/heads/master": master,
+ "refs/tags/v3.0.2": master,
+ "refs/heads/release/3.2": rc1,
+ "refs/tags/v3.2.0-rc1": rc1,
+ "refs/heads/release/3.3": beta1,
+ "refs/tags/v3.3.0-beta1": beta1,
+ }
+ ancestry = {(rc1, candidate), (master, candidate)}
+
+ ga = release_policy.plan_public_promotion(
+ "3.2.0", candidate, refs, lambda ancestor, descendant: (ancestor, descendant) in ancestry
+ )
+ self.assertEqual(ga["newest_ga_line"], "3.0")
+ self.assertTrue(ga["ga_line_is_newest"])
+ self.assertTrue(ga["ga_release_is_latest"])
+ self.assertEqual(
+ ga["updates"],
+ ["refs/heads/release/3.2", "refs/tags/v3.2.0", "refs/heads/master"],
+ )
+
+ rc2 = release_policy.plan_public_promotion(
+ "3.2.0-rc2", candidate, refs, lambda ancestor, descendant: (ancestor, descendant) in ancestry
+ )
+ self.assertFalse(rc2["advance_master"])
+ self.assertEqual(rc2["updates"], ["refs/heads/release/3.2", "refs/tags/v3.2.0-rc2"])
+
+ self.assertFalse(release_policy.public_release_line_policy("3.2.0-rc2", refs)["ga_release_is_latest"])
+ beta2 = release_policy.public_release_line_policy("3.3.0-beta2", refs)
+ self.assertFalse(beta2["ga_release_is_latest"])
+ self.assertEqual(beta2["latest_public_tag_on_candidate_line"], "v3.3.0-beta1")
+
+ def test_older_line_ga_patch_with_newer_line_beta_tags_leaves_master(self):
+ newest = "a" * 40
+ branch = "b" * 40
+ candidate = "c" * 40
+ plan = release_policy.plan_public_promotion(
+ "3.2.1",
+ candidate,
+ {
+ "refs/heads/master": newest,
+ "refs/tags/v3.3.0": newest,
+ "refs/heads/release/3.2": branch,
+ "refs/tags/v3.2.0": branch,
+ "refs/tags/v3.4.0-beta1": "d" * 40,
+ },
+ lambda ancestor, descendant: (ancestor, descendant) == (branch, candidate),
+ )
+ self.assertEqual(plan["newest_ga_line"], "3.3")
+ self.assertFalse(plan["advance_master"])
+ self.assertFalse(plan["ga_release_is_latest"])
+ self.assertEqual(plan["updates"], ["refs/heads/release/3.2", "refs/tags/v3.2.1"])
+
+ def test_public_promotion_fetches_legacy_line_tag_before_branch_bootstrap(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ bare = root / "public.git"
+ source = root / "source"
+ legacy = root / "legacy"
+ subprocess.run(["git", "init", "--bare", bare], check=True, capture_output=True)
+ # Background auto-maintenance would race the directory's removal.
+ subprocess.run(["git", "--git-dir", bare, "config", "maintenance.auto", "false"], check=True)
+ for repository in (source, legacy):
+ subprocess.run(["git", "init", repository], check=True, capture_output=True)
+ for key, value in (
+ ("user.name", "Release Test"),
+ ("user.email", "release-test@example.invalid"),
+ ("maintenance.auto", "false"),
+ ):
+ subprocess.run(["git", "-C", repository, "config", key, value], check=True)
+ (repository / "source.txt").write_text(repository.name, encoding="utf-8")
+ subprocess.run(["git", "-C", repository, "add", "source.txt"], check=True)
+ subprocess.run(
+ ["git", "-C", repository, "commit", "-m", repository.name],
+ check=True,
+ capture_output=True,
+ )
+
+ def head(repository: Path) -> str:
+ return subprocess.run(
+ ["git", "-C", repository, "rev-parse", "HEAD"],
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout.strip()
+
+ source_head = head(source)
+ legacy_head = head(legacy)
+ for repository in (source, legacy):
+ subprocess.run(
+ ["git", "-C", repository, "remote", "add", "public", bare],
+ check=True,
+ )
+ subprocess.run(
+ ["git", "-C", source, "push", "public", f"{source_head}:refs/heads/master"],
+ check=True,
+ capture_output=True,
+ )
+ subprocess.run(
+ ["git", "-C", source, "push", "public", f"{source_head}:refs/tags/v3.0.2"],
+ check=True,
+ capture_output=True,
+ )
+ subprocess.run(
+ ["git", "-C", legacy, "push", "public", f"{legacy_head}:refs/tags/v3.2.0-rc1"],
+ check=True,
+ capture_output=True,
+ )
+
+ (source / "source.txt").write_text("disconnected", encoding="utf-8")
+ subprocess.run(["git", "-C", source, "add", "source.txt"], check=True)
+ subprocess.run(
+ ["git", "-C", source, "commit", "-m", "disconnected candidate"],
+ check=True,
+ capture_output=True,
+ )
+ with self.assertRaisesRegex(ValueError, "disconnected branch initialization"):
+ release_policy.inspect_public_promotion(
+ "3.2.0-rc2", head(source), "public", cwd=source
+ )
+
+ subprocess.run(
+ ["git", "-C", source, "checkout", "--detach", legacy_head],
+ check=True,
+ capture_output=True,
+ )
+ (source / "source.txt").write_text("descends from public RC", encoding="utf-8")
+ subprocess.run(["git", "-C", source, "add", "source.txt"], check=True)
+ subprocess.run(
+ ["git", "-C", source, "commit", "-m", "connected candidate"],
+ check=True,
+ capture_output=True,
+ )
+ plan = release_policy.inspect_public_promotion(
+ "3.2.0-rc2", head(source), "public", cwd=source
+ )
+ self.assertEqual(
+ plan["updates"],
+ ["refs/heads/release/3.2", "refs/tags/v3.2.0-rc2"],
+ )
+
+ def test_atomic_public_push_rejects_raced_branch_update_without_creating_tag(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ bare = root / "public.git"
+ work = root / "source"
+ subprocess.run(["git", "init", "--bare", bare], check=True, capture_output=True)
+ subprocess.run(["git", "--git-dir", bare, "config", "maintenance.auto", "false"], check=True)
+ subprocess.run(["git", "init", work], check=True, capture_output=True)
+ for key, value in (("user.name", "Release Test"), ("user.email", "release-test@example.invalid"),
+ ("maintenance.auto", "false")):
+ subprocess.run(["git", "-C", work, "config", key, value], check=True)
+
+ def commit(parent: str | None, content: str, subject: str) -> str:
+ if parent:
+ subprocess.run(["git", "-C", work, "checkout", "--detach", parent], check=True, capture_output=True)
+ (work / "source.txt").write_text(content, encoding="utf-8")
+ subprocess.run(["git", "-C", work, "add", "source.txt"], check=True)
+ subprocess.run(["git", "-C", work, "commit", "-m", subject], check=True, capture_output=True)
+ return subprocess.run(
+ ["git", "-C", work, "rev-parse", "HEAD"],
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout.strip()
+
+ initial = commit(None, "initial", "initial")
+ subprocess.run(["git", "-C", work, "remote", "add", "public", bare], check=True)
+ subprocess.run(["git", "-C", work, "push", "public", f"{initial}:refs/heads/master"], check=True, capture_output=True)
+ subprocess.run(["git", "-C", work, "push", "public", f"{initial}:refs/tags/v3.0.2"], check=True, capture_output=True)
+
+ first_candidate = commit(initial, "rc1", "rc1")
+ first_plan = release_policy.inspect_public_promotion(
+ "3.2.0-rc1", first_candidate, "public", cwd=work
+ )
+ release_policy.push_public_ref_updates("public", first_plan, cwd=work)
+ release_policy.push_public_ref_updates(
+ "public",
+ release_policy.inspect_public_promotion(
+ "3.2.0-rc1", first_candidate, "public", cwd=work
+ ),
+ cwd=work,
+ )
+ subprocess.run(
+ ["git", "-C", work, "push", "public", f"{initial}:refs/heads/release/3.4"],
+ check=True,
+ capture_output=True,
+ )
+ with self.assertRaisesRegex(ValueError, "changed after validation"):
+ release_policy.promote_public_source(
+ "3.2.0-rc1",
+ first_candidate,
+ "public",
+ first_plan["public_refs_digest"],
+ cwd=work,
+ )
+
+ second_candidate = commit(first_candidate, "rc2", "rc2")
+ second_plan = release_policy.inspect_public_promotion(
+ "3.2.0-rc2", second_candidate, "public", cwd=work
+ )
+ release_policy.push_public_ref_updates("public", second_plan, cwd=work)
+
+ stale_candidate = commit(second_candidate, "rc3", "rc3")
+ stale_plan = release_policy.inspect_public_promotion(
+ "3.2.0-rc3", stale_candidate, "public", cwd=work
+ )
+ concurrent = commit(initial, "concurrent", "concurrent branch update")
+ subprocess.run(["git", "-C", work, "push", "public", f"{concurrent}:refs/heads/race"], check=True, capture_output=True)
+ subprocess.run(
+ ["git", "--git-dir", bare, "update-ref", "refs/heads/release/3.2", concurrent],
+ check=True,
+ )
+
+ with self.assertRaisesRegex(ValueError, "atomic public ref update failed"):
+ release_policy.push_public_ref_updates("public", stale_plan, cwd=work)
+ actual_branch = subprocess.run(
+ ["git", "--git-dir", bare, "rev-parse", "refs/heads/release/3.2"],
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout.strip()
+ self.assertEqual(actual_branch, concurrent)
+ missing_tag = subprocess.run(
+ ["git", "--git-dir", bare, "show-ref", "--verify", "refs/tags/v3.2.0-rc3"],
+ capture_output=True,
+ text=True,
+ )
+ self.assertNotEqual(missing_tag.returncode, 0)
+
+ def test_public_promotion_reads_annotated_public_beta_tags(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ bare = root / "public.git"
+ work = root / "source"
+ subprocess.run(["git", "init", "--bare", bare], check=True, capture_output=True)
+ subprocess.run(["git", "--git-dir", bare, "config", "maintenance.auto", "false"], check=True)
+ subprocess.run(["git", "init", work], check=True, capture_output=True)
+ for key, value in (("user.name", "Release Test"), ("user.email", "release-test@example.invalid"),
+ ("maintenance.auto", "false")):
+ subprocess.run(["git", "-C", work, "config", key, value], check=True)
+
+ def git(*arguments: str) -> str:
+ return subprocess.run(
+ ["git", "-C", work, *arguments], check=True, capture_output=True, text=True
+ ).stdout.strip()
+
+ def commit(parent: str, subject: str) -> str:
+ if parent:
+ git("checkout", "--detach", parent)
+ (work / "source.txt").write_text(subject, encoding="utf-8")
+ git("add", "source.txt")
+ git("commit", "-m", subject)
+ return git("rev-parse", "HEAD")
+
+ initial = commit("", "initial")
+ rc1 = commit(initial, "rc1")
+ beta1 = commit(rc1, "beta1")
+ git("tag", "-a", "v3.3.0-beta1", "-m", "beta1", beta1)
+ git("remote", "add", "public", str(bare))
+ for source, ref in (
+ (initial, "refs/heads/master"),
+ (initial, "refs/tags/v3.0.2"),
+ (rc1, "refs/heads/release/3.2"),
+ (rc1, "refs/tags/v3.2.0-rc1"),
+ (beta1, "refs/heads/release/3.3"),
+ ("refs/tags/v3.3.0-beta1", "refs/tags/v3.3.0-beta1"),
+ ):
+ git("push", "public", f"{source}:{ref}")
+
+ rc2 = commit(rc1, "rc2")
+ self.assertEqual(
+ release_policy.inspect_public_promotion("3.2.0-rc2", rc2, "public", cwd=work)["updates"],
+ ["refs/heads/release/3.2", "refs/tags/v3.2.0-rc2"],
+ )
+ beta2 = commit(beta1, "beta2")
+ plan = release_policy.inspect_public_promotion("3.3.0-beta2", beta2, "public", cwd=work)
+ self.assertEqual(plan["latest_public_tag_sha_on_candidate_line"], beta1)
+ self.assertEqual(plan["updates"], ["refs/heads/release/3.3", "refs/tags/v3.3.0-beta2"])
+
+ def test_accepts_publication_environment_with_one_or_more_reviewers_and_self_review(self):
+ release_policy.validate_publication_environment({
+ "name": "public-release",
+ "protection_rules": [{
+ "type": "required_reviewers",
+ "prevent_self_review": False,
+ "reviewers": [
+ {"type": "User", "reviewer": {"id": 42}},
+ {"type": "Team", "reviewer": {"id": 7}},
+ ],
+ }],
+ })
+
+ def test_rejects_missing_publication_reviewers(self):
+ with self.assertRaisesRegex(ValueError, "one required-reviewers rule"):
+ release_policy.validate_publication_environment({
+ "name": "public-release",
+ "protection_rules": [],
+ })
+
+ def test_rejects_malformed_or_self_review_blocking_publication_rule(self):
+ for rule in (
+ {"type": "required_reviewers", "reviewers": [{"type": "User", "reviewer": {"id": 42}}]},
+ {
+ "type": "required_reviewers",
+ "prevent_self_review": True,
+ "reviewers": [{"type": "User", "reviewer": {"id": 42}}],
+ },
+ {
+ "type": "required_reviewers",
+ "prevent_self_review": False,
+ "reviewers": [{"type": "User", "reviewer": {"id": "42"}}],
+ },
+ ):
+ with self.subTest(rule=rule), self.assertRaises(ValueError):
+ release_policy.validate_publication_environment({
+ "name": "public-release",
+ "protection_rules": [rule],
+ })
+
+ def test_beta_publication_requires_beta_release_without_reviewers_for_beta_tags_only(self):
+ environment = {
+ "name": "beta-release",
+ "protection_rules": [{"type": "branch_policy"}],
+ "deployment_branch_policy": {"protected_branches": False, "custom_branch_policies": True},
+ }
+ policies = {"total_count": 1, "branch_policies": [{"id": 3, "name": "v*-beta*", "type": "tag"}]}
+ release_policy.validate_publication_environment(environment, "BETA", policies)
+ reviewers = {
+ "type": "required_reviewers",
+ "prevent_self_review": False,
+ "reviewers": [{"type": "Team", "reviewer": {"id": 7}}],
+ }
+ protected_only = {"protected_branches": True, "custom_branch_policies": False}
+ only_beta_tags = "exactly the v\\*-beta\\* tag pattern"
+ for broken, broken_policies, message in (
+ ({**environment, "name": "public-release"}, policies, "beta-release environment response"),
+ ({**environment, "protection_rules": [reviewers]}, policies, "must not require reviewers"),
+ ({**environment, "deployment_branch_policy": None}, policies, "custom deployment patterns"),
+ ({**environment, "deployment_branch_policy": protected_only}, policies, "custom deployment patterns"),
+ (environment, None, only_beta_tags),
+ (environment, {"branch_policies": []}, only_beta_tags),
+ (environment, {"branch_policies": [{"name": "v*", "type": "tag"}]}, only_beta_tags),
+ (environment, {"branch_policies": [{"name": "v*-beta*", "type": "branch"}]}, only_beta_tags),
+ (
+ environment,
+ {"branch_policies": [{"name": "v*-beta*", "type": "tag"}, {"name": "v*-rc*", "type": "tag"}]},
+ only_beta_tags,
+ ),
+ ):
+ with self.subTest(message=message, environment=broken, policies=broken_policies):
+ with self.assertRaisesRegex(ValueError, message):
+ release_policy.validate_publication_environment(broken, "BETA", broken_policies)
+
+ def test_rc_and_ga_publication_keep_the_public_release_reviewer_rule(self):
+ public = {
+ "name": "public-release",
+ "protection_rules": [{
+ "type": "required_reviewers",
+ "prevent_self_review": False,
+ "reviewers": [{"type": "Team", "reviewer": {"id": 7}}],
+ }],
+ }
+ beta = {
+ "name": "beta-release",
+ "protection_rules": [],
+ "deployment_branch_policy": {"protected_branches": False, "custom_branch_policies": True},
+ }
+ policies = {"branch_policies": [{"name": "v*-beta*", "type": "tag"}]}
+ for channel in ("RC", "GA"):
+ with self.subTest(channel=channel):
+ release_policy.validate_publication_environment(public, channel)
+ with self.assertRaisesRegex(ValueError, "public-release environment response"):
+ release_policy.validate_publication_environment(beta, channel, policies)
+ with self.assertRaisesRegex(ValueError, "one required-reviewers rule"):
+ release_policy.validate_publication_environment(
+ {"name": "public-release", "protection_rules": []}, channel
+ )
+
+ def test_classifies_ga_beta_and_rc(self):
+ ga = release_policy.classify("3.2.0")
+ self.assertEqual((ga["channel"], ga["prerelease_number"]), ("GA", ""))
identity = release_policy.classify("3.2.0-rc2")
self.assertEqual(identity["channel"], "RC")
- self.assertEqual(identity["rc_number"], "2")
+ self.assertEqual(identity["prerelease_number"], "2")
self.assertEqual(identity["release_branch"], "release/3.2")
+ beta = release_policy.classify("3.3.0-beta10")
+ self.assertEqual(
+ (beta["channel"], beta["prerelease_number"], beta["release_branch"]),
+ ("BETA", "10", "release/3.3"),
+ )
def test_rejects_non_release_versions(self):
- for version in ("v3.2.0", "3.2.0-beta1", "3.2", "3.2.0-rc0"):
+ for version in (
+ "v3.2.0", "3.2", "3.2.0-rc0", "3.2.0-beta0", "3.2.0-beta", "3.2.0-alpha1",
+ "3.2.0-beta1-rc1", "3.2.0-BETA1", "3.2.0-devel",
+ ):
with self.subTest(version=version), self.assertRaises(ValueError):
release_policy.classify(version)
@@ -37,7 +786,7 @@ class ReleasePolicyTest(unittest.TestCase):
(root / "release-state.txt").write_text(
"version=3.2.0\n"
"channel=RC\n"
- "rc=1\n"
+ "prerelease=1\n"
"revision=$Format:%H$\n"
)
identity = release_policy.validate_source(root, "3.2.0-rc1")
@@ -46,18 +795,74 @@ class ReleasePolicyTest(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "release channel"):
release_policy.validate_source(root, "3.2.0")
(root / "release-state.txt").write_text(
- "version=3.2.0\nchannel=RC\nrc=1\nrevision=" + "a" * 40 + "\n"
+ "version=3.2.0\nchannel=RC\nprerelease=1\nrevision=" + "a" * 40 + "\n"
)
with self.assertRaisesRegex(ValueError, "revision"):
release_policy.validate_source(root, "3.2.0-rc1")
- def test_read_state_cli_accepts_single_digit_rc(self):
+ def test_parse_state_prerelease_contract(self):
+ def state(channel: str, prerelease: str, *extra: str) -> str:
+ lines = ("version=3.3.0", f"channel={channel}", f"prerelease={prerelease}", "revision=$Format:%H$")
+ return "\n".join((*lines, *extra)) + "\n"
+
+ beta = release_policy.parse_state(state("BETA", "1", "windows_signing=unsigned"))
+ self.assertEqual(
+ (beta["channel"], beta["prerelease"], beta["windows_signing"]),
+ ("BETA", "1", "unsigned"),
+ )
+ self.assertEqual(release_policy.parse_state(state("RC", "2"))["windows_signing"], "signpath")
+ self.assertEqual(release_policy.parse_state(state("DEVEL", ""))["prerelease"], "")
+ for contents, message in (
+ (state("BETA", "1"), "BETA release state requires windows_signing=unsigned"),
+ (state("BETA", "1", "windows_signing=signpath"), "BETA release state requires windows_signing=unsigned"),
+ (state("BETA", "", "windows_signing=unsigned"), "positive prerelease number"),
+ (state("BETA", "0", "windows_signing=unsigned"), "positive prerelease number"),
+ (state("RC", "0"), "positive prerelease number"),
+ (state("DEVEL", "1"), "empty prerelease number"),
+ (state("GA", "1"), "empty prerelease number"),
+ (state("ALPHA", "1"), "channel must be DEVEL, BETA, RC, or GA"),
+ (state("RC", "1").replace("prerelease=", "rc="), "must define version, channel, prerelease, revision"),
+ ):
+ with self.subTest(contents=contents), self.assertRaisesRegex(ValueError, message):
+ release_policy.parse_state(contents)
+
+ def test_validates_beta_source_and_archive(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ state = (
+ "version=3.3.0\nchannel=BETA\nprerelease=1\n"
+ "revision=$Format:%H$\nwindows_signing=unsigned\n"
+ )
+ (root / "release-state.txt").write_text(state)
+ identity = release_policy.validate_source(root, "3.3.0-beta1")
+ self.assertEqual(
+ (identity["channel"], identity["prerelease_number"], identity["windows_signing"]),
+ ("BETA", "1", "unsigned"),
+ )
+ for version, message in (
+ ("3.3.0-beta2", "prerelease number 1 does not match 2"),
+ ("3.3.0-rc1", "release channel BETA does not match RC"),
+ ):
+ with self.subTest(version=version), self.assertRaisesRegex(ValueError, message):
+ release_policy.validate_source(root, version)
+ commit = "e" * 40
+ archived_state = state.replace("$Format:%H$", commit).encode()
+ archive = root / "source.tar.gz"
+ with tarfile.open(archive, "w:gz") as output:
+ info = tarfile.TarInfo("wsjtx-3.3.0-beta1/release-state.txt")
+ info.size = len(archived_state)
+ output.addfile(info, io.BytesIO(archived_state))
+ release_policy.validate_archive(archive, "3.3.0-beta1", commit)
+ with self.assertRaisesRegex(ValueError, "release identity does not match"):
+ release_policy.validate_archive(archive, "3.3.0-beta2", commit)
+
+ def test_read_state_cli_accepts_single_digit_prerelease(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / "release-state.txt").write_text(
"version=3.2.0\n"
"channel=RC\n"
- "rc=1\n"
+ "prerelease=1\n"
"revision=$Format:%H$\n"
)
result = subprocess.run(
@@ -71,7 +876,7 @@ class ReleasePolicyTest(unittest.TestCase):
{
"version": "3.2.0",
"channel": "RC",
- "rc": "1",
+ "prerelease": "1",
"revision": "$Format:%H$",
"windows_signing": "signpath",
},
@@ -80,7 +885,7 @@ class ReleasePolicyTest(unittest.TestCase):
(root / "release-state.txt").write_text(
"version=3.2.0\n"
"channel=RC\n"
- "rc=1beta\n"
+ "prerelease=1beta\n"
"revision=$Format:%H$\n"
)
result = subprocess.run(
@@ -89,13 +894,13 @@ class ReleasePolicyTest(unittest.TestCase):
text=True,
)
self.assertNotEqual(result.returncode, 0)
- self.assertIn("positive RC number", result.stderr)
+ self.assertIn("positive prerelease number", result.stderr)
def test_source_pins_unsigned_mode_and_rejects_unknown_mode(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
state = (
- "version=3.2.0\nchannel=RC\nrc=1\n"
+ "version=3.2.0\nchannel=RC\nprerelease=1\n"
"revision=$Format:%H$\nwindows_signing=unsigned\n"
)
(root / "release-state.txt").write_text(state)
@@ -118,7 +923,7 @@ class ReleasePolicyTest(unittest.TestCase):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
commit = "b" * 40
- state = f"version=3.2.0\nchannel=RC\nrc=1\nrevision={commit}\n".encode()
+ state = f"version=3.2.0\nchannel=RC\nprerelease=1\nrevision={commit}\n".encode()
tar_path = root / "source.tar.gz"
with tarfile.open(tar_path, "w:gz") as archive:
info = tarfile.TarInfo("wsjtx-3.2.0-rc1/release-state.txt")
@@ -132,6 +937,43 @@ class ReleasePolicyTest(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "revision"):
release_policy.validate_archive(tar_path, "3.2.0-rc1", "c" * 40)
+ def test_candidate_and_public_gates_reject_missing_intel_payloads(self):
+ version = "3.3.0-beta1"
+ for distribution in (False, True):
+ mode = "distribution" if distribution else "validation"
+ for public in (False, True):
+ with self.subTest(mode=mode, public=public), tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ expected = (
+ release_policy.public_expected_assets(version, mode)
+ if public else release_policy.expected_assets(version, distribution)
+ )
+ for name in expected:
+ target = root / name
+ target.mkdir()
+ suffix = release_policy.asset_suffix(name)
+ filename = name.replace("-unsigned", "")
+ if not filename.endswith(suffix):
+ filename += suffix
+ (target / filename).write_bytes(name.encode())
+ def verify():
+ if public:
+ return release_policy.find_public_asset_files(root, version, mode)
+ return release_policy.find_asset_files(root, version, distribution)
+ verify()
+ suffix = "macOS.pkg" if distribution else "macOS-unsigned.pkg"
+ required = [f"wsjtx-{version}-x86_64-{suffix}"] + [
+ f"wsjtx-{version}-x86_64-macOS-{group}"
+ for group in ("jt9", "jt9stream", "wsprd", "utilities")
+ ]
+ for name in required:
+ artifact = root / name
+ held = root / "held"
+ artifact.rename(held)
+ with self.subTest(missing=name), self.assertRaisesRegex(ValueError, re.escape(name)):
+ verify()
+ held.rename(artifact)
+
def test_distribution_gate_rejects_unsigned_package(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
@@ -139,7 +981,7 @@ class ReleasePolicyTest(unittest.TestCase):
for name in release_policy.expected_assets(version, True):
target = root / name
target.mkdir()
- suffix = ".pkg" if "macOS" in name else ".AppImage" if "linux" in name else ".exe"
+ suffix = release_policy.asset_suffix(name)
(target / f"artifact{suffix}").write_bytes(b"signed")
(root / "extra").mkdir()
(root / "extra" / "unexpected-unsigned.pkg").write_bytes(b"unsigned")
@@ -153,7 +995,7 @@ class ReleasePolicyTest(unittest.TestCase):
for name in release_policy.expected_assets(version, True):
target = root / name
target.mkdir()
- suffix = ".pkg" if "macOS" in name else ".AppImage" if "linux" in name else ".exe"
+ suffix = release_policy.asset_suffix(name)
(target / f"{name}{suffix}" if not name.endswith(suffix) else target / name).write_bytes(name.encode())
for arch in ("x86_64", "aarch64", "armhf"):
for package_type in ("deb", "rpm"):
@@ -180,21 +1022,82 @@ class ReleasePolicyTest(unittest.TestCase):
self.assertEqual(manifest["macos_signing"]["mode"], "distribution")
self.assertEqual(manifest["macos_signing"]["replaceable_assets"], [])
self.assertEqual(manifest["windows_signing"]["mode"], "signpath")
- self.assertEqual(len(manifest["assets"]), 13)
+ self.assertEqual(len(manifest["assets"]), 37)
+ self.assertTrue(
+ {f"{name}.tar.gz" for name in release_policy.release_tarballs(version)}
+ <= {entry["name"] for entry in manifest["assets"]}
+ )
def test_manual_macos_assets_keep_release_names_without_immutable_hashes(self):
+ for version in ("3.2.0", "3.2.0-rc1"):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ for name in release_policy.public_expected_assets(version, "validation"):
+ target = root / name
+ target.mkdir()
+ if name in release_policy.release_tarballs(version):
+ filename = f"{name}.tar.gz"
+ elif "macOS" in name:
+ filename = name.replace("-unsigned", "")
+ elif "linux" in name:
+ filename = f"{name}.AppImage"
+ else:
+ filename = "wsjtx-win64.exe"
+ (target / filename).write_bytes(name.encode())
+ for arch in ("x86_64", "aarch64", "armhf"):
+ for package_type in ("deb", "rpm"):
+ target = root / f"wsjtx-{version}-linux-{arch}-{package_type}"
+ target.mkdir()
+ (target / f"wsjtx-{arch}.{package_type}").write_bytes(arch.encode())
+ (root / f"wsjtx-{version}-src.tar.gz").write_bytes(b"source")
+ args = type("Args", (), {
+ "artifacts": str(root), "version": version, "repository": "WSJTX/wsjtx",
+ "commit": "a" * 40, "run_id": "123",
+ "linux_x86_64_digest": "sha256:" + "1" * 64,
+ "linux_aarch64_digest": "sha256:" + "2" * 64,
+ "linux_armhf_cross_digest": "sha256:" + "3" * 64,
+ "linux_armhf_digest": "sha256:" + "4" * 64,
+ "macos_mode": "validation",
+ "windows_mode": "signpath",
+ })()
+
+ release_policy.write_manifest(args)
+
+ manifest = json.loads((root / "release-manifest.json").read_text())
+ replaceable = {
+ f"wsjtx-{version}-arm64-macOS.pkg",
+ f"wsjtx-{version}-x86_64-macOS.pkg",
+ }
+ release_names = {path.name for path in release_policy.release_files(root, version, "validation")}
+ immutable_names = {entry["name"] for entry in manifest["assets"]}
+ checksum_names = {
+ line.split(" ", 1)[1]
+ for line in (root / "SHA256SUMS").read_text().splitlines()
+ }
+ self.assertEqual(manifest["macos_signing"]["mode"], "manual")
+ self.assertEqual(set(manifest["macos_signing"]["replaceable_assets"]), replaceable)
+ self.assertTrue(replaceable <= release_names)
+ self.assertTrue(replaceable.isdisjoint(immutable_names))
+ self.assertTrue(replaceable.isdisjoint(checksum_names))
+ self.assertIn("wsjtx-win64.exe", immutable_names)
+ tarballs = {f"{name}.tar.gz" for name in release_policy.release_tarballs(version)}
+ self.assertTrue(tarballs <= immutable_names & checksum_names)
+
+ def test_unsigned_windows_manifest_selects_and_hashes_installer(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
- version = "3.2.0"
- for name in release_policy.public_expected_assets(version, "validation"):
+ version = "3.2.0-rc1"
+ for name in release_policy.public_expected_assets(version, "validation", "unsigned"):
target = root / name
target.mkdir()
- if "macOS" in name:
+ if name in release_policy.release_tarballs(version):
+ filename = f"{name}.tar.gz"
+ elif "macOS" in name:
filename = name.replace("-unsigned", "")
elif "linux" in name:
filename = f"{name}.AppImage"
else:
- filename = "wsjtx-win64.exe"
+ filename = f"wsjtx-{version}-win64.exe"
(target / filename).write_bytes(name.encode())
for arch in ("x86_64", "aarch64", "armhf"):
for package_type in ("deb", "rpm"):
@@ -209,38 +1112,147 @@ class ReleasePolicyTest(unittest.TestCase):
"linux_aarch64_digest": "sha256:" + "2" * 64,
"linux_armhf_cross_digest": "sha256:" + "3" * 64,
"linux_armhf_digest": "sha256:" + "4" * 64,
- "macos_mode": "validation",
- "windows_mode": "signpath",
+ "macos_mode": "validation", "windows_mode": "unsigned",
})()
-
release_policy.write_manifest(args)
-
manifest = json.loads((root / "release-manifest.json").read_text())
- replaceable = {
- f"wsjtx-{version}-arm64-macOS.pkg",
- f"wsjtx-{version}-x86_64-macOS.pkg",
- }
- release_names = {path.name for path in release_policy.release_files(root, version, "validation")}
- immutable_names = {entry["name"] for entry in manifest["assets"]}
- checksum_names = {
- line.split(" ", 1)[1]
- for line in (root / "SHA256SUMS").read_text().splitlines()
- }
- self.assertEqual(manifest["macos_signing"]["mode"], "manual")
- self.assertEqual(set(manifest["macos_signing"]["replaceable_assets"]), replaceable)
- self.assertTrue(replaceable <= release_names)
- self.assertTrue(replaceable.isdisjoint(immutable_names))
- self.assertTrue(replaceable.isdisjoint(checksum_names))
- self.assertIn("wsjtx-win64.exe", immutable_names)
+ installer = f"wsjtx-{version}-win64.exe"
+ self.assertEqual(manifest["windows_signing"]["mode"], "unsigned")
+ self.assertIn(installer, {entry["name"] for entry in manifest["assets"]})
+ for group in ("jt9", "jt9stream", "wsprd", "utilities"):
+ self.assertIn(
+ f"wsjtx-{version}-windows-x86_64-{group}.tar.gz", {entry["name"] for entry in manifest["assets"]}
+ )
+ self.assertIn(installer, (root / "SHA256SUMS").read_text())
+ installer_path = root / f"wsjtx-{version}-windows-x86_64-installer" / installer
+ installer_path.rename(installer_path.with_name("unexpected.exe"))
+ with self.assertRaisesRegex(ValueError, "unexpected unsigned Windows installer"):
+ release_policy.find_public_asset_files(root, version, "validation", "unsigned")
+ installer_path.with_name("unexpected.exe").rename(installer_path)
+ signed_dir = root / f"wsjtx-{version}-windows-x86_64-installer-signed"
+ signed_dir.mkdir()
+ with self.assertRaisesRegex(ValueError, "signed Windows installer"):
+ release_policy.find_public_asset_files(root, version, "validation", "unsigned")
- def test_unsigned_windows_manifest_selects_and_hashes_installer(self):
+ def test_release_tarballs_are_required_by_candidate_and_public_gates(self):
+ version = "3.2.0-rc1"
+ tools = release_policy.release_tarballs(version)
+ self.assertEqual(
+ tools,
+ [
+ f"wsjtx-{version}-{target}-{group}"
+ for target in ("arm64-macOS", "x86_64-macOS", "linux-x86_64", "linux-aarch64", "linux-armhf", "windows-x86_64")
+ for group in ("jt9", "jt9stream", "wsprd", "utilities")
+ ],
+ )
+ self.assertEqual([release_policy.asset_suffix(name) for name in tools], [".tar.gz"] * 24)
+ self.assertEqual(
+ [release_policy.asset_suffix(name) for name in release_policy.expected_assets(version, False)[:6]],
+ [".pkg", ".pkg", ".AppImage", ".AppImage", ".AppImage", ".exe"],
+ )
+ for distribution in (False, True):
+ self.assertTrue(set(tools) <= set(release_policy.expected_assets(version, distribution)))
+ for macos_mode in release_policy.MACOS_MODES:
+ for windows_mode in release_policy.WINDOWS_MODES:
+ self.assertTrue(
+ set(tools) <= set(release_policy.public_expected_assets(version, macos_mode, windows_mode))
+ )
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
- version = "3.2.0-rc1"
+ for name in release_policy.expected_assets(version, False):
+ target = root / name
+ target.mkdir()
+ (target / f"{name}{release_policy.asset_suffix(name)}").write_bytes(name.encode())
+ files = release_policy.find_asset_files(root, version, False)
+ self.assertEqual(
+ sorted(path.name for path in files if path.name.endswith(".tar.gz")),
+ sorted(f"{name}.tar.gz" for name in tools),
+ )
+ armhf = root / f"wsjtx-{version}-linux-armhf-jt9stream"
+ (armhf / f"{armhf.name}.tar.gz").unlink()
+ with self.assertRaisesRegex(ValueError, "linux-armhf-jt9stream must contain exactly one .tar.gz"):
+ release_policy.find_asset_files(root, version, False)
+
+ def test_release_tarball_uploads_agree_with_the_group_file_and_the_policy(self):
+ root = SCRIPT.parents[2]
+ action = (root / ".github/actions/upload-release-tarballs/action.yml").read_text(encoding="utf-8")
+ prefix = r"wsjtx-\$\{\{ inputs\.version \}\}-\$\{\{ inputs\.target \}\}-"
+ names = re.findall(rf"\n name: {prefix}(\S+)\n", action)
+ paths = re.findall(rf"\n path: \$\{{\{{ inputs\.directory \}}\}}/{prefix}(\S+)\.tar\.gz\n", action)
+ self.assertEqual(names, release_policy.tarball_groups())
+ self.assertEqual(paths, names)
+ self.assertEqual(action.count("if-no-files-found: error"), len(names))
+
+ version = "3.3.0"
+ installers = []
+ for name in release_policy.public_expected_assets(version, "validation", "unsigned"):
+ if name not in release_policy.release_tarballs(version):
+ installers.append(re.sub(r"-(unsigned\.pkg|AppImage|installer)$", "", name.removeprefix(f"wsjtx-{version}-")).removesuffix(".pkg"))
+ self.assertEqual(installers, list(release_policy.RELEASE_TARGETS))
+ macos_arches = [target.removesuffix("-macOS") for target in installers if target.endswith("-macOS")]
+ linux_arches = [target.removeprefix("linux-") for target in installers if target.startswith("linux-")]
+
+ uploads = []
+ for path in (
+ ".github/workflows/build-macos.yml", ".github/workflows/build-windows.yml",
+ ".github/workflows/build-linux.yml", ".github/actions/build-linux-payload/action.yml",
+ ):
+ text = (root / path).read_text(encoding="utf-8")
+ calls = re.findall(
+ r"uses: \./\.github/actions/upload-release-tarballs\n\s+with:\n\s+version: \$\{\{ inputs\.version \}\}\n"
+ r"\s+target: (.+)\n\s+directory: release-tarballs\n",
+ text,
+ )
+ self.assertEqual(len(calls), text.count("upload-release-tarballs"), path)
+ uploads += [(path, target) for target in calls]
+ targets = {target for _, target in uploads if "${{" not in target}
+ for path, target in uploads:
+ if target == "${{ inputs.arch }}-macOS":
+ targets |= {f"{arch}-macOS" for arch in macos_arches}
+ elif target == "linux-${{ inputs.arch }}":
+ targets |= {f"linux-{arch}" for arch in linux_arches if f"linux-{arch}" not in targets}
+ self.assertEqual(targets, set(release_policy.RELEASE_TARGETS))
+
+ def test_tarball_groups_come_from_the_group_file(self):
+ self.assertEqual(release_policy.tarball_groups(), ["jt9", "jt9stream", "wsprd", "utilities"])
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "release-tarballs.txt"
+ path.write_bytes(b"# comment\r\njt9 jt9\r\n\r\nengine jt9stream wsprd\r\n")
+ self.assertEqual(release_policy.tarball_groups(path), ["jt9", "engine"])
+ for contents, message in (
+ ("", "must name each release tarball once"),
+ ("# only a comment\n", "must name each release tarball once"),
+ ("jt9 jt9\njt9 jt9stream\n", "must name each release tarball once"),
+ ("jt9 jt9\nutilities\n", "release tarball utilities names no programs"),
+ ("jt9 jt9\ninstaller wsprd\n", "release tarball name installer cannot name a release asset"),
+ ("jt9 jt9\nsrc wsprd\n", "release tarball name src cannot name a release asset"),
+ ("jt9 jt9\nAppImage wsprd\n", "release tarball name AppImage cannot name a release asset"),
+ ):
+ with self.subTest(contents=contents):
+ path.write_text(contents, encoding="utf-8")
+ with self.assertRaisesRegex(ValueError, message):
+ release_policy.tarball_groups(path)
+
+ def test_asset_suffix_tells_tarballs_from_installers_on_every_target(self):
+ version = "3.3.0-beta1"
+ for name in release_policy.release_tarballs(version):
+ with self.subTest(name=name):
+ self.assertEqual(release_policy.asset_suffix(name), ".tar.gz")
+ self.assertEqual(
+ [release_policy.asset_suffix(name) for name in release_policy.public_expected_assets(version, "validation", "unsigned")[:6]],
+ [".pkg", ".pkg", ".AppImage", ".AppImage", ".AppImage", ".exe"],
+ )
+
+ def test_beta_manifest_hashes_unsigned_macos_packages_as_immutable_assets(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ version = "3.3.0-beta2"
for name in release_policy.public_expected_assets(version, "validation", "unsigned"):
target = root / name
target.mkdir()
- if "macOS" in name:
+ if name in release_policy.release_tarballs(version):
+ filename = f"{name}.tar.gz"
+ elif "macOS" in name:
filename = name.replace("-unsigned", "")
elif "linux" in name:
filename = f"{name}.AppImage"
@@ -262,21 +1274,29 @@ class ReleasePolicyTest(unittest.TestCase):
"linux_armhf_digest": "sha256:" + "4" * 64,
"macos_mode": "validation", "windows_mode": "unsigned",
})()
+
release_policy.write_manifest(args)
+
manifest = json.loads((root / "release-manifest.json").read_text())
- installer = f"wsjtx-{version}-win64.exe"
- self.assertEqual(manifest["windows_signing"]["mode"], "unsigned")
- self.assertIn(installer, {entry["name"] for entry in manifest["assets"]})
- self.assertIn(installer, (root / "SHA256SUMS").read_text())
- installer_path = root / f"wsjtx-{version}-windows-x86_64-installer" / installer
- installer_path.rename(installer_path.with_name("unexpected.exe"))
- with self.assertRaisesRegex(ValueError, "unexpected unsigned Windows installer"):
- release_policy.find_public_asset_files(root, version, "validation", "unsigned")
- installer_path.with_name("unexpected.exe").rename(installer_path)
- signed_dir = root / f"wsjtx-{version}-windows-x86_64-installer-signed"
- signed_dir.mkdir()
- with self.assertRaisesRegex(ValueError, "signed Windows installer"):
- release_policy.find_public_asset_files(root, version, "validation", "unsigned")
+ beta_assets = {f"wsjtx-{version}-{arch}-macOS.pkg" for arch in ("arm64", "x86_64")}
+ beta_assets |= {f"{name}.tar.gz" for name in release_policy.release_tarballs(version)}
+ immutable_names = {entry["name"] for entry in manifest["assets"]}
+ checksum_names = {
+ line.split(" ", 1)[1]
+ for line in (root / "SHA256SUMS").read_text().splitlines()
+ }
+ self.assertEqual(manifest["macos_signing"], {"mode": "unsigned", "replaceable_assets": []})
+ self.assertTrue(beta_assets <= immutable_names)
+ self.assertTrue(beta_assets <= checksum_names)
+ hashes = {entry["name"]: entry["sha256"] for entry in manifest["assets"]}
+ for arch in ("arm64", "x86_64"):
+ name = f"wsjtx-{version}-{arch}-macOS.pkg"
+ package = root / f"wsjtx-{version}-{arch}-macOS-unsigned.pkg" / name
+ self.assertEqual(hashes[name], release_policy.hash_file(package))
+
+ args.macos_mode = "distribution"
+ with self.assertRaisesRegex(ValueError, "BETA releases publish the validated unsigned macOS packages"):
+ release_policy.write_manifest(args)
def test_signing_reports_bind_hashes_and_source(self):
with tempfile.TemporaryDirectory() as directory:
@@ -316,6 +1336,18 @@ class ReleasePolicyTest(unittest.TestCase):
"signer_thumbprint": "5678", "identity_verified": True,
}))
release_policy.verify_signing_reports(root, version, commit, tag)
+ intel_report = root / f"macos-signing-report-{version}-x86_64" / "macos-signing-report.json"
+ contents = intel_report.read_bytes()
+ intel_report.unlink()
+ with self.assertRaisesRegex(ValueError, "macos-signing-report.*x86_64"):
+ release_policy.verify_signing_reports(root, version, commit, tag)
+ intel_report.write_bytes(contents)
+ intel_report_data = json.loads(contents)
+ intel_report_data["sha256"] = "0" * 64
+ intel_report.write_text(json.dumps(intel_report_data))
+ with self.assertRaisesRegex(ValueError, "macOS x86_64 report hash"):
+ release_policy.verify_signing_reports(root, version, commit, tag)
+ intel_report.write_bytes(contents)
(verification_dir / "verification.json").write_text("{}")
with self.assertRaisesRegex(ValueError, "release ref"):
release_policy.verify_signing_reports(root, version, commit, tag)
@@ -357,6 +1389,18 @@ class ReleasePolicyTest(unittest.TestCase):
}))
release_policy.verify_signing_reports(root, version, commit, tag, "validation")
+ intel_report = root / f"macos-signing-report-{version}-x86_64" / "macos-signing-report.json"
+ contents = intel_report.read_bytes()
+ intel_report.unlink()
+ with self.assertRaisesRegex(ValueError, "macos-signing-report.*x86_64"):
+ release_policy.verify_signing_reports(root, version, commit, tag, "validation")
+ intel_report.write_bytes(contents)
+ intel_report_data = json.loads(contents)
+ intel_report_data["sha256"] = "0" * 64
+ intel_report.write_text(json.dumps(intel_report_data))
+ with self.assertRaisesRegex(ValueError, "macOS x86_64 report hash"):
+ release_policy.verify_signing_reports(root, version, commit, tag, "validation")
+ intel_report.write_bytes(contents)
report = json.loads(
(root / f"macos-signing-report-{version}-arm64" / "macos-signing-report.json").read_text()
diff --git a/.github/scripts/tests/test_release_workflow_policy.py b/.github/scripts/tests/test_release_workflow_policy.py
new file mode 100644
index 00000000..68e8c23d
--- /dev/null
+++ b/.github/scripts/tests/test_release_workflow_policy.py
@@ -0,0 +1,202 @@
+import pathlib
+import re
+import unittest
+
+
+ROOT = pathlib.Path(__file__).resolve().parents[3]
+PUBLIC = (ROOT / ".github/workflows/public-release.yml").read_text()
+SIGN = (ROOT / ".github/workflows/sign-windows-release.yml").read_text()
+PREPARE = (ROOT / ".github/workflows/prepare-release-dependencies.yml").read_text()
+
+
+def step(workflow: str, name: str) -> str:
+ start = workflow.index(f" - name: {name}\n")
+ following = re.search(r"\n - ", workflow[start + 1:])
+ return workflow[start:start + 1 + following.start()] if following else workflow[start:]
+
+
+def job(workflow: str, name: str) -> str:
+ start = workflow.index(f"\n {name}:\n") + 1
+ following = re.search(r"\n [A-Za-z0-9_-]+:\n", workflow[start:])
+ return workflow[start:start + following.start() + 1] if following else workflow[start:]
+
+
+class ReleaseWorkflowPolicyTests(unittest.TestCase):
+ def test_both_macos_jobs_are_required_before_candidate_and_public_assembly(self):
+ release = (ROOT / ".github/workflows/release.yml").read_text()
+ for workflow, gate in ((release, "candidate-ready"), (PUBLIC, "assemble")):
+ self.assertIn("needs: [prepare, macos, macos-intel, linux, linux-arm, linux-armhf, windows]", job(workflow, gate))
+ for name, arch, runner, target in (
+ ("macos", "arm64", "macos-15", "11.0"),
+ ("macos-intel", "x86_64", "macos-15-intel", "10.13"),
+ ):
+ body = job(workflow, name)
+ self.assertIn("needs: prepare", body)
+ self.assertNotIn(" if:", body)
+ self.assertIn("uses: ./.github/workflows/build-macos.yml", body)
+ self.assertIn(f"arch: {arch}", body)
+ self.assertIn(f"runner: {runner}", body)
+ self.assertIn(f'deployment_target: "{target}"', body)
+ self.assertNotIn("rc_number:", body)
+ self.assertNotIn("release_channel:", body)
+ signing = "validation" if gate == "candidate-ready" else "${{ needs.prepare.outputs.macos_sign_mode }}"
+ self.assertIn(f"signing_mode: {signing}", body)
+
+ def test_intel_ci_is_opt_in_and_selected_artifacts_include_it(self):
+ ci = (ROOT / ".github/workflows/ci.yml").read_text()
+ intel = job(ci, "macos-intel")
+ self.assertIn("needs: [prepare, linux]", intel)
+ predicate = intel.split(" if: >-\n", 1)[1].split(" uses:", 1)[0]
+ self.assertEqual(predicate.strip(), "github.event_name == 'workflow_dispatch' ||\n contains(github.event.pull_request.labels.*.name, 'full-ci')")
+ selected = (ROOT / ".github/workflows/build-selected-artifacts.yml").read_text()
+ self.assertIn(" - macos-x64\n", selected)
+ body = job(selected, "macos-x64")
+ self.assertIn("(inputs.targets == 'macos-x64' || inputs.targets == 'all')", body)
+ self.assertIn("needs: [prepare, linux-smoke-x64]", body)
+ for body in (intel, body):
+ self.assertIn('arch: "x86_64"', body)
+ self.assertIn('runner: "macos-15-intel"', body)
+ self.assertIn('deployment_target: "10.13"', body)
+ self.assertNotIn("release_channel:", body)
+ self.assertNotIn("rc_number:", body)
+
+ def test_macos_dispatch_defaults_and_compiler_selection_support_intel(self):
+ build = (ROOT / ".github/workflows/build-macos.yml").read_text()
+ runner = "${{ inputs.runner || (inputs.arch == 'x86_64' && 'macos-15-intel' || 'macos-15') }}"
+ self.assertIn("runs-on: " + runner, job(build, "build"))
+ self.assertIn("RUNNER: " + runner, job(build, "build"))
+ self.assertIn("runs-on: " + runner, job(build, "sign_distribution"))
+ self.assertIn("DEPLOYMENT_TARGET: ${{ inputs.deployment_target || (inputs.arch == 'x86_64' && '10.13' || '11.0') }}", build)
+ self.assertIn(" - x86_64\n", build)
+ action = (ROOT / ".github/actions/warm-macos-deps/action.yml").read_text()
+ for text in (build, action):
+ self.assertIn("arm64:macos-15:11.0|x86_64:macos-15-intel:10.13)", text)
+ self.assertIn("if: inputs.arch == 'x86_64'", text)
+ self.assertIn(".github/scripts/install-xpack-gfortran-macos.sh", text)
+ self.assertIn('if [ "${{ inputs.arch }}" = "x86_64" ]; then', text)
+ self.assertIn("steps.controlled-intel-fc.outputs.runtime_archives", text)
+
+ def test_intel_cache_jobs_outputs_and_summary_are_connected(self):
+ warm = (ROOT / ".github/workflows/warm-dependency-caches.yml").read_text()
+ self.assertIn(" - macos-x86_64\n", warm)
+ self.assertIn("macos_x86_64: ${{ steps.detect.outputs.macos_x86_64 }}", job(warm, "detect"))
+ deps = job(warm, "warm-macos-x86_64-deps")
+ compiler = job(warm, "warm-macos-x86_64-ccache")
+ self.assertIn("needs: detect", deps)
+ self.assertIn("needs: [detect, warm-macos-x86_64-deps]", compiler)
+ for body in (deps, compiler):
+ self.assertIn("if: needs.detect.outputs.macos_x86_64 == 'true'", body)
+ self.assertIn("arch: x86_64", body)
+ self.assertIn("runner: macos-15-intel", body)
+ self.assertIn('deployment_target: "10.13"', body)
+ self.assertIn("runs-on: macos-15-intel", deps)
+ self.assertIn("save_ccache: true", compiler)
+ summary = job(warm, "summary")
+ self.assertIn("- warm-macos-x86_64-deps", summary)
+ self.assertIn("- warm-macos-x86_64-ccache", summary)
+
+ def test_public_release_marks_every_non_ga_channel_prerelease_and_latest_stays_ga_only(self):
+ publish = step(PUBLIC, "Publish public GitHub Release")
+ self.assertRegex(publish, r'if \[ "\$CHANNEL" != GA \]; then\s+EXPECTED_PRERELEASE=true\s+fi')
+ self.assertRegex(publish, r'if \[ "\$CHANNEL" != GA \]; then\s+FLAGS\+=\(--prerelease\)\s+fi')
+ self.assertEqual(publish.count("--prerelease"), 1)
+ self.assertRegex(
+ publish,
+ r'LATEST=false\s+if \[ "\$CHANNEL" = GA \] && \[ "\$GA_RELEASE_IS_LATEST" = true \]; then\s+LATEST=true\s+fi',
+ )
+ self.assertEqual(publish.count("LATEST=true"), 1)
+ self.assertIn('FLAGS+=("--latest=$LATEST")', publish)
+
+ def test_publication_environment_and_its_validation_follow_the_channel(self):
+ selected = "${{ needs.prepare.outputs.release_channel == 'BETA' && 'beta-release' || 'public-release' }}"
+ self.assertIn(f" environment: {selected}\n", job(PUBLIC, "publish"))
+ guard = step(PUBLIC, "Validate final publication environment protection")
+ self.assertRegex(
+ guard,
+ r'ENVIRONMENT=public-release\s+POLICIES=\(\)\s+'
+ r'if \[ "\$CHANNEL" = BETA \]; then\s+ENVIRONMENT=beta-release',
+ )
+ self.assertIn('"repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT/deployment-branch-policies"', guard)
+ self.assertIn('"repos/$GITHUB_REPOSITORY/environments/$ENVIRONMENT"', guard)
+ self.assertIn('--channel "$CHANNEL" "${POLICIES[@]}"', guard)
+ self.assertLess(PUBLIC.index(guard), PUBLIC.index("\n macos:\n"))
+
+ def test_betas_publish_validated_macos_packages_with_nothing_replaceable(self):
+ identity = step(PUBLIC, "Validate public release tag and source identity")
+ self.assertRegex(
+ identity,
+ r'if \[ "\$CHANNEL" = BETA \]; then\s+echo "macos_sign_mode=validation" >> "\$GITHUB_OUTPUT"',
+ )
+ self.assertLess(
+ identity.index('[ "$CHANNEL" = BETA ]'),
+ identity.index('[ "$MACOS_DISTRIBUTION_SIGNING_ENABLED" = true ]'),
+ )
+ recheck = step(PUBLIC, "Recheck bundle and immutable public tag")
+ self.assertRegex(recheck, r'if \[ "\$CHANNEL" = BETA \]; then\s+EXPECTED_MACOS_MODE=unsigned\s+elif')
+ publish = step(PUBLIC, "Publish public GitHub Release")
+ self.assertIn(".macos_signing.replaceable_assets[]", publish)
+ self.assertNotIn("MACOS_MODE", publish)
+
+ def test_a_rerun_compares_every_published_asset_except_the_manifests_replaceable_ones(self):
+ publish = step(PUBLIC, "Publish public GitHub Release")
+ self.assertIn("mapfile -t REPLACEABLE_NAMES < <(jq -r '.macos_signing.replaceable_assets[]' "
+ "release-bundle/release-manifest.json)", publish)
+ preserve = [
+ "if printf '%s\\n' \"${REPLACEABLE_NAMES[@]}\" | grep -Fxq \"$name\"; then",
+ "if printf '%s\\n' \"${ACTUAL_NAMES[@]}\" | grep -Fxq \"$name\"; then",
+ "echo \"Preserving manually replaceable macOS asset: $name\"",
+ ]
+ self.assertRegex(publish, r"\s+".join(map(re.escape, preserve)))
+ self.assertEqual(len(re.findall(r"^\s+continue$", publish, re.M)), 1)
+ self.assertEqual(publish.count('cmp "$file"'), 1)
+
+ def test_a_new_release_body_carries_the_change_list_or_keeps_the_generated_notes(self):
+ self.assertIn("fetch-depth: 0", job(PUBLIC, "publish"))
+ publish = step(PUBLIC, "Publish public GitHub Release")
+ self.assertIn("--generate-notes", publish)
+ notes = publish[publish.index('if [ "$CREATED" = true ]; then'):]
+ self.assertIn('CHANGES=$(python3 .github/scripts/generate-change-list.py \\\n'
+ ' "$GITHUB_REPOSITORY" "$GITHUB_REF_NAME" || true)', notes)
+ self.assertRegex(notes, r'if \[ -z "\$CHANGES" \]; then\s+echo "::warning::[^"]*"\s+'
+ r'CHANGES=\$\(gh release view "\$GITHUB_REF_NAME" --json body --jq \.body \|\| true\)')
+ # Notes never fail a publication, and a body without changes never replaces GitHub's notes.
+ edit = notes.index("gh release edit")
+ self.assertRegex(notes[:edit], r'if \[ -z "\$CHANGES" \]; then\s+echo "::warning::[^"]*"\s+else\s+NOTES=\$CHANGES\s')
+ self.assertRegex(notes[edit:], r'^gh release edit "\$GITHUB_REF_NAME" --notes-file "\$RUNNER_TEMP/release-notes.md" \\\n'
+ r'\s+\|\| echo "::warning::[^"]*"\n\s+fi\n')
+ self.assertEqual(notes.count("gh release edit"), 1)
+
+ def test_windows_signing_guard_admits_only_rc_and_ga(self):
+ guard = step(SIGN, "Require a public RC or GA invocation")
+ self.assertIn('test "$(jq -r .channel <<<"$IDENTITY")" = "$CHANNEL"', guard)
+ self.assertIn('test "$CHANNEL" = RC || test "$CHANNEL" = GA', guard)
+ self.assertLess(SIGN.index(guard), SIGN.index("uses: signpath/github-action-submit-signing-request"))
+
+ def test_dependency_preparation_fails_unless_develop_and_the_source_branch_are_protected(self):
+ prepare = job(PREPARE, "prepare")
+ self.assertIn("github.ref == 'refs/heads/develop'", prepare.split("\n steps:\n", 1)[0])
+ self.assertEqual(PREPARE.count("ref_protected"), 1)
+ self.assertNotIn("continue-on-error", prepare)
+ guard = step(PREPARE, "Require protected develop")
+ self.assertNotRegex(guard, r"\n if:")
+ self.assertIn("REF_PROTECTED: ${{ github.ref_protected }}", guard)
+ self.assertRegex(guard, r'if \[ "\$REF_PROTECTED" != true \]; then\s+echo "::error::[^"]+"\s+exit 1')
+ self.assertLess(prepare.index("Require protected develop"), prepare.index("actions/checkout"))
+ source = step(PREPARE, "Resolve protected source branch to an exact commit")
+ self.assertRegex(
+ source,
+ r'if \[ "\$\(jq -r \'\.protected\' <<< "\$branch"\)" != true \]; then\s+echo "::error::[^"]+"\s+exit 1',
+ )
+
+ def test_full_artifact_downloads_drop_the_armhf_build_tree(self):
+ release = (ROOT / ".github/workflows/release.yml").read_text()
+ for workflow, job_name, next_step in ((release, "candidate-ready", "Verify all candidate artifacts"), (PUBLIC, "assemble", "Build corresponding source archive")):
+ body = job(workflow, job_name)
+ download = body.index("uses: actions/download-artifact@v8\n with:\n path: artifacts\n")
+ drop = body.index(" - name: Drop the ARMHF build tree\n run: rm -rf artifacts/armhf-build-tree\n")
+ self.assertLess(download, drop, job_name)
+ self.assertLess(drop, body.index(f" - name: {next_step}\n"), job_name)
+
+
+if __name__ == "__main__":
+ unittest.main()