from dataclasses import replace from decimal import Decimal import json from pathlib import Path import pytest from dx_productivity.part_replace.certification import ( CertificationError, CertificationStore, interface_fingerprint, ) from dx_productivity.part_replace.models import ( ComponentSnapshot, DesignSnapshot, ExternalChecks, MappingRule, PinSnapshot, UnitSnapshot, ) from dx_productivity.part_replace.verification import verify_replacement @pytest.fixture def snapshots() -> tuple[DesignSnapshot, DesignSnapshot]: before = DesignSnapshot( format_version=2, project_id="representative-project", project_path="C:/Projects/trial.prj", fingerprint="captured-before", components=( ComponentSnapshot( logical_key="/MAIN|U1", refdes="U1", part_number="OLD-1", attributes=(("manufacturer", "Acme"),), units=( UnitSnapshot( unit_id=" A ", sheet="/MAIN", symbol="Library:AMP", origin_x=Decimal("9.5"), origin_y=Decimal("19.5"), x=Decimal("10"), y=Decimal("20"), rotation=0, mirrored=False, pins=( PinSnapshot("1", "IN+", Decimal("10.25"), Decimal("20"), "NET-IN"), PinSnapshot("2", "IN-", Decimal("10.5"), Decimal("20"), "NET-REF"), ), ), ), ), ), ) after = replace(before, components=(replace(before.components[0], part_number="NEW-1"),)) return before, after @pytest.fixture def rule() -> MappingRule: return MappingRule("OLD-1", "NEW-1") @pytest.fixture def verification(snapshots: tuple[DesignSnapshot, DesignSnapshot], rule: MappingRule): before, after = snapshots return verify_replacement(before, after, rule, ("/MAIN|U1",)) @pytest.fixture def target_fingerprint(snapshots: tuple[DesignSnapshot, DesignSnapshot]) -> str: _, after = snapshots return interface_fingerprint(after, ("/MAIN|U1",)) @pytest.fixture def store( tmp_path: Path, snapshots: tuple[DesignSnapshot, DesignSnapshot], verification, ) -> CertificationStore: before, after = snapshots return CertificationStore( tmp_path / "certifications.json", before=before, after=after, verification=verification, evidence_paths=("before.json", "after.json", "packager.txt", "erc.txt", "netlist.txt"), ) @pytest.fixture def certification( store: CertificationStore, rule: MappingRule, target_fingerprint: str, ): return store.record( rule, target_fingerprint, "lib-r42", ExternalChecks(packager=True, erc=True, netlist=True), ) def test_certification_requires_hard_checks_and_external_checks( store: CertificationStore, rule: MappingRule, target_fingerprint: str, ) -> None: # Catches a record path that treats an omitted or false external result as success. with pytest.raises(CertificationError, match="external_checks_incomplete"): store.record( rule, target_fingerprint, "lib-r42", ExternalChecks(packager=True, erc=None, netlist=True), ) with pytest.raises(CertificationError, match="external_checks_incomplete"): store.record( rule, target_fingerprint, "lib-r42", ExternalChecks(packager=True, erc=False, netlist=True), ) def test_changed_library_or_target_fingerprint_invalidates( store: CertificationStore, certification, ) -> None: # Catches lookup that permits a certification after target or library drift. with pytest.raises(CertificationError, match="certification_mismatch"): store.require(certification.rule, "different-fingerprint", "lib-r42") with pytest.raises(CertificationError, match="certification_mismatch"): store.require(certification.rule, certification.target_fingerprint, "lib-r43") def test_certification_round_trips_immutable_trial_evidence( tmp_path: Path, store: CertificationStore, certification, ) -> None: # Catches persistence that omits required immutable trial evidence or cannot be reopened. reopened = CertificationStore(tmp_path / "certifications.json") loaded = reopened.require( certification.rule, certification.target_fingerprint, certification.library_identity, ) assert loaded == certification assert loaded.dxdesigner_build == "7.9.5" assert loaded.evidence_paths == ("before.json", "after.json", "packager.txt", "erc.txt", "netlist.txt") assert loaded.representative_project_fingerprint == "621b3eb72b9c1abecf3856103474c8675adb2857b33d8bd8cb9240a3070672be" with pytest.raises((AttributeError, TypeError)): loaded.target_fingerprint = "other" # type: ignore[misc] assert (tmp_path / "certifications.json").read_text(encoding="utf-8").endswith("\n") def test_interface_fingerprint_includes_only_observed_interface( snapshots: tuple[DesignSnapshot, DesignSnapshot], ) -> None: # Catches target identity that accidentally depends on project, Part Number, placement, nets, or attributes. _, after = snapshots component = after.components[0] unit = component.units[0] moved_component = _placed_occurrence( component, logical_key="/OTHER|X99", refdes="X99", x=Decimal("100"), y=Decimal("200"), rotation=270, mirrored=True, ) moved_unit = moved_component.units[0] unrelated_change = replace( after, project_id="another-project", project_path="D:/Other/board.prj", fingerprint="different-snapshot", components=( replace( moved_component, part_number="DIFFERENT-PART", attributes=(("vendor", "Other"),), units=( replace( moved_unit, pins=( replace(moved_unit.pins[0], net="OTHER-NET"), replace(moved_unit.pins[1], net="OTHER-NET-2"), ), ), ), ), ), ) changed_interface = replace( after, components=(replace(component, units=(replace(unit, pins=(replace(unit.pins[0], name="INPUT+"), unit.pins[1])),)),), ) expected = "decbaa0cd1cd8810b5900448a1da19f272c18639d7acc194fdc928a22cd55dc1" assert interface_fingerprint(after, ("/MAIN|U1",)) == expected assert interface_fingerprint(unrelated_change, ("/OTHER|X99",)) == expected assert interface_fingerprint(changed_interface, ("/MAIN|U1",)) != expected def _placed_occurrence( component: ComponentSnapshot, *, logical_key: str, refdes: str, x: Decimal, y: Decimal, rotation: int, mirrored: bool, ) -> ComponentSnapshot: source = component.units[0] def place(source_x: Decimal, source_y: Decimal) -> tuple[Decimal, Decimal]: local_x = source_x - source.x local_y = source_y - source.y mirrored_x = -local_x if mirrored else local_x angle = rotation % 360 if angle == 0: offset_x, offset_y = mirrored_x, local_y elif angle == 90: offset_x, offset_y = -local_y, mirrored_x elif angle == 180: offset_x, offset_y = -mirrored_x, -local_y elif angle == 270: offset_x, offset_y = local_y, -mirrored_x else: raise AssertionError("test placement uses quarter-turn rotations") return x + offset_x, y + offset_y pins = tuple( replace(pin, x=place(pin.x, pin.y)[0], y=place(pin.x, pin.y)[1]) for pin in source.pins ) origin_x, origin_y = place(source.origin_x, source.origin_y) unit = replace( source, origin_x=origin_x, origin_y=origin_y, x=x, y=y, rotation=rotation, mirrored=mirrored, pins=pins, ) return replace(component, logical_key=logical_key, refdes=refdes, units=(unit,)) def test_interface_fingerprint_is_independent_of_occurrence_count_and_placement( snapshots: tuple[DesignSnapshot, DesignSnapshot], ) -> None: # Catches certification identities tied to project hit count or instance transforms. _, after = snapshots component = after.components[0] occurrences = ( _placed_occurrence( component, logical_key="/MAIN|U1", refdes="U1", x=Decimal("10"), y=Decimal("20"), rotation=0, mirrored=False, ), _placed_occurrence( component, logical_key="/MAIN|U2", refdes="U2", x=Decimal("100"), y=Decimal("200"), rotation=90, mirrored=False, ), _placed_occurrence( component, logical_key="/MAIN|U3", refdes="U3", x=Decimal("-5"), y=Decimal("30"), rotation=270, mirrored=True, ), ) single = replace(after, components=(occurrences[0],)) repeated = replace(after, components=occurrences) assert interface_fingerprint(single, ("/MAIN|U1",)) == interface_fingerprint( repeated, ("/MAIN|U1", "/MAIN|U2", "/MAIN|U3"), ) def test_interface_fingerprint_rejects_heterogeneous_selected_occurrences( snapshots: tuple[DesignSnapshot, DesignSnapshot], ) -> None: # Catches hashing unlike target interfaces into one occurrence-dependent certificate. _, after = snapshots first = after.components[0] different = replace( first, logical_key="/MAIN|U2", refdes="U2", units=( replace( first.units[0], pins=(replace(first.units[0].pins[0], name="DIFFERENT"), first.units[0].pins[1]), ), ), ) heterogeneous = replace(after, components=(first, different)) with pytest.raises(CertificationError, match="heterogeneous_interface"): interface_fingerprint(heterogeneous, ("/MAIN|U1", "/MAIN|U2")) def test_certification_rejects_a_target_not_observed_in_the_trial( store: CertificationStore, rule: MappingRule, ) -> None: # Catches record creation that accepts a caller-supplied fingerprint unrelated to the verified trial. with pytest.raises(CertificationError, match="target_fingerprint_mismatch"): store.record( rule, "not-the-observed-interface", None, ExternalChecks(packager=True, erc=True, netlist=True), ) def test_certification_requires_a_passing_hard_verification( tmp_path: Path, snapshots: tuple[DesignSnapshot, DesignSnapshot], verification, rule: MappingRule, target_fingerprint: str, ) -> None: # Catches a record path that accepts external success after hard verification has failed. before, after = snapshots failed_trial = CertificationStore( tmp_path / "certifications.json", before=before, after=after, verification=replace(verification, passed=False), ) with pytest.raises(CertificationError, match="hard_verification_failed"): failed_trial.record( rule, target_fingerprint, "lib-r42", ExternalChecks(packager=True, erc=True, netlist=True), ) def test_certification_without_library_identity_requires_exact_target( store: CertificationStore, rule: MappingRule, target_fingerprint: str, ) -> None: # Catches lookup that accepts a no-library certification when its observed target drifts. store.record( rule, target_fingerprint, None, ExternalChecks(packager=True, erc=True, netlist=True), ) with pytest.raises(CertificationError, match="certification_mismatch"): store.require(rule, "different-fingerprint", None) def test_interface_fingerprint_rejects_ambiguous_or_missing_selection( snapshots: tuple[DesignSnapshot, DesignSnapshot], ) -> None: # Catches an interface identity generated from duplicate or absent logical components. _, after = snapshots with pytest.raises(CertificationError, match="invalid_logical_keys"): interface_fingerprint(after, ("/MAIN|U1", "/MAIN|U1")) with pytest.raises(CertificationError, match="invalid_logical_keys"): interface_fingerprint(after, ("/MAIN|MISSING",)) def test_corrupt_persisted_certification_blocks_apply(tmp_path: Path, rule: MappingRule) -> None: # Catches Apply lookup that ignores malformed durable certification evidence. path = tmp_path / "certifications.json" path.write_text('{"format_version":1,"certifications":[{"old_part_number":"OLD-1"}]}', encoding="utf-8") with pytest.raises(CertificationError, match="corrupt_certification"): CertificationStore(path).require(rule, "target", "lib-r42") @pytest.mark.parametrize( "payload", ( '{"format_version":1,"format_version":1,"certifications":[]}', '{"format_version":2,"certifications":[]}', '{"format_version":1,"certifications":{}}', ), ) def test_corrupt_document_roots_fail_closed(tmp_path: Path, rule: MappingRule, payload: str) -> None: # Catches Apply lookup that accepts duplicate, unsupported, or structurally invalid document roots. path = tmp_path / "certifications.json" path.write_text(payload, encoding="utf-8") with pytest.raises(CertificationError, match="corrupt_certification"): CertificationStore(path).require(rule, "target", None) def test_certification_requires_complete_trial_context( tmp_path: Path, rule: MappingRule, target_fingerprint: str, ) -> None: # Catches record creation without the verified representative snapshots. with pytest.raises(CertificationError, match="trial_context_missing"): CertificationStore(tmp_path / "certifications.json").record( rule, target_fingerprint, None, ExternalChecks(packager=True, erc=True, netlist=True), ) def test_certification_rejects_trial_project_mismatch( tmp_path: Path, snapshots: tuple[DesignSnapshot, DesignSnapshot], verification, rule: MappingRule, target_fingerprint: str, ) -> None: # Catches certification that binds a verification result to a different representative project. before, after = snapshots mismatched = CertificationStore( tmp_path / "certifications.json", before=before, after=replace(after, project_id="other-project"), verification=verification, ) with pytest.raises(CertificationError, match="hard_verification_failed"): mismatched.record( rule, target_fingerprint, None, ExternalChecks(packager=True, erc=True, netlist=True), ) def test_interface_fingerprint_rejects_invalid_snapshot_and_blank_gate( snapshots: tuple[DesignSnapshot, DesignSnapshot], ) -> None: # Catches interface hashes created from a non-snapshot value or an empty normalized gate identity. _, after = snapshots with pytest.raises(CertificationError, match="invalid_snapshot"): interface_fingerprint(object(), ("/MAIN|U1",)) # type: ignore[arg-type] blank_gate = replace(after, components=(replace(after.components[0], units=(replace(after.components[0].units[0], unit_id=" "),)),)) with pytest.raises(CertificationError, match="invalid_interface"): interface_fingerprint(blank_gate, ("/MAIN|U1",)) def test_record_rejects_invalid_mapping_target_library_and_evidence( tmp_path: Path, snapshots: tuple[DesignSnapshot, DesignSnapshot], verification, rule: MappingRule, target_fingerprint: str, ) -> None: # Catches durable certificates with missing identities or malformed evidence paths. before, after = snapshots store = CertificationStore( tmp_path / "certifications.json", before=before, after=after, verification=verification, evidence_paths=("",), ) checks = ExternalChecks(packager=True, erc=True, netlist=True) with pytest.raises(CertificationError, match="invalid_mapping_rule"): store.record(MappingRule("", "NEW-1"), target_fingerprint, None, checks) with pytest.raises(CertificationError, match="invalid_target_fingerprint"): store.record(rule, "", None, checks) with pytest.raises(CertificationError, match="invalid_library_identity"): store.record(rule, target_fingerprint, "", checks) with pytest.raises(CertificationError, match="invalid_evidence_paths"): store.record(rule, target_fingerprint, None, checks) def test_certification_rejects_verification_forged_for_different_snapshots( tmp_path: Path, snapshots: tuple[DesignSnapshot, DesignSnapshot], verification, rule: MappingRule, ) -> None: # Catches a passing result from a different snapshot pair minting a certificate. before, after = snapshots altered_after = replace( after, components=( replace( after.components[0], units=( replace( after.components[0].units[0], pins=(replace(after.components[0].units[0].pins[0], net="OTHER-NET"), after.components[0].units[0].pins[1]), ), ), ), ), ) store = CertificationStore( tmp_path / "certifications.json", before=before, after=altered_after, verification=verification, evidence_paths=("trial.txt",), ) with pytest.raises(CertificationError, match="hard_verification_failed"): store.record( rule, interface_fingerprint(altered_after, ("/MAIN|U1",)), None, ExternalChecks(packager=True, erc=True, netlist=True), ) def test_certification_rejects_trial_with_empty_pin_observations( tmp_path: Path, snapshots: tuple[DesignSnapshot, DesignSnapshot], rule: MappingRule, ) -> None: # Catches certification when the trial has no observed pins for an expected unit. before, after = snapshots empty_before = replace(before, components=(replace(before.components[0], units=(replace(before.components[0].units[0], pins=()),)),)) empty_after = replace(after, components=(replace(after.components[0], units=(replace(after.components[0].units[0], pins=()),)),)) store = CertificationStore( tmp_path / "certifications.json", before=empty_before, after=empty_after, verification=verify_replacement(empty_before, empty_after, rule, ("/MAIN|U1",)), evidence_paths=("trial.txt",), ) with pytest.raises(CertificationError, match="invalid_interface"): interface_fingerprint(empty_after, ("/MAIN|U1",)) with pytest.raises(CertificationError, match="trial_data_incomplete"): store.record( rule, "unusable-target-interface", None, ExternalChecks(packager=True, erc=True, netlist=True), ) def test_certification_rejects_trial_with_missing_network_identity( tmp_path: Path, snapshots: tuple[DesignSnapshot, DesignSnapshot], rule: MappingRule, ) -> None: # Catches certification when an expected pin lacks a network identity despite matching snapshots. before, after = snapshots no_net_before = replace( before, components=(replace(before.components[0], units=(replace(before.components[0].units[0], pins=(replace(before.components[0].units[0].pins[0], net=None), before.components[0].units[0].pins[1])),)),), ) no_net_after = replace( after, components=(replace(after.components[0], units=(replace(after.components[0].units[0], pins=(replace(after.components[0].units[0].pins[0], net=None), after.components[0].units[0].pins[1])),)),), ) store = CertificationStore( tmp_path / "certifications.json", before=no_net_before, after=no_net_after, verification=verify_replacement(no_net_before, no_net_after, rule, ("/MAIN|U1",)), evidence_paths=("trial.txt",), ) with pytest.raises(CertificationError, match="trial_data_incomplete"): store.record( rule, interface_fingerprint(no_net_after, ("/MAIN|U1",)), None, ExternalChecks(packager=True, erc=True, netlist=True), ) def test_certification_requires_nonempty_evidence_paths( tmp_path: Path, snapshots: tuple[DesignSnapshot, DesignSnapshot], verification, rule: MappingRule, target_fingerprint: str, ) -> None: # Catches record creation that treats an empty evidence-path collection as proof. before, after = snapshots store = CertificationStore( tmp_path / "certifications.json", before=before, after=after, verification=verification, ) with pytest.raises(CertificationError, match="invalid_evidence_paths"): store.record( rule, target_fingerprint, None, ExternalChecks(packager=True, erc=True, netlist=True), ) @pytest.mark.parametrize("evidence_paths", ([], "trial.txt", {"path": "trial.txt"})) def test_corrupt_certification_with_invalid_evidence_paths_blocks_apply( tmp_path: Path, store: CertificationStore, certification, evidence_paths: object, ) -> None: # Catches Apply lookup that converts a non-array JSON evidence value into false proof. path = tmp_path / "certifications.json" document = json.loads(path.read_text(encoding="utf-8")) document["certifications"][0]["evidence_paths"] = evidence_paths path.write_text(json.dumps(document), encoding="utf-8") with pytest.raises(CertificationError, match="corrupt_certification"): store.require( certification.rule, certification.target_fingerprint, certification.library_identity, )