| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200 |
- #!/usr/bin/env python3
- """Identity and entrypoint contracts for the Prod2U Profile 4 CLI."""
- from __future__ import annotations
- import hashlib
- import importlib.util
- import json
- import subprocess
- import sys
- import tempfile
- import unittest
- from pathlib import Path
- from types import SimpleNamespace
- ROOT = Path(__file__).resolve().parents[2]
- TOOLS = ROOT / "tools"
- sys.path.insert(0, str(TOOLS))
- def load_cli():
- path = TOOLS / "prod2u_p4_cli.py"
- spec = importlib.util.spec_from_file_location("test_prod2u_p4_cli_identity_owned", path)
- if spec is None or spec.loader is None:
- raise AssertionError(f"unable to import {path}")
- module = importlib.util.module_from_spec(spec)
- sys.modules[spec.name] = module
- spec.loader.exec_module(module)
- return module
- def write_identity_fixture(root: Path, *, variant: str = "normal") -> SimpleNamespace:
- from prod2u_build_identity import source_manifest_sha256
- bitstream = root / f"{variant}.bit"
- bitstream.write_bytes(f"prod2u-p4-{variant}".encode("ascii"))
- bitstream_sha256 = hashlib.sha256(bitstream.read_bytes()).hexdigest()
- source = {
- "schema": "prod2u-source-manifest-v1",
- "profile": "prod2u-fan-tach-binary921-v2",
- "td_version": "6.2.2.198412",
- "files": [
- {
- "path": f"src/top/prod2u_fan_tach_binary921_v2_{variant}_top.v",
- "size": 1,
- "sha256": "a" * 64,
- }
- ],
- }
- source_hash = source_manifest_sha256(source)
- source.update(source_manifest_sha256=source_hash, build_id=source_hash[:8].upper())
- source_manifest = root / f"{variant}-source-manifest.json"
- source_manifest.write_text(json.dumps(source), encoding="utf-8")
- td_receipt = root / f"{variant}-td.json"
- td_receipt.write_text(
- json.dumps(
- {
- "schema": "prod2u-td-build-receipt-v1",
- "status": "pass",
- "top": f"prod2u_fan_tach_binary921_v2_{variant}",
- "top_module": f"prod2u_fan_tach_binary921_v2_{variant}_top",
- "pin_profile": "prod2u-fan-tach-binary921-v2",
- "build_id": source["build_id"],
- "source_manifest_sha256": source_hash,
- "build_identity": {
- "status": "pass",
- "build_id": source["build_id"],
- "source_manifest_sha256": source_hash,
- "staged_manifest_sha256": "b" * 64,
- },
- "por_initialization": {"status": "not_applicable", "failures": []},
- "bitstream": {
- "path": str(bitstream),
- "size": bitstream.stat().st_size,
- "sha256": bitstream_sha256,
- },
- "resources": {"utilization": {"lut": 1}},
- "timing": {"setup_wns_ns": 1.0, "hold_wns_ns": 0.1},
- "timing_gate": {"status": "pass", "failures": []},
- "syn": {"returncode": 0, "log_has_error": False},
- "phy": {"returncode": 0, "log_has_error": False},
- }
- ),
- encoding="utf-8",
- )
- td_root = root / "TD"
- (td_root / "bin").mkdir(parents=True)
- (td_root / "bin" / "bw_commands_prompt.exe").write_bytes(b"fixture")
- return SimpleNamespace(
- variant=variant,
- build_id=int(source["build_id"], 16),
- bitstream=bitstream,
- sha256=bitstream_sha256,
- td_receipt=td_receipt,
- source_manifest=source_manifest,
- td_root=td_root,
- output_dir=root / "evidence",
- run_id="identity-fixture",
- )
- class Prod2UP4CliIdentityTests(unittest.TestCase):
- def test_live_commands_require_td_receipt_and_source_manifest(self) -> None:
- cli = load_cli()
- parser = cli.build_parser()
- with self.assertRaises(SystemExit):
- parser.parse_args(
- [
- "program-only",
- "--variant",
- "normal",
- "--build-id",
- "1234ABCD",
- "--bitstream",
- "normal.bit",
- "--sha256",
- "a" * 64,
- "--td-root",
- "TD",
- "--output-dir",
- "evidence",
- ]
- )
- def test_preflight_hash_binds_bitstream_manifest_td_receipt_and_build(self) -> None:
- cli = load_cli()
- with tempfile.TemporaryDirectory() as temp:
- args = write_identity_fixture(Path(temp))
- passed = cli.run_preflight(args)
- receipt = json.loads(args.td_receipt.read_text(encoding="utf-8"))
- receipt["build_id"] = "DEADBEEF"
- args.td_receipt.write_text(json.dumps(receipt), encoding="utf-8")
- failed = cli.run_preflight(args)
- self.assertEqual(passed["status"], "pass", passed)
- self.assertEqual(passed["identity"]["build_id"], f"{args.build_id:08X}")
- self.assertEqual(passed["identity"]["source_manifest_status"], "pass")
- self.assertEqual(passed["identity"]["td_receipt_status"], "pass")
- self.assertEqual(failed["status"], "fail")
- self.assertIn("td_receipt_build_id_mismatch", failed["failures"])
- def test_default_powershell_selftest_routes_to_profile4(self) -> None:
- result = subprocess.run(
- [
- "powershell.exe",
- "-NoProfile",
- "-ExecutionPolicy",
- "Bypass",
- "-File",
- str(TOOLS / "prod2u.ps1"),
- "selftest",
- ],
- cwd=ROOT,
- capture_output=True,
- text=True,
- check=False,
- )
- payload = json.loads(result.stdout)
- self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
- self.assertEqual(payload["profile_id"], 4)
- self.assertEqual(payload["protocol_version"], 2)
- def test_powershell_profile_routing_preserves_profile3_read_only_commands(self) -> None:
- def run(*arguments: str) -> subprocess.CompletedProcess[str]:
- return subprocess.run(
- [
- "powershell.exe",
- "-NoProfile",
- "-ExecutionPolicy",
- "Bypass",
- "-File",
- str(TOOLS / "prod2u.ps1"),
- *arguments,
- ],
- cwd=ROOT,
- capture_output=True,
- text=True,
- check=False,
- )
- profile3_selftest = run("selftest", "-Profile", "profile3")
- self.assertEqual(profile3_selftest.returncode, 0, profile3_selftest.stdout + profile3_selftest.stderr)
- self.assertEqual(json.loads(profile3_selftest.stdout)["profile_id"], 3)
- with tempfile.TemporaryDirectory() as temp:
- receipt = Path(temp) / "td.json"
- receipt.write_text("{}", encoding="utf-8")
- profile3_legacy = run("validate-td-receipt", "-Profile", "profile3", "-TdReceipt", str(receipt))
- self.assertEqual(profile3_legacy.returncode, 1)
- self.assertEqual(json.loads(profile3_legacy.stdout)["schema"], "prod2u-td-receipt-schema-validation-v1")
- unsupported = run("validate-td-receipt", "-Profile", "profile4")
- self.assertNotEqual(unsupported.returncode, 0)
- self.assertIn("Profile 4 does not support command: validate-td-receipt", unsupported.stdout + unsupported.stderr)
- if __name__ == "__main__":
- unittest.main()
|