import json import os import subprocess import tempfile import unittest from pathlib import Path ROOT = Path(__file__).resolve().parents[2] DEPLOY = ROOT / "scripts" / "deploy-community.sh" class DeployCommunityMigrationGuardTests(unittest.TestCase): def run_deploy( self, *, version: int = 15, preflight: str | None = None, apply_success: bool = True, plan: str | None = None, ) -> tuple[subprocess.CompletedProcess[str], list[list[str]], Path]: temporary = tempfile.TemporaryDirectory() self.addCleanup(temporary.cleanup) root = Path(temporary.name) bin_dir = root / "bin" bin_dir.mkdir() tmp_dir = root / "tmp" tmp_dir.mkdir() log = root / "docker.jsonl" if preflight is None: preflight = json.dumps( {"status": "current", "version": version}, separators=(",", ":") ) (root / ".env").write_text( "POSTGRES_HOST=postgres\nPOSTGRES_PASSWORD=test-password\nCRANK_ADMIN_API_IMAGE=crank:test\n", encoding="utf-8", ) (root / "docker-compose.yml").write_text("services: {}\n", encoding="utf-8") docker = r'''#!/usr/bin/env python3 import json, os, pathlib, sys args = sys.argv[1:] with open(os.environ["FAKE_DOCKER_LOG"], "a", encoding="utf-8") as stream: stream.write(json.dumps(args) + "\n") if args[:2] == ["compose", "config"] and args[2:3] == ["--services"]: print("admin-api") elif args[:2] == ["compose", "ps"]: pass elif args[:2] == ["compose", "up"]: pass elif args[:2] == ["network", "create"]: print(args[2]) elif args[:2] == ["network", "rm"] or args[:2] == ["rm", "-fv"]: pass elif args[:1] == ["logs"]: print("PostgreSQL init process complete") elif args[:1] == ["exec"] and "pg_isready" in args: pass elif args[:1] == ["exec"] and "psql" in args: pass elif args[:1] == ["run"]: if "pg_dump" in args: mount = next(value for value in args if value.startswith("/") and ":/backup" in value) pathlib.Path(mount.split(":/backup", 1)[0], "postgres.dump").write_bytes(b"fake dump") elif "crank-migrate" in args: command = args[args.index("crank-migrate") + 1:] if command == ["apply"]: sys.exit(0 if os.environ.get("FAKE_APPLY_SUCCESS") == "1" else 1) if command == ["plan", "--target-version"]: sys.stdout.write(os.environ["FAKE_PLAN_OUTPUT"] + "\n") elif command == ["preflight"]: sys.stdout.write(os.environ["FAKE_PREFLIGHT"] + "\n") elif args[:1] == ["inspect"] and args[1:2] == ["--format"]: print("") sys.exit(0) ''' curl = "#!/bin/sh\nexit 0\n" sleep = "#!/bin/sh\nexit 0\n" for name, contents in (("docker", docker), ("curl", curl), ("sleep", sleep)): path = bin_dir / name path.write_text(contents, encoding="utf-8") path.chmod(0o755) env = os.environ.copy() env.update( { "PATH": f"{bin_dir}:{env['PATH']}", "FAKE_DOCKER_LOG": str(log), "FAKE_PREFLIGHT": preflight, "FAKE_APPLY_SUCCESS": "1" if apply_success else "0", "FAKE_PLAN_OUTPUT": plan if plan is not None else str(version), "TMPDIR": str(tmp_dir), } ) result = subprocess.run( ["sh", str(DEPLOY), str(root)], text=True, capture_output=True, env=env, check=False, ) calls = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] return result, calls, root def test_current_v13_shadow_migration_allows_compose_up(self) -> None: result, calls, root = self.run_deploy(version=13) self.assertEqual(result.returncode, 0, result.stderr) self.assertTrue(any(call[:2] == ["compose", "up"] for call in calls)) self.assertTrue(any(call[:2] == ["rm", "-fv"] for call in calls)) self.assertTrue(any(call[:2] == ["network", "rm"] for call in calls)) self.assertEqual(list((root / "tmp").iterdir()), []) def test_current_v15_shadow_migration_allows_compose_up(self) -> None: result, calls, root = self.run_deploy(version=15) self.assertEqual(result.returncode, 0, result.stderr) self.assertTrue(any(call[:2] == ["compose", "up"] for call in calls)) self.assertEqual(list((root / "tmp").iterdir()), []) def test_future_current_shadow_migration_allows_compose_up(self) -> None: result, calls, root = self.run_deploy(version=27) self.assertEqual(result.returncode, 0, result.stderr) self.assertTrue(any(call[:2] == ["compose", "up"] for call in calls)) self.assertEqual(list((root / "tmp").iterdir()), []) def test_invalid_preflight_responses_and_failed_apply_never_start_compose(self) -> None: cases = ( ("", True), ("not-json", True), ('noise\n{"status":"current","version":15}', True), ('{"status":"current","version":15}\nnoise', True), ('{"status":"current","version":15}\n', True), ('{"status":"applied","version":15}', True), ('{"status":"current","version":13}', True), ('{"status":"current","version":15,"extra":true}', True), ('{"status":"current","version":"15"}', True), ('{"status":"current","version":15}', False), ) for preflight, apply_success in cases: with self.subTest(preflight=preflight, apply_success=apply_success): result, calls, root = self.run_deploy( version=15, preflight=preflight, apply_success=apply_success ) self.assertNotEqual(result.returncode, 0) self.assertFalse(any(call[:2] == ["compose", "up"] for call in calls)) self.assertTrue(any(call[:2] == ["rm", "-fv"] for call in calls)) self.assertTrue(any(call[:2] == ["network", "rm"] for call in calls)) self.assertEqual(list((root / "tmp").iterdir()), []) def test_invalid_target_version_is_rejected_before_shadow_database(self) -> None: for target in ("", "0", "-1", "version", "15\n16", "15\n", "015"): with self.subTest(target=target): result, calls, _ = self.run_deploy(version=15, plan=target) self.assertNotEqual(result.returncode, 0) self.assertFalse(any(call[:2] == ["compose", "up"] for call in calls)) self.assertFalse(any(call[:2] == ["network", "create"] for call in calls)) if __name__ == "__main__": unittest.main()