from dataclasses import fields, replace from decimal import Decimal import json from pathlib import Path import pytest from dx_productivity.part_replace.models import ( ComponentSnapshot, DesignSnapshot, PinSnapshot, Scope, UnitSnapshot, ) from dx_productivity.part_replace.protocol import ( BridgeCommand, BridgeStatus, ProtocolError, atomic_write_text, load_snapshot, load_status, snapshot_fingerprint, write_command, write_snapshot, ) FIXTURES = Path(__file__).parents[1] / "fixtures" @pytest.fixture def before_snapshot() -> DesignSnapshot: return DesignSnapshot( format_version=2, project_id="project-1", project_path="C:/Projects/board.prj", fingerprint="stored-before-fingerprint", components=( ComponentSnapshot( logical_key="/MAIN|R1", refdes="R1", part_number="OLD-1", attributes=(("tolerance", "1%"), ("vendor", "Acme")), units=( UnitSnapshot( unit_id="A", sheet="/MAIN", symbol="RES", origin_x=Decimal("-0.5"), origin_y=Decimal("-0.5"), x=Decimal("0"), y=Decimal("0"), rotation=0, mirrored=False, pins=( PinSnapshot("1", "A", Decimal("10.25"), Decimal("20"), "N$1"), PinSnapshot("2", "B", Decimal("11"), Decimal("20"), None), ), ), ), ), ), ) def load_fixture(name: str) -> DesignSnapshot: return load_snapshot(FIXTURES / name) def test_snapshot_v2_requires_and_round_trips_distinct_origin_coordinates( tmp_path: Path, ) -> None: # Catches a bridge snapshot that reads OriginX/Y but drops them in serialization. path = tmp_path / "snapshot-v2.json" path.write_text( '{"components":[{"attributes":[],"logical_key":"/MAIN|U1",' '"part_number":"OLD-1","refdes":"U1","units":[{"mirrored":false,' '"origin_x":"1.25","origin_y":"2.5","pins":[],"rotation":0,' '"sheet":"/MAIN","symbol":"IC","unit_id":"A","x":"100",' '"y":"200"}]}],"fingerprint":"stored","format_version":2,' '"project_id":"p1","project_path":"C:/Projects/board.prj"}', encoding="utf-8", ) snapshot = load_snapshot(path) unit = snapshot.components[0].units[0] assert (unit.origin_x, unit.origin_y, unit.x, unit.y) == ( Decimal("1.25"), Decimal("2.5"), Decimal("100"), Decimal("200"), ) output = tmp_path / "round-trip.json" write_snapshot(output, snapshot) assert load_snapshot(output) == snapshot def test_snapshot_v1_is_explicitly_rejected_as_missing_origin_evidence( tmp_path: Path, ) -> None: # A v1 snapshot cannot be migrated safely because it never recorded unit origin. path = tmp_path / "legacy-v1.json" path.write_text( '{"components":[],"fingerprint":"stored","format_version":1,' '"project_id":"p1","project_path":"C:/Projects/board.prj"}', encoding="utf-8", ) with pytest.raises(ProtocolError) as raised: load_snapshot(path) assert raised.value.code == "legacy_snapshot_missing_origin" def test_snapshot_fixture_has_independently_checked_content(before_snapshot: DesignSnapshot) -> None: loaded = load_fixture("snapshot-before.json") assert loaded == before_snapshot assert loaded.components[0].units[0].pins[0].x == Decimal("10.25") assert loaded.components[0].units[0].pins[1].net is None def test_snapshot_round_trip_is_canonical(tmp_path: Path, before_snapshot: DesignSnapshot) -> None: output = tmp_path / "snapshot.json" write_snapshot(output, before_snapshot) assert output.read_text(encoding="utf-8") == ( '{"components":[{"attributes":[{"name":"tolerance","value":"1%"},' '{"name":"vendor","value":"Acme"}],"logical_key":"/MAIN|R1",' '"part_number":"OLD-1","refdes":"R1","units":[{"mirrored":false,' '"origin_x":"-0.5","origin_y":"-0.5",' '"pins":[{"name":"A","net":"N$1","number":"1","x":"10.25",' '"y":"20"},{"name":"B","net":null,"number":"2","x":"11",' '"y":"20"}],"rotation":0,"sheet":"/MAIN","symbol":"RES",' '"unit_id":"A","x":"0","y":"0"}]}],' '"fingerprint":"stored-before-fingerprint","format_version":2,' '"project_id":"project-1","project_path":"C:/Projects/board.prj"}\n' ) loaded = load_snapshot(output) assert loaded == before_snapshot assert snapshot_fingerprint(loaded) == snapshot_fingerprint(before_snapshot) assert not list(tmp_path.glob("*.tmp")) def test_snapshot_fingerprint_excludes_only_stored_fingerprint(before_snapshot: DesignSnapshot) -> None: assert snapshot_fingerprint(before_snapshot) == "f89a844afe0e47a733dcd4060a854dda7bcfe53fd9acea810b4aebd3ccfdb914" assert snapshot_fingerprint(replace(before_snapshot, fingerprint="different")) == ( "f89a844afe0e47a733dcd4060a854dda7bcfe53fd9acea810b4aebd3ccfdb914" ) assert snapshot_fingerprint(replace(before_snapshot, project_path="C:/Projects/other.prj")) != ( "f89a844afe0e47a733dcd4060a854dda7bcfe53fd9acea810b4aebd3ccfdb914" ) def test_after_snapshot_fixtures_preserve_or_change_the_expected_pin() -> None: compatible = load_fixture("snapshot-after-compatible.json") changed = load_fixture("snapshot-after-pin-change.json") assert compatible.components[0].part_number == "NEW-1" assert compatible.components[0].units[0].pins[1].number == "2" assert changed.components[0].units[0].pins[1].number == "3" @pytest.mark.parametrize( ("payload", "code"), ( ('{"format_version":3}', "unsupported_format_version"), ('{"format_version":2}', "missing_required_field"), ('{"format_version":true,"project_id":"p","project_path":"x","fingerprint":"f","components":[]}', "wrong_type"), ('{"format_version":2,"project_id":"p","project_path":"x","fingerprint":"f","components":[],"extra":null}', "unknown_field"), ), ) def test_snapshot_schema_is_fail_closed(tmp_path: Path, payload: str, code: str) -> None: path = tmp_path / "invalid.json" path.write_text(payload, encoding="utf-8") with pytest.raises(ProtocolError, match=code): load_snapshot(path) @pytest.mark.parametrize( ("components", "code"), ( ( '[{"logical_key":"k","refdes":"R1","part_number":"P","attributes":[],"units":[]},' '{"logical_key":"k","refdes":"R2","part_number":"P","attributes":[],"units":[]}]', "duplicate_logical_key", ), ( '[{"logical_key":"k","refdes":"R1","part_number":"P","attributes":[],"units":[' '{"unit_id":"A","sheet":"/","symbol":"X","origin_x":"0","origin_y":"0","x":"0","y":"0","rotation":0,"mirrored":false,"pins":[]},' '{"unit_id":"A","sheet":"/","symbol":"Y","origin_x":"0","origin_y":"0","x":"0","y":"0","rotation":0,"mirrored":false,"pins":[]}]}]', "duplicate_unit_id", ), ( '[{"logical_key":"k","refdes":"R1","part_number":"P","attributes":[],"units":[' '{"unit_id":"A","sheet":"/","symbol":"X","origin_x":"0","origin_y":"0","x":"0","y":"0","rotation":0,"mirrored":false,"pins":[' '{"number":"1","name":"A","x":"0","y":"0","net":null},' '{"number":"1","name":"B","x":"1","y":"0","net":null}]}]}]', "duplicate_pin_number", ), ), ) def test_snapshot_rejects_duplicate_structural_keys(tmp_path: Path, components: str, code: str) -> None: path = tmp_path / "duplicates.json" path.write_text( '{"format_version":2,"project_id":"p","project_path":"x","fingerprint":"f","components":' + components + '}', encoding="utf-8", ) with pytest.raises(ProtocolError, match=code): load_snapshot(path) def test_pin_number_can_repeat_in_different_units(tmp_path: Path) -> None: path = tmp_path / "separate-units.json" path.write_text( '{"format_version":2,"project_id":"p","project_path":"x","fingerprint":"f","components":[' '{"logical_key":"k","refdes":"R1","part_number":"P","attributes":[],"units":[' '{"unit_id":"A","sheet":"/","symbol":"X","origin_x":"0","origin_y":"0","x":"0","y":"0","rotation":0,"mirrored":false,"pins":[{"number":"1","name":"A","x":"0","y":"0","net":null}]},' '{"unit_id":"B","sheet":"/","symbol":"Y","origin_x":"0","origin_y":"0","x":"0","y":"0","rotation":0,"mirrored":false,"pins":[{"number":"1","name":"B","x":"0","y":"0","net":null}]}]}]}', encoding="utf-8", ) assert tuple(unit.unit_id for unit in load_snapshot(path).components[0].units) == ("A", "B") def test_command_is_immutable_has_exact_fields_and_writes_canonical_json(tmp_path: Path) -> None: command = BridgeCommand( 1, "cmd-7", "replace_part", "job-2", "project-1", Scope.FULL_PROJECT, "OLD-1", "NEW-1", ("/MAIN|R2", "/MAIN|R1"), 2, "fingerprint-1", ) output = tmp_path / "command.json" write_command(output, command) assert tuple(field.name for field in fields(BridgeCommand)) == ( "format_version", "command_id", "action", "job_id", "project_id", "scope", "old_part_number", "new_part_number", "expected_logical_keys", "expected_count", "expected_fingerprint", ) assert output.read_text(encoding="utf-8") == ( '{"action":"replace_part","command_id":"cmd-7","expected_count":2,' '"expected_fingerprint":"fingerprint-1","expected_logical_keys":["/MAIN|R2","/MAIN|R1"],' '"format_version":1,"job_id":"job-2","new_part_number":"NEW-1",' '"old_part_number":"OLD-1","project_id":"project-1","scope":"full_project"}\n' ) def test_snapshot_writer_rejects_boolean_format_version(tmp_path: Path, before_snapshot: DesignSnapshot) -> None: with pytest.raises(ProtocolError, match="wrong_type"): write_snapshot(tmp_path / "snapshot.json", replace(before_snapshot, format_version=True)) # type: ignore[arg-type] @pytest.mark.parametrize( ("invalid_snapshot", "code"), ( ( lambda snapshot: replace( snapshot, components=(snapshot.components[0], replace(snapshot.components[0], refdes="R2")), ), "duplicate_logical_key", ), ( lambda snapshot: replace( snapshot, components=( replace( snapshot.components[0], units=( snapshot.components[0].units[0], replace(snapshot.components[0].units[0], symbol="ALT"), ), ), ), ), "duplicate_unit_id", ), ( lambda snapshot: replace( snapshot, components=( replace( snapshot.components[0], units=( replace( snapshot.components[0].units[0], pins=( snapshot.components[0].units[0].pins[0], replace(snapshot.components[0].units[0].pins[0], name="Duplicate"), ), ), ), ), ), ), "duplicate_pin_number", ), ( lambda snapshot: replace( snapshot, components=( replace( snapshot.components[0], units=( object(), # type: ignore[arg-type] ), ), ), ), "wrong_type", ), ), ) def test_snapshot_publication_and_fingerprinting_reject_invalid_models( tmp_path: Path, before_snapshot: DesignSnapshot, invalid_snapshot: object, code: str, ) -> None: snapshot = invalid_snapshot(before_snapshot) # type: ignore[operator] output = tmp_path / "invalid-snapshot.json" with pytest.raises(ProtocolError, match=code): write_snapshot(output, snapshot) assert not output.exists() with pytest.raises(ProtocolError, match=code): snapshot_fingerprint(snapshot) def test_status_parsing_is_immutable_and_fail_closed(tmp_path: Path) -> None: path = tmp_path / "status.json" path.write_text( '{"command_id":"cmd-7","details":[["phase","apply"]],"error_code":null,' '"error_message":null,"format_version":1,"project_id":"project-1",' '"snapshot_path":"C:/Run/after.json","state":"completed"}', encoding="utf-8", ) assert load_status(path) == BridgeStatus( 1, "cmd-7", "project-1", "completed", "C:/Run/after.json", None, None, (("phase", "apply"),), ) path.write_text( '{"command_id":"cmd-7","details":[],"error_code":null,"error_message":null,' '"format_version":1,"project_id":"project-1","snapshot_path":null,"state":"completed","extra":0}', encoding="utf-8", ) with pytest.raises(ProtocolError, match="unknown_field"): load_status(path) def test_atomic_write_normalizes_newlines_and_cleans_up_after_replace_failure(tmp_path: Path) -> None: output = tmp_path / "mailbox.txt" atomic_write_text(output, "first\r\nsecond\rthird\n") assert output.read_bytes() == b"first\nsecond\nthird\n" target_directory = tmp_path / "target-directory" target_directory.mkdir() with pytest.raises(OSError): atomic_write_text(target_directory, "cannot replace a directory") assert not list(tmp_path.glob("*.tmp"))