Skip to content
pi-c Artifact [54e795ebe0]
Login

Artifact [54e795ebe0]

Artifact 54e795ebe0634a44ba2656878cbf7c23ca86c230f3cb95214c7c0c04029881ec:


"""Metadata checks are development helpers, never runtime contract qualification."""
import copy
import hashlib
import importlib.util
import json
from pathlib import Path
import tempfile
import unittest

ROOT = Path(__file__).resolve().parents[1]
SPEC = importlib.util.spec_from_file_location("check_contracts", ROOT / "tools/check_contracts.py")
checks = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(checks)


class ContractChecks(unittest.TestCase):
    def setUp(self):
        self.data = json.loads((ROOT / "contracts/registry.json").read_text())

    def test_valid_inventory_is_not_product_qualification(self):
        checks.validate_registry(self.data, ROOT)
        self.assertEqual(len(self.data["contracts"]), 79)
        self.assertTrue(all(row["status"] == "NOT RUN" for row in self.data["contracts"]))

    def test_missing_contracts_rejected(self):
        self.data["contracts"].pop()
        with self.assertRaisesRegex(ValueError, "79"):
            checks.validate_registry(self.data, ROOT)

    def test_duplicate_or_unknown_contracts_rejected(self):
        for replacement in (self.data["contracts"][1]["id"], "H99"):
            data = copy.deepcopy(self.data)
            data["contracts"][0]["id"] = replacement
            with self.assertRaises(ValueError):
                checks.validate_registry(data, ROOT)

    def test_reference_pin_must_match(self):
        self.data["reference_commit"] = "0" * 40
        with self.assertRaisesRegex(ValueError, "commit"):
            checks.validate_registry(self.data, ROOT)

    def test_invalid_stage_case_or_status_rejected(self):
        for field, value in (("stage", "S99"), ("cases", ["A99"]),
                             ("status", "done"), ("disposition", "whatever")):
            data = copy.deepcopy(self.data)
            data["contracts"][0][field] = value
            with self.assertRaises(ValueError):
                checks.validate_registry(data, ROOT)

    def test_citation_drift_and_escape_rejected(self):
        for citation in ({"path": "../outside", "line": 1},
                         {"path": "docs/harness-features.md", "line": 1}):
            self.data["contracts"][0]["citation"] = citation
            with self.assertRaises(ValueError):
                checks.validate_registry(self.data, ROOT)

    def test_pass_without_evidence_rejected(self):
        self.data["contracts"][0]["status"] = "PASS"
        with self.assertRaisesRegex(ValueError, "product evidence"):
            checks.validate_registry(self.data, ROOT)

    def test_deviation_requires_reviewed_decision(self):
        self.data["contracts"][0]["status"] = "DEVIATION"
        with self.assertRaisesRegex(ValueError, "reviewed decision"):
            checks.validate_registry(self.data, ROOT)

    def test_fixture_evidence_cannot_qualify_product(self):
        folder = ROOT / "build" / "qualification"
        folder.mkdir(parents=True, exist_ok=True)
        with tempfile.TemporaryDirectory(dir=folder) as temporary:
            path = Path(temporary)
            payload = path / "fixture.txt"
            payload.write_text("made-up fixture result")
            item = {"path": str(payload.relative_to(ROOT)),
                    "sha256": hashlib.sha256(payload.read_bytes()).hexdigest()}
            evidence = {"version": 1, "status": "PASS", "scope": "qualification_fixture",
                        "reason": "Fixture only, not production", "sources": [item],
                        "binaries": [item], "artifacts": [item], "command": ["fixture"],
                        "host": "synthetic", "toolchain": {"compiler": "test", "version": "1",
                        "flags": []}, "workload_sha256": "a" * 64,
                        "dependencies_sha256": "b" * 64, "samples": 1,
                        "durability_policy": "not applicable", "failure_model": "fixture",
                        "teardown": {"status": "not-required", "resources": []},
                        "contract_ids": ["H01"]}
            checks.validate_evidence(evidence, ROOT)
            evidence["teardown"]["status"] = "cleanup-pending"
            with self.assertRaisesRegex(ValueError, "teardown"):
                checks.validate_evidence(evidence, ROOT)
            evidence["teardown"]["status"] = "not-required"
            evidence["toolchain"]["flags"] = [42]
            with self.assertRaisesRegex(ValueError, "toolchain"):
                checks.validate_evidence(evidence, ROOT)
            evidence["toolchain"]["flags"] = []
            record = path / "evidence.json"
            record.write_text(json.dumps(evidence))
            self.data["contracts"][0].update(status="PASS", evidence=[str(record.relative_to(ROOT))])
            with self.assertRaisesRegex(ValueError, "product evidence"):
                checks.validate_registry(self.data, ROOT)
            evidence["artifacts"][0]["sha256"] = "0" * 64
            with self.assertRaisesRegex(ValueError, "Hash mismatch"):
                checks.validate_evidence(evidence, ROOT)

    def test_incomplete_pass_or_unresolved_cleanup_rejected(self):
        evidence = {"version": 1, "status": "PASS", "scope": "qualification_fixture",
                    "reason": "Missing actual artifacts"}
        with self.assertRaises(ValueError):
            checks.validate_evidence(evidence, ROOT)
        evidence.update(status="GATED", reason="Required runner unavailable")
        checks.validate_evidence(evidence, ROOT)


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