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

+975
View File
@@ -0,0 +1,975 @@
from __future__ import annotations
from contextlib import redirect_stdout
from dataclasses import dataclass, replace
from decimal import Decimal
from io import StringIO
import json
from pathlib import Path
from typing import Any
from dx_productivity.part_replace.certification import CertificationStore, interface_fingerprint
from dx_productivity.part_replace.cli import main as cli_main
from dx_productivity.part_replace.controller import BatchController
from dx_productivity.part_replace.models import (
ComponentSnapshot,
DesignSnapshot,
ExternalChecks,
MappingRule,
PinSnapshot,
ProjectRef,
ProjectState,
Scope,
UnitSnapshot,
)
from dx_productivity.part_replace.protocol import (
BridgeCommand,
atomic_write_text,
load_snapshot,
load_status,
snapshot_fingerprint,
write_snapshot,
)
from dx_productivity.part_replace.run_store import TreeFile, TreeManifest, verify_tree
from dx_productivity.part_replace.verification import eligible_logical_keys, verify_replacement
RULE = MappingRule("OLD-1", "NEW-1")
LIBRARY_IDENTITY = "lib-r42"
_COMMAND_FIELDS = {
"action",
"command_id",
"expected_count",
"expected_fingerprint",
"expected_logical_keys",
"format_version",
"job_id",
"new_part_number",
"old_part_number",
"project_id",
"scope",
}
class BridgeStatusEvidenceError(ValueError):
"""The operator could not correlate durable bridge status evidence."""
def _pin_coordinates(
origin_x: Decimal,
origin_y: Decimal,
rotation: int,
mirrored: bool,
local_x: Decimal,
local_y: Decimal,
) -> tuple[Decimal, Decimal]:
transformed_x = -local_x if mirrored else local_x
transformed_y = local_y
if rotation == 0:
delta_x, delta_y = transformed_x, transformed_y
elif rotation == 90:
delta_x, delta_y = -transformed_y, transformed_x
elif rotation == 180:
delta_x, delta_y = -transformed_x, -transformed_y
elif rotation == 270:
delta_x, delta_y = transformed_y, -transformed_x
else: # pragma: no cover - fixtures use only DxDesigner quarter turns
raise ValueError(f"unsupported fixture rotation: {rotation}")
return origin_x + delta_x, origin_y + delta_y
def _component(
index: int,
part_number: str,
*,
rotation: int = 0,
mirrored: bool = False,
) -> ComponentSnapshot:
origin_x = Decimal(index * 10)
origin_y = Decimal(index * 20)
symbol_origin_x, symbol_origin_y = _pin_coordinates(
origin_x,
origin_y,
rotation,
mirrored,
Decimal("-0.5"),
Decimal("-0.5"),
)
pins = []
for number, name, local_x, local_y, net in (
("1", "IN", Decimal("0.25"), Decimal("0"), f"N{index}-IN"),
("2", "OUT", Decimal("0.50"), Decimal("0"), f"N{index}-OUT"),
):
x, y = _pin_coordinates(origin_x, origin_y, rotation, mirrored, local_x, local_y)
pins.append(PinSnapshot(number, name, x, y, net))
return ComponentSnapshot(
logical_key=f"/MAIN|U{index}",
refdes=f"U{index}",
part_number=part_number,
attributes=(("manufacturer", "Acme"),),
units=(
UnitSnapshot(
unit_id="A",
sheet="/MAIN",
symbol="LIB:NEW" if part_number != RULE.old_part_number else "LIB:OLD",
origin_x=symbol_origin_x,
origin_y=symbol_origin_y,
x=origin_x,
y=origin_y,
rotation=rotation,
mirrored=mirrored,
pins=tuple(pins),
),
),
)
def _fingerprinted(snapshot: DesignSnapshot) -> DesignSnapshot:
return replace(snapshot, fingerprint=snapshot_fingerprint(snapshot))
def _snapshot(project_id: str, marker: Path, part_number: str, count: int) -> DesignSnapshot:
placements = ((0, False), (90, True), (270, False))
snapshot = DesignSnapshot(
format_version=2,
project_id=project_id,
project_path=str(marker.resolve()),
fingerprint="pending",
components=(_component(0, "KEEP-1"),)
+ tuple(
_component(
index,
part_number,
rotation=placements[index - 1][0],
mirrored=placements[index - 1][1],
)
for index in range(1, count + 1)
),
)
return _fingerprinted(snapshot)
def _json_object(path: Path) -> dict[str, Any]:
def reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
result: dict[str, Any] = {}
for key, value in pairs:
if key in result:
raise AssertionError(f"published command repeats {key!r}")
result[key] = value
return result
data = json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=reject_duplicates)
assert isinstance(data, dict)
return data
def _load_command(path: Path) -> BridgeCommand:
data = _json_object(path)
assert set(data) == _COMMAND_FIELDS
return BridgeCommand(
format_version=data["format_version"],
command_id=data["command_id"],
action=data["action"],
job_id=data["job_id"],
project_id=data["project_id"],
scope=Scope(data["scope"]),
old_part_number=data["old_part_number"],
new_part_number=data["new_part_number"],
expected_logical_keys=tuple(data["expected_logical_keys"]),
expected_count=data["expected_count"],
expected_fingerprint=data["expected_fingerprint"],
)
def _invoke_cli(*arguments: str) -> tuple[int, dict[str, Any]]:
output = StringIO()
with redirect_stdout(output):
exit_code = cli_main(["--json", *arguments])
payload = json.loads(output.getvalue())
assert isinstance(payload, dict)
return exit_code, payload
@dataclass(frozen=True, slots=True)
class JobInputs:
mapping: Path
projects: Path
certifications: Path
markers: dict[str, Path]
@classmethod
def create(cls, root: Path) -> JobInputs:
root.mkdir(parents=True)
markers: dict[str, Path] = {}
for name in ("p1", "p2"):
project_root = root / "projects" / name
project_root.mkdir(parents=True)
marker = project_root / f"{name}.prj"
marker.write_text(f"DxDesigner project {name}\n", encoding="utf-8")
(project_root / "design.sch").write_text("native design: OLD-1\n", encoding="utf-8")
markers[name] = marker
mapping = root / "mapping.csv"
mapping.write_text(
"old_part_number,new_part_number\nOLD-1,NEW-1\n",
encoding="utf-8",
)
projects = root / "projects.txt"
projects.write_text(
"".join(f"{markers[name].resolve()}\n" for name in ("p1", "p2")),
encoding="utf-8",
)
certifications = root / "certifications.json"
cls._record_certification(root, certifications)
return cls(mapping, projects, certifications, markers)
@staticmethod
def _record_certification(root: Path, certifications: Path) -> None:
trial_root = root / "trial"
trial_root.mkdir()
marker = trial_root / "trial.prj"
marker.write_text("representative trial\n", encoding="utf-8")
before = _snapshot("trial", marker, RULE.old_part_number, 1)
after = _snapshot("trial", marker, RULE.new_part_number, 1)
before_path = trial_root / "before.json"
after_path = trial_root / "after.json"
write_snapshot(before_path, before)
write_snapshot(after_path, after)
evidence_paths = [before_path, after_path]
for name in ("packager", "erc", "netlist"):
path = trial_root / f"{name}.txt"
path.write_text("PASS\n", encoding="utf-8")
evidence_paths.append(path)
expected_keys = ("/MAIN|U1",)
verification = verify_replacement(before, after, RULE, expected_keys)
CertificationStore(
certifications,
before=before,
after=after,
verification=verification,
evidence_paths=tuple(str(path.resolve()) for path in evidence_paths),
).record(
RULE,
interface_fingerprint(after, expected_keys),
LIBRARY_IDENTITY,
ExternalChecks(True, True, True),
)
class MockDxDesigner:
def __init__(
self,
run_dir: Path,
project: ProjectRef,
marker: Path,
hit_count: int,
job_id: str,
) -> None:
self.run_dir = Path(run_dir)
self.project = project
self.marker = Path(marker)
self.hit_count = hit_count
self.job_id = job_id
self.mailbox = self.run_dir / "mailbox" / project.project_id
self.mailbox.mkdir(parents=True, exist_ok=True)
self.current_snapshot = self.mailbox / "inventory.json"
self.persisted_snapshot = self.mailbox / "persisted.json"
self.native_project = self.marker.parent / "design.sch"
self._current = _snapshot(project.project_id, self.marker, RULE.old_part_number, hit_count)
write_snapshot(self.native_project, self._current)
self._before_apply: DesignSnapshot | None = None
self._active_command: BridgeCommand | None = None
self._apply_command: BridgeCommand | None = None
self.is_open = True
self.saved = False
self.apply_groups: list[tuple[str, str, int]] = []
@classmethod
def resume(cls, run_dir: Path, project: ProjectRef, hit_count: int, job_id: str) -> MockDxDesigner:
instance = cls.__new__(cls)
instance.run_dir = Path(run_dir)
instance.project = project
instance.marker = Path(project.project_path)
instance.hit_count = hit_count
instance.job_id = job_id
instance.mailbox = instance.run_dir / "mailbox" / project.project_id
instance.current_snapshot = instance.mailbox / "inventory.json"
instance.persisted_snapshot = instance.mailbox / "persisted.json"
instance.native_project = instance.marker.parent / "design.sch"
available = next(
path
for path in (
instance.persisted_snapshot,
instance.mailbox / "snapshot.json",
instance.current_snapshot,
instance.native_project,
)
if path.exists()
)
instance._current = load_snapshot(available)
instance._before_apply = None
command_path = instance.mailbox / "command.json"
instance._active_command = _load_command(command_path) if command_path.exists() else None
instance._apply_command = (
instance._active_command
if instance._active_command is not None
and instance._active_command.action == "replace_part"
else None
)
instance.is_open = True
instance.saved = instance.persisted_snapshot.exists()
instance.apply_groups = []
return instance
@property
def project_id(self) -> str:
return self.project.project_id
def inventory(self) -> Path:
command = _load_command(self.mailbox / "command.json")
assert command.action == "inventory"
assert command.job_id == self.job_id
assert command.project_id == self.project_id
assert command.expected_count == 0
assert command.expected_logical_keys == ()
assert self.is_open
self._active_command = command
write_snapshot(self.current_snapshot, self._current)
observed = load_snapshot(self.current_snapshot)
assert observed == self._current
assert observed.fingerprint == snapshot_fingerprint(observed)
snapshot_path = self.mailbox / "snapshot.json"
write_snapshot(snapshot_path, observed)
self._write_status("inventory_exported", snapshot_path=snapshot_path)
return snapshot_path
def close(self) -> Path:
command = _load_command(self.mailbox / "command.json")
assert command.action in {"close_project", "close_without_save"}
assert command.job_id == self.job_id
assert command.project_id == self.project_id
assert command.expected_count == 0
assert command.expected_logical_keys == ()
assert self.is_open
if command.action == "close_project":
assert command.expected_fingerprint == self._current.fingerprint
self._active_command = command
snapshot_path = self.mailbox / "snapshot.json"
write_snapshot(snapshot_path, self._current)
self._write_status("project_closed", snapshot_path=snapshot_path)
self.is_open = False
if command.action == "close_without_save":
self._current = load_snapshot(self.native_project)
return snapshot_path
def open(self) -> Path:
command = _load_command(self.mailbox / "command.json")
assert command.action == "open_project"
assert command.job_id == self.job_id
assert command.project_id == self.project_id
assert command.expected_count == 0
assert command.expected_logical_keys == ()
assert not self.is_open
self._current = load_snapshot(self.native_project)
assert command.expected_fingerprint == self._current.fingerprint
self._active_command = command
self.is_open = True
snapshot_path = self.mailbox / "snapshot.json"
write_snapshot(snapshot_path, self._current)
self._write_status("project_opened", snapshot_path=snapshot_path)
return snapshot_path
def consume_command(self) -> BridgeCommand:
command = _load_command(self.mailbox / "command.json")
selected = eligible_logical_keys(self._current, RULE)
assert command.format_version == 1
assert command.command_id
assert command.job_id == self.job_id
assert command.project_id == self.project_id
assert command.action == "replace_part"
assert command.scope is Scope.FULL_PROJECT
assert (command.old_part_number, command.new_part_number) == (
RULE.old_part_number,
RULE.new_part_number,
)
assert command.expected_fingerprint == self._current.fingerprint
assert command.expected_logical_keys == selected
assert command.expected_count == len(selected) == self.hit_count
self._active_command = command
self._apply_command = command
self.apply_groups.append((self.marker.stem, command.old_part_number, command.expected_count))
self._write_status("applying", snapshot_path=None)
return command
def replace(self, rule: MappingRule, fault: str | None = None) -> None:
command = self._active_command
assert command is not None
assert rule == RULE
if fault not in {None, "wrong_target"}:
raise ValueError(f"unsupported isolated fault: {fault}")
self._before_apply = self._current
expected = set(command.expected_logical_keys)
changed: list[ComponentSnapshot] = []
for component in self._current.components:
if component.logical_key not in expected:
changed.append(component)
continue
changed.append(
replace(
component,
part_number=rule.new_part_number,
units=tuple(replace(unit, symbol="LIB:NEW") for unit in component.units),
)
)
if fault == "wrong_target":
first = changed.index(next(component for component in changed if component.logical_key in expected))
changed[first] = replace(changed[first], part_number="WRONG-1")
self._current = _fingerprinted(replace(self._current, components=tuple(changed)))
after_path = self.mailbox / "snapshot.json"
write_snapshot(after_path, self._current)
self._write_status("applied", snapshot_path=after_path)
def undo(self) -> None:
assert self._before_apply is not None
command = _load_command(self.mailbox / "command.json")
assert command.action == "undo"
assert self._apply_command is not None
assert command.command_id == self._apply_command.command_id
assert command.expected_fingerprint == self._current.fingerprint
self._active_command = command
self._current = self._before_apply
undo_path = self.mailbox / "undo.json"
write_snapshot(undo_path, self._current)
self.current_snapshot = undo_path
snapshot_path = self.mailbox / "snapshot.json"
write_snapshot(snapshot_path, self._current)
self._write_status(
"undo_verified",
snapshot_path=snapshot_path,
status_action="replace_part",
)
def save(self) -> None:
command = _load_command(self.mailbox / "command.json")
assert command.action == "save"
assert self._apply_command is not None
assert command.command_id == self._apply_command.command_id
assert command.expected_fingerprint == self._current.fingerprint
self._active_command = command
write_snapshot(self.native_project, self._current)
persisted = load_snapshot(self.native_project)
write_snapshot(self.persisted_snapshot, persisted)
snapshot_path = self.mailbox / "snapshot.json"
write_snapshot(snapshot_path, persisted)
self.saved = True
self._write_status(
"saved",
snapshot_path=snapshot_path,
status_action="replace_part",
)
def external_check(self, check: str, *, change_design: bool = False) -> None:
command = _load_command(self.mailbox / "command.json")
assert command.action == check
assert check in {"packager", "erc", "netlist"}
assert command.expected_count == 0
assert command.expected_logical_keys == ()
assert command.expected_fingerprint == self._current.fingerprint
self._active_command = command
if change_design:
first = self._current.components[0]
self._current = _fingerprinted(
replace(
self._current,
components=(replace(first, part_number="CHECK-CHANGED"),)
+ self._current.components[1:],
)
)
snapshot_path = self.mailbox / "snapshot.json"
write_snapshot(snapshot_path, self._current)
self._write_status("external_check_passed", snapshot_path=snapshot_path)
def _write_status(
self,
state: str,
*,
snapshot_path: Path | None,
status_action: str | None = None,
) -> None:
command = self._active_command
assert command is not None
path = self.mailbox / "status.json"
data = {
"command_id": command.command_id,
"details": [
["action", status_action or command.action],
["expected_count", str(command.expected_count)],
["job_id", command.job_id],
],
"error_code": None,
"error_message": None,
"format_version": 1,
"project_id": self.project_id,
"snapshot_path": str(snapshot_path.resolve()) if snapshot_path is not None else None,
"state": state,
}
atomic_write_text(
path,
json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n",
)
@dataclass(frozen=True, slots=True)
class HarnessResult:
run_dir: Path
project_states: dict[str, str]
apply_groups: list[tuple[str, str, int]]
backups_verified: bool
saved_projects: set[str]
undo_verified: bool
exit_codes: tuple[tuple[str, int], ...]
report_paths: tuple[Path, ...]
projects: dict[str, MockDxDesigner]
class MockBatchHarness:
def __init__(self, root: Path, inputs: JobInputs) -> None:
self.root = Path(root)
self.inputs = inputs
self.run_dir = self.root / "run"
self.exit_codes: list[tuple[str, int]] = []
code, created = self._cli(
"create",
str(self.run_dir),
"--mapping",
str(inputs.mapping),
"--projects",
str(inputs.projects),
"--certifications",
str(inputs.certifications),
"--suffix",
".prj",
"--library-identity",
LIBRARY_IDENTITY,
)
assert code == 0
self.job_id = created["job_id"]
refs = {
project["display_name"]: ProjectRef(
project["project_id"],
project["project_path"],
project["display_name"],
)
for project in created["projects"]
}
self.projects = {
"p1": MockDxDesigner(self.run_dir, refs["p1"], inputs.markers["p1"], 3, self.job_id),
"p2": MockDxDesigner(self.run_dir, refs["p2"], inputs.markers["p2"], 1, self.job_id),
}
self.next_action: tuple[str, str] | None = None
self.project_states: dict[str, str] = created["states"]
def _cli(self, *arguments: str) -> tuple[int, dict[str, Any]]:
code, payload = _invoke_cli(*arguments)
self.exit_codes.append((arguments[0], code))
return code, payload
def _ingest_all(self) -> None:
for mock in self.projects.values():
code, _ = self._cli("prepare-inventory", str(self.run_dir), mock.project_id)
assert code == 0
mock.inventory()
code, _ = self._cli("ingest", str(self.run_dir), mock.project_id)
assert code == 0
def _next(self) -> tuple[str, dict[str, Any]] | None:
code, payload = self._cli("next", str(self.run_dir))
if payload["complete"]:
assert code == 0
return None
assert code == 4
project = payload["project"]
return project["display_name"], payload
def _consume_status(
self,
name: str,
state: str,
snapshot_name: str | None,
) -> Path | None:
mock = self.projects[name]
def require(condition: bool, message: str) -> None:
if not condition:
raise BridgeStatusEvidenceError(f"bridge_status: {message}")
try:
command = _load_command(mock.mailbox / "command.json")
status = load_status(mock.mailbox / "status.json")
require(command.format_version == 1, "command format version does not match")
require(bool(command.command_id), "command ID is empty")
require(command.job_id == self.job_id, "command job ID does not match")
require(command.project_id == mock.project_id, "command project ID does not match")
status_action = (
"replace_part" if command.action in {"undo", "save"} else command.action
)
expected_count = (
mock.hit_count
if command.action in {"replace_part", "undo", "save"}
else 0
)
require(command.expected_count == expected_count, "command expected count does not match")
require(status.format_version == 1, "status format version does not match")
require(status.command_id == command.command_id, "status command ID does not match")
require(status.project_id == command.project_id, "status project ID does not match")
require(status.state == state, "status state does not match")
require(status.error_code is None, "status contains an error code")
require(status.error_message is None, "status contains an error message")
require(
status.details
== (
("action", status_action),
("expected_count", str(command.expected_count)),
("job_id", command.job_id),
),
"status details do not match the command",
)
expected_path = mock.mailbox / snapshot_name if snapshot_name is not None else None
expected_status_path = str(expected_path.resolve()) if expected_path is not None else None
require(status.snapshot_path == expected_status_path, "status snapshot path does not match")
if expected_path is None:
return None
require(expected_path.is_file(), "status snapshot is missing")
snapshot = load_snapshot(expected_path)
require(snapshot.project_id == mock.project_id, "snapshot project ID does not match")
require(
Path(snapshot.project_path).resolve(strict=False) == mock.marker.resolve(strict=False),
"snapshot project path does not match",
)
require(
snapshot.fingerprint == snapshot_fingerprint(snapshot),
"snapshot fingerprint does not match its contents",
)
return expected_path
except BridgeStatusEvidenceError:
raise
except (AssertionError, KeyError, OSError, TypeError, UnicodeError, ValueError) as error:
raise BridgeStatusEvidenceError(
f"bridge_status: invalid evidence for {mock.project_id} in state {state}"
) from error
def _apply(self, name: str, fault: str | None = None) -> tuple[int, dict[str, Any]]:
mock = self.projects[name]
code, _ = self._cli("prepare", str(self.run_dir), mock.project_id, "0")
assert code == 4
mock.consume_command()
mock.replace(RULE, fault=fault)
return self._cli("verify", str(self.run_dir), mock.project_id, "0")
def _close_and_open(self, name: str) -> None:
mock = self.projects[name]
code, command = self._cli(
"prepare-close",
str(self.run_dir),
mock.project_id,
)
assert code == 4
assert command["action"] == "close_project"
mock.close()
code, closed = self._cli(
"confirm-close",
str(self.run_dir),
mock.project_id,
)
assert code == 0
assert closed["state"] == ProjectState.APPLY_PENDING.value
code, command = self._cli(
"prepare-open",
str(self.run_dir),
mock.project_id,
)
assert code == 4
assert command["action"] == "open_project"
mock.open()
code, opened = self._cli(
"confirm-open",
str(self.run_dir),
mock.project_id,
)
assert code == 0
assert opened["state"] == ProjectState.APPLY_PENDING.value
def _save(self, name: str) -> None:
mock = self.projects[name]
code, command = self._cli(
"prepare-save",
str(self.run_dir),
mock.project_id,
)
assert code == 4
assert command["action"] == "save"
mock.save()
code, payload = self._cli(
"confirm-saved",
str(self.run_dir),
mock.project_id,
)
assert code == 4
assert payload["state"] == ProjectState.AWAITING_EXTERNAL_CHECKS.value
for index, check in enumerate(("packager", "erc", "netlist")):
code, command = self._cli(
"prepare-check",
str(self.run_dir),
mock.project_id,
check,
)
assert code == 4
assert command["action"] == check
mock.external_check(check)
code, payload = self._cli(
"confirm-check",
str(self.run_dir),
mock.project_id,
check,
)
assert code == (0 if index == 2 else 4)
assert payload["state"] == ProjectState.VERIFIED_SAVED.value
def run_successfully(self) -> HarnessResult:
self._ingest_all()
while True:
next_item = self._next()
if next_item is None:
break
name, payload = next_item
assert payload["action"] == "prepare-close"
self._close_and_open(name)
code, verified = self._apply(name)
assert code == 0 and verified["passed"] is True
self._save(name)
return self._result(undo_verified=False)
def run_with_fault(self, project_name: str, fault: str) -> HarnessResult:
self._ingest_all()
next_item = self._next()
assert next_item is not None and next_item[0] == project_name
assert next_item[1]["action"] == "prepare-close"
self._close_and_open(project_name)
code, verified = self._apply(project_name, fault=fault)
assert code == 3 and verified["passed"] is False
mock = self.projects[project_name]
code, command = self._cli(
"prepare-undo",
str(self.run_dir),
mock.project_id,
)
assert code == 4
assert command["action"] == "undo"
mock.undo()
code, _ = self._cli(
"confirm-undo",
str(self.run_dir),
mock.project_id,
)
assert code == 0
undo_verified = True
return self._result(undo_verified=undo_verified)
def crash_during_apply(self, project_name: str) -> Path:
self._ingest_all()
while True:
next_item = self._next()
assert next_item is not None
name, payload = next_item
assert payload["action"] == "prepare-close"
mock = self.projects[name]
self._close_and_open(name)
code, _ = self._cli("prepare", str(self.run_dir), mock.project_id, "0")
assert code == 4
mock.consume_command()
if name == project_name:
return self.run_dir
mock.replace(RULE)
code, verified = self._cli("verify", str(self.run_dir), mock.project_id, "0")
assert code == 0 and verified["passed"] is True
self._save(name)
@classmethod
def resume(cls, run_dir: Path) -> MockBatchHarness:
controller = BatchController.open(run_dir)
harness = cls.__new__(cls)
harness.root = Path(run_dir).parent
harness.run_dir = Path(run_dir)
harness.exit_codes = []
harness.job_id = controller.job_id
harness.inputs = JobInputs(
harness.run_dir / "inputs" / "mapping.csv",
harness.run_dir / "inputs" / "projects.txt",
controller.certification_path,
{project.display_name: Path(project.project_path) for project in controller.projects},
)
counts = {"p1": 3, "p2": 1}
harness.projects = {
project.display_name: MockDxDesigner.resume(
harness.run_dir,
project,
counts[project.display_name],
harness.job_id,
)
for project in controller.projects
}
code, next_payload = harness._cli("next", str(harness.run_dir))
assert code == 4
assert next_payload["action"] == "reconcile"
next_name = next_payload["project"]["display_name"]
harness.next_action = (next_name, next_payload["action"])
harness._consume_status(next_name, "applying", None)
mock = harness.projects[next_name]
code, blocked = harness._cli(
"reconcile",
str(harness.run_dir),
mock.project_id,
)
assert code == 3
assert blocked["error"]["code"] == "recovery_evidence_missing"
code, close_command = harness._cli(
"prepare-close",
str(harness.run_dir),
mock.project_id,
)
assert code == 4
assert close_command["action"] == "close_without_save"
mock.close()
code, closed = harness._cli(
"confirm-close",
str(harness.run_dir),
mock.project_id,
)
assert code == 0
assert closed["state"] == ProjectState.BLOCKED.value
code, reconciled = harness._cli(
"reconcile",
str(harness.run_dir),
mock.project_id,
)
assert code == 0
assert reconciled["state"] == ProjectState.INVENTORY_PENDING.value
code, open_command = harness._cli(
"prepare-open",
str(harness.run_dir),
mock.project_id,
)
assert code == 4
assert open_command["action"] == "open_project"
mock.open()
code, opened = harness._cli(
"confirm-open",
str(harness.run_dir),
mock.project_id,
)
assert code == 0
assert opened["state"] == ProjectState.INVENTORY_PENDING.value
code, inventory_command = harness._cli(
"prepare-inventory",
str(harness.run_dir),
mock.project_id,
)
assert code == 0
assert inventory_command["action"] == "inventory"
mock.inventory()
code, _ = harness._cli(
"ingest",
str(harness.run_dir),
mock.project_id,
)
assert code == 0
code, status = harness._cli("status", str(harness.run_dir))
assert code == 0
harness.project_states = {
project["display_name"]: project["state"] for project in status["projects"]
}
return harness
def _result(self, *, undo_verified: bool) -> HarnessResult:
code, status = self._cli("status", str(self.run_dir))
assert code == 0
states = {project["display_name"]: project["state"] for project in status["projects"]}
code, report = self._cli("report", str(self.run_dir))
assert code == 0
return HarnessResult(
run_dir=self.run_dir,
project_states=states,
apply_groups=[group for mock in self.projects.values() for group in mock.apply_groups],
backups_verified=self._backups_verified(),
saved_projects={name for name, mock in self.projects.items() if mock.saved},
undo_verified=undo_verified,
exit_codes=tuple(self.exit_codes),
report_paths=tuple(Path(path) for path in report.values()),
projects=self.projects,
)
def _backups_verified(self) -> bool:
try:
records = [
json.loads(line)
for line in (self.run_dir / "events.jsonl").read_text(encoding="utf-8").splitlines()
]
backup_events = [record for record in records if record["event"] == "backup_verified"]
projects_by_id = {mock.project_id: mock for mock in self.projects.values()}
if len(backup_events) != len(projects_by_id):
return False
if {event["project_id"] for event in backup_events} != set(projects_by_id):
return False
referenced_backups: set[Path] = set()
for event in backup_events:
project_id = event["project_id"]
mock = projects_by_id[project_id]
payload = event["payload"]
if not isinstance(payload, dict) or set(payload) != {"backup_path", "manifest_path"}:
return False
backup_relative = Path(payload["backup_path"])
if (
backup_relative.is_absolute()
or len(backup_relative.parts) != 2
or backup_relative.parts[0] != "backups"
or not backup_relative.name.startswith(f"{project_id}-")
):
return False
manifest_relative = Path(payload["manifest_path"])
if (
manifest_relative.is_absolute()
or len(manifest_relative.parts) != 3
or manifest_relative.parts[:2] != ("evidence", project_id)
or not manifest_relative.name.startswith("backup-")
or manifest_relative.suffix != ".json"
):
return False
backup = self.run_dir / backup_relative
referenced_backups.add(backup)
data = _json_object(self.run_dir / manifest_relative)
manifest = TreeManifest(
data["project_root"],
tuple(
TreeFile(entry["path"], entry["size"], entry["sha256"])
for entry in data["files"]
),
)
if Path(manifest.project_root).resolve() != mock.marker.parent.resolve():
return False
if not verify_tree(backup, manifest):
return False
if load_snapshot(backup / "design.sch") != load_snapshot(mock.current_snapshot):
return False
actual_backups = set((self.run_dir / "backups").iterdir())
return actual_backups == referenced_backups
except (AssertionError, KeyError, OSError, TypeError, UnicodeError, ValueError):
return False
@@ -0,0 +1,484 @@
import importlib.util
import inspect
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import call, patch
ROOT = Path(__file__).resolve().parents[2]
RUNTIME = ROOT / "integration" / "dxdesigner795"
SPEC = importlib.util.spec_from_file_location(
"native", ROOT / "src" / "dx_productivity" / "trial_task_center" / "native_helper.py"
)
native = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(native)
FAKES = r"""
Class TestPoint
Public X, Y
End Class
Class TestAttribute
Public Name, Value, InstanceValue, Font, Size, Visible, IgnoreColor
Private ColorValue, OrientationValue, Point
Private Sub Class_Initialize()
Set Point = New TestPoint
Point.X = 0
Point.Y = 0
ColorValue = 0
IgnoreColor = False
OrientationValue = 0
End Sub
Public Property Get Color
Color = ColorValue
End Property
Public Property Let Color(ByVal NewValue)
If Not IgnoreColor Then ColorValue = NewValue
End Property
Public Property Get Orientation
Orientation = OrientationValue
End Property
Public Property Let Orientation(ByVal NewValue)
If NewValue <> OrientationValue Then
Point.X = Point.X - 6
Point.Y = Point.Y + 8
End If
OrientationValue = NewValue
End Property
Public Function GetLocation()
Set GetLocation = Point
End Function
Public Sub SetLocation(ByVal LocationX, ByVal LocationY)
Point.X = LocationX
Point.Y = LocationY
End Sub
End Class
Class TestComponent
Public UID, Refdes, Orientation, Scale, LocationX, LocationY
Public Function GetLocation()
Dim Point
Set Point = New TestPoint
Point.X = LocationX
Point.Y = LocationY
Set GetLocation = Point
End Function
End Class
Class TestView
Public Components, Block
Public Function Query(ByVal Flags, ByVal Selection)
Set Query = Components
End Function
Public Function GetName(ByVal Mode)
GetName = "Main"
End Function
End Class
Class TestBlock
Public SheetNum
End Class
Class TestProjectData
Public Function GetProjectFilePath()
GetProjectFilePath = "C:\test\project.prj"
End Function
End Class
Class TestApplication
Public ActiveView
Public Function GetProjectData()
Set GetProjectData = New TestProjectData
End Function
End Class
Function StyleRecord()
Dim Record
Set Record = CreateObject("Scripting.Dictionary")
Record.Add "name", "Value"
Record.Add "x", "103"
Record.Add "y", "204"
Record.Add "color", "4"
Record.Add "font", "0"
Record.Add "size", "12"
Record.Add "orientation", "2"
Record.Add "visible", "3"
Set StyleRecord = Record
End Function
Sub Require(ByVal Condition, ByVal Message)
If Not Condition Then Err.Raise 500, "Regression", Message
End Sub
"""
class NativeTests(unittest.TestCase):
def test_native_command_does_not_use_physical_mouse_fallback(self):
source = inspect.getsource(native.run_native)
self.assertIn("replacement_command_from_resources(executable)", source)
self.assertNotIn("win32api.SetCursorPos", source)
self.assertNotIn("mouse_event", source)
self.assertNotIn("win32gui.SetCursorPos(screen_point)", source)
def test_snapshot_batch_is_reselected_before_the_strict_selection_gate(self):
app = object()
api = object()
metadata = ["M"]
first = type("Component", (), {"UID": "wanted"})()
other = type("Component", (), {"UID": "other"})()
records = [["C", "wanted"]]
with patch.object(native, "check_context", side_effect=([first, other], [first, other])) as check:
with patch.object(native, "selection") as select:
result = native.select_snapshot_batch(app, api, metadata, records)
self.assertEqual(result, [first, other])
self.assertEqual(check.call_args_list[0], call(app, api, metadata, records, require_selection=False))
self.assertEqual(check.call_args_list[1], call(app, api, metadata, records))
self.assertEqual(select.call_args_list, [call(first, True), call(other, False)])
def test_snapshot_escape_format(self):
self.assertEqual(native.decode("a%0009b%000Ac%0025"), "a\tb\nc%")
self.assertEqual(native.decode("%0025000A"), "%000A")
self.assertEqual(native.decode("emoji:%D83D%DE00"), "emoji:\U0001f600")
for malformed in ("%D83D", "%DE00", "%D83Dtext"):
with self.subTest(malformed=malformed), self.assertRaises(ValueError):
native.decode(malformed)
def test_library_unique_exact_match(self):
row = (object(), ["Resistors", "R0805", "Discrete:RES"])
self.assertIs(native.exact_target([row], "R0805"), row)
def test_library_waits_for_an_exact_target_and_stable_rows(self):
target = (object(), ["Resistors", "R0805", "Discrete:RES"])
states = [[], [(object(), ["Resistors", "OTHER", "Discrete:RES"])], [target]]
def rows():
return states.pop(0) if len(states) > 1 else states[0]
self.assertEqual(
native.wait_for_library_rows(rows, "R0805", timeout=1, stable_for=0, poll_interval=0),
[target],
)
def test_multislot_symbol_suffix_must_be_within_target_slots(self):
self.assertTrue(native.target_symbol_matches("Discrete:RES", "Discrete:RES", 4))
self.assertTrue(native.target_symbol_matches("Discrete:RES.4", "Discrete:RES", 4))
self.assertFalse(native.target_symbol_matches("Discrete:RES.5", "Discrete:RES", 4))
self.assertFalse(native.target_symbol_matches("Discrete:OTHER.1", "Discrete:RES", 4))
def test_pin_number_promotion_covers_every_target_slot(self):
component = type("Component", (), {"UID": "uid"})()
pin = type("Pin", (), {"Component": component, "Number": "1"})()
item = type("PinItem", (), {"_oleobj_": object()})()
block = unittest.mock.Mock()
view = type("View", (), {"Block": block, "Query": lambda self, *_args: [item]})()
app = type("Application", (), {"ActiveView": view})()
api = type("Api", (), {"IVdCmpPin": staticmethod(lambda _item: pin)})()
with patch.object(native, "components_on_sheet", return_value=[component]), patch.object(native, "selection") as select:
promoted = native.promote_pin_numbers(app, api, ["uid"], 3)
self.assertEqual(block.PromoteSymbolNumbers.call_args_list, [call(1, 1), call(1, 2), call(1, 3)])
self.assertEqual(promoted, [{"uid": "uid", "number": "1"}])
self.assertEqual(select.call_args_list, [call(component, True), call(component, False)])
def test_part_label_is_only_required_by_part_label_value_mode(self):
component = type("Component", (), {"UID": "uid", "Refdes": "R1"})()
records = [["C", "uid", "R1"]]
def value(_component, name):
return {"Part Number": "NEW", "Part Name": "RES", "Part Label": ""}[name]
with patch.object(native, "attribute_value", side_effect=value):
self.assertEqual(native.replacement_matches([component], records, "NEW", False), ["uid"])
with self.assertRaisesRegex(ValueError, "Part Label readback failed"):
native.replacement_matches([component], records, "NEW", True)
self.assertEqual(native.snapshot_value_mode(["M", "project", "OLD", "NEW", "sheet"]), "part_label")
self.assertEqual(native.snapshot_value_mode(["M", "project", "OLD", "NEW", "sheet", "custom"]), "custom")
def test_replace_symbol_menu_title_supports_localized_accelerators(self):
self.assertTrue(native.is_replace_symbol_title("替换符号(&R)..."))
self.assertTrue(native.is_replace_symbol_title("Replace &Symbol..."))
self.assertFalse(native.is_replace_symbol_title("符号更新(&U)"))
def test_native_error_sidecar_is_written_and_cleared(self):
with tempfile.TemporaryDirectory() as directory:
snapshot = Path(directory) / "snapshot.tsv"
error_path = Path(str(snapshot) + ".native.error.txt")
native.save_report(snapshot, {"ok": False, "error": "focus failed"})
self.assertEqual(error_path.read_text(encoding="utf-8"), "focus failed")
native.save_report(snapshot, {"ok": True})
self.assertFalse(error_path.exists())
def test_failed_atomic_report_publish_preserves_previous_report(self):
with tempfile.TemporaryDirectory() as directory:
snapshot = Path(directory) / "snapshot.tsv"
report_path = Path(str(snapshot) + ".native.json")
report_path.write_text('{"stage":"previous"}', encoding="utf-8")
with patch.object(native.os, "replace", side_effect=OSError("locked")):
with self.assertRaises(OSError):
native.save_report(snapshot, {"stage": "replacement", "ok": False})
self.assertEqual(report_path.read_text(encoding="utf-8"), '{"stage":"previous"}')
self.assertEqual(tuple(report_path.parent.glob(f".{report_path.name}.*.tmp")), ())
def test_library_ambiguous_gate_is_rejected(self):
row = (None, ["Resistors", "R0805", "Discrete:RES"])
with self.assertRaises(ValueError):
native.exact_target([row, row], "R0805")
def test_library_missing_or_wrong_part_is_rejected(self):
for rows in ([], [(None, ["Resistors", "R08050", "Discrete:RES"])]):
with self.subTest(rows=rows), self.assertRaises(ValueError):
native.exact_target(rows, "R0805")
def test_library_blank_symbol_is_rejected(self):
with self.assertRaises(ValueError):
native.exact_target([(None, ["Resistors", "R0805", ""])], "R0805")
def test_snapshot_duplicate_uid_is_rejected(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "snapshot.tsv"
path.write_text("M\tproject\told\tnew\tsheet\n" + "C\tuid\tR1\t0\t0\t0\t1\tnet\n" * 2)
with self.assertRaises(ValueError):
native.read_snapshot(path)
def test_snapshot_accepts_explicit_part_label_value_policy(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "snapshot.tsv"
path.write_text("M\tproject\told\tnew\tsheet\tpart_label\nC\tuid\tR1\t0\t0\t0\t1\tnet\n")
metadata, components = native.read_snapshot(path)
self.assertEqual(metadata[5], "part_label")
self.assertEqual(components[0][1], "uid")
def test_no_op_rule_is_rejected(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "snapshot.tsv"
path.write_text("M\tproject\tSAME\tsame\tsheet\nC\tuid\tR1\t0\t0\t0\t1\tnet\n")
with self.assertRaises(ValueError):
native.read_snapshot(path)
class VBScriptTests(unittest.TestCase):
def test_old_unassigned_pins_accept_target_numbers_only_with_same_network(self):
self.run_vbs('Require QPConnectionsMatch("1|500|550|NET1|VCC" & vbLf, "|500|550|NET1|VCC" & vbLf), "unassigned source blocked"')
def test_assigned_pin_number_changes_are_rejected(self):
self.run_vbs('Require Not QPConnectionsMatch("2|500|550|NET1|VCC" & vbLf, "1|500|550|NET1|VCC" & vbLf), "assigned pin number changed"')
def test_unassigned_target_or_changed_net_is_rejected(self):
self.run_vbs('Require Not QPConnectionsMatch("|500|550|NET1|VCC" & vbLf, "|500|550|NET1|VCC" & vbLf), "target remains unassigned"\nRequire Not QPConnectionsMatch("1|500|550|NET2|GND" & vbLf, "|500|550|NET1|VCC" & vbLf), "net changed"')
def test_unassigned_pins_accept_library_geometry_translation_and_change(self):
self.run_vbs('Require QPConnectionsMatch("1|1330|1170|NEWUID|SYS_RESET_N" & vbLf & "2|1330|1140|OTHERUID|GND" & vbLf, "|1328|1144|OLDUID|GND" & vbLf & "|1328|1174|OLDUID2|SYS_RESET_N" & vbLf), "valid topology was rejected after library geometry changed"')
def test_missing_old_value_gets_hidden_style(self):
self.run_vbs("""Dim Attr, Style, Original
Set Attr = New TestAttribute
Set Original = StyleRecord()
QPRestoreDisplay Attr, Original, "R1"
Set Style = QPHiddenValueStyle(Attr)
Require Style("name") = "Value" And Style("visible") = "0", "new value is not hidden"
Require Style("x") = Original("x") And Style("y") = Original("y"), "fallback location changed"
""")
def test_rollback_snapshot_ignores_attribute_enumeration_order(self):
self.run_vbs('Require QPSortSnapshotLines("B" & vbCrLf & "A" & vbCrLf) = QPSortSnapshotLines("A" & vbCrLf & "B" & vbCrLf), "unstable rollback fingerprint"')
def test_final_display_readback_rejects_later_drift(self):
self.run_vbs("""Dim Attr, Record, Failure
Set Attr = New TestAttribute
Set Record = StyleRecord()
QPRestoreDisplay Attr, Record, "R1"
Attr.SetLocation 999, 999
On Error Resume Next
QPVerifyDisplay Attr, Record, "R1"
Failure = Err.Number
Err.Clear
On Error GoTo 0
Require Failure <> 0, "later display drift falsely passed"
""")
def test_attribute_coordinate_readback_accepts_ten_unit_grid_drift(self):
self.run_vbs("""Dim Attr, Record
Set Attr = New TestAttribute
Set Record = StyleRecord()
QPRestoreDisplay Attr, Record, "R1"
Attr.SetLocation 113, 194
QPVerifyDisplay Attr, Record, "R1"
""")
def test_attribute_coordinate_readback_rejects_larger_drift_with_context(self):
self.run_vbs("""Dim Attr, Record, Failure, Description
Set Attr = New TestAttribute
Set Record = StyleRecord()
Record("name") = "Part Label"
Record.Add "uid", "uid"
QPRestoreDisplay Attr, Record, "R1"
Attr.SetLocation 114, 204
On Error Resume Next
QPVerifyDisplay Attr, Record, "R1"
Failure = Err.Number
Description = Err.Description
Err.Clear
On Error GoTo 0
Require Failure <> 0, "attribute drift beyond tolerance falsely passed"
Require InStr(Description, "Part Label") > 0, "attribute name missing from failure"
Require InStr(Description, "refdes=R1") > 0, "refdes missing from failure"
Require InStr(Description, "uid=uid") > 0, "uid missing from failure"
Require InStr(Description, "x=103->114") > 0, "coordinate difference missing from failure"
""")
def test_component_coordinate_readback_accepts_ten_unit_grid_drift(self):
self.run_vbs("""Dim Comp, Record
Set Comp = New TestComponent
Comp.UID = "uid": Comp.Refdes = "R1": Comp.Orientation = 0: Comp.Scale = 1
Comp.LocationX = 110: Comp.LocationY = 190
Set Record = CreateObject("Scripting.Dictionary")
Record.Add "uid", "uid": Record.Add "refdes", "R1"
Record.Add "x", "100": Record.Add "y", "200"
Record.Add "orientation", "0": Record.Add "scale", "1"
QPVerifyTransform Comp, Record
""")
def test_component_coordinate_readback_rejects_more_than_ten_units(self):
self.run_vbs("""Dim Comp, Record, Failure
Set Comp = New TestComponent
Comp.UID = "uid": Comp.Refdes = "R1": Comp.Orientation = 0: Comp.Scale = 1
Comp.LocationX = 111: Comp.LocationY = 200
Set Record = CreateObject("Scripting.Dictionary")
Record.Add "uid", "uid": Record.Add "refdes", "R1"
Record.Add "x", "100": Record.Add "y", "200"
Record.Add "orientation", "0": Record.Add "scale", "1"
On Error Resume Next
QPVerifyTransform Comp, Record
Failure = Err.Number
Err.Clear
On Error GoTo 0
Require Failure <> 0, "component drift beyond tolerance falsely passed"
""")
def test_component_orientation_readback_remains_strict(self):
self.run_vbs("""Dim Comp, Record, Failure
Set Comp = New TestComponent
Comp.UID = "uid": Comp.Refdes = "R1": Comp.Orientation = 1: Comp.Scale = 1
Comp.LocationX = 100: Comp.LocationY = 200
Set Record = CreateObject("Scripting.Dictionary")
Record.Add "uid", "uid": Record.Add "refdes", "R1"
Record.Add "x", "100": Record.Add "y", "200"
Record.Add "orientation", "0": Record.Add "scale", "1"
On Error Resume Next
QPVerifyTransform Comp, Record
Failure = Err.Number
Err.Clear
On Error GoTo 0
Require Failure <> 0, "orientation mismatch falsely passed"
""")
def run_vbs(self, body):
source = (RUNTIME / "QuickPartReplace.vbs").read_text(encoding="utf-8-sig")
header = source[:source.index("Set QP_Fso =")]
routines = source[source.index("Sub QPMain()") :]
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "regression.vbs"
script = header + '\nSet QP_Fso = CreateObject("Scripting.FileSystemObject")\n'
script += 'QP_Root = "' + directory + '"\n' + body + '\nWScript.Echo "PASS"\nWScript.Quit 0\n' + FAKES + routines
path.write_text(script, encoding="utf-8")
result = subprocess.run(["cscript.exe", "//nologo", str(path)], capture_output=True, timeout=15)
self.assertEqual(result.returncode, 0, (result.stdout + result.stderr).decode(errors="replace"))
self.assertIn(b"PASS", result.stdout)
def test_display_restore_and_readback(self):
self.run_vbs("""Dim Attr, Record
Set Attr = New TestAttribute
Set Record = StyleRecord()
QPRestoreDisplay Attr, Record, "R1"
Require Attr.Color = 4 And Attr.Size = 12 And Attr.Orientation = 2, "style not restored"
QPVerifyDisplay Attr, Record, "R1"
""")
def test_silent_display_setter_failure_is_rejected(self):
self.run_vbs("""Dim Attr, Record, Failure
Set Attr = New TestAttribute
Attr.IgnoreColor = True
Set Record = StyleRecord()
On Error Resume Next
QPRestoreDisplay Attr, Record, "R1"
Failure = Err.Number
Err.Clear
On Error GoTo 0
Require Failure <> 0, "silent no-op setter falsely passed"
""")
def test_incomplete_style_is_rejected(self):
self.run_vbs("""Dim Attr, Record, Failure
Set Attr = New TestAttribute
Set Record = StyleRecord()
Record("x") = ""
On Error Resume Next
QPRestoreDisplay Attr, Record, "R1"
Failure = Err.Number
Err.Clear
On Error GoTo 0
Require Failure <> 0, "incomplete style falsely passed"
""")
def test_target_identity_is_not_instance_owned(self):
self.run_vbs("""Require QPIsInstanceAttribute("User_Comment"), "custom instance not preserved"
Require QPIsInstanceAttribute("Notes"), "notes not preserved"
Require Not QPIsInstanceAttribute("Part Number"), "old PN may overwrite target"
Require Not QPIsInstanceAttribute("Part Label"), "old label may overwrite target"
Require Not QPIsInstanceAttribute("Tolerance"), "old electrical data may overwrite target"
""")
def test_uid_association_precedes_overlapping_position(self):
self.run_vbs("""Dim First, Second, Record, View, Found
Set First = New TestComponent
First.UID = "original"
First.Refdes = "R1"
First.LocationX = 100
First.LocationY = 100
Set Second = New TestComponent
Second.UID = "other"
Second.Refdes = "R2"
Second.LocationX = 100
Second.LocationY = 100
Set Record = StyleRecord()
Record.Add "uid", "original"
Record.Add "refdes", "R1"
Set View = New TestView
Set View.Components = CreateObject("Scripting.Dictionary")
Set View.Block = New TestBlock
View.Block.SheetNum = "1"
View.Components.Add First, True
View.Components.Add Second, True
Set QP_App = New TestApplication
Set QP_App.ActiveView = View
Set Found = QPFindUniqueByOldLocation(Record)
Require Found.UID = "original", "UID association failed"
""")
def test_ambiguous_refdes_is_rejected(self):
self.run_vbs("""Dim First, Second, Record, View, Found, Failure
Set First = New TestComponent
First.UID = "new1"
First.Refdes = "R1"
Set Second = New TestComponent
Second.UID = "new2"
Second.Refdes = "R1"
Set Record = StyleRecord()
Record.Add "uid", "old"
Record.Add "refdes", "R1"
Set View = New TestView
Set View.Components = CreateObject("Scripting.Dictionary")
View.Components.Add First, True
View.Components.Add Second, True
Set QP_App = New TestApplication
Set QP_App.ActiveView = View
On Error Resume Next
Set Found = QPFindUniqueByOldLocation(Record)
Failure = Err.Number
Err.Clear
On Error GoTo 0
Require Failure <> 0, "ambiguous identity falsely passed"
""")
if __name__ == "__main__":
unittest.main(verbosity=2)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,211 @@
from __future__ import annotations
from pathlib import Path
import re
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = ROOT / "integration" / "dxdesigner795" / "QuickPartReplace.vbs"
def test_quick_part_replace_is_an_ascii_current_sheet_automatic_contract() -> None:
"""Keep the automatic native replacement and strict restoration contract intact."""
text = SCRIPT.read_text(encoding="ascii")
assert all(byte <= 0x7F for byte in SCRIPT.read_bytes())
for required in (
"%LOCALAPPDATA%\\DxProductivity\\trial-task-center\\quick-run",
"QPProjectPath()",
"QPSheetIdentity()",
"QP_App.ActiveView.Query(VDM_COMP, VD_ALL)",
'QPRequiredAttributeValue(Comp, "Part Number")',
"Comp.FindAttribute(CStr(Name))",
"Comp.UID",
"Comp.Refdes",
"Comp.GetLocation",
"Comp.Orientation",
"Comp.Scale",
"QP_App.ActiveView.Query(VDM_COMPPIN, VD_ALL)",
"CmpPin.Component.UID",
"Set Connection = CmpPin.Connection",
"Set Net = Connection.Net",
"Net.UID",
"Net.LogicalNetName",
"InstanceValue",
"GetLocation",
"Color",
"Font",
"Size",
"Orientation",
"Visible",
"awaiting_native_replace",
"batch_saved_unverified",
"status.tsv",
"snapshot-",
"quick-part-replace.log",
'QPFindCurrentAttribute(Comp, "Part Label")',
'AddAttribute("Value=" & LabelValue',
"QPNativeReplace Command, SnapshotPath",
'" --native-helper --snapshot "',
):
assert required in text
assert re.search(r"comp\.Selected\s*=\s*True", text, re.IGNORECASE)
assert re.search(r"For Each Comp In Components\s+Comp\.Selected = False", text)
assert "vbTextCompare" in text
assert '"|UNCONNECTED"' in text
assert "QPAddSortedSignature" in text
assert "QPEffectiveAttributeValue" in text
assert "QP_CurrentJobId" in text
assert 'Meta.Add "sheet_name"' in text
assert "snapshot project or sheet mismatch" in text
assert "WScript.Arguments" in text
assert "Attr.Color = CLng(Record(\"color\"))" in text
assert "Attr.Font = CLng(Record(\"font\"))" in text
assert "Attr.Orientation = CLng(Record(\"orientation\"))" in text
assert "Attr.Visible = CLng(Record(\"visible\"))" in text
assert "QPRestorePreflight Candidate" in text
assert "completed" not in text.casefold()
for prohibited in (
"SelectExactSet",
"OpenReplacePartDialog",
"ReplacePartCompleted",
"PartReplaceProbe",
"profile",
"SendKeys",
"AppActivate",
"GetConnections",
):
assert prohibited.casefold() not in text.casefold()
assert "Const VDM_COMP = 128" in text
assert "Const VDM_COMPPIN = 4096" in text
assert "Const VD_ALL = 0" in text
assert 'GetObject(, "Viewdraw.Application")' in text
assert 'CreateObject("Viewdraw.Application")' in text
assert 'QPEnsureProject QP_App, TargetPath' in text
assert 'For Attempt = 1 To 60' in text
assert "WScript.Quit QP_ExitCode" in text
assert "QP_ExitCode = 3" in text
assert "QP_BatchSaveCommitted" in text
assert "project was saved before readback verification failed" in text
def test_quick_part_replace_uses_job_scoped_multirow_commands() -> None:
"""A later rule for one project must not be hidden by the first TSV row."""
text = SCRIPT.read_text(encoding="ascii")
assert 'Array("task_id", "job_id", "project_path", "old_part", "new_part")' in text
assert "For LineIndex = 1 To UBound(Lines)" in text
assert "QPCanonicalPath(QPProjectPath())" in text
assert re.search(
r"QPReadState\(StatusPath,\s*_\s*CStr\(Candidate\(\"job_id\"\)\)\)",
text,
)
assert '"job_id" & vbTab & "state"' in text
assert '"restored_ok"' in text
assert "QPJobSnapshotPath" in text
assert 'Meta.Add "sheet_name", QPDecode(Fields(4))' in text
def test_quick_part_replace_prioritizes_recovery_and_preflights_before_writes() -> None:
"""Do not strand an automatic replacement or restore before validation."""
text = SCRIPT.read_text(encoding="ascii")
assert "QPReadProjectRuleStates" in text
assert '"awaiting_native_replace"' in text
assert '"hard_failure"' in text
assert "multiple awaiting_native_replace rules" in text
assert text.index("QPRestorePreflight") < text.index("Comp.Refdes =")
assert "Cannot capture " in text
assert "QPOptionalAttributeField" in text
assert "value_style_defaulted" in text
assert 'QP_App.ExecuteCommand("undo")' in text
assert '".native.rolled-back"' in text
assert "native undo does not match the original snapshot" in text
assert 'QP_CurrentJobId = CStr(Candidate("job_id"))' in text
restoration = text[text.index("Sub QPRestoreAfterOperatorReplace("):text.index("Sub QPRestorePlans(")]
assert restoration.index("snapshot project or sheet mismatch") < restoration.index("Set Plans =")
def test_retry_ready_recovery_closes_only_the_verified_read_only_project_before_unlocking() -> None:
text = SCRIPT.read_text(encoding="ascii")
recovery = text[text.index("Sub QPRecoverSavedJob("):]
branch = recovery[recovery.index("If OldCount = Plans.Count Then"):recovery.index("On Error Resume Next")]
assert branch.index("QPRequireCommandSnapshot") < branch.index("RecoveryDocument.Close False")
assert 'RecoveryDocuments.Count <> 1' in branch
assert branch.index("QP_App.CloseProject") < branch.index('"retry_ready"')
assert 'RecoveryProjectData.GetProjectFilePath()' in branch
assert 'Close True' not in branch
def test_connection_mismatch_records_both_signatures_before_rollback() -> None:
"""A live connection mismatch must identify the exact component and evidence."""
text = SCRIPT.read_text(encoding="ascii")
assert re.search(r'"connection_mismatch uid=" &\s*_\s*CStr\(ComponentRecord\("uid"\)\)', text)
assert re.search(r'" saved=" &\s*_\s*QPLogField\(SavedConnections\)', text)
assert re.search(r'" current=" &\s*_\s*QPLogField\(CurrentConnections\)', text)
assert text.index("connection_mismatch uid=") < text.index('"connection validation failed"')
assert "Function QPLogField(ByVal Value)" in text
def test_batch_status_appends_without_rereading_the_full_history() -> None:
text = SCRIPT.read_text(encoding="ascii")
status_writer = text[text.index("Sub QPWriteStatus("):text.index("Sub QPFail(")]
assert "QPAppendAscii Path" in status_writer
assert "QPReadUtf8" not in status_writer
assert "Existing" not in status_writer
assert '"current-state.tsv"' in status_writer
assert '"current-command.tsv"' in text
assert "QPActiveCommandPath" in text
def test_runtime_log_appends_and_sheet_manifest_is_checked_in_one_scan() -> None:
text = SCRIPT.read_text(encoding="ascii")
log_writer = text[text.index("Sub QPLog("):text.index("Function QPLogField(")]
ensure_project = text[text.index("Sub QPEnsureProject("):text.index("Sub QPDiscoverSheets(")]
assert "QPAppendAscii Path" in log_writer
assert "QPEncode(CStr(Now))" in log_writer
assert "QPReadUtf8" not in log_writer
assert "QPWriteUtf8" not in log_writer
assert "QPSheetIsAvailable" not in text
assert "QPRequireSheetManifest TargetPath, Documents, QP_TargetSchematic, QP_TargetSheet" in ensure_project
assert 'Expected.Exists(TargetKey)' in text
assert 'QPLog QP_Root, "INFO", "no_match ' in text
def test_discovery_inventory_queries_components_and_closes_pages_without_saving() -> None:
text = SCRIPT.read_text(encoding="ascii")
inventory = text[text.index("Sub QPDiscoverInventory("):text.index("Function QPReadInventoryRequest(")]
assert "View.Query(VDM_COMP, VD_ALL)" in inventory
assert 'QPFindCurrentAttribute(Comp, "Part Number")' in inventory
assert "Requested.Exists(PartKey)" in inventory
assert 'Document.Close False, ""' in inventory
assert 'QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "inventory.tsv")' in inventory
def test_component_lookup_reuses_one_sheet_index() -> None:
text = SCRIPT.read_text(encoding="ascii")
builder = text[text.index("Sub QPBuildComponentIndex("):text.index("Function QPComponentPins(")]
finder = text[text.index("Function QPFindUniqueByOldLocation("):text.index("Function QPDisplayVerificationSummary(")]
assert "For Each Comp In Components" in builder
assert "QP_ComponentUidIndex" in builder
assert "QP_ComponentRefdesIndex" in builder
assert "QP_ComponentLocationIndex" in builder
assert "QPEnsureComponentIndex" in finder
assert "ActiveView.Query" not in finder
def test_success_summary_reports_verified_display_colors_without_per_item_pin_noise() -> None:
text = SCRIPT.read_text(encoding="ascii")
summary = text[text.index("Function QPDisplayVerificationSummary("):text.index("Sub QPVerifyTransform(")]
assert 'Record("color")' in summary
assert '"Display verified: attributes="' in summary
assert '"; colors="' in summary
assert "stage=query_pins" not in text
@@ -0,0 +1,517 @@
import ast
from pathlib import Path
import subprocess
import pytest
SOURCE = Path(__file__).resolve().parents[2] / 'integration/dxdesigner795/QuickPartReplace.vbs'
FAKES = r'''
Dim FakeApp, AttachCalls, LaunchCalls, ReadyAfter, SleepCalls
Set FakeApp = New SessionApp
AttachCalls = 0
LaunchCalls = 0
SleepCalls = 0
ReadyAfter = 0
Function FakeAttach()
AttachCalls = AttachCalls + 1
Set FakeAttach = Nothing
If AttachCalls > ReadyAfter Then Set FakeAttach = FakeApp
End Function
Function FakeLaunch()
LaunchCalls = LaunchCalls + 1
Set FakeLaunch = FakeApp
End Function
Sub FakeSleep(ByVal Milliseconds)
SleepCalls = SleepCalls + 1
End Sub
Sub Require(ByVal Condition, ByVal Message)
If Not Condition Then Err.Raise 51000, "Test", Message
End Sub
Class SessionApp
Public ProjectPath, Visible, OpenCount, OpenResult, ActiveView, Documents, ActualSheet, CloseCount, SaveCount, RefuseClose, Components
Private Sub Class_Initialize()
ProjectPath = ""
OpenCount = 0
OpenResult = True
ActualSheet = "1"
Set ActiveView = Nothing
Set Components = CreateObject("Scripting.Dictionary")
Set Documents = New SessionDocuments
Set Documents.Owner = Me
End Sub
Public Function GetProjectData()
Set GetProjectData = Me
End Function
Public Function GetProjectFilePath()
GetProjectFilePath = ProjectPath
End Function
Public Function OpenProject(ByVal Target)
OpenCount = OpenCount + 1
If OpenResult Then ProjectPath = Target
OpenProject = OpenResult
End Function
Public Function SchematicSheetDocuments()
Set SchematicSheetDocuments = Documents
End Function
Public Sub CloseProject()
CloseCount = CloseCount + 1
If Not RefuseClose Then ProjectPath = ""
End Sub
Public Function GetName(ByVal Flags)
GetName = "Main"
End Function
Public Property Get Block()
Set Block = Me
End Property
Public Property Get SheetNum()
SheetNum = ActualSheet
End Property
Public Function Query(ByVal Kind, ByVal Scope)
Set Query = Components
End Function
End Class
Class SessionDocuments
Public Owner, OpenCount, SheetCount
Private Sub Class_Initialize()
OpenCount = 0
SheetCount = 1
End Sub
Public Function GetAvailableSchematics()
Dim Names
Set Names = CreateObject("Scripting.Dictionary")
Names.Add "Main", True
Set GetAvailableSchematics = Names
End Function
Public Function GetAvailableSheets(ByVal Schematic)
Dim Names, Index
Set Names = CreateObject("Scripting.Dictionary")
For Index = 1 To SheetCount
Names.Add CStr(Index), True
Next
Set GetAvailableSheets = Names
End Function
Public Function Open(ByVal Schematic, ByVal Sheet)
OpenCount = OpenCount + 1
Set Owner.ActiveView = Owner
Set Open = Me
End Function
Public Sub Activate()
End Sub
Public Property Get Count
Count = 1
End Property
Public Function Item(ByVal Index)
If Index <> 1 Then Err.Raise 51000,"Test","bad document index"
Set Item = Me
End Function
Public Sub Close(ByVal SaveChanges, ByVal FileName)
If SaveChanges Then Owner.SaveCount = Owner.SaveCount + 1
Set Owner.ActiveView = Nothing
End Sub
End Class
Class SessionComponent
Public PartNumber, Refdes
Public Function FindAttribute(ByVal Name)
Dim Attribute
Set FindAttribute = Nothing
If Name = "Part Number" Then
Set Attribute = New SessionAttribute
Attribute.Value = PartNumber
Set FindAttribute = Attribute
End If
End Function
End Class
Class SessionAttribute
Public InstanceValue, Value
End Class
'''
def run_session(tmp_path, body):
source = SOURCE.read_text(encoding='ascii')
header = source[:source.index('Set QP_Fso =')]
routines = source[source.index('Sub QPMain()'):]
routines = routines.replace('GetObject(, "Viewdraw.Application")', 'FakeAttach()')
routines = routines.replace('CreateObject("Viewdraw.Application")', 'FakeLaunch()')
routines = routines.replace('WScript.Sleep ', 'FakeSleep ')
routines = routines.replace('QPAttachOrStart(QPDesignerProcessCount())', 'QPAttachOrStart(0)')
target = tmp_path / 'target.prj'
target.touch()
setup = f'''
Set QP_Fso = CreateObject("Scripting.FileSystemObject")
QP_Root = "{tmp_path}"
Dim Target, Attached
Target = "{target}"
'''
wrapper = tmp_path / 'session-test.vbs'
wrapper.write_text(header + FAKES + setup + body + '\nWScript.Echo "PASS"\nWScript.Quit 0\n' + routines, encoding='ascii')
result = subprocess.run(['cscript.exe', '//nologo', str(wrapper)], capture_output=True, timeout=15,
creationflags=subprocess.CREATE_NO_WINDOW)
assert result.returncode == 0, (result.stdout + result.stderr).decode(errors='replace')
assert b'PASS' in result.stdout, result.stderr.decode('gbk', errors='replace')
def test_batch_refuses_to_take_over_an_existing_project(tmp_path):
run_session(tmp_path, '''
QP_BatchMode=True
FakeApp.ProjectPath=Target
On Error Resume Next
QPEnsureProject FakeApp,Target
Dim Failure
Failure=Err.Number
Err.Clear
On Error GoTo 0
Require Failure<>0,"batch took over user project"
Require FakeApp.OpenCount=0,"opened another project"
Require IsEmpty(FakeApp.CloseCount),"closed user project"
''')
def test_batch_no_match_commits_only_after_owned_project_close(tmp_path):
run_session(tmp_path, '''
Set QP_App=FakeApp
FakeApp.ProjectPath=Target
QP_CurrentJobId="batch-job": QP_ExpectedJobId="batch-job"
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"command.tsv"),"task_id" & vbTab & "job_id" & vbTab & "project_path" & vbTab & "old_part" & vbTab & "new_part" & vbTab & "value_mode" & vbCrLf & "task" & vbTab & "batch-job" & vbTab & Target & vbTab & "OLD" & vbTab & "NEW" & vbTab & "preserve" & vbCrLf
QP_BatchMode=True: QP_OwnedProject=True
QPWriteStatus QP_Root,QP_CurrentJobId,"no_match","","not found"
Require Not QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root,"status.tsv")),"published success before close"
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),QP_CurrentJobId)="no_match","pending no-match not visible to worker"
QPFinishBatchItem
Require FakeApp.CloseCount=1,"project not closed exactly once"
Require FakeApp.SaveCount=1,"sheet not closed with saving allowed"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"batch_closed")>0,"no completion proof"
''')
def test_batch_never_closes_unowned_project(tmp_path):
run_session(tmp_path, '''
Set QP_App=FakeApp
FakeApp.ProjectPath=Target
QP_OwnedProject=False
On Error Resume Next
QPCloseBatchProject Target
Dim Failure
Failure=Err.Number
Err.Clear
On Error GoTo 0
Require Failure<>0,"unowned project accepted"
Require IsEmpty(FakeApp.CloseCount),"unowned project closed"
''')
def test_batch_close_failure_is_not_reported_as_done(tmp_path):
run_session(tmp_path, '''
Set QP_App=FakeApp
FakeApp.ProjectPath=Target
QP_OwnedProject=True: FakeApp.RefuseClose=True
On Error Resume Next
QPCloseBatchProject Target
Dim Failure
Failure=Err.Number
Err.Clear
On Error GoTo 0
Require Failure<>0,"close refusal ignored"
Require Not QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root,"status.tsv")),"false terminal status"
''')
def test_absent_designer_is_started_once(tmp_path):
run_session(tmp_path, '''
ReadyAfter = 999
Set Attached = QPAttachOrStart(0)
Require LaunchCalls = 1, "did not start exactly once"
Require Attached Is FakeApp, "wrong application"
Require FakeApp.Visible, "new application not visible"
''')
def test_existing_designer_is_reused(tmp_path):
run_session(tmp_path, '''
Set Attached = QPAttachOrStart(1)
Require LaunchCalls = 0, "started duplicate"
Require Attached Is FakeApp, "wrong application"
''')
def test_starting_designer_is_waited_for_not_duplicated(tmp_path):
run_session(tmp_path, '''
ReadyAfter = 3
Set Attached = QPAttachOrStart(1)
Require LaunchCalls = 0, "started duplicate during startup"
Require SleepCalls > 0, "did not wait for registration"
''')
@pytest.mark.parametrize('count', [1, 2])
def test_unavailable_or_multiple_instances_do_not_launch(tmp_path, count):
run_session(tmp_path, f'''
ReadyAfter = 999
On Error Resume Next
Set Attached = QPAttachOrStart({count})
Dim Failure, FailureSource
Failure = Err.Number
FailureSource = Err.Source
Err.Clear
On Error GoTo 0
Require Failure <> 0, "unsafe instance accepted"
Require FailureSource = "QuickPartReplace.Session", "wrong failure source"
Require LaunchCalls = 0, "started duplicate instance"
''')
def test_empty_session_opens_project_and_only_sheet(tmp_path):
run_session(tmp_path, '''
QPEnsureProject FakeApp, Target
Require FakeApp.OpenCount = 1, "project not opened"
Require FakeApp.ProjectPath = Target, "wrong project"
Require FakeApp.Documents.OpenCount = 1, "sole sheet not opened"
''')
def test_matching_active_project_is_not_reopened(tmp_path):
run_session(tmp_path, '''
FakeApp.ProjectPath = Target
Set FakeApp.ActiveView = FakeApp
QPEnsureProject FakeApp, Target
Require FakeApp.OpenCount = 0, "reopened user project"
Require FakeApp.Documents.OpenCount = 0, "changed user page"
''')
def test_other_project_is_never_closed_or_replaced(tmp_path):
run_session(tmp_path, '''
FakeApp.ProjectPath = "C:\\unrelated.prj"
On Error Resume Next
QPEnsureProject FakeApp, Target
Dim Failure
Failure = Err.Source
Err.Clear
On Error GoTo 0
Require Failure = "QuickPartReplace.Session", "accepted wrong project"
Require FakeApp.OpenCount = 0, "switched unrelated project"
''')
@pytest.mark.parametrize('sheets', [0, 2])
def test_missing_or_ambiguous_sheet_is_not_silently_selected(tmp_path, sheets):
run_session(tmp_path, f'''
FakeApp.Documents.SheetCount = {sheets}
On Error Resume Next
QPEnsureProject FakeApp, Target
Dim Failure
Failure = Err.Source
Err.Clear
On Error GoTo 0
Require Failure = "QuickPartReplace.Session", "invalid page set accepted"
Require FakeApp.Documents.OpenCount = 0, "selected arbitrary page"
''')
def test_batch_opens_the_exact_confirmed_sheet_in_a_multisheet_project(tmp_path):
run_session(tmp_path, '''
QP_BatchMode = True
QP_ExpectedJobId = "job"
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "command.tsv"), _
"task_id" & vbTab & "job_id" & vbTab & "project_path" & vbTab & "schematic_name" & vbTab & "sheet_number" & vbTab & "old_part" & vbTab & "new_part" & vbTab & "value_mode" & vbCrLf & _
"task" & vbTab & "job" & vbTab & Target & vbTab & "Main" & vbTab & "2" & vbTab & "OLD" & vbTab & "NEW" & vbTab & "preserve" & vbCrLf
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "sheets.tsv"), _
"project_path" & vbTab & "schematic_name" & vbTab & "sheet_number" & vbCrLf & _
Target & vbTab & "Main" & vbTab & "1" & vbCrLf & _
Target & vbTab & "Main" & vbTab & "2" & vbCrLf
FakeApp.Documents.SheetCount = 2
FakeApp.ActualSheet = "2"
Dim Confirmed
Confirmed = QPConfirmedProjectPath()
QPEnsureProject FakeApp, Confirmed
Require FakeApp.Documents.OpenCount = 1, "confirmed sheet not opened exactly once"
Require CStr(FakeApp.ActiveView.Block.SheetNum) = "2", "wrong confirmed sheet activated"
''')
def test_changed_sheet_set_stops_before_opening_a_page(tmp_path):
run_session(tmp_path, '''
QP_BatchMode = True
QP_ExpectedJobId = "job"
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "command.tsv"), _
"task_id" & vbTab & "job_id" & vbTab & "project_path" & vbTab & "schematic_name" & vbTab & "sheet_number" & vbTab & "old_part" & vbTab & "new_part" & vbTab & "value_mode" & vbCrLf & _
"task" & vbTab & "job" & vbTab & Target & vbTab & "Main" & vbTab & "1" & vbTab & "OLD" & vbTab & "NEW" & vbTab & "preserve" & vbCrLf
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "sheets.tsv"), _
"project_path" & vbTab & "schematic_name" & vbTab & "sheet_number" & vbCrLf & _
Target & vbTab & "Main" & vbTab & "1" & vbCrLf
FakeApp.Documents.SheetCount = 2
Dim Confirmed, Failure
Confirmed = QPConfirmedProjectPath()
On Error Resume Next
QPEnsureProject FakeApp, Confirmed
Failure = Err.Description
Err.Clear
On Error GoTo 0
Require Failure = "project sheet set changed after discovery", "changed page set accepted"
Require FakeApp.Documents.OpenCount = 0, "opened a page after manifest mismatch"
''')
def test_sheet_discovery_records_every_page_and_closes_without_saving(tmp_path):
run_session(tmp_path, '''
Set QP_App = FakeApp
QP_BatchMode = True
QP_DiscoveryMode = True
QP_OwnedProject = True
FakeApp.ProjectPath = Target
FakeApp.Documents.SheetCount = 2
QPDiscoverSheets
Require FakeApp.CloseCount = 1, "discovery did not close its project"
Require FakeApp.ProjectPath = "", "discovery left the project open"
Require FakeApp.Documents.OpenCount = 0, "discovery opened a page"
Dim Manifest
Manifest = QPReadUtf8(QP_Fso.BuildPath(QP_Root, "sheets.tsv"))
Require InStr(Manifest, Target & vbTab & "Main" & vbTab & "1") > 0, "sheet one missing"
Require InStr(Manifest, Target & vbTab & "Main" & vbTab & "2") > 0, "sheet two missing"
''')
def test_sheet_discovery_writes_an_empty_inventory_for_an_absent_requested_part(tmp_path):
run_session(tmp_path, '''
Set QP_App = FakeApp
QP_BatchMode = True
QP_DiscoveryMode = True
QP_OwnedProject = True
FakeApp.ProjectPath = Target
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "inventory-request.tsv"), _
"old_part" & vbCrLf & "MISSING" & vbCrLf
QPDiscoverSheets
Require FakeApp.Documents.OpenCount = 1, "inventory did not open the available sheet exactly once"
Require FakeApp.SaveCount = 0, "read-only inventory saved the sheet"
Dim Inventory
Inventory = QPReadUtf8(QP_Fso.BuildPath(QP_Root, "inventory.tsv"))
Require InStr(Inventory, "MISSING") = 0, "absent source part was reported as present"
''')
def test_replacement_summary_uses_the_confirmed_snapshot_refdes(tmp_path):
run_session(tmp_path, '''
Dim Records, Components, ComponentRecord, Plans, Candidate, Summary
Set Records = CreateObject("Scripting.Dictionary")
Set Components = CreateObject("Scripting.Dictionary")
Set ComponentRecord = CreateObject("Scripting.Dictionary")
ComponentRecord.Add "refdes", "C42"
ComponentRecord.Add "uid", "$1I52"
Components.Add "0", ComponentRecord
Set ComponentRecord = CreateObject("Scripting.Dictionary")
ComponentRecord.Add "refdes", ""
ComponentRecord.Add "uid", "$1I60"
Components.Add "1", ComponentRecord
Records.Add "components", Components
Set Plans = CreateObject("Scripting.Dictionary")
Set Candidate = New SessionComponent
Candidate.Refdes = ""
Plans.Add "0", Candidate
Set Candidate = New SessionComponent
Candidate.Refdes = ""
Plans.Add "1", Candidate
Summary = QPReplacementSummary(Records, Plans, "OLD", "NEW")
Require Summary = "C42 OLD -> NEW; UID=$1I60 OLD -> NEW", "replacement summary lost component identity"
''')
def test_open_failure_does_not_enumerate_or_open_sheets(tmp_path):
run_session(tmp_path, '''
FakeApp.OpenResult = False
On Error Resume Next
QPEnsureProject FakeApp, Target
Dim Failure
Failure = Err.Source
Err.Clear
On Error GoTo 0
Require Failure = "QuickPartReplace.Session", "failed OpenProject accepted"
Require FakeApp.Documents.OpenCount = 0, "opened sheets after failure"
''')
def test_confirmed_job_selects_project_before_launch(tmp_path):
run_session(tmp_path, '''
QP_ExpectedJobId = "job-two"
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "command.tsv"), _
"job_id" & vbTab & "project_path" & vbCrLf & _
"job-one" & vbTab & "C:\\wrong.prj" & vbCrLf & _
"job-two" & vbTab & Target & vbCrLf
Require QPConfirmedProjectPath() = Target, "picked first row instead of confirmed job"
ReadyAfter = 999
QPBootstrapSession
Require QP_App Is FakeApp, "bootstrap did not attach returned application"
Require FakeApp.ProjectPath = Target, "bootstrap opened wrong target"
Require QP_Stage = "session_ready", "bootstrap did not finish"
Require LaunchCalls = 1, "bootstrap launch count"
''')
@pytest.mark.parametrize('rows', ['missing', 'duplicate', 'missing_file'])
def test_invalid_confirmed_job_never_launches_designer(tmp_path, rows):
expression = {
'missing': '"other" & vbTab & Target & vbCrLf',
'duplicate': '"job" & vbTab & Target & vbCrLf & "job" & vbTab & Target & vbCrLf',
'missing_file': '"job" & vbTab & Target & ".missing" & vbCrLf',
}[rows]
run_session(tmp_path, f'''
QP_ExpectedJobId = "job"
QPWriteUtf8 QP_Fso.BuildPath(QP_Root, "command.tsv"), _
"job_id" & vbTab & "project_path" & vbCrLf & {expression}
On Error Resume Next
QPBootstrapSession
Dim Failure
Failure = Err.Source
Err.Clear
On Error GoTo 0
Require Failure = "QuickPartReplace.Session", "bad confirmed job accepted"
Require AttachCalls = 0, "attached before command validation"
Require LaunchCalls = 0, "launched before command validation"
''')
def test_real_worker_rejects_missing_project_without_touching_com(tmp_path):
(tmp_path / 'command.tsv').write_text('job_id\tproject_path\njob\tC:\\nonexistent-startup-test\\missing.prj\n', encoding='utf-8')
status = tmp_path / 'status.tsv'
status.write_text('job_id\tstate\tcode\tmessage\n', encoding='utf-8')
before = status.read_bytes()
result = subprocess.run(['C:\\Windows\\SysWOW64\\cscript.exe', '//nologo', str(SOURCE), str(tmp_path), '', '', 'job'],
capture_output=True, timeout=15, creationflags=subprocess.CREATE_NO_WINDOW)
assert result.returncode == 2
assert b'confirmed project file does not exist' in result.stderr
assert status.read_bytes() == before
assert 'stage=session_startup' in (tmp_path / 'quick-part-replace.log').read_text(encoding='utf-8-sig')
assert not list(tmp_path.glob('snapshot-*'))
def test_opened_wrong_sheet_is_rejected(tmp_path):
run_session(tmp_path, '''
FakeApp.ActualSheet = "2"
On Error Resume Next
QPEnsureProject FakeApp, Target
Dim Failure
Failure = Err.Description
Err.Clear
On Error GoTo 0
Require Failure = "active sheet does not match the requested sheet", "wrong sheet was accepted"
''')
def test_sheet_identity_uses_members_from_installed_type_library():
api = SOURCE.parents[2] / 'build/DxPartReplace-generated/viewdraw_api.py'
if not api.is_file():
pytest.skip('Local 7.9.5 generated type library is not available')
classes = {node.name: node for node in ast.parse(api.read_text(encoding='utf-8-sig')).body if isinstance(node, ast.ClassDef)}
def properties(class_name):
definition = next(node.value for node in classes[class_name].body if isinstance(node, ast.Assign)
and any(isinstance(target, ast.Name) and target.id == '_prop_map_get_' for target in node.targets))
return {key.value for key in definition.keys if isinstance(key, ast.Constant)}
assert 'Block' in properties('IVdView')
assert 'SheetNumber' not in properties('IVdView')
assert 'SheetNum' in properties('IVdBlock')
source = SOURCE.read_text(encoding='ascii')
assert 'View.SheetNumber' not in source
assert 'CStr(View.Block.SheetNum) <> OnlySheet' in source
+687
View File
@@ -0,0 +1,687 @@
import ast
from pathlib import Path
import subprocess
import pytest
ROOT = Path(__file__).resolve().parents[2]
SOURCE = ROOT / 'integration/dxdesigner795/QuickPartReplace.vbs'
TREE = ast.parse((Path(__file__).with_name('test_automatic_replacement_regression.py')).read_text(encoding='utf-8'))
FAKES = next(ast.literal_eval(statement.value) for statement in TREE.body
if isinstance(statement, ast.Assign) and any(isinstance(target, ast.Name) and target.id == 'FAKES'
for target in statement.targets))
EXTRA = r'''
Class ValueComponent
Public UID, Refdes, Orientation, Scale, Attributes, AddCount
Private Point
Private Sub Class_Initialize()
Set Point=New TestPoint
Point.X=0: Point.Y=0
AddCount=0
Set Attributes=CreateObject("Scripting.Dictionary")
End Sub
Public Function GetLocation()
Set GetLocation=Point
End Function
Public Sub SetLocation(ByVal LocationX,ByVal LocationY)
Point.X=LocationX: Point.Y=LocationY
End Sub
Public Function FindAttribute(ByVal Name)
Dim Attr
Set FindAttribute=Nothing
For Each Attr In Attributes
If Attr.Name=Name Then Set FindAttribute=Attr
Next
End Function
Public Sub RemoveAttribute(ByVal Name)
Dim Attr
For Each Attr In Attributes
If Attr.Name=Name Then
Attributes.Remove Attr
Exit Sub
End If
Next
End Sub
Public Function AddAttribute(ByVal Text, ByVal LocationX, ByVal LocationY, ByVal Visibility)
Dim Separator, Attr
Separator=InStr(Text,"=")
Set Attr=AddValueAttr(Me,Left(Text,Separator-1),Mid(Text,Separator+1))
Attr.SetLocation LocationX,LocationY
Attr.Visible=Visibility
AddCount=AddCount+1
Set AddAttribute=Attr
End Function
End Class
Class ValuePin
Public Component, Number
Public Property Get Connection
Set Connection=Me
End Property
Public Property Get Net
Set Net=Me
End Property
Public Property Get UID
UID="NET1"
End Property
Public Property Get LogicalNetName
LogicalNetName="VCC"
End Property
Public Function GetLocation()
Dim Point
Set Point=New TestPoint
Point.X=10: Point.Y=10
Set GetLocation=Point
End Function
End Class
Class ValueApp
Public Components, Pins, ProjectPath, UndoCount, PinQueries, TransactionOpen, TransactionCount
Public DocumentCount, CloseCount, SaveCalled, RefuseClose
Public Function SchematicSheetDocuments()
Set SchematicSheetDocuments=Me
End Function
Public Property Get Count
Count=DocumentCount
End Property
Public Function Item(ByVal DocumentIndex)
Require DocumentIndex=1,"unexpected document index"
Set Item=Me
End Function
Public Sub Close(ByVal SaveChanges,ByVal FileName)
CloseCount=CloseCount+1
If SaveChanges Then SaveCalled=True
End Sub
Public Sub CloseProject()
Require CloseCount=1,"project closed before document"
If Not RefuseClose Then ProjectPath=""
End Sub
Public Property Get ActiveView
Set ActiveView=Me
End Property
Public Property Get Block
Set Block=Me
End Property
Public Property Get SheetNum
SheetNum=1
End Property
Public Function GetName(ByVal Flags)
GetName="A"
End Function
Public Function GetProjectData()
Set GetProjectData=Me
End Function
Public Function GetProjectFilePath()
GetProjectFilePath=ProjectPath
End Function
Public Function Query(ByVal Flags,ByVal Selection)
If Flags=128 Then
Set Query=Components
Else
PinQueries=PinQueries+1
Set Query=Pins
End If
End Function
Public Sub StartUndoTransaction()
TransactionCount=TransactionCount+1
TransactionOpen=True
End Sub
Public Sub EndUndoTransaction()
TransactionOpen=False
End Sub
Public Function ExecuteCommand(ByVal Command)
UndoCount=UndoCount+1
ExecuteCommand=True
End Function
End Class
Function AddValueAttr(ByRef Comp,ByVal Name,ByVal Text)
Dim Attr
Set Attr=New TestAttribute
Attr.Name=Name: Attr.Value=Text: Attr.InstanceValue=""
Attr.Font=0: Attr.Size=10: Attr.Visible=1
Comp.Attributes.Add Attr,True
Set AddValueAttr=Attr
End Function
'''
SETUP = r'''
Dim Comp, Pin, Attr, Ignored, Command, Snapshot, SnapshotPath, Failure, Saved
Set QP_Fso=CreateObject("Scripting.FileSystemObject")
QP_Root="__ROOT__"
QP_CurrentJobId="value-job"
Set QP_App=New ValueApp
QP_App.ProjectPath="C:\value-test\one.prj": QP_App.UndoCount=0
QP_App.DocumentCount=1: QP_App.CloseCount=0: QP_App.SaveCalled=False: QP_App.RefuseClose=False
Set QP_App.Components=CreateObject("Scripting.Dictionary")
Set QP_App.Pins=CreateObject("Scripting.Dictionary")
Set Comp=New ValueComponent
Comp.UID="recorded": Comp.Refdes="R1": Comp.Orientation=0: Comp.Scale=1
QP_App.Components.Add Comp,True
Set Pin=New ValuePin
Set Pin.Component=Comp: Pin.Number="1"
QP_App.Pins.Add Pin,True
Set Ignored=AddValueAttr(Comp,"Part Number","OLD")
Set Ignored=AddValueAttr(Comp,"Part Name","OLD_NAME")
Set Ignored=AddValueAttr(Comp,"Part Label","OLD_LABEL")
Set Attr=AddValueAttr(Comp,"Value","OLD_VALUE")
Set Saved=StyleRecord()
QPRestoreDisplay Attr,Saved,"R1"
Set Command=CreateObject("Scripting.Dictionary")
Command.Add "job_id","value-job"
Command.Add "old_part_number","OLD"
Command.Add "new_part_number","NEW"
Command.Add "value_mode","__MODE__"
Command.Add "custom_value","__CUSTOM__"
Command.Add "sync_nc","__SYNC_NC__"
__BEFORE__
SnapshotPath=QPJobSnapshotPath(QP_CurrentJobId)
Snapshot="M" & vbTab & QPEncode(QPProjectPath()) & vbTab & "OLD" & vbTab & "NEW" & vbTab & QPEncode(QPSheetIdentity()) & vbTab & "__MODE__" & vbTab & QPEncode("__CUSTOM__") & vbTab & "__SYNC_NC__" & vbCrLf & QPSnapshotComponent(Comp)
QPWriteUtf8 SnapshotPath,Snapshot
Set Attr=Comp.FindAttribute("Part Number"): Attr.Value="NEW"
Set Attr=Comp.FindAttribute("Part Name"): Attr.Value="NEW_NAME"
Set Attr=Comp.FindAttribute("Part Label"): Attr.Value="NEW_LABEL"
Comp.RemoveAttribute "Value"
Set Attr=AddValueAttr(Comp,"Value","TARGET_VALUE")
Attr.SetLocation 900,901
__AFTER__
'''
def run_vbs(tmp_path, mode, body, *, before='', after='', custom_value='', sync_nc=True, routines_transform=None):
source = SOURCE.read_text(encoding='utf-8-sig')
header = source[:source.index('Set QP_Fso =')]
routines = source[source.index('Sub QPMain()'):]
if routines_transform is not None:
routines = routines_transform(routines)
setup = (SETUP.replace('__ROOT__', str(tmp_path)).replace('__MODE__', mode)
.replace('__CUSTOM__', custom_value).replace('__SYNC_NC__', '1' if sync_nc else '0')
.replace('__BEFORE__', before).replace('__AFTER__', after))
wrapper = tmp_path / 'value-regression.vbs'
wrapper.write_text(header + setup + body + '\nWScript.Echo "PASS"\nWScript.Quit 0\n' + FAKES + EXTRA + routines, encoding='ascii')
result = subprocess.run(['cscript.exe', '//nologo', str(wrapper)], capture_output=True, timeout=15,
creationflags=subprocess.CREATE_NO_WINDOW)
assert result.returncode == 0, (result.stdout + result.stderr).decode(errors='replace')
assert b'PASS' in result.stdout
def test_recovery_of_saved_result_does_not_write_again(tmp_path):
run_vbs(tmp_path, 'part_number', '''
Command.Add "recovery_part_name","NEW_NAME"
Command.Add "recovery_part_label","NEW_LABEL"
QPRestoreAfterOperatorReplace Command,SnapshotPath
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"status.tsv"),"job_id" & vbTab & "state" & vbTab & "code" & vbTab & "message" & vbCrLf
QPRecoverSavedJob Command,SnapshotPath
Require QP_App.TransactionCount=1,"already restored task wrote to CAD again"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"recovery_verified")>0,"did not identify already saved completion"
Require QP_App.UndoCount=0,"recovery undid prior CAD work"
''')
@pytest.mark.parametrize('mode', ['preserve', 'part_label', 'part_number'])
def test_recovery_repairs_attributes_without_native_replace(tmp_path, mode):
run_vbs(tmp_path, mode, '''
Command.Add "recovery_part_name","NEW_NAME"
Command.Add "recovery_part_label","NEW_LABEL"
QPRecoverSavedJob Command,SnapshotPath
Require QP_App.TransactionCount=1,"did not restore in one owned transaction"
Require Not QP_App.TransactionOpen,"recovery transaction remains open"
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),QP_CurrentJobId)="restored_ok","recovery failed"
Require QP_App.UndoCount=0,"recovery undid native transaction"
''')
def test_recovery_of_unsaved_result_only_prepares_retry(tmp_path):
run_vbs(tmp_path, 'part_number', '''
Set Attr=Comp.FindAttribute("Part Number"): Attr.Value="OLD"
Set Attr=Comp.FindAttribute("Part Name"): Attr.Value="OLD_NAME"
Set Attr=Comp.FindAttribute("Part Label"): Attr.Value="OLD_LABEL"
Set Attr=Comp.FindAttribute("Value"): Attr.Value="OLD_VALUE"
QPRestoreDisplay Attr,Saved,"R1"
QPRecoverSavedJob Command,SnapshotPath
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),QP_CurrentJobId)="retry_ready","original source not recognized"
Require Not QP_App.TransactionOpen,"unchanged source was modified"
Require QP_App.UndoCount=0,"unchanged source was undone"
Require QP_App.CloseCount=1,"read-only document was not closed"
Require Not QP_App.SaveCalled,"read-only recovery saved unexpectedly"
Require Len(QP_App.ProjectPath)=0,"retry would be blocked by an open recovery project"
''')
@pytest.mark.parametrize('change', ['QP_App.DocumentCount=2', 'QP_App.RefuseClose=True'])
def test_readonly_recovery_does_not_unlock_if_document_ownership_or_close_fails(tmp_path, change):
run_vbs(tmp_path, 'part_number', '''
Set Attr=Comp.FindAttribute("Part Number"): Attr.Value="OLD"
Set Attr=Comp.FindAttribute("Part Name"): Attr.Value="OLD_NAME"
Set Attr=Comp.FindAttribute("Part Label"): Attr.Value="OLD_LABEL"
Set Attr=Comp.FindAttribute("Value"): Attr.Value="OLD_VALUE"
QPRestoreDisplay Attr,Saved,"R1"
''' + change + '''
On Error Resume Next
QPRecoverSavedJob Command,SnapshotPath
Failure=Err.Number
Err.Clear
On Error GoTo 0
Require Failure<>0,"unsafe close did not fail"
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),QP_CurrentJobId)<>"retry_ready","unsafe close unlocked retry"
Require Not QP_App.SaveCalled,"unsafe close saved project"
''')
@pytest.mark.parametrize('change', ['Pin.Number="2"', 'Set Attr=Comp.FindAttribute("Part Name"): Attr.Value="OTHER"'])
def test_recovery_rejects_connection_or_identity_changes(tmp_path, change):
run_vbs(tmp_path, 'part_number', '''
Command.Add "recovery_part_name","NEW_NAME"
Command.Add "recovery_part_label","NEW_LABEL"
''' + change + '''
On Error Resume Next
QPRecoverSavedJob Command,SnapshotPath
Failure=Err.Number
Err.Clear
On Error GoTo 0
Require Failure<>0,"unsafe target accepted"
Require Not QP_App.TransactionOpen,"unsafe recovery wrote to CAD"
Require QP_App.UndoCount=0,"unsafe recovery undid work"
''')
def test_recovery_read_error_does_not_trigger_restore(tmp_path):
def broken_verification(routines):
signature = 'Sub QPVerifyRestoredPlans(ByRef Command, ByRef Records, ByRef Plans, ByRef ValueStates)'
return routines.replace(signature, signature + '\n Err.Raise 440,"Test","COM read failed"')
run_vbs(tmp_path, 'part_number', '''
Command.Add "recovery_part_name","NEW_NAME"
Command.Add "recovery_part_label","NEW_LABEL"
On Error Resume Next
QPRecoverSavedJob Command,SnapshotPath
Failure=Err.Number
Err.Clear
On Error GoTo 0
Require Failure=440,"COM read error was swallowed"
Require Not QP_App.TransactionOpen,"COM failure triggered writes"
''', routines_transform=broken_verification)
def test_zero_match_reports_without_snapshot_or_selection_writes(tmp_path):
run_vbs(tmp_path, 'preserve', r'''
QP_Fso.DeleteFile SnapshotPath
QP_NativeMutationPossible=False
QPCaptureAndSelect Command, SnapshotPath
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),"value-job")="no_match","zero match state"
Require Not QP_Fso.FileExists(SnapshotPath),"no snapshot for no match"
Require Comp.FindAttribute("Part Number").Value="NEW","component untouched"
Require Not QP_NativeMutationPossible,"no native mutation"
''')
def test_pin_index_avoids_repeated_full_sheet_queries(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QPInvalidatePinIndex
QP_App.PinQueries=0
Dim Repeated, Signature
For Repeated=1 To 67
Signature=QPConnectionSignature(Comp)
Next
Require QP_App.PinQueries=1,"rescanned whole sheet for each component check"
''')
def test_pin_index_is_rebuilt_after_mutation_boundary(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QPInvalidatePinIndex
QP_App.PinQueries=0
Dim Signature
Signature=QPConnectionSignature(Comp)
Set QP_App.Pins=CreateObject("Scripting.Dictionary")
Set Pin=New ValuePin
Set Pin.Component=Comp: Pin.Number="2"
QP_App.Pins.Add Pin,True
QPInvalidatePinIndex
Signature=QPConnectionSignature(Comp)
Require QP_App.PinQueries=2,"mutation did not invalidate index"
Require Left(Signature,2)="2|","stale pin reused"
''')
def test_pin_index_is_invalidated_by_project_change(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QPInvalidatePinIndex
QP_App.PinQueries=0
Dim Signature
Signature=QPConnectionSignature(Comp)
QP_App.ProjectPath="C:\\value-test\\two.prj"
Set QP_App.Pins=CreateObject("Scripting.Dictionary")
Set Pin=New ValuePin
Set Pin.Component=Comp: Pin.Number="2"
QP_App.Pins.Add Pin,True
Signature=QPConnectionSignature(Comp)
Require QP_App.PinQueries=2,"cross-project index reuse"
Require Left(Signature,2)="2|","cross-project stale pin"
''')
def test_cancel_is_deferred_while_native_helper_is_active(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QP_AttemptToken=String(32,"a")
QP_ExpectedJobId=QP_CurrentJobId
QP_NativeMutationPossible=False
QP_NativeCallActive=True
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"monitor-" & QP_AttemptToken & ".stop"),QP_AttemptToken
QPProgress "native_replace",0,1
Require Not QP_NativeMutationPossible,"helper start was mistaken for mutation evidence"
''')
def test_stale_cancel_token_does_not_stop_current_attempt(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QP_AttemptToken=String(32,"a")
QP_ExpectedJobId=QP_CurrentJobId
QP_NativeMutationPossible=False
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"monitor-" & QP_AttemptToken & ".stop"),String(32,"b")
QPProgress "capture",0,1
''')
def test_restoration_closes_transaction_and_reuses_pin_index_for_verification(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QP_App.PinQueries=0
QPRestoreAfterOperatorReplace Command,SnapshotPath
Require Not QP_App.TransactionOpen,"transaction left open"
Require Not QP_RestoreTransactionOpen,"worker transaction flag left open"
Require QP_App.PinQueries=1,"restoration should reuse the post-replacement pin index"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")), _
"Replacements: R1 OLD -> NEW")>0,"replacement mapping status missing"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"quick-part-replace.log")), _
"replacement R1 OLD -> NEW")>0,"replacement mapping log missing"
''')
def test_cancel_during_restoration_is_deferred_until_safe_completion(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QP_AttemptToken=String(32,"a")
QP_ExpectedJobId=QP_CurrentJobId
QP_NativeMutationPossible=True
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"monitor-" & QP_AttemptToken & ".stop"),QP_AttemptToken
QPRestoreAfterOperatorReplace Command,SnapshotPath
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),QP_CurrentJobId)="restored_ok","cancel interrupted restoration"
Require Not QP_App.TransactionOpen,"cancel left transaction open"
''')
def test_cancel_before_mutation_stops_at_checkpoint(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QP_AttemptToken=String(32,"a")
QP_ExpectedJobId=QP_CurrentJobId
QP_NativeMutationPossible=False
QP_RestoreTransactionOpen=False
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"monitor-" & QP_AttemptToken & ".stop"),QP_AttemptToken
On Error Resume Next
QPProgress "capture",0,1
Failure=Err.Source
Err.Clear
On Error GoTo 0
Require Failure="QuickPartReplace.SafeStop","stop was not acknowledged safely"
Require Not QP_App.TransactionOpen,"unexpected transaction"
''')
def test_native_launch_failure_never_claims_mutation_or_undo(tmp_path):
def replace_shell(routines):
return routines.replace('Set Shell = CreateObject("WScript.Shell")', 'Set Shell = New FailingLaunchShell') + '''
Class FailingLaunchShell
Public Function Run(ByVal CommandLine, ByVal WindowStyle, ByVal Wait)
Err.Raise 51000,"FailingLaunchShell","launch refused"
End Function
End Class
'''
run_vbs(tmp_path, 'part_number', '''
QP_HelperExecutable=WScript.FullName
QP_HelperScript=""
QP_NativeMutationPossible=False
On Error Resume Next
QPNativeReplace Command,SnapshotPath
Failure=Err.Source
Err.Clear
On Error GoTo 0
Require Failure="FailingLaunchShell","did not reach launch failure"
Require Not QP_NativeMutationPossible,"launch failure was mistaken for a replacement"
Require QP_App.UndoCount=0,"launch failure invoked undo"
''', routines_transform=replace_shell)
def test_main_continues_after_zero_match_without_calling_native_helper(tmp_path):
run_vbs(tmp_path, 'preserve', r'''
QP_Fso.DeleteFile SnapshotPath
QP_NativeMutationPossible=False
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"command.tsv"), _
"task_id" & vbTab & "job_id" & vbTab & "project_path" & vbTab & "old_part" & vbTab & "new_part" & vbTab & "value_mode" & vbCrLf & _
"task" & vbTab & "value-job" & vbTab & QPProjectPath() & vbTab & "OLD" & vbTab & "NEW" & vbTab & "preserve" & vbCrLf & _
"task" & vbTab & "second-job" & vbTab & QPProjectPath() & vbTab & "OTHER" & vbTab & "OTHER_NEW" & vbTab & "preserve" & vbCrLf
QP_ExpectedJobId="value-job"
QPMain
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),"value-job")="no_match","first item not reported"
QP_ExpectedJobId="second-job"
QPMain
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),"second-job")="no_match","second item blocked"
Require Not QP_Fso.FileExists(SnapshotPath),"unexpected first snapshot"
Require Not QP_Fso.FileExists(QPJobSnapshotPath("second-job")),"unexpected second snapshot"
Require QP_App.UndoCount=0,"unexpected rollback"
''')
@pytest.mark.parametrize('mode,expected', [
('preserve', 'TARGET_VALUE'),
('part_label', 'NEW_LABEL'),
('part_number', 'NEW'),
])
def test_value_content_policy_preserves_original_display(tmp_path, mode, expected):
run_vbs(tmp_path, mode, f'''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="{expected}","Value content policy failed"
QPVerifyDisplay Attr,Saved,"R1"
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),"value-job")="restored_ok","final verification failed"
''')
def test_unchecked_does_not_create_missing_target_value(tmp_path):
run_vbs(tmp_path, 'preserve', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require Attr Is Nothing,"unchecked created Value"
Require Comp.AddCount=0,"unchecked called AddAttribute"
''', after='Comp.RemoveAttribute "Value"')
def test_checked_creates_value_from_part_label_with_old_style(tmp_path):
run_vbs(tmp_path, 'part_label', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="NEW_LABEL","missing Value not created correctly"
QPVerifyDisplay Attr,Saved,"R1"
''', after='Comp.RemoveAttribute "Value"')
def test_custom_value_overrides_global_source_and_keeps_old_style(tmp_path):
run_vbs(tmp_path, 'custom', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="47k","custom Value was not written"
QPVerifyDisplay Attr,Saved,"R1"
''', custom_value='47k', after='Comp.RemoveAttribute "Value"')
def test_no_old_value_keeps_native_style_when_unchecked(tmp_path):
run_vbs(tmp_path, 'preserve', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="TARGET_VALUE","unexpected content write"
Require Attr.GetLocation().X=900 And Attr.GetLocation().Y=901,"invented old Value style"
''', before='Comp.RemoveAttribute "Value"')
def test_policy_change_is_rejected_before_restore_writes(tmp_path):
run_vbs(tmp_path, 'preserve', '''
Command("value_mode")="part_number"
On Error Resume Next
QPRestoreAfterOperatorReplace Command,SnapshotPath
Failure=Err.Description
Err.Clear
On Error GoTo 0
Require InStr(Failure,"policy mismatch")>0,"snapshot did not bind policy"
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="TARGET_VALUE","wrote before policy validation"
Require QP_App.UndoCount=0,"unexpected Undo"
''')
def test_policy_change_is_rejected_before_native_helper(tmp_path):
run_vbs(tmp_path, 'preserve', '''
Command("value_mode")="part_number"
On Error Resume Next
QPAutomaticReplaceAndRestore Command,SnapshotPath
Failure=Err.Description
Err.Clear
On Error GoTo 0
Require InStr(Failure,"policy mismatch")>0,"called native helper before policy validation"
''')
def test_wrong_active_project_is_rejected_by_vbs_before_selection(tmp_path):
run_vbs(tmp_path, 'preserve', r'''
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"command.tsv"), _
"task_id" & vbTab & "job_id" & vbTab & "project_path" & vbTab & "old_part" & vbTab & "new_part" & vbTab & "value_mode" & vbCrLf & _
"task" & vbTab & "expected-job" & vbTab & "C:\value-test\other.prj" & vbTab & "OLD" & vbTab & "NEW" & vbTab & "preserve" & vbCrLf & _
"task" & vbTab & "other-job" & vbTab & QPProjectPath() & vbTab & "OLD" & vbTab & "NEW" & vbTab & "preserve" & vbCrLf
QP_ExpectedJobId="expected-job"
QP_CurrentJobId=""
On Error Resume Next
Set Command=QPReadCommand(QP_Fso.BuildPath(QP_Root,"command.tsv"))
Failure=Err.Description
Err.Clear
On Error GoTo 0
Require InStr(Failure,"confirmed queue job")>0,"selected different queued project"
Require QP_CurrentJobId="","claimed a job before confirmation validation"
Require QP_App.UndoCount=0,"unexpected Undo"
''')
def test_checked_without_any_old_value_uses_hidden_fallback(tmp_path):
run_vbs(tmp_path, 'part_label', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="NEW_LABEL","wrong created Value"
Require Attr.Visible=0,"missing old Value should not invent a visible style"
''', before='Comp.RemoveAttribute "Value"', after='Comp.RemoveAttribute "Value"')
@pytest.mark.parametrize('native_value', ['', 'INSTANCE_OVERRIDE'])
def test_unchecked_preserves_blank_or_instance_value(tmp_path, native_value):
run_vbs(tmp_path, 'preserve', f'''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="{native_value}","unchecked changed native content"
QPVerifyDisplay Attr,Saved,"R1"
''', after=f'Set Attr=Comp.FindAttribute("Value"): Attr.Value="": Attr.InstanceValue="{native_value}"')
@pytest.mark.parametrize('part_label_setup', [
'Comp.RemoveAttribute "Part Label"',
'Set Attr=Comp.FindAttribute("Part Label"): Attr.Value="": Attr.InstanceValue=""',
])
def test_unchecked_does_not_require_target_part_label(tmp_path, part_label_setup):
run_vbs(tmp_path, 'preserve', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="TARGET_VALUE","unchecked changed native Value"
Require QP_App.UndoCount=0,"unchecked Part Label handling triggered rollback"
''', after=part_label_setup)
@pytest.mark.parametrize('part_label_setup', [
'Comp.RemoveAttribute "Part Label"',
'Set Attr=Comp.FindAttribute("Part Label"): Attr.Value="": Attr.InstanceValue=""',
])
def test_checked_requires_nonblank_target_part_label(tmp_path, part_label_setup):
run_vbs(tmp_path, 'part_label', '''
On Error Resume Next
QPRestoreAfterOperatorReplace Command,SnapshotPath
Failure=Err.Description
Err.Clear
On Error GoTo 0
Require InStr(Failure,"Part Label")>0,"checked mode accepted unavailable Part Label"
Require InStr(Failure,"refdes=R1")>0,"Part Label failure omitted the affected refdes"
Require QP_App.TransactionCount=0,"invalid Part Label reached restoration transaction"
''', after=part_label_setup)
@pytest.mark.parametrize('mode', ['preserve', 'part_label'])
def test_nc_marker_is_synchronized_for_both_value_modes(tmp_path, mode):
run_vbs(tmp_path, mode, '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="R0805/NC","NC marker was not synchronized"
QPVerifyDisplay Attr,Saved,"R1"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"quick-part-replace.log")), _
"nc_sync R1 R0603/NC -> R0805/NC")>0,"NC synchronization log missing"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")), _
"NC synced: R1 R0603/NC -> R0805/NC")>0,"NC synchronization status missing"
''',
before='Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0603/NC"',
after='Set Attr=Comp.FindAttribute("Part Label"): Attr.Value="R0805": '
'Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0805"')
def test_nc_marker_is_not_duplicated(tmp_path):
run_vbs(tmp_path, 'preserve', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="R0805/NC","NC marker was duplicated"
Require Attr.InstanceValue="","existing NC marker created a redundant instance override"
''',
before='Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0603/NC"',
after='Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0805/NC"')
def test_nc_marker_is_not_detected_when_rule_option_is_unchecked(tmp_path):
run_vbs(tmp_path, 'preserve', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="R0805","unchecked NC option changed Value"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"quick-part-replace.log")),"nc_sync")=0,"unchecked NC option logged synchronization"
''',
sync_nc=False,
before='Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0603/NC"',
after='Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0805"')
def test_nc_marker_creates_missing_native_value_with_old_style(tmp_path):
run_vbs(tmp_path, 'preserve', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="/NC","missing target Value did not retain NC"
QPVerifyDisplay Attr,Saved,"R1"
''',
before='Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0603/NC"',
after='Comp.RemoveAttribute "Value"')
@pytest.mark.parametrize('source_value', ['NC', 'R0603/NCM', 'R0603/NC_OPTION'])
def test_similar_text_is_not_treated_as_nc_marker(tmp_path, source_value):
run_vbs(tmp_path, 'preserve', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="R0805","non-NC text triggered synchronization"
''',
before=f'Set Attr=Comp.FindAttribute("Value"): Attr.Value="{source_value}"',
after='Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0805"')
def test_final_value_verification_rejects_wrong_part_number(tmp_path):
run_vbs(tmp_path, 'part_number', '''
Dim Before
Set Before=QPCaptureValueState(Comp)
On Error Resume Next
QPVerifyValuePolicy Comp,"part_number",Before
Failure=Err.Description
Err.Clear
On Error GoTo 0
Require InStr(Failure,"final Value mismatch")>0,"wrong target Value falsely passed"
''')