from __future__ import annotations
import hashlib
import json
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[2]
VIEWER_ROOT = ROOT / "tools" / "board-viewer"
sys.path.insert(0, str(VIEWER_ROOT))
from board_viewer.assets import ( # noqa: E402
AssetIntegrityError,
sha256_file,
validate_generated_assets,
)
def write(path: Path, content: str) -> str:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
return hashlib.sha256(content.encode("utf-8")).hexdigest()
def create_asset_set(tmp_path: Path) -> tuple[Path, dict[str, Path]]:
generated = tmp_path / "generated"
sources = {
"brd": tmp_path / "source.brd",
"inventory": tmp_path / "inventory.json",
"annotations": tmp_path / "annotations.json",
}
source_hashes = {name: write(path, f"{name}-source") for name, path in sources.items()}
assets = {
"board-data.json": write(generated / "board-data.json", '{"schema":"board-viewer-data-v2"}'),
"board-mask-edge.svg": write(generated / "board-mask-edge.svg", ""),
"board-silkscreen.svg": write(generated / "board-silkscreen.svg", ""),
"board-copper.svg": write(generated / "board-copper.svg", ""),
"import-report.json": write(generated / "import-report.json", '{"errors":[],"warnings":[]}'),
}
build_info = {
"schema": "board-viewer-build-info-v1",
"generated_at": "2026-07-21T00:00:00Z",
"generator_version": "1.0.0",
"toolchain": {"python": "3.12.9", "kicad": "10.0.4"},
"sources": {
name: {"path": str(path), "sha256": source_hashes[name]}
for name, path in sources.items()
},
"assets": {name: {"sha256": digest, "bytes": (generated / name).stat().st_size} for name, digest in assets.items()},
"verification": {
"ipcd356": {
"numbered_pads": 455,
"matched_pads": 455,
"record_types": {"317": 72, "327": 383},
"tolerance_mm": 0.02,
}
},
"counts": {
"footprints": 1052,
"touchpoints": 110,
"pads": 472,
"resistors": 0,
"resistor_pads": 0,
},
}
write(generated / "build-info.json", json.dumps(build_info))
return generated, sources
def test_sha256_file_streams_exact_file_content(tmp_path: Path) -> None:
path = tmp_path / "payload.bin"
path.write_bytes(b"abc" * 100_000)
assert sha256_file(path) == hashlib.sha256(b"abc" * 100_000).hexdigest()
def test_generated_assets_pass_when_hashes_and_sources_match(tmp_path: Path) -> None:
generated, _ = create_asset_set(tmp_path)
result = validate_generated_assets(generated)
assert result.status == "pass"
assert result.asset_errors == []
assert result.stale_sources == []
@pytest.mark.parametrize("problem", ["missing", "hash_mismatch"])
def test_generated_asset_damage_fails_closed(tmp_path: Path, problem: str) -> None:
generated, _ = create_asset_set(tmp_path)
asset = generated / "board-data.json"
if problem == "missing":
asset.unlink()
else:
asset.write_text("tampered", encoding="utf-8")
with pytest.raises(AssetIntegrityError, match="board-data.json"):
validate_generated_assets(generated)
@pytest.mark.parametrize("problem", ["missing", "hash_mismatch"])
def test_source_change_enters_stale_read_only_mode(tmp_path: Path, problem: str) -> None:
generated, sources = create_asset_set(tmp_path)
if problem == "missing":
sources["brd"].unlink()
else:
sources["inventory"].write_text("changed", encoding="utf-8")
result = validate_generated_assets(generated)
assert result.status == "stale_sources"
assert result.asset_errors == []
assert result.stale_sources
assert result.recommendations_enabled is False
assert result.adc_copy_enabled is False
def test_missing_build_info_fails_closed(tmp_path: Path) -> None:
generated = tmp_path / "generated"
generated.mkdir()
with pytest.raises(AssetIntegrityError, match="build-info.json"):
validate_generated_assets(generated)
def test_relative_source_paths_resolve_from_repository_root(tmp_path: Path) -> None:
generated, _ = create_asset_set(tmp_path)
build_info_path = generated / "build-info.json"
build_info = json.loads(build_info_path.read_text(encoding="utf-8"))
build_info["sources"]["brd"]["path"] = "source.brd"
build_info_path.write_text(json.dumps(build_info), encoding="utf-8")
result = validate_generated_assets(generated, repository_root=tmp_path)
assert result.status == "pass"