from __future__ import annotations import json import hashlib import shutil import sys from dataclasses import dataclass from pathlib import Path import pytest ROOT = Path(__file__).resolve().parents[2] VIEWER_ROOT = ROOT / "tools" / "board-viewer" FIXTURE = Path(__file__).parent / "fixtures" / "parser_edge_cases.kicad_pcb" D356_FIXTURE = Path(__file__).parent / "fixtures" / "parser_edge_cases.d356" sys.path.insert(0, str(VIEWER_ROOT)) from board_viewer.assets import sha256_file, validate_generated_assets # noqa: E402 from board_viewer.generator import ( # noqa: E402 GenerationConfig, GenerationError, generate_assets, manifest_source_path, ) @dataclass class FakeResult: returncode: int = 0 stdout: str = "" stderr: str = "" class FakeKiCad: def __init__(self, *, fail_export: bool = False) -> None: self.commands: list[list[str]] = [] self.fail_export = fail_export def __call__(self, command: list[str], cwd: Path) -> FakeResult: self.commands.append(command) if command[-1] == "--version": return FakeResult(stdout="10.0.4\n") if command[1:3] == ["pcb", "import"]: output = Path(command[command.index("--output") + 1]) report = Path(command[command.index("--report-file") + 1]) shutil.copy2(FIXTURE, output) report.write_text( json.dumps( { "errors": [], "warnings": [], "statistics": {"footprints": 2, "tracks": 0, "vias": 0, "zones": 0}, } ), encoding="utf-8", ) return FakeResult() if command[1:4] == ["pcb", "export", "svg"]: if self.fail_export: return FakeResult(returncode=1, stderr="export failed") output = Path(command[command.index("--output") + 1]) layers = command[command.index("--layers") + 1] output.write_text( '' f'fixture date 2026-07-21T12:00:00{layers}', encoding="utf-8", ) return FakeResult() if command[1:4] == ["pcb", "export", "ipcd356"]: output = Path(command[command.index("--output") + 1]) shutil.copy2(D356_FIXTURE, output) return FakeResult() raise AssertionError(f"unexpected command: {command}") def write_json(path: Path, payload: object) -> None: path.write_text(json.dumps(payload), encoding="utf-8") def generation_config(tmp_path: Path) -> GenerationConfig: brd = tmp_path / "fixture.brd" inventory = tmp_path / "inventory.json" annotations = tmp_path / "annotations.json" brd.write_bytes(b"fixture Allegro source") write_json( inventory, { "schema": "fixture-v1", "board_id": "fixture-board", "pins": [], }, ) write_json( annotations, { "schema": "board-viewer-annotations-v1", "board_id": "fixture-board", "connector_profiles": {}, "touchpoints": {}, "interfaces": [], "photo_overlay": None, }, ) return GenerationConfig( brd_path=brd, inventory_path=inventory, annotations_path=annotations, output_dir=tmp_path / "published" / "generated", kicad_cli=tmp_path / "kicad-cli.exe", board_name="Fixture board", required_kicad_version="10.0.4", expected_counts={"footprints": 2, "touchpoints": 2, "pads": 3}, expected_front_only=False, temp_parent=tmp_path / "outside-worktree-temp", ) def test_generate_builds_valid_hashed_bundle_then_replaces_old_assets(tmp_path: Path) -> None: config = generation_config(tmp_path) config.kicad_cli.write_text("fake", encoding="utf-8") config.output_dir.mkdir(parents=True) (config.output_dir / "old.txt").write_text("old", encoding="utf-8") runner = FakeKiCad() result = generate_assets(config, runner=runner) assert result["status"] == "pass" assert not (config.output_dir / "old.txt").exists() assert {path.name for path in config.output_dir.iterdir()} == { "board-data.json", "board-mask-edge.svg", "board-silkscreen.svg", "board-copper.svg", "board-mask-edge-back.svg", "board-silkscreen-back.svg", "board-copper-back.svg", "import-report.json", "build-info.json", } build_info = json.loads((config.output_dir / "build-info.json").read_text(encoding="utf-8")) assert build_info["counts"] == { "footprints": 2, "touchpoints": 2, "pads": 3, "resistors": 0, "resistor_pads": 0, } assert build_info["toolchain"]["kicad"] == "10.0.4" assert build_info["verification"]["ipcd356"] == { "numbered_pads": 2, "matched_pads": 2, "record_types": {"317": 1, "327": 1}, "tolerance_mm": 0.02, } assert build_info["sources"]["brd"]["sha256"] == sha256_file(config.brd_path) generator_sources = { "generator_pipeline": VIEWER_ROOT / "board_viewer" / "generator.py", "generator_data": VIEWER_ROOT / "board_viewer" / "data.py", "generator_annotations": VIEWER_ROOT / "board_viewer" / "annotations.py", "generator_eligibility": VIEWER_ROOT / "board_viewer" / "eligibility.py", "generator_pcb": VIEWER_ROOT / "board_viewer" / "pcb.py", "generator_sexpr": VIEWER_ROOT / "board_viewer" / "sexpr.py", "generator_ipcd356": VIEWER_ROOT / "board_viewer" / "ipcd356.py", "generator_photo": VIEWER_ROOT / "board_viewer" / "photo.py", "generator_regression": VIEWER_ROOT / "board_viewer" / "regression.py", "schema_data": ROOT / "schemas" / "board_viewer_data.schema.json", "schema_annotations": ROOT / "schemas" / "board_viewer_annotations.schema.json", } for name, path in generator_sources.items(): assert build_info["sources"][name]["path"] == path.relative_to(ROOT).as_posix() assert build_info["sources"][name]["sha256"] == sha256_file(path) assert validate_generated_assets(config.output_dir).status == "pass" for name, metadata in build_info["assets"].items(): assert metadata["sha256"] == sha256_file(config.output_dir / name) assert all("F.Fab" not in " ".join(command) for command in runner.commands) export_layers = { command[command.index("--layers") + 1] for command in runner.commands if command[1:4] == ["pcb", "export", "svg"] } assert export_layers == { "F.Mask,Edge.Cuts", "F.SilkS,Edge.Cuts", "F.Cu,Edge.Cuts", "B.Mask,Edge.Cuts", "B.SilkS,Edge.Cuts", "B.Cu,Edge.Cuts", } mirrored = { tuple(command) for command in runner.commands if command[1:4] == ["pcb", "export", "svg"] and "--mirror" in command } assert len(mirrored) == 3 assert build_info["verification"]["side_views"]["back_mirror_axis"] == "y" assert build_info["verification"]["side_views"]["back_svg_export_mirrored"] is True assert "2026-07-21T12:00:00" not in (config.output_dir / "board-mask-edge.svg").read_text(encoding="utf-8") def test_generate_failure_keeps_previous_bundle_untouched(tmp_path: Path) -> None: config = generation_config(tmp_path) config.kicad_cli.write_text("fake", encoding="utf-8") config.output_dir.mkdir(parents=True) sentinel = config.output_dir / "old.txt" sentinel.write_text("must survive", encoding="utf-8") with pytest.raises(GenerationError, match="export failed"): generate_assets(config, runner=FakeKiCad(fail_export=True)) assert sentinel.read_text(encoding="utf-8") == "must survive" def test_generate_rejects_wrong_kicad_version_before_import(tmp_path: Path) -> None: config = generation_config(tmp_path) config.kicad_cli.write_text("fake", encoding="utf-8") runner = FakeKiCad() def wrong_version(command: list[str], cwd: Path) -> FakeResult: if command[-1] == "--version": return FakeResult(stdout="9.0.0") return runner(command, cwd) with pytest.raises(GenerationError, match="requires KiCad 10.0.4"): generate_assets(config, runner=wrong_version) assert runner.commands == [] def test_generate_rejects_temp_directory_inside_repository(tmp_path: Path) -> None: config = generation_config(tmp_path) config.kicad_cli.write_text("fake", encoding="utf-8") config.temp_parent = ROOT / "tmp" / "board-viewer-test" with pytest.raises(GenerationError, match="temporary directory must be outside repository"): generate_assets(config, runner=FakeKiCad()) def test_manifest_uses_portable_paths_for_repository_sources(tmp_path: Path) -> None: assert manifest_source_path(ROOT / "config" / "pin_inventory.fcb_fpga_mcu0611.json") == "config/pin_inventory.fcb_fpga_mcu0611.json" assert manifest_source_path(tmp_path / "external.brd") == str((tmp_path / "external.brd").resolve()) def test_generate_includes_optional_hash_bound_photo_overlay(tmp_path: Path) -> None: config = generation_config(tmp_path) config.kicad_cli.write_text("fake", encoding="utf-8") config.photo_root = tmp_path photo = tmp_path / "board-photo.png" photo.write_bytes(b"fixture-photo") annotations = json.loads(config.annotations_path.read_text(encoding="utf-8")) annotations["photo_overlay"] = { "path": "board-photo.png", "sha256": hashlib.sha256(b"fixture-photo").hexdigest(), "control_points": [ {"image": {"x": 0, "y": 0}, "board": {"x": 0, "y": -10}}, {"image": {"x": 100, "y": 0}, "board": {"x": 30, "y": -10}}, {"image": {"x": 0, "y": 100}, "board": {"x": 0, "y": 0}}, ], } write_json(config.annotations_path, annotations) generate_assets(config, runner=FakeKiCad()) board_data = json.loads((config.output_dir / "board-data.json").read_text(encoding="utf-8")) build_info = json.loads((config.output_dir / "build-info.json").read_text(encoding="utf-8")) assert (config.output_dir / "board-photo.png").read_bytes() == b"fixture-photo" assert board_data["photo_overlay"]["asset"] == "board-photo.png" assert board_data["photo_overlay"]["matrix"] == pytest.approx([0.3, 0.0, 0.0, 0.1, 0.0, 0.0]) assert "board-photo.png" in build_info["assets"] assert build_info["sources"]["photo"]["path"] == str(photo.resolve())