Initial import of DxDesigner part replacement tool (r21)

This commit is contained in:
阿白叔 committed 2026-09-29 15:42:21 +08:00
commit ffe066cb1e
151 files changed
+58745

No files matched your search

+637
View File
@@ -0,0 +1,637 @@
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,
)
File diff suppressed because it is too large. Load diff
+69
View File
@@ -0,0 +1,69 @@
from __future__ import annotations
from copy import deepcopy
import pytest
from dx_productivity.part_replace.command_schema import command_data, command_from_data
from dx_productivity.part_replace.controller import ControllerError
from dx_productivity.part_replace.models import Scope
from dx_productivity.part_replace.protocol import BridgeCommand
def _command_document() -> dict[str, object]:
return {
"action": "replace_part",
"command_id": "a" * 32,
"expected_count": 2,
"expected_fingerprint": "f" * 64,
"expected_logical_keys": ["/MAIN|R1", "/MAIN|R2"],
"format_version": 1,
"job_id": "job-1",
"new_part_number": "NEW-1",
"old_part_number": "OLD-1",
"project_id": "project-1",
"scope": "full_project",
}
def test_command_codec_round_trips_the_exact_durable_schema() -> None:
expected = _command_document()
command = BridgeCommand(
format_version=1,
command_id="a" * 32,
action="replace_part",
job_id="job-1",
project_id="project-1",
scope=Scope.FULL_PROJECT,
old_part_number="OLD-1",
new_part_number="NEW-1",
expected_logical_keys=("/MAIN|R1", "/MAIN|R2"),
expected_count=2,
expected_fingerprint="f" * 64,
)
assert command_data(command) == expected
assert command_from_data(expected) == command
@pytest.mark.parametrize(
("field", "value", "message"),
(
("unexpected", 1, "fields"),
("format_version", True, "values"),
("scope", "selection", "scope"),
("command_id", "G" * 32, "values"),
),
)
def test_command_codec_rejects_noncanonical_durable_documents(
field: str,
value: object,
message: str,
) -> None:
document = deepcopy(_command_document())
document[field] = value
with pytest.raises(ControllerError, match=message) as captured:
command_from_data(document)
assert captured.value.code == "corrupt_publication"
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+189
View File
@@ -0,0 +1,189 @@
import hashlib
import os
from pathlib import Path
import pytest
from dx_productivity.part_replace.inputs import (
InputError,
discover_projects,
load_mapping,
load_projects,
)
from dx_productivity.part_replace.models import MappingRule, ProjectRef
def write(path: Path, text: str, *, encoding: str = "utf-8") -> Path:
path.write_text(text, encoding=encoding)
return path
def test_load_mapping_rejects_case_duplicate_chain_and_cycle(tmp_path: Path) -> None:
duplicate = write(tmp_path / "duplicate.csv", "old_part_number,new_part_number\nA,B\na,C\n")
with pytest.raises(InputError, match="duplicate_source"):
load_mapping(duplicate)
chain = write(tmp_path / "chain.csv", "old_part_number,new_part_number\nA,B\nB,C\n")
with pytest.raises(InputError, match="mapping_chain"):
load_mapping(chain)
cycle = write(tmp_path / "cycle.csv", "old_part_number,new_part_number\nA,B\nB,A\n")
with pytest.raises(InputError, match="mapping_cycle"):
load_mapping(cycle)
def test_load_mapping_accepts_utf8_bom_and_preserves_spelling(tmp_path: Path) -> None:
path = tmp_path / "替换.csv"
path.write_text(
"old_part_number,new_part_number\n old-01 , New-01 \n",
encoding="utf-8-sig",
)
assert load_mapping(path) == (MappingRule("old-01", "New-01"),)
def test_load_mapping_requires_exact_two_column_header_and_nonblank_values(tmp_path: Path) -> None:
for name, contents, code in (
(
"missing.csv",
"old_part_number\nA\n",
"mapping_header",
),
(
"extra.csv",
"old_part_number,new_part_number,comment\nA,B,note\n",
"mapping_header",
),
(
"blank.csv",
"old_part_number,new_part_number\n ,B\n",
"blank_part_number",
),
):
with pytest.raises(InputError, match=code):
load_mapping(write(tmp_path / name, contents))
def test_load_mapping_accepts_named_columns_in_either_order_but_rejects_extra_row_values(
tmp_path: Path,
) -> None:
reversed_header = write(
tmp_path / "reversed.csv",
"new_part_number,old_part_number\nB,A\n",
)
assert load_mapping(reversed_header) == (MappingRule("A", "B"),)
extra_value = write(
tmp_path / "extra-value.csv",
"old_part_number,new_part_number\nA,B,unexpected\n",
)
with pytest.raises(InputError, match="mapping_columns"):
load_mapping(extra_value)
def test_load_mapping_rejects_case_insensitive_equal_rule_before_graph_checks(tmp_path: Path) -> None:
path = write(tmp_path / "equal.csv", "old_part_number,new_part_number\n Part-A , part-a \n")
with pytest.raises(InputError, match="equal_rule"):
load_mapping(path)
def test_load_mapping_reports_chain_for_graph_larger_than_recursion_limit(tmp_path: Path) -> None:
rows = ["old_part_number,new_part_number"]
rows.extend(f"P{index},P{index + 1}" for index in range(1_200))
path = write(tmp_path / "long-chain.csv", "\n".join(rows) + "\n")
with pytest.raises(InputError, match="mapping_chain"):
load_mapping(path)
def test_load_mapping_reports_cycle_for_graph_larger_than_recursion_limit(tmp_path: Path) -> None:
rows = ["old_part_number,new_part_number"]
rows.extend(f"P{index},P{index + 1}" for index in range(1_199))
rows.append("P1199,P1")
path = write(tmp_path / "long-cycle.csv", "\n".join(rows) + "\n")
with pytest.raises(InputError, match="mapping_cycle"):
load_mapping(path)
def test_load_projects_ignores_comments_and_builds_stable_refs(tmp_path: Path) -> None:
project = tmp_path / "设计.PRJ"
project.write_text("project definition", encoding="utf-8")
list_path = write(
tmp_path / "projects.txt",
f"\n# operator comment\n {project} \n",
)
canonical = project.resolve()
normalized = os.path.normcase(str(canonical))
expected_id = hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:16]
assert load_projects(list_path, (".prj",)) == (
ProjectRef(expected_id, str(canonical), "设计"),
)
def test_load_projects_rejects_relative_missing_directory_suffix_and_duplicate(tmp_path: Path) -> None:
project = tmp_path / "one.prj"
project.write_text("project definition", encoding="utf-8")
(tmp_path / "one.txt").write_text("not a project", encoding="utf-8")
cases = (
("relative.prj\n", "project_path_not_absolute"),
(f"{tmp_path / 'missing.prj'}\n", "project_not_found"),
(f"{tmp_path}\n", "project_not_file"),
(f"{tmp_path / 'one.txt'}\n", "unsupported_project_suffix"),
)
for contents, code in cases:
with pytest.raises(InputError, match=code):
load_projects(write(tmp_path / f"{code}.txt", contents), (".prj",))
duplicate_list = write(tmp_path / "duplicates.txt", f"{project}\n{project.resolve()}\n")
with pytest.raises(InputError, match="duplicate_project"):
load_projects(duplicate_list, (".prj",))
def test_load_projects_accepts_suffix_case_insensitively_and_resolves_paths(tmp_path: Path) -> None:
project = tmp_path / "sub" / "Board.PrJ"
project.parent.mkdir()
project.write_text("project definition", encoding="utf-8")
listed = tmp_path / "projects.txt"
write(listed, f"{project}\n")
result = load_projects(listed, (".PRJ",))
assert result[0].project_path == str(project.resolve())
assert result[0].display_name == "Board"
@pytest.mark.parametrize("nested", (False, True), ids=("same-root", "nested-root"))
def test_load_projects_rejects_overlapping_project_ownership_roots(
tmp_path: Path,
nested: bool,
) -> None:
# Catches one project's backup or restore tree containing another project marker.
first_root = tmp_path / "projects" / "first"
second_root = first_root / "nested" if nested else first_root
second_root.mkdir(parents=True)
first = first_root / "first.prj"
second = second_root / "second.prj"
first.write_text("first\n", encoding="utf-8")
second.write_text("second\n", encoding="utf-8")
projects = tmp_path / "projects.txt"
projects.write_text(f"{first.resolve()}\n{second.resolve()}\n", encoding="utf-8")
with pytest.raises(InputError, match="overlapping_project_roots"):
load_projects(projects, (".prj",))
def test_discover_projects_returns_sorted_unique_canonical_candidates_without_writing(tmp_path: Path) -> None:
root = tmp_path / "设计"
(root / "z").mkdir(parents=True)
(root / "a").mkdir()
first = root / "z" / "B.PRJ"
second = root / "a" / "a.prj"
ignored = root / "a" / "notes.txt"
first.write_text("project", encoding="utf-8")
second.write_text("project", encoding="utf-8")
ignored.write_text("ignored", encoding="utf-8")
discovered = discover_projects(root, (".prj",))
expected = tuple(sorted((first.resolve(), second.resolve()), key=lambda path: str(path).casefold()))
assert discovered == expected
assert not (root / "projects.txt").exists()
+75
View File
@@ -0,0 +1,75 @@
from dataclasses import FrozenInstanceError
from decimal import Decimal
import pytest
from dx_productivity.part_replace.models import (
ComponentSnapshot,
DesignSnapshot,
Issue,
MappingRule,
PinSnapshot,
ProjectState,
Scope,
UnitSnapshot,
)
def test_snapshot_model_is_immutable_and_decimal_exact() -> None:
pin = PinSnapshot(number="1", name="A", x=Decimal("10.25"), y=Decimal("20"), net="N$1")
unit = UnitSnapshot(
unit_id="u1", sheet="/MAIN", symbol="res.1",
origin_x=Decimal("0"), origin_y=Decimal("0"), x=Decimal("0"),
y=Decimal("0"), rotation=0, mirrored=False, pins=(pin,),
)
component = ComponentSnapshot(logical_key="/MAIN|R1", refdes="R1",
part_number="OLD-1", units=(unit,), attributes=())
snapshot = DesignSnapshot(format_version=2, project_id="p1", project_path="C:/P/a.prj",
fingerprint="abc", components=(component,))
with pytest.raises(FrozenInstanceError):
snapshot.project_id = "p2" # type: ignore[misc]
assert snapshot.components[0].units[0].pins[0].x == Decimal("10.25")
def test_unit_keeps_origin_coordinates_distinct_from_position() -> None:
# Catches collapsing the symbol origin into the placed x/y coordinates.
unit = UnitSnapshot(
unit_id="u1",
sheet="/MAIN",
symbol="res.1",
origin_x=Decimal("1.25"),
origin_y=Decimal("2.5"),
x=Decimal("100"),
y=Decimal("200"),
rotation=0,
mirrored=False,
)
assert (unit.origin_x, unit.origin_y, unit.x, unit.y) == (
Decimal("1.25"),
Decimal("2.5"),
Decimal("100"),
Decimal("200"),
)
def test_state_and_scope_values_are_protocol_stable() -> None:
assert Scope.FULL_PROJECT.value == "full_project"
assert ProjectState.AWAITING_SAVE_CONFIRMATION.value == "awaiting_save_confirmation"
assert MappingRule("OLD", "NEW").old_part_number == "OLD"
def test_nested_records_are_normalized_to_immutable_sorted_tuples() -> None:
snapshot = ComponentSnapshot(
logical_key="k", refdes="R1", part_number="P",
units=[], attributes={"z": "2", "a": "1"},
)
assert snapshot.units == ()
assert snapshot.attributes == (("a", "1"), ("z", "2"))
def test_issue_details_do_not_retain_mutable_inner_entries() -> None:
issue = Issue("bad", "blocking", "Invalid data", [["field", "value"]]) # type: ignore[arg-type]
assert issue.details == (("field", "value"),)
with pytest.raises(TypeError):
issue.details[0][0] = "changed" # type: ignore[index]
+356
View File
@@ -0,0 +1,356 @@
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"))
+191
View File
@@ -0,0 +1,191 @@
from __future__ import annotations
from pathlib import Path
from dx_productivity.part_replace.certification import Certification
from dx_productivity.part_replace.models import (
ExternalChecks,
ImpactCell,
Issue,
MappingRule,
ProjectState,
VerificationResult,
)
from dx_productivity.part_replace.reports import (
BatchReport,
write_differences_json,
write_impact_csv,
write_summary_html,
)
RULE = MappingRule("OLD-1", "NEW-1")
def _report(*states: ProjectState, old_part_number: str = "OLD-1") -> BatchReport:
rule = MappingRule(old_part_number, "NEW-1")
result = VerificationResult(
project_id="project-a",
rule=rule,
expected_logical_keys=("/MAIN|R1",),
changed_logical_keys=("/MAIN|R1",),
issues=(
Issue("connectivity_changed", "error", "Pin 1 net changed"),
Issue("library_attribute_changed", "info", "Value updated"),
),
passed=False,
)
return BatchReport(
job_id="job-42",
generated_time="2026-09-02T01:02:03Z",
input_hashes={"job.json": "abc123", "events.jsonl": "def456"},
project_states={f"project-{index}": state for index, state in enumerate(states, start=1)},
impact_cells=(ImpactCell("project-a", rule, 1, 2),),
verification_results=(result,),
external_checks={"project-a": ExternalChecks(packager=True, erc=None, netlist=False)},
certifications=(
Certification(
created_utc="2026-09-01T00:00:00Z",
dxdesigner_build="7.9.5",
rule=rule,
target_fingerprint="target-fingerprint",
library_identity="library-r42",
representative_project_fingerprint="trial-fingerprint",
evidence_paths=("before.json", "after.json"),
),
),
backup_path="C:/Backups/job-42",
resume_action="Reconcile blocked projects before continuing.",
advisory_attachments=("ai-review.json",),
)
def test_html_report_escapes_part_numbers_and_has_no_remote_content(tmp_path: Path) -> None:
# Catches direct interpolation that lets a part number create executable or remote HTML.
output = tmp_path / "report.html"
write_summary_html(output, _report(ProjectState.BLOCKED, old_part_number='<script src="https://x">'))
text = output.read_text(encoding="utf-8")
assert "&lt;script" in text
assert "https://x" not in text
assert "<script" not in text.casefold()
def test_partial_batch_never_renders_as_success(tmp_path: Path) -> None:
# Catches summary status derived from one verified project while another project is blocked.
output = tmp_path / "report.html"
write_summary_html(output, _report(ProjectState.VERIFIED_SAVED, ProjectState.BLOCKED))
text = output.read_text(encoding="utf-8")
assert "PARTIAL" in text
assert "BATCH STATUS: SUCCESS" not in text
def test_ai_review_artifact_cannot_change_verified_state(tmp_path: Path) -> None:
# Catches an advisory file being treated as approval that overrides event-derived project state.
report = _report(ProjectState.BLOCKED)
(tmp_path / "ai-review.json").write_text('{"recommendation":"approve"}', encoding="utf-8")
output = tmp_path / "report.html"
write_summary_html(output, report)
text = output.read_text(encoding="utf-8")
assert "BLOCKED" in text
assert "Advisory attachments" in text
def test_html_summary_shows_required_operator_evidence(tmp_path: Path) -> None:
# Catches a summary that omits evidence an operator needs to audit or resume a batch.
output = tmp_path / "report.html"
write_summary_html(output, _report(ProjectState.BLOCKED))
text = output.read_text(encoding="utf-8")
for value in (
"job-42",
"2026-09-02T01:02:03Z",
"abc123",
"project-1",
"OLD-1",
"connectivity_changed",
"library_attribute_changed",
"packager: PASS",
"target-fingerprint",
"C:/Backups/job-42",
"Reconcile blocked projects before continuing.",
):
assert value in text
def test_html_summary_includes_escaped_hard_impact_issue_with_mapping_context(tmp_path: Path) -> None:
# Catches hard inventory or mapping findings being omitted when no verification result carries an error.
output = tmp_path / "report.html"
rule = MappingRule(" OLD-IMPACT ", " NEW-IMPACT ")
report = BatchReport(
job_id="job-impact",
generated_time="2026-09-02T01:02:03Z",
project_states={"project-impact": ProjectState.BLOCKED},
impact_cells=(
ImpactCell(
"project-impact",
rule,
0,
0,
(Issue("inventory_identity_ambiguous", "error", "Ambiguous <inventory> identity"),),
),
),
)
write_summary_html(output, report)
hard_issues = output.read_text(encoding="utf-8").split("<h2>Hard issues</h2>", 1)[1].split(
"<h2>Nonblocking attribute differences</h2>", 1
)[0]
assert "project-impact" in hard_issues
assert " OLD-IMPACT " in hard_issues
assert " NEW-IMPACT " in hard_issues
assert "inventory_identity_ambiguous" in hard_issues
assert "Ambiguous &lt;inventory&gt; identity" in hard_issues
def test_impact_csv_keeps_original_part_number_spelling_and_counts(tmp_path: Path) -> None:
# Catches report formatting that normalizes a user-supplied mapping identity or drops unit counts.
output = tmp_path / "impact.csv"
cells = (
ImpactCell("project-z", MappingRule(" old-1 ", " NEW-1 "), 2, 3),
)
write_impact_csv(output, cells)
assert output.read_text(encoding="utf-8") == (
"project_id,old_part_number,new_part_number,logical_count,unit_count,issues\n"
"project-z, old-1 , NEW-1 ,2,3,\n"
)
def test_differences_json_is_canonical_and_separates_hard_and_nonblocking_issues(tmp_path: Path) -> None:
# Catches noncanonical report JSON or a severity filter that hides informational attribute differences.
output = tmp_path / "differences.json"
result = VerificationResult(
project_id="project-a",
rule=RULE,
expected_logical_keys=("/MAIN|R1",),
changed_logical_keys=("/MAIN|R1",),
issues=(
Issue("library_attribute_changed", "info", "Value updated", (("attribute", "value"),)),
Issue("connectivity_changed", "error", "Pin 1 net changed"),
),
passed=False,
)
write_differences_json(output, (result,))
assert output.read_text(encoding="utf-8") == (
'{"results":[{"changed_logical_keys":["/MAIN|R1"],"expected_logical_keys":["/MAIN|R1"],"hard_issues"'
':[{"code":"connectivity_changed","details":{},"message":"Pin 1 net changed","severity":"error"}]'
',"new_part_number":"NEW-1","nonblocking_differences"'
':[{"code":"library_attribute_changed","details":{"attribute":"value"},"message":"Value updated","severity":"info"}]'
',"old_part_number":"OLD-1","passed":false,"project_id":"project-a"}]}\n'
)
+972
View File
@@ -0,0 +1,972 @@
from __future__ import annotations
from dataclasses import replace
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import time
import pytest
from dx_productivity.part_replace.models import MappingRule, ProjectRef, ProjectState
from dx_productivity.part_replace.run_store import (
BackupError,
RunStore,
StateError,
backup_project,
fingerprint_tree,
restore_project,
verify_tree,
)
import dx_productivity.part_replace.run_store as run_store_module
@pytest.fixture
def project(tmp_path: Path) -> Path:
root = tmp_path / "工程"
(root / "design" / "空").mkdir(parents=True)
(root / "design" / "main.sch").write_bytes(b"schematic")
(root / "readme.txt").write_text("unicode: 工程\n", encoding="utf-8")
return root
@pytest.fixture
def run_store(tmp_path: Path, project: Path) -> RunStore:
return RunStore.create(
tmp_path / "run",
(MappingRule("OLD-1", "NEW-1"),),
(ProjectRef("p1", str(project), "工程"),),
)
def _advance_to_verified(store: RunStore) -> None:
for state in (
ProjectState.INVENTORY_COMPLETE,
ProjectState.APPLY_PENDING,
ProjectState.APPLYING,
ProjectState.AWAITING_SAVE_CONFIRMATION,
ProjectState.AWAITING_EXTERNAL_CHECKS,
ProjectState.VERIFIED_SAVED,
):
store.transition("p1", state)
def _make_changed_project_and_backup(tmp_path: Path) -> tuple[Path, Path, object]:
project = tmp_path / "project"
project.mkdir()
(project / "main.sch").write_bytes(b"original")
backup = tmp_path / "backup"
manifest = backup_project(project, backup)
(project / "main.sch").write_bytes(b"failed change")
(project / "new.tmp").write_bytes(b"new")
return project, backup, manifest
def test_invalid_state_transition_is_rejected(run_store: RunStore) -> None:
with pytest.raises(StateError, match="invalid_transition"):
run_store.transition("p1", ProjectState.VERIFIED_SAVED)
def test_valid_transitions_replay_and_verified_saved_is_terminal(
run_store: RunStore,
) -> None:
_advance_to_verified(run_store)
reopened = RunStore(run_store.root)
assert reopened.project_state("p1") is ProjectState.VERIFIED_SAVED
with pytest.raises(StateError, match="invalid_transition"):
reopened.transition("p1", ProjectState.BLOCKED)
def test_blocked_requires_explicit_durable_reconcile_event(
run_store: RunStore,
) -> None:
run_store.transition("p1", ProjectState.BLOCKED)
with pytest.raises(StateError, match="reconcile_required"):
run_store.transition("p1", ProjectState.INVENTORY_PENDING)
run_store.append_event("p1", "reconcile", {"reason": "operator_review"})
assert RunStore(run_store.root).project_state("p1") is ProjectState.INVENTORY_PENDING
def test_no_changes_required_is_a_durable_direct_completion_event(run_store: RunStore) -> None:
# Catches no-op projects being forced through fake Apply/save/check transitions or left pending.
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
run_store.complete_no_changes("p1")
assert run_store.project_state("p1") is ProjectState.VERIFIED_SAVED
assert RunStore(run_store.root).project_state("p1") is ProjectState.VERIFIED_SAVED
record = json.loads((run_store.root / "events.jsonl").read_text(encoding="utf-8").splitlines()[-1])
assert record["event"] == "no_changes_required"
assert record["payload"] == {}
assert record["prior_state"] == "inventory_complete"
assert record["target_state"] == "verified_saved"
def test_no_changes_required_rejects_non_inventory_complete_and_reserved_spoofing(run_store: RunStore) -> None:
# Catches the special no-op event bypassing inventory/impact review.
with pytest.raises(StateError, match="invalid_transition"):
run_store.complete_no_changes("p1")
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
for payload in ({}, {"unexpected": True}):
with pytest.raises(StateError, match="invalid_event"):
run_store.append_event("p1", "no_changes_required", payload)
@pytest.mark.parametrize(
("field", "value"),
(
("prior_state", "apply_pending"),
("target_state", "apply_pending"),
("payload", {"unexpected": True}),
),
)
def test_replay_rejects_invalid_no_change_event_shape(
run_store: RunStore,
field: str,
value: object,
) -> None:
# Catches tampered no-op events replaying from the wrong state, target, or payload.
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
run_store.complete_no_changes("p1")
event_path = run_store.root / "events.jsonl"
records = [json.loads(line) for line in event_path.read_text(encoding="utf-8").splitlines()]
records[-1][field] = value
event_path.write_text(
"".join(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n" for record in records),
encoding="utf-8",
)
with pytest.raises(StateError, match="corrupt_event_log"):
RunStore(run_store.root)
def test_events_are_canonical_contiguous_jsonl_with_utc_timestamps(
run_store: RunStore,
) -> None:
run_store.append_event("p1", "inventory_observed", {"fingerprint": "雪"})
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
lines = (run_store.root / "events.jsonl").read_text(encoding="utf-8").splitlines()
records = [json.loads(line) for line in lines]
assert [record["sequence"] for record in records] == [1, 2]
assert records[0]["prior_state"] == records[0]["target_state"] == "inventory_pending"
assert records[1]["prior_state"] == "inventory_pending"
assert records[1]["target_state"] == "inventory_complete"
assert all(record["timestamp_utc"].endswith("Z") for record in records)
assert all(
line == json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
for line, record in zip(lines, records, strict=True)
)
def test_events_returns_only_records_revalidated_under_the_run_lock(
run_store: RunStore,
) -> None:
# Catches event consumers reading bytes without canonical, sequence, and state replay checks.
run_store.append_event("p1", "operator_note", {"value": "checked"})
records = run_store.events("p1")
assert [record["event"] for record in records] == ["operator_note"]
path = run_store.root / "events.jsonl"
record = json.loads(path.read_text(encoding="utf-8"))
path.write_text(json.dumps(record, separators=(", ", ": ")) + "\n", encoding="utf-8")
with pytest.raises(StateError, match="corrupt_event_log"):
run_store.events()
def test_create_persists_immutable_job_inputs_and_rejects_unknown_project(
run_store: RunStore,
) -> None:
job = json.loads((run_store.root / "job.json").read_text(encoding="utf-8"))
assert job["rules"] == [{"new_part_number": "NEW-1", "old_part_number": "OLD-1"}]
assert job["projects"][0]["project_path"] == str(Path(job["projects"][0]["project_path"]).resolve())
with pytest.raises(StateError, match="unknown_project"):
run_store.project_state("not-recorded")
@pytest.mark.parametrize(
"corrupt_line",
[
"not-json",
'{"event":"transition"}',
'{"event":"transition","payload":{},"prior_state":"inventory_pending",'
'"project_id":"p1","sequence":2,"target_state":"inventory_complete",'
'"timestamp_utc":"2026-09-01T00:00:00Z"}',
],
)
def test_open_fails_closed_on_malformed_or_noncontiguous_event_log(
run_store: RunStore, corrupt_line: str
) -> None:
(run_store.root / "events.jsonl").write_text(corrupt_line + "\n", encoding="utf-8")
with pytest.raises(StateError, match="corrupt_event_log"):
RunStore(run_store.root)
def test_replay_rejects_semantically_impossible_event(run_store: RunStore) -> None:
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
event_path = run_store.root / "events.jsonl"
record = json.loads(event_path.read_text(encoding="utf-8"))
record["prior_state"] = "applying"
event_path.write_text(
json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n",
encoding="utf-8",
)
with pytest.raises(StateError, match="corrupt_event_log"):
RunStore(run_store.root)
def test_replay_rejects_noncanonical_json_event(run_store: RunStore) -> None:
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
event_path = run_store.root / "events.jsonl"
record = json.loads(event_path.read_text(encoding="utf-8"))
event_path.write_text(json.dumps(record, ensure_ascii=False) + "\n", encoding="utf-8")
with pytest.raises(StateError, match="corrupt_event_log"):
RunStore(run_store.root)
@pytest.mark.parametrize("line_ending", [b"", b"\r\n"])
def test_replay_rejects_missing_lf_or_crlf(
run_store: RunStore, line_ending: bytes
) -> None:
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
event_path = run_store.root / "events.jsonl"
content = event_path.read_bytes().removesuffix(b"\n") + line_ending
event_path.write_bytes(content)
with pytest.raises(StateError, match="corrupt_event_log"):
RunStore(run_store.root)
def test_replay_preserves_unicode_json_separators(run_store: RunStore) -> None:
separators = "before\u0085middle\u2028line\u2029after"
run_store.append_event("p1", "unicode_payload", {"value": separators})
reopened = RunStore(run_store.root)
assert reopened.project_state("p1") is ProjectState.INVENTORY_PENDING
assert separators in (run_store.root / "events.jsonl").read_text(encoding="utf-8")
def test_replay_rejects_float_sequence(run_store: RunStore) -> None:
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
event_path = run_store.root / "events.jsonl"
record = json.loads(event_path.read_text(encoding="utf-8"))
record["sequence"] = 1.0
event_path.write_text(
json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n",
encoding="utf-8",
)
with pytest.raises(StateError, match="corrupt_event_log"):
RunStore(run_store.root)
@pytest.mark.parametrize("metadata_name", ["job.json", "events.jsonl"])
def test_run_store_rejects_metadata_file_symlinks_when_available(
run_store: RunStore, tmp_path: Path, metadata_name: str
) -> None:
metadata = run_store.root / metadata_name
outside = tmp_path / f"outside-{metadata_name}"
outside.write_bytes(metadata.read_bytes())
metadata.unlink()
try:
metadata.symlink_to(outside)
except OSError as error:
pytest.skip(f"symbolic links unavailable: {error}")
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore(run_store.root)
@pytest.mark.skipif(os.name != "nt", reason="Windows reparse-point coverage")
@pytest.mark.parametrize("metadata_name", ["job.json", "events.jsonl"])
def test_run_store_rejects_metadata_junctions(
run_store: RunStore, tmp_path: Path, metadata_name: str
) -> None:
metadata = run_store.root / metadata_name
metadata.unlink()
outside = tmp_path / f"outside-{metadata_name}"
outside.mkdir()
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(metadata), str(outside)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.fail(f"junction creation failed: {created.stderr or created.stdout}")
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore(run_store.root)
finally:
metadata.rmdir()
@pytest.mark.parametrize("metadata_name", ["job.json", "events.jsonl"])
def test_run_store_rejects_metadata_replaced_between_lstat_and_open(
run_store: RunStore, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, metadata_name: str
) -> None:
metadata = run_store.root / metadata_name
replacement = tmp_path / f"replacement-{metadata_name}"
replacement.write_bytes(metadata.read_bytes())
real_open = os.open
replaced = False
def replace_before_open(path: object, flags: int, mode: int = 0o777) -> int:
nonlocal replaced
if Path(path) == metadata and not replaced:
replaced = True
os.replace(replacement, metadata)
return real_open(path, flags, mode)
monkeypatch.setattr(run_store_module.os, "open", replace_before_open)
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore(run_store.root)
def test_run_store_rejects_metadata_hard_link(run_store: RunStore, tmp_path: Path) -> None:
metadata = run_store.root / "job.json"
outside = tmp_path / "outside-job.json"
outside.write_bytes(metadata.read_bytes())
metadata.unlink()
os.link(outside, metadata)
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore(run_store.root)
@pytest.mark.skipif(os.name != "nt", reason="Windows handle-containment coverage")
def test_open_rejects_junction_inserted_before_run_root_resolution(
run_store: RunStore, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
logical_root = run_store.root
displaced_root = tmp_path / "displaced-open-run"
outside_root = tmp_path / "outside-open-run"
shutil.copytree(logical_root, outside_root)
real_resolve = Path.resolve
swapped = False
def swap_before_resolution(path: Path, strict: bool = False) -> Path:
nonlocal swapped
if path == logical_root and not swapped:
os.rename(logical_root, displaced_root)
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(logical_root), str(outside_root)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.fail(f"junction creation failed: {created.stderr or created.stdout}")
swapped = True
return real_resolve(path, strict=strict)
monkeypatch.setattr(Path, "resolve", swap_before_resolution)
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore(logical_root)
finally:
if swapped:
logical_root.rmdir()
os.rename(displaced_root, logical_root)
@pytest.mark.skipif(os.name != "nt", reason="Windows handle-containment coverage")
def test_create_rejects_junction_inserted_before_parent_resolution(
tmp_path: Path, project: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
logical_parent = tmp_path / "create-container"
logical_parent.mkdir()
logical_root = logical_parent / "run"
displaced_parent = tmp_path / "displaced-create-container"
outside_parent = tmp_path / "outside-create-parent"
outside_parent.mkdir()
real_resolve = Path.resolve
swapped = False
def swap_before_resolution(path: Path, strict: bool = False) -> Path:
nonlocal swapped
if path == logical_parent and not swapped:
os.rename(logical_parent, displaced_parent)
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(logical_parent), str(outside_parent)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.fail(f"junction creation failed: {created.stderr or created.stdout}")
swapped = True
return real_resolve(path, strict=strict)
monkeypatch.setattr(Path, "resolve", swap_before_resolution)
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore.create(
logical_root,
(MappingRule("OLD-1", "NEW-1"),),
(ProjectRef("p1", str(project), "project"),),
)
assert not (outside_parent / "run").exists()
finally:
if swapped:
logical_parent.rmdir()
os.rename(displaced_parent, logical_parent)
@pytest.mark.skipif(os.name != "nt", reason="Windows handle-containment coverage")
@pytest.mark.parametrize("swap_level", ["root", "parent"])
def test_event_append_rejects_root_component_swap_before_leaf_lstat(
tmp_path: Path, project: Path, monkeypatch: pytest.MonkeyPatch, swap_level: str
) -> None:
container = tmp_path / "container"
container.mkdir()
store = RunStore.create(
container / "run",
(MappingRule("OLD-1", "NEW-1"),),
(ProjectRef("p1", str(project), "project"),),
)
logical_root = store.root
logical_event = logical_root / "events.jsonl"
displaced = tmp_path / f"displaced-{swap_level}"
outside_component = tmp_path / f"outside-{swap_level}"
if swap_level == "root":
shutil.copytree(logical_root, outside_component)
swap_path = logical_root
else:
outside_component.mkdir()
shutil.copytree(logical_root, outside_component / "run")
swap_path = container
real_lstat = Path.lstat
swapped = False
def swap_before_leaf_lstat(path: Path):
nonlocal swapped
if path == logical_event and not swapped:
swapped = True
os.rename(swap_path, displaced)
os.rename(outside_component, swap_path)
return real_lstat(path)
monkeypatch.setattr(Path, "lstat", swap_before_leaf_lstat)
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
store.append_event("p1", "must_not_escape", {})
current_external_event = (
logical_root / "events.jsonl"
if swap_level == "root"
else container / "run" / "events.jsonl"
)
assert current_external_event.read_bytes() == b""
finally:
if swapped:
quarantine = tmp_path / f"quarantine-{swap_level}"
if swap_path.exists() and not quarantine.exists():
os.rename(swap_path, quarantine)
if displaced.exists():
os.rename(displaced, swap_path)
@pytest.mark.skipif(os.name != "nt", reason="Windows handle-containment coverage")
def test_job_open_validates_root_relationship_before_read(
run_store: RunStore, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
logical_root = run_store.root
logical_job = logical_root / "job.json"
displaced = tmp_path / "displaced-job-run"
outside_root = tmp_path / "outside-job-run"
shutil.copytree(logical_root, outside_root)
real_lstat = Path.lstat
real_read = os.read
swapped = False
def swap_before_leaf_lstat(path: Path):
nonlocal swapped
if path == logical_job and not swapped:
swapped = True
os.rename(logical_root, displaced)
os.rename(outside_root, logical_root)
return real_lstat(path)
def reject_external_read(descriptor: int, size: int) -> bytes:
if swapped:
raise AssertionError("external job was read before containment validation")
return real_read(descriptor, size)
monkeypatch.setattr(Path, "lstat", swap_before_leaf_lstat)
monkeypatch.setattr(run_store_module.os, "read", reject_external_read)
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore(logical_root)
finally:
if swapped:
os.rename(logical_root, outside_root)
os.rename(displaced, logical_root)
def test_two_processes_append_with_contiguous_sequences(run_store: RunStore, tmp_path: Path) -> None:
ready = tmp_path / "first-writer-ready"
delayed_writer = r"""
from pathlib import Path
import sys
import time
from dx_productivity.part_replace.run_store import RunStore
import dx_productivity.part_replace.run_store as module
root = Path(sys.argv[1])
ready = Path(sys.argv[2])
real_write = module.os.write
def delayed_write(descriptor, data):
if b'\"sequence\":1' in data:
ready.write_text('ready', encoding='utf-8')
time.sleep(1.0)
return real_write(descriptor, data)
module.os.write = delayed_write
RunStore(root).append_event('p1', 'writer_a', {})
"""
ordinary_writer = r"""
from pathlib import Path
import sys
from dx_productivity.part_replace.run_store import RunStore
RunStore(Path(sys.argv[1])).append_event('p1', 'writer_b', {})
"""
first = subprocess.Popen(
[sys.executable, "-c", delayed_writer, str(run_store.root), str(ready)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
deadline = time.monotonic() + 10
while not ready.exists() and first.poll() is None and time.monotonic() < deadline:
time.sleep(0.01)
assert ready.exists(), first.communicate(timeout=1)
second = subprocess.run(
[sys.executable, "-c", ordinary_writer, str(run_store.root)],
check=False,
capture_output=True,
text=True,
timeout=15,
)
first_stdout, first_stderr = first.communicate(timeout=15)
assert first.returncode == 0, (first_stdout, first_stderr)
assert second.returncode == 0, (second.stdout, second.stderr)
records = [
json.loads(line)
for line in (run_store.root / "events.jsonl").read_text(encoding="utf-8").split("\n")
if line
]
assert [record["sequence"] for record in records] == [1, 2]
assert RunStore(run_store.root).project_state("p1") is ProjectState.INVENTORY_PENDING
def test_persistent_lock_file_does_not_cause_stale_lockout(run_store: RunStore) -> None:
assert (run_store.root / ".run.lock").exists()
RunStore(run_store.root).append_event("p1", "after_reopen", {})
assert RunStore(run_store.root).project_state("p1") is ProjectState.INVENTORY_PENDING
@pytest.mark.skipif(os.name != "nt", reason="Windows reparse-point coverage")
def test_run_store_rejects_reparse_lock_file(run_store: RunStore, tmp_path: Path) -> None:
lock_path = run_store.root / ".run.lock"
lock_path.unlink()
outside = tmp_path / "outside-lock"
outside.mkdir()
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(lock_path), str(outside)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.fail(f"junction creation failed: {created.stderr or created.stdout}")
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore(run_store.root)
finally:
lock_path.rmdir()
@pytest.mark.skipif(os.name != "nt", reason="Windows reparse-point coverage")
def test_existing_store_rejects_run_root_replaced_by_junction(
run_store: RunStore, tmp_path: Path
) -> None:
original_root = run_store.root
displaced = tmp_path / "displaced-run"
os.rename(original_root, displaced)
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(original_root), str(displaced)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
os.rename(displaced, original_root)
pytest.fail(f"junction creation failed: {created.stderr or created.stdout}")
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
run_store.append_event("p1", "must_not_escape", {})
finally:
original_root.rmdir()
os.rename(displaced, original_root)
def test_backup_is_complete_and_manifest_detects_change(
tmp_path: Path, project: Path
) -> None:
backup = tmp_path / "backup"
manifest = backup_project(project, backup)
assert manifest.project_root == str(project.resolve())
assert [entry.path for entry in manifest.files] == ["design/main.sch", "readme.txt"]
assert verify_tree(backup, manifest)
assert (backup / "design" / "空").is_dir()
(backup / "design" / "main.sch").write_bytes(b"changed")
assert not verify_tree(backup, manifest)
def test_tree_manifest_detects_added_and_removed_files(project: Path) -> None:
manifest = fingerprint_tree(project)
(project / "extra.bin").write_bytes(b"extra")
assert not verify_tree(project, manifest)
(project / "extra.bin").unlink()
(project / "readme.txt").unlink()
assert not verify_tree(project, manifest)
@pytest.mark.parametrize("operation", ["fingerprint", "backup"])
def test_tree_walk_fails_closed_on_traversal_error(
tmp_path: Path,
project: Path,
monkeypatch: pytest.MonkeyPatch,
operation: str,
) -> None:
denied = project / "design"
real_scandir = os.scandir
def fail_design_scan(path: object):
if Path(path) == denied:
raise PermissionError("injected traversal denial")
return real_scandir(path)
monkeypatch.setattr(run_store_module.os, "scandir", fail_design_scan)
with pytest.raises(BackupError, match="tree_scan_failed"):
if operation == "fingerprint":
fingerprint_tree(project)
else:
backup_project(project, tmp_path / "backup")
assert not (tmp_path / "backup").exists()
def test_backup_rejects_existing_or_nested_destination(
tmp_path: Path, project: Path
) -> None:
existing = tmp_path / "existing"
existing.mkdir()
with pytest.raises(BackupError, match="destination_exists"):
backup_project(project, existing)
with pytest.raises(BackupError, match="destination_inside_source"):
backup_project(project, project / "backup")
def test_tree_operations_reject_symbolic_links(tmp_path: Path, project: Path) -> None:
outside = tmp_path / "outside.txt"
outside.write_bytes(b"outside")
link = project / "linked.txt"
try:
link.symlink_to(outside)
except OSError as error:
pytest.skip(f"symbolic links unavailable: {error}")
with pytest.raises(BackupError, match="unsupported_link"):
fingerprint_tree(project)
with pytest.raises(BackupError, match="unsupported_link"):
backup_project(project, tmp_path / "backup")
@pytest.mark.skipif(os.name != "nt", reason="Windows reparse-point coverage")
def test_tree_operations_reject_windows_junctions(tmp_path: Path, project: Path) -> None:
outside = tmp_path / "outside"
outside.mkdir()
junction = project / "junction"
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(junction), str(outside)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.skip(f"junctions unavailable: {created.stderr or created.stdout}")
try:
with pytest.raises(BackupError, match="unsupported_link"):
fingerprint_tree(project)
finally:
junction.rmdir()
def test_restore_requires_closed_project_and_preserves_failed_tree(tmp_path: Path) -> None:
project, backup, manifest = _make_changed_project_and_backup(tmp_path)
recovery = tmp_path / "recovery"
with pytest.raises(BackupError, match="project_must_be_closed"):
restore_project(project, backup, recovery, manifest, closed_confirmed=False)
failed_manifest = restore_project(
project, backup, recovery, manifest, closed_confirmed=True
)
assert verify_tree(project, manifest)
assert verify_tree(recovery, failed_manifest)
assert (recovery / "main.sch").read_bytes() == b"failed change"
assert verify_tree(backup, manifest)
def test_restore_requires_explicit_boolean_confirmation(tmp_path: Path) -> None:
project, backup, manifest = _make_changed_project_and_backup(tmp_path)
with pytest.raises(BackupError, match="project_must_be_closed"):
restore_project(project, backup, tmp_path / "recovery", manifest, closed_confirmed=1) # type: ignore[arg-type]
def test_restore_revalidates_displaced_tree_before_publication(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
project, backup, manifest = _make_changed_project_and_backup(tmp_path)
recovery = tmp_path / "recovery"
real_rename = os.rename
def mutate_after_displacement(source: object, destination: object) -> None:
source_path = Path(source)
destination_path = Path(destination)
real_rename(source, destination)
if source_path == project and destination_path.name.startswith(f".{project.name}.original-"):
(destination_path / "main.sch").write_bytes(b"mutated-after-recovery")
monkeypatch.setattr(run_store_module.os, "rename", mutate_after_displacement)
with pytest.raises(BackupError, match="failed_tree_changed"):
restore_project(project, backup, recovery, manifest, True)
assert (project / "main.sch").read_bytes() == b"mutated-after-recovery"
assert (recovery / "main.sch").read_bytes() == b"failed change"
assert any(tmp_path.glob(f".{project.name}.restore-*"))
assert verify_tree(backup, manifest)
def test_restore_rejects_wrong_recorded_target_and_unverified_backup(
tmp_path: Path,
) -> None:
project, backup, manifest = _make_changed_project_and_backup(tmp_path)
other = tmp_path / "other"
other.mkdir()
(other / "main.sch").write_bytes(b"original")
with pytest.raises(BackupError, match="target_mismatch"):
restore_project(other, backup, tmp_path / "recovery-wrong", manifest, True)
(backup / "main.sch").write_bytes(b"corrupt")
with pytest.raises(BackupError, match="backup_verification_failed"):
restore_project(project, backup, tmp_path / "recovery-corrupt", manifest, True)
assert (project / "main.sch").read_bytes() == b"failed change"
def test_restore_requires_distinct_nonexisting_recovery_destination(
tmp_path: Path,
) -> None:
project, backup, manifest = _make_changed_project_and_backup(tmp_path)
existing = tmp_path / "recovery"
existing.mkdir()
with pytest.raises(BackupError, match="recovery_exists"):
restore_project(project, backup, existing, manifest, True)
with pytest.raises(BackupError, match="recovery_inside_source"):
restore_project(project, backup, project / "recovery", manifest, True)
def test_restore_publication_failure_leaves_original_and_staging_recoverable(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
project, backup, manifest = _make_changed_project_and_backup(tmp_path)
recovery = tmp_path / "recovery"
real_rename = os.rename
def fail_restore_publication(source: object, destination: object) -> None:
source_path = Path(source)
destination_path = Path(destination)
if source_path.name.startswith(f".{project.name}.restore-") and destination_path == project:
raise OSError("injected publication failure")
real_rename(source, destination)
monkeypatch.setattr("dx_productivity.part_replace.run_store.os.rename", fail_restore_publication)
with pytest.raises(BackupError, match="restore_publication_failed"):
restore_project(project, backup, recovery, manifest, True)
assert (project / "main.sch").read_bytes() == b"failed change"
assert verify_tree(recovery, fingerprint_tree(project))
assert any(tmp_path.glob(f".{project.name}.restore-*"))
assert verify_tree(backup, manifest)
def test_restore_does_not_overwrite_destination_created_during_publication(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
project, backup, manifest = _make_changed_project_and_backup(tmp_path)
real_rename = os.rename
def create_racing_destination(source: object, destination: object) -> None:
source_path = Path(source)
destination_path = Path(destination)
if source_path == project and destination_path.name.startswith(f".{project.name}.original-"):
real_rename(source, destination)
project.mkdir()
(project / "racing-owner.txt").write_text("do not overwrite", encoding="utf-8")
return
if source_path.name.startswith(f".{project.name}.restore-") and destination_path == project:
shutil.rmtree(project)
real_rename(source, destination)
monkeypatch.setattr("dx_productivity.part_replace.run_store.os.rename", create_racing_destination)
with pytest.raises(BackupError, match="destination_exists"):
restore_project(project, backup, tmp_path / "recovery", manifest, True)
assert (project / "racing-owner.txt").read_text(encoding="utf-8") == "do not overwrite"
@pytest.mark.skipif(os.name != "nt", reason="Windows no-replace rename behavior")
def test_backup_publication_does_not_replace_racing_destination(
tmp_path: Path, project: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
backup = tmp_path / "backup"
real_rename = os.rename
def create_destination_before_rename(source: object, destination: object) -> None:
destination_path = Path(destination)
if destination_path == backup:
backup.mkdir()
(backup / "owner.txt").write_text("racing owner", encoding="utf-8")
real_rename(source, destination)
monkeypatch.setattr(run_store_module.os, "rename", create_destination_before_rename)
with pytest.raises(BackupError, match="backup_publication_failed"):
backup_project(project, backup)
assert (backup / "owner.txt").read_text(encoding="utf-8") == "racing owner"
def test_destructive_tree_operations_fail_closed_off_windows(
tmp_path: Path, project: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
backup = tmp_path / "existing-backup"
manifest = backup_project(project, backup)
(project / "readme.txt").write_text("failed", encoding="utf-8")
monkeypatch.setattr(
run_store_module, "_WINDOWS_DESTRUCTIVE_OPERATIONS", False, raising=False
)
with pytest.raises(BackupError, match="unsupported_platform"):
backup_project(project, tmp_path / "new-backup")
with pytest.raises(BackupError, match="unsupported_platform"):
restore_project(project, backup, tmp_path / "recovery", manifest, True)
assert not (tmp_path / "new-backup").exists()
assert not (tmp_path / "recovery").exists()
assert (project / "readme.txt").read_text(encoding="utf-8") == "failed"
def test_run_store_create_and_open_fail_closed_off_windows(
tmp_path: Path, project: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
existing = RunStore.create(
tmp_path / "existing-run",
(MappingRule("OLD-1", "NEW-1"),),
(ProjectRef("p1", str(project), "project"),),
)
metadata_before = {
name: (existing.root / name).read_bytes()
for name in ("job.json", "events.jsonl", ".run.lock")
}
unsupported_root = tmp_path / "unsupported-run"
monkeypatch.setattr(run_store_module, "_WINDOWS_DESTRUCTIVE_OPERATIONS", False)
with pytest.raises(StateError, match="unsupported_platform"):
RunStore.create(
unsupported_root,
(MappingRule("OLD-1", "NEW-1"),),
(ProjectRef("p1", str(project), "project"),),
)
with pytest.raises(StateError, match="unsupported_platform"):
RunStore(existing.root)
assert not unsupported_root.exists()
assert {
name: (existing.root / name).read_bytes()
for name in ("job.json", "events.jsonl", ".run.lock")
} == metadata_before
@pytest.mark.skipif(os.name != "nt", reason="Windows handle-containment coverage")
def test_run_store_create_validates_root_before_writing_job(
tmp_path: Path, project: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
logical_root = tmp_path / "new-run"
displaced = tmp_path / "displaced-new-run"
outside_root = tmp_path / "outside-new-run"
outside_root.mkdir()
outside_job = outside_root / "job.json"
outside_job.write_bytes(b"")
real_open = os.open
swapped = False
def swap_root() -> None:
nonlocal swapped
if not swapped:
swapped = True
os.rename(logical_root, displaced)
os.rename(outside_root, logical_root)
def swap_before_descriptor_open(path: object, flags: int, mode: int = 0o777) -> int:
if Path(path).name == "job.json":
swap_root()
return real_open(path, flags, mode)
monkeypatch.setattr(run_store_module.os, "open", swap_before_descriptor_open)
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore.create(
logical_root,
(MappingRule("OLD-1", "NEW-1"),),
(ProjectRef("p1", str(project), "project"),),
)
assert (logical_root / "job.json").read_bytes() == b""
finally:
if swapped:
quarantine = tmp_path / "quarantine-new-run"
os.rename(logical_root, quarantine)
os.rename(displaced, logical_root)
def test_manifest_is_immutable(project: Path) -> None:
manifest = fingerprint_tree(project)
with pytest.raises((AttributeError, TypeError)):
manifest.files = () # type: ignore[misc]
with pytest.raises((AttributeError, TypeError)):
replace(manifest.files[0], size=0).sha256 = "changed" # type: ignore[misc]
+382
View File
@@ -0,0 +1,382 @@
from __future__ import annotations
from dataclasses import dataclass, replace
from decimal import Decimal
import pytest
from dx_productivity.part_replace.models import (
ComponentSnapshot,
DesignSnapshot,
MappingRule,
PinSnapshot,
UnitSnapshot,
)
from dx_productivity.part_replace.verification import (
build_impact_matrix,
eligible_logical_keys,
verify_replacement,
)
@dataclass(frozen=True)
class ReplacementFixtures:
before: DesignSnapshot
compatible: DesignSnapshot
def _component(
logical_key: str,
refdes: str,
part_number: str,
*,
units: tuple[UnitSnapshot, ...] | None = None,
attributes: tuple[tuple[str, str], ...] = (),
) -> ComponentSnapshot:
return ComponentSnapshot(
logical_key=logical_key,
refdes=refdes,
part_number=part_number,
units=units if units is not None else (_unit("A"),),
attributes=attributes,
)
def _unit(unit_id: str, *, x: Decimal = Decimal("0"), pins: tuple[PinSnapshot, ...] | None = None) -> UnitSnapshot:
return UnitSnapshot(
unit_id=unit_id,
sheet="/MAIN",
symbol="SOURCE_SYMBOL",
origin_x=x - Decimal("0.5"),
origin_y=Decimal("3.5"),
x=x,
y=Decimal("4"),
rotation=90,
mirrored=False,
pins=pins if pins is not None else (
PinSnapshot("1", "A", Decimal("10"), Decimal("20"), "N$1"),
PinSnapshot("2", "B", Decimal("11"), Decimal("20"), "N$2"),
),
)
@pytest.fixture
def fixtures() -> ReplacementFixtures:
replacement = _component(
"/MAIN|R1", "R1", " old-1 ", attributes=(("tolerance", "1%"),),
)
unrelated = _component("/MAIN|C1", "C1", "KEEP-1", attributes=(("value", "1u"),))
before = DesignSnapshot(2, "project-1", "C:/Projects/board.prj", "before", (replacement, unrelated))
compatible = replace(
before,
fingerprint="after",
components=(
replace(
replacement,
part_number=" New-1 ",
units=(replace(replacement.units[0], symbol="LIBRARY_SYMBOL"),),
attributes=(("tolerance", "5%"), ("library", "central")),
),
unrelated,
),
)
return ReplacementFixtures(before, compatible)
def _replacement(after: DesignSnapshot) -> ComponentSnapshot:
return after.components[0]
def _replace_replacement(after: DesignSnapshot, component: ComponentSnapshot) -> DesignSnapshot:
return replace(after, components=(component, after.components[1]))
def change_refdes(after: DesignSnapshot) -> DesignSnapshot:
return _replace_replacement(after, replace(_replacement(after), refdes="R99"))
def move_origin(after: DesignSnapshot) -> DesignSnapshot:
component = _replacement(after)
return _replace_replacement(after, replace(component, units=(replace(component.units[0], x=Decimal("0.1")),)))
def change_origin_only(after: DesignSnapshot) -> DesignSnapshot:
component = _replacement(after)
unit = component.units[0]
assert hasattr(unit, "origin_x")
return _replace_replacement(
after,
replace(component, units=(replace(unit, origin_x=Decimal("7.125")),)),
)
def remove_pin(after: DesignSnapshot) -> DesignSnapshot:
component = _replacement(after)
return _replace_replacement(after, replace(component, units=(replace(component.units[0], pins=component.units[0].pins[:1]),)))
def move_pin(after: DesignSnapshot) -> DesignSnapshot:
component = _replacement(after)
pin = component.units[0].pins[0]
return _replace_replacement(
after,
replace(component, units=(replace(component.units[0], pins=(replace(pin, x=Decimal("10.1")), component.units[0].pins[1])),)),
)
def change_net(after: DesignSnapshot) -> DesignSnapshot:
component = _replacement(after)
pin = component.units[0].pins[0]
return _replace_replacement(
after,
replace(component, units=(replace(component.units[0], pins=(replace(pin, net="N$2"), component.units[0].pins[1])),)),
)
def change_unrelated_part(after: DesignSnapshot) -> DesignSnapshot:
return replace(after, components=(after.components[0], replace(after.components[1], part_number="CHANGED")))
def select_wrong_target(after: DesignSnapshot) -> DesignSnapshot:
return _replace_replacement(after, replace(_replacement(after), part_number="WRONG-1"))
def test_compatible_replacement_preserves_every_hard_invariant(fixtures: ReplacementFixtures) -> None:
result = verify_replacement(fixtures.before, fixtures.compatible, MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",))
assert result.passed
assert [(issue.code, issue.severity) for issue in result.issues] == [
("library_symbol_changed", "info"),
("library_attribute_changed", "info"),
]
assert result.changed_logical_keys == ("/MAIN|R1",)
def test_library_controlled_symbol_pin_names_and_attributes_are_reported_without_blocking(fixtures: ReplacementFixtures) -> None:
component = _replacement(fixtures.compatible)
library_wins = _replace_replacement(
fixtures.compatible,
replace(
component,
attributes=(("library", "central"),),
units=(
replace(
component.units[0],
symbol="ANOTHER_LIBRARY_SYMBOL",
pins=(replace(component.units[0].pins[0], name="LIBRARY_A"), component.units[0].pins[1]),
),
),
),
)
result = verify_replacement(fixtures.before, library_wins, MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",))
assert result.passed
assert [(issue.code, issue.severity) for issue in result.issues] == [
("library_symbol_changed", "info"),
("library_pin_name_changed", "info"),
("library_attribute_changed", "info"),
]
def test_unrelated_symbol_and_attribute_changes_remain_blocking(fixtures: ReplacementFixtures) -> None:
unrelated = fixtures.compatible.components[1]
changed_unrelated = replace(
unrelated,
attributes=(("value", "47u"),),
units=(replace(unrelated.units[0], symbol="OTHER_SYMBOL"),),
)
after = replace(fixtures.compatible, components=(fixtures.compatible.components[0], changed_unrelated))
result = verify_replacement(fixtures.before, after, MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",))
assert not result.passed
assert ("unrelated_component_changed", "error") in [(issue.code, issue.severity) for issue in result.issues]
@pytest.mark.parametrize("mutator,code", [
(change_refdes, "refdes_changed"),
(move_origin, "placement_changed"),
(change_origin_only, "origin_changed"),
(remove_pin, "pin_set_changed"),
(move_pin, "pin_position_changed"),
(change_net, "connectivity_changed"),
(change_unrelated_part, "unrelated_component_changed"),
(select_wrong_target, "wrong_target_part_number"),
])
def test_verification_blocks_unsafe_change(fixtures: ReplacementFixtures, mutator, code: str) -> None:
result = verify_replacement(fixtures.before, mutator(fixtures.compatible), MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",))
assert not result.passed
assert code in {issue.code for issue in result.issues}
def test_impact_matrix_uses_trimmed_casefold_matching_and_snapshot_rule_order(fixtures: ReplacementFixtures) -> None:
second = replace(fixtures.before, project_id="project-2", components=(
_component("/MAIN|R2", "R2", "old-1", units=(_unit("A"), _unit("B"))),
))
rules = (MappingRule(" keep-1 ", "KEEP-2"), MappingRule("OLD-1", "NEW-1"))
matrix = build_impact_matrix((fixtures.before, second), rules)
assert [(cell.project_id, cell.rule.old_part_number, cell.logical_count, cell.unit_count) for cell in matrix] == [
("project-1", " keep-1 ", 1, 1),
("project-1", "OLD-1", 1, 1),
("project-2", " keep-1 ", 0, 0),
("project-2", "OLD-1", 1, 2),
]
assert eligible_logical_keys(fixtures.before, MappingRule(" OLD-1", "NEW-1")) == ("/MAIN|R1",)
@pytest.mark.parametrize(
("mutator", "expected_code"),
(
(lambda component: replace(component, units=()), "missing_units"),
(
lambda component: replace(
component,
units=(replace(component.units[0], pins=()),),
),
"missing_pins",
),
(
lambda component: replace(
component,
units=(
replace(
component.units[0],
pins=(replace(component.units[0].pins[0], net=None), component.units[0].pins[1]),
),
),
),
"missing_network_identity",
),
),
)
def test_matched_component_missing_evidence_blocks_impact_and_hard_verification(
fixtures: ReplacementFixtures,
mutator,
expected_code: str,
) -> None:
# Catches equality-only checks that accept equally incomplete before/after snapshots.
before_component = mutator(fixtures.before.components[0])
after_component = mutator(fixtures.compatible.components[0])
before = replace(fixtures.before, components=(before_component, fixtures.before.components[1]))
after = replace(fixtures.compatible, components=(after_component, fixtures.compatible.components[1]))
rule = MappingRule("OLD-1", "NEW-1")
impact = build_impact_matrix((before,), (rule,))[0]
result = verify_replacement(before, after, rule, ("/MAIN|R1",))
assert impact.logical_count == 1
assert expected_code in {issue.code for issue in impact.issues}
assert not result.passed
assert expected_code in {issue.code for issue in result.issues}
def test_coordinate_tolerance_allows_exact_boundary_but_blocks_larger_difference(fixtures: ReplacementFixtures) -> None:
component = _replacement(fixtures.compatible)
pin = component.units[0].pins[0]
at_boundary = _replace_replacement(
fixtures.compatible,
replace(component, units=(replace(component.units[0], pins=(replace(pin, x=Decimal("10.000001")), component.units[0].pins[1])),)),
)
beyond_boundary = _replace_replacement(
fixtures.compatible,
replace(component, units=(replace(component.units[0], pins=(replace(pin, x=Decimal("10.0000011")), component.units[0].pins[1])),)),
)
assert verify_replacement(fixtures.before, at_boundary, MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",)).passed
result = verify_replacement(fixtures.before, beyond_boundary, MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",))
assert "pin_position_changed" in {issue.code for issue in result.issues}
@pytest.mark.parametrize(
("mutator", "code"),
[
(lambda before, after: (replace(after, project_id="other"), "project_id_changed"), "project_id_changed"),
(lambda before, after: (replace(after, project_path="C:/Other/board.prj"), "project_path_changed"), "project_path_changed"),
(lambda before, after: (replace(after, components=after.components[:1]), "component_removed"), "component_removed"),
(lambda before, after: (replace(after, components=after.components + (_component("/MAIN|L1", "L1", "KEEP"),)), "component_added"), "component_added"),
(lambda before, after: (after, "expected_logical_key_missing"), "expected_logical_key_missing"),
],
)
def test_verification_blocks_project_and_component_identity_changes(fixtures: ReplacementFixtures, mutator, code: str) -> None:
after, expected_code = mutator(fixtures.before, fixtures.compatible)
expected_keys = ("/MAIN|R1",) if expected_code != "expected_logical_key_missing" else ("/MAIN|MISSING",)
result = verify_replacement(fixtures.before, after, MappingRule("OLD-1", "NEW-1"), expected_keys)
assert code in {issue.code for issue in result.issues}
assert not result.passed
def test_multi_unit_replacement_requires_the_same_gate_slot_set(fixtures: ReplacementFixtures) -> None:
units = (_unit("A"), _unit("B", x=Decimal("30")))
before_component = _component("/MAIN|U1", "U1", "OLD-1", units=units)
before = replace(fixtures.before, components=(before_component, fixtures.before.components[1]))
after = replace(before, components=(replace(before_component, part_number="NEW-1"), before.components[1]))
incompatible = replace(after, components=(replace(after.components[0], units=(after.components[0].units[0], _unit("C", x=Decimal("30")))), after.components[1]))
assert verify_replacement(before, after, MappingRule("OLD-1", "NEW-1"), ("/MAIN|U1",)).passed
result = verify_replacement(before, incompatible, MappingRule("OLD-1", "NEW-1"), ("/MAIN|U1",))
assert "unit_set_changed" in {issue.code for issue in result.issues}
def test_expected_key_must_have_the_rule_source_part_number(fixtures: ReplacementFixtures) -> None:
wrong_before = _replace_replacement(fixtures.before, replace(fixtures.before.components[0], part_number="OTHER"))
result = verify_replacement(wrong_before, fixtures.compatible, MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",))
assert "source_part_number_mismatch" in {issue.code for issue in result.issues}
assert not result.passed
def test_verification_fails_closed_for_duplicate_direct_snapshot_identities(fixtures: ReplacementFixtures) -> None:
duplicate_component = replace(fixtures.before.components[0], refdes="R2")
duplicate_unit = replace(fixtures.before.components[0].units[0], unit_id="A")
duplicate_pin = replace(fixtures.before.components[0].units[0].pins[0], name="Alternative")
malformed = replace(
fixtures.compatible,
components=(
replace(fixtures.compatible.components[0], units=(duplicate_unit, duplicate_unit)),
fixtures.compatible.components[1],
duplicate_component,
),
)
malformed = replace(
malformed,
components=(
replace(
malformed.components[0],
units=(
replace(duplicate_unit, pins=(duplicate_pin, duplicate_pin)),
duplicate_unit,
),
),
malformed.components[1],
malformed.components[2],
),
)
result = verify_replacement(fixtures.before, malformed, MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",))
assert {"duplicate_logical_key", "duplicate_unit_id", "duplicate_pin_number"} <= {issue.code for issue in result.issues}
assert not result.passed
def test_duplicate_normalized_refdes_is_ineligible_and_blocks_verification(fixtures: ReplacementFixtures) -> None:
duplicate_refdes_before = replace(fixtures.before.components[1], refdes=" r1 ", part_number="OLD-1")
before = replace(fixtures.before, components=(fixtures.before.components[0], duplicate_refdes_before))
after = replace(
fixtures.compatible,
components=(
fixtures.compatible.components[0],
replace(duplicate_refdes_before, part_number="NEW-1"),
),
)
rule = MappingRule("OLD-1", "NEW-1")
assert eligible_logical_keys(before, rule) == ()
result = verify_replacement(before, after, rule, ("/MAIN|R1", "/MAIN|C1"))
assert not result.passed
assert ("duplicate_refdes", "error") in [(issue.code, issue.severity) for issue in result.issues]