test_generator.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. from __future__ import annotations
  2. import json
  3. import hashlib
  4. import shutil
  5. import sys
  6. from dataclasses import dataclass
  7. from pathlib import Path
  8. import pytest
  9. ROOT = Path(__file__).resolve().parents[2]
  10. VIEWER_ROOT = ROOT / "tools" / "board-viewer"
  11. FIXTURE = Path(__file__).parent / "fixtures" / "parser_edge_cases.kicad_pcb"
  12. D356_FIXTURE = Path(__file__).parent / "fixtures" / "parser_edge_cases.d356"
  13. sys.path.insert(0, str(VIEWER_ROOT))
  14. from board_viewer.assets import sha256_file, validate_generated_assets # noqa: E402
  15. from board_viewer.generator import ( # noqa: E402
  16. GenerationConfig,
  17. GenerationError,
  18. generate_assets,
  19. manifest_source_path,
  20. )
  21. @dataclass
  22. class FakeResult:
  23. returncode: int = 0
  24. stdout: str = ""
  25. stderr: str = ""
  26. class FakeKiCad:
  27. def __init__(self, *, fail_export: bool = False) -> None:
  28. self.commands: list[list[str]] = []
  29. self.fail_export = fail_export
  30. def __call__(self, command: list[str], cwd: Path) -> FakeResult:
  31. self.commands.append(command)
  32. if command[-1] == "--version":
  33. return FakeResult(stdout="10.0.4\n")
  34. if command[1:3] == ["pcb", "import"]:
  35. output = Path(command[command.index("--output") + 1])
  36. report = Path(command[command.index("--report-file") + 1])
  37. shutil.copy2(FIXTURE, output)
  38. report.write_text(
  39. json.dumps(
  40. {
  41. "errors": [],
  42. "warnings": [],
  43. "statistics": {"footprints": 2, "tracks": 0, "vias": 0, "zones": 0},
  44. }
  45. ),
  46. encoding="utf-8",
  47. )
  48. return FakeResult()
  49. if command[1:4] == ["pcb", "export", "svg"]:
  50. if self.fail_export:
  51. return FakeResult(returncode=1, stderr="export failed")
  52. output = Path(command[command.index("--output") + 1])
  53. layers = command[command.index("--layers") + 1]
  54. output.write_text(
  55. '<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" '
  56. 'width="30mm" height="10mm" viewBox="0 0 30 10">'
  57. f'<title>fixture date 2026-07-21T12:00:00</title><desc>{layers}</desc></svg>',
  58. encoding="utf-8",
  59. )
  60. return FakeResult()
  61. if command[1:4] == ["pcb", "export", "ipcd356"]:
  62. output = Path(command[command.index("--output") + 1])
  63. shutil.copy2(D356_FIXTURE, output)
  64. return FakeResult()
  65. raise AssertionError(f"unexpected command: {command}")
  66. def write_json(path: Path, payload: object) -> None:
  67. path.write_text(json.dumps(payload), encoding="utf-8")
  68. def generation_config(tmp_path: Path) -> GenerationConfig:
  69. brd = tmp_path / "fixture.brd"
  70. inventory = tmp_path / "inventory.json"
  71. annotations = tmp_path / "annotations.json"
  72. brd.write_bytes(b"fixture Allegro source")
  73. write_json(
  74. inventory,
  75. {
  76. "schema": "fixture-v1",
  77. "board_id": "fixture-board",
  78. "pins": [],
  79. },
  80. )
  81. write_json(
  82. annotations,
  83. {
  84. "schema": "board-viewer-annotations-v1",
  85. "board_id": "fixture-board",
  86. "connector_profiles": {},
  87. "touchpoints": {},
  88. "interfaces": [],
  89. "photo_overlay": None,
  90. },
  91. )
  92. return GenerationConfig(
  93. brd_path=brd,
  94. inventory_path=inventory,
  95. annotations_path=annotations,
  96. output_dir=tmp_path / "published" / "generated",
  97. kicad_cli=tmp_path / "kicad-cli.exe",
  98. board_name="Fixture board",
  99. required_kicad_version="10.0.4",
  100. expected_counts={"footprints": 2, "touchpoints": 2, "pads": 3},
  101. expected_front_only=False,
  102. temp_parent=tmp_path / "outside-worktree-temp",
  103. )
  104. def test_generate_builds_valid_hashed_bundle_then_replaces_old_assets(tmp_path: Path) -> None:
  105. config = generation_config(tmp_path)
  106. config.kicad_cli.write_text("fake", encoding="utf-8")
  107. config.output_dir.mkdir(parents=True)
  108. (config.output_dir / "old.txt").write_text("old", encoding="utf-8")
  109. runner = FakeKiCad()
  110. result = generate_assets(config, runner=runner)
  111. assert result["status"] == "pass"
  112. assert not (config.output_dir / "old.txt").exists()
  113. assert {path.name for path in config.output_dir.iterdir()} == {
  114. "board-data.json",
  115. "board-mask-edge.svg",
  116. "board-silkscreen.svg",
  117. "board-copper.svg",
  118. "import-report.json",
  119. "build-info.json",
  120. }
  121. build_info = json.loads((config.output_dir / "build-info.json").read_text(encoding="utf-8"))
  122. assert build_info["counts"] == {"footprints": 2, "touchpoints": 2, "pads": 3}
  123. assert build_info["toolchain"]["kicad"] == "10.0.4"
  124. assert build_info["verification"]["ipcd356"] == {
  125. "numbered_pads": 2,
  126. "matched_pads": 2,
  127. "record_types": {"317": 1, "327": 1},
  128. "tolerance_mm": 0.02,
  129. }
  130. assert build_info["sources"]["brd"]["sha256"] == sha256_file(config.brd_path)
  131. generator_sources = {
  132. "generator_pipeline": VIEWER_ROOT / "board_viewer" / "generator.py",
  133. "generator_data": VIEWER_ROOT / "board_viewer" / "data.py",
  134. "generator_annotations": VIEWER_ROOT / "board_viewer" / "annotations.py",
  135. "generator_eligibility": VIEWER_ROOT / "board_viewer" / "eligibility.py",
  136. "generator_pcb": VIEWER_ROOT / "board_viewer" / "pcb.py",
  137. "generator_sexpr": VIEWER_ROOT / "board_viewer" / "sexpr.py",
  138. "generator_ipcd356": VIEWER_ROOT / "board_viewer" / "ipcd356.py",
  139. "generator_photo": VIEWER_ROOT / "board_viewer" / "photo.py",
  140. "generator_regression": VIEWER_ROOT / "board_viewer" / "regression.py",
  141. "schema_data": ROOT / "schemas" / "board_viewer_data.schema.json",
  142. "schema_annotations": ROOT / "schemas" / "board_viewer_annotations.schema.json",
  143. }
  144. for name, path in generator_sources.items():
  145. assert build_info["sources"][name]["path"] == path.relative_to(ROOT).as_posix()
  146. assert build_info["sources"][name]["sha256"] == sha256_file(path)
  147. assert validate_generated_assets(config.output_dir).status == "pass"
  148. for name, metadata in build_info["assets"].items():
  149. assert metadata["sha256"] == sha256_file(config.output_dir / name)
  150. assert all("F.Fab" not in " ".join(command) for command in runner.commands)
  151. export_layers = {
  152. command[command.index("--layers") + 1]
  153. for command in runner.commands
  154. if command[1:4] == ["pcb", "export", "svg"]
  155. }
  156. assert export_layers == {"F.Mask,Edge.Cuts", "F.SilkS,Edge.Cuts", "F.Cu,Edge.Cuts"}
  157. assert "2026-07-21T12:00:00" not in (config.output_dir / "board-mask-edge.svg").read_text(encoding="utf-8")
  158. def test_generate_failure_keeps_previous_bundle_untouched(tmp_path: Path) -> None:
  159. config = generation_config(tmp_path)
  160. config.kicad_cli.write_text("fake", encoding="utf-8")
  161. config.output_dir.mkdir(parents=True)
  162. sentinel = config.output_dir / "old.txt"
  163. sentinel.write_text("must survive", encoding="utf-8")
  164. with pytest.raises(GenerationError, match="export failed"):
  165. generate_assets(config, runner=FakeKiCad(fail_export=True))
  166. assert sentinel.read_text(encoding="utf-8") == "must survive"
  167. def test_generate_rejects_wrong_kicad_version_before_import(tmp_path: Path) -> None:
  168. config = generation_config(tmp_path)
  169. config.kicad_cli.write_text("fake", encoding="utf-8")
  170. runner = FakeKiCad()
  171. def wrong_version(command: list[str], cwd: Path) -> FakeResult:
  172. if command[-1] == "--version":
  173. return FakeResult(stdout="9.0.0")
  174. return runner(command, cwd)
  175. with pytest.raises(GenerationError, match="requires KiCad 10.0.4"):
  176. generate_assets(config, runner=wrong_version)
  177. assert runner.commands == []
  178. def test_generate_rejects_temp_directory_inside_repository(tmp_path: Path) -> None:
  179. config = generation_config(tmp_path)
  180. config.kicad_cli.write_text("fake", encoding="utf-8")
  181. config.temp_parent = ROOT / "tmp" / "board-viewer-test"
  182. with pytest.raises(GenerationError, match="temporary directory must be outside repository"):
  183. generate_assets(config, runner=FakeKiCad())
  184. def test_manifest_uses_portable_paths_for_repository_sources(tmp_path: Path) -> None:
  185. assert manifest_source_path(ROOT / "config" / "pin_inventory.fcb_fpga_mcu0611.json") == "config/pin_inventory.fcb_fpga_mcu0611.json"
  186. assert manifest_source_path(tmp_path / "external.brd") == str((tmp_path / "external.brd").resolve())
  187. def test_generate_includes_optional_hash_bound_photo_overlay(tmp_path: Path) -> None:
  188. config = generation_config(tmp_path)
  189. config.kicad_cli.write_text("fake", encoding="utf-8")
  190. config.photo_root = tmp_path
  191. photo = tmp_path / "board-photo.png"
  192. photo.write_bytes(b"fixture-photo")
  193. annotations = json.loads(config.annotations_path.read_text(encoding="utf-8"))
  194. annotations["photo_overlay"] = {
  195. "path": "board-photo.png",
  196. "sha256": hashlib.sha256(b"fixture-photo").hexdigest(),
  197. "control_points": [
  198. {"image": {"x": 0, "y": 0}, "board": {"x": 0, "y": -10}},
  199. {"image": {"x": 100, "y": 0}, "board": {"x": 30, "y": -10}},
  200. {"image": {"x": 0, "y": 100}, "board": {"x": 0, "y": 0}},
  201. ],
  202. }
  203. write_json(config.annotations_path, annotations)
  204. generate_assets(config, runner=FakeKiCad())
  205. board_data = json.loads((config.output_dir / "board-data.json").read_text(encoding="utf-8"))
  206. build_info = json.loads((config.output_dir / "build-info.json").read_text(encoding="utf-8"))
  207. assert (config.output_dir / "board-photo.png").read_bytes() == b"fixture-photo"
  208. assert board_data["photo_overlay"]["asset"] == "board-photo.png"
  209. assert board_data["photo_overlay"]["matrix"] == pytest.approx([0.3, 0.0, 0.0, 0.1, 0.0, 0.0])
  210. assert "board-photo.png" in build_info["assets"]
  211. assert build_info["sources"]["photo"]["path"] == str(photo.resolve())