Skip to content

Python tool for aircraft Doppler audio geolocation using historical ADS-B flight data (Source-available)

5.5 KB
Raw Blame
"""Offline checks of release restoration; no public download is required."""
import hashlib
import importlib.util
import io
import json
from pathlib import Path
import tarfile
import tempfile
import unittest
from unittest.mock import patch

SCRIPT = Path(__file__).resolve().parents[1] / "scripts/restore_ci_checkpoint.py"
SPEC = importlib.util.spec_from_file_location("restore_ci_checkpoint", SCRIPT)
RESTORE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(RESTORE)


class CheckpointRestoreTests(unittest.TestCase):
    def setUp(self):
        self.temporary = tempfile.TemporaryDirectory()
        self.addCleanup(self.temporary.cleanup)
        self.root = Path(self.temporary.name)
        self.destination = self.root / "checkout"
        self.destination.mkdir()
        self.archive = self.root / "fixture.tar.gz"
        self.files = {"data/source/input.txt": b"reference fixture\n",
                      "data/terrain/settings.json": b"{}\n"}
        with tarfile.open(self.archive, "w:gz") as bundle:
            for name, content in self.files.items():
                member = tarfile.TarInfo(name)
                member.size = len(content)
                bundle.addfile(member, io.BytesIO(content))
        self.asset = {"name": self.archive.name, "bytes": self.archive.stat().st_size,
                      "sha256": RESTORE.digest(self.archive),
                      "files": [{"path": name, "bytes": len(content),
                                 "sha256": hashlib.sha256(content).hexdigest()}
                                for name, content in self.files.items()]}

    def test_verified_contents_restored_and_second_run_preserves_files(self):
        self.assertEqual(RESTORE.restore_archive(self.archive, self.asset, self.destination), 2)
        for name, content in self.files.items():
            self.assertEqual((self.destination / name).read_bytes(), content)
        target = self.destination / "data/source/input.txt"
        target.write_bytes(b"independent evidence")
        with self.assertRaises(FileExistsError):
            RESTORE.restore_archive(self.archive, self.asset, self.destination)
        self.assertEqual(target.read_bytes(), b"independent evidence")

    def test_member_checksum_failure_writes_no_destination_files(self):
        self.asset["files"][-1]["sha256"] = "0" * 64
        with self.assertRaisesRegex(ValueError, "Checksum/size mismatch"):
            RESTORE.restore_archive(self.archive, self.asset, self.destination)
        self.assertEqual(list(self.destination.iterdir()), [])

    def test_manifest_missing_member_is_rejected_before_writes(self):
        self.asset["files"].append({"path": "data/source/missing.txt", "bytes": 0,
                                    "sha256": hashlib.sha256(b"").hexdigest()})
        with self.assertRaisesRegex(ValueError, "missing manifest files"):
            RESTORE.restore_archive(self.archive, self.asset, self.destination)
        self.assertEqual(list(self.destination.iterdir()), [])

    def test_existing_parent_file_leaves_no_partial_restoration(self):
        blocker = self.destination / "data/terrain"
        blocker.parent.mkdir()
        blocker.write_bytes(b"independent evidence")
        with self.assertRaises(FileExistsError):
            RESTORE.restore_archive(self.archive, self.asset, self.destination)
        self.assertFalse((self.destination / "data/source").exists())
        self.assertEqual(blocker.read_bytes(), b"independent evidence")

    def test_existing_receipt_is_rejected_before_download_or_restoration(self):
        receipt = self.root / "prior-receipt.json"
        receipt.write_bytes(b'{"status": "prior evidence"}\n')
        argv = [str(SCRIPT), "--destination", str(self.destination),
                "--manifest", str(self.root / "unused-manifest.json"),
                "--receipt", str(receipt)]
        with (patch("sys.argv", argv),
              patch.object(RESTORE.SHARED, "download_asset") as download,
              patch.object(RESTORE, "restore_archive") as restore):
            with self.assertRaisesRegex(FileExistsError, "receipt"):
                RESTORE.main()
        download.assert_not_called()
        restore.assert_not_called()
        self.assertEqual(receipt.read_bytes(), b'{"status": "prior evidence"}\n')
        self.assertEqual(list(self.destination.iterdir()), [])

    def test_failed_shared_download_retains_failure_receipt(self):
        manifest = self.root / "manifest.json"
        manifest.write_text(json.dumps({"assets": [self.asset]}))
        receipt = self.root / "download-failure.json"
        argv = [str(SCRIPT), "--destination", str(self.destination),
                "--manifest", str(manifest), "--receipt", str(receipt)]
        with (patch("sys.argv", argv),
              patch.object(RESTORE, "ASSETS", (self.archive.name,)),
              patch.object(RESTORE.SHARED, "download_asset", side_effect=RuntimeError("release access unavailable")),
              patch.object(RESTORE, "restore_archive") as restore):
            with self.assertRaisesRegex(RuntimeError, "release access unavailable"):
                RESTORE.main()
        restore.assert_not_called()
        record = json.loads(receipt.read_text())
        self.assertEqual(record["status"], "failed")
        self.assertEqual(record["assets"], [])
        self.assertEqual(record["restoration_implementation"]["download"], "gh release download")
        self.assertFalse(record["restoration_implementation"]["credentials_recorded"])
        self.assertFalse((self.destination / "data").exists())


if __name__ == "__main__":
    unittest.main()