test_release_analysis_bundle.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. """Release inclusion must be tied to qualified source and firmware identities."""
  2. import hashlib
  3. import json
  4. from pathlib import Path
  5. import subprocess
  6. import pytest
  7. from tools import package_unified_analysis as bundle
  8. from tools.package_archive import read_archive
  9. def sha(data):
  10. return hashlib.sha256(data).hexdigest()
  11. def put_json(path, value):
  12. path.parent.mkdir(parents=True, exist_ok=True)
  13. path.write_text(json.dumps(value))
  14. @pytest.fixture
  15. def release(tmp_path, monkeypatch):
  16. repo = tmp_path / "repo"
  17. repo.mkdir()
  18. (repo / "tools").mkdir()
  19. (repo / "tools/package_archive.py").write_bytes(Path(bundle.__file__).with_name("package_archive.py").read_bytes())
  20. (repo / "VERSION").write_text("2.1.0\n")
  21. (repo / "design.v").write_text("module design; endmodule\n")
  22. (repo / "docs/releases").mkdir(parents=True)
  23. (repo / "docs/releases/v2.1.0.md").write_text("Synthetic release fixture, not hardware validation.\n")
  24. for args in (("init", "-b", "dev"), ("config", "user.name", "Bundle Test"),
  25. ("config", "user.email", "bundle-test@example.invalid"), ("add", "."),
  26. ("commit", "-m", "synthetic source")):
  27. subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True)
  28. commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip()
  29. monkeypatch.setattr(bundle, "ROOT", repo)
  30. inputs = {"design.v": sha((repo / "design.v").read_bytes())}
  31. manifest = sha(json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode())
  32. runs = []
  33. guis = {}
  34. gui_dir = tmp_path / "gui"
  35. for product in ("6400-v2", "mrdimm-chamber"):
  36. run = tmp_path / product
  37. run.mkdir()
  38. bit = run / "firmware.bit"
  39. bit.write_bytes(("synthetic bit " + product).encode())
  40. receipt = {"profile": product, "status": "PASS", "production": True,
  41. "simulation_only": False, "timing_pass_25mhz": True,
  42. "warning_audit": {"status": "PASS"}, "inputs": inputs,
  43. "source_manifest_sha256": manifest, "bitstream": str(bit),
  44. "bitstream_sha256": sha(bit.read_bytes()), "commit": commit,
  45. "build_parameters": {"host_baud": 921600}}
  46. put_json(run / "td-receipt.json", receipt)
  47. runs.append(run)
  48. exe = gui_dir / (product + ".exe")
  49. exe.parent.mkdir(exist_ok=True)
  50. exe.write_bytes(("synthetic exe " + product).encode())
  51. guis[product] = {"status": "PASS", "self_test_exit": 0,
  52. "exe": exe.name, "sha256": sha(exe.read_bytes()),
  53. "metadata": {"release_version": "2.1.0", "host_baud": 921600,
  54. "bitstream_sha256": receipt["bitstream_sha256"]}}
  55. put_json(gui_dir / "BUILD-SUMMARY.json", {"products": guis})
  56. review = tmp_path / "review"
  57. review.mkdir()
  58. put_json(review / "test.json", {"status": "SYNTHETIC_FIXTURE"})
  59. hardware = tmp_path / "hardware.json"
  60. put_json(hardware, {"physical_test": "NOT_RUN"})
  61. out = tmp_path / "delivery"
  62. argv = ["--output-dir", str(out), "--gui-dir", str(gui_dir),
  63. "--review-dir", str(review), "--hardware-status", str(hardware)]
  64. for run in runs:
  65. argv += ["--td-run", str(run)]
  66. return {"repo": repo, "runs": runs, "gui": gui_dir, "out": out, "argv": argv}
  67. def test_complete_bundle_preserves_sources_and_actual_identities(release):
  68. assert bundle.main(release["argv"]) == 0
  69. out = release["out"]
  70. results = json.loads((out / "PACKAGE-RESULTS.json").read_text())
  71. assert len(results) == 3
  72. analysis = next(row for row in results if row["file"].startswith("Prod2U-Analysis-"))
  73. archive = read_archive(out / analysis["file"])
  74. assert archive["sha256"] == analysis["sha256"]
  75. files = archive["files"]
  76. assert files["sources/cpld/design.v"] == (release["repo"] / "design.v").read_bytes()
  77. assert files["history/cpld.bundle"].startswith(b"# v2 git bundle")
  78. assert "debug/review/test.json" in files
  79. assert json.loads(files["RUN.json"])["hardware"]["physical_test"] == "NOT_RUN"
  80. for product in ("6400-v2", "mrdimm-chamber"):
  81. assert f"products/{product}/921600/firmware.bit" in files
  82. assert f"products/{product}/{product}.exe" in files
  83. for item in json.loads((out / "DELIVERY-SHA256.json").read_text()):
  84. data = (out / item["path"]).read_bytes()
  85. assert len(data) == item["size_bytes"]
  86. assert sha(data) == item["sha256"]
  87. @pytest.mark.parametrize("fault", ["failed_td", "changed_source", "changed_bit", "wrong_manifest"])
  88. def test_rejects_unqualified_or_changed_firmware(release, fault):
  89. run = release["runs"][0]
  90. path = run / "td-receipt.json"
  91. receipt = json.loads(path.read_text())
  92. if fault == "failed_td":
  93. receipt["warning_audit"]["status"] = "FAIL"
  94. elif fault == "changed_source":
  95. (release["repo"] / "design.v").write_text("module changed; endmodule\n")
  96. elif fault == "changed_bit":
  97. (run / "firmware.bit").write_bytes(b"different bit")
  98. else:
  99. receipt["source_manifest_sha256"] = "0" * 64
  100. put_json(path, receipt)
  101. with pytest.raises(ValueError):
  102. bundle.verified_td(run)
  103. def test_rejects_gui_from_a_different_firmware(release):
  104. path = release["gui"] / "BUILD-SUMMARY.json"
  105. summary = json.loads(path.read_text())
  106. summary["products"]["6400-v2"]["metadata"]["bitstream_sha256"] = "0" * 64
  107. put_json(path, summary)
  108. with pytest.raises(ValueError, match="identity mismatch"):
  109. bundle.main(release["argv"])
  110. assert not list(release["out"].glob("*.zip"))
  111. def test_explicit_hardware_survives_source_restore_without_entering_debug(release, tmp_path):
  112. relative = Path("reference/original/boards/MRDIMM-V1.2/main.BRD")
  113. board = release["repo"] / relative
  114. board.parent.mkdir(parents=True)
  115. board.write_bytes(b"synthetic ignored board original\x00\xff")
  116. with (release["repo"] / ".git/info/exclude").open("a") as exclude:
  117. exclude.write("\nreference/original/boards/\n")
  118. subprocess.run(["git", "check-ignore", "--quiet", str(relative)],
  119. cwd=release["repo"], check=True)
  120. external = tmp_path / "external" / "schematic.pdf"
  121. external.parent.mkdir()
  122. external.write_bytes(b"%PDF synthetic external original\x00")
  123. argv = release["argv"] + ["--hardware-file", str(board),
  124. "--hardware-file", str(external),
  125. "--hardware-file", str(board),
  126. "--hardware-file", str(release["repo"] / "design.v")]
  127. assert bundle.main(argv) == 0
  128. expected = {"sources/cpld/" + relative.as_posix(): board.read_bytes(),
  129. "hardware/originals/schematic.pdf": external.read_bytes()}
  130. results = json.loads((release["out"] / "PACKAGE-RESULTS.json").read_text())
  131. for result in results:
  132. archive = read_archive(release["out"] / result["file"])
  133. assert archive["sha256"] == result["sha256"]
  134. files = archive["files"]
  135. is_debug = result["file"].startswith("Prod2U-Debug-")
  136. for name, data in expected.items():
  137. if is_debug:
  138. assert name not in files
  139. else:
  140. assert files[name] == data
  141. assert sha(files[name]) == sha(data)
  142. assert "hardware/originals/main.BRD" not in files
  143. assert "explicit hardware originals included" in json.loads(files["EXCLUSIONS.json"])["source_scope"]
  144. conflict = tmp_path / "different" / external.name
  145. conflict.parent.mkdir()
  146. conflict.write_bytes(b"different original with the same external filename")
  147. rejected_out = tmp_path / "conflicting-delivery"
  148. conflict_argv = argv + ["--hardware-file", str(conflict)]
  149. conflict_argv[conflict_argv.index("--output-dir") + 1] = str(rejected_out)
  150. with pytest.raises(ValueError, match="conflicting hardware file"):
  151. bundle.main(conflict_argv)
  152. assert not list(rejected_out.glob("*.zip"))
  153. def test_protocol_doc_bundled_at_release_root_and_in_archives(release):
  154. proto = release["repo"] / "docs/CPLD_通讯协议v2.0.md"
  155. proto.write_text("# Synthetic protocol doc\n", encoding="utf-8")
  156. subprocess.run(["git", "add", str(proto.relative_to(release["repo"]))], cwd=release["repo"], check=True)
  157. subprocess.run(["git", "commit", "-m", "add protocol doc"], cwd=release["repo"], check=True, capture_output=True)
  158. assert bundle.main(release["argv"]) == 0
  159. out = release["out"]
  160. expected_bytes = proto.read_bytes()
  161. assert (out / "CPLD_通讯协议v2.0.md").read_bytes() == expected_bytes
  162. run_meta = json.loads((out / "RUN.json").read_text(encoding="utf-8"))
  163. assert run_meta["protocol_doc"]["file"] == "CPLD_通讯协议v2.0.md"
  164. assert run_meta["protocol_doc"]["sha256"] == sha(expected_bytes)
  165. delivery = {item["path"]: item for item in json.loads((out / "DELIVERY-SHA256.json").read_text(encoding="utf-8"))}
  166. assert delivery["CPLD_通讯协议v2.0.md"]["sha256"] == sha(expected_bytes)
  167. for row in json.loads((out / "PACKAGE-RESULTS.json").read_text(encoding="utf-8")):
  168. files = read_archive(out / row["file"])["files"]
  169. assert files["CPLD_通讯协议v2.0.md"] == expected_bytes