| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188 |
- """Release inclusion must be tied to qualified source and firmware identities."""
- import hashlib
- import json
- from pathlib import Path
- import subprocess
- import pytest
- from tools import package_unified_analysis as bundle
- from tools.package_archive import read_archive
- def sha(data):
- return hashlib.sha256(data).hexdigest()
- def put_json(path, value):
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps(value))
- @pytest.fixture
- def release(tmp_path, monkeypatch):
- repo = tmp_path / "repo"
- repo.mkdir()
- (repo / "tools").mkdir()
- (repo / "tools/package_archive.py").write_bytes(Path(bundle.__file__).with_name("package_archive.py").read_bytes())
- (repo / "VERSION").write_text("2.1.0\n")
- (repo / "design.v").write_text("module design; endmodule\n")
- (repo / "docs/releases").mkdir(parents=True)
- (repo / "docs/releases/v2.1.0.md").write_text("Synthetic release fixture, not hardware validation.\n")
- for args in (("init", "-b", "dev"), ("config", "user.name", "Bundle Test"),
- ("config", "user.email", "bundle-test@example.invalid"), ("add", "."),
- ("commit", "-m", "synthetic source")):
- subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True)
- commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip()
- monkeypatch.setattr(bundle, "ROOT", repo)
- inputs = {"design.v": sha((repo / "design.v").read_bytes())}
- manifest = sha(json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode())
- runs = []
- guis = {}
- gui_dir = tmp_path / "gui"
- for product in ("6400-v2", "mrdimm-chamber"):
- run = tmp_path / product
- run.mkdir()
- bit = run / "firmware.bit"
- bit.write_bytes(("synthetic bit " + product).encode())
- receipt = {"profile": product, "status": "PASS", "production": True,
- "simulation_only": False, "timing_pass_25mhz": True,
- "warning_audit": {"status": "PASS"}, "inputs": inputs,
- "source_manifest_sha256": manifest, "bitstream": str(bit),
- "bitstream_sha256": sha(bit.read_bytes()), "commit": commit,
- "build_parameters": {"host_baud": 921600}}
- put_json(run / "td-receipt.json", receipt)
- runs.append(run)
- exe = gui_dir / (product + ".exe")
- exe.parent.mkdir(exist_ok=True)
- exe.write_bytes(("synthetic exe " + product).encode())
- guis[product] = {"status": "PASS", "self_test_exit": 0,
- "exe": exe.name, "sha256": sha(exe.read_bytes()),
- "metadata": {"release_version": "2.1.0", "host_baud": 921600,
- "bitstream_sha256": receipt["bitstream_sha256"]}}
- put_json(gui_dir / "BUILD-SUMMARY.json", {"products": guis})
- review = tmp_path / "review"
- review.mkdir()
- put_json(review / "test.json", {"status": "SYNTHETIC_FIXTURE"})
- hardware = tmp_path / "hardware.json"
- put_json(hardware, {"physical_test": "NOT_RUN"})
- out = tmp_path / "delivery"
- argv = ["--output-dir", str(out), "--gui-dir", str(gui_dir),
- "--review-dir", str(review), "--hardware-status", str(hardware)]
- for run in runs:
- argv += ["--td-run", str(run)]
- return {"repo": repo, "runs": runs, "gui": gui_dir, "out": out, "argv": argv}
- def test_complete_bundle_preserves_sources_and_actual_identities(release):
- assert bundle.main(release["argv"]) == 0
- out = release["out"]
- results = json.loads((out / "PACKAGE-RESULTS.json").read_text())
- assert len(results) == 3
- analysis = next(row for row in results if row["file"].startswith("Prod2U-Analysis-"))
- archive = read_archive(out / analysis["file"])
- assert archive["sha256"] == analysis["sha256"]
- files = archive["files"]
- assert files["sources/cpld/design.v"] == (release["repo"] / "design.v").read_bytes()
- assert files["history/cpld.bundle"].startswith(b"# v2 git bundle")
- assert "debug/review/test.json" in files
- assert json.loads(files["RUN.json"])["hardware"]["physical_test"] == "NOT_RUN"
- for product in ("6400-v2", "mrdimm-chamber"):
- assert f"products/{product}/921600/firmware.bit" in files
- assert f"products/{product}/{product}.exe" in files
- for item in json.loads((out / "DELIVERY-SHA256.json").read_text()):
- data = (out / item["path"]).read_bytes()
- assert len(data) == item["size_bytes"]
- assert sha(data) == item["sha256"]
- @pytest.mark.parametrize("fault", ["failed_td", "changed_source", "changed_bit", "wrong_manifest"])
- def test_rejects_unqualified_or_changed_firmware(release, fault):
- run = release["runs"][0]
- path = run / "td-receipt.json"
- receipt = json.loads(path.read_text())
- if fault == "failed_td":
- receipt["warning_audit"]["status"] = "FAIL"
- elif fault == "changed_source":
- (release["repo"] / "design.v").write_text("module changed; endmodule\n")
- elif fault == "changed_bit":
- (run / "firmware.bit").write_bytes(b"different bit")
- else:
- receipt["source_manifest_sha256"] = "0" * 64
- put_json(path, receipt)
- with pytest.raises(ValueError):
- bundle.verified_td(run)
- def test_rejects_gui_from_a_different_firmware(release):
- path = release["gui"] / "BUILD-SUMMARY.json"
- summary = json.loads(path.read_text())
- summary["products"]["6400-v2"]["metadata"]["bitstream_sha256"] = "0" * 64
- put_json(path, summary)
- with pytest.raises(ValueError, match="identity mismatch"):
- bundle.main(release["argv"])
- assert not list(release["out"].glob("*.zip"))
- def test_explicit_hardware_survives_source_restore_without_entering_debug(release, tmp_path):
- relative = Path("reference/original/boards/MRDIMM-V1.2/main.BRD")
- board = release["repo"] / relative
- board.parent.mkdir(parents=True)
- board.write_bytes(b"synthetic ignored board original\x00\xff")
- with (release["repo"] / ".git/info/exclude").open("a") as exclude:
- exclude.write("\nreference/original/boards/\n")
- subprocess.run(["git", "check-ignore", "--quiet", str(relative)],
- cwd=release["repo"], check=True)
- external = tmp_path / "external" / "schematic.pdf"
- external.parent.mkdir()
- external.write_bytes(b"%PDF synthetic external original\x00")
- argv = release["argv"] + ["--hardware-file", str(board),
- "--hardware-file", str(external),
- "--hardware-file", str(board),
- "--hardware-file", str(release["repo"] / "design.v")]
- assert bundle.main(argv) == 0
- expected = {"sources/cpld/" + relative.as_posix(): board.read_bytes(),
- "hardware/originals/schematic.pdf": external.read_bytes()}
- results = json.loads((release["out"] / "PACKAGE-RESULTS.json").read_text())
- for result in results:
- archive = read_archive(release["out"] / result["file"])
- assert archive["sha256"] == result["sha256"]
- files = archive["files"]
- is_debug = result["file"].startswith("Prod2U-Debug-")
- for name, data in expected.items():
- if is_debug:
- assert name not in files
- else:
- assert files[name] == data
- assert sha(files[name]) == sha(data)
- assert "hardware/originals/main.BRD" not in files
- assert "explicit hardware originals included" in json.loads(files["EXCLUSIONS.json"])["source_scope"]
- conflict = tmp_path / "different" / external.name
- conflict.parent.mkdir()
- conflict.write_bytes(b"different original with the same external filename")
- rejected_out = tmp_path / "conflicting-delivery"
- conflict_argv = argv + ["--hardware-file", str(conflict)]
- conflict_argv[conflict_argv.index("--output-dir") + 1] = str(rejected_out)
- with pytest.raises(ValueError, match="conflicting hardware file"):
- bundle.main(conflict_argv)
- assert not list(rejected_out.glob("*.zip"))
- def test_protocol_doc_bundled_at_release_root_and_in_archives(release):
- proto = release["repo"] / "docs/CPLD_通讯协议v2.0.md"
- proto.write_text("# Synthetic protocol doc\n", encoding="utf-8")
- subprocess.run(["git", "add", str(proto.relative_to(release["repo"]))], cwd=release["repo"], check=True)
- subprocess.run(["git", "commit", "-m", "add protocol doc"], cwd=release["repo"], check=True, capture_output=True)
- assert bundle.main(release["argv"]) == 0
- out = release["out"]
- expected_bytes = proto.read_bytes()
- assert (out / "CPLD_通讯协议v2.0.md").read_bytes() == expected_bytes
- run_meta = json.loads((out / "RUN.json").read_text(encoding="utf-8"))
- assert run_meta["protocol_doc"]["file"] == "CPLD_通讯协议v2.0.md"
- assert run_meta["protocol_doc"]["sha256"] == sha(expected_bytes)
- delivery = {item["path"]: item for item in json.loads((out / "DELIVERY-SHA256.json").read_text(encoding="utf-8"))}
- assert delivery["CPLD_通讯协议v2.0.md"]["sha256"] == sha(expected_bytes)
- for row in json.loads((out / "PACKAGE-RESULTS.json").read_text(encoding="utf-8")):
- files = read_archive(out / row["file"])["files"]
- assert files["CPLD_通讯协议v2.0.md"] == expected_bytes
|