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

+28
View File
@@ -0,0 +1,28 @@
from decimal import Decimal
import pytest
from dx_productivity.part_replace.models import ComponentSnapshot, DesignSnapshot, PinSnapshot, UnitSnapshot
@pytest.fixture(autouse=True)
def accept_minimal_project_placeholders(monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest) -> None:
if request.node.path.name != "test_scanner.py":
monkeypatch.setattr(
"dx_productivity.trial_task_center.scanner._is_schematic_project",
lambda _path: True,
)
@pytest.fixture
def snapshot_factory():
"""Return a fresh minimal snapshot factory for tests."""
def make(project_id: str = "p1", part_number: str = "OLD-1") -> DesignSnapshot:
pin = PinSnapshot("1", "A", Decimal("10.25"), Decimal("20"), "N$1")
unit = UnitSnapshot(
"u1", "/MAIN", "res.1", Decimal("0"), Decimal("0"),
Decimal("0"), Decimal("0"), 0, False, (pin,),
)
component = ComponentSnapshot("/MAIN|R1", "R1", part_number, (unit,), ())
return DesignSnapshot(2, project_id, "C:/P/a.prj", "abc", (component,))
return make
@@ -0,0 +1,206 @@
{
"format_version": 1,
"dxdesigner": {
"build": "7.9.5.1234",
"version": "7.9.5"
},
"project": {
"active_view": "Sheet1",
"dirty": false,
"identity": "probe-fixture"
},
"enumeration": {
"available": true,
"component_count": 1,
"route": "Application.DesignComponents"
},
"components": [
{
"api_errors": [
{
"description": "fixture error",
"number": 51001,
"operation": "fixture.operation",
"source": "fixture.source"
}
],
"attributes": [
{
"name": "Vendor",
"value": "Acme"
}
],
"gates": [
{
"name": "A",
"unit_number": 1
}
],
"hierarchy": "/MAIN",
"logical_identity": "/MAIN|U1",
"mirror": false,
"nets": [
"N1"
],
"origin": {
"x": 0.5,
"y": 1
},
"part_number": "OLD-1",
"pins": [
{
"name": "IN",
"net_identity": "N1",
"number": "1",
"x": 0,
"y": 1.5
},
{
"name": "NC",
"net_identity": null,
"number": "2",
"x": 2,
"y": 3
}
],
"position": {
"x": 10,
"y": 20
},
"refdes": "U1",
"rotation": 90,
"symbol_identity": "IC_A",
"units": 1
}
],
"interfaces": {
"attributes": {"available": true},
"gates": {"available": true},
"hierarchy": {"available": true},
"logical_identity": {"available": true},
"mirror": {"available": true},
"nets": {"available": true},
"origin_x": {"available": true},
"origin_y": {"available": true},
"part_number": {"available": true},
"pins": {"available": true},
"position_x": {"available": true},
"position_y": {"available": true},
"refdes": {"available": true},
"rotation": {"available": true},
"symbol_identity": {"available": true},
"units": {"available": true}
},
"production_replace_route": "native_replace_part",
"routes": {
"exact_set_selection": {
"attempted": true,
"available": true,
"manual_fallback": "manual_exact_set_selection",
"route": "ActiveView.SelectExactSet",
"attempts": [{"attempted": true, "available": true, "error": null, "route": "ActiveView.SelectExactSet"}]
},
"native_replace_part": {
"attempted": true,
"available": true,
"manual_fallback": "manual_native_replace_part",
"route": "Application.OpenReplacePartDialog",
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.OpenReplacePartDialog"}]
},
"completion_observation": {
"attempted": true,
"available": true,
"manual_fallback": "manual_completion_observation",
"route": "Application.ReplacePartCompleted",
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.ReplacePartCompleted"}]
},
"undo": {
"attempted": true,
"available": true,
"manual_fallback": "manual_undo",
"route": "Application.Undo",
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.Undo"}]
},
"save": {
"attempted": true,
"available": true,
"manual_fallback": "manual_save",
"route": "Application.Save",
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.Save"}]
},
"open_project": {
"attempted": true,
"available": true,
"manual_fallback": "manual_open_project",
"route": "Application.OpenProject",
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.OpenProject"}]
},
"close_project": {
"attempted": true,
"available": true,
"manual_fallback": "manual_close_project",
"route": "Application.CloseProject",
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.CloseProject"}]
},
"packager": {
"attempted": true,
"available": true,
"manual_fallback": "manual_packager",
"route": "Application.RunPackager",
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.RunPackager"}]
},
"erc": {
"attempted": true,
"available": true,
"manual_fallback": "manual_erc",
"route": "Application.RunERC",
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.RunERC"}]
},
"netlist": {
"attempted": true,
"available": true,
"manual_fallback": "manual_netlist",
"route": "Application.RunNetlist",
"attempts": [{"attempted": true, "available": true, "error": null, "route": "Application.RunNetlist"}]
},
"ccomp_research": {
"attempted": true,
"available": false,
"manual_fallback": "manual_ccomp_research",
"route": "Application.CComp",
"attempts": [
{
"attempted": true,
"available": false,
"error": {
"description": "fixture error",
"number": 51001,
"operation": "fixture.operation",
"source": "fixture.source"
},
"route": "Application.CComp"
}
],
"production_enabled": false
}
},
"safety": {
"disposable_project_marker": true,
"mutating_probe_attempted": true,
"mutating_probe_authorized": true,
"operator_confirmation": true,
"request_valid": true
},
"api_errors": [
{
"description": "fixture error",
"number": 51001,
"operation": "fixture.operation",
"source": "fixture.source"
}
],
"live_acceptance": {
"checked": false,
"reason": "live_795_host_not_exercised"
}
}
+1
View File
@@ -0,0 +1 @@
{"components":[{"attributes":[{"name":"tolerance","value":"1%"},{"name":"vendor","value":"Acme"}],"logical_key":"/MAIN|R1","part_number":"NEW-1","refdes":"R1","units":[{"mirrored":false,"origin_x":"-0.5","origin_y":"-0.5","pins":[{"name":"A","net":"N$1","number":"1","x":"10.25","y":"20"},{"name":"B","net":null,"number":"2","x":"11","y":"20"}],"rotation":0,"sheet":"/MAIN","symbol":"RES","unit_id":"A","x":"0","y":"0"}]}],"fingerprint":"stored-after-compatible-fingerprint","format_version":2,"project_id":"project-1","project_path":"C:/Projects/board.prj"}
+1
View File
@@ -0,0 +1 @@
{"components":[{"attributes":[{"name":"tolerance","value":"1%"},{"name":"vendor","value":"Acme"}],"logical_key":"/MAIN|R1","part_number":"NEW-1","refdes":"R1","units":[{"mirrored":false,"origin_x":"-0.5","origin_y":"-0.5","pins":[{"name":"A","net":"N$1","number":"1","x":"10.25","y":"20"},{"name":"B","net":null,"number":"3","x":"11","y":"20"}],"rotation":0,"sheet":"/MAIN","symbol":"RES","unit_id":"A","x":"0","y":"0"}]}],"fingerprint":"stored-after-pin-change-fingerprint","format_version":2,"project_id":"project-1","project_path":"C:/Projects/board.prj"}
+1
View File
@@ -0,0 +1 @@
{"components":[{"attributes":[{"name":"tolerance","value":"1%"},{"name":"vendor","value":"Acme"}],"logical_key":"/MAIN|R1","part_number":"OLD-1","refdes":"R1","units":[{"mirrored":false,"origin_x":"-0.5","origin_y":"-0.5","pins":[{"name":"A","net":"N$1","number":"1","x":"10.25","y":"20"},{"name":"B","net":null,"number":"2","x":"11","y":"20"}],"rotation":0,"sheet":"/MAIN","symbol":"RES","unit_id":"A","x":"0","y":"0"}]}],"fingerprint":"stored-before-fingerprint","format_version":2,"project_id":"project-1","project_path":"C:/Projects/board.prj"}
@@ -0,0 +1,16 @@
{
"format_version": 1,
"project": {"identity": "C:/Projects/Board.PRJ"},
"enumeration": {"available": true, "component_count": 2, "route": "Application.DesignComponents"},
"interfaces": {
"logical_identity": {"available": true}, "part_number": {"available": true},
"refdes": {"available": true}, "hierarchy": {"available": true}, "units": {"available": true},
"origin_x": {"available": true}, "origin_y": {"available": true},
"position_x": {"available": true}, "position_y": {"available": true}, "rotation": {"available": true},
"mirror": {"available": true}, "pins": {"available": true}, "nets": {"available": true}, "parameter_probe": {"available": true}
},
"components": [
{"logical_identity": "/MAIN|R1", "part_number": "WRONG", "refdes": "R1", "hierarchy": "/MAIN", "units": 1, "origin": {"x": 0, "y": 0}, "position": {"x": 10, "y": 20}, "rotation": 0, "mirror": false, "pins": [], "nets": [], "attributes": [], "parameter_probe": {}},
{"logical_identity": "/MAIN|R1", "part_number": "EXISTING-TARGET", "refdes": "C1", "hierarchy": "/MAIN", "units": 1, "origin": {"x": 1, "y": 1}, "position": {"x": 30, "y": 40}, "rotation": 0, "mirror": false, "pins": [], "nets": [], "attributes": [], "parameter_probe": {}}
]
}
@@ -0,0 +1,17 @@
{
"format_version": 1,
"project": {"identity": "c:\\projects\\board.prj"},
"enumeration": {"available": true, "component_count": 2, "route": "Application.DesignComponents"},
"interfaces": {
"logical_identity": {"available": true}, "part_number": {"available": true},
"refdes": {"available": true}, "hierarchy": {"available": true}, "units": {"available": true},
"origin_x": {"available": true}, "origin_y": {"available": true},
"position_x": {"available": true}, "position_y": {"available": true},
"rotation": {"available": true}, "mirror": {"available": true}, "pins": {"available": true},
"nets": {"available": true}, "parameter_probe": {"available": true}
},
"components": [
{"logical_identity": "/MAIN|R1", "part_number": "NEW-1", "refdes": "R1", "hierarchy": "/MAIN", "units": 1, "origin": {"x": 0, "y": 0}, "position": {"x": 10, "y": 20}, "rotation": 0, "mirror": false, "pins": [{"number": "1", "name": "A", "net_identity": "N1", "x": 0, "y": 0}], "nets": ["N1"], "attributes": [{"name": "Part Label", "value": "R"}, {"name": "Value", "value": "10K"}], "parameter_probe": {"Value": {"status": "supported", "value": "10K"}}},
{"logical_identity": "/MAIN|C1", "part_number": "EXISTING-TARGET", "refdes": "C1", "hierarchy": "/MAIN", "units": 1, "origin": {"x": 1, "y": 1}, "position": {"x": 30, "y": 40}, "rotation": 0, "mirror": false, "pins": [{"number": "1", "name": "A", "net_identity": "N2", "x": 1, "y": 1}], "nets": ["N2"], "attributes": [], "parameter_probe": {}}
]
}
+17
View File
@@ -0,0 +1,17 @@
{
"format_version": 1,
"project": {"identity": "C:/Projects/Board.PRJ"},
"enumeration": {"available": true, "component_count": 2, "route": "Application.DesignComponents"},
"interfaces": {
"logical_identity": {"available": true}, "part_number": {"available": true},
"refdes": {"available": true}, "hierarchy": {"available": true}, "units": {"available": true},
"origin_x": {"available": true}, "origin_y": {"available": true},
"position_x": {"available": true}, "position_y": {"available": true},
"rotation": {"available": true}, "mirror": {"available": true}, "pins": {"available": true},
"nets": {"available": true}, "parameter_probe": {"available": true}
},
"components": [
{"logical_identity": "/MAIN|R1", "part_number": "OLD-1", "refdes": "R1", "hierarchy": "/MAIN", "units": 1, "origin": {"x": 0, "y": 0}, "position": {"x": 10, "y": 20}, "rotation": 0, "mirror": false, "pins": [{"number": "1", "name": "A", "net_identity": "N1", "x": 0, "y": 0}], "nets": ["N1"], "attributes": [{"name": "Part Label", "value": "R"}, {"name": "Value", "value": "10K"}], "parameter_probe": {"Value": {"status": "supported", "value": "10K"}}},
{"logical_identity": "/MAIN|C1", "part_number": "EXISTING-TARGET", "refdes": "C1", "hierarchy": "/MAIN", "units": 1, "origin": {"x": 1, "y": 1}, "position": {"x": 30, "y": 40}, "rotation": 0, "mirror": false, "pins": [{"number": "1", "name": "A", "net_identity": "N2", "x": 1, "y": 1}], "nets": ["N2"], "attributes": [], "parameter_probe": {}}
]
}
+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"
''')
@@ -0,0 +1,90 @@
from __future__ import annotations
import json
import os
from pathlib import Path
import subprocess
import sys
def test_build_files_target_only_repository_local_dx_part_replace_outputs() -> None:
"""Broad cleanup in the release script could delete a user's unrelated build output."""
root = Path(__file__).resolve().parents[2]
spec = root / "packaging" / "DxPartReplace.spec"
script = root / "packaging" / "Build-DxPartReplace.ps1"
assert spec.is_file()
assert script.is_file()
spec_text = spec.read_text(encoding="utf-8")
script_text = script.read_text(encoding="utf-8")
assert "name='DxPartReplace'" in spec_text
assert "console=False" in spec_text
assert "Resolve-Path -LiteralPath" in script_text
assert "build\\DxPartReplace" in script_text
assert "dist\\DxPartReplace" in script_text
assert "Remove-Item -LiteralPath" in script_text
assert "DxPartReplace.exe" in script_text
assert "QuickPartReplace.vbs" in spec_text
assert "legacy-runtime/dxdesigner795" in spec_text
assert '"viewdraw_api"' in spec_text
assert '"win32com.client"' in spec_text
assert '"pywinauto.controls.uiawrapper"' in spec_text
assert 'collect_data_files("PySide6")' not in spec_text
assert 'collect_dynamic_libs("PySide6")' not in spec_text
assert '"PySide6.QtWebEngineCore"' in spec_text
assert '"qt6quick.dll"' in spec_text
assert '"qpdf.dll"' in spec_text
assert "Get-FileHash" in script_text
assert "QuickPartReplace.vbs" in script_text
assert "packaged QuickPartReplace.vbs" in script_text
assert "--smoke-test" in script_text
assert "--data-root" in script_text
assert "DxPartReplace-smoke-" in script_text
assert "application_start" in script_text
assert "application_clean_shutdown" in script_text
assert "Start-Process -FilePath $executable" in script_text
assert "-Wait" in script_text
assert "-PassThru" in script_text
assert "-WindowStyle Hidden" in script_text
assert "$smokeProcess.ExitCode" in script_text
assert "$quotedSmokeRoot = '\"' + $smokeRoot + '\"'" in script_text
assert '"--data-root", $quotedSmokeRoot' in script_text
assert ".venv\\Scripts\\python.exe" in script_text
assert "DxPartReplace-preserved-data" in script_text
assert "Move-Item -LiteralPath $distData" in script_text
assert 'Join-Path (Split-Path -Parent $executable) "data"' in script_text
def test_start_process_argument_probe_preserves_a_spaced_data_root(tmp_path: Path) -> None:
"""Start-Process joins ArgumentList values, so the data-root value must carry its own quotes."""
probe = tmp_path / "probe.py"
output = tmp_path / "arguments.json"
smoke_root = tmp_path / "smoke root"
probe.write_text(
"import json, sys\nfrom pathlib import Path\nPath(sys.argv[1]).write_text(json.dumps(sys.argv[2:]))\n",
encoding="utf-8",
)
environment = os.environ | {
"SMOKE_ROOT": str(smoke_root),
"PROBE_SCRIPT": str(probe),
"PROBE_OUTPUT": str(output),
"PYTHON_EXE": sys.executable,
}
script = """
$quotedSmokeRoot = '"' + $env:SMOKE_ROOT + '"'
$quotedProbe = '"' + $env:PROBE_SCRIPT + '"'
$quotedOutput = '"' + $env:PROBE_OUTPUT + '"'
$probeProcess = Start-Process -FilePath $env:PYTHON_EXE -ArgumentList @($quotedProbe, $quotedOutput, "--data-root", $quotedSmokeRoot) -Wait -PassThru
exit $probeProcess.ExitCode
"""
completed = subprocess.run(
["powershell.exe", "-NoProfile", "-Command", script],
capture_output=True,
text=True,
env=environment,
check=False,
)
assert completed.returncode == 0, completed.stderr
assert json.loads(output.read_text(encoding="utf-8")) == ["--data-root", str(smoke_root)]
+637
View File
@@ -0,0 +1,637 @@
from dataclasses import replace
from decimal import Decimal
import json
from pathlib import Path
import pytest
from dx_productivity.part_replace.certification import (
CertificationError,
CertificationStore,
interface_fingerprint,
)
from dx_productivity.part_replace.models import (
ComponentSnapshot,
DesignSnapshot,
ExternalChecks,
MappingRule,
PinSnapshot,
UnitSnapshot,
)
from dx_productivity.part_replace.verification import verify_replacement
@pytest.fixture
def snapshots() -> tuple[DesignSnapshot, DesignSnapshot]:
before = DesignSnapshot(
format_version=2,
project_id="representative-project",
project_path="C:/Projects/trial.prj",
fingerprint="captured-before",
components=(
ComponentSnapshot(
logical_key="/MAIN|U1",
refdes="U1",
part_number="OLD-1",
attributes=(("manufacturer", "Acme"),),
units=(
UnitSnapshot(
unit_id=" A ", sheet="/MAIN", symbol="Library:AMP",
origin_x=Decimal("9.5"), origin_y=Decimal("19.5"),
x=Decimal("10"), y=Decimal("20"),
rotation=0, mirrored=False,
pins=(
PinSnapshot("1", "IN+", Decimal("10.25"), Decimal("20"), "NET-IN"),
PinSnapshot("2", "IN-", Decimal("10.5"), Decimal("20"), "NET-REF"),
),
),
),
),
),
)
after = replace(before, components=(replace(before.components[0], part_number="NEW-1"),))
return before, after
@pytest.fixture
def rule() -> MappingRule:
return MappingRule("OLD-1", "NEW-1")
@pytest.fixture
def verification(snapshots: tuple[DesignSnapshot, DesignSnapshot], rule: MappingRule):
before, after = snapshots
return verify_replacement(before, after, rule, ("/MAIN|U1",))
@pytest.fixture
def target_fingerprint(snapshots: tuple[DesignSnapshot, DesignSnapshot]) -> str:
_, after = snapshots
return interface_fingerprint(after, ("/MAIN|U1",))
@pytest.fixture
def store(
tmp_path: Path,
snapshots: tuple[DesignSnapshot, DesignSnapshot],
verification,
) -> CertificationStore:
before, after = snapshots
return CertificationStore(
tmp_path / "certifications.json",
before=before,
after=after,
verification=verification,
evidence_paths=("before.json", "after.json", "packager.txt", "erc.txt", "netlist.txt"),
)
@pytest.fixture
def certification(
store: CertificationStore,
rule: MappingRule,
target_fingerprint: str,
):
return store.record(
rule,
target_fingerprint,
"lib-r42",
ExternalChecks(packager=True, erc=True, netlist=True),
)
def test_certification_requires_hard_checks_and_external_checks(
store: CertificationStore,
rule: MappingRule,
target_fingerprint: str,
) -> None:
# Catches a record path that treats an omitted or false external result as success.
with pytest.raises(CertificationError, match="external_checks_incomplete"):
store.record(
rule,
target_fingerprint,
"lib-r42",
ExternalChecks(packager=True, erc=None, netlist=True),
)
with pytest.raises(CertificationError, match="external_checks_incomplete"):
store.record(
rule,
target_fingerprint,
"lib-r42",
ExternalChecks(packager=True, erc=False, netlist=True),
)
def test_changed_library_or_target_fingerprint_invalidates(
store: CertificationStore,
certification,
) -> None:
# Catches lookup that permits a certification after target or library drift.
with pytest.raises(CertificationError, match="certification_mismatch"):
store.require(certification.rule, "different-fingerprint", "lib-r42")
with pytest.raises(CertificationError, match="certification_mismatch"):
store.require(certification.rule, certification.target_fingerprint, "lib-r43")
def test_certification_round_trips_immutable_trial_evidence(
tmp_path: Path,
store: CertificationStore,
certification,
) -> None:
# Catches persistence that omits required immutable trial evidence or cannot be reopened.
reopened = CertificationStore(tmp_path / "certifications.json")
loaded = reopened.require(
certification.rule,
certification.target_fingerprint,
certification.library_identity,
)
assert loaded == certification
assert loaded.dxdesigner_build == "7.9.5"
assert loaded.evidence_paths == ("before.json", "after.json", "packager.txt", "erc.txt", "netlist.txt")
assert loaded.representative_project_fingerprint == "621b3eb72b9c1abecf3856103474c8675adb2857b33d8bd8cb9240a3070672be"
with pytest.raises((AttributeError, TypeError)):
loaded.target_fingerprint = "other" # type: ignore[misc]
assert (tmp_path / "certifications.json").read_text(encoding="utf-8").endswith("\n")
def test_interface_fingerprint_includes_only_observed_interface(
snapshots: tuple[DesignSnapshot, DesignSnapshot],
) -> None:
# Catches target identity that accidentally depends on project, Part Number, placement, nets, or attributes.
_, after = snapshots
component = after.components[0]
unit = component.units[0]
moved_component = _placed_occurrence(
component,
logical_key="/OTHER|X99",
refdes="X99",
x=Decimal("100"),
y=Decimal("200"),
rotation=270,
mirrored=True,
)
moved_unit = moved_component.units[0]
unrelated_change = replace(
after,
project_id="another-project",
project_path="D:/Other/board.prj",
fingerprint="different-snapshot",
components=(
replace(
moved_component,
part_number="DIFFERENT-PART",
attributes=(("vendor", "Other"),),
units=(
replace(
moved_unit,
pins=(
replace(moved_unit.pins[0], net="OTHER-NET"),
replace(moved_unit.pins[1], net="OTHER-NET-2"),
),
),
),
),
),
)
changed_interface = replace(
after,
components=(replace(component, units=(replace(unit, pins=(replace(unit.pins[0], name="INPUT+"), unit.pins[1])),)),),
)
expected = "decbaa0cd1cd8810b5900448a1da19f272c18639d7acc194fdc928a22cd55dc1"
assert interface_fingerprint(after, ("/MAIN|U1",)) == expected
assert interface_fingerprint(unrelated_change, ("/OTHER|X99",)) == expected
assert interface_fingerprint(changed_interface, ("/MAIN|U1",)) != expected
def _placed_occurrence(
component: ComponentSnapshot,
*,
logical_key: str,
refdes: str,
x: Decimal,
y: Decimal,
rotation: int,
mirrored: bool,
) -> ComponentSnapshot:
source = component.units[0]
def place(source_x: Decimal, source_y: Decimal) -> tuple[Decimal, Decimal]:
local_x = source_x - source.x
local_y = source_y - source.y
mirrored_x = -local_x if mirrored else local_x
angle = rotation % 360
if angle == 0:
offset_x, offset_y = mirrored_x, local_y
elif angle == 90:
offset_x, offset_y = -local_y, mirrored_x
elif angle == 180:
offset_x, offset_y = -mirrored_x, -local_y
elif angle == 270:
offset_x, offset_y = local_y, -mirrored_x
else:
raise AssertionError("test placement uses quarter-turn rotations")
return x + offset_x, y + offset_y
pins = tuple(
replace(pin, x=place(pin.x, pin.y)[0], y=place(pin.x, pin.y)[1])
for pin in source.pins
)
origin_x, origin_y = place(source.origin_x, source.origin_y)
unit = replace(
source,
origin_x=origin_x,
origin_y=origin_y,
x=x,
y=y,
rotation=rotation,
mirrored=mirrored,
pins=pins,
)
return replace(component, logical_key=logical_key, refdes=refdes, units=(unit,))
def test_interface_fingerprint_is_independent_of_occurrence_count_and_placement(
snapshots: tuple[DesignSnapshot, DesignSnapshot],
) -> None:
# Catches certification identities tied to project hit count or instance transforms.
_, after = snapshots
component = after.components[0]
occurrences = (
_placed_occurrence(
component,
logical_key="/MAIN|U1",
refdes="U1",
x=Decimal("10"),
y=Decimal("20"),
rotation=0,
mirrored=False,
),
_placed_occurrence(
component,
logical_key="/MAIN|U2",
refdes="U2",
x=Decimal("100"),
y=Decimal("200"),
rotation=90,
mirrored=False,
),
_placed_occurrence(
component,
logical_key="/MAIN|U3",
refdes="U3",
x=Decimal("-5"),
y=Decimal("30"),
rotation=270,
mirrored=True,
),
)
single = replace(after, components=(occurrences[0],))
repeated = replace(after, components=occurrences)
assert interface_fingerprint(single, ("/MAIN|U1",)) == interface_fingerprint(
repeated,
("/MAIN|U1", "/MAIN|U2", "/MAIN|U3"),
)
def test_interface_fingerprint_rejects_heterogeneous_selected_occurrences(
snapshots: tuple[DesignSnapshot, DesignSnapshot],
) -> None:
# Catches hashing unlike target interfaces into one occurrence-dependent certificate.
_, after = snapshots
first = after.components[0]
different = replace(
first,
logical_key="/MAIN|U2",
refdes="U2",
units=(
replace(
first.units[0],
pins=(replace(first.units[0].pins[0], name="DIFFERENT"), first.units[0].pins[1]),
),
),
)
heterogeneous = replace(after, components=(first, different))
with pytest.raises(CertificationError, match="heterogeneous_interface"):
interface_fingerprint(heterogeneous, ("/MAIN|U1", "/MAIN|U2"))
def test_certification_rejects_a_target_not_observed_in_the_trial(
store: CertificationStore,
rule: MappingRule,
) -> None:
# Catches record creation that accepts a caller-supplied fingerprint unrelated to the verified trial.
with pytest.raises(CertificationError, match="target_fingerprint_mismatch"):
store.record(
rule,
"not-the-observed-interface",
None,
ExternalChecks(packager=True, erc=True, netlist=True),
)
def test_certification_requires_a_passing_hard_verification(
tmp_path: Path,
snapshots: tuple[DesignSnapshot, DesignSnapshot],
verification,
rule: MappingRule,
target_fingerprint: str,
) -> None:
# Catches a record path that accepts external success after hard verification has failed.
before, after = snapshots
failed_trial = CertificationStore(
tmp_path / "certifications.json",
before=before,
after=after,
verification=replace(verification, passed=False),
)
with pytest.raises(CertificationError, match="hard_verification_failed"):
failed_trial.record(
rule,
target_fingerprint,
"lib-r42",
ExternalChecks(packager=True, erc=True, netlist=True),
)
def test_certification_without_library_identity_requires_exact_target(
store: CertificationStore,
rule: MappingRule,
target_fingerprint: str,
) -> None:
# Catches lookup that accepts a no-library certification when its observed target drifts.
store.record(
rule,
target_fingerprint,
None,
ExternalChecks(packager=True, erc=True, netlist=True),
)
with pytest.raises(CertificationError, match="certification_mismatch"):
store.require(rule, "different-fingerprint", None)
def test_interface_fingerprint_rejects_ambiguous_or_missing_selection(
snapshots: tuple[DesignSnapshot, DesignSnapshot],
) -> None:
# Catches an interface identity generated from duplicate or absent logical components.
_, after = snapshots
with pytest.raises(CertificationError, match="invalid_logical_keys"):
interface_fingerprint(after, ("/MAIN|U1", "/MAIN|U1"))
with pytest.raises(CertificationError, match="invalid_logical_keys"):
interface_fingerprint(after, ("/MAIN|MISSING",))
def test_corrupt_persisted_certification_blocks_apply(tmp_path: Path, rule: MappingRule) -> None:
# Catches Apply lookup that ignores malformed durable certification evidence.
path = tmp_path / "certifications.json"
path.write_text('{"format_version":1,"certifications":[{"old_part_number":"OLD-1"}]}', encoding="utf-8")
with pytest.raises(CertificationError, match="corrupt_certification"):
CertificationStore(path).require(rule, "target", "lib-r42")
@pytest.mark.parametrize(
"payload",
(
'{"format_version":1,"format_version":1,"certifications":[]}',
'{"format_version":2,"certifications":[]}',
'{"format_version":1,"certifications":{}}',
),
)
def test_corrupt_document_roots_fail_closed(tmp_path: Path, rule: MappingRule, payload: str) -> None:
# Catches Apply lookup that accepts duplicate, unsupported, or structurally invalid document roots.
path = tmp_path / "certifications.json"
path.write_text(payload, encoding="utf-8")
with pytest.raises(CertificationError, match="corrupt_certification"):
CertificationStore(path).require(rule, "target", None)
def test_certification_requires_complete_trial_context(
tmp_path: Path,
rule: MappingRule,
target_fingerprint: str,
) -> None:
# Catches record creation without the verified representative snapshots.
with pytest.raises(CertificationError, match="trial_context_missing"):
CertificationStore(tmp_path / "certifications.json").record(
rule,
target_fingerprint,
None,
ExternalChecks(packager=True, erc=True, netlist=True),
)
def test_certification_rejects_trial_project_mismatch(
tmp_path: Path,
snapshots: tuple[DesignSnapshot, DesignSnapshot],
verification,
rule: MappingRule,
target_fingerprint: str,
) -> None:
# Catches certification that binds a verification result to a different representative project.
before, after = snapshots
mismatched = CertificationStore(
tmp_path / "certifications.json",
before=before,
after=replace(after, project_id="other-project"),
verification=verification,
)
with pytest.raises(CertificationError, match="hard_verification_failed"):
mismatched.record(
rule,
target_fingerprint,
None,
ExternalChecks(packager=True, erc=True, netlist=True),
)
def test_interface_fingerprint_rejects_invalid_snapshot_and_blank_gate(
snapshots: tuple[DesignSnapshot, DesignSnapshot],
) -> None:
# Catches interface hashes created from a non-snapshot value or an empty normalized gate identity.
_, after = snapshots
with pytest.raises(CertificationError, match="invalid_snapshot"):
interface_fingerprint(object(), ("/MAIN|U1",)) # type: ignore[arg-type]
blank_gate = replace(after, components=(replace(after.components[0], units=(replace(after.components[0].units[0], unit_id=" "),)),))
with pytest.raises(CertificationError, match="invalid_interface"):
interface_fingerprint(blank_gate, ("/MAIN|U1",))
def test_record_rejects_invalid_mapping_target_library_and_evidence(
tmp_path: Path,
snapshots: tuple[DesignSnapshot, DesignSnapshot],
verification,
rule: MappingRule,
target_fingerprint: str,
) -> None:
# Catches durable certificates with missing identities or malformed evidence paths.
before, after = snapshots
store = CertificationStore(
tmp_path / "certifications.json",
before=before,
after=after,
verification=verification,
evidence_paths=("",),
)
checks = ExternalChecks(packager=True, erc=True, netlist=True)
with pytest.raises(CertificationError, match="invalid_mapping_rule"):
store.record(MappingRule("", "NEW-1"), target_fingerprint, None, checks)
with pytest.raises(CertificationError, match="invalid_target_fingerprint"):
store.record(rule, "", None, checks)
with pytest.raises(CertificationError, match="invalid_library_identity"):
store.record(rule, target_fingerprint, "", checks)
with pytest.raises(CertificationError, match="invalid_evidence_paths"):
store.record(rule, target_fingerprint, None, checks)
def test_certification_rejects_verification_forged_for_different_snapshots(
tmp_path: Path,
snapshots: tuple[DesignSnapshot, DesignSnapshot],
verification,
rule: MappingRule,
) -> None:
# Catches a passing result from a different snapshot pair minting a certificate.
before, after = snapshots
altered_after = replace(
after,
components=(
replace(
after.components[0],
units=(
replace(
after.components[0].units[0],
pins=(replace(after.components[0].units[0].pins[0], net="OTHER-NET"), after.components[0].units[0].pins[1]),
),
),
),
),
)
store = CertificationStore(
tmp_path / "certifications.json",
before=before,
after=altered_after,
verification=verification,
evidence_paths=("trial.txt",),
)
with pytest.raises(CertificationError, match="hard_verification_failed"):
store.record(
rule,
interface_fingerprint(altered_after, ("/MAIN|U1",)),
None,
ExternalChecks(packager=True, erc=True, netlist=True),
)
def test_certification_rejects_trial_with_empty_pin_observations(
tmp_path: Path,
snapshots: tuple[DesignSnapshot, DesignSnapshot],
rule: MappingRule,
) -> None:
# Catches certification when the trial has no observed pins for an expected unit.
before, after = snapshots
empty_before = replace(before, components=(replace(before.components[0], units=(replace(before.components[0].units[0], pins=()),)),))
empty_after = replace(after, components=(replace(after.components[0], units=(replace(after.components[0].units[0], pins=()),)),))
store = CertificationStore(
tmp_path / "certifications.json",
before=empty_before,
after=empty_after,
verification=verify_replacement(empty_before, empty_after, rule, ("/MAIN|U1",)),
evidence_paths=("trial.txt",),
)
with pytest.raises(CertificationError, match="invalid_interface"):
interface_fingerprint(empty_after, ("/MAIN|U1",))
with pytest.raises(CertificationError, match="trial_data_incomplete"):
store.record(
rule,
"unusable-target-interface",
None,
ExternalChecks(packager=True, erc=True, netlist=True),
)
def test_certification_rejects_trial_with_missing_network_identity(
tmp_path: Path,
snapshots: tuple[DesignSnapshot, DesignSnapshot],
rule: MappingRule,
) -> None:
# Catches certification when an expected pin lacks a network identity despite matching snapshots.
before, after = snapshots
no_net_before = replace(
before,
components=(replace(before.components[0], units=(replace(before.components[0].units[0], pins=(replace(before.components[0].units[0].pins[0], net=None), before.components[0].units[0].pins[1])),)),),
)
no_net_after = replace(
after,
components=(replace(after.components[0], units=(replace(after.components[0].units[0], pins=(replace(after.components[0].units[0].pins[0], net=None), after.components[0].units[0].pins[1])),)),),
)
store = CertificationStore(
tmp_path / "certifications.json",
before=no_net_before,
after=no_net_after,
verification=verify_replacement(no_net_before, no_net_after, rule, ("/MAIN|U1",)),
evidence_paths=("trial.txt",),
)
with pytest.raises(CertificationError, match="trial_data_incomplete"):
store.record(
rule,
interface_fingerprint(no_net_after, ("/MAIN|U1",)),
None,
ExternalChecks(packager=True, erc=True, netlist=True),
)
def test_certification_requires_nonempty_evidence_paths(
tmp_path: Path,
snapshots: tuple[DesignSnapshot, DesignSnapshot],
verification,
rule: MappingRule,
target_fingerprint: str,
) -> None:
# Catches record creation that treats an empty evidence-path collection as proof.
before, after = snapshots
store = CertificationStore(
tmp_path / "certifications.json",
before=before,
after=after,
verification=verification,
)
with pytest.raises(CertificationError, match="invalid_evidence_paths"):
store.record(
rule,
target_fingerprint,
None,
ExternalChecks(packager=True, erc=True, netlist=True),
)
@pytest.mark.parametrize("evidence_paths", ([], "trial.txt", {"path": "trial.txt"}))
def test_corrupt_certification_with_invalid_evidence_paths_blocks_apply(
tmp_path: Path,
store: CertificationStore,
certification,
evidence_paths: object,
) -> None:
# Catches Apply lookup that converts a non-array JSON evidence value into false proof.
path = tmp_path / "certifications.json"
document = json.loads(path.read_text(encoding="utf-8"))
document["certifications"][0]["evidence_paths"] = evidence_paths
path.write_text(json.dumps(document), encoding="utf-8")
with pytest.raises(CertificationError, match="corrupt_certification"):
store.require(
certification.rule,
certification.target_fingerprint,
certification.library_identity,
)
File diff suppressed because it is too large. Load diff
+69
View File
@@ -0,0 +1,69 @@
from __future__ import annotations
from copy import deepcopy
import pytest
from dx_productivity.part_replace.command_schema import command_data, command_from_data
from dx_productivity.part_replace.controller import ControllerError
from dx_productivity.part_replace.models import Scope
from dx_productivity.part_replace.protocol import BridgeCommand
def _command_document() -> dict[str, object]:
return {
"action": "replace_part",
"command_id": "a" * 32,
"expected_count": 2,
"expected_fingerprint": "f" * 64,
"expected_logical_keys": ["/MAIN|R1", "/MAIN|R2"],
"format_version": 1,
"job_id": "job-1",
"new_part_number": "NEW-1",
"old_part_number": "OLD-1",
"project_id": "project-1",
"scope": "full_project",
}
def test_command_codec_round_trips_the_exact_durable_schema() -> None:
expected = _command_document()
command = BridgeCommand(
format_version=1,
command_id="a" * 32,
action="replace_part",
job_id="job-1",
project_id="project-1",
scope=Scope.FULL_PROJECT,
old_part_number="OLD-1",
new_part_number="NEW-1",
expected_logical_keys=("/MAIN|R1", "/MAIN|R2"),
expected_count=2,
expected_fingerprint="f" * 64,
)
assert command_data(command) == expected
assert command_from_data(expected) == command
@pytest.mark.parametrize(
("field", "value", "message"),
(
("unexpected", 1, "fields"),
("format_version", True, "values"),
("scope", "selection", "scope"),
("command_id", "G" * 32, "values"),
),
)
def test_command_codec_rejects_noncanonical_durable_documents(
field: str,
value: object,
message: str,
) -> None:
document = deepcopy(_command_document())
document[field] = value
with pytest.raises(ControllerError, match=message) as captured:
command_from_data(document)
assert captured.value.code == "corrupt_publication"
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+189
View File
@@ -0,0 +1,189 @@
import hashlib
import os
from pathlib import Path
import pytest
from dx_productivity.part_replace.inputs import (
InputError,
discover_projects,
load_mapping,
load_projects,
)
from dx_productivity.part_replace.models import MappingRule, ProjectRef
def write(path: Path, text: str, *, encoding: str = "utf-8") -> Path:
path.write_text(text, encoding=encoding)
return path
def test_load_mapping_rejects_case_duplicate_chain_and_cycle(tmp_path: Path) -> None:
duplicate = write(tmp_path / "duplicate.csv", "old_part_number,new_part_number\nA,B\na,C\n")
with pytest.raises(InputError, match="duplicate_source"):
load_mapping(duplicate)
chain = write(tmp_path / "chain.csv", "old_part_number,new_part_number\nA,B\nB,C\n")
with pytest.raises(InputError, match="mapping_chain"):
load_mapping(chain)
cycle = write(tmp_path / "cycle.csv", "old_part_number,new_part_number\nA,B\nB,A\n")
with pytest.raises(InputError, match="mapping_cycle"):
load_mapping(cycle)
def test_load_mapping_accepts_utf8_bom_and_preserves_spelling(tmp_path: Path) -> None:
path = tmp_path / "替换.csv"
path.write_text(
"old_part_number,new_part_number\n old-01 , New-01 \n",
encoding="utf-8-sig",
)
assert load_mapping(path) == (MappingRule("old-01", "New-01"),)
def test_load_mapping_requires_exact_two_column_header_and_nonblank_values(tmp_path: Path) -> None:
for name, contents, code in (
(
"missing.csv",
"old_part_number\nA\n",
"mapping_header",
),
(
"extra.csv",
"old_part_number,new_part_number,comment\nA,B,note\n",
"mapping_header",
),
(
"blank.csv",
"old_part_number,new_part_number\n ,B\n",
"blank_part_number",
),
):
with pytest.raises(InputError, match=code):
load_mapping(write(tmp_path / name, contents))
def test_load_mapping_accepts_named_columns_in_either_order_but_rejects_extra_row_values(
tmp_path: Path,
) -> None:
reversed_header = write(
tmp_path / "reversed.csv",
"new_part_number,old_part_number\nB,A\n",
)
assert load_mapping(reversed_header) == (MappingRule("A", "B"),)
extra_value = write(
tmp_path / "extra-value.csv",
"old_part_number,new_part_number\nA,B,unexpected\n",
)
with pytest.raises(InputError, match="mapping_columns"):
load_mapping(extra_value)
def test_load_mapping_rejects_case_insensitive_equal_rule_before_graph_checks(tmp_path: Path) -> None:
path = write(tmp_path / "equal.csv", "old_part_number,new_part_number\n Part-A , part-a \n")
with pytest.raises(InputError, match="equal_rule"):
load_mapping(path)
def test_load_mapping_reports_chain_for_graph_larger_than_recursion_limit(tmp_path: Path) -> None:
rows = ["old_part_number,new_part_number"]
rows.extend(f"P{index},P{index + 1}" for index in range(1_200))
path = write(tmp_path / "long-chain.csv", "\n".join(rows) + "\n")
with pytest.raises(InputError, match="mapping_chain"):
load_mapping(path)
def test_load_mapping_reports_cycle_for_graph_larger_than_recursion_limit(tmp_path: Path) -> None:
rows = ["old_part_number,new_part_number"]
rows.extend(f"P{index},P{index + 1}" for index in range(1_199))
rows.append("P1199,P1")
path = write(tmp_path / "long-cycle.csv", "\n".join(rows) + "\n")
with pytest.raises(InputError, match="mapping_cycle"):
load_mapping(path)
def test_load_projects_ignores_comments_and_builds_stable_refs(tmp_path: Path) -> None:
project = tmp_path / "设计.PRJ"
project.write_text("project definition", encoding="utf-8")
list_path = write(
tmp_path / "projects.txt",
f"\n# operator comment\n {project} \n",
)
canonical = project.resolve()
normalized = os.path.normcase(str(canonical))
expected_id = hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:16]
assert load_projects(list_path, (".prj",)) == (
ProjectRef(expected_id, str(canonical), "设计"),
)
def test_load_projects_rejects_relative_missing_directory_suffix_and_duplicate(tmp_path: Path) -> None:
project = tmp_path / "one.prj"
project.write_text("project definition", encoding="utf-8")
(tmp_path / "one.txt").write_text("not a project", encoding="utf-8")
cases = (
("relative.prj\n", "project_path_not_absolute"),
(f"{tmp_path / 'missing.prj'}\n", "project_not_found"),
(f"{tmp_path}\n", "project_not_file"),
(f"{tmp_path / 'one.txt'}\n", "unsupported_project_suffix"),
)
for contents, code in cases:
with pytest.raises(InputError, match=code):
load_projects(write(tmp_path / f"{code}.txt", contents), (".prj",))
duplicate_list = write(tmp_path / "duplicates.txt", f"{project}\n{project.resolve()}\n")
with pytest.raises(InputError, match="duplicate_project"):
load_projects(duplicate_list, (".prj",))
def test_load_projects_accepts_suffix_case_insensitively_and_resolves_paths(tmp_path: Path) -> None:
project = tmp_path / "sub" / "Board.PrJ"
project.parent.mkdir()
project.write_text("project definition", encoding="utf-8")
listed = tmp_path / "projects.txt"
write(listed, f"{project}\n")
result = load_projects(listed, (".PRJ",))
assert result[0].project_path == str(project.resolve())
assert result[0].display_name == "Board"
@pytest.mark.parametrize("nested", (False, True), ids=("same-root", "nested-root"))
def test_load_projects_rejects_overlapping_project_ownership_roots(
tmp_path: Path,
nested: bool,
) -> None:
# Catches one project's backup or restore tree containing another project marker.
first_root = tmp_path / "projects" / "first"
second_root = first_root / "nested" if nested else first_root
second_root.mkdir(parents=True)
first = first_root / "first.prj"
second = second_root / "second.prj"
first.write_text("first\n", encoding="utf-8")
second.write_text("second\n", encoding="utf-8")
projects = tmp_path / "projects.txt"
projects.write_text(f"{first.resolve()}\n{second.resolve()}\n", encoding="utf-8")
with pytest.raises(InputError, match="overlapping_project_roots"):
load_projects(projects, (".prj",))
def test_discover_projects_returns_sorted_unique_canonical_candidates_without_writing(tmp_path: Path) -> None:
root = tmp_path / "设计"
(root / "z").mkdir(parents=True)
(root / "a").mkdir()
first = root / "z" / "B.PRJ"
second = root / "a" / "a.prj"
ignored = root / "a" / "notes.txt"
first.write_text("project", encoding="utf-8")
second.write_text("project", encoding="utf-8")
ignored.write_text("ignored", encoding="utf-8")
discovered = discover_projects(root, (".prj",))
expected = tuple(sorted((first.resolve(), second.resolve()), key=lambda path: str(path).casefold()))
assert discovered == expected
assert not (root / "projects.txt").exists()
+75
View File
@@ -0,0 +1,75 @@
from dataclasses import FrozenInstanceError
from decimal import Decimal
import pytest
from dx_productivity.part_replace.models import (
ComponentSnapshot,
DesignSnapshot,
Issue,
MappingRule,
PinSnapshot,
ProjectState,
Scope,
UnitSnapshot,
)
def test_snapshot_model_is_immutable_and_decimal_exact() -> None:
pin = PinSnapshot(number="1", name="A", x=Decimal("10.25"), y=Decimal("20"), net="N$1")
unit = UnitSnapshot(
unit_id="u1", sheet="/MAIN", symbol="res.1",
origin_x=Decimal("0"), origin_y=Decimal("0"), x=Decimal("0"),
y=Decimal("0"), rotation=0, mirrored=False, pins=(pin,),
)
component = ComponentSnapshot(logical_key="/MAIN|R1", refdes="R1",
part_number="OLD-1", units=(unit,), attributes=())
snapshot = DesignSnapshot(format_version=2, project_id="p1", project_path="C:/P/a.prj",
fingerprint="abc", components=(component,))
with pytest.raises(FrozenInstanceError):
snapshot.project_id = "p2" # type: ignore[misc]
assert snapshot.components[0].units[0].pins[0].x == Decimal("10.25")
def test_unit_keeps_origin_coordinates_distinct_from_position() -> None:
# Catches collapsing the symbol origin into the placed x/y coordinates.
unit = UnitSnapshot(
unit_id="u1",
sheet="/MAIN",
symbol="res.1",
origin_x=Decimal("1.25"),
origin_y=Decimal("2.5"),
x=Decimal("100"),
y=Decimal("200"),
rotation=0,
mirrored=False,
)
assert (unit.origin_x, unit.origin_y, unit.x, unit.y) == (
Decimal("1.25"),
Decimal("2.5"),
Decimal("100"),
Decimal("200"),
)
def test_state_and_scope_values_are_protocol_stable() -> None:
assert Scope.FULL_PROJECT.value == "full_project"
assert ProjectState.AWAITING_SAVE_CONFIRMATION.value == "awaiting_save_confirmation"
assert MappingRule("OLD", "NEW").old_part_number == "OLD"
def test_nested_records_are_normalized_to_immutable_sorted_tuples() -> None:
snapshot = ComponentSnapshot(
logical_key="k", refdes="R1", part_number="P",
units=[], attributes={"z": "2", "a": "1"},
)
assert snapshot.units == ()
assert snapshot.attributes == (("a", "1"), ("z", "2"))
def test_issue_details_do_not_retain_mutable_inner_entries() -> None:
issue = Issue("bad", "blocking", "Invalid data", [["field", "value"]]) # type: ignore[arg-type]
assert issue.details == (("field", "value"),)
with pytest.raises(TypeError):
issue.details[0][0] = "changed" # type: ignore[index]
+356
View File
@@ -0,0 +1,356 @@
from dataclasses import fields, replace
from decimal import Decimal
import json
from pathlib import Path
import pytest
from dx_productivity.part_replace.models import (
ComponentSnapshot,
DesignSnapshot,
PinSnapshot,
Scope,
UnitSnapshot,
)
from dx_productivity.part_replace.protocol import (
BridgeCommand,
BridgeStatus,
ProtocolError,
atomic_write_text,
load_snapshot,
load_status,
snapshot_fingerprint,
write_command,
write_snapshot,
)
FIXTURES = Path(__file__).parents[1] / "fixtures"
@pytest.fixture
def before_snapshot() -> DesignSnapshot:
return DesignSnapshot(
format_version=2,
project_id="project-1",
project_path="C:/Projects/board.prj",
fingerprint="stored-before-fingerprint",
components=(
ComponentSnapshot(
logical_key="/MAIN|R1",
refdes="R1",
part_number="OLD-1",
attributes=(("tolerance", "1%"), ("vendor", "Acme")),
units=(
UnitSnapshot(
unit_id="A",
sheet="/MAIN",
symbol="RES",
origin_x=Decimal("-0.5"),
origin_y=Decimal("-0.5"),
x=Decimal("0"),
y=Decimal("0"),
rotation=0,
mirrored=False,
pins=(
PinSnapshot("1", "A", Decimal("10.25"), Decimal("20"), "N$1"),
PinSnapshot("2", "B", Decimal("11"), Decimal("20"), None),
),
),
),
),
),
)
def load_fixture(name: str) -> DesignSnapshot:
return load_snapshot(FIXTURES / name)
def test_snapshot_v2_requires_and_round_trips_distinct_origin_coordinates(
tmp_path: Path,
) -> None:
# Catches a bridge snapshot that reads OriginX/Y but drops them in serialization.
path = tmp_path / "snapshot-v2.json"
path.write_text(
'{"components":[{"attributes":[],"logical_key":"/MAIN|U1",'
'"part_number":"OLD-1","refdes":"U1","units":[{"mirrored":false,'
'"origin_x":"1.25","origin_y":"2.5","pins":[],"rotation":0,'
'"sheet":"/MAIN","symbol":"IC","unit_id":"A","x":"100",'
'"y":"200"}]}],"fingerprint":"stored","format_version":2,'
'"project_id":"p1","project_path":"C:/Projects/board.prj"}',
encoding="utf-8",
)
snapshot = load_snapshot(path)
unit = snapshot.components[0].units[0]
assert (unit.origin_x, unit.origin_y, unit.x, unit.y) == (
Decimal("1.25"),
Decimal("2.5"),
Decimal("100"),
Decimal("200"),
)
output = tmp_path / "round-trip.json"
write_snapshot(output, snapshot)
assert load_snapshot(output) == snapshot
def test_snapshot_v1_is_explicitly_rejected_as_missing_origin_evidence(
tmp_path: Path,
) -> None:
# A v1 snapshot cannot be migrated safely because it never recorded unit origin.
path = tmp_path / "legacy-v1.json"
path.write_text(
'{"components":[],"fingerprint":"stored","format_version":1,'
'"project_id":"p1","project_path":"C:/Projects/board.prj"}',
encoding="utf-8",
)
with pytest.raises(ProtocolError) as raised:
load_snapshot(path)
assert raised.value.code == "legacy_snapshot_missing_origin"
def test_snapshot_fixture_has_independently_checked_content(before_snapshot: DesignSnapshot) -> None:
loaded = load_fixture("snapshot-before.json")
assert loaded == before_snapshot
assert loaded.components[0].units[0].pins[0].x == Decimal("10.25")
assert loaded.components[0].units[0].pins[1].net is None
def test_snapshot_round_trip_is_canonical(tmp_path: Path, before_snapshot: DesignSnapshot) -> None:
output = tmp_path / "snapshot.json"
write_snapshot(output, before_snapshot)
assert output.read_text(encoding="utf-8") == (
'{"components":[{"attributes":[{"name":"tolerance","value":"1%"},'
'{"name":"vendor","value":"Acme"}],"logical_key":"/MAIN|R1",'
'"part_number":"OLD-1","refdes":"R1","units":[{"mirrored":false,'
'"origin_x":"-0.5","origin_y":"-0.5",'
'"pins":[{"name":"A","net":"N$1","number":"1","x":"10.25",'
'"y":"20"},{"name":"B","net":null,"number":"2","x":"11",'
'"y":"20"}],"rotation":0,"sheet":"/MAIN","symbol":"RES",'
'"unit_id":"A","x":"0","y":"0"}]}],'
'"fingerprint":"stored-before-fingerprint","format_version":2,'
'"project_id":"project-1","project_path":"C:/Projects/board.prj"}\n'
)
loaded = load_snapshot(output)
assert loaded == before_snapshot
assert snapshot_fingerprint(loaded) == snapshot_fingerprint(before_snapshot)
assert not list(tmp_path.glob("*.tmp"))
def test_snapshot_fingerprint_excludes_only_stored_fingerprint(before_snapshot: DesignSnapshot) -> None:
assert snapshot_fingerprint(before_snapshot) == "f89a844afe0e47a733dcd4060a854dda7bcfe53fd9acea810b4aebd3ccfdb914"
assert snapshot_fingerprint(replace(before_snapshot, fingerprint="different")) == (
"f89a844afe0e47a733dcd4060a854dda7bcfe53fd9acea810b4aebd3ccfdb914"
)
assert snapshot_fingerprint(replace(before_snapshot, project_path="C:/Projects/other.prj")) != (
"f89a844afe0e47a733dcd4060a854dda7bcfe53fd9acea810b4aebd3ccfdb914"
)
def test_after_snapshot_fixtures_preserve_or_change_the_expected_pin() -> None:
compatible = load_fixture("snapshot-after-compatible.json")
changed = load_fixture("snapshot-after-pin-change.json")
assert compatible.components[0].part_number == "NEW-1"
assert compatible.components[0].units[0].pins[1].number == "2"
assert changed.components[0].units[0].pins[1].number == "3"
@pytest.mark.parametrize(
("payload", "code"),
(
('{"format_version":3}', "unsupported_format_version"),
('{"format_version":2}', "missing_required_field"),
('{"format_version":true,"project_id":"p","project_path":"x","fingerprint":"f","components":[]}', "wrong_type"),
('{"format_version":2,"project_id":"p","project_path":"x","fingerprint":"f","components":[],"extra":null}', "unknown_field"),
),
)
def test_snapshot_schema_is_fail_closed(tmp_path: Path, payload: str, code: str) -> None:
path = tmp_path / "invalid.json"
path.write_text(payload, encoding="utf-8")
with pytest.raises(ProtocolError, match=code):
load_snapshot(path)
@pytest.mark.parametrize(
("components", "code"),
(
(
'[{"logical_key":"k","refdes":"R1","part_number":"P","attributes":[],"units":[]},'
'{"logical_key":"k","refdes":"R2","part_number":"P","attributes":[],"units":[]}]',
"duplicate_logical_key",
),
(
'[{"logical_key":"k","refdes":"R1","part_number":"P","attributes":[],"units":['
'{"unit_id":"A","sheet":"/","symbol":"X","origin_x":"0","origin_y":"0","x":"0","y":"0","rotation":0,"mirrored":false,"pins":[]},'
'{"unit_id":"A","sheet":"/","symbol":"Y","origin_x":"0","origin_y":"0","x":"0","y":"0","rotation":0,"mirrored":false,"pins":[]}]}]',
"duplicate_unit_id",
),
(
'[{"logical_key":"k","refdes":"R1","part_number":"P","attributes":[],"units":['
'{"unit_id":"A","sheet":"/","symbol":"X","origin_x":"0","origin_y":"0","x":"0","y":"0","rotation":0,"mirrored":false,"pins":['
'{"number":"1","name":"A","x":"0","y":"0","net":null},'
'{"number":"1","name":"B","x":"1","y":"0","net":null}]}]}]',
"duplicate_pin_number",
),
),
)
def test_snapshot_rejects_duplicate_structural_keys(tmp_path: Path, components: str, code: str) -> None:
path = tmp_path / "duplicates.json"
path.write_text(
'{"format_version":2,"project_id":"p","project_path":"x","fingerprint":"f","components":' + components + '}',
encoding="utf-8",
)
with pytest.raises(ProtocolError, match=code):
load_snapshot(path)
def test_pin_number_can_repeat_in_different_units(tmp_path: Path) -> None:
path = tmp_path / "separate-units.json"
path.write_text(
'{"format_version":2,"project_id":"p","project_path":"x","fingerprint":"f","components":['
'{"logical_key":"k","refdes":"R1","part_number":"P","attributes":[],"units":['
'{"unit_id":"A","sheet":"/","symbol":"X","origin_x":"0","origin_y":"0","x":"0","y":"0","rotation":0,"mirrored":false,"pins":[{"number":"1","name":"A","x":"0","y":"0","net":null}]},'
'{"unit_id":"B","sheet":"/","symbol":"Y","origin_x":"0","origin_y":"0","x":"0","y":"0","rotation":0,"mirrored":false,"pins":[{"number":"1","name":"B","x":"0","y":"0","net":null}]}]}]}',
encoding="utf-8",
)
assert tuple(unit.unit_id for unit in load_snapshot(path).components[0].units) == ("A", "B")
def test_command_is_immutable_has_exact_fields_and_writes_canonical_json(tmp_path: Path) -> None:
command = BridgeCommand(
1, "cmd-7", "replace_part", "job-2", "project-1", Scope.FULL_PROJECT,
"OLD-1", "NEW-1", ("/MAIN|R2", "/MAIN|R1"), 2, "fingerprint-1",
)
output = tmp_path / "command.json"
write_command(output, command)
assert tuple(field.name for field in fields(BridgeCommand)) == (
"format_version", "command_id", "action", "job_id", "project_id", "scope",
"old_part_number", "new_part_number", "expected_logical_keys", "expected_count",
"expected_fingerprint",
)
assert output.read_text(encoding="utf-8") == (
'{"action":"replace_part","command_id":"cmd-7","expected_count":2,'
'"expected_fingerprint":"fingerprint-1","expected_logical_keys":["/MAIN|R2","/MAIN|R1"],'
'"format_version":1,"job_id":"job-2","new_part_number":"NEW-1",'
'"old_part_number":"OLD-1","project_id":"project-1","scope":"full_project"}\n'
)
def test_snapshot_writer_rejects_boolean_format_version(tmp_path: Path, before_snapshot: DesignSnapshot) -> None:
with pytest.raises(ProtocolError, match="wrong_type"):
write_snapshot(tmp_path / "snapshot.json", replace(before_snapshot, format_version=True)) # type: ignore[arg-type]
@pytest.mark.parametrize(
("invalid_snapshot", "code"),
(
(
lambda snapshot: replace(
snapshot,
components=(snapshot.components[0], replace(snapshot.components[0], refdes="R2")),
),
"duplicate_logical_key",
),
(
lambda snapshot: replace(
snapshot,
components=(
replace(
snapshot.components[0],
units=(
snapshot.components[0].units[0],
replace(snapshot.components[0].units[0], symbol="ALT"),
),
),
),
),
"duplicate_unit_id",
),
(
lambda snapshot: replace(
snapshot,
components=(
replace(
snapshot.components[0],
units=(
replace(
snapshot.components[0].units[0],
pins=(
snapshot.components[0].units[0].pins[0],
replace(snapshot.components[0].units[0].pins[0], name="Duplicate"),
),
),
),
),
),
),
"duplicate_pin_number",
),
(
lambda snapshot: replace(
snapshot,
components=(
replace(
snapshot.components[0],
units=(
object(), # type: ignore[arg-type]
),
),
),
),
"wrong_type",
),
),
)
def test_snapshot_publication_and_fingerprinting_reject_invalid_models(
tmp_path: Path,
before_snapshot: DesignSnapshot,
invalid_snapshot: object,
code: str,
) -> None:
snapshot = invalid_snapshot(before_snapshot) # type: ignore[operator]
output = tmp_path / "invalid-snapshot.json"
with pytest.raises(ProtocolError, match=code):
write_snapshot(output, snapshot)
assert not output.exists()
with pytest.raises(ProtocolError, match=code):
snapshot_fingerprint(snapshot)
def test_status_parsing_is_immutable_and_fail_closed(tmp_path: Path) -> None:
path = tmp_path / "status.json"
path.write_text(
'{"command_id":"cmd-7","details":[["phase","apply"]],"error_code":null,'
'"error_message":null,"format_version":1,"project_id":"project-1",'
'"snapshot_path":"C:/Run/after.json","state":"completed"}',
encoding="utf-8",
)
assert load_status(path) == BridgeStatus(
1, "cmd-7", "project-1", "completed", "C:/Run/after.json", None, None,
(("phase", "apply"),),
)
path.write_text(
'{"command_id":"cmd-7","details":[],"error_code":null,"error_message":null,'
'"format_version":1,"project_id":"project-1","snapshot_path":null,"state":"completed","extra":0}',
encoding="utf-8",
)
with pytest.raises(ProtocolError, match="unknown_field"):
load_status(path)
def test_atomic_write_normalizes_newlines_and_cleans_up_after_replace_failure(tmp_path: Path) -> None:
output = tmp_path / "mailbox.txt"
atomic_write_text(output, "first\r\nsecond\rthird\n")
assert output.read_bytes() == b"first\nsecond\nthird\n"
target_directory = tmp_path / "target-directory"
target_directory.mkdir()
with pytest.raises(OSError):
atomic_write_text(target_directory, "cannot replace a directory")
assert not list(tmp_path.glob("*.tmp"))
+191
View File
@@ -0,0 +1,191 @@
from __future__ import annotations
from pathlib import Path
from dx_productivity.part_replace.certification import Certification
from dx_productivity.part_replace.models import (
ExternalChecks,
ImpactCell,
Issue,
MappingRule,
ProjectState,
VerificationResult,
)
from dx_productivity.part_replace.reports import (
BatchReport,
write_differences_json,
write_impact_csv,
write_summary_html,
)
RULE = MappingRule("OLD-1", "NEW-1")
def _report(*states: ProjectState, old_part_number: str = "OLD-1") -> BatchReport:
rule = MappingRule(old_part_number, "NEW-1")
result = VerificationResult(
project_id="project-a",
rule=rule,
expected_logical_keys=("/MAIN|R1",),
changed_logical_keys=("/MAIN|R1",),
issues=(
Issue("connectivity_changed", "error", "Pin 1 net changed"),
Issue("library_attribute_changed", "info", "Value updated"),
),
passed=False,
)
return BatchReport(
job_id="job-42",
generated_time="2026-09-02T01:02:03Z",
input_hashes={"job.json": "abc123", "events.jsonl": "def456"},
project_states={f"project-{index}": state for index, state in enumerate(states, start=1)},
impact_cells=(ImpactCell("project-a", rule, 1, 2),),
verification_results=(result,),
external_checks={"project-a": ExternalChecks(packager=True, erc=None, netlist=False)},
certifications=(
Certification(
created_utc="2026-09-01T00:00:00Z",
dxdesigner_build="7.9.5",
rule=rule,
target_fingerprint="target-fingerprint",
library_identity="library-r42",
representative_project_fingerprint="trial-fingerprint",
evidence_paths=("before.json", "after.json"),
),
),
backup_path="C:/Backups/job-42",
resume_action="Reconcile blocked projects before continuing.",
advisory_attachments=("ai-review.json",),
)
def test_html_report_escapes_part_numbers_and_has_no_remote_content(tmp_path: Path) -> None:
# Catches direct interpolation that lets a part number create executable or remote HTML.
output = tmp_path / "report.html"
write_summary_html(output, _report(ProjectState.BLOCKED, old_part_number='<script src="https://x">'))
text = output.read_text(encoding="utf-8")
assert "&lt;script" in text
assert "https://x" not in text
assert "<script" not in text.casefold()
def test_partial_batch_never_renders_as_success(tmp_path: Path) -> None:
# Catches summary status derived from one verified project while another project is blocked.
output = tmp_path / "report.html"
write_summary_html(output, _report(ProjectState.VERIFIED_SAVED, ProjectState.BLOCKED))
text = output.read_text(encoding="utf-8")
assert "PARTIAL" in text
assert "BATCH STATUS: SUCCESS" not in text
def test_ai_review_artifact_cannot_change_verified_state(tmp_path: Path) -> None:
# Catches an advisory file being treated as approval that overrides event-derived project state.
report = _report(ProjectState.BLOCKED)
(tmp_path / "ai-review.json").write_text('{"recommendation":"approve"}', encoding="utf-8")
output = tmp_path / "report.html"
write_summary_html(output, report)
text = output.read_text(encoding="utf-8")
assert "BLOCKED" in text
assert "Advisory attachments" in text
def test_html_summary_shows_required_operator_evidence(tmp_path: Path) -> None:
# Catches a summary that omits evidence an operator needs to audit or resume a batch.
output = tmp_path / "report.html"
write_summary_html(output, _report(ProjectState.BLOCKED))
text = output.read_text(encoding="utf-8")
for value in (
"job-42",
"2026-09-02T01:02:03Z",
"abc123",
"project-1",
"OLD-1",
"connectivity_changed",
"library_attribute_changed",
"packager: PASS",
"target-fingerprint",
"C:/Backups/job-42",
"Reconcile blocked projects before continuing.",
):
assert value in text
def test_html_summary_includes_escaped_hard_impact_issue_with_mapping_context(tmp_path: Path) -> None:
# Catches hard inventory or mapping findings being omitted when no verification result carries an error.
output = tmp_path / "report.html"
rule = MappingRule(" OLD-IMPACT ", " NEW-IMPACT ")
report = BatchReport(
job_id="job-impact",
generated_time="2026-09-02T01:02:03Z",
project_states={"project-impact": ProjectState.BLOCKED},
impact_cells=(
ImpactCell(
"project-impact",
rule,
0,
0,
(Issue("inventory_identity_ambiguous", "error", "Ambiguous <inventory> identity"),),
),
),
)
write_summary_html(output, report)
hard_issues = output.read_text(encoding="utf-8").split("<h2>Hard issues</h2>", 1)[1].split(
"<h2>Nonblocking attribute differences</h2>", 1
)[0]
assert "project-impact" in hard_issues
assert " OLD-IMPACT " in hard_issues
assert " NEW-IMPACT " in hard_issues
assert "inventory_identity_ambiguous" in hard_issues
assert "Ambiguous &lt;inventory&gt; identity" in hard_issues
def test_impact_csv_keeps_original_part_number_spelling_and_counts(tmp_path: Path) -> None:
# Catches report formatting that normalizes a user-supplied mapping identity or drops unit counts.
output = tmp_path / "impact.csv"
cells = (
ImpactCell("project-z", MappingRule(" old-1 ", " NEW-1 "), 2, 3),
)
write_impact_csv(output, cells)
assert output.read_text(encoding="utf-8") == (
"project_id,old_part_number,new_part_number,logical_count,unit_count,issues\n"
"project-z, old-1 , NEW-1 ,2,3,\n"
)
def test_differences_json_is_canonical_and_separates_hard_and_nonblocking_issues(tmp_path: Path) -> None:
# Catches noncanonical report JSON or a severity filter that hides informational attribute differences.
output = tmp_path / "differences.json"
result = VerificationResult(
project_id="project-a",
rule=RULE,
expected_logical_keys=("/MAIN|R1",),
changed_logical_keys=("/MAIN|R1",),
issues=(
Issue("library_attribute_changed", "info", "Value updated", (("attribute", "value"),)),
Issue("connectivity_changed", "error", "Pin 1 net changed"),
),
passed=False,
)
write_differences_json(output, (result,))
assert output.read_text(encoding="utf-8") == (
'{"results":[{"changed_logical_keys":["/MAIN|R1"],"expected_logical_keys":["/MAIN|R1"],"hard_issues"'
':[{"code":"connectivity_changed","details":{},"message":"Pin 1 net changed","severity":"error"}]'
',"new_part_number":"NEW-1","nonblocking_differences"'
':[{"code":"library_attribute_changed","details":{"attribute":"value"},"message":"Value updated","severity":"info"}]'
',"old_part_number":"OLD-1","passed":false,"project_id":"project-a"}]}\n'
)
+972
View File
@@ -0,0 +1,972 @@
from __future__ import annotations
from dataclasses import replace
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import time
import pytest
from dx_productivity.part_replace.models import MappingRule, ProjectRef, ProjectState
from dx_productivity.part_replace.run_store import (
BackupError,
RunStore,
StateError,
backup_project,
fingerprint_tree,
restore_project,
verify_tree,
)
import dx_productivity.part_replace.run_store as run_store_module
@pytest.fixture
def project(tmp_path: Path) -> Path:
root = tmp_path / "工程"
(root / "design" / "空").mkdir(parents=True)
(root / "design" / "main.sch").write_bytes(b"schematic")
(root / "readme.txt").write_text("unicode: 工程\n", encoding="utf-8")
return root
@pytest.fixture
def run_store(tmp_path: Path, project: Path) -> RunStore:
return RunStore.create(
tmp_path / "run",
(MappingRule("OLD-1", "NEW-1"),),
(ProjectRef("p1", str(project), "工程"),),
)
def _advance_to_verified(store: RunStore) -> None:
for state in (
ProjectState.INVENTORY_COMPLETE,
ProjectState.APPLY_PENDING,
ProjectState.APPLYING,
ProjectState.AWAITING_SAVE_CONFIRMATION,
ProjectState.AWAITING_EXTERNAL_CHECKS,
ProjectState.VERIFIED_SAVED,
):
store.transition("p1", state)
def _make_changed_project_and_backup(tmp_path: Path) -> tuple[Path, Path, object]:
project = tmp_path / "project"
project.mkdir()
(project / "main.sch").write_bytes(b"original")
backup = tmp_path / "backup"
manifest = backup_project(project, backup)
(project / "main.sch").write_bytes(b"failed change")
(project / "new.tmp").write_bytes(b"new")
return project, backup, manifest
def test_invalid_state_transition_is_rejected(run_store: RunStore) -> None:
with pytest.raises(StateError, match="invalid_transition"):
run_store.transition("p1", ProjectState.VERIFIED_SAVED)
def test_valid_transitions_replay_and_verified_saved_is_terminal(
run_store: RunStore,
) -> None:
_advance_to_verified(run_store)
reopened = RunStore(run_store.root)
assert reopened.project_state("p1") is ProjectState.VERIFIED_SAVED
with pytest.raises(StateError, match="invalid_transition"):
reopened.transition("p1", ProjectState.BLOCKED)
def test_blocked_requires_explicit_durable_reconcile_event(
run_store: RunStore,
) -> None:
run_store.transition("p1", ProjectState.BLOCKED)
with pytest.raises(StateError, match="reconcile_required"):
run_store.transition("p1", ProjectState.INVENTORY_PENDING)
run_store.append_event("p1", "reconcile", {"reason": "operator_review"})
assert RunStore(run_store.root).project_state("p1") is ProjectState.INVENTORY_PENDING
def test_no_changes_required_is_a_durable_direct_completion_event(run_store: RunStore) -> None:
# Catches no-op projects being forced through fake Apply/save/check transitions or left pending.
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
run_store.complete_no_changes("p1")
assert run_store.project_state("p1") is ProjectState.VERIFIED_SAVED
assert RunStore(run_store.root).project_state("p1") is ProjectState.VERIFIED_SAVED
record = json.loads((run_store.root / "events.jsonl").read_text(encoding="utf-8").splitlines()[-1])
assert record["event"] == "no_changes_required"
assert record["payload"] == {}
assert record["prior_state"] == "inventory_complete"
assert record["target_state"] == "verified_saved"
def test_no_changes_required_rejects_non_inventory_complete_and_reserved_spoofing(run_store: RunStore) -> None:
# Catches the special no-op event bypassing inventory/impact review.
with pytest.raises(StateError, match="invalid_transition"):
run_store.complete_no_changes("p1")
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
for payload in ({}, {"unexpected": True}):
with pytest.raises(StateError, match="invalid_event"):
run_store.append_event("p1", "no_changes_required", payload)
@pytest.mark.parametrize(
("field", "value"),
(
("prior_state", "apply_pending"),
("target_state", "apply_pending"),
("payload", {"unexpected": True}),
),
)
def test_replay_rejects_invalid_no_change_event_shape(
run_store: RunStore,
field: str,
value: object,
) -> None:
# Catches tampered no-op events replaying from the wrong state, target, or payload.
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
run_store.complete_no_changes("p1")
event_path = run_store.root / "events.jsonl"
records = [json.loads(line) for line in event_path.read_text(encoding="utf-8").splitlines()]
records[-1][field] = value
event_path.write_text(
"".join(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n" for record in records),
encoding="utf-8",
)
with pytest.raises(StateError, match="corrupt_event_log"):
RunStore(run_store.root)
def test_events_are_canonical_contiguous_jsonl_with_utc_timestamps(
run_store: RunStore,
) -> None:
run_store.append_event("p1", "inventory_observed", {"fingerprint": "雪"})
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
lines = (run_store.root / "events.jsonl").read_text(encoding="utf-8").splitlines()
records = [json.loads(line) for line in lines]
assert [record["sequence"] for record in records] == [1, 2]
assert records[0]["prior_state"] == records[0]["target_state"] == "inventory_pending"
assert records[1]["prior_state"] == "inventory_pending"
assert records[1]["target_state"] == "inventory_complete"
assert all(record["timestamp_utc"].endswith("Z") for record in records)
assert all(
line == json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
for line, record in zip(lines, records, strict=True)
)
def test_events_returns_only_records_revalidated_under_the_run_lock(
run_store: RunStore,
) -> None:
# Catches event consumers reading bytes without canonical, sequence, and state replay checks.
run_store.append_event("p1", "operator_note", {"value": "checked"})
records = run_store.events("p1")
assert [record["event"] for record in records] == ["operator_note"]
path = run_store.root / "events.jsonl"
record = json.loads(path.read_text(encoding="utf-8"))
path.write_text(json.dumps(record, separators=(", ", ": ")) + "\n", encoding="utf-8")
with pytest.raises(StateError, match="corrupt_event_log"):
run_store.events()
def test_create_persists_immutable_job_inputs_and_rejects_unknown_project(
run_store: RunStore,
) -> None:
job = json.loads((run_store.root / "job.json").read_text(encoding="utf-8"))
assert job["rules"] == [{"new_part_number": "NEW-1", "old_part_number": "OLD-1"}]
assert job["projects"][0]["project_path"] == str(Path(job["projects"][0]["project_path"]).resolve())
with pytest.raises(StateError, match="unknown_project"):
run_store.project_state("not-recorded")
@pytest.mark.parametrize(
"corrupt_line",
[
"not-json",
'{"event":"transition"}',
'{"event":"transition","payload":{},"prior_state":"inventory_pending",'
'"project_id":"p1","sequence":2,"target_state":"inventory_complete",'
'"timestamp_utc":"2026-09-01T00:00:00Z"}',
],
)
def test_open_fails_closed_on_malformed_or_noncontiguous_event_log(
run_store: RunStore, corrupt_line: str
) -> None:
(run_store.root / "events.jsonl").write_text(corrupt_line + "\n", encoding="utf-8")
with pytest.raises(StateError, match="corrupt_event_log"):
RunStore(run_store.root)
def test_replay_rejects_semantically_impossible_event(run_store: RunStore) -> None:
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
event_path = run_store.root / "events.jsonl"
record = json.loads(event_path.read_text(encoding="utf-8"))
record["prior_state"] = "applying"
event_path.write_text(
json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n",
encoding="utf-8",
)
with pytest.raises(StateError, match="corrupt_event_log"):
RunStore(run_store.root)
def test_replay_rejects_noncanonical_json_event(run_store: RunStore) -> None:
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
event_path = run_store.root / "events.jsonl"
record = json.loads(event_path.read_text(encoding="utf-8"))
event_path.write_text(json.dumps(record, ensure_ascii=False) + "\n", encoding="utf-8")
with pytest.raises(StateError, match="corrupt_event_log"):
RunStore(run_store.root)
@pytest.mark.parametrize("line_ending", [b"", b"\r\n"])
def test_replay_rejects_missing_lf_or_crlf(
run_store: RunStore, line_ending: bytes
) -> None:
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
event_path = run_store.root / "events.jsonl"
content = event_path.read_bytes().removesuffix(b"\n") + line_ending
event_path.write_bytes(content)
with pytest.raises(StateError, match="corrupt_event_log"):
RunStore(run_store.root)
def test_replay_preserves_unicode_json_separators(run_store: RunStore) -> None:
separators = "before\u0085middle\u2028line\u2029after"
run_store.append_event("p1", "unicode_payload", {"value": separators})
reopened = RunStore(run_store.root)
assert reopened.project_state("p1") is ProjectState.INVENTORY_PENDING
assert separators in (run_store.root / "events.jsonl").read_text(encoding="utf-8")
def test_replay_rejects_float_sequence(run_store: RunStore) -> None:
run_store.transition("p1", ProjectState.INVENTORY_COMPLETE)
event_path = run_store.root / "events.jsonl"
record = json.loads(event_path.read_text(encoding="utf-8"))
record["sequence"] = 1.0
event_path.write_text(
json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n",
encoding="utf-8",
)
with pytest.raises(StateError, match="corrupt_event_log"):
RunStore(run_store.root)
@pytest.mark.parametrize("metadata_name", ["job.json", "events.jsonl"])
def test_run_store_rejects_metadata_file_symlinks_when_available(
run_store: RunStore, tmp_path: Path, metadata_name: str
) -> None:
metadata = run_store.root / metadata_name
outside = tmp_path / f"outside-{metadata_name}"
outside.write_bytes(metadata.read_bytes())
metadata.unlink()
try:
metadata.symlink_to(outside)
except OSError as error:
pytest.skip(f"symbolic links unavailable: {error}")
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore(run_store.root)
@pytest.mark.skipif(os.name != "nt", reason="Windows reparse-point coverage")
@pytest.mark.parametrize("metadata_name", ["job.json", "events.jsonl"])
def test_run_store_rejects_metadata_junctions(
run_store: RunStore, tmp_path: Path, metadata_name: str
) -> None:
metadata = run_store.root / metadata_name
metadata.unlink()
outside = tmp_path / f"outside-{metadata_name}"
outside.mkdir()
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(metadata), str(outside)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.fail(f"junction creation failed: {created.stderr or created.stdout}")
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore(run_store.root)
finally:
metadata.rmdir()
@pytest.mark.parametrize("metadata_name", ["job.json", "events.jsonl"])
def test_run_store_rejects_metadata_replaced_between_lstat_and_open(
run_store: RunStore, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, metadata_name: str
) -> None:
metadata = run_store.root / metadata_name
replacement = tmp_path / f"replacement-{metadata_name}"
replacement.write_bytes(metadata.read_bytes())
real_open = os.open
replaced = False
def replace_before_open(path: object, flags: int, mode: int = 0o777) -> int:
nonlocal replaced
if Path(path) == metadata and not replaced:
replaced = True
os.replace(replacement, metadata)
return real_open(path, flags, mode)
monkeypatch.setattr(run_store_module.os, "open", replace_before_open)
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore(run_store.root)
def test_run_store_rejects_metadata_hard_link(run_store: RunStore, tmp_path: Path) -> None:
metadata = run_store.root / "job.json"
outside = tmp_path / "outside-job.json"
outside.write_bytes(metadata.read_bytes())
metadata.unlink()
os.link(outside, metadata)
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore(run_store.root)
@pytest.mark.skipif(os.name != "nt", reason="Windows handle-containment coverage")
def test_open_rejects_junction_inserted_before_run_root_resolution(
run_store: RunStore, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
logical_root = run_store.root
displaced_root = tmp_path / "displaced-open-run"
outside_root = tmp_path / "outside-open-run"
shutil.copytree(logical_root, outside_root)
real_resolve = Path.resolve
swapped = False
def swap_before_resolution(path: Path, strict: bool = False) -> Path:
nonlocal swapped
if path == logical_root and not swapped:
os.rename(logical_root, displaced_root)
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(logical_root), str(outside_root)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.fail(f"junction creation failed: {created.stderr or created.stdout}")
swapped = True
return real_resolve(path, strict=strict)
monkeypatch.setattr(Path, "resolve", swap_before_resolution)
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore(logical_root)
finally:
if swapped:
logical_root.rmdir()
os.rename(displaced_root, logical_root)
@pytest.mark.skipif(os.name != "nt", reason="Windows handle-containment coverage")
def test_create_rejects_junction_inserted_before_parent_resolution(
tmp_path: Path, project: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
logical_parent = tmp_path / "create-container"
logical_parent.mkdir()
logical_root = logical_parent / "run"
displaced_parent = tmp_path / "displaced-create-container"
outside_parent = tmp_path / "outside-create-parent"
outside_parent.mkdir()
real_resolve = Path.resolve
swapped = False
def swap_before_resolution(path: Path, strict: bool = False) -> Path:
nonlocal swapped
if path == logical_parent and not swapped:
os.rename(logical_parent, displaced_parent)
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(logical_parent), str(outside_parent)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.fail(f"junction creation failed: {created.stderr or created.stdout}")
swapped = True
return real_resolve(path, strict=strict)
monkeypatch.setattr(Path, "resolve", swap_before_resolution)
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore.create(
logical_root,
(MappingRule("OLD-1", "NEW-1"),),
(ProjectRef("p1", str(project), "project"),),
)
assert not (outside_parent / "run").exists()
finally:
if swapped:
logical_parent.rmdir()
os.rename(displaced_parent, logical_parent)
@pytest.mark.skipif(os.name != "nt", reason="Windows handle-containment coverage")
@pytest.mark.parametrize("swap_level", ["root", "parent"])
def test_event_append_rejects_root_component_swap_before_leaf_lstat(
tmp_path: Path, project: Path, monkeypatch: pytest.MonkeyPatch, swap_level: str
) -> None:
container = tmp_path / "container"
container.mkdir()
store = RunStore.create(
container / "run",
(MappingRule("OLD-1", "NEW-1"),),
(ProjectRef("p1", str(project), "project"),),
)
logical_root = store.root
logical_event = logical_root / "events.jsonl"
displaced = tmp_path / f"displaced-{swap_level}"
outside_component = tmp_path / f"outside-{swap_level}"
if swap_level == "root":
shutil.copytree(logical_root, outside_component)
swap_path = logical_root
else:
outside_component.mkdir()
shutil.copytree(logical_root, outside_component / "run")
swap_path = container
real_lstat = Path.lstat
swapped = False
def swap_before_leaf_lstat(path: Path):
nonlocal swapped
if path == logical_event and not swapped:
swapped = True
os.rename(swap_path, displaced)
os.rename(outside_component, swap_path)
return real_lstat(path)
monkeypatch.setattr(Path, "lstat", swap_before_leaf_lstat)
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
store.append_event("p1", "must_not_escape", {})
current_external_event = (
logical_root / "events.jsonl"
if swap_level == "root"
else container / "run" / "events.jsonl"
)
assert current_external_event.read_bytes() == b""
finally:
if swapped:
quarantine = tmp_path / f"quarantine-{swap_level}"
if swap_path.exists() and not quarantine.exists():
os.rename(swap_path, quarantine)
if displaced.exists():
os.rename(displaced, swap_path)
@pytest.mark.skipif(os.name != "nt", reason="Windows handle-containment coverage")
def test_job_open_validates_root_relationship_before_read(
run_store: RunStore, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
logical_root = run_store.root
logical_job = logical_root / "job.json"
displaced = tmp_path / "displaced-job-run"
outside_root = tmp_path / "outside-job-run"
shutil.copytree(logical_root, outside_root)
real_lstat = Path.lstat
real_read = os.read
swapped = False
def swap_before_leaf_lstat(path: Path):
nonlocal swapped
if path == logical_job and not swapped:
swapped = True
os.rename(logical_root, displaced)
os.rename(outside_root, logical_root)
return real_lstat(path)
def reject_external_read(descriptor: int, size: int) -> bytes:
if swapped:
raise AssertionError("external job was read before containment validation")
return real_read(descriptor, size)
monkeypatch.setattr(Path, "lstat", swap_before_leaf_lstat)
monkeypatch.setattr(run_store_module.os, "read", reject_external_read)
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore(logical_root)
finally:
if swapped:
os.rename(logical_root, outside_root)
os.rename(displaced, logical_root)
def test_two_processes_append_with_contiguous_sequences(run_store: RunStore, tmp_path: Path) -> None:
ready = tmp_path / "first-writer-ready"
delayed_writer = r"""
from pathlib import Path
import sys
import time
from dx_productivity.part_replace.run_store import RunStore
import dx_productivity.part_replace.run_store as module
root = Path(sys.argv[1])
ready = Path(sys.argv[2])
real_write = module.os.write
def delayed_write(descriptor, data):
if b'\"sequence\":1' in data:
ready.write_text('ready', encoding='utf-8')
time.sleep(1.0)
return real_write(descriptor, data)
module.os.write = delayed_write
RunStore(root).append_event('p1', 'writer_a', {})
"""
ordinary_writer = r"""
from pathlib import Path
import sys
from dx_productivity.part_replace.run_store import RunStore
RunStore(Path(sys.argv[1])).append_event('p1', 'writer_b', {})
"""
first = subprocess.Popen(
[sys.executable, "-c", delayed_writer, str(run_store.root), str(ready)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
deadline = time.monotonic() + 10
while not ready.exists() and first.poll() is None and time.monotonic() < deadline:
time.sleep(0.01)
assert ready.exists(), first.communicate(timeout=1)
second = subprocess.run(
[sys.executable, "-c", ordinary_writer, str(run_store.root)],
check=False,
capture_output=True,
text=True,
timeout=15,
)
first_stdout, first_stderr = first.communicate(timeout=15)
assert first.returncode == 0, (first_stdout, first_stderr)
assert second.returncode == 0, (second.stdout, second.stderr)
records = [
json.loads(line)
for line in (run_store.root / "events.jsonl").read_text(encoding="utf-8").split("\n")
if line
]
assert [record["sequence"] for record in records] == [1, 2]
assert RunStore(run_store.root).project_state("p1") is ProjectState.INVENTORY_PENDING
def test_persistent_lock_file_does_not_cause_stale_lockout(run_store: RunStore) -> None:
assert (run_store.root / ".run.lock").exists()
RunStore(run_store.root).append_event("p1", "after_reopen", {})
assert RunStore(run_store.root).project_state("p1") is ProjectState.INVENTORY_PENDING
@pytest.mark.skipif(os.name != "nt", reason="Windows reparse-point coverage")
def test_run_store_rejects_reparse_lock_file(run_store: RunStore, tmp_path: Path) -> None:
lock_path = run_store.root / ".run.lock"
lock_path.unlink()
outside = tmp_path / "outside-lock"
outside.mkdir()
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(lock_path), str(outside)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.fail(f"junction creation failed: {created.stderr or created.stdout}")
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore(run_store.root)
finally:
lock_path.rmdir()
@pytest.mark.skipif(os.name != "nt", reason="Windows reparse-point coverage")
def test_existing_store_rejects_run_root_replaced_by_junction(
run_store: RunStore, tmp_path: Path
) -> None:
original_root = run_store.root
displaced = tmp_path / "displaced-run"
os.rename(original_root, displaced)
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(original_root), str(displaced)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
os.rename(displaced, original_root)
pytest.fail(f"junction creation failed: {created.stderr or created.stdout}")
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
run_store.append_event("p1", "must_not_escape", {})
finally:
original_root.rmdir()
os.rename(displaced, original_root)
def test_backup_is_complete_and_manifest_detects_change(
tmp_path: Path, project: Path
) -> None:
backup = tmp_path / "backup"
manifest = backup_project(project, backup)
assert manifest.project_root == str(project.resolve())
assert [entry.path for entry in manifest.files] == ["design/main.sch", "readme.txt"]
assert verify_tree(backup, manifest)
assert (backup / "design" / "空").is_dir()
(backup / "design" / "main.sch").write_bytes(b"changed")
assert not verify_tree(backup, manifest)
def test_tree_manifest_detects_added_and_removed_files(project: Path) -> None:
manifest = fingerprint_tree(project)
(project / "extra.bin").write_bytes(b"extra")
assert not verify_tree(project, manifest)
(project / "extra.bin").unlink()
(project / "readme.txt").unlink()
assert not verify_tree(project, manifest)
@pytest.mark.parametrize("operation", ["fingerprint", "backup"])
def test_tree_walk_fails_closed_on_traversal_error(
tmp_path: Path,
project: Path,
monkeypatch: pytest.MonkeyPatch,
operation: str,
) -> None:
denied = project / "design"
real_scandir = os.scandir
def fail_design_scan(path: object):
if Path(path) == denied:
raise PermissionError("injected traversal denial")
return real_scandir(path)
monkeypatch.setattr(run_store_module.os, "scandir", fail_design_scan)
with pytest.raises(BackupError, match="tree_scan_failed"):
if operation == "fingerprint":
fingerprint_tree(project)
else:
backup_project(project, tmp_path / "backup")
assert not (tmp_path / "backup").exists()
def test_backup_rejects_existing_or_nested_destination(
tmp_path: Path, project: Path
) -> None:
existing = tmp_path / "existing"
existing.mkdir()
with pytest.raises(BackupError, match="destination_exists"):
backup_project(project, existing)
with pytest.raises(BackupError, match="destination_inside_source"):
backup_project(project, project / "backup")
def test_tree_operations_reject_symbolic_links(tmp_path: Path, project: Path) -> None:
outside = tmp_path / "outside.txt"
outside.write_bytes(b"outside")
link = project / "linked.txt"
try:
link.symlink_to(outside)
except OSError as error:
pytest.skip(f"symbolic links unavailable: {error}")
with pytest.raises(BackupError, match="unsupported_link"):
fingerprint_tree(project)
with pytest.raises(BackupError, match="unsupported_link"):
backup_project(project, tmp_path / "backup")
@pytest.mark.skipif(os.name != "nt", reason="Windows reparse-point coverage")
def test_tree_operations_reject_windows_junctions(tmp_path: Path, project: Path) -> None:
outside = tmp_path / "outside"
outside.mkdir()
junction = project / "junction"
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(junction), str(outside)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.skip(f"junctions unavailable: {created.stderr or created.stdout}")
try:
with pytest.raises(BackupError, match="unsupported_link"):
fingerprint_tree(project)
finally:
junction.rmdir()
def test_restore_requires_closed_project_and_preserves_failed_tree(tmp_path: Path) -> None:
project, backup, manifest = _make_changed_project_and_backup(tmp_path)
recovery = tmp_path / "recovery"
with pytest.raises(BackupError, match="project_must_be_closed"):
restore_project(project, backup, recovery, manifest, closed_confirmed=False)
failed_manifest = restore_project(
project, backup, recovery, manifest, closed_confirmed=True
)
assert verify_tree(project, manifest)
assert verify_tree(recovery, failed_manifest)
assert (recovery / "main.sch").read_bytes() == b"failed change"
assert verify_tree(backup, manifest)
def test_restore_requires_explicit_boolean_confirmation(tmp_path: Path) -> None:
project, backup, manifest = _make_changed_project_and_backup(tmp_path)
with pytest.raises(BackupError, match="project_must_be_closed"):
restore_project(project, backup, tmp_path / "recovery", manifest, closed_confirmed=1) # type: ignore[arg-type]
def test_restore_revalidates_displaced_tree_before_publication(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
project, backup, manifest = _make_changed_project_and_backup(tmp_path)
recovery = tmp_path / "recovery"
real_rename = os.rename
def mutate_after_displacement(source: object, destination: object) -> None:
source_path = Path(source)
destination_path = Path(destination)
real_rename(source, destination)
if source_path == project and destination_path.name.startswith(f".{project.name}.original-"):
(destination_path / "main.sch").write_bytes(b"mutated-after-recovery")
monkeypatch.setattr(run_store_module.os, "rename", mutate_after_displacement)
with pytest.raises(BackupError, match="failed_tree_changed"):
restore_project(project, backup, recovery, manifest, True)
assert (project / "main.sch").read_bytes() == b"mutated-after-recovery"
assert (recovery / "main.sch").read_bytes() == b"failed change"
assert any(tmp_path.glob(f".{project.name}.restore-*"))
assert verify_tree(backup, manifest)
def test_restore_rejects_wrong_recorded_target_and_unverified_backup(
tmp_path: Path,
) -> None:
project, backup, manifest = _make_changed_project_and_backup(tmp_path)
other = tmp_path / "other"
other.mkdir()
(other / "main.sch").write_bytes(b"original")
with pytest.raises(BackupError, match="target_mismatch"):
restore_project(other, backup, tmp_path / "recovery-wrong", manifest, True)
(backup / "main.sch").write_bytes(b"corrupt")
with pytest.raises(BackupError, match="backup_verification_failed"):
restore_project(project, backup, tmp_path / "recovery-corrupt", manifest, True)
assert (project / "main.sch").read_bytes() == b"failed change"
def test_restore_requires_distinct_nonexisting_recovery_destination(
tmp_path: Path,
) -> None:
project, backup, manifest = _make_changed_project_and_backup(tmp_path)
existing = tmp_path / "recovery"
existing.mkdir()
with pytest.raises(BackupError, match="recovery_exists"):
restore_project(project, backup, existing, manifest, True)
with pytest.raises(BackupError, match="recovery_inside_source"):
restore_project(project, backup, project / "recovery", manifest, True)
def test_restore_publication_failure_leaves_original_and_staging_recoverable(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
project, backup, manifest = _make_changed_project_and_backup(tmp_path)
recovery = tmp_path / "recovery"
real_rename = os.rename
def fail_restore_publication(source: object, destination: object) -> None:
source_path = Path(source)
destination_path = Path(destination)
if source_path.name.startswith(f".{project.name}.restore-") and destination_path == project:
raise OSError("injected publication failure")
real_rename(source, destination)
monkeypatch.setattr("dx_productivity.part_replace.run_store.os.rename", fail_restore_publication)
with pytest.raises(BackupError, match="restore_publication_failed"):
restore_project(project, backup, recovery, manifest, True)
assert (project / "main.sch").read_bytes() == b"failed change"
assert verify_tree(recovery, fingerprint_tree(project))
assert any(tmp_path.glob(f".{project.name}.restore-*"))
assert verify_tree(backup, manifest)
def test_restore_does_not_overwrite_destination_created_during_publication(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
project, backup, manifest = _make_changed_project_and_backup(tmp_path)
real_rename = os.rename
def create_racing_destination(source: object, destination: object) -> None:
source_path = Path(source)
destination_path = Path(destination)
if source_path == project and destination_path.name.startswith(f".{project.name}.original-"):
real_rename(source, destination)
project.mkdir()
(project / "racing-owner.txt").write_text("do not overwrite", encoding="utf-8")
return
if source_path.name.startswith(f".{project.name}.restore-") and destination_path == project:
shutil.rmtree(project)
real_rename(source, destination)
monkeypatch.setattr("dx_productivity.part_replace.run_store.os.rename", create_racing_destination)
with pytest.raises(BackupError, match="destination_exists"):
restore_project(project, backup, tmp_path / "recovery", manifest, True)
assert (project / "racing-owner.txt").read_text(encoding="utf-8") == "do not overwrite"
@pytest.mark.skipif(os.name != "nt", reason="Windows no-replace rename behavior")
def test_backup_publication_does_not_replace_racing_destination(
tmp_path: Path, project: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
backup = tmp_path / "backup"
real_rename = os.rename
def create_destination_before_rename(source: object, destination: object) -> None:
destination_path = Path(destination)
if destination_path == backup:
backup.mkdir()
(backup / "owner.txt").write_text("racing owner", encoding="utf-8")
real_rename(source, destination)
monkeypatch.setattr(run_store_module.os, "rename", create_destination_before_rename)
with pytest.raises(BackupError, match="backup_publication_failed"):
backup_project(project, backup)
assert (backup / "owner.txt").read_text(encoding="utf-8") == "racing owner"
def test_destructive_tree_operations_fail_closed_off_windows(
tmp_path: Path, project: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
backup = tmp_path / "existing-backup"
manifest = backup_project(project, backup)
(project / "readme.txt").write_text("failed", encoding="utf-8")
monkeypatch.setattr(
run_store_module, "_WINDOWS_DESTRUCTIVE_OPERATIONS", False, raising=False
)
with pytest.raises(BackupError, match="unsupported_platform"):
backup_project(project, tmp_path / "new-backup")
with pytest.raises(BackupError, match="unsupported_platform"):
restore_project(project, backup, tmp_path / "recovery", manifest, True)
assert not (tmp_path / "new-backup").exists()
assert not (tmp_path / "recovery").exists()
assert (project / "readme.txt").read_text(encoding="utf-8") == "failed"
def test_run_store_create_and_open_fail_closed_off_windows(
tmp_path: Path, project: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
existing = RunStore.create(
tmp_path / "existing-run",
(MappingRule("OLD-1", "NEW-1"),),
(ProjectRef("p1", str(project), "project"),),
)
metadata_before = {
name: (existing.root / name).read_bytes()
for name in ("job.json", "events.jsonl", ".run.lock")
}
unsupported_root = tmp_path / "unsupported-run"
monkeypatch.setattr(run_store_module, "_WINDOWS_DESTRUCTIVE_OPERATIONS", False)
with pytest.raises(StateError, match="unsupported_platform"):
RunStore.create(
unsupported_root,
(MappingRule("OLD-1", "NEW-1"),),
(ProjectRef("p1", str(project), "project"),),
)
with pytest.raises(StateError, match="unsupported_platform"):
RunStore(existing.root)
assert not unsupported_root.exists()
assert {
name: (existing.root / name).read_bytes()
for name in ("job.json", "events.jsonl", ".run.lock")
} == metadata_before
@pytest.mark.skipif(os.name != "nt", reason="Windows handle-containment coverage")
def test_run_store_create_validates_root_before_writing_job(
tmp_path: Path, project: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
logical_root = tmp_path / "new-run"
displaced = tmp_path / "displaced-new-run"
outside_root = tmp_path / "outside-new-run"
outside_root.mkdir()
outside_job = outside_root / "job.json"
outside_job.write_bytes(b"")
real_open = os.open
swapped = False
def swap_root() -> None:
nonlocal swapped
if not swapped:
swapped = True
os.rename(logical_root, displaced)
os.rename(outside_root, logical_root)
def swap_before_descriptor_open(path: object, flags: int, mode: int = 0o777) -> int:
if Path(path).name == "job.json":
swap_root()
return real_open(path, flags, mode)
monkeypatch.setattr(run_store_module.os, "open", swap_before_descriptor_open)
try:
with pytest.raises(StateError, match="unsafe_run_metadata"):
RunStore.create(
logical_root,
(MappingRule("OLD-1", "NEW-1"),),
(ProjectRef("p1", str(project), "project"),),
)
assert (logical_root / "job.json").read_bytes() == b""
finally:
if swapped:
quarantine = tmp_path / "quarantine-new-run"
os.rename(logical_root, quarantine)
os.rename(displaced, logical_root)
def test_manifest_is_immutable(project: Path) -> None:
manifest = fingerprint_tree(project)
with pytest.raises((AttributeError, TypeError)):
manifest.files = () # type: ignore[misc]
with pytest.raises((AttributeError, TypeError)):
replace(manifest.files[0], size=0).sha256 = "changed" # type: ignore[misc]
+382
View File
@@ -0,0 +1,382 @@
from __future__ import annotations
from dataclasses import dataclass, replace
from decimal import Decimal
import pytest
from dx_productivity.part_replace.models import (
ComponentSnapshot,
DesignSnapshot,
MappingRule,
PinSnapshot,
UnitSnapshot,
)
from dx_productivity.part_replace.verification import (
build_impact_matrix,
eligible_logical_keys,
verify_replacement,
)
@dataclass(frozen=True)
class ReplacementFixtures:
before: DesignSnapshot
compatible: DesignSnapshot
def _component(
logical_key: str,
refdes: str,
part_number: str,
*,
units: tuple[UnitSnapshot, ...] | None = None,
attributes: tuple[tuple[str, str], ...] = (),
) -> ComponentSnapshot:
return ComponentSnapshot(
logical_key=logical_key,
refdes=refdes,
part_number=part_number,
units=units if units is not None else (_unit("A"),),
attributes=attributes,
)
def _unit(unit_id: str, *, x: Decimal = Decimal("0"), pins: tuple[PinSnapshot, ...] | None = None) -> UnitSnapshot:
return UnitSnapshot(
unit_id=unit_id,
sheet="/MAIN",
symbol="SOURCE_SYMBOL",
origin_x=x - Decimal("0.5"),
origin_y=Decimal("3.5"),
x=x,
y=Decimal("4"),
rotation=90,
mirrored=False,
pins=pins if pins is not None else (
PinSnapshot("1", "A", Decimal("10"), Decimal("20"), "N$1"),
PinSnapshot("2", "B", Decimal("11"), Decimal("20"), "N$2"),
),
)
@pytest.fixture
def fixtures() -> ReplacementFixtures:
replacement = _component(
"/MAIN|R1", "R1", " old-1 ", attributes=(("tolerance", "1%"),),
)
unrelated = _component("/MAIN|C1", "C1", "KEEP-1", attributes=(("value", "1u"),))
before = DesignSnapshot(2, "project-1", "C:/Projects/board.prj", "before", (replacement, unrelated))
compatible = replace(
before,
fingerprint="after",
components=(
replace(
replacement,
part_number=" New-1 ",
units=(replace(replacement.units[0], symbol="LIBRARY_SYMBOL"),),
attributes=(("tolerance", "5%"), ("library", "central")),
),
unrelated,
),
)
return ReplacementFixtures(before, compatible)
def _replacement(after: DesignSnapshot) -> ComponentSnapshot:
return after.components[0]
def _replace_replacement(after: DesignSnapshot, component: ComponentSnapshot) -> DesignSnapshot:
return replace(after, components=(component, after.components[1]))
def change_refdes(after: DesignSnapshot) -> DesignSnapshot:
return _replace_replacement(after, replace(_replacement(after), refdes="R99"))
def move_origin(after: DesignSnapshot) -> DesignSnapshot:
component = _replacement(after)
return _replace_replacement(after, replace(component, units=(replace(component.units[0], x=Decimal("0.1")),)))
def change_origin_only(after: DesignSnapshot) -> DesignSnapshot:
component = _replacement(after)
unit = component.units[0]
assert hasattr(unit, "origin_x")
return _replace_replacement(
after,
replace(component, units=(replace(unit, origin_x=Decimal("7.125")),)),
)
def remove_pin(after: DesignSnapshot) -> DesignSnapshot:
component = _replacement(after)
return _replace_replacement(after, replace(component, units=(replace(component.units[0], pins=component.units[0].pins[:1]),)))
def move_pin(after: DesignSnapshot) -> DesignSnapshot:
component = _replacement(after)
pin = component.units[0].pins[0]
return _replace_replacement(
after,
replace(component, units=(replace(component.units[0], pins=(replace(pin, x=Decimal("10.1")), component.units[0].pins[1])),)),
)
def change_net(after: DesignSnapshot) -> DesignSnapshot:
component = _replacement(after)
pin = component.units[0].pins[0]
return _replace_replacement(
after,
replace(component, units=(replace(component.units[0], pins=(replace(pin, net="N$2"), component.units[0].pins[1])),)),
)
def change_unrelated_part(after: DesignSnapshot) -> DesignSnapshot:
return replace(after, components=(after.components[0], replace(after.components[1], part_number="CHANGED")))
def select_wrong_target(after: DesignSnapshot) -> DesignSnapshot:
return _replace_replacement(after, replace(_replacement(after), part_number="WRONG-1"))
def test_compatible_replacement_preserves_every_hard_invariant(fixtures: ReplacementFixtures) -> None:
result = verify_replacement(fixtures.before, fixtures.compatible, MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",))
assert result.passed
assert [(issue.code, issue.severity) for issue in result.issues] == [
("library_symbol_changed", "info"),
("library_attribute_changed", "info"),
]
assert result.changed_logical_keys == ("/MAIN|R1",)
def test_library_controlled_symbol_pin_names_and_attributes_are_reported_without_blocking(fixtures: ReplacementFixtures) -> None:
component = _replacement(fixtures.compatible)
library_wins = _replace_replacement(
fixtures.compatible,
replace(
component,
attributes=(("library", "central"),),
units=(
replace(
component.units[0],
symbol="ANOTHER_LIBRARY_SYMBOL",
pins=(replace(component.units[0].pins[0], name="LIBRARY_A"), component.units[0].pins[1]),
),
),
),
)
result = verify_replacement(fixtures.before, library_wins, MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",))
assert result.passed
assert [(issue.code, issue.severity) for issue in result.issues] == [
("library_symbol_changed", "info"),
("library_pin_name_changed", "info"),
("library_attribute_changed", "info"),
]
def test_unrelated_symbol_and_attribute_changes_remain_blocking(fixtures: ReplacementFixtures) -> None:
unrelated = fixtures.compatible.components[1]
changed_unrelated = replace(
unrelated,
attributes=(("value", "47u"),),
units=(replace(unrelated.units[0], symbol="OTHER_SYMBOL"),),
)
after = replace(fixtures.compatible, components=(fixtures.compatible.components[0], changed_unrelated))
result = verify_replacement(fixtures.before, after, MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",))
assert not result.passed
assert ("unrelated_component_changed", "error") in [(issue.code, issue.severity) for issue in result.issues]
@pytest.mark.parametrize("mutator,code", [
(change_refdes, "refdes_changed"),
(move_origin, "placement_changed"),
(change_origin_only, "origin_changed"),
(remove_pin, "pin_set_changed"),
(move_pin, "pin_position_changed"),
(change_net, "connectivity_changed"),
(change_unrelated_part, "unrelated_component_changed"),
(select_wrong_target, "wrong_target_part_number"),
])
def test_verification_blocks_unsafe_change(fixtures: ReplacementFixtures, mutator, code: str) -> None:
result = verify_replacement(fixtures.before, mutator(fixtures.compatible), MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",))
assert not result.passed
assert code in {issue.code for issue in result.issues}
def test_impact_matrix_uses_trimmed_casefold_matching_and_snapshot_rule_order(fixtures: ReplacementFixtures) -> None:
second = replace(fixtures.before, project_id="project-2", components=(
_component("/MAIN|R2", "R2", "old-1", units=(_unit("A"), _unit("B"))),
))
rules = (MappingRule(" keep-1 ", "KEEP-2"), MappingRule("OLD-1", "NEW-1"))
matrix = build_impact_matrix((fixtures.before, second), rules)
assert [(cell.project_id, cell.rule.old_part_number, cell.logical_count, cell.unit_count) for cell in matrix] == [
("project-1", " keep-1 ", 1, 1),
("project-1", "OLD-1", 1, 1),
("project-2", " keep-1 ", 0, 0),
("project-2", "OLD-1", 1, 2),
]
assert eligible_logical_keys(fixtures.before, MappingRule(" OLD-1", "NEW-1")) == ("/MAIN|R1",)
@pytest.mark.parametrize(
("mutator", "expected_code"),
(
(lambda component: replace(component, units=()), "missing_units"),
(
lambda component: replace(
component,
units=(replace(component.units[0], pins=()),),
),
"missing_pins",
),
(
lambda component: replace(
component,
units=(
replace(
component.units[0],
pins=(replace(component.units[0].pins[0], net=None), component.units[0].pins[1]),
),
),
),
"missing_network_identity",
),
),
)
def test_matched_component_missing_evidence_blocks_impact_and_hard_verification(
fixtures: ReplacementFixtures,
mutator,
expected_code: str,
) -> None:
# Catches equality-only checks that accept equally incomplete before/after snapshots.
before_component = mutator(fixtures.before.components[0])
after_component = mutator(fixtures.compatible.components[0])
before = replace(fixtures.before, components=(before_component, fixtures.before.components[1]))
after = replace(fixtures.compatible, components=(after_component, fixtures.compatible.components[1]))
rule = MappingRule("OLD-1", "NEW-1")
impact = build_impact_matrix((before,), (rule,))[0]
result = verify_replacement(before, after, rule, ("/MAIN|R1",))
assert impact.logical_count == 1
assert expected_code in {issue.code for issue in impact.issues}
assert not result.passed
assert expected_code in {issue.code for issue in result.issues}
def test_coordinate_tolerance_allows_exact_boundary_but_blocks_larger_difference(fixtures: ReplacementFixtures) -> None:
component = _replacement(fixtures.compatible)
pin = component.units[0].pins[0]
at_boundary = _replace_replacement(
fixtures.compatible,
replace(component, units=(replace(component.units[0], pins=(replace(pin, x=Decimal("10.000001")), component.units[0].pins[1])),)),
)
beyond_boundary = _replace_replacement(
fixtures.compatible,
replace(component, units=(replace(component.units[0], pins=(replace(pin, x=Decimal("10.0000011")), component.units[0].pins[1])),)),
)
assert verify_replacement(fixtures.before, at_boundary, MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",)).passed
result = verify_replacement(fixtures.before, beyond_boundary, MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",))
assert "pin_position_changed" in {issue.code for issue in result.issues}
@pytest.mark.parametrize(
("mutator", "code"),
[
(lambda before, after: (replace(after, project_id="other"), "project_id_changed"), "project_id_changed"),
(lambda before, after: (replace(after, project_path="C:/Other/board.prj"), "project_path_changed"), "project_path_changed"),
(lambda before, after: (replace(after, components=after.components[:1]), "component_removed"), "component_removed"),
(lambda before, after: (replace(after, components=after.components + (_component("/MAIN|L1", "L1", "KEEP"),)), "component_added"), "component_added"),
(lambda before, after: (after, "expected_logical_key_missing"), "expected_logical_key_missing"),
],
)
def test_verification_blocks_project_and_component_identity_changes(fixtures: ReplacementFixtures, mutator, code: str) -> None:
after, expected_code = mutator(fixtures.before, fixtures.compatible)
expected_keys = ("/MAIN|R1",) if expected_code != "expected_logical_key_missing" else ("/MAIN|MISSING",)
result = verify_replacement(fixtures.before, after, MappingRule("OLD-1", "NEW-1"), expected_keys)
assert code in {issue.code for issue in result.issues}
assert not result.passed
def test_multi_unit_replacement_requires_the_same_gate_slot_set(fixtures: ReplacementFixtures) -> None:
units = (_unit("A"), _unit("B", x=Decimal("30")))
before_component = _component("/MAIN|U1", "U1", "OLD-1", units=units)
before = replace(fixtures.before, components=(before_component, fixtures.before.components[1]))
after = replace(before, components=(replace(before_component, part_number="NEW-1"), before.components[1]))
incompatible = replace(after, components=(replace(after.components[0], units=(after.components[0].units[0], _unit("C", x=Decimal("30")))), after.components[1]))
assert verify_replacement(before, after, MappingRule("OLD-1", "NEW-1"), ("/MAIN|U1",)).passed
result = verify_replacement(before, incompatible, MappingRule("OLD-1", "NEW-1"), ("/MAIN|U1",))
assert "unit_set_changed" in {issue.code for issue in result.issues}
def test_expected_key_must_have_the_rule_source_part_number(fixtures: ReplacementFixtures) -> None:
wrong_before = _replace_replacement(fixtures.before, replace(fixtures.before.components[0], part_number="OTHER"))
result = verify_replacement(wrong_before, fixtures.compatible, MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",))
assert "source_part_number_mismatch" in {issue.code for issue in result.issues}
assert not result.passed
def test_verification_fails_closed_for_duplicate_direct_snapshot_identities(fixtures: ReplacementFixtures) -> None:
duplicate_component = replace(fixtures.before.components[0], refdes="R2")
duplicate_unit = replace(fixtures.before.components[0].units[0], unit_id="A")
duplicate_pin = replace(fixtures.before.components[0].units[0].pins[0], name="Alternative")
malformed = replace(
fixtures.compatible,
components=(
replace(fixtures.compatible.components[0], units=(duplicate_unit, duplicate_unit)),
fixtures.compatible.components[1],
duplicate_component,
),
)
malformed = replace(
malformed,
components=(
replace(
malformed.components[0],
units=(
replace(duplicate_unit, pins=(duplicate_pin, duplicate_pin)),
duplicate_unit,
),
),
malformed.components[1],
malformed.components[2],
),
)
result = verify_replacement(fixtures.before, malformed, MappingRule("OLD-1", "NEW-1"), ("/MAIN|R1",))
assert {"duplicate_logical_key", "duplicate_unit_id", "duplicate_pin_number"} <= {issue.code for issue in result.issues}
assert not result.passed
def test_duplicate_normalized_refdes_is_ineligible_and_blocks_verification(fixtures: ReplacementFixtures) -> None:
duplicate_refdes_before = replace(fixtures.before.components[1], refdes=" r1 ", part_number="OLD-1")
before = replace(fixtures.before, components=(fixtures.before.components[0], duplicate_refdes_before))
after = replace(
fixtures.compatible,
components=(
fixtures.compatible.components[0],
replace(duplicate_refdes_before, part_number="NEW-1"),
),
)
rule = MappingRule("OLD-1", "NEW-1")
assert eligible_logical_keys(before, rule) == ()
result = verify_replacement(before, after, rule, ("/MAIN|R1", "/MAIN|C1"))
assert not result.passed
assert ("duplicate_refdes", "error") in [(issue.code, issue.severity) for issue in result.issues]
+183
View File
@@ -0,0 +1,183 @@
from __future__ import annotations
from pathlib import Path
import os
import subprocess
import sys
def test_default_data_root_uses_windows_known_folder_without_environment(tmp_path: Path, monkeypatch) -> None:
from dx_productivity.trial_task_center import application
known_folder = tmp_path / "Local App Data"
monkeypatch.delenv("LOCALAPPDATA", raising=False)
monkeypatch.setattr(application, "_windows_local_app_data", lambda: known_folder)
assert application.resolve_data_root(None) == (
known_folder / "DxProductivity" / "trial-task-center"
).resolve()
def test_frozen_application_keeps_data_beside_the_executable(tmp_path: Path, monkeypatch) -> None:
from dx_productivity.trial_task_center import application
executable = tmp_path / "DxPartReplace" / "DxPartReplace.exe"
monkeypatch.setattr(application.sys, "frozen", True, raising=False)
monkeypatch.setattr(application.sys, "executable", str(executable))
assert application.resolve_data_root(None) == (executable.parent / "data").resolve()
def test_explicit_data_root_still_overrides_frozen_portable_default(tmp_path: Path, monkeypatch) -> None:
from dx_productivity.trial_task_center import application
monkeypatch.setattr(application.sys, "frozen", True, raising=False)
monkeypatch.setattr(application.sys, "executable", str(tmp_path / "app" / "DxPartReplace.exe"))
override = tmp_path / "override"
assert application.resolve_data_root(override) == override.resolve()
def test_main_configures_logging_before_qapplication_and_logs_recovery(tmp_path: Path, monkeypatch) -> None:
"""Moving logging after Qt creation would lose startup and recovery diagnostics."""
from dx_productivity.trial_task_center import application
from dx_productivity.trial_task_center.logging_setup import configure_logging
events: list[str] = []
context = configure_logging(tmp_path)
class Store:
path = tmp_path / "task-center.db"
def __init__(self, path: Path) -> None:
assert events == ["logging"]
self.path = path
def recover_interrupted_work(self) -> tuple[str, ...]:
return ("project-1",)
def close(self) -> None:
events.append("closed")
class Application:
def __init__(self, _argv: list[str]) -> None:
assert events == ["logging"]
def exec(self) -> int:
return 0
class Service:
def __init__(self, _store, _context) -> None:
assert events == ["logging"]
class Window:
def __init__(self, _service) -> None:
events.append("window")
def show(self) -> None:
events.append("shown")
monkeypatch.setattr(application, "configure_logging", lambda _root: events.append("logging") or context)
monkeypatch.setattr(application, "TaskStore", Store)
monkeypatch.setattr(application, "TaskCenterService", Service)
monkeypatch.setattr(application, "QApplication", Application)
monkeypatch.setattr(application, "_load_window", lambda: Window)
assert application.main(["--data-root", str(tmp_path)]) == 0
assert events == ["logging", "window", "shown", "closed"]
assert "recovered_interrupted_projects=project-1" in context.application_log_path.read_text(encoding="utf-8")
assert f"version={application.VERSION}" in context.application_log_path.read_text(encoding="utf-8")
def test_smoke_test_closes_window_with_zero_delay_timer_and_reopens_database(tmp_path: Path, monkeypatch) -> None:
"""A packaged smoke run must exit cleanly and leave its SQLite database reusable."""
from dx_productivity.trial_task_center import application
calls: list[object] = []
class Application:
def __init__(self, _argv: list[str]) -> None:
calls.append("application")
def quit(self) -> None:
calls.append("quit")
def exec(self) -> int:
return 0
class Timer:
@staticmethod
def singleShot(delay: int, callback) -> None:
calls.append(delay)
callback()
class Window:
def __init__(self, _service) -> None:
calls.append("window")
def show(self) -> None:
calls.append("shown")
def close(self) -> None:
calls.append("closed")
monkeypatch.setattr(application, "QApplication", Application)
monkeypatch.setattr(application, "QTimer", Timer)
monkeypatch.setattr(application, "_load_window", lambda: Window)
arguments = ["--smoke-test", "--data-root", str(tmp_path)]
assert application.main(arguments) == 0
assert application.main(arguments) == 0
assert calls == [
"application", "window", "shown", 0, "closed", "quit",
"application", "window", "shown", 0, "closed", "quit",
]
assert (tmp_path / "task-center.db").exists()
def test_fatal_startup_exception_is_logged_with_traceback_and_nonzero_exit(tmp_path: Path, monkeypatch) -> None:
"""A database startup crash must be diagnosable without presenting a half-built window."""
from dx_productivity.trial_task_center import application
def fail_store(_path: Path):
raise RuntimeError("database unavailable")
monkeypatch.setattr(application, "TaskStore", fail_store)
assert application.main(["--data-root", str(tmp_path)]) == 1
application_log = (tmp_path / "logs" / "application.log").read_text(encoding="utf-8")
assert "RuntimeError: database unavailable" in application_log
assert "operation=startup" in application_log
def test_native_helper_mode_skips_database_logging_and_qt(tmp_path: Path, monkeypatch) -> None:
"""The helper subprocess must attach to DxDesigner without starting another GUI shell."""
from dx_productivity.trial_task_center import application, native_helper
snapshot = tmp_path / "snapshot.tsv"
snapshot.touch()
calls: list[Path] = []
monkeypatch.setattr(native_helper, "run", lambda path: calls.append(path) or 7)
monkeypatch.setattr(application, "configure_logging", lambda _root: (_ for _ in ()).throw(AssertionError("logging started")))
assert application.main(["--native-helper", "--snapshot", str(snapshot)]) == 7
assert calls == [snapshot]
def test_application_module_runs_as_a_script_for_the_frozen_entrypoint(tmp_path: Path) -> None:
"""Relative imports would make a PyInstaller script entrypoint fail before logging starts."""
source_root = Path(__file__).resolve().parents[2] / "src"
script = source_root / "dx_productivity" / "trial_task_center" / "application.py"
environment = os.environ | {"PYTHONPATH": str(source_root), "QT_QPA_PLATFORM": "offscreen"}
result = subprocess.run(
[sys.executable, str(script), "--smoke-test", "--data-root", str(tmp_path)],
capture_output=True,
text=True,
timeout=15,
env=environment,
check=False,
)
assert result.returncode == 0, result.stderr
assert "application_clean_shutdown" in (tmp_path / "logs" / "application.log").read_text(encoding="utf-8")
File diff suppressed because it is too large. Load diff
+170
View File
@@ -0,0 +1,170 @@
from __future__ import annotations
import copy
import json
from pathlib import Path
import pytest
from dx_productivity.part_replace.models import MappingRule
from dx_productivity.trial_task_center.comparison import compare_profiles
FIXTURES = Path(__file__).parents[1] / "fixtures" / "trial_task_center"
def _profile(name: str) -> dict[str, object]:
return json.loads((FIXTURES / name).read_text(encoding="utf-8"))
def _codes(result: object) -> set[str]:
return {issue.code for issue in result.issues}
def test_compare_profiles_matches_material_numbers_and_serializes_canonically() -> None:
result = compare_profiles(
_profile("profile-before.json"),
_profile("profile-after-valid.json"),
(MappingRule(" old-1 ", "NEW-1"), MappingRule("OLD-2", "NEW-2")),
)
assert result.passed
assert result.matched_logical_identities[MappingRule(" old-1 ", "NEW-1")] == ("/MAIN|R1",)
assert result.matched_logical_identities[MappingRule("OLD-2", "NEW-2")] == ()
assert {warning.code for warning in result.warnings} == {"no_matching_source_part"}
assert result.to_json() == result.to_json()
assert json.loads(result.to_json())["passed"] is True
def test_compare_profiles_rejects_wrong_target_and_missing_or_duplicate_identity() -> None:
before = _profile("profile-before.json")
invalid = _profile("profile-after-invalid.json")
result = compare_profiles(before, invalid, (MappingRule("OLD-1", "NEW-1"),))
assert not result.passed
assert {"wrong_target_part_number", "duplicate_logical_identity"} <= _codes(result)
def test_compare_profiles_detects_protected_changes_and_unrelated_changes() -> None:
before = _profile("profile-before.json")
after = copy.deepcopy(_profile("profile-after-valid.json"))
component = after["components"][0]
component["refdes"] = "R9"
component["hierarchy"] = "/OTHER"
component["units"] = 2
component["origin"]["x"] = 11
component["position"]["y"] = 99
component["rotation"] = 90
component["mirror"] = True
component["pins"][0]["number"] = "9"
component["nets"] = ["GND"]
after["components"][1]["refdes"] = "C9"
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
assert not result.passed
assert {
"refdes_changed", "hierarchy_changed", "unit_count_changed", "origin_changed",
"position_changed", "rotation_changed", "mirror_changed", "pins_changed",
"nets_changed", "unrelated_component_changed",
} <= _codes(result)
def test_compare_profiles_reports_parameter_presentation_as_warning_not_a_pass() -> None:
before = _profile("profile-before.json")
after = _profile("profile-after-valid.json")
after["interfaces"]["parameter_probe"] = {"available": False}
after["components"][0]["parameter_probe"] = None
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
assert result.passed
assert {warning.code for warning in result.warnings} == {"parameter_presentation_unavailable"}
def test_compare_profiles_keeps_part_label_and_value_differences_as_warnings() -> None:
before = _profile("profile-before.json")
after = _profile("profile-after-valid.json")
after["components"][0]["attributes"] = [
{"name": "Part Label", "value": "R-ALT"},
{"name": "Value", "value": "12K"},
]
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
assert result.passed
assert {warning.code for warning in result.warnings} == {"part_label_changed", "value_changed"}
def test_compare_profiles_canonical_json_does_not_depend_on_rule_input_order() -> None:
before = _profile("profile-before.json")
after = _profile("profile-after-valid.json")
first = MappingRule("OLD-1", "NEW-1")
second = MappingRule("OLD-2", "NEW-2")
forward = compare_profiles(before, after, (first, second))
reverse = compare_profiles(before, after, (second, first))
assert forward.to_json() == reverse.to_json()
def test_compare_profiles_does_not_pass_when_part_number_evidence_is_missing() -> None:
before = _profile("profile-before.json")
after = _profile("profile-after-valid.json")
before["components"][0]["part_number"] = None
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
assert not result.passed
assert "missing_protected_evidence" in _codes(result)
def test_compare_profiles_rejects_part_number_changes_on_unmatched_components() -> None:
before = _profile("profile-before.json")
after = _profile("profile-after-valid.json")
after["components"][1]["part_number"] = "SURPRISE-PART"
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
assert not result.passed
assert "unrelated_component_changed" in _codes(result)
@pytest.mark.parametrize(
("field", "value"),
(
("refdes", ""),
("hierarchy", ""),
("origin", []),
("position", {"x": 1}),
("units", 1.5),
("pins", {"number": "1"}),
("nets", [1]),
),
)
def test_compare_profiles_rejects_invalid_protected_component_schema(field: str, value: object) -> None:
before = _profile("profile-before.json")
after = _profile("profile-after-valid.json")
before["components"][0][field] = value
after["components"][0][field] = copy.deepcopy(value)
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
assert not result.passed
assert "invalid_protected_evidence" in _codes(result)
def test_compare_profiles_canonical_json_does_not_depend_on_component_input_order() -> None:
before = _profile("profile-before.json")
after = _profile("profile-after-valid.json")
reversed_before = copy.deepcopy(before)
reversed_after = copy.deepcopy(after)
reversed_before["components"].reverse()
reversed_after["components"].reverse()
rules = (MappingRule("OLD-1", "NEW-1"), MappingRule("OLD-2", "NEW-2"))
forward = compare_profiles(before, after, rules)
reversed_result = compare_profiles(reversed_before, reversed_after, rules)
assert forward.to_json() == reversed_result.to_json()
+233
View File
@@ -0,0 +1,233 @@
from __future__ import annotations
import hashlib
import json
import os
from pathlib import Path
import subprocess
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
import dx_productivity.trial_task_center.evidence as evidence_module
from dx_productivity.trial_task_center.evidence import capture_profile, profile_stamp
FIXTURES = Path(__file__).parents[1] / "fixtures" / "trial_task_center"
def _copy_fixture(name: str, destination: Path) -> bytes:
data = (FIXTURES / name).read_bytes()
destination.write_bytes(data)
return data
def _directory_alias(alias: Path, target: Path) -> None:
if os.name == "nt":
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(alias), str(target)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.skip(f"junctions unavailable: {created.stderr or created.stdout}")
else:
try:
alias.symlink_to(target, target_is_directory=True)
except OSError as error:
pytest.skip(f"directory aliases unavailable: {error}")
def test_profile_stamp_returns_exact_hash_for_a_stable_snapshot(tmp_path: Path) -> None:
source = tmp_path / "profile.json"
data = _copy_fixture("profile-before.json", source)
stamp = profile_stamp(source)
assert stamp is not None
assert stamp.size == len(data)
assert stamp.sha256 == hashlib.sha256(data).hexdigest()
assert stamp.modified_ns == source.stat().st_mtime_ns
assert profile_stamp(tmp_path / "missing.json") is None
@pytest.mark.parametrize(
("contents", "code"),
(
(b"{", "profile_json"),
(b'{"format_version": 1, "format_version": 1}', "profile_duplicate_key"),
(b'{"format_version": 2, "project": {"identity": "C:/Projects/Board.prj"}}', "profile_version"),
(b'{"format_version": 1, "project": {"identity": "C:/Other/Board.prj"}}', "profile_project"),
),
)
def test_capture_profile_rejects_untrustworthy_probe_output(
tmp_path: Path, contents: bytes, code: str
) -> None:
source = tmp_path / "menu-probe.json"
destination = tmp_path / "captured.json"
source.write_bytes(contents)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, destination, Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == code
assert not destination.exists()
def test_capture_profile_requires_new_evidence_and_publishes_exact_bytes_atomically(tmp_path: Path) -> None:
source = tmp_path / "menu-probe.json"
destination = tmp_path / "captured.json"
original = _copy_fixture("profile-before.json", source)
previous = profile_stamp(source)
assert previous is not None
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, destination, Path("C:/Projects/Board.PRJ"), previous)
assert raised.value.code == "profile_unchanged"
updated = json.loads(original)
updated["capture"] = "after operator action"
data = json.dumps(updated, sort_keys=True, separators=(",", ":")).encode("utf-8")
source.write_bytes(data)
os.utime(source, ns=(previous.modified_ns + 1, previous.modified_ns + 1))
captured = capture_profile(source, destination, Path("c:\\projects\\board.prj"), previous)
assert captured.source == source
assert captured.destination == destination
assert captured.project_identity == "C:/Projects/Board.PRJ"
assert captured.stamp.sha256 == hashlib.sha256(data).hexdigest()
assert destination.read_bytes() == data
assert source.read_bytes() == data
assert not list(tmp_path.glob(".captured.json.*"))
@pytest.mark.parametrize("constant", ("NaN", "Infinity", "-Infinity"))
def test_capture_profile_rejects_non_finite_json_constants(tmp_path: Path, constant: str) -> None:
source = tmp_path / "menu-probe.json"
source.write_bytes(
('{"format_version":1,"project":{"identity":"C:/Projects/Board.PRJ"},"value":' + constant + "}").encode("ascii")
)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, tmp_path / "captured.json", Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == "profile_json"
def test_capture_profile_accepts_a_canonical_project_alias(tmp_path: Path) -> None:
real_project = tmp_path / "projects" / "Board.prj"
alias = tmp_path / "alias" / "Board.prj"
real_project.parent.mkdir()
real_project.write_text("project", encoding="utf-8")
_directory_alias(alias.parent, real_project.parent)
source = tmp_path / "menu-probe.json"
profile = json.loads((FIXTURES / "profile-before.json").read_text(encoding="utf-8"))
profile["project"]["identity"] = str(alias)
source.write_text(json.dumps(profile), encoding="utf-8")
captured = capture_profile(source, tmp_path / "captured.json", real_project, None)
assert captured.project_identity == str(alias)
def test_capture_profile_rejects_a_reparse_destination_parent(tmp_path: Path) -> None:
source = tmp_path / "menu-probe.json"
_copy_fixture("profile-before.json", source)
target = tmp_path / "target"
target.mkdir()
alias = tmp_path / "alias"
_directory_alias(alias, target)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, alias / "captured.json", Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == "profile_publish_path"
def test_capture_profile_rejects_staged_path_hardlink_substitution(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
source = tmp_path / "menu-probe.json"
destination = tmp_path / "published" / "captured.json"
attacker = tmp_path / "attacker.json"
_copy_fixture("profile-before.json", source)
destination.parent.mkdir()
destination.write_bytes(b"previous-profile")
attacker.write_bytes(b"attacker-controlled-bytes")
def substitute(_: Path, temporary: Path) -> None:
temporary.unlink()
os.link(attacker, temporary)
monkeypatch.setattr(evidence_module, "_publication_hook", substitute, raising=False)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, destination, Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == "profile_publish"
assert destination.read_bytes() == b"previous-profile"
assert attacker.read_bytes() == b"attacker-controlled-bytes"
def test_capture_profile_rejects_source_destination_alias_without_mutating_source(tmp_path: Path) -> None:
source = tmp_path / "menu-probe.json"
_copy_fixture("profile-before.json", source)
before = source.stat()
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, source, Path("C:/Projects/Board.PRJ"), None)
after = source.stat()
assert raised.value.code == "profile_source_destination_alias"
assert (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) == (
before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns,
)
def test_capture_profile_rejects_hardlink_destination_alias(tmp_path: Path) -> None:
source = tmp_path / "menu-probe.json"
destination = tmp_path / "destination.json"
_copy_fixture("profile-before.json", source)
os.link(source, destination)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, destination, Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == "profile_source_destination_alias"
def test_capture_profile_rejects_junction_or_symlink_destination_alias(tmp_path: Path) -> None:
source_parent = tmp_path / "source-parent"
source = source_parent / "menu-probe.json"
alias_parent = tmp_path / "alias-parent"
source_parent.mkdir()
_copy_fixture("profile-before.json", source)
_directory_alias(alias_parent, source_parent)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, alias_parent / source.name, Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == "profile_source_destination_alias"
def test_capture_profile_rejects_non_windows_publication_before_destination_write(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
source = tmp_path / "menu-probe.json"
destination = tmp_path / "not-created" / "captured.json"
original = _copy_fixture("profile-before.json", source)
before = source.stat()
monkeypatch.setattr(evidence_module, "_WINDOWS_EVIDENCE_PUBLICATION", False, raising=False)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, destination, Path("C:/Projects/Board.PRJ"), None)
after = source.stat()
assert raised.value.code == "unsupported_platform"
assert source.read_bytes() == original
assert (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) == (
before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns,
)
assert not destination.parent.exists()
@@ -0,0 +1,94 @@
import ast
from pathlib import Path
import subprocess
import pytest
from dx_productivity.trial_task_center import native_helper
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.models import ProjectRecord, ProjectStatus, RuleRecord
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
SOURCE = Path(__file__).resolve().parents[2] / 'integration/dxdesigner795/QuickPartReplace.vbs'
def test_native_route_never_injects_global_mouse_or_keyboard():
tree = ast.parse(Path(native_helper.__file__).read_text(encoding='utf-8'))
forbidden = {'SetCursorPos', 'mouse_event', 'keybd_event', 'click_input', 'SetForegroundWindow', 'BlockInput'}
used = {node.attr for node in ast.walk(tree) if isinstance(node, ast.Attribute)}
assert not used & forbidden
def test_installed_resource_resolves_without_attaching_to_cad():
executable = Path('D:/Mentor/7.9.5EE/SDD_HOME/wv/win32/bin/viewdraw.exe')
if not executable.is_file():
pytest.skip('Installed DxDesigner resource not available')
assert native_helper.replacement_command_from_resources(executable) == 33977
def test_mixed_no_match_queue_resumes_without_blocking_or_false_success(tmp_path):
projects = tuple(ProjectRecord(f'project-{index}', 'task', f'Project {index}',
tmp_path / f'project-{index}.prj', tmp_path, True, True,
ProjectStatus.PENDING, 0) for index in range(3))
rules = (RuleRecord('rule', 'task', 0, 'OLD', 'NEW', True),)
states = ['no_match', 'restored_ok', 'no_match']
called = []
def worker(command, timeout):
rows = [line.split('\t') for line in (tmp_path / 'quick-run/command.tsv').read_text(encoding='utf-8').splitlines()[1:]]
row = rows[len(called)]
assert command[-1] == row[1]
state = states[len(called)]
with (tmp_path / 'quick-run/status.tsv').open('a', encoding='utf-8') as handle:
if state == 'restored_ok':
handle.write(f'{row[1]}\tawaiting_native_replace\t\tcaptured\n')
handle.write(f'{row[1]}\t{state}\t\tchecked current sheet\n')
called.append(row[1])
return subprocess.CompletedProcess(command, 0, '', '')
def preparer():
return QuickRunPreparer(tmp_path, script_source=SOURCE, process_runner=worker,
cscript_resolver=lambda: Path('C:/Windows/SysWOW64/cscript.exe'))
runner = preparer()
for index in range(3):
result = runner.execute_step('task', projects, rules)
assert result.state == states[index]
runner = preparer()
progress = runner.progress('task', projects, rules)
assert progress.completed_items == index + 1
assert progress.no_match_items == [1, 1, 2][index]
assert progress.queue_complete and result.next_project_path is None
assert runner.current_phase('task', projects, rules) == 'complete'
with pytest.raises(TaskCenterError, match='quick_run_complete'):
runner.execute_step('task', projects, rules)
assert len(called) == 3
def test_no_match_cannot_mask_a_previously_captured_replacement(tmp_path):
from dx_productivity.trial_task_center.quick_run import _correlated_status_change
commands = (('task', 'job', 'project', 'OLD', 'NEW'),)
before = (('job', 'awaiting_native_replace', '', 'captured'),)
after = (*before, ('job', 'no_match', '', 'not found'))
assert _correlated_status_change(commands, before, after) is None
def test_invalid_transaction_evidence_never_promotes_pins(monkeypatch, tmp_path):
from types import SimpleNamespace
components = [SimpleNamespace(UID='outside-snapshot')]
monkeypatch.setattr(native_helper, 'read_snapshot', lambda path: (['M', 'project', 'OLD', 'NEW', 'sheet'],
[['C', 'recorded', 'R1', '0', '0', '0', '1', 'net']]))
monkeypatch.setattr(native_helper, 'attach', lambda: (object(), object()))
monkeypatch.setattr(native_helper, 'check_active_context', lambda *args: None)
monkeypatch.setattr(native_helper, 'components_on_sheet', lambda *args: components)
monkeypatch.setattr(native_helper, 'attribute_value', lambda *args: 'OLD')
calls = []
monkeypatch.setattr(native_helper, 'promote_pin_numbers', lambda *args: calls.append(args))
report = {}
with pytest.raises(ValueError, match='Cannot prove'):
native_helper.run_native(tmp_path / 'snapshot.tsv', report)
assert calls == []
assert report == {}
@@ -0,0 +1,180 @@
import json
import logging
from logging.handlers import RotatingFileHandler
from pathlib import Path
import sys
import threading
import time
import dx_productivity.trial_task_center.logging_setup as logging_setup
from dx_productivity.trial_task_center.logging_setup import (
_next_event_sequence,
_tail_utf8_lines,
append_task_event,
capture_subprocess_output,
configure_logging,
install_exception_hooks,
)
def test_configure_logging_creates_utf8_rotating_application_log(tmp_path: Path) -> None:
"""A long-running trial must retain bounded readable diagnostics."""
context = configure_logging(tmp_path)
handlers = [handler for handler in context.logger.handlers if isinstance(handler, RotatingFileHandler)]
assert context.application_log_path == tmp_path / "logs" / "application.log"
assert context.application_log_path.exists()
assert len(handlers) == 1
assert handlers[0].maxBytes == 5 * 1024 * 1024
assert handlers[0].backupCount == 5
assert handlers[0].encoding == "utf-8"
def test_relative_logging_root_reuses_one_utc_handler(tmp_path: Path, monkeypatch) -> None:
"""Repeated startup from a relative storage root must neither duplicate nor mislabel timestamps."""
monkeypatch.chdir(tmp_path)
first = configure_logging(Path("task-center"))
second = configure_logging(Path("task-center"))
handlers = [handler for handler in first.logger.handlers if isinstance(handler, RotatingFileHandler)]
record = logging.LogRecord("trial", logging.INFO, __file__, 1, "message", (), None)
record.created = 0
assert first.root == tmp_path / "task-center"
assert first.application_log_path == tmp_path / "task-center" / "logs" / "application.log"
assert first.logger is second.logger
assert len(handlers) == 1
assert handlers[0].formatter.converter is time.gmtime
assert handlers[0].formatter.format(record).startswith("1970-01-01T00:00:00Z")
def test_task_events_are_canonical_json_and_visible_before_return(tmp_path: Path) -> None:
"""The UI must not report an action before its task event is durable and readable."""
context = configure_logging(tmp_path)
first = append_task_event(
context,
level="INFO",
task_id="task-1",
project_id="project-1",
operation="scan",
state_before="pending",
state_after="pending",
message="scan complete",
details={"count": 2},
)
second = append_task_event(context, level="WARNING", task_id="task-1", operation="rescan")
event_path = tmp_path / "tasks" / "task-1" / "events.jsonl"
lines = event_path.read_text(encoding="utf-8").splitlines()
decoded = json.loads(lines[0])
assert first["sequence"] == 1
assert second["sequence"] == 2
assert list(decoded) == [
"sequence",
"timestamp_utc",
"level",
"task_id",
"project_id",
"operation",
"state_before",
"state_after",
"error_id",
"message",
"details",
]
assert decoded["details"] == {"count": 2}
assert json.loads(lines[1])["operation"] == "rescan"
def test_tail_reader_handles_large_utf8_lines_and_sequence_without_full_text_read(tmp_path: Path) -> None:
path = tmp_path / "events.jsonl"
large_prefix = "汉" * 5000
records = [
json.dumps({"sequence": 40, "message": large_prefix}, ensure_ascii=False),
json.dumps({"sequence": 41, "message": "倒数第二条"}, ensure_ascii=False),
json.dumps({"sequence": 42, "message": "最后一条"}, ensure_ascii=False),
]
path.write_text("\n".join(records) + "\n", encoding="utf-8")
assert _tail_utf8_lines(path, 2) == tuple(records[-2:])
assert _next_event_sequence(path) == 43
def test_task_event_rotation_keeps_sequence_contiguous_across_segments(tmp_path: Path, monkeypatch) -> None:
monkeypatch.setattr(logging_setup, "_MAX_EVENT_LOG_BYTES", 300)
context = configure_logging(tmp_path)
for index in range(12):
append_task_event(
context,
level="INFO",
task_id="rotating-task",
operation="stress_event",
message=f"event-{index}-" + "x" * 80,
)
current = tmp_path / "tasks" / "rotating-task" / "events.jsonl"
segments = [current.with_name(f"{current.name}.{index}") for index in range(5, 0, -1)]
segments.append(current)
records = [
json.loads(line)
for segment in segments
if segment.exists()
for line in segment.read_text(encoding="utf-8").splitlines()
]
assert [record["sequence"] for record in records] == list(range(7, 13))
assert _next_event_sequence(current) == 13
def test_exception_and_subprocess_helpers_record_traceback_and_streams(tmp_path: Path) -> None:
"""Unhandled details stay in the log, while the stable error ID is available to callers."""
context = configure_logging(tmp_path)
try:
raise RuntimeError("broken command")
except RuntimeError as error:
reported = context.report_exception("probe", error)
capture_subprocess_output(
context,
operation="probe-command",
returncode=4,
stdout="probe stdout",
stderr="probe stderr",
)
application_log = context.application_log_path.read_text(encoding="utf-8")
assert reported.error_id.startswith("DXT-")
assert "RuntimeError: broken command" in application_log
assert reported.error_id in application_log
assert "probe stdout" in application_log
assert "probe stderr" in application_log
assert "returncode=4" in application_log
def test_exception_hooks_log_worker_exception_with_error_id(tmp_path: Path) -> None:
"""A worker crash must be correlated in application.log rather than silently disappearing."""
context = configure_logging(tmp_path)
previous_sys_hook = sys.excepthook
previous_thread_hook = threading.excepthook
try:
install_exception_hooks(context)
def fail_worker() -> None:
raise RuntimeError("worker failure")
worker = threading.Thread(target=fail_worker, name="test-worker")
worker.start()
worker.join()
finally:
sys.excepthook = previous_sys_hook
threading.excepthook = previous_thread_hook
application_log = context.application_log_path.read_text(encoding="utf-8")
assert "worker failure" in application_log
assert "test-worker" in application_log
assert "DXT-" in application_log
@@ -0,0 +1,108 @@
from pathlib import Path
import sqlite3
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.models import TaskStatus
from dx_productivity.trial_task_center.service import TaskCenterService, _quick_run_lease
from dx_productivity.trial_task_center.store import TaskStore
@pytest.fixture
def populated(tmp_path):
store = TaskStore(tmp_path / 'tasks.db')
data = tmp_path / 'data'
service = TaskCenterService(store, configure_logging(data))
task = service.create_task('Delete me')
other = service.create_task('Keep me')
project_file = tmp_path / 'keep.prj'
project_file.write_text('original engineering data', encoding='utf-8')
project = service.scan_projects(task.task_id, tmp_path)[0]
service.add_rule(task.task_id, 'OLD', 'NEW')
with store.transaction():
store._connection.execute('INSERT INTO attempts(project_id,attempt_number,probe_source,baseline_size,baseline_sha256,baseline_modified_ns,rules_json) VALUES(?,1,?,0,?,0,?)',
(project.project_id, 'probe', 'hash', '[]'))
store._connection.execute('INSERT INTO migration_recoveries(project_id,task_id,project_before,project_after,error_id,project_summary) VALUES(?,?,?,?,?,?)',
(project.project_id, task.task_id, 'pending', 'failed', 'error', 'history'))
yield store, service, task, other, project_file, data
store.close()
def test_permanent_delete_removes_relations_and_releases_name(populated):
store, service, task, other, project_file, data = populated
service.delete_task(task.task_id)
evidence = data / 'tasks' / task.task_id / 'evidence.txt'
evidence.parent.mkdir(parents=True, exist_ok=True)
evidence.write_text('retained diagnostic evidence', encoding='utf-8')
assert service.purge_task(task.task_id, confirmed=True) == task.task_id
with pytest.raises(TaskCenterError, match='unknown_task'):
store.get_task(task.task_id)
for table in ('rules', 'projects', 'attempts', 'migration_recoveries'):
assert store._connection.execute(f'SELECT COUNT(*) FROM {table}').fetchone()[0] == 0
assert store._connection.execute('PRAGMA foreign_key_check').fetchall() == []
assert service.get_task(other.task_id).name == 'Keep me'
assert service.create_task('Delete me').task_id != task.task_id
assert project_file.read_text(encoding='utf-8') == 'original engineering data'
assert evidence.read_text(encoding='utf-8') == 'retained diagnostic evidence'
def test_purge_requires_deleted_state_and_explicit_confirmation(populated):
store, service, task, _, _, _ = populated
with pytest.raises(TaskCenterError, match='task_not_deleted'):
service.purge_task(task.task_id, confirmed=True)
service.delete_task(task.task_id)
with pytest.raises(TaskCenterError, match='permanent_delete_confirmation'):
service.purge_task(task.task_id)
assert store.get_task(task.task_id).status is TaskStatus.DELETED
def test_failed_delete_rolls_back_all_child_deletions(populated):
store, service, task, _, _, _ = populated
service.delete_task(task.task_id)
store._connection.execute("CREATE TRIGGER reject_purge BEFORE DELETE ON projects BEGIN SELECT RAISE(ABORT, 'injected failure'); END")
with pytest.raises(sqlite3.IntegrityError, match='injected failure'):
store.purge_task(task.task_id)
for table in ('rules', 'projects', 'attempts', 'migration_recoveries'):
assert store._connection.execute(f'SELECT COUNT(*) FROM {table}').fetchone()[0] == 1
assert store.get_task(task.task_id).status is TaskStatus.DELETED
def test_purge_deleted_task_bypasses_execution_lease(populated):
store, service, task, _, _, data = populated
service.delete_task(task.task_id)
with _quick_run_lease(data):
assert service.purge_task(task.task_id, confirmed=True) == task.task_id
with pytest.raises(TaskCenterError, match='unknown_task'):
store.get_task(task.task_id)
@pytest.mark.parametrize('state', ['awaiting_native_replace', 'hard_failure', 'invalid_state'])
def test_unresolved_queue_evidence_is_retained_after_task_purge(populated, state):
store, service, task, _, project_file, data = populated
service.delete_task(task.task_id)
queue = data / 'quick-run'
queue.mkdir()
(queue / 'command.tsv').write_text(f'task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\n{task.task_id}\tjob\t{project_file}\tOLD\tNEW\tpreserve\n', encoding='utf-8')
(queue / 'status.tsv').write_text(f'job_id\tstate\tcode\tmessage\njob\t{state}\t\tretained\n', encoding='utf-8')
assert service.purge_task(task.task_id, confirmed=True) == task.task_id
with pytest.raises(TaskCenterError, match='unknown_task'):
store.get_task(task.task_id)
assert (queue / 'command.tsv').is_file()
assert (queue / 'status.tsv').is_file()
assert project_file.read_text(encoding='utf-8') == 'original engineering data'
def test_deleted_completed_queue_can_be_viewed_and_purged(populated):
store, service, task, _, project_file, data = populated
service.set_project_selected(service.projects(task.task_id)[0].project_id, True)
queue = data / 'quick-run'
queue.mkdir()
(queue / 'command.tsv').write_text(f'task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\n{task.task_id}\tjob\t{project_file}\tOLD\tNEW\tpreserve\n', encoding='utf-8')
(queue / 'status.tsv').write_text('job_id\tstate\tcode\tmessage\njob\tno_match\t\tno changes\n', encoding='utf-8')
service.delete_task(task.task_id)
assert service.quick_run_progress(task.task_id).queue_complete
assert store.get_task(task.task_id).status is TaskStatus.DELETED
service.purge_task(task.task_id, confirmed=True)
assert (queue / 'command.tsv').is_file()
+980
View File
@@ -0,0 +1,980 @@
from __future__ import annotations
from datetime import datetime, timezone
from pathlib import Path
import json
import subprocess
from threading import Event, Thread
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.models import ProjectRecord, ProjectStatus, RuleRecord, TaskStatus
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
def _runtime_script(tmp_path: Path) -> Path:
script = tmp_path / "QuickPartReplace.vbs"
script.write_text("' fixture runtime\n", encoding="ascii")
return script
def _command_field(command_path: Path, name: str) -> str:
lines = command_path.read_text(encoding="utf-8").splitlines()
return lines[1].split("\t")[lines[0].split("\t").index(name)]
def _service(tmp_path: Path, runtime_script: Path) -> TaskCenterService:
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
return TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
configure_logging(tmp_path / "storage"),
quick_run_preparer=QuickRunPreparer(
tmp_path / "storage", script_source=runtime_script, run_token_factory=lambda: "run_abcdef"
),
clock=lambda: datetime(2026, 9, 4, tzinfo=timezone.utc),
)
def test_prepare_quick_run_exports_selected_available_projects_and_enabled_rules_as_utf8_jobs(tmp_path: Path) -> None:
"""A command that includes hidden rows can apply replacement to an unapproved project or rule."""
service = _service(tmp_path, _runtime_script(tmp_path))
task = service.create_task("Quick")
first_rule = service.add_rule(task.task_id, "OLD-1", "NEW-1")
disabled_rule = service.add_rule(task.task_id, "OLD-2", "NEW-2")
service.update_rule(disabled_rule.rule_id, old_part_number="OLD-2", new_part_number="NEW-2", enabled=False)
root = tmp_path / "projects"
root.mkdir()
(root / "first.prj").touch()
(root / "second.prj").touch()
projects = service.scan_projects(task.task_id, root)
service.set_project_selected(projects[0].project_id, True)
result = service.prepare_quick_run(task.task_id)
assert result.script_path.read_text(encoding="ascii") == "' fixture runtime\n"
assert result.command_path.read_bytes().decode("utf-8") == (
"task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode\r\n"
f"{task.task_id}\trun_abcdef_0\t{projects[0].path}\t{first_rule.old_part_number}\t{first_rule.new_part_number}\tpreserve\t\t1\tpreserve\r\n"
)
assert result.status_path == tmp_path / "storage" / "quick-run" / "status.tsv"
assert result.log_path == tmp_path / "storage" / "quick-run" / "quick-part-replace.log"
assert result.status_path.read_text(encoding="utf-8") == "job_id\tstate\tcode\tmessage\n"
assert result.log_path.is_file()
application_log = (tmp_path / "storage" / "logs" / "application.log").read_text(encoding="utf-8")
assert "quick_run_prepared" in application_log
def test_vbs_field_encoding_round_trips_unicode_delimiters_and_percent() -> None:
from dx_productivity.trial_task_center.quick_run import _decode_vbs_field, _encode_vbs_field
value = "中文%值\tline\r\nemoji:\U0001f600"
encoded = _encode_vbs_field(value)
assert encoded.isascii()
assert _decode_vbs_field(encoded) == value
def test_malformed_vbs_utf16_status_uses_stable_task_center_error(tmp_path: Path) -> None:
from dx_productivity.trial_task_center.quick_run import _read_status_details
status = tmp_path / "status.tsv"
status.write_text(
"job_id\tstate\tcode\tmessage\njob\trestored_ok\t\t%D800\n",
encoding="ascii",
)
with pytest.raises(TaskCenterError) as raised:
_read_status_details(status)
assert raised.value.code == "quick_run_status"
def test_prepare_quick_run_appends_its_log_and_uses_a_new_safe_run_token(tmp_path: Path) -> None:
"""Repreparing must not erase VBS evidence or reuse a snapshot filename from an earlier run."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
tokens = iter(("first", "second"))
runtime = _runtime_script(tmp_path)
preparer = QuickRunPreparer(
tmp_path,
script_source=runtime,
run_token_factory=lambda: next(tokens),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
first = preparer.prepare("task", (project,), (rule,))
first.log_path.write_text("vbs evidence\n", encoding="utf-8")
second = preparer.prepare("task", (project,), (rule,))
assert "vbs evidence" in second.log_path.read_text(encoding="utf-8")
assert _command_field(second.command_path, "job_id") == "second_0"
def test_prepare_quick_run_does_not_overwrite_an_awaiting_native_replace_status(tmp_path: Path) -> None:
"""A second export during manual replacement would orphan the VBS snapshot and its pending job."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
preparer = QuickRunPreparer(tmp_path, script_source=_runtime_script(tmp_path), run_token_factory=lambda: "next")
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
root = tmp_path / "quick-run"
root.mkdir()
command = root / "command.tsv"
status = root / "status.tsv"
command.write_text("old command\n", encoding="utf-8")
status.write_bytes(
"job_id\tstate\tcode\tmessage\r\npending_job\tawaiting_native_replace\t\tmanual selection\r\n".encode("utf-8-sig")
)
with pytest.raises(TaskCenterError) as raised:
preparer.prepare("task", (project,), (rule,))
assert raised.value.code == "quick_run_pending"
assert command.read_text(encoding="utf-8") == "old command\n"
assert "quick_run_pending" in (root / "quick-part-replace.log").read_text(encoding="utf-8")
def test_quick_run_queue_isolated_by_task_id_even_when_paths_and_rules_match(tmp_path: Path) -> None:
"""A completed queue for one task must be archived before a same-shaped task starts."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
import subprocess
calls: list[tuple[str, ...]] = []
opened: list[Path] = []
def run_script(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
assert timeout == 150
calls.append(command)
command_path = tmp_path / "storage" / "quick-run" / "command.tsv"
job_id = _command_field(command_path, "job_id")
(tmp_path / "storage" / "quick-run" / "status.tsv").write_text(
"job_id\tstate\tcode\tmessage\n"
f"{job_id}\tawaiting_native_replace\t\tSnapshot captured.\n"
f"{job_id}\trestored_ok\t\tAutomatic replacement verified.\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0, "", "")
service = TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
configure_logging(tmp_path / "storage"),
path_opener=opened.append,
quick_run_preparer=QuickRunPreparer(
tmp_path / "storage",
script_source=_runtime_script(tmp_path),
process_runner=run_script,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
),
)
root = tmp_path / "projects"
root.mkdir()
(root / "same.prj").touch()
first = service.create_task("First")
first_project = service.scan_projects(first.task_id, root)[0]
service.set_project_selected(first_project.project_id, True)
service.add_rule(first.task_id, "OLD-1", "NEW-1")
second = service.create_task("Second")
second_project = service.scan_projects(second.task_id, root)[0]
service.set_project_selected(second_project.project_id, True)
service.add_rule(second.task_id, "OLD-1", "NEW-1")
service.execute_quick_run(first.task_id)
assert service.quick_run_phase(first.task_id) == "complete"
assert service.get_task(first.task_id).status is TaskStatus.COMPLETED
assert service.projects(first.task_id)[0].status is ProjectStatus.COMPLETED
assert service.open_evidence(first.task_id, first_project.project_id) == tmp_path / "storage" / "quick-run"
assert opened == [tmp_path / "storage" / "quick-run"]
assert service.quick_run_phase(second.task_id) == "selection"
assert service.execute_quick_run(second.task_id).state == "restored_ok"
assert len(calls) == 2
history = tmp_path / "storage" / "quick-run-history"
assert len(tuple(history.glob("obsolete-*"))) == 1
archived_evidence = service.open_evidence(first.task_id, first_project.project_id)
assert archived_evidence.parent == history
assert archived_evidence.name.startswith("obsolete-")
def test_service_rejects_concurrent_quick_run_execution(tmp_path: Path) -> None:
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
started = Event()
release = Event()
def blocking_runner(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
del timeout
started.set()
release.wait(5)
root = tmp_path / "storage" / "quick-run"
job_id = _command_field(root / "command.tsv", "job_id")
(root / "status.tsv").write_text(
"job_id\tstate\tcode\tmessage\n"
f"{job_id}\tawaiting_native_replace\t\tcaptured\n"
f"{job_id}\trestored_ok\t\tverified\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0, "", "")
service = TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
configure_logging(tmp_path / "storage"),
quick_run_preparer=QuickRunPreparer(
tmp_path / "storage",
script_source=_runtime_script(tmp_path),
process_runner=blocking_runner,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
),
)
project_root = tmp_path / "projects"
project_root.mkdir()
(project_root / "one.prj").touch()
task = service.create_task("Concurrent")
project = service.scan_projects(task.task_id, project_root)[0]
service.set_project_selected(project.project_id, True)
service.add_rule(task.task_id, "OLD", "NEW")
result: list[object] = []
worker = Thread(target=lambda: result.append(service.execute_quick_run(task.task_id)))
worker.start()
try:
assert started.wait(2)
with pytest.raises(TaskCenterError) as raised:
service.execute_quick_run(task.task_id)
assert raised.value.code == "quick_run_busy"
with pytest.raises(TaskCenterError) as delete_error:
service.delete_task(task.task_id)
assert delete_error.value.code == "quick_run_busy"
with pytest.raises(TaskCenterError) as rule_error:
service.add_rule(task.task_id, "OTHER", "TARGET")
assert rule_error.value.code == "quick_run_busy"
finally:
release.set()
worker.join(5)
assert len(result) == 1
def test_prepare_quick_run_rejects_malformed_status_without_overwriting_command(tmp_path: Path) -> None:
"""Treating a damaged status file as empty would overwrite an unknown operator state."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
preparer = QuickRunPreparer(tmp_path, script_source=_runtime_script(tmp_path))
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
root = tmp_path / "quick-run"
root.mkdir()
command = root / "command.tsv"
command.write_text("old command\n", encoding="utf-8")
(root / "status.tsv").write_text("not a status file\n", encoding="utf-8")
with pytest.raises(TaskCenterError) as raised:
preparer.prepare("task", (project,), (rule,))
assert raised.value.code == "quick_run_status"
assert command.read_text(encoding="utf-8") == "old command\n"
assert "quick_run_status_invalid" in (root / "quick-part-replace.log").read_text(encoding="utf-8")
def test_service_default_quick_run_uses_its_logging_data_root(tmp_path: Path) -> None:
"""The Python worker now passes this custom root to VBS instead of warning about a default-root mismatch."""
service = TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
configure_logging(tmp_path / "selected-data-root"),
clock=lambda: datetime(2026, 9, 4, tzinfo=timezone.utc),
)
task = service.create_task("Quick")
root = tmp_path / "projects"
root.mkdir()
(root / "one.prj").touch()
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
service.add_rule(task.task_id, "OLD", "NEW")
result = service.prepare_quick_run(task.task_id)
assert result.script_path.parent == tmp_path / "selected-data-root" / "quick-run"
assert result.vbs_root_compatible
application_log = (tmp_path / "selected-data-root" / "logs" / "application.log").read_text(encoding="utf-8")
assert "quick_run_vbs_root_mismatch" not in application_log
def test_prepare_quick_run_rejects_tab_or_newline_fields_before_writing_command(tmp_path: Path) -> None:
"""A TSV field containing a record delimiter could turn one approved mapping into extra commands."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
preparer = QuickRunPreparer(tmp_path, script_source=_runtime_script(tmp_path))
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD\tINJECTED", "NEW", True)
with pytest.raises(TaskCenterError) as raised:
preparer.prepare("task", (project,), (rule,))
assert raised.value.code == "quick_run_field"
assert not (tmp_path / "quick-run" / "command.tsv").exists()
def test_prepare_quick_run_reports_a_missing_runtime_resource(tmp_path: Path) -> None:
"""An empty frozen resource directory must fail before an operator receives a non-runnable script path."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
preparer = QuickRunPreparer(tmp_path, script_source=tmp_path / "missing.vbs")
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as raised:
preparer.prepare("task", (project,), (rule,))
assert raised.value.code == "quick_run_script_missing"
def test_execute_quick_step_launches_automatic_runtime_and_reports_completion(tmp_path: Path) -> None:
"""The GUI click must pass the hidden helper entry and finish restoration in one process."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _native_helper_launch_arguments
calls: list[tuple[tuple[str, ...], int]] = []
def run_script(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
calls.append((command, timeout))
status = tmp_path / "quick-run" / "status.tsv"
job_id = _command_field(tmp_path / "quick-run" / "command.tsv", "job_id")
status.write_text(
"job_id\tstate\tcode\tmessage\n"
f"{job_id}\tawaiting_native_replace\t\tSnapshot captured.\n"
f"{job_id}\trestored_ok\t\tReplaced and verified 2 current-sheet matches.\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0, "", "")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
run_token_factory=lambda: "one_click",
process_runner=run_script,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
result = preparer.execute_step("task", (project,), (rule,))
assert calls == [
((
"C:\\Windows\\SysWOW64\\cscript.exe",
"//nologo",
str(result.script_path),
str(tmp_path / "quick-run"),
*_native_helper_launch_arguments(),
_command_field(result.command_path, "job_id"),
), 150)
]
assert result.state == "restored_ok"
assert result.message == "Replaced and verified 2 current-sheet matches."
def test_execute_quick_step_accepts_capture_and_restore_rows_from_one_worker(tmp_path: Path) -> None:
"""Automatic VBS appends both durable transitions during the same invocation."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
command_bytes: list[bytes] = []
def run_script(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
del timeout
command_path = tmp_path / "quick-run" / "command.tsv"
status_path = tmp_path / "quick-run" / "status.tsv"
command_bytes.append(command_path.read_bytes())
job_id = _command_field(command_path, "job_id")
existing = status_path.read_text(encoding="utf-8")
status_path.write_text(
existing
+ f"{job_id}\tawaiting_native_replace\t\tcaptured\n"
+ f"{job_id}\trestored_ok\t\tverified\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0, "", "")
runtime = _runtime_script(tmp_path)
preparer = QuickRunPreparer(
tmp_path,
script_source=runtime,
run_token_factory=lambda: "stable_run",
process_runner=run_script,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
first = preparer.execute_step("task", (project,), (rule,))
assert first.state == "restored_ok"
assert len(command_bytes) == 1
def test_execute_quick_step_keeps_the_vbs_attach_failure_retriable(tmp_path: Path) -> None:
"""VBS exit 2 without a status row means DxDesigner was unavailable, not an uncertain mutation."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def attach_failure(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
calls += 1
return subprocess.CompletedProcess(command, 2, "", "DxDesigner unavailable")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=attach_failure,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (project,), (rule,))
with pytest.raises(TaskCenterError) as retry:
preparer.execute_step("task", (project,), (rule,))
assert calls == 2
assert raised.value.code == "quick_run_session"
assert retry.value.code == "quick_run_session"
assert not (tmp_path / "quick-run" / "uncertain.flag").exists()
assert "DxDesigner unavailable" in (tmp_path / "quick-run" / "quick-part-replace.log").read_text(encoding="utf-8")
def test_execute_quick_step_keeps_a_pre_mutation_vbs_failure_retriable(tmp_path: Path) -> None:
"""Exit 3 before a VBS job is selected cannot have modified the current sheet."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def wrong_project(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
calls += 1
return subprocess.CompletedProcess(command, 3, "", "The open project has no pending quick-run rule")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=wrong_project,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as first:
preparer.execute_step("task", (project,), (rule,))
with pytest.raises(TaskCenterError) as retry:
preparer.execute_step("task", (project,), (rule,))
assert calls == 2
assert first.value.code == "quick_run_session"
assert retry.value.code == "quick_run_session"
assert not (tmp_path / "quick-run" / "uncertain.flag").exists()
def test_execute_quick_step_locks_a_pre_mutation_exit_with_a_status_change(tmp_path: Path) -> None:
"""An exit 3 accompanied by a row is contradictory evidence and must not be retried."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
def contradictory_result(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
status = tmp_path / "quick-run" / "status.tsv"
job_id = _command_field(tmp_path / "quick-run" / "command.tsv", "job_id")
status.write_text(
"job_id\tstate\tcode\tmessage\n"
f"{job_id}\tawaiting_native_replace\t\tunexpected selection\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 3, "", "pre-mutation failure")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=contradictory_result,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (project,), (rule,))
assert raised.value.code == "quick_run_uncertain"
assert (tmp_path / "quick-run" / "uncertain.flag").is_file()
def test_current_phase_is_complete_when_every_matching_job_was_restored(tmp_path: Path) -> None:
"""A fully restored durable queue must not offer a new selection step."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
preparer = QuickRunPreparer(tmp_path, script_source=_runtime_script(tmp_path), run_token_factory=lambda: "complete")
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
handoff = preparer.prepare("task", (project,), (rule,))
job_id = _command_field(handoff.command_path, "job_id")
handoff.status_path.write_text(
"job_id\tstate\tcode\tmessage\n"
f"{job_id}\trestored_ok\t\trestored\n",
encoding="utf-8",
)
assert preparer.current_phase("task", (project,), (rule,)) == "complete"
def test_verified_rollback_clears_native_mutation_evidence(tmp_path: Path) -> None:
"""A queue may be replaced after VBS proves native Undo restored the exact snapshot."""
from dx_productivity.trial_task_center.quick_run import _queue_has_mutation_evidence
root = tmp_path / "quick-run"
root.mkdir()
report = root / "snapshot-job.tsv.native.json"
report.write_text('{"stage":"native_replace_verified","ok":true}', encoding="utf-8")
assert _queue_has_mutation_evidence(root)
(root / "snapshot-job.tsv.native.rolled-back").write_text("verified\n", encoding="utf-8")
assert not _queue_has_mutation_evidence(root)
def test_preflight_hard_failure_retries_only_its_job_in_a_partly_completed_queue(tmp_path: Path) -> None:
"""Mutation evidence from completed jobs must not block a preflight-only failed job."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def complete_retry(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
del command, timeout
calls += 1
root = tmp_path / "quick-run"
lines = (root / "command.tsv").read_text(encoding="utf-8").splitlines()
second_job = lines[2].split("\t")[1]
status = root / "status.tsv"
assert status.read_text(encoding="utf-8").splitlines()[-1].split("\t")[:2] == [
second_job,
"awaiting_native_replace",
]
status.write_text(
status.read_text(encoding="utf-8") + f"{second_job}\trestored_ok\t\tverified\n",
encoding="utf-8",
)
return subprocess.CompletedProcess((), 0, "", "")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
run_token_factory=lambda: "mixed",
process_runner=complete_retry,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
first = ProjectRecord("p1", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
second = ProjectRecord("p2", "task", "Two", Path("C:/two.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
handoff = preparer.prepare("task", (first, second), (rule,))
command_lines = handoff.command_path.read_text(encoding="utf-8").splitlines()
first_job = command_lines[1].split("\t")[1]
second_job = command_lines[2].split("\t")[1]
handoff.status_path.write_text(
"job_id\tstate\tcode\tmessage\n"
f"{first_job}\tawaiting_native_replace\t\tcaptured\n"
f"{first_job}\trestored_ok\t\tverified\n"
f"{second_job}\tawaiting_native_replace\t\tcaptured\n"
f"{second_job}\thard_failure\t1\tcursor API failed\n",
encoding="utf-8",
)
Path(str(tmp_path / "quick-run" / f"snapshot-{first_job}.tsv") + ".native.json").write_text(
'{"stage":"native_replace_verified","ok":true}', encoding="utf-8"
)
Path(str(tmp_path / "quick-run" / f"snapshot-{second_job}.tsv") + ".native.json").write_text(
'{"stage":"preflight","ok":false}', encoding="utf-8"
)
result = preparer.execute_step("task", (first, second), (rule,))
assert calls == 1
assert result.state == "restored_ok"
states = [(job_id, state) for job_id, state, _, _ in __import__(
"dx_productivity.trial_task_center.quick_run", fromlist=["_read_status_details"]
)._read_status_details(handoff.status_path)]
assert states == [
(first_job, "awaiting_native_replace"),
(first_job, "restored_ok"),
(second_job, "awaiting_native_replace"),
(second_job, "restored_ok"),
]
def test_mutation_stage_hard_failure_still_blocks_a_partly_completed_queue(tmp_path: Path) -> None:
"""A failed job with possible native writes must never be made pending automatically."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
run_token_factory=lambda: "mixed",
process_runner=lambda command, timeout: pytest.fail("unsafe queue was executed"),
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
first = ProjectRecord("p1", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
second = ProjectRecord("p2", "task", "Two", Path("C:/two.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
handoff = preparer.prepare("task", (first, second), (rule,))
command_lines = handoff.command_path.read_text(encoding="utf-8").splitlines()
first_job = command_lines[1].split("\t")[1]
second_job = command_lines[2].split("\t")[1]
original_status = (
"job_id\tstate\tcode\tmessage\n"
f"{first_job}\tawaiting_native_replace\t\tcaptured\n"
f"{first_job}\trestored_ok\t\tverified\n"
f"{second_job}\tawaiting_native_replace\t\tcaptured\n"
f"{second_job}\thard_failure\t1\tnative write failed\n"
)
handoff.status_path.write_text(original_status, encoding="utf-8")
Path(str(tmp_path / "quick-run" / f"snapshot-{first_job}.tsv") + ".native.json").write_text(
'{"stage":"native_replace_verified","ok":true}', encoding="utf-8"
)
Path(str(tmp_path / "quick-run" / f"snapshot-{second_job}.tsv") + ".native.json").write_text(
'{"stage":"native_replace_started","ok":false}', encoding="utf-8"
)
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (first, second), (rule,))
assert raised.value.code == "quick_run_execution"
assert handoff.status_path.read_text(encoding="utf-8") == original_status
def test_execute_quick_step_locks_a_zero_exit_without_status(tmp_path: Path) -> None:
"""A successful process exit without an expected VBS status can still hide an uncertain native mutation."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def no_status(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
calls += 1
return subprocess.CompletedProcess(command, 0, "", "")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=no_status,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as first:
preparer.execute_step("task", (project,), (rule,))
with pytest.raises(TaskCenterError) as second:
preparer.execute_step("task", (project,), (rule,))
assert calls == 1
assert first.value.code == "quick_run_uncertain"
assert second.value.code == "quick_run_uncertain"
assert (tmp_path / "quick-run" / "uncertain.flag").is_file()
def test_execute_quick_step_rejects_an_appended_status_for_an_unrelated_job(tmp_path: Path) -> None:
"""Another Task Center instance must not be able to satisfy this execution with its status row."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
def run_script(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
del timeout
status = tmp_path / "quick-run" / "status.tsv"
status.write_text(
status.read_text(encoding="utf-8") + "other_job\tawaiting_native_replace\t\tunrelated\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0, "", "")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=run_script,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (project,), (rule,))
assert raised.value.code == "quick_run_uncertain"
@pytest.mark.parametrize("report", [None, '{"stage":"native_replace_started","transaction":{}}', '{"stage":"preflight","ok":false}'])
def test_native_failure_exposes_recovery_unless_preflight_proves_no_mutation(tmp_path: Path, report) -> None:
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
def native_failure(command, timeout):
root = tmp_path / "quick-run"
job_id = _command_field(root / "command.tsv", "job_id")
(root / "status.tsv").write_text(
"job_id\tstate\tcode\tmessage\n"
f"{job_id}\tawaiting_native_replace\t\tstarted\n"
f"{job_id}\thard_failure\t1\tnative failure\n", encoding="utf-8")
if report is not None:
(root / f"snapshot-{job_id}.tsv.native.json").write_text(report, encoding="utf-8")
return subprocess.CompletedProcess(command, 1, "", "native failure")
preparer = QuickRunPreparer(tmp_path, script_source=_runtime_script(tmp_path), process_runner=native_failure,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"))
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (project,), (rule,))
safe = report is not None and 'preflight' in report
assert raised.value.code == ("quick_run_preflight" if safe else "quick_run_uncertain")
assert (tmp_path / "quick-run/uncertain.flag").exists() is not safe
@pytest.mark.parametrize("exit_code", [0, 91])
def test_worker_exit_without_native_completion_requires_reconciliation(tmp_path: Path, exit_code) -> None:
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
def interrupted_worker(command, timeout):
root = tmp_path / "quick-run"
job_id = _command_field(root / "command.tsv", "job_id")
(root / "status.tsv").write_text("job_id\tstate\tcode\tmessage\n" +
f"{job_id}\tawaiting_native_replace\t\tstarted\n", encoding="utf-8")
return subprocess.CompletedProcess(command, exit_code, "", "")
preparer = QuickRunPreparer(tmp_path, script_source=_runtime_script(tmp_path), process_runner=interrupted_worker,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"))
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (project,), (rule,))
assert raised.value.code == "quick_run_uncertain"
assert (tmp_path / "quick-run/uncertain.flag").is_file()
def test_execute_quick_step_blocks_retry_after_a_worker_timeout(tmp_path: Path) -> None:
"""A killed COM worker may have changed the design and must require manual reconciliation."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def time_out(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
calls += 1
raise subprocess.TimeoutExpired(command, timeout)
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=time_out,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError):
preparer.execute_step("task", (project,), (rule,))
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (project,), (rule,))
assert calls == 1
assert raised.value.code == "quick_run_uncertain"
assert (tmp_path / "quick-run" / "uncertain.flag").is_file()
def test_execute_quick_step_keeps_timeout_lock_when_the_queue_input_changes(tmp_path: Path) -> None:
"""Changing a rule after a timeout must not turn an uncertain native mutation into a fresh queue."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def time_out(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
calls += 1
raise subprocess.TimeoutExpired(command, timeout)
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=time_out,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
first_rule = RuleRecord("rule-1", "task", 0, "OLD", "NEW", True)
changed_rule = RuleRecord("rule-2", "task", 0, "OTHER", "NEWER", True)
with pytest.raises(TaskCenterError):
preparer.execute_step("task", (project,), (first_rule,))
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (project,), (changed_rule,))
assert calls == 1
assert raised.value.code == "quick_run_uncertain"
def test_execute_quick_step_marks_two_appended_status_rows_as_uncertain(tmp_path: Path) -> None:
"""A valid worker row plus a concurrent append leaves correlation ambiguous and must lock execution."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def append_two_rows(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
del timeout
calls += 1
root = tmp_path / "quick-run"
job_id = _command_field(root / "command.tsv", "job_id")
status = root / "status.tsv"
status.write_text(
status.read_text(encoding="utf-8")
+ f"{job_id}\tawaiting_native_replace\t\tselected\n"
+ "other_job\thard_failure\t\tconcurrent\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0, "", "")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=append_two_rows,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as first:
preparer.execute_step("task", (project,), (rule,))
with pytest.raises(TaskCenterError) as second:
preparer.execute_step("task", (project,), (rule,))
assert calls == 1
assert first.value.code == "quick_run_uncertain"
assert second.value.code == "quick_run_uncertain"
assert (tmp_path / "quick-run" / "uncertain.flag").is_file()
def test_verified_native_rollback_stops_without_uncertain_lock(tmp_path: Path) -> None:
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
def rolled_back(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
del timeout
root = tmp_path / "quick-run"
job_id = command[-1]
snapshot = root / f"snapshot-{job_id}.tsv"
snapshot.write_text("snapshot", encoding="utf-8")
snapshot.with_suffix(".tsv.native.json").write_text(
json.dumps({"stage": "native_replace_verified", "ok": False}), encoding="utf-8"
)
Path(str(snapshot) + ".native.rolled-back").write_text(
"native replacement rollback verified\n", encoding="utf-8"
)
with (root / "status.tsv").open("a", encoding="utf-8") as stream:
stream.write(f"{job_id}\tawaiting_native_replace\t\tstarted\n")
return subprocess.CompletedProcess(command, 1, "", "validation failed")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=rolled_back,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError, match="quick_run_rollback_verified") as raised:
preparer.execute_step("task", (project,), (rule,))
assert "已恢复到替换前状态" in raised.value.message
assert not (tmp_path / "quick-run/uncertain.flag").exists()
assert "rollback_verified" in (tmp_path / "quick-run/status.tsv").read_text(encoding="utf-8")
def test_verified_rollback_terminal_failure_can_be_retried_without_recovery_lock(tmp_path: Path) -> None:
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def worker(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
del timeout
calls += 1
root = tmp_path / "quick-run"
job_id = command[-1]
with (root / "status.tsv").open("a", encoding="utf-8") as stream:
if calls == 1:
stream.write(f"{job_id}\tawaiting_native_replace\t\tstarted\n")
stream.write(f"{job_id}\thard_failure\trollback_verified\trolled back\n")
snapshot = root / f"snapshot-{job_id}.tsv"
snapshot.write_text("snapshot", encoding="utf-8")
snapshot.with_suffix(".tsv.native.json").write_text(
json.dumps({"stage": "native_replace_verified", "ok": False}), encoding="utf-8"
)
Path(str(snapshot) + ".native.rolled-back").write_text(
"native replacement rollback verified\n", encoding="utf-8"
)
return subprocess.CompletedProcess(command, 1, "", "validation failed")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=worker,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError, match="quick_run_rollback_verified"):
preparer.execute_step("task", (project,), (rule,))
with pytest.raises(TaskCenterError, match="quick_run_rollback_verified"):
preparer.execute_step("task", (project,), (rule,))
assert calls == 2
assert not (tmp_path / "quick-run/uncertain.flag").exists()
def test_resolve_cscript_requires_syswow64_on_a_64_bit_host(tmp_path: Path) -> None:
"""Falling back to a 64-bit script host cannot attach reliably to 32-bit EE 7.9.5 COM."""
from dx_productivity.trial_task_center.quick_run import _resolve_cscript
system32 = tmp_path / "System32"
system32.mkdir()
(system32 / "cscript.exe").touch()
with pytest.raises(TaskCenterError) as raised:
_resolve_cscript(tmp_path, is_64_bit=True)
assert raised.value.code == "quick_run_cscript"
def test_restored_step_reports_the_next_project_that_must_be_opened(tmp_path: Path) -> None:
"""A batch queue must tell the operator which project to open before launching its next rule."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
def run_script(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
del timeout
command_path = tmp_path / "quick-run" / "command.tsv"
status_path = tmp_path / "quick-run" / "status.tsv"
first_job = _command_field(command_path, "job_id")
status_path.write_text(
status_path.read_text(encoding="utf-8")
+ f"{first_job}\tawaiting_native_replace\t\tcaptured\n"
+ f"{first_job}\trestored_ok\t\tverified\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0, "", "")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=run_script,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
first = ProjectRecord("p1", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
second = ProjectRecord("p2", "task", "Two", Path("C:/two.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
result = preparer.execute_step("task", (first, second), (rule,))
assert result.state == "restored_ok"
assert result.next_project_path == second.path
assert result.next_old_part_number == "OLD"
assert result.next_new_part_number == "NEW"
+288
View File
@@ -0,0 +1,288 @@
import json
from pathlib import Path
import subprocess
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.native_helper import read_snapshot, transaction_binding
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _read_commands, _read_status_details
from dx_productivity.trial_task_center.recovery import _is_link_or_reparse, _recovery_hashes, recover
def test_link_detection_does_not_require_path_is_junction():
path = SimpleNamespace(lstat=lambda: SimpleNamespace(st_mode=0, st_file_attributes=0))
assert not _is_link_or_reparse(path)
def test_locked_recovery_files_return_stable_recovery_error(tmp_path, monkeypatch):
import dx_productivity.trial_task_center.recovery as recovery_module
def locked(_root):
raise PermissionError('locked')
monkeypatch.setattr(recovery_module, '_hashes', locked)
with pytest.raises(TaskCenterError) as raised:
_recovery_hashes(tmp_path)
assert raised.value.code == 'quick_run_recovery'
assert '占用' in raised.value.message
@pytest.fixture
def interrupted(tmp_path):
project = tmp_path / 'project' / 'one.prj'
project.parent.mkdir()
project.write_text('project')
script = tmp_path / 'runtime.vbs'
script.write_text('fixture runtime')
root = tmp_path / 'data'
preparer = QuickRunPreparer(root, script_source=script, run_token_factory=lambda: 'first',
cscript_resolver=lambda: Path('cscript.exe'))
projects = (SimpleNamespace(path=project, selected=True, available=True),)
rules = (SimpleNamespace(old_part_number='OLD', new_part_number='NEW', enabled=True),)
handoff = preparer.prepare('task', projects, rules, copy_part_number_to_value=True)
job = _read_commands(handoff.command_path)[0][1]
snapshot = handoff.command_path.parent / f'snapshot-{job}.tsv'
snapshot.write_text(f'M\t{project}\tOLD\tNEW\tA:1\tpart_label\nC\tuid\tR1\t0\t0\t0\t1\tpins\n', encoding='utf-8')
metadata, components = read_snapshot(snapshot)
report = {'stage': 'native_replace_verified', 'transaction': transaction_binding(
snapshot, metadata, components, ['library', 'NEW', 'symbol', '', 'cap', 'label'], 'symbol')}
snapshot.with_suffix('.tsv.native.json').write_text(json.dumps(report), encoding='utf-8')
handoff.status_path.write_text('job_id\tstate\tcode\tmessage\n' + job + '\tawaiting_native_replace\t\tstarted\n', encoding='utf-8')
lock = handoff.command_path.parent / 'uncertain.flag'
lock.write_text('old timeout')
return SimpleNamespace(preparer=preparer, root=root, projects=projects, rules=rules, snapshot=snapshot,
job=job, handoff=handoff, lock=lock, report=report)
def invoke(fixture, **kwargs):
return recover(fixture.preparer, 'task', fixture.projects, fixture.rules,
copy_part_number_to_value=True, confirmed=True, **kwargs)
def worker_result(fixture, state='restored_ok', job=None, code=0):
def run(command, timeout):
worker = Path(command[3])
assert worker != fixture.lock.parent
assert (worker / 'recovery.request').read_text() == fixture.job
assert timeout == 150
assert fixture.lock.exists()
(worker / 'status.tsv').write_text('job_id\tstate\tcode\tmessage\n' + (job or fixture.job) + '\t' + state + '\t\tverified\n')
return subprocess.CompletedProcess(command, code, '', '')
return run
@pytest.mark.parametrize('hard_failure', [False, True])
def test_legacy_interruption_without_flag_can_be_reconciled_only_with_bound_evidence(interrupted, hard_failure):
interrupted.lock.unlink()
if hard_failure:
with interrupted.handoff.status_path.open('a', encoding='utf-8') as stream:
stream.write(interrupted.job + '\thard_failure\t1\tnative write failed\n')
assert interrupted.preparer.has_interrupted('task')
assert not interrupted.preparer.has_interrupted('other-task')
interrupted.preparer._process_runner = worker_result(interrupted, 'retry_ready')
result = invoke(interrupted)
assert result.state == 'retry_ready'
assert not interrupted.lock.exists()
assert not interrupted.preparer.has_interrupted('task')
def test_preflight_failure_without_transaction_does_not_offer_unsafe_recovery(interrupted):
interrupted.lock.unlink()
with interrupted.handoff.status_path.open('a', encoding='utf-8') as stream:
stream.write(interrupted.job + '\thard_failure\t1\tmissing target\n')
interrupted.snapshot.with_suffix('.tsv.native.json').write_text('{"stage":"preflight","ok":false}', encoding='utf-8')
assert not interrupted.preparer.has_interrupted('task')
with pytest.raises(TaskCenterError):
invoke(interrupted)
assert not interrupted.lock.exists()
def test_recovery_requires_explicit_confirmation(interrupted):
with pytest.raises(TaskCenterError, match='quick_run_recovery_confirmation'):
recover(interrupted.preparer, 'task', interrupted.projects, interrupted.rules)
assert interrupted.lock.exists()
def test_verified_recovery_preserves_evidence_and_commits_once(interrupted):
interrupted.preparer._process_runner = worker_result(interrupted)
snapshot = interrupted.snapshot.read_bytes()
result = invoke(interrupted)
assert result.state == 'restored_ok'
assert result.next_project_path is None
assert not interrupted.lock.exists()
assert interrupted.snapshot.read_bytes() == snapshot
assert _read_status_details(interrupted.handoff.status_path)[-1][1] == 'restored_ok'
audit = next((interrupted.root / 'quick-run-history').glob('recovery-*'))
assert (audit / 'resolved-uncertain.flag').read_text() == 'old timeout'
assert (audit / 'evidence-before' / interrupted.snapshot.name).read_bytes() == snapshot
with pytest.raises(TaskCenterError):
invoke(interrupted)
def test_r12_part_number_queue_keeps_recorded_policy_during_recovery(interrupted):
command_path = interrupted.handoff.command_path
lines = [line.split('\t') for line in command_path.read_text(encoding='utf-8').splitlines()]
for column in ('value_mode', 'base_value_mode'):
lines[1][lines[0].index(column)] = 'part_number'
command_path.write_text('\n'.join('\t'.join(line) for line in lines) + '\n', encoding='utf-8')
interrupted.snapshot.write_text(
interrupted.snapshot.read_text(encoding='utf-8').replace('\tpart_label\n', '\tpart_number\n'),
encoding='utf-8',
)
metadata, components = read_snapshot(interrupted.snapshot)
report = {'stage': 'native_replace_verified', 'transaction': transaction_binding(
interrupted.snapshot, metadata, components,
['library', 'NEW', 'symbol', '', 'cap', 'label'], 'symbol')}
interrupted.snapshot.with_suffix('.tsv.native.json').write_text(json.dumps(report), encoding='utf-8')
def worker(command, timeout):
worker_root = Path(command[3])
assert '\tpart_number\t' in (worker_root / 'command.tsv').read_text(encoding='utf-8')
return worker_result(interrupted)(command, timeout)
interrupted.preparer._process_runner = worker
result = invoke(interrupted)
assert result.state == 'restored_ok'
assert result.next_project_path is None
assert interrupted.preparer.progress(
'task', interrupted.projects, interrupted.rules, copy_part_number_to_value=True
).queue_complete
def test_page_addressed_recovery_keeps_the_original_sheet_binding(interrupted):
project = interrupted.projects[0].path
interrupted.handoff.command_path.write_text(
'task_id\tjob_id\tproject_path\tschematic_name\tsheet_number\told_part\tnew_part\tvalue_mode\n'
f'task\t{interrupted.job}\t{project}\tA\t1\tOLD\tNEW\tpart_label\n',
encoding='utf-8',
)
(interrupted.handoff.command_path.parent / 'sheets.tsv').write_text(
'project_path\tschematic_name\tsheet_number\n'
f'{project}\tA\t1\n',
encoding='utf-8',
)
def worker(command, timeout):
worker_root = Path(command[3])
header = (worker_root / 'command.tsv').read_text(encoding='utf-8').splitlines()[0].split('\t')
row = (worker_root / 'command.tsv').read_text(encoding='utf-8').splitlines()[1].split('\t')
assert row[header.index('schematic_name')] == 'A'
assert row[header.index('sheet_number')] == '1'
assert (worker_root / 'sheets.tsv').is_file()
(worker_root / 'status.tsv').write_text(
f'job_id\tstate\tcode\tmessage\n{interrupted.job}\trestored_ok\t\tverified\n',
encoding='utf-8',
)
return subprocess.CompletedProcess(command, 0, '', '')
interrupted.preparer._process_runner = worker
result = invoke(interrupted)
assert result.state == 'restored_ok'
assert result.next_project_path is None
def test_unsaved_recovery_creates_fresh_job_without_replacing(interrupted):
interrupted.preparer._process_runner = worker_result(interrupted, 'retry_ready')
result = invoke(interrupted)
assert result.state == 'retry_ready'
assert result.next_project_path == interrupted.projects[0].path
assert _read_commands(interrupted.handoff.command_path)[0][1] != interrupted.job
assert _read_status_details(interrupted.handoff.status_path) == ()
assert interrupted.snapshot.exists()
@pytest.mark.parametrize(('state', 'job', 'code'), [('hard_failure', None, 1), ('restored_ok', 'foreign', 0),
('awaiting_native_replace', None, 0), ('restored_ok', None, 2)])
def test_uncorrelated_or_failed_recovery_never_unlocks(interrupted, state, job, code):
before = interrupted.handoff.status_path.read_bytes()
interrupted.preparer._process_runner = worker_result(interrupted, state, job, code)
with pytest.raises(TaskCenterError):
invoke(interrupted)
assert interrupted.lock.exists()
assert interrupted.handoff.status_path.read_bytes() == before
def test_recovery_timeout_keeps_old_lock(interrupted):
def timeout(command, seconds):
raise subprocess.TimeoutExpired(command, seconds)
interrupted.preparer._process_runner = timeout
with pytest.raises(TaskCenterError):
invoke(interrupted)
assert interrupted.lock.read_text() == 'old timeout'
def test_snapshot_binding_mismatch_prevents_worker_start(interrupted):
interrupted.snapshot.write_text(interrupted.snapshot.read_text() + '\n')
with pytest.raises(TaskCenterError):
invoke(interrupted)
assert interrupted.lock.exists()
assert not (interrupted.root / 'quick-run-history').exists()
def test_concurrent_evidence_change_does_not_commit(interrupted):
worker = worker_result(interrupted)
def change(command, seconds):
result = worker(command, seconds)
interrupted.lock.write_text('new protection')
return result
interrupted.preparer._process_runner = change
with pytest.raises(TaskCenterError):
invoke(interrupted)
assert interrupted.lock.read_text() == 'new protection'
def test_other_pending_job_prevents_global_unlock(interrupted):
with interrupted.handoff.status_path.open('a') as stream:
stream.write('other-job\thard_failure\t\tunknown\n')
with pytest.raises(TaskCenterError):
invoke(interrupted)
assert interrupted.lock.exists()
def test_failed_commit_restores_status_and_lock(interrupted, monkeypatch):
from dx_productivity.trial_task_center import recovery
interrupted.preparer._process_runner = worker_result(interrupted)
original = interrupted.handoff.status_path.read_bytes()
real_replace = recovery.os.replace
def fail_unlock(source, target):
if Path(source) == interrupted.lock:
raise PermissionError('locked')
return real_replace(source, target)
monkeypatch.setattr(recovery.os, 'replace', fail_unlock)
with pytest.raises(PermissionError):
invoke(interrupted)
assert interrupted.lock.exists()
assert interrupted.handoff.status_path.read_bytes() == original
@pytest.mark.parametrize('initial', ['ready', 'paused', 'failed'])
def test_service_recovery_updates_queue_and_database(interrupted, initial):
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.models import TaskStatus
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
store = TaskStore(interrupted.root / 'task-center.db')
service = TaskCenterService(store, configure_logging(interrupted.root), quick_run_preparer=interrupted.preparer)
task = service.create_task('Interrupted')
service.set_copy_part_number_to_value(task.task_id, True)
projects = service.scan_projects(task.task_id, interrupted.projects[0].path.parent)
service.set_project_selected(projects[0].project_id, True)
service.add_rule(task.task_id, 'OLD', 'NEW')
command_path = interrupted.handoff.command_path
command_path.write_text(command_path.read_text().replace('task\t', task.task_id + '\t'), encoding='utf-8')
if store.get_task(task.task_id).status is TaskStatus.DRAFT:
store.set_task_status(task.task_id, TaskStatus.READY)
if initial == 'paused':
store.set_task_status(task.task_id, TaskStatus.RUNNING)
store.set_task_status(task.task_id, TaskStatus.PAUSED)
elif initial == 'failed':
store.set_task_status(task.task_id, TaskStatus.FAILED)
interrupted.preparer._process_runner = worker_result(interrupted)
result = service.recover_quick_run(task.task_id, confirmed=True)
assert result.state == 'restored_ok'
assert store.get_task(task.task_id).status is TaskStatus.COMPLETED
assert service.quick_run_progress(task.task_id).queue_complete
assert not service.has_interrupted_quick_run(task.task_id)
+74
View File
@@ -0,0 +1,74 @@
from __future__ import annotations
import os
from pathlib import Path
from dx_productivity.trial_task_center.retention import (
maintain_quick_run_storage,
rotate_text_log,
)
def test_log_rotation_preserves_three_newest_complete_segments(tmp_path: Path) -> None:
log = tmp_path / "quick-part-replace.log"
for text in ("first", "second", "third", "fourth"):
log.write_text(text * 4, encoding="utf-8")
assert rotate_text_log(log, max_bytes=10, backup_count=3)
assert not log.exists()
assert log.with_name(f"{log.name}.1").read_text(encoding="utf-8") == "fourth" * 4
assert log.with_name(f"{log.name}.2").read_text(encoding="utf-8") == "third" * 4
assert log.with_name(f"{log.name}.3").read_text(encoding="utf-8") == "second" * 4
def test_history_retention_removes_only_oldest_recognized_entries(tmp_path: Path) -> None:
history = tmp_path / "quick-run-history"
history.mkdir()
now = 2_000_000_000.0
for index in range(6):
entry = history / f"batch-{index}"
entry.mkdir()
(entry / "evidence.bin").write_bytes(bytes(index + 1))
os.utime(entry, (now - 100 + index, now - 100 + index))
unknown = history / "operator-notes"
unknown.mkdir()
(unknown / "keep.txt").write_text("keep", encoding="utf-8")
result = maintain_quick_run_storage(
tmp_path,
now=now,
max_age_days=30,
max_entries=3,
max_bytes=1024,
min_entries=2,
)
assert result.removed_entries == ("batch-0", "batch-1", "batch-2")
assert result.removed_bytes == 1 + 2 + 3
assert result.skipped_entries == ()
assert {path.name for path in history.iterdir()} == {
"batch-3", "batch-4", "batch-5", "operator-notes"
}
def test_history_age_and_size_limits_never_delete_minimum_recent_entries(tmp_path: Path) -> None:
history = tmp_path / "quick-run-history"
history.mkdir()
now = 2_000_000_000.0
for index in range(4):
entry = history / f"recovery-{index}"
entry.mkdir()
(entry / "backup.bin").write_bytes(b"x" * 20)
os.utime(entry, (now - 40 * 86400 + index, now - 40 * 86400 + index))
result = maintain_quick_run_storage(
tmp_path,
now=now,
max_age_days=30,
max_entries=100,
max_bytes=25,
min_entries=2,
)
assert result.removed_entries == ("recovery-0", "recovery-1")
assert {path.name for path in history.iterdir()} == {"recovery-2", "recovery-3"}
+682
View File
@@ -0,0 +1,682 @@
from __future__ import annotations
import json
import os
from pathlib import Path
import sqlite3
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.models import ProjectStatus, TaskStatus
import dx_productivity.trial_task_center.runner as runner_module
from dx_productivity.trial_task_center.runner import TrialRunner
from dx_productivity.trial_task_center.store import TaskStore
FIXTURES = Path(__file__).parents[1] / "fixtures" / "trial_task_center"
def _write_profile(name: str, destination: Path, project: Path) -> None:
profile = json.loads((FIXTURES / name).read_text(encoding="utf-8"))
profile["project"]["identity"] = str(project)
destination.write_text(json.dumps(profile), encoding="utf-8")
def _runner_with_selected_projects(tmp_path: Path, count: int = 1) -> tuple[TrialRunner, TaskStore, str, tuple[str, ...]]:
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
store.add_rule(task.task_id, "OLD-1", "NEW-1")
root = tmp_path / "projects"
root.mkdir()
paths = []
for number in range(count):
path = root / f"project-{number + 1}.prj"
path.write_text("project", encoding="utf-8")
paths.append(path)
projects = store.sync_projects(task.task_id, root, paths)
for project in projects:
store.set_project_selected(project.project_id, True)
probe_source = tmp_path / "menu-probe-default.json"
probe_source.write_text("baseline", encoding="utf-8")
return (
TrialRunner(
store,
configure_logging(tmp_path / "logs"),
probe_source_resolver=lambda _task, _project: probe_source,
),
store,
task.task_id,
tuple(project.project_id for project in projects),
)
def _runner_with_probe_source(
tmp_path: Path, count: int = 1
) -> tuple[TrialRunner, TaskStore, str, tuple[str, ...], Path]:
runner, store, task_id, project_ids = _runner_with_selected_projects(tmp_path, count)
probe_source = tmp_path / "menu-probe.json"
probe_source.write_text("baseline", encoding="utf-8")
return (
TrialRunner(
store,
configure_logging(tmp_path / "logs"),
probe_source_resolver=lambda _task, _project: probe_source,
),
store,
task_id,
project_ids,
probe_source,
)
def test_start_requires_disposable_confirmation_and_activates_exact_first_selected_project(tmp_path: Path) -> None:
"""Removing the confirmation or choosing an unselected project must block the trial."""
runner, store, task_id, project_ids = _runner_with_selected_projects(tmp_path, count=2)
store.set_project_selected(project_ids[0], False)
with pytest.raises(TaskCenterError) as raised:
runner.start_task(task_id, disposable_copy_confirmed=False)
assert raised.value.code == "disposable_copy_required"
snapshot = runner.start_task(task_id, disposable_copy_confirmed=True)
assert snapshot.task.status is TaskStatus.RUNNING
assert snapshot.active_project is not None
assert snapshot.active_project.project_id == project_ids[1]
assert snapshot.active_project.status is ProjectStatus.CAPTURING_BEFORE
def test_before_capture_supplies_project_and_matching_rules_to_operator(tmp_path: Path) -> None:
"""A before profile must be captured before native replacement guidance is shown."""
runner, store, task_id, (project_id,) = _runner_with_selected_projects(tmp_path)
project = store.list_projects(task_id)[0]
probe = tmp_path / "before.json"
_write_profile("profile-before.json", probe, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
snapshot = runner.capture_before(task_id, project_id, probe)
assert snapshot.active_project is not None
assert snapshot.active_project.status is ProjectStatus.AWAITING_OPERATOR
assert snapshot.instruction is not None
assert snapshot.instruction.project_path == project.path
assert [(rule.old_part_number, rule.new_part_number, rule.match_count) for rule in snapshot.instruction.rules] == [
("OLD-1", "NEW-1", 1)
]
assert snapshot.evidence_directory.joinpath("before.json").exists()
def test_operator_confirmation_does_not_mark_project_successful(tmp_path: Path) -> None:
"""Changing confirmation into completion would let an assertion bypass machine verification."""
runner, store, task_id, (project_id,) = _runner_with_selected_projects(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
_write_profile("profile-before.json", before, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
snapshot = runner.confirm_native_attempt(task_id, project_id)
assert snapshot.task.status is TaskStatus.RUNNING
assert snapshot.active_project is not None
assert snapshot.active_project.status is ProjectStatus.AWAITING_OPERATOR
assert store.get_task(task_id).status is not TaskStatus.COMPLETED
def test_fresh_after_capture_that_passes_completes_project_and_advances_queue(tmp_path: Path) -> None:
"""Skipping comparison or next-project activation would leave verified work unsafe or stranded."""
runner, store, task_id, project_ids = _runner_with_selected_projects(tmp_path, count=2)
first, second = (store.list_projects(task_id)[index] for index in range(2))
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", before, first.path)
_write_profile("profile-after-valid.json", after, first.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_ids[0], before)
runner.confirm_native_attempt(task_id, project_ids[0])
snapshot = runner.capture_after(task_id, project_ids[0], after)
assert store.list_projects(task_id)[0].status is ProjectStatus.COMPLETED
assert snapshot.task.status is TaskStatus.RUNNING
assert snapshot.active_project is not None
assert snapshot.active_project.project_id == second.project_id
assert snapshot.active_project.status is ProjectStatus.CAPTURING_BEFORE
def test_hard_comparison_failure_keeps_project_failed_and_task_failed(tmp_path: Path) -> None:
"""Treating a hard profile mismatch as success would violate the trial safety gate."""
runner, store, task_id, (project_id,) = _runner_with_selected_projects(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", before, project.path)
_write_profile("profile-after-invalid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
with pytest.raises(TaskCenterError) as raised:
runner.capture_after(task_id, project_id, after)
assert raised.value.code == "comparison_failed"
assert store.list_projects(task_id)[0].status is ProjectStatus.FAILED
assert store.get_task(task_id).status is TaskStatus.FAILED
def test_paused_commit_still_records_a_failed_comparison_as_task_failure(tmp_path: Path) -> None:
"""Leaving a paused task nonfailed after a rejected commit would hide a hard safety failure."""
runner, store, task_id, (project_id,) = _runner_with_selected_projects(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", before, project.path)
_write_profile("profile-after-invalid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
runner.pause_task(task_id)
with pytest.raises(TaskCenterError, match="comparison_failed"):
runner.capture_after(task_id, project_id, after)
assert store.list_projects(task_id)[0].status is ProjectStatus.FAILED
assert store.get_task(task_id).status is TaskStatus.FAILED
def test_pause_prevents_next_project_then_resume_reactivates_it(tmp_path: Path) -> None:
"""Starting another project while paused would defeat the operator's pause request."""
runner, store, task_id, project_ids = _runner_with_selected_projects(tmp_path, count=2)
first = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", before, first.path)
_write_profile("profile-after-valid.json", after, first.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_ids[0], before)
runner.pause_task(task_id)
paused = runner.capture_after(task_id, project_ids[0], after)
assert paused.task.status is TaskStatus.PAUSED
assert paused.active_project is None
assert store.list_projects(task_id)[1].status is ProjectStatus.PENDING
resumed = runner.resume_task(task_id)
assert resumed.task.status is TaskStatus.RUNNING
assert resumed.active_project is not None
assert resumed.active_project.project_id == project_ids[1]
def test_retry_uses_new_attempt_directory_and_skip_finishes_queue(tmp_path: Path) -> None:
"""Reusing a failed attempt's evidence or failing to finish skipped work loses auditability."""
runner, store, task_id, (project_id,) = _runner_with_selected_projects(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", before, project.path)
_write_profile("profile-after-invalid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
with pytest.raises(TaskCenterError):
runner.capture_after(task_id, project_id, after)
failed_directory = runner.snapshot(task_id).evidence_directory
retried = runner.retry_project(task_id, project_id)
assert retried.active_project is not None
assert retried.evidence_directory != failed_directory
assert retried.evidence_directory.name == "attempt-2"
completed = runner.skip_project(task_id, project_id)
assert store.list_projects(task_id)[0].status is ProjectStatus.SKIPPED
assert completed.task.status is TaskStatus.COMPLETED
def test_passing_final_project_completes_the_task(tmp_path: Path) -> None:
"""Omitting terminal task completion would strand a verified one-project trial."""
runner, store, task_id, (project_id,) = _runner_with_selected_projects(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", before, project.path)
_write_profile("profile-after-valid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
completed = runner.capture_after(task_id, project_id, after)
assert completed.task.status is TaskStatus.COMPLETED
assert completed.active_project is None
def test_restart_recovery_uses_store_state_and_records_transition_events(tmp_path: Path) -> None:
"""A restarted process must recover durable work instead of trusting a stale runner instance."""
runner, store, task_id, (project_id,) = _runner_with_selected_projects(tmp_path)
runner.start_task(task_id, disposable_copy_confirmed=True)
restarted = TrialRunner(store, configure_logging(tmp_path / "logs"))
snapshot = restarted.snapshot(task_id)
events = [
json.loads(line)
for line in (tmp_path / "logs" / "tasks" / task_id / "events.jsonl").read_text(encoding="utf-8").splitlines()
]
assert snapshot.task.status is TaskStatus.PAUSED
assert snapshot.active_project is None
assert store.list_projects(task_id)[0].status is ProjectStatus.FAILED
recovery_events = [
event
for event in events
if event["operation"] == "recover_interrupted_work" and event["project_id"] == project_id
]
assert [event["details"]["phase"] for event in recovery_events] == ["before", "after"]
assert [event["state_before"] for event in recovery_events] == [
ProjectStatus.CAPTURING_BEFORE.value,
ProjectStatus.CAPTURING_BEFORE.value,
]
def test_restart_awaiting_operator_uses_persisted_before_stamp_and_instruction(tmp_path: Path) -> None:
"""Dropping an attempt context on restart must fail closed instead of accepting the old probe as after evidence."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
_write_profile("profile-after-valid.json", probe_source, project.path)
_write_profile("profile-after-valid.json", before, project.path)
before_profile = json.loads(before.read_text(encoding="utf-8"))
before_profile["capture"] = "new-before-probe"
before.write_text(json.dumps(before_profile), encoding="utf-8")
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
restarted = TrialRunner(
store,
configure_logging(tmp_path / "logs"),
probe_source_resolver=lambda _task, _project: probe_source,
)
recovered = restarted.snapshot(task_id)
assert recovered.instruction is not None
with pytest.raises(TaskCenterError) as raised:
restarted.capture_after(task_id, project_id, before)
assert raised.value.code == "profile_unchanged"
assert store.get_task(task_id).status is TaskStatus.FAILED
def test_restart_without_persisted_before_stamp_fails_closed(tmp_path: Path) -> None:
"""A damaged attempt record cannot safely advance from operator state to verification."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
after = tmp_path / "after.json"
_write_profile("profile-before.json", probe_source, project.path)
_write_profile("profile-after-valid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
store.set_project_status(project_id, ProjectStatus.AWAITING_OPERATOR)
restarted = TrialRunner(
store,
configure_logging(tmp_path / "logs"),
probe_source_resolver=lambda _task, _project: probe_source,
)
with pytest.raises(TaskCenterError) as raised:
restarted.capture_after(task_id, project_id, after)
assert raised.value.code == "attempt_before_missing"
assert store.list_projects(task_id)[0].status is ProjectStatus.FAILED
def test_capture_after_rechecks_persisted_before_content_hash(tmp_path: Path) -> None:
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
_write_profile("profile-before.json", probe_source, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
before = json.loads(probe_source.read_text(encoding="utf-8"))
before["capture"] = "fresh-before"
probe_source.write_text(json.dumps(before), encoding="utf-8")
runner.capture_before(task_id, project_id, probe_source)
context = store.current_attempt(project_id)
assert context is not None and context.before_path is not None
altered = json.loads(context.before_path.read_text(encoding="utf-8"))
altered["components"][0]["pins"][0]["x"] = 999
context.before_path.write_text(json.dumps(altered), encoding="utf-8")
_write_profile("profile-after-valid.json", probe_source, project.path)
with pytest.raises(TaskCenterError) as raised:
runner.capture_after(task_id, project_id, probe_source)
assert raised.value.code == "evidence_integrity"
assert store.list_projects(task_id)[0].status is ProjectStatus.FAILED
def test_attempt_freezes_rules_for_instruction_and_comparison(tmp_path: Path) -> None:
"""Comparing with an edited mapping rather than the attempt mapping must reject the UI edit race."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", probe_source, project.path)
_write_profile("profile-before.json", before, project.path)
before_profile = json.loads(before.read_text(encoding="utf-8"))
before_profile["capture"] = "new-before-probe"
before.write_text(json.dumps(before_profile), encoding="utf-8")
_write_profile("profile-after-valid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
rule = store.list_rules(task_id)[0]
store.update_rule(rule.rule_id, old_part_number="OLD-1", new_part_number="OTHER-1", enabled=True)
completed = runner.capture_after(task_id, project_id, after)
assert completed.task.status is TaskStatus.COMPLETED
def test_start_baseline_rejects_unchanged_before_probe(tmp_path: Path) -> None:
"""Capturing the probe present at Start as a before profile would permit stale evidence."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
_write_profile("profile-before.json", probe_source, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
with pytest.raises(TaskCenterError) as raised:
runner.capture_before(task_id, project_id, probe_source)
assert raised.value.code == "profile_unchanged"
def test_global_active_project_gate_blocks_second_task(tmp_path: Path) -> None:
"""Selecting one active project per task still permits dangerous concurrent native work."""
first, store, first_task_id, _, probe_source = _runner_with_probe_source(tmp_path)
second_task = store.create_task("Second")
store.add_rule(second_task.task_id, "OLD-1", "NEW-1")
second_path = tmp_path / "second.prj"
second_path.write_text("project", encoding="utf-8")
second_project = store.sync_projects(second_task.task_id, tmp_path, (second_path,))[0]
store.set_project_selected(second_project.project_id, True)
second = TrialRunner(store, configure_logging(tmp_path / "logs"), probe_source_resolver=lambda _task, _project: probe_source)
first.start_task(first_task_id, disposable_copy_confirmed=True)
with pytest.raises(TaskCenterError) as raised:
second.start_task(second_task.task_id, disposable_copy_confirmed=True)
assert raised.value.code == "active_project_exists"
assert store.get_task(second_task.task_id).status is TaskStatus.DRAFT
def test_retry_slot_conflict_leaves_failed_task_and_project_unchanged(tmp_path: Path) -> None:
"""A rejected retry claim must not first persist a runnable task or pending project."""
blocker, store, blocker_task_id, _, probe_source = _runner_with_probe_source(tmp_path)
blocked_task = store.create_task("Blocked retry")
store.add_rule(blocked_task.task_id, "OLD-1", "NEW-1")
path = tmp_path / "blocked-retry.prj"
path.write_text("project", encoding="utf-8")
blocked_project = store.sync_projects(blocked_task.task_id, tmp_path, (path,))[0]
store.set_project_selected(blocked_project.project_id, True)
store.set_task_status(blocked_task.task_id, TaskStatus.RUNNING)
store.set_project_status(blocked_project.project_id, ProjectStatus.CAPTURING_BEFORE)
store.set_project_status(blocked_project.project_id, ProjectStatus.FAILED)
store.set_task_status(blocked_task.task_id, TaskStatus.FAILED)
blocker.start_task(blocker_task_id, disposable_copy_confirmed=True)
events_path = tmp_path / "logs" / "tasks" / blocked_task.task_id / "events.jsonl"
with pytest.raises(TaskCenterError) as raised:
blocker.retry_project(blocked_task.task_id, blocked_project.project_id)
assert raised.value.code == "active_project_exists"
assert store.get_task(blocked_task.task_id).status is TaskStatus.FAILED
assert store.list_projects(blocked_task.task_id)[0].status is ProjectStatus.FAILED
assert not events_path.exists() or "retry started" not in events_path.read_text(encoding="utf-8")
def test_resume_slot_conflict_leaves_paused_task_and_pending_project_unchanged(tmp_path: Path) -> None:
"""A rejected resume claim must not advertise success after another task owns the slot."""
blocker, store, blocker_task_id, _, probe_source = _runner_with_probe_source(tmp_path)
blocked_task = store.create_task("Blocked resume")
store.add_rule(blocked_task.task_id, "OLD-1", "NEW-1")
path = tmp_path / "blocked-resume.prj"
path.write_text("project", encoding="utf-8")
blocked_project = store.sync_projects(blocked_task.task_id, tmp_path, (path,))[0]
store.set_project_selected(blocked_project.project_id, True)
store.set_task_status(blocked_task.task_id, TaskStatus.RUNNING)
store.set_task_status(blocked_task.task_id, TaskStatus.PAUSED)
blocker.start_task(blocker_task_id, disposable_copy_confirmed=True)
events_path = tmp_path / "logs" / "tasks" / blocked_task.task_id / "events.jsonl"
with pytest.raises(TaskCenterError) as raised:
blocker.resume_task(blocked_task.task_id)
assert raised.value.code == "active_project_exists"
assert store.get_task(blocked_task.task_id).status is TaskStatus.PAUSED
assert store.list_projects(blocked_task.task_id)[0].status is ProjectStatus.PENDING
assert not events_path.exists() or "trial resumed" not in events_path.read_text(encoding="utf-8")
def test_resume_completes_terminal_task_while_another_task_owns_the_active_slot(tmp_path: Path) -> None:
"""A finished queue needs no native-work slot, so resuming it must be allowed to complete."""
blocker, store, blocker_task_id, _, _ = _runner_with_probe_source(tmp_path)
completed_task = store.create_task("Completed queue")
path = tmp_path / "completed-queue.prj"
path.write_text("project", encoding="utf-8")
completed_project = store.sync_projects(completed_task.task_id, tmp_path, (path,))[0]
store.set_project_selected(completed_project.project_id, True)
store.set_task_status(completed_task.task_id, TaskStatus.RUNNING)
for status in (
ProjectStatus.CAPTURING_BEFORE,
ProjectStatus.AWAITING_OPERATOR,
ProjectStatus.CAPTURING_AFTER,
ProjectStatus.VERIFYING,
ProjectStatus.COMPLETED,
):
store.set_project_status(completed_project.project_id, status)
store.set_task_status(completed_task.task_id, TaskStatus.PAUSED)
blocker.start_task(blocker_task_id, disposable_copy_confirmed=True)
resumed = blocker.resume_task(completed_task.task_id)
assert resumed.task.status is TaskStatus.COMPLETED
assert resumed.active_project is None
def test_v1_migration_recovery_emits_before_and_after_events(tmp_path: Path) -> None:
"""Fail-closed v1 migration must retain enough durable context for recovery audit events."""
database = tmp_path / "task-center.db"
first = TaskStore(database)
task = first.create_task("Trial")
path = tmp_path / "one.prj"
path.touch()
project = first.sync_projects(task.task_id, tmp_path, (path,))[0]
first.set_task_status(task.task_id, TaskStatus.RUNNING)
first.set_project_status(project.project_id, ProjectStatus.CAPTURING_BEFORE)
first.close()
with sqlite3.connect(database) as connection:
connection.execute("DROP TABLE attempts")
connection.execute("UPDATE metadata SET value = '1' WHERE key = 'schema_version'")
migrated = TaskStore(database)
TrialRunner(migrated, configure_logging(tmp_path / "logs"))
events = [
json.loads(line)
for line in (tmp_path / "logs" / "tasks" / task.task_id / "events.jsonl").read_text(encoding="utf-8").splitlines()
]
project_events = [
event for event in events if event["operation"] == "recover_v1_attemptless_work" and event["project_id"] == project.project_id
]
task_events = [
event for event in events if event["operation"] == "recover_v1_attemptless_work" and event["project_id"] is None
]
assert [event["details"]["phase"] for event in project_events] == ["before", "after"]
assert [event["state_before"] for event in project_events] == [ProjectStatus.CAPTURING_BEFORE.value] * 2
assert [event["state_after"] for event in project_events] == [ProjectStatus.FAILED.value] * 2
assert [event["details"]["phase"] for event in task_events] == ["before", "after"]
assert [event["state_before"] for event in task_events] == [TaskStatus.RUNNING.value] * 2
assert [event["state_after"] for event in task_events] == [TaskStatus.PAUSED.value] * 2
@pytest.mark.parametrize("failure_point", ("append_after_write", "acknowledge_before_delete"))
def test_v1_migration_recovery_events_are_idempotent_across_restart(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure_point: str
) -> None:
"""Restarting after a partial recovery must not duplicate an event that is already durable."""
database = tmp_path / "task-center.db"
first = TaskStore(database)
task = first.create_task("Trial")
path = tmp_path / "one.prj"
path.touch()
project = first.sync_projects(task.task_id, tmp_path, (path,))[0]
first.set_task_status(task.task_id, TaskStatus.RUNNING)
first.set_project_status(project.project_id, ProjectStatus.CAPTURING_BEFORE)
first.close()
with sqlite3.connect(database) as connection:
connection.execute("DROP TABLE attempts")
connection.execute("UPDATE metadata SET value = '1' WHERE key = 'schema_version'")
migrated = TaskStore(database)
logging_context = configure_logging(tmp_path / "logs")
original_append = runner_module.append_task_event
original_acknowledge = TaskStore.acknowledge_migration_recoveries
append_count = 0
if failure_point == "append_after_write":
def append_then_fail(*args: object, **kwargs: object) -> dict[str, object]:
nonlocal append_count
event = original_append(*args, **kwargs)
append_count += 1
if append_count == 2:
raise TaskCenterError("event_write_failed", "simulated crash after durable append")
return event
monkeypatch.setattr(runner_module, "append_task_event", append_then_fail)
else:
def fail_acknowledge(_store: TaskStore, _project_ids: object) -> None:
raise TaskCenterError("recovery_ack_failed", "simulated crash before recovery acknowledgement")
monkeypatch.setattr(TaskStore, "acknowledge_migration_recoveries", fail_acknowledge)
with pytest.raises(TaskCenterError):
TrialRunner(migrated, logging_context)
migrated.close()
monkeypatch.setattr(runner_module, "append_task_event", original_append)
monkeypatch.setattr(TaskStore, "acknowledge_migration_recoveries", original_acknowledge)
restarted_store = TaskStore(database)
TrialRunner(restarted_store, configure_logging(tmp_path / "logs"))
events = [
json.loads(line)
for line in (tmp_path / "logs" / "tasks" / task.task_id / "events.jsonl").read_text(encoding="utf-8").splitlines()
]
recovery_events = [event for event in events if event["operation"] == "recover_v1_attemptless_work"]
assert len(recovery_events) == 4
assert len({event["details"]["recovery_event_id"] for event in recovery_events}) == 4
assert restarted_store.pending_migration_recoveries() == ()
def test_completed_project_event_failure_reconciles_task_without_illegal_failure(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""An event-write failure after completion must not attempt an illegal completed-to-failed transition."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", probe_source, project.path)
_write_profile("profile-before.json", before, project.path)
os.utime(probe_source, ns=(1_700_000_000_000_000_000, 1_700_000_000_000_000_000))
os.utime(before, ns=(1_700_000_001_000_000_000, 1_700_000_001_000_000_000))
_write_profile("profile-after-valid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
original_append = runner_module.append_task_event
def fail_terminal_event(*args: object, **kwargs: object) -> dict[str, object]:
if kwargs.get("operation") == "compare_profiles" and kwargs.get("details") == {"phase": "after"}:
raise TaskCenterError("event_write_failed", "cannot append task event")
return original_append(*args, **kwargs)
monkeypatch.setattr(runner_module, "append_task_event", fail_terminal_event)
with pytest.raises(TaskCenterError, match="event_write_failed"):
runner.capture_after(task_id, project_id, after)
assert store.list_projects(task_id)[0].status is ProjectStatus.COMPLETED
assert store.get_task(task_id).status is TaskStatus.COMPLETED
def test_restart_reconciles_completed_project_when_task_completion_was_interrupted(tmp_path: Path) -> None:
"""A crash after project completion must not leave a restartable trial permanently running."""
runner, store, task_id, (project_id,), _ = _runner_with_probe_source(tmp_path)
runner.start_task(task_id, disposable_copy_confirmed=True)
store.set_project_status(project_id, ProjectStatus.FAILED)
store.set_project_status(project_id, ProjectStatus.PENDING)
store.set_project_status(project_id, ProjectStatus.CAPTURING_BEFORE)
store.set_project_status(project_id, ProjectStatus.AWAITING_OPERATOR)
store.set_project_status(project_id, ProjectStatus.CAPTURING_AFTER)
store.set_project_status(project_id, ProjectStatus.VERIFYING)
store.set_project_status(project_id, ProjectStatus.COMPLETED)
restarted = TrialRunner(store, configure_logging(tmp_path / "logs"))
assert restarted.snapshot(task_id).task.status is TaskStatus.COMPLETED
def test_retry_uses_blank_current_instruction_without_mutating_prior_attempt_evidence(tmp_path: Path) -> None:
"""Reusing a previous attempt instruction can direct the operator with stale match evidence."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", probe_source, project.path)
_write_profile("profile-before.json", before, project.path)
before_profile = json.loads(before.read_text(encoding="utf-8"))
before_profile["capture"] = "new-before-probe"
before.write_text(json.dumps(before_profile), encoding="utf-8")
_write_profile("profile-after-invalid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
first_attempt = runner.capture_before(task_id, project_id, before)
original_before = (first_attempt.evidence_directory / "before.json").read_bytes()
with pytest.raises(TaskCenterError):
runner.capture_after(task_id, project_id, after)
retried = runner.retry_project(task_id, project_id)
assert retried.instruction is None
assert (first_attempt.evidence_directory / "before.json").read_bytes() == original_before
def test_before_capture_rejects_duplicate_logical_identity(tmp_path: Path) -> None:
"""Ignoring malformed components before operator action creates unverified replacement guidance."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
_write_profile("profile-before.json", probe_source, project.path)
profile = json.loads((FIXTURES / "profile-before.json").read_text(encoding="utf-8"))
profile["project"]["identity"] = str(project.path)
profile["components"].append(dict(profile["components"][0]))
before.write_text(json.dumps(profile), encoding="utf-8")
runner.start_task(task_id, disposable_copy_confirmed=True)
with pytest.raises(TaskCenterError) as raised:
runner.capture_before(task_id, project_id, before)
assert raised.value.code == "before_profile_invalid"
assert store.list_projects(task_id)[0].status is ProjectStatus.FAILED
def test_failed_project_can_be_deselected_and_reconciles_task(tmp_path: Path) -> None:
"""A failed deselected project must not keep an otherwise empty queue in failed state forever."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", probe_source, project.path)
_write_profile("profile-before.json", before, project.path)
before_profile = json.loads(before.read_text(encoding="utf-8"))
before_profile["capture"] = "before-evidence"
before.write_text(json.dumps(before_profile), encoding="utf-8")
_write_profile("profile-after-invalid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
with pytest.raises(TaskCenterError):
runner.capture_after(task_id, project_id, after)
snapshot = runner.set_project_selected(task_id, project_id, False)
assert not store.list_projects(task_id)[0].selected
assert snapshot.task.status is TaskStatus.PAUSED
+210
View File
@@ -0,0 +1,210 @@
from __future__ import annotations
import os
from pathlib import Path
import subprocess
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.scanner import scan_projects
SCHEMATIC_PROJECT = '''SECTION DesignInfo
KEY FrontEndSnapshot "DxD"
ENDSECTION
SECTION iCDB
KEY iCDBDir ".\\database"
ENDSECTION
'''
def _write_schematic_project(path: Path) -> None:
path.write_text(SCHEMATIC_PROJECT, encoding="utf-8")
def test_scan_projects_discovers_case_insensitive_prj_files_in_canonical_order(tmp_path: Path) -> None:
root = tmp_path / "projects"
first = root / "z" / "B.PRJ"
second = root / "a" / "a.PrJ"
first.parent.mkdir(parents=True)
second.parent.mkdir()
_write_schematic_project(first)
_write_schematic_project(second)
before = sorted(path.relative_to(root) for path in root.rglob("*"))
result = scan_projects(root)
assert result == tuple(sorted((first.resolve(), second.resolve()), key=lambda path: str(path).casefold()))
assert sorted(path.relative_to(root) for path in root.rglob("*")) == before
def test_scan_projects_stops_at_selected_project_directory_when_it_contains_prj_files(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Descending past a directly selected project can expose backups as separate projects."""
root = tmp_path / "selected-project"
first = root / "A.PRJ"
second = root / "Board.prj"
nested_backup = root / "backup" / "Board-old.prj"
nested_generated = root / "generated" / "Board-copy.PRJ"
nested_backup.parent.mkdir(parents=True)
nested_generated.parent.mkdir()
_write_schematic_project(first)
_write_schematic_project(second)
_write_schematic_project(nested_backup)
_write_schematic_project(nested_generated)
real_scandir = os.scandir
def reject_nested(path: str | bytes | int) -> object:
if Path(path) != root:
raise AssertionError(f"unexpected nested scan: {path}")
return real_scandir(path)
monkeypatch.setattr("dx_productivity.trial_task_center.scanner.os.scandir", reject_nested)
result = scan_projects(root)
assert result == (first.resolve(), second.resolve())
def test_scan_projects_reads_batch_root_once_before_recursive_fallback(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Enumerating a live root twice can mix two different filesystem snapshots."""
root = tmp_path / "projects"
child = root / "child"
project = child / "Board.prj"
child.mkdir(parents=True)
_write_schematic_project(project)
real_scandir = os.scandir
root_reads = 0
def count_root(path: str | bytes | int) -> object:
nonlocal root_reads
if Path(path) == root:
root_reads += 1
return real_scandir(path)
monkeypatch.setattr("dx_productivity.trial_task_center.scanner.os.scandir", count_root)
result = scan_projects(root)
assert result == (project.resolve(),)
assert root_reads == 1
def test_scan_projects_skips_portable_task_data_and_its_backups(tmp_path: Path) -> None:
root = tmp_path / "DxPartReplace"
project = root / "projects" / "Board" / "Board.prj"
backup = root / "data" / "quick-run-history" / "batch-test" / "project-1" / "Board.prj"
project.parent.mkdir(parents=True)
backup.parent.mkdir(parents=True)
_write_schematic_project(project)
_write_schematic_project(backup)
assert scan_projects(root, excluded_roots=(root / "data",)) == (project.resolve(),)
def test_scan_projects_rejects_task_data_as_the_selected_root(tmp_path: Path) -> None:
data = tmp_path / "data"
data.mkdir()
with pytest.raises(TaskCenterError) as raised:
scan_projects(data, excluded_roots=(data,))
assert raised.value.code == "discovery_root"
def test_scan_projects_wraps_invalid_roots_without_losing_input_error_code(tmp_path: Path) -> None:
missing = tmp_path / "missing"
file_root = tmp_path / "not-a-directory.prj"
_write_schematic_project(file_root)
for root in (missing, file_root):
with pytest.raises(TaskCenterError) as raised:
scan_projects(root)
assert raised.value.code == "discovery_root"
def test_scan_projects_turns_inaccessible_subtree_errors_into_explicit_task_errors(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
root = tmp_path / "projects"
denied = root / "denied"
denied.mkdir(parents=True)
real_scandir = __import__("os").scandir
def deny(path: str | bytes | int) -> object:
if Path(path) == denied:
raise PermissionError("denied subtree")
return real_scandir(path)
monkeypatch.setattr("dx_productivity.trial_task_center.scanner.os.scandir", deny)
with pytest.raises(TaskCenterError) as raised:
scan_projects(root)
assert raised.value.code == "discovery_access"
@pytest.mark.skipif(os.name != "nt", reason="Windows junction coverage")
def test_scan_projects_rejects_junction_subtrees_without_scanning_them(tmp_path: Path) -> None:
root = tmp_path / "projects"
outside = tmp_path / "outside"
junction = root / "junction"
normal = root / "normal.prj"
outside_project = outside / "outside.prj"
root.mkdir()
outside.mkdir()
_write_schematic_project(normal)
_write_schematic_project(outside_project)
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(junction), str(outside)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.skip(f"junctions unavailable: {created.stderr or created.stdout}")
try:
with pytest.raises(TaskCenterError) as raised:
scan_projects(root)
finally:
junction.rmdir()
assert raised.value.code == "discovery_reparse"
assert normal.exists()
assert outside_project.exists()
def test_scan_projects_ignores_pcb_and_other_prj_files(tmp_path: Path) -> None:
root = tmp_path / "projects"
schematic = root / "Schematic.prj"
pcb = root / "PCB.prj"
vivado = root / "vlog.prj"
schematic.parent.mkdir(parents=True)
_write_schematic_project(schematic)
pcb.write_text(
'SECTION DesignInfo\nKEY FrontEndSnapshot "PCB"\nENDSECTION\n'
'SECTION Board\nKEY PCBDesignPath "PCB\\Board.pcb"\nENDSECTION\n',
encoding="utf-8",
)
vivado.write_text("verilog work source.v\n", encoding="utf-8")
assert scan_projects(root) == (schematic.resolve(),)
def test_scan_projects_keeps_schematic_projects_that_also_contain_pcb_configuration(tmp_path: Path) -> None:
root = tmp_path / "projects"
integrated = root / "Integrated.prj"
integrated.parent.mkdir(parents=True)
integrated.write_text(
SCHEMATIC_PROJECT
+ 'SECTION Board1\nKEY ConfigType "PCB"\nKEY PCBDesignPath "PCB\\Board1.pcb"\nENDSECTION\n',
encoding="utf-8",
)
assert scan_projects(root) == (integrated.resolve(),)
@@ -0,0 +1,81 @@
from __future__ import annotations
from io import StringIO
import json
from pathlib import Path
import sqlite3
from dx_productivity.trial_task_center.sceneos_cli import run
from dx_productivity.trial_task_center.store import TaskStore
def test_sceneos_cli_creates_scans_and_reuses_one_task(tmp_path: Path) -> None:
projects = tmp_path / "projects"
projects.mkdir()
(projects / "alpha.prj").touch()
(projects / "beta.prj").touch()
data_root = tmp_path / "data"
payload = {
"protocol": "sceneos-cli/v1",
"input": {"taskName": "SceneOS scan", "projectRoot": str(projects.resolve())},
"context": {"runId": "run-1", "stepId": "create", "idempotencyKey": "run-1:create"},
}
first_output = StringIO()
repeated_output = StringIO()
assert run(data_root, StringIO(json.dumps(payload)), first_output) == 0
assert run(data_root, StringIO(json.dumps(payload)), repeated_output) == 0
first = json.loads(first_output.getvalue())
repeated = json.loads(repeated_output.getvalue())
assert first["created"] is True
assert first["projectCount"] == 2
assert repeated == first | {"created": False}
with sqlite3.connect(data_root / "task-center.db") as connection:
assert connection.execute("SELECT COUNT(*) FROM tasks").fetchone()[0] == 1
assert connection.execute("SELECT COUNT(*) FROM external_requests").fetchone()[0] == 1
def test_sceneos_cli_rejects_conflicting_input_for_the_same_key(tmp_path: Path) -> None:
first_root = tmp_path / "first"
second_root = tmp_path / "second"
first_root.mkdir()
second_root.mkdir()
context = {"runId": "run-1", "stepId": "create", "idempotencyKey": "fixed-key"}
first = _invoke(tmp_path / "data", "First", first_root, context)
conflict = _invoke(tmp_path / "data", "Second", second_root, context)
assert first[0] == 0
assert conflict[0] == 2
assert conflict[1]["error"] == "external_request_conflict"
def test_sceneos_cli_request_can_be_recreated_after_task_is_purged(tmp_path: Path) -> None:
projects = tmp_path / "projects"
projects.mkdir()
data_root = tmp_path / "data"
context = {"runId": "run-1", "stepId": "create", "idempotencyKey": "purged-key"}
first = _invoke(data_root, "Replace scan", projects, context)
store = TaskStore(data_root / "task-center.db")
try:
store.soft_delete_task(str(first[1]["taskId"]))
store.purge_task(str(first[1]["taskId"]))
finally:
store.close()
recreated = _invoke(data_root, "Replace scan", projects, context)
assert recreated[0] == 0
assert recreated[1]["created"] is True
assert recreated[1]["taskId"] != first[1]["taskId"]
def _invoke(data_root: Path, name: str, project_root: Path, context: dict[str, str]) -> tuple[int, dict[str, object]]:
output = StringIO()
code = run(data_root, StringIO(json.dumps({
"protocol": "sceneos-cli/v1",
"input": {"taskName": name, "projectRoot": str(project_root.resolve())},
"context": context,
})), output)
return code, json.loads(output.getvalue())
+251
View File
@@ -0,0 +1,251 @@
from __future__ import annotations
import json
from datetime import datetime, timezone
from pathlib import Path
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.quick_run import QuickRunProgress
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
FIXTURES = Path(__file__).parents[1] / "fixtures" / "trial_task_center"
def _service(tmp_path: Path, opened: list[Path] | None = None) -> TaskCenterService:
probe_source = tmp_path / "menu-probe.json"
probe_source.write_text("baseline", encoding="utf-8")
return TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
configure_logging(tmp_path / "storage"),
path_opener=(opened.append if opened is not None else lambda _: None),
clock=lambda: datetime(2026, 9, 4, tzinfo=timezone.utc),
probe_source_resolver=lambda _task, _project: probe_source,
)
def _write_profile(name: str, destination: Path, project: Path) -> None:
profile = json.loads((FIXTURES / name).read_text(encoding="utf-8"))
profile["project"]["identity"] = str(project)
destination.write_text(json.dumps(profile), encoding="utf-8")
def test_task_crud_scan_and_selection_commands_keep_previous_operator_choice(tmp_path: Path) -> None:
"""Replacing service delegation with UI-local state would lose the durable selection."""
service = _service(tmp_path)
root = tmp_path / "projects"
root.mkdir()
first = root / "one.prj"
second = root / "two.prj"
first.touch()
second.touch()
task = service.create_task("Trial", note="first")
service.update_task(task.task_id, name="Renamed", note="updated")
scanned = service.scan_projects(task.task_id, root)
service.set_project_selected(scanned[0].project_id, True)
rescan = service.scan_projects(task.task_id, root)
selected = service.select_all_projects(task.task_id)
cleared = service.clear_project_selection(task.task_id)
assert service.get_task(task.task_id).name == "Renamed"
assert next(project for project in rescan if project.project_id == scanned[0].project_id).selected
assert all(project.selected for project in selected)
assert not any(project.selected for project in cleared)
def test_bulk_selection_has_constant_project_list_queries(tmp_path: Path, monkeypatch) -> None:
service = _service(tmp_path)
root = tmp_path / "projects"
root.mkdir()
for index in range(200):
(root / f"project-{index:04d}.prj").touch()
task = service.create_task("Bulk")
service.scan_projects(task.task_id, root)
calls = 0
original = service._store.list_projects
def counted(task_id: str):
nonlocal calls
calls += 1
return original(task_id)
monkeypatch.setattr(service._store, "list_projects", counted)
selected = service.select_all_projects(task.task_id)
select_calls = calls
calls = 0
cleared = service.clear_project_selection(task.task_id)
assert all(project.selected for project in selected)
assert not any(project.selected for project in cleared)
assert select_calls <= 4
assert calls <= 4
def test_repeated_completed_progress_skips_redundant_database_sync(tmp_path: Path, monkeypatch) -> None:
service = _service(tmp_path)
root = tmp_path / "projects"
root.mkdir()
project_path = root / "one.prj"
project_path.touch()
task = service.create_task("Progress")
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
progress = QuickRunProgress(
1,
1,
None,
None,
None,
(project_path,),
True,
project_summaries=((project_path, "quick_run_result:1:0:saved"),),
saved_items=1,
)
service._synchronize_quick_run_progress(task.task_id, progress=progress)
sync_calls = 0
original = service._store.record_quick_run_progress
def counted(*args, **kwargs):
nonlocal sync_calls
sync_calls += 1
return original(*args, **kwargs)
monkeypatch.setattr(service._store, "record_quick_run_progress", counted)
service._synchronize_quick_run_progress(task.task_id, progress=progress)
assert sync_calls == 0
def test_operation_log_records_distinct_completion_time(tmp_path: Path) -> None:
timestamps = iter((
datetime(2026, 9, 7, 10, 0, tzinfo=timezone.utc),
datetime(2026, 9, 7, 10, 0, 3, tzinfo=timezone.utc),
))
logging = configure_logging(tmp_path / "storage")
service = TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
logging,
clock=lambda: next(timestamps),
)
service.tasks()
log = logging.application_log_path.read_text(encoding="utf-8")
assert "operation_start=list_tasks task_id= at=2026-09-07T10:00:00+00:00" in log
assert "operation_complete=list_tasks task_id= at=2026-09-07T10:00:03+00:00" in log
def test_task_delete_and_restore_delegate_to_durable_store(tmp_path: Path) -> None:
"""Keeping deletion only in UI state would lose the audit-preserving soft-delete contract."""
service = _service(tmp_path)
task = service.create_task("Trial")
deleted = service.delete_task(task.task_id)
restored = service.restore_task(task.task_id)
assert deleted.task_id == task.task_id
assert restored.task_id == task.task_id
assert service.tasks() == (restored,)
def test_rule_validation_errors_are_task_center_errors_with_stable_ids(tmp_path: Path) -> None:
"""Leaking parser errors would deny the UI a support identifier for invalid mappings."""
service = _service(tmp_path)
task = service.create_task("Trial")
service.add_rule(task.task_id, "OLD-1", "NEW-1")
with pytest.raises(TaskCenterError) as raised:
service.add_rule(task.task_id, "NEW-1", "OLD-2")
assert raised.value.code == "mapping_chain"
assert raised.value.error_id.startswith("DXT-")
def test_current_instruction_log_tailing_and_injected_evidence_opener(tmp_path: Path) -> None:
"""The UI must receive guidance and paths through the service without launching Explorer itself."""
opened: list[Path] = []
service = _service(tmp_path, opened)
task = service.create_task("Trial")
service.add_rule(task.task_id, "OLD-1", "NEW-1")
root = tmp_path / "projects"
root.mkdir()
project_path = root / "one.prj"
project_path.touch()
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
before = tmp_path / "before.json"
_write_profile("profile-before.json", before, project_path)
service.start_task(task.task_id, disposable_copy_confirmed=True)
service.capture_before(task.task_id, project.project_id, before)
instruction = service.current_instruction(task.task_id)
evidence_path = service.open_evidence(task.task_id, project.project_id)
log_lines = service.tail_log(task.task_id, limit=4)
assert instruction is not None
assert instruction.project_path == project_path
assert instruction.rules[0].old_part_number == "OLD-1"
assert evidence_path == opened[0]
assert any("capture_before" in line for line in log_lines)
def test_tail_log_does_not_amplify_the_application_log(tmp_path: Path) -> None:
service = _service(tmp_path)
task = service.create_task("Log polling")
application_log = service._logging.application_log_path
before = application_log.read_text(encoding="utf-8")
assert service.tail_log(task.task_id, limit=10) == ()
assert application_log.read_text(encoding="utf-8") == before
def test_service_rejects_mapping_edits_while_an_attempt_is_active(tmp_path: Path) -> None:
"""Changing rules mid-attempt would make UI mappings disagree with captured evidence."""
service = _service(tmp_path)
task = service.create_task("Trial")
rule = service.add_rule(task.task_id, "OLD-1", "NEW-1")
root = tmp_path / "projects"
root.mkdir()
project_path = root / "one.prj"
project_path.touch()
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
service.start_task(task.task_id, disposable_copy_confirmed=True)
with pytest.raises(TaskCenterError) as raised:
service.update_rule(rule.rule_id, old_part_number="OLD-1", new_part_number="OTHER-1", enabled=True)
assert raised.value.code == "rules_locked"
with pytest.raises(TaskCenterError, match="rules_locked"):
service.add_rule(task.task_id, "OLD-2", "NEW-2")
with pytest.raises(TaskCenterError, match="rules_locked"):
service.delete_rule(rule.rule_id)
with pytest.raises(TaskCenterError, match="rules_locked"):
service.move_rule(rule.rule_id, 1)
def test_prepared_queue_freezes_project_inventory_and_rule_options(tmp_path: Path) -> None:
service = _service(tmp_path)
task = service.create_task("Frozen queue")
root = tmp_path / "projects"
root.mkdir()
(root / "one.prj").touch()
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
rule = service.add_rule(task.task_id, "OLD", "NEW")
service.prepare_quick_run(task.task_id)
with pytest.raises(TaskCenterError, match="quick_run_options_locked"):
service.set_project_selected(project.project_id, False)
with pytest.raises(TaskCenterError, match="quick_run_options_locked"):
service.scan_projects(task.task_id, root)
with pytest.raises(TaskCenterError, match="rules_locked"):
service.update_rule(rule.rule_id, old_part_number="OLD", new_part_number="OTHER", enabled=True)
@@ -0,0 +1,20 @@
import pytest
from dx_productivity.trial_task_center import quick_run
@pytest.mark.parametrize('detail,expected', [
('stage=launch_designer COM: failed', '自动启动'),
('stage=wait_designer timeout', '未启动第二个实例'),
('stage=check_project another project is already open', '其他工程'),
('stage=open_sheet project has multiple sheets', '多张图页'),
('stage=open_sheet target project has no available schematic sheets', '没有可用原理图'),
])
def test_startup_errors_explain_action_without_losing_original(detail, expected):
message = quick_run._session_failure_message(detail)
assert expected in message
assert detail in message
def test_non_session_worker_error_is_not_misreported_as_startup():
assert quick_run._session_failure_message('original attachment error') == 'original attachment error'
+512
View File
@@ -0,0 +1,512 @@
from dataclasses import FrozenInstanceError
from pathlib import Path
import sqlite3
import threading
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.models import ProjectRecord, ProjectStatus, TaskRecord, TaskStatus
from dx_productivity.trial_task_center.store import TaskStore
def test_task_records_are_immutable_and_task_crud_round_trips(tmp_path: Path) -> None:
"""Changing a task through its record must not mutate durable state."""
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("试验任务", note="first")
assert isinstance(task, TaskRecord)
assert store.get_task(task.task_id).name == "试验任务"
with pytest.raises(FrozenInstanceError):
task.name = "not permitted" # type: ignore[misc]
renamed = store.update_task(task.task_id, name="单项目替换", note="updated")
assert renamed.name == "单项目替换"
assert renamed.note == "updated"
assert renamed.updated_utc > task.updated_utc
def test_task_names_must_be_unique_and_nonblank(tmp_path: Path) -> None:
"""A duplicate or blank draft name would make task selection ambiguous."""
store = TaskStore(tmp_path / "task-center.db")
store.create_task("Trial")
with pytest.raises(TaskCenterError, match="task_name"):
store.create_task(" trial ")
with pytest.raises(TaskCenterError, match="task_name"):
store.create_task(" \t ")
def test_soft_delete_restore_and_running_delete_rejection(tmp_path: Path) -> None:
"""A running task must remain available until the operator pauses it."""
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
deleted = store.soft_delete_task(task.task_id)
assert deleted.status is TaskStatus.DELETED
assert store.list_tasks() == ()
assert store.list_tasks(TaskStatus.DELETED)[0].task_id == task.task_id
assert store.restore_task(task.task_id).status is TaskStatus.DRAFT
store.set_task_status(task.task_id, TaskStatus.RUNNING)
with pytest.raises(TaskCenterError, match="task_running"):
store.soft_delete_task(task.task_id)
def test_rule_crud_reordering_enablement_and_validation_rollback(tmp_path: Path) -> None:
"""A rejected mapping edit must leave the prior valid ordered rules intact."""
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
first = store.add_rule(task.task_id, " OLD-1 ", "NEW-1")
second = store.add_rule(task.task_id, "OLD-2", "NEW-2")
updated = store.update_rule(
first.rule_id,
old_part_number="OLD-1",
new_part_number="NEW-1",
enabled=False,
)
moved = store.move_rule(second.rule_id, -1)
assert updated.enabled is False
assert [rule.rule_id for rule in moved] == [second.rule_id, first.rule_id]
assert [rule.position for rule in moved] == [0, 1]
with pytest.raises(TaskCenterError, match="mapping_chain"):
store.update_rule(
first.rule_id,
old_part_number="OLD-1",
new_part_number="OLD-2",
enabled=True,
)
restored = store.list_rules(task.task_id)
assert [(rule.old_part_number, rule.new_part_number, rule.enabled) for rule in restored] == [
("OLD-2", "NEW-2", True),
("OLD-1", "NEW-1", False),
]
store.delete_rule(first.rule_id)
assert [rule.rule_id for rule in store.list_rules(task.task_id)] == [second.rule_id]
def test_project_rescan_preserves_existing_selection_and_marks_missing_unavailable(tmp_path: Path) -> None:
"""Rescanning must never silently alter an operator's prior selection."""
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
root = tmp_path / "projects"
root.mkdir()
first_path = root / "one.prj"
second_path = root / "two.prj"
first_path.touch()
second_path.touch()
first_scan = store.sync_projects(task.task_id, root, (first_path, second_path))
selected = store.set_project_selected(first_scan[0].project_id, True)
second_scan = store.sync_projects(task.task_id, root, (second_path,))
assert selected.selected is True
by_path = {project.path.name: project for project in second_scan}
assert by_path["one.prj"].selected is True
assert by_path["one.prj"].available is False
assert by_path["two.prj"].selected is False
assert by_path["two.prj"].available is True
def test_bulk_project_selection_updates_available_inventory_in_one_operation(tmp_path: Path) -> None:
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
root = tmp_path / "projects"
root.mkdir()
first_path = root / "one.prj"
second_path = root / "two.prj"
first_path.touch()
second_path.touch()
store.sync_projects(task.task_id, root, (first_path, second_path))
projects = store.sync_projects(task.task_id, root, (second_path,))
selected = store.set_projects_selected(task.task_id, True, available_only=True)
by_path = {project.path.name: project for project in selected}
assert by_path["one.prj"].selected is False
assert by_path["two.prj"].selected is True
cleared = store.set_projects_selected(task.task_id, False)
assert not any(project.selected for project in cleared)
def test_project_scan_new_root_replaces_unstarted_inventory(tmp_path: Path) -> None:
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
first_root = tmp_path / "first"
second_root = tmp_path / "second"
first_root.mkdir()
second_root.mkdir()
first_path = first_root / "old.prj"
second_path = second_root / "new.prj"
first_path.touch()
second_path.touch()
first = store.sync_projects(task.task_id, first_root, (first_path,))[0]
store.set_project_selected(first.project_id, True)
second = store.sync_projects(task.task_id, second_root, (second_path,))
assert [project.path for project in second] == [second_path.resolve()]
assert store.list_projects(task.task_id) == second
assert second[0].selected is False
def test_project_scan_new_root_preserves_started_inventory_and_fails_closed(tmp_path: Path) -> None:
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
first_root = tmp_path / "first"
second_root = tmp_path / "second"
first_root.mkdir()
second_root.mkdir()
first_path = first_root / "old.prj"
second_path = second_root / "new.prj"
first_path.touch()
second_path.touch()
first = store.sync_projects(task.task_id, first_root, (first_path,))[0]
store.set_project_status(first.project_id, ProjectStatus.CAPTURING_BEFORE)
with pytest.raises(TaskCenterError) as raised:
store.sync_projects(task.task_id, second_root, (second_path,))
projects = store.list_projects(task.task_id)
assert raised.value.code == "discovery_root_locked"
assert store.get_task(task.task_id).discovery_root == first_root.resolve()
assert len(projects) == 1
assert projects[0].path == first_path.resolve()
assert projects[0].status is ProjectStatus.CAPTURING_BEFORE
def test_same_project_path_can_belong_to_independent_tasks(tmp_path: Path) -> None:
"""Project records must be scoped to their owning task, not globally by path."""
store = TaskStore(tmp_path / "task-center.db")
first_task = store.create_task("First trial")
second_task = store.create_task("Second trial")
project_path = tmp_path / "shared.prj"
project_path.touch()
first_project = store.sync_projects(first_task.task_id, tmp_path, (project_path,))[0]
second_project = store.sync_projects(second_task.task_id, tmp_path, (project_path,))[0]
assert first_project.task_id == first_task.task_id
assert second_project.task_id == second_task.task_id
assert first_project.project_id != second_project.project_id
def test_reader_cannot_observe_a_task_that_later_rolls_back(tmp_path: Path) -> None:
"""A second thread must wait for a transaction rather than observe its uncommitted rows."""
store = TaskStore(tmp_path / "task-center.db")
reader_started = threading.Event()
reader_finished = threading.Event()
observed: list[tuple[TaskRecord, ...]] = []
def read_tasks() -> None:
reader_started.set()
observed.append(store.list_tasks())
reader_finished.set()
reader = threading.Thread(target=read_tasks, name="transaction-reader")
try:
with pytest.raises(RuntimeError, match="abort"):
with store.transaction():
store.create_task("Uncommitted")
reader.start()
assert reader_started.wait(timeout=1)
assert not reader_finished.wait(timeout=0.2)
raise RuntimeError("abort")
finally:
reader.join(timeout=1)
assert not reader.is_alive()
assert reader_finished.is_set()
assert observed == [()]
def test_project_and_task_state_transitions_are_persisted(tmp_path: Path) -> None:
"""Execution state changes must survive the write before UI can observe them."""
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
project_path = tmp_path / "one.prj"
project_path.touch()
project = store.sync_projects(task.task_id, tmp_path, (project_path,))[0]
store.set_task_status(task.task_id, TaskStatus.READY)
store.set_task_status(task.task_id, TaskStatus.RUNNING)
captured = store.set_project_status(project.project_id, ProjectStatus.CAPTURING_BEFORE)
waiting = store.set_project_status(project.project_id, ProjectStatus.AWAITING_OPERATOR)
assert captured.status is ProjectStatus.CAPTURING_BEFORE
assert waiting.status is ProjectStatus.AWAITING_OPERATOR
assert store.get_task(task.task_id).status is TaskStatus.RUNNING
def test_transaction_rollback_leaves_no_partial_task(tmp_path: Path) -> None:
"""A failed grouped write must not expose a partially-created task."""
store = TaskStore(tmp_path / "task-center.db")
with pytest.raises(RuntimeError, match="abort"):
with store.transaction():
store.create_task("Uncommitted")
raise RuntimeError("abort")
assert store.list_tasks() == ()
def test_schema_reopens_and_recovers_interrupted_work(tmp_path: Path) -> None:
"""A crash mid-capture must become a paused task and failed retryable project."""
database = tmp_path / "task-center.db"
first_store = TaskStore(database)
task = first_store.create_task("Trial")
path = tmp_path / "one.prj"
path.touch()
project = first_store.sync_projects(task.task_id, tmp_path, (path,))[0]
first_store.set_task_status(task.task_id, TaskStatus.RUNNING)
first_store.set_project_status(project.project_id, ProjectStatus.CAPTURING_BEFORE)
first_store.set_project_status(project.project_id, ProjectStatus.AWAITING_OPERATOR)
first_store.set_project_status(project.project_id, ProjectStatus.CAPTURING_AFTER)
first_store.close()
reopened = TaskStore(database)
recovered = reopened.recover_interrupted_work()
recovered_task = reopened.get_task(task.task_id)
recovered_project = reopened.list_projects(task.task_id)[0]
assert recovered == (project.project_id,)
assert recovered_task.status is TaskStatus.PAUSED
assert recovered_project.status is ProjectStatus.FAILED
assert recovered_project.error_id is not None
assert "interrupted" in recovered_project.summary.casefold()
def test_completed_task_delete_and_restore_preserves_completed_status(tmp_path: Path) -> None:
"""Archiving a completed task must not turn it into a draft on restore."""
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Completed trial")
store.set_task_status(task.task_id, TaskStatus.RUNNING)
store.set_task_status(task.task_id, TaskStatus.COMPLETED)
deleted = store.soft_delete_task(task.task_id)
restored = store.restore_task(task.task_id)
assert deleted.status is TaskStatus.DELETED
assert restored.status is TaskStatus.COMPLETED
def test_restore_completed_task_preserves_original_completed_timestamp(tmp_path: Path) -> None:
"""Restoring an archived completed task must not manufacture a new completion event."""
database = tmp_path / "task-center.db"
store = TaskStore(database)
task = store.create_task("Timestamp trial")
store.set_task_status(task.task_id, TaskStatus.RUNNING)
completed = store.set_task_status(task.task_id, TaskStatus.COMPLETED)
with sqlite3.connect(database) as connection:
original_timestamp = connection.execute(
"SELECT completed_utc FROM tasks WHERE task_id = ?", (task.task_id,)
).fetchone()[0]
store.soft_delete_task(task.task_id)
restored = store.restore_task(task.task_id)
with sqlite3.connect(database) as connection:
restored_timestamp = connection.execute(
"SELECT completed_utc FROM tasks WHERE task_id = ?", (task.task_id,)
).fetchone()[0]
assert restored.status is TaskStatus.COMPLETED
assert restored.completed_utc == completed.completed_utc
assert restored_timestamp == original_timestamp
def test_attempt_context_is_durable_and_claims_the_only_active_project(tmp_path: Path) -> None:
"""Attempt evidence metadata must survive restart and atomically exclude another active project."""
database = tmp_path / "task-center.db"
store = TaskStore(database)
first_task = store.create_task("First")
second_task = store.create_task("Second")
first_path = tmp_path / "first.prj"
second_path = tmp_path / "second.prj"
first_path.touch()
second_path.touch()
first = store.sync_projects(first_task.task_id, tmp_path, (first_path,))[0]
second = store.sync_projects(second_task.task_id, tmp_path, (second_path,))[0]
store.set_project_selected(first.project_id, True)
store.set_project_selected(second.project_id, True)
store.begin_project_attempt(
first_task.task_id,
first.project_id,
probe_source=tmp_path / "menu-probe.json",
baseline_size=7,
baseline_sha256="a" * 64,
baseline_modified_ns=11,
rules_json='[{"old_part_number":"OLD-1","new_part_number":"NEW-1"}]',
)
store.save_attempt_before(first.project_id, before_path=tmp_path / "before.json", before_size=8, before_sha256="b" * 64, before_modified_ns=12, instruction_json='{"rules":[]}')
with pytest.raises(TaskCenterError, match="active_project_exists"):
store.begin_project_attempt(
second_task.task_id,
second.project_id,
probe_source=tmp_path / "menu-probe.json",
baseline_size=7,
baseline_sha256="a" * 64,
baseline_modified_ns=11,
rules_json="[]",
)
store.close()
reopened = TaskStore(database)
attempt = reopened.current_attempt(first.project_id)
assert attempt is not None
assert attempt.baseline_sha256 == "a" * 64
assert attempt.before_sha256 == "b" * 64
assert attempt.instruction_json == '{"rules":[]}'
def test_v1_database_migrates_to_attempt_metadata_schema(tmp_path: Path) -> None:
"""Upgrading an existing task database must add durable attempt storage without losing tasks."""
database = tmp_path / "task-center.db"
first = TaskStore(database)
task = first.create_task("Trial")
first.close()
with sqlite3.connect(database) as connection:
connection.execute("DROP TABLE attempts")
connection.execute("UPDATE metadata SET value = '1' WHERE key = 'schema_version'")
migrated = TaskStore(database)
assert migrated.get_task(task.task_id).name == "Trial"
with sqlite3.connect(database) as connection:
assert connection.execute("SELECT value FROM metadata WHERE key = 'schema_version'").fetchone()[0] == "5"
assert connection.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'attempts'").fetchone()
assert connection.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'external_requests'").fetchone()
def test_rule_value_and_nc_options_round_trip_and_preserve_on_legacy_update(tmp_path: Path) -> None:
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Rule options")
rule = store.add_rule(
task.task_id,
"OLD",
"NEW",
custom_value_enabled=True,
custom_value="10k",
sync_nc=False,
)
assert (rule.custom_value_enabled, rule.custom_value, rule.sync_nc) == (True, "10k", False)
updated = store.update_rule(
rule.rule_id,
old_part_number="OLD",
new_part_number="NEWER",
enabled=False,
)
assert (updated.custom_value_enabled, updated.custom_value, updated.sync_nc) == (True, "10k", False)
def test_custom_value_must_be_nonblank_and_single_line(tmp_path: Path) -> None:
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Rule validation")
with pytest.raises(TaskCenterError, match="custom_value"):
store.add_rule(task.task_id, "OLD", "NEW", custom_value_enabled=True, custom_value=" ")
with pytest.raises(TaskCenterError, match="custom_value"):
store.add_rule(task.task_id, "OLD", "NEW", custom_value_enabled=True, custom_value="A\tB")
@pytest.mark.parametrize(
"active_status",
(
ProjectStatus.CAPTURING_BEFORE,
ProjectStatus.AWAITING_OPERATOR,
ProjectStatus.CAPTURING_AFTER,
ProjectStatus.VERIFYING,
),
)
def test_v1_migration_fails_attemptless_active_project_closed(tmp_path: Path, active_status: ProjectStatus) -> None:
"""A v1 active project has no attempt context and must not retain the global native-work slot."""
database = tmp_path / "task-center.db"
first = TaskStore(database)
task = first.create_task("Trial")
path = tmp_path / "one.prj"
path.touch()
project = first.sync_projects(task.task_id, tmp_path, (path,))[0]
first.set_task_status(task.task_id, TaskStatus.RUNNING)
transitions = (
ProjectStatus.CAPTURING_BEFORE,
ProjectStatus.AWAITING_OPERATOR,
ProjectStatus.CAPTURING_AFTER,
ProjectStatus.VERIFYING,
)
for status in transitions[: transitions.index(active_status) + 1]:
first.set_project_status(project.project_id, status)
first.close()
with sqlite3.connect(database) as connection:
connection.execute("DROP TABLE attempts")
connection.execute("UPDATE metadata SET value = '1' WHERE key = 'schema_version'")
migrated = TaskStore(database)
recovered = migrated.list_projects(task.task_id)[0]
assert migrated.get_task(task.task_id).status is TaskStatus.PAUSED
assert recovered.status is ProjectStatus.FAILED
assert active_status.value in recovered.summary
assert recovered.error_id is not None
def test_claim_project_attempt_uses_declared_failed_retry_transitions(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A retry claim must traverse the task and project state graph inside its transaction."""
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
path = tmp_path / "one.prj"
path.touch()
project = store.sync_projects(task.task_id, tmp_path, (path,))[0]
store.set_project_selected(project.project_id, True)
store.set_task_status(task.task_id, TaskStatus.RUNNING)
store.set_project_status(project.project_id, ProjectStatus.CAPTURING_BEFORE)
store.set_project_status(project.project_id, ProjectStatus.FAILED)
store.set_task_status(task.task_id, TaskStatus.FAILED)
task_transitions: list[tuple[TaskStatus, TaskStatus]] = []
project_transitions: list[tuple[ProjectStatus, ProjectStatus]] = []
set_task_status = store.set_task_status
set_project_status = store.set_project_status
def record_task_transition(task_id: str, status: TaskStatus, **kwargs: object) -> TaskRecord:
current = store.get_task(task_id).status
if current is not status:
task_transitions.append((current, status))
return set_task_status(task_id, status, **kwargs)
def record_project_transition(project_id: str, status: ProjectStatus, **kwargs: object) -> ProjectRecord:
current = store.list_projects(task.task_id)[0].status
if current is not status:
project_transitions.append((current, status))
return set_project_status(project_id, status, **kwargs)
monkeypatch.setattr(store, "set_task_status", record_task_transition)
monkeypatch.setattr(store, "set_project_status", record_project_transition)
claimed_task, claimed_project = store.claim_project_attempt(
task.task_id,
project.project_id,
expected_task_status=TaskStatus.FAILED,
expected_project_status=ProjectStatus.FAILED,
probe_source=tmp_path / "probe.json",
baseline_size=1,
baseline_sha256="a" * 64,
baseline_modified_ns=1,
rules_json="[]",
task_summary="retry started",
project_summary="project selected for retry",
)
assert task_transitions == [(TaskStatus.FAILED, TaskStatus.PAUSED), (TaskStatus.PAUSED, TaskStatus.RUNNING)]
assert project_transitions == [(ProjectStatus.FAILED, ProjectStatus.PENDING)]
assert claimed_task.status is TaskStatus.RUNNING
assert claimed_project.status is ProjectStatus.CAPTURING_BEFORE
@@ -0,0 +1,213 @@
from pathlib import Path
import subprocess
import sqlite3
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.models import ProjectRecord, ProjectStatus, RuleRecord
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
SOURCE = Path(__file__).resolve().parents[2] / 'integration/dxdesigner795/QuickPartReplace.vbs'
def inputs():
projects = tuple(ProjectRecord(f'project-{index}', 'task', f'Project {index}',
Path(f'C:/review/project-{index}.prj'), Path('C:/review'),
True, True, ProjectStatus.PENDING, 0) for index in range(2))
return projects, (RuleRecord('rule', 'task', 0, 'OLD', 'NEW', True),)
def test_task_value_option_defaults_off_and_survives_reopen(tmp_path):
database = TaskStore(tmp_path / 'tasks.db')
task = database.create_task('Option')
assert task.copy_part_number_to_value is False
database.set_copy_part_number_to_value(task.task_id, True)
database.close()
database = TaskStore(tmp_path / 'tasks.db')
try:
assert database.get_task(task.task_id).copy_part_number_to_value is True
finally:
database.close()
@pytest.mark.parametrize('enabled,mode', [(False, 'preserve'), (True, 'part_label')])
def test_queue_records_explicit_value_policy(tmp_path, enabled, mode):
projects, rules = inputs()
preparer = QuickRunPreparer(tmp_path, script_source=SOURCE)
result = preparer.prepare('task', projects, rules, copy_part_number_to_value=enabled)
lines = result.command_path.read_text(encoding='utf-8').splitlines()
header = lines[0].split('\t')
assert 'value_mode' in header
assert {line.split('\t')[header.index('value_mode')] for line in lines[1:]} == {mode}
def test_queue_freezes_custom_value_and_nc_policy_per_rule(tmp_path):
projects, _ = inputs()
rules = (RuleRecord('rule', 'task', 0, 'OLD', 'NEW', True, True, '100nF', False),)
result = QuickRunPreparer(tmp_path, script_source=SOURCE).prepare(
'task', projects, rules, copy_part_number_to_value=True
)
lines = result.command_path.read_text(encoding='utf-8').splitlines()
header = lines[0].split('\t')
row = dict(zip(header, lines[1].split('\t'), strict=True))
assert row['value_mode'] == 'custom'
assert row['custom_value'] == '100nF'
assert row['sync_nc'] == '0'
assert row['base_value_mode'] == 'part_label'
def test_result_for_other_queued_project_is_rejected(tmp_path):
projects, rules = inputs()
def worker(command, timeout):
rows = (tmp_path / 'quick-run/command.tsv').read_text(encoding='utf-8').splitlines()
wrong_job = rows[2].split('\t')[1]
with (tmp_path / 'quick-run/status.tsv').open('a', encoding='utf-8') as handle:
handle.write(f'{wrong_job}\tawaiting_native_replace\t\tcaptured\n{wrong_job}\trestored_ok\t\tverified\n')
return subprocess.CompletedProcess(command, 0, '', '')
preparer = QuickRunPreparer(tmp_path, script_source=SOURCE, process_runner=worker,
cscript_resolver=lambda: Path('C:/Windows/SysWOW64/cscript.exe'))
with pytest.raises(TaskCenterError, match='quick_run_uncertain'):
preparer.execute_step('task', projects, rules)
assert (tmp_path / 'quick-run/uncertain.flag').exists()
def test_policy_change_cannot_reinterpret_partial_queue(tmp_path):
projects, rules = inputs()
preparer = QuickRunPreparer(tmp_path, script_source=SOURCE)
result = preparer.prepare('task', projects, rules)
job = result.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
result.status_path.write_text(f'job_id\tstate\tcode\tmessage\n{job}\tawaiting_native_replace\t\tcaptured\n', encoding='utf-8')
with pytest.raises(TaskCenterError, match='quick_run_pending'):
preparer.execute_step('task', projects, rules, copy_part_number_to_value=True)
def test_service_freezes_setting_after_queue_is_prepared(tmp_path):
database = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(database, configure_logging(tmp_path / 'data'))
task = service.create_task('Freeze')
service.set_copy_part_number_to_value(task.task_id, True)
assert service.get_task(task.task_id).copy_part_number_to_value is True
queue = tmp_path / 'data/quick-run'
queue.mkdir()
(queue / 'command.tsv').write_text(
f'task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\n{task.task_id}\tjob\tC:/test.prj\tOLD\tNEW\tpart_number\n',
encoding='utf-8')
(queue / 'status.tsv').write_text('job_id\tstate\tcode\tmessage\n', encoding='utf-8')
try:
with pytest.raises(TaskCenterError, match='quick_run_options_locked'):
service.set_copy_part_number_to_value(task.task_id, False)
finally:
database.close()
def test_v2_task_migration_defaults_off_without_changing_task(tmp_path):
path = tmp_path / 'old.db'
database = TaskStore(path)
task = database.create_task('Existing task', 'Keep this note')
database.close()
with sqlite3.connect(path) as connection:
connection.execute('ALTER TABLE tasks DROP COLUMN copy_part_number_to_value')
connection.execute("UPDATE metadata SET value='2' WHERE key='schema_version'")
database = TaskStore(path)
try:
migrated = database.get_task(task.task_id)
assert migrated.name == task.name and migrated.note == task.note
assert migrated.status is task.status
assert migrated.copy_part_number_to_value is False
finally:
database.close()
def test_checked_service_uses_same_policy_for_execution_and_progress(tmp_path):
root = tmp_path / 'data'
def worker(command, timeout):
lines = (root / 'quick-run/command.tsv').read_text(encoding='utf-8').splitlines()
row = lines[1].split('\t')
assert row[-1] == 'part_label'
assert command[-1] == row[1]
with (root / 'quick-run/status.tsv').open('a', encoding='utf-8') as handle:
handle.write(f'{row[1]}\tawaiting_native_replace\t\tcaptured\n{row[1]}\trestored_ok\t\tverified\n')
return subprocess.CompletedProcess(command, 0, '', '')
preparer = QuickRunPreparer(root, script_source=SOURCE, process_runner=worker,
cscript_resolver=lambda: Path('C:/Windows/SysWOW64/cscript.exe'))
database = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(database, configure_logging(root), quick_run_preparer=preparer)
task = service.create_task('Checked')
(tmp_path / 'one.prj').touch()
project = service.scan_projects(task.task_id, tmp_path)[0]
service.set_project_selected(project.project_id, True)
service.add_rule(task.task_id, 'OLD', 'NEW')
service.set_copy_part_number_to_value(task.task_id, True)
try:
result = service.execute_quick_run(task.task_id, expected_item=(str(project.path), 'OLD', 'NEW', 'part_label'))
assert result.state == 'restored_ok'
assert service.quick_run_progress(task.task_id).queue_complete
finally:
database.close()
def test_changed_confirmation_never_starts_worker(tmp_path):
projects, rules = inputs()
calls = []
preparer = QuickRunPreparer(tmp_path, script_source=SOURCE, process_runner=lambda *args: calls.append(args))
with pytest.raises(TaskCenterError, match='quick_run_selection_changed'):
preparer.execute_step('task', projects, rules, expected_item=(str(projects[1].path), 'OLD', 'NEW', 'preserve'))
assert calls == []
def test_serial_three_project_two_rule_queue_pins_each_job(tmp_path):
selected, _ = inputs()
third = ProjectRecord('third', 'task', 'Third', Path('C:/review/third.prj'), Path('C:/review'), True, True, ProjectStatus.PENDING, 0)
projects = (*selected, third)
rules = (RuleRecord('first', 'task', 0, 'OLD', 'NEW', True), RuleRecord('second', 'task', 1, 'OLD2', 'NEW2', True))
completed = []
def worker(command, timeout):
rows = [line.split('\t') for line in (tmp_path / 'quick-run/command.tsv').read_text(encoding='utf-8').splitlines()[1:]]
row = rows[len(completed)]
assert command[-1] == row[1]
with (tmp_path / 'quick-run/status.tsv').open('a', encoding='utf-8') as handle:
handle.write(f'{row[1]}\tawaiting_native_replace\t\tcaptured\n{row[1]}\trestored_ok\t\tverified\n')
completed.append((row[2], row[3]))
return subprocess.CompletedProcess(command, 0, '', '')
preparer = QuickRunPreparer(tmp_path, script_source=SOURCE, process_runner=worker,
cscript_resolver=lambda: Path('C:/Windows/SysWOW64/cscript.exe'))
for index in range(6):
preparer.execute_step('task', projects, rules)
assert len(completed) == index + 1
assert completed == [(str(project.path), rule.old_part_number) for project in projects for rule in rules]
assert preparer.progress('task', projects, rules).queue_complete
def test_old_queue_snapshot_blocks_policy_reinterpretation_without_status(tmp_path):
projects, rules = inputs()
preparer = QuickRunPreparer(tmp_path, script_source=SOURCE)
result = preparer.prepare('task', projects, rules)
lines = [line.split('\t') for line in result.command_path.read_text(encoding='utf-8').splitlines()]
value_mode_index = lines[0].index('value_mode')
result.command_path.write_text(
'\n'.join('\t'.join(fields[:value_mode_index] + fields[value_mode_index + 1:]) for fields in lines) + '\n',
encoding='utf-8',
)
(result.command_path.parent / 'snapshot-old.tsv').write_text('retained evidence', encoding='utf-8')
with pytest.raises(TaskCenterError, match='quick_run_pending'):
preparer.execute_step('task', projects, rules)
def test_frozen_launcher_reserves_helper_script_slot(monkeypatch, tmp_path):
import sys
from dx_productivity.trial_task_center.quick_run import _native_helper_launch_arguments
monkeypatch.setattr(sys, 'frozen', True, raising=False)
monkeypatch.setattr(sys, 'executable', str(tmp_path / 'DxPartReplace.exe'))
assert _native_helper_launch_arguments() == (str((tmp_path / 'DxPartReplace.exe').resolve()), '')
@@ -0,0 +1,193 @@
import json
from pathlib import Path
import subprocess
import sys
import pytest
from dx_productivity.trial_task_center import worker_monitor
def frame(sequence, stage='capture', done=1, total=18, safe=1, token='token', job='job'):
return f'DX_PROGRESS\t{token}\t{job}\t{sequence}\t{stage}\t{done}\t{total}\t{safe}\n'.encode()
def test_progress_allows_total_runtime_to_exceed_idle_limit():
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
for sequence, now in enumerate(range(100, 1001, 100), 1):
assert watch.accept(frame(sequence), now)
assert watch.action(now) is None
assert not watch.stop_requested
def test_idle_requests_stop_before_emergency_timeout():
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
assert watch.action(149) is None
assert watch.action(150) == 'request_stop'
assert watch.action(151) is None
assert watch.action(299) is None
assert watch.action(300) == 'unresponsive'
def test_progress_during_drain_prevents_emergency_kill():
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
assert watch.action(150) == 'request_stop'
for sequence, now in enumerate((200, 350, 490, 630), 1):
assert watch.accept(frame(sequence, safe=0), now)
assert watch.action(now) is None
assert watch.stop_requested
@pytest.mark.parametrize('line', [
frame(1, token='stale'), frame(1, job='other'), frame(0),
frame(1, done=19), frame(1, safe=3), b'garbage\n', frame(1, stage='bad\tstage'),
])
def test_invalid_or_foreign_frames_do_not_extend_deadline(line):
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
assert not watch.accept(line, 140)
assert watch.action(150) == 'request_stop'
def test_replayed_sequence_does_not_extend_deadline():
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
assert watch.accept(frame(2), 10)
assert not watch.accept(frame(2), 155)
assert not watch.accept(frame(1), 155)
assert watch.action(160) == 'request_stop'
def toy_worker(tmp_path: Path, body: str):
script = tmp_path / 'toy.py'
script.write_text('''
import pathlib,sys,time
root=pathlib.Path(sys.argv[1])
job=sys.argv[4]
token=sys.argv[5]
ready=root/f'monitor-{token}.ready'
stop=root/f'monitor-{token}.stop'
while not ready.exists(): time.sleep(0.01)
def emit(sequence):
print(f'DX_PROGRESS\\t{token}\\t{job}\\t{sequence}\\tverify\\t{sequence}\\t10\\t0',flush=True)
''' + body, encoding='utf-8')
return (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
def test_real_process_with_progress_outlives_idle_timeout(tmp_path):
command = toy_worker(tmp_path, '''
for sequence in range(1,6):
emit(sequence)
time.sleep(0.4)
print('DONE',flush=True)
''')
result = worker_monitor.run_monitored_process(command, 1.0)
assert result.returncode == 0
assert 'DONE' in result.stdout
assert 'DX_PROGRESS' not in result.stdout
progress = json.loads((tmp_path / 'worker-progress.json').read_text(encoding='utf-8'))
assert progress['sequence'] == 5
assert not progress['stop_requested']
def test_idle_worker_can_acknowledge_cooperative_stop(tmp_path):
command = toy_worker(tmp_path, '''
while not stop.exists(): time.sleep(0.01)
print('stopped before mutation',flush=True)
sys.exit(3)
''')
result = worker_monitor.run_monitored_process(command, 0.5)
assert result.returncode == 3
assert 'stopped before mutation' in result.stdout
progress = json.loads((tmp_path / 'worker-progress.json').read_text(encoding='utf-8'))
assert progress['stop_requested']
def test_unresponsive_worker_is_not_left_running(tmp_path):
command = toy_worker(tmp_path, '''
import os,subprocess
child=subprocess.Popen([sys.executable,'-c','import time;time.sleep(60)'])
(root/'pids.json').write_text(__import__('json').dumps([os.getpid(),child.pid]))
time.sleep(60)
''')
with pytest.raises(subprocess.TimeoutExpired):
worker_monitor.run_monitored_process(command, 0.7)
import win32api
import win32con
import win32event
for pid in json.loads((tmp_path / 'pids.json').read_text()):
try:
handle = win32api.OpenProcess(win32con.SYNCHRONIZE, False, pid)
except Exception:
continue
try:
assert win32event.WaitForSingleObject(handle, 2000) == win32event.WAIT_OBJECT_0
finally:
handle.Close()
def test_real_vbs_monitor_handshake_fails_before_cad_for_missing_project(tmp_path):
script = Path(__file__).resolve().parents[2] / 'integration/dxdesigner795/QuickPartReplace.vbs'
(tmp_path / 'command.tsv').write_text('job_id\tproject_path\njob\tC:\\nonexistent-monitor-fixture\\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()
command = (r'C:\Windows\SysWOW64\cscript.exe', '//nologo', str(script), str(tmp_path), sys.executable, '', 'job')
result = worker_monitor.run_monitored_process(command, 5)
assert result.returncode == 2
assert 'confirmed project file does not exist' in result.stderr
assert status.read_bytes() == before
progress = json.loads((tmp_path / 'worker-progress.json').read_text(encoding='utf-8'))
assert progress['stage'] == 'session_startup'
assert progress['sequence'] == 1
assert not progress['stop_requested']
def test_monitor_io_failure_remains_an_uncertain_execution(tmp_path, monkeypatch):
command = toy_worker(tmp_path, 'time.sleep(60)\n')
def fail_write(path, text):
raise OSError('disk not writable')
monkeypatch.setattr(worker_monitor, '_atomic_text', fail_write)
with pytest.raises(worker_monitor.WorkerMonitorError, match='disk not writable'):
worker_monitor.run_monitored_process(command, 1)
def test_locked_progress_display_does_not_interrupt_real_worker(tmp_path):
import win32con
import win32file
progress = tmp_path / 'worker-progress.json'
progress.write_text('{}', encoding='utf-8')
handle = win32file.CreateFile(str(progress), win32con.GENERIC_READ,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None, win32con.OPEN_EXISTING, 0, None)
try:
command = toy_worker(tmp_path, '''
for sequence in range(1,6):
emit(sequence)
time.sleep(0.25)
print('DONE',flush=True)
''')
result = worker_monitor.run_monitored_process(command, 0.8)
assert result.returncode == 0
assert 'DONE' in result.stdout
assert not list(tmp_path.glob('monitor-*.stop'))
finally:
handle.Close()
worker_monitor._publish_progress(progress, {'sequence': 6})
assert json.loads(progress.read_text()) == {'sequence': 6}
def test_progress_contention_does_not_hide_control_file_failure(tmp_path, monkeypatch):
original = worker_monitor._atomic_text
def locked_ready(path, text):
if path.suffix == '.ready':
raise PermissionError('control file locked')
return original(path, text)
monkeypatch.setattr(worker_monitor, '_atomic_text', locked_ready)
with pytest.raises(worker_monitor.WorkerMonitorError, match='control file locked'):
worker_monitor.run_monitored_process(toy_worker(tmp_path, 'time.sleep(60)\n'), 1)
def test_chinese_worker_diagnostics_are_not_replaced_with_garbage():
assert worker_monitor._decode('对象不支持此属性或方法'.encode('mbcs')) == '对象不支持此属性或方法'
+317
View File
@@ -0,0 +1,317 @@
from pathlib import Path
import json
import subprocess
from types import SimpleNamespace
import pytest
from PySide6.QtWidgets import QMessageBox
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.ui import main_window
from dx_productivity.trial_task_center.ui.main_window import (
TrialTaskCenterWindow,
_aligned_log_line,
_format_task_log_lines,
_nc_sync_log_lines,
)
def test_nc_sync_evidence_is_formatted_for_operator_log():
message = (
'Native replacement passed. NC synced: '
'R1 R0603/NC -> R0805/NC (detected /NC and synchronized); '
'C2 C0603/NC -> C0805/NC (detected /NC and synchronized)'
)
assert _nc_sync_log_lines(message) == (
'位号 R1 R0603/NC -> R0805/NC,识别到 NC,已同步',
'位号 C2 C0603/NC -> C0805/NC,识别到 NC,已同步',
)
def test_task_event_json_is_rendered_as_readable_operator_text():
line = json.dumps({
'timestamp_utc': '2026-09-06T10:55:34.796685Z',
'level': 'INFO',
'operation': 'value_policy_changed',
'message': '',
'details': {'copy_part_number_to_value': True},
})
assert _format_task_log_lines((line, 'legacy line')) == (
'2026-09-06 10:55:34 | INFO | value_policy_changed | Value 选项已更新:替换后写入目标 Part Label。',
' | INFO | legacy | legacy line',
)
def test_log_operation_column_stays_aligned_for_long_names():
line = _aligned_log_line(
'2026-09-10 12:34:56',
'WARNING',
'operation_name_that_is_longer_than_the_column',
'内容',
)
assert line.index(' | 内容') == 19 + 3 + 7 + 3 + 28
assert 'operation_name_that_is_lo...' in line
def test_running_batch_rebuilds_project_table_only_at_project_boundaries(qtbot, tmp_path, monkeypatch):
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
task = service.create_task('Refresh boundary')
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.open_task(task.task_id)
window._active_quick_run_task_id = task.task_id
window._quick_run_elapsed.start()
window._batch_rendered = (task.task_id, 0)
renders = []
monkeypatch.setattr(window, '_populate_projects', lambda: renders.append('render'))
monkeypatch.setattr(window, '_update_gates', lambda: None)
progress = SimpleNamespace(
completed_items=1,
total_items=3,
no_match_items=1,
completed_project_paths=(),
)
service._batch_feedback = (task.task_id, progress, '正在处理')
window._update_quick_run_elapsed()
assert renders == []
assert '已处理 1/3 项' in window.run_panel.queue_summary.text()
progress.completed_items = 2
progress.completed_project_paths = (tmp_path / 'project.prj',)
service._batch_feedback = (task.task_id, progress, '工程已完成')
window._update_quick_run_elapsed()
assert renders == ['render']
window.close()
store.close()
@pytest.mark.parametrize('code', ['quick_run_session', 'quick_run_preflight'])
def test_pre_mutation_failure_does_not_keep_running_label_or_claim_possible_writes(qtbot, tmp_path, code):
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
task = service.create_task('Diagnostic')
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.open_task(task.task_id)
window.run_panel.execution_status.setText('正在执行')
window._show_error(TaskCenterError(code, 'test preflight'))
assert '执行已停止' in window.run_panel.execution_status.text()
assert '尚未开始替换' in window.run_panel.execution_status.text()
assert '图页可能已被修改' not in window.run_panel.operator_band.text()
assert '不能假定图页未修改' not in window.run_panel.operator_band.text()
window.close()
store.close()
def test_backup_failure_exposes_one_shot_continue_button(qtbot, tmp_path, monkeypatch):
root = tmp_path / 'projects'
root.mkdir()
(root / 'one.prj').touch()
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
task = service.create_task('Backup override')
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
service.add_rule(task.task_id, 'OLD', 'NEW')
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.open_task(task.task_id)
assert window.run_panel.continue_without_backup_button.isHidden()
window._show_error(TaskCenterError('quick_run_backup', 'simulated backup failure'))
assert not window.run_panel.continue_without_backup_button.isHidden()
assert window.run_panel.continue_without_backup_button.isEnabled()
dispatched = []
monkeypatch.setattr(
QMessageBox,
'warning',
lambda *_args, **_kwargs: QMessageBox.StandardButton.Yes,
)
monkeypatch.setattr(
window,
'_start_quick_run_queue',
lambda task_id, expected_item, **options: dispatched.append((task_id, expected_item, options)),
)
window._continue_without_backup()
assert dispatched[0][0] == task.task_id
assert dispatched[0][1][1:] == ('OLD', 'NEW', 'preserve')
assert dispatched[0][2] == {'continue_after_backup_failure': True}
window.close()
store.close()
def test_non_backup_failure_does_not_expose_backup_override(qtbot, tmp_path):
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
task = service.create_task('No backup override')
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.open_task(task.task_id)
window._show_error(TaskCenterError('quick_run_preflight', 'simulated preflight failure'))
assert window.run_panel.continue_without_backup_button.isHidden()
window.close()
store.close()
@pytest.mark.parametrize('displayed', [False, True])
@pytest.mark.parametrize('state', ['no_match', 'restored_ok'])
def test_confirmation_matches_execution_and_zero_match_is_a_completed_skip(qtbot, tmp_path, monkeypatch, displayed, state):
data = tmp_path / 'data'
executed = []
messages = []
def worker(command, timeout):
row = (data / 'quick-run/command.tsv').read_text(encoding='utf-8').splitlines()[1].split('\t')
executed.append(row[-1])
with (data / 'quick-run/status.tsv').open('a', encoding='utf-8') as handle:
if state == 'restored_ok':
handle.write(f'{row[1]}\tawaiting_native_replace\t\tcaptured\n')
terminal = 'saved_ok' if state == 'restored_ok' else state
handle.write(f'{row[1]}\t{terminal}\tbatch_closed\tcurrent sheet checked\n')
return subprocess.CompletedProcess(command, 0, '', '')
class ConfirmBox:
Icon = QMessageBox.Icon
ButtonRole = QMessageBox.ButtonRole
def __init__(self, icon, title, text, parent=None):
messages.append(text)
self.buttons = []
def addButton(self, text, role):
button = object()
self.buttons.append(button)
return button
def exec(self):
return 0
def clickedButton(self):
return self.buttons[0]
source = Path(__file__).resolve().parents[2] / 'integration/dxdesigner795/QuickPartReplace.vbs'
preparer = QuickRunPreparer(data, script_source=source, process_runner=worker,
cscript_resolver=lambda: Path('C:/Windows/SysWOW64/cscript.exe'),
sheet_discoverer=lambda project: (('Main', '1'),))
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(data), quick_run_preparer=preparer)
task = service.create_task('Policy consistency')
project_root = tmp_path / 'projects'
project_root.mkdir()
(project_root / 'one.prj').touch()
project = service.scan_projects(task.task_id, project_root)[0]
service.set_project_selected(project.project_id, True)
service.add_rule(task.task_id, 'OLD', 'NEW')
service.set_copy_part_number_to_value(task.task_id, displayed)
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.show()
window.open_task(task.task_id)
qtbot.waitUntil(lambda: not window._workers)
other_store = TaskStore(tmp_path / 'tasks.db')
other = TaskCenterService(other_store, configure_logging(data))
try:
other.set_copy_part_number_to_value(task.task_id, not displayed)
assert window.run_panel.copy_value_check.isChecked() is displayed
monkeypatch.setattr(main_window, 'QMessageBox', ConfirmBox)
window._prepare_quick_run()
qtbot.waitUntil(lambda: not window._workers, timeout=10000)
expected = 'preserve' if displayed else 'part_label'
shown = '保留原 Value,不额外改写' if displayed else '复制目标 Part Label'
assert shown in messages[0]
assert '枚举工程内全部原理图页' in messages[0]
assert '图页清单在替换前固定' in messages[0]
assert executed == [expected]
assert service.quick_run_progress(task.task_id).queue_complete
if state == 'no_match':
assert '成功 0,失败 0,未命中 1' in window.run_panel.operator_band.text()
assert '全工程图页队列完成' in window.run_panel.operator_band.text()
assert window.run_panel.operator_band.property('state') == 'success'
assert window.run_panel.execution_status.text() == '队列已完成'
assert '未命中 1' in window.run_panel.queue_summary.text()
assert '全工程图页队列完成' in window.run_panel.operator_band.text()
assert window.project_table.item(0, 3).text() == '未命中跳过'
assert '未作替换' in window.project_table.item(0, 4).text()
else:
assert '成功 1,失败 0,未命中 0' in window.run_panel.operator_band.text()
window.open_task(task.task_id)
qtbot.waitUntil(lambda: not window._workers)
assert '尚未' not in window.run_panel.operator_band.text()
assert '成功项已保存' in window.run_panel.operator_band.text()
assert '已保存' in window.project_table.item(0, 4).text()
finally:
window.close()
other_store.close()
store.close()
def test_closing_during_execution_requests_boundary_pause(qtbot, tmp_path):
from threading import Event
from PySide6.QtGui import QCloseEvent
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.show()
qtbot.waitUntil(lambda: not window._workers)
stop = Event()
window._batch_stop = stop
window._button_generations[window.run_panel.quick_run_button] = 1
close_event = QCloseEvent()
try:
window.closeEvent(close_event)
assert not close_event.isAccepted()
assert stop.is_set()
assert not window.run_panel.stop_queue_button.isEnabled()
assert '正在完成当前项' in window.run_panel.stop_queue_button.text()
finally:
window._button_generations.clear()
window._batch_stop = None
window.close()
store.close()
def test_manual_skip_is_disabled_while_automatic_worker_runs(qtbot, tmp_path):
from threading import Event
root = tmp_path / 'projects'
root.mkdir()
(root / 'one.prj').touch()
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
task = service.create_task('Automatic queue')
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
service.add_rule(task.task_id, 'OLD', 'NEW')
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.open_task(task.task_id)
window.project_table.selectRow(0)
window._batch_stop = Event()
window._button_generations[window.run_panel.quick_run_button] = 1
try:
window._update_gates()
assert not window.skip_button.isEnabled()
assert not window.retry_button.isEnabled()
assert window.project_table.isEnabled()
assert window.mapping_table.isEnabled()
assert not window.project_table.cellWidget(0, 0).isEnabled()
assert not window.mapping_table.cellWidget(0, 4).findChild(main_window.QCheckBox).isEnabled()
finally:
window._button_generations.clear()
window._batch_stop = None
window.close()
store.close()
+83
View File
@@ -0,0 +1,83 @@
import pytest
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QApplication, QMessageBox
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.models import TaskStatus
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
@pytest.mark.parametrize('accept', [False, True])
def test_deleted_task_has_confirmed_permanent_delete(qtbot, tmp_path, accept):
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
task = service.create_task('Recycle bin task')
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.show()
window.open_task(task.task_id)
assert window.task_list.delete_button.text() == '删除'
service.delete_task(task.task_id)
window.task_list.filter.setCurrentText('已删除')
window.open_task(task.task_id)
assert window.task_list.delete_button.text() == '彻底删除'
assert window.task_list.restore_button.isEnabled()
observed = []
def choose():
dialog = QApplication.activeModalWidget()
assert isinstance(dialog, QMessageBox)
assert 'Recycle bin task' in dialog.text()
assert '诊断日志和执行证据保留' in dialog.text()
assert '不再受队列执行锁' in dialog.text()
assert dialog.defaultButton().text() == '取消'
assert dialog.escapeButton().text() == '取消'
observed.append(True)
next(button for button in dialog.buttons() if button.text() == ('彻底删除' if accept else '取消')).click()
try:
QTimer.singleShot(0, choose)
window._delete_task()
qtbot.waitUntil(lambda: not window._workers, timeout=10000)
assert observed == [True]
if accept:
assert window.task_list.list.count() == 0
assert window._task_id is None
assert not window.task_list.delete_button.isEnabled()
with pytest.raises(TaskCenterError, match='unknown_task'):
service.get_task(task.task_id)
else:
assert service.get_task(task.task_id).status is TaskStatus.DELETED
assert window.task_list.list.count() == 1
finally:
window.close()
store.close()
def test_restore_during_confirmation_cannot_be_permanently_deleted(qtbot, tmp_path):
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
task = service.create_task('Concurrent restore')
service.delete_task(task.task_id)
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.show()
window.task_list.filter.setCurrentText('已删除')
def restore_then_confirm():
service.restore_task(task.task_id)
dialog = QApplication.activeModalWidget()
next(button for button in dialog.buttons() if button.text() == '彻底删除').click()
try:
QTimer.singleShot(0, restore_then_confirm)
window._delete_task()
qtbot.waitUntil(lambda: not window._workers, timeout=10000)
assert service.get_task(task.task_id).status is TaskStatus.DRAFT
assert '任务状态可能已变化' in window.run_panel.operator_band.text()
finally:
window.close()
store.close()
+112
View File
@@ -0,0 +1,112 @@
from __future__ import annotations
from datetime import datetime, timezone
from pathlib import Path
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QComboBox, QHeaderView, QListWidget, QPushButton, QSplitter, QTableWidget, QWidget
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.models import TaskStatus
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
def _service(tmp_path: Path) -> tuple[TaskCenterService, TaskStore]:
store = TaskStore(tmp_path / "task-center.db")
service = TaskCenterService(
store,
configure_logging(tmp_path / "storage"),
path_opener=lambda _path: None,
clock=lambda: datetime(2026, 9, 4, tzinfo=timezone.utc),
)
return service, store
def test_interrupted_task_offers_recovery_instead_of_repeat_replace(qtbot, tmp_path, monkeypatch):
from PySide6.QtWidgets import QMessageBox
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service, store = _service(tmp_path)
task = service.create_task("Interrupted")
project = tmp_path / 'projects' / 'one.prj'
project.parent.mkdir()
project.touch()
service.scan_projects(task.task_id, project.parent)
service.set_project_selected(service.projects(task.task_id)[0].project_id, True)
service.add_rule(task.task_id, 'OLD', 'NEW')
handoff = service.prepare_quick_run(task.task_id)
(handoff.command_path.parent / 'uncertain.flag').write_text('timeout')
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.show()
assert window.run_panel.recover_button.isVisible()
assert window.run_panel.recover_button.isEnabled()
assert not window.run_panel.quick_run_button.isEnabled()
monkeypatch.setattr(QMessageBox, 'question', lambda *args: QMessageBox.StandardButton.No)
window._recover_quick_run()
assert not window._workers
assert (handoff.command_path.parent / 'uncertain.flag').exists()
other = service.create_task('Other')
assert not service.has_interrupted_quick_run(other.task_id)
def test_shell_has_stable_automation_controls_and_task_filters(qtbot, tmp_path: Path) -> None:
"""Removing task navigation controls would make archived work inaccessible."""
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service, store = _service(tmp_path)
active = service.create_task("Active")
completed = service.create_task("Completed")
deleted = service.create_task("Deleted")
store.set_task_status(completed.task_id, TaskStatus.READY)
store.set_task_status(completed.task_id, TaskStatus.RUNNING)
store.set_task_status(completed.task_id, TaskStatus.COMPLETED)
service.delete_task(deleted.task_id)
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.show()
assert window.minimumWidth() <= 900
assert window.minimumHeight() <= 600
task_filter = window.findChild(QComboBox, "taskFilter")
task_list = window.findChild(QListWidget, "taskList")
assert task_filter is not None
assert task_list is not None
assert {window.findChild(QWidget, name) is not None for name in (
"newTaskButton", "editTaskButton", "deleteTaskButton", "restoreTaskButton", "directoryPath",
"browseDirectoryButton", "scanProjectsButton", "projectTable", "selectAllProjectsButton",
"clearProjectsButton", "mappingTable", "addMappingButton", "quickRunButton", "queueSummary",
"executionStatus", "quickRunBusyIndicator", "logView",
)} == {True}
assert [task_filter.itemText(index) for index in range(task_filter.count())] == ["进行中", "已完成", "已删除"]
assert window.windowTitle() == "DxDesigner 器件批量替换任务中心 · 1.0.0"
assert window.findChild(QWidget, "directoryPath").placeholderText() == "请选择 DxDesigner 工程所在目录"
assert window.run_panel.operator_band.text() == "请扫描并勾选至少一个工程。"
assert window.findChild(QPushButton, "newTaskButton").text() == "新建"
assert window.findChild(QPushButton, "scanProjectsButton").text() == "扫描工程"
assert window.findChild(QPushButton, "startTaskButton") is None
assert window.findChild(QTableWidget, "projectTable").horizontalHeaderItem(0).text() == "选择"
assert window.findChild(QTableWidget, "mappingTable").horizontalHeaderItem(0).text() == "旧物料编码"
workspace_splitter = window.findChild(QSplitter, "workspaceSplitter")
detail_splitter = window.findChild(QSplitter, "detailSplitter")
assert workspace_splitter is not None and workspace_splitter.orientation() is Qt.Orientation.Horizontal
assert detail_splitter is not None and detail_splitter.orientation() is Qt.Orientation.Vertical
assert not workspace_splitter.childrenCollapsible()
assert not detail_splitter.childrenCollapsible()
assert detail_splitter.count() == 3
project_header = window.findChild(QTableWidget, "projectTable").horizontalHeader()
mapping_header = window.findChild(QTableWidget, "mappingTable").horizontalHeader()
assert all(project_header.sectionResizeMode(section) is QHeaderView.ResizeMode.Interactive for section in range(1, 5))
assert all(mapping_header.sectionResizeMode(section) is QHeaderView.ResizeMode.Interactive for section in range(4))
assert task_list.currentItem().text() == "Active"
assert window._task_id == active.task_id
task_filter.setCurrentText("已完成")
assert [task_list.item(index).text() for index in range(task_list.count())] == ["Completed"]
task_filter.setCurrentText("已删除")
assert [task_list.item(index).text() for index in range(task_list.count())] == ["Deleted"]
task_filter.setCurrentText("进行中")
assert [task_list.item(index).text() for index in range(task_list.count())] == ["Active"]
+769
View File
@@ -0,0 +1,769 @@
from __future__ import annotations
from datetime import datetime, timezone
from pathlib import Path
from threading import Event
import pytest
from PySide6.QtCore import Qt, QTimer
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QAbstractItemView, QCheckBox, QComboBox, QPushButton, QTableWidget
from shiboken6 import isValid
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.models import ProjectStatus, TaskStatus
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
def _service(tmp_path: Path) -> TaskCenterService:
return TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
configure_logging(tmp_path / "storage"),
path_opener=lambda _path: None,
clock=lambda: datetime(2026, 9, 4, tzinfo=timezone.utc),
)
def _service_and_store(tmp_path: Path) -> tuple[TaskCenterService, TaskStore]:
store = TaskStore(tmp_path / "task-center.db")
return (
TaskCenterService(
store,
configure_logging(tmp_path / "storage"),
path_opener=lambda _path: None,
clock=lambda: datetime(2026, 9, 4, tzinfo=timezone.utc),
),
store,
)
def test_scan_selection_mapping_and_quick_run_gate_use_service_workers(qtbot, tmp_path: Path) -> None:
"""A UI-thread scan or a permissive quick-run button could export unsafe task input."""
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
root = tmp_path / "projects"
root.mkdir()
(root / "one.prj").touch()
(root / "two.prj").touch()
service = _service(tmp_path)
task = service.create_task("Trial")
window = TrialTaskCenterWindow(service, directory_picker=lambda: root)
qtbot.addWidget(window)
window.show()
window.open_task(task.task_id)
scan = window.findChild(__import__("PySide6.QtWidgets", fromlist=["QPushButton"]).QPushButton, "scanProjectsButton")
assert scan is not None
QTest.mouseClick(window.findChild(__import__("PySide6.QtWidgets", fromlist=["QPushButton"]).QPushButton, "browseDirectoryButton"), Qt.MouseButton.LeftButton)
QTest.mouseClick(scan, Qt.MouseButton.LeftButton)
assert not scan.isEnabled()
qtbot.waitUntil(lambda: scan.isEnabled(), timeout=5000)
projects = window.findChild(QTableWidget, "projectTable")
quick_run = window.findChild(__import__("PySide6.QtWidgets", fromlist=["QPushButton"]).QPushButton, "quickRunButton")
assert projects is not None and projects.rowCount() == 2
assert quick_run is not None and not quick_run.isEnabled()
QTest.mouseClick(window.findChild(__import__("PySide6.QtWidgets", fromlist=["QPushButton"]).QPushButton, "selectAllProjectsButton"), Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: all(project.selected for project in service.projects(task.task_id)), timeout=2000)
qtbot.waitUntil(lambda: not window._workers, timeout=2000)
assert not quick_run.isEnabled()
window.add_mapping("OLD-1", "NEW-1")
qtbot.waitUntil(lambda: quick_run.isEnabled(), timeout=2000)
mappings = window.findChild(QTableWidget, "mappingTable")
assert mappings is not None and mappings.rowCount() == 1
clear = window.findChild(__import__("PySide6.QtWidgets", fromlist=["QPushButton"]).QPushButton, "clearProjectsButton")
qtbot.waitUntil(clear.isEnabled, timeout=2000)
QTest.mouseClick(clear, Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: not quick_run.isEnabled(), timeout=2000)
def test_changing_directory_hides_and_replaces_previous_scan(qtbot, tmp_path: Path) -> None:
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
first_root = tmp_path / "first"
second_root = tmp_path / "second"
first_root.mkdir()
second_root.mkdir()
(first_root / "old.prj").touch()
(second_root / "new.prj").touch()
choices = iter((first_root, second_root))
service = _service(tmp_path)
task = service.create_task("Trial")
window = TrialTaskCenterWindow(service, directory_picker=lambda: next(choices))
qtbot.addWidget(window)
window.show()
window.open_task(task.task_id)
QTest.mouseClick(window.browse_directory_button, Qt.MouseButton.LeftButton)
QTest.mouseClick(window.scan_projects_button, Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: window.project_table.rowCount() == 1, timeout=5000)
assert service.projects(task.task_id)[0].path.name == "old.prj"
QTest.mouseClick(window.browse_directory_button, Qt.MouseButton.LeftButton)
assert window.project_table.rowCount() == 0
assert window.run_panel.execution_status.text() == "等待扫描"
QTest.mouseClick(window.scan_projects_button, Qt.MouseButton.LeftButton)
qtbot.waitUntil(
lambda: window.project_table.rowCount() == 1
and service.projects(task.task_id)[0].path.name == "new.prj",
timeout=5000,
)
assert [project.path.name for project in service.projects(task.task_id)] == ["new.prj"]
def test_quick_run_button_confirms_and_executes_replacement_without_showing_a_script_path(qtbot, tmp_path: Path) -> None:
"""The primary action must complete replacement instead of handing a script to the operator."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
import subprocess
root = tmp_path / "projects"
root.mkdir()
(root / "one.prj").touch()
service = TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
configure_logging(tmp_path / "storage"),
path_opener=lambda _path: None,
clock=lambda: datetime(2026, 9, 4, tzinfo=timezone.utc),
quick_run_preparer=QuickRunPreparer(
tmp_path / "storage",
process_runner=lambda command, timeout: _write_completed_status(command, tmp_path / "storage", timeout),
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
sheet_discoverer=lambda project: (("Main", "1"),),
),
)
task = service.create_task("Quick")
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
service.add_rule(task.task_id, "OLD-1", "NEW-1")
window = TrialTaskCenterWindow(service, quick_run_confirmer=lambda *_args: True)
qtbot.addWidget(window)
window.show()
window.open_task(task.task_id)
button = window.findChild(QPushButton, "quickRunButton")
assert button is not None and button.isEnabled()
QTest.mouseClick(button, Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: not window._workers, timeout=3000)
assert "成功 1,失败 0,未命中 0" in window.run_panel.operator_band.text()
assert button.text() == "当前队列已完成"
assert not button.isEnabled()
assert "QuickPartReplace.vbs" not in window.run_panel.operator_band.text()
def _write_completed_status(command: tuple[str, ...], data_root: Path, timeout: int):
import subprocess
assert timeout == 150
command_path = data_root / "quick-run" / "command.tsv"
command_lines = command_path.read_text(encoding="utf-8").splitlines()
job_id = command_lines[1].split("\t")[command_lines[0].split("\t").index("job_id")]
(data_root / "quick-run" / "status.tsv").write_text(
"job_id\tstate\tcode\tmessage\n"
f"{job_id}\tawaiting_native_replace\t\tSelected current-sheet matches.\n"
f"{job_id}\tsaved_ok\tbatch_closed\tAutomatic replacement verified and saved.\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0, "", "")
def test_quick_run_confirmation_runs_the_full_replacement_once(qtbot, tmp_path: Path) -> None:
"""One confirmation must cover native replacement, restoration, and verification."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
root = tmp_path / "projects"
root.mkdir()
(root / "one.prj").touch()
service = TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
configure_logging(tmp_path / "storage"),
path_opener=lambda _path: None,
clock=lambda: datetime(2026, 9, 4, tzinfo=timezone.utc),
quick_run_preparer=QuickRunPreparer(
tmp_path / "storage",
process_runner=lambda command, timeout: _write_completed_status(command, tmp_path / "storage", timeout),
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
sheet_discoverer=lambda project: (("Main", "1"),),
),
)
task = service.create_task("Quick")
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
service.add_rule(task.task_id, "OLD-1", "NEW-1")
confirmations: list[tuple[object, ...]] = []
def confirm(*args: object) -> bool:
confirmations.append(args)
return True
window = TrialTaskCenterWindow(service, quick_run_confirmer=confirm)
qtbot.addWidget(window)
window.show()
window.open_task(task.task_id)
button = window.findChild(QPushButton, "quickRunButton")
assert button is not None and button.isEnabled()
QTest.mouseClick(button, Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: not window._workers, timeout=3000)
assert confirmations == [("selection", 1, 1)]
assert window._quick_run_phase == "complete"
assert button.text() == "当前队列已完成"
assert not button.isEnabled()
def test_quick_run_cancellation_does_not_execute_replacement(qtbot, tmp_path: Path) -> None:
"""Cancelling the confirmation must stop before service execution is queued."""
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
root = tmp_path / "projects"
root.mkdir()
(root / "one.prj").touch()
service = _service(tmp_path)
task = service.create_task("Quick")
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
service.add_rule(task.task_id, "OLD-1", "NEW-1")
confirmations: list[tuple[object, ...]] = []
executions: list[str] = []
service.execute_quick_run_queue = lambda task_id, **kwargs: executions.append(task_id)
def cancel(*args: object) -> bool:
confirmations.append(args)
return False
window = TrialTaskCenterWindow(service, quick_run_confirmer=cancel)
qtbot.addWidget(window)
window.show()
window.open_task(task.task_id)
button = window.findChild(QPushButton, "quickRunButton")
assert button is not None and button.isEnabled()
QTest.mouseClick(button, Qt.MouseButton.LeftButton)
assert confirmations == [("selection", 1, 1)]
assert executions == []
assert not window._workers
def test_mapping_enabled_checkbox_updates_the_rule_and_execution_gate(qtbot, tmp_path: Path) -> None:
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
root = tmp_path / "projects"
root.mkdir()
(root / "one.prj").touch()
service = _service(tmp_path)
task = service.create_task("Quick")
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
service.add_rule(task.task_id, "OLD-1", "NEW-1")
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.open_task(task.task_id)
enabled_cell = window.mapping_table.cellWidget(0, 4)
enabled_check = enabled_cell.findChild(QCheckBox) if enabled_cell is not None else None
assert enabled_check is not None and enabled_check.isChecked()
QTest.mouseClick(enabled_check, Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: not service.rules(task.task_id)[0].enabled, timeout=2000)
assert not window.run_panel.quick_run_button.isEnabled()
def test_error_feedback_keeps_specific_reason_and_treats_completion_as_normal(qtbot, tmp_path: Path) -> None:
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service = _service(tmp_path)
task = service.create_task("Quick")
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.open_task(task.task_id)
window._show_error(TaskCenterError("quick_run_execution", "target library row NEW-1 was not found"))
assert "target library row NEW-1 was not found" in window.run_panel.operator_band.text()
assert "不能假定图页未修改" in window.run_panel.operator_band.text()
window._show_error(TaskCenterError("quick_run_uncertain", "worker returned an uncorrelated status"))
assert "无法确认本次替换结果" in window.run_panel.operator_band.text()
assert "超时" not in window.run_panel.operator_band.text()
window._show_error(TaskCenterError("quick_run_complete", "all quick-run items are complete"))
assert "无需重复执行" in window.run_panel.operator_band.text()
assert "操作失败" not in window.run_panel.operator_band.text()
def test_opening_a_task_with_a_completed_quick_run_restores_the_completed_phase(qtbot, tmp_path: Path) -> None:
"""A task switch must preserve the durable completed queue state."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
root = tmp_path / "projects"
root.mkdir()
(root / "one.prj").touch()
service = TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
configure_logging(tmp_path / "storage"),
path_opener=lambda _path: None,
clock=lambda: datetime(2026, 9, 4, tzinfo=timezone.utc),
quick_run_preparer=QuickRunPreparer(
tmp_path / "storage",
process_runner=lambda command, timeout: _write_completed_status(command, tmp_path / "storage", timeout),
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
sheet_discoverer=lambda project: (("Main", "1"),),
),
)
first = service.create_task("First")
project = service.scan_projects(first.task_id, root)[0]
service.set_project_selected(project.project_id, True)
service.add_rule(first.task_id, "OLD-1", "NEW-1")
second = service.create_task("Second")
confirmations: list[tuple[object, ...]] = []
window = TrialTaskCenterWindow(
service,
quick_run_confirmer=lambda *args: confirmations.append(args) or True,
)
qtbot.addWidget(window)
window.show()
window.open_task(first.task_id)
button = window.findChild(QPushButton, "quickRunButton")
assert button is not None and button.isEnabled()
QTest.mouseClick(button, Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: not window._workers, timeout=3000)
window.open_task(second.task_id)
window.open_task(first.task_id)
assert window._quick_run_phase == "complete"
assert button.text() == "当前队列已完成"
assert not button.isEnabled()
assert confirmations == [("selection", 1, 1)]
def test_returning_to_a_task_recovers_completion_after_its_late_worker_result_is_discarded(qtbot, tmp_path: Path) -> None:
"""The status queue, rather than a discarded UI callback, determines task completion."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
import subprocess
root = tmp_path / "projects"
root.mkdir()
(root / "one.prj").touch()
worker_started = Event()
allow_completion = Event()
def delayed_completed_status(command: tuple[str, ...], timeout: int):
assert timeout == 150
worker_started.set()
assert allow_completion.wait(3)
return _write_completed_status(command, tmp_path / "storage", timeout)
service = TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
configure_logging(tmp_path / "storage"),
path_opener=lambda _path: None,
clock=lambda: datetime(2026, 9, 4, tzinfo=timezone.utc),
quick_run_preparer=QuickRunPreparer(
tmp_path / "storage",
process_runner=delayed_completed_status,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
sheet_discoverer=lambda project: (("Main", "1"),),
),
)
first = service.create_task("First")
project = service.scan_projects(first.task_id, root)[0]
service.set_project_selected(project.project_id, True)
service.add_rule(first.task_id, "OLD-1", "NEW-1")
second = service.create_task("Second")
window = TrialTaskCenterWindow(service, quick_run_confirmer=lambda *_args: True)
qtbot.addWidget(window)
window.show()
window.open_task(first.task_id)
button = window.findChild(QPushButton, "quickRunButton")
assert button is not None and button.isEnabled()
QTest.mouseClick(button, Qt.MouseButton.LeftButton)
qtbot.waitUntil(worker_started.is_set, timeout=3000)
window.open_task(second.task_id)
allow_completion.set()
qtbot.waitUntil(lambda: not window._workers, timeout=3000)
window.open_task(first.task_id)
assert window._quick_run_phase == "complete"
assert button.text() == "当前队列已完成"
assert not button.isEnabled()
def test_project_filter_read_only_tables_and_selected_failed_project_action(qtbot, tmp_path: Path) -> None:
"""Editing a cell or acting on the active project would hide a failed selected row."""
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
root = tmp_path / "projects"
root.mkdir()
(root / "failed.prj").touch()
(root / "done.prj").touch()
service, store = _service_and_store(tmp_path)
task = service.create_task("Trial")
projects = service.scan_projects(task.task_id, root)
by_name = {project.path.name: project for project in projects}
failed = by_name["failed.prj"]
done = by_name["done.prj"]
store.set_task_status(task.task_id, TaskStatus.RUNNING)
for status in (ProjectStatus.CAPTURING_BEFORE, ProjectStatus.AWAITING_OPERATOR, ProjectStatus.CAPTURING_AFTER, ProjectStatus.VERIFYING):
store.set_project_status(done.project_id, status)
store.set_project_status(done.project_id, ProjectStatus.COMPLETED)
store.set_project_status(failed.project_id, ProjectStatus.CAPTURING_BEFORE)
store.set_project_status(failed.project_id, ProjectStatus.FAILED)
store.set_task_status(task.task_id, TaskStatus.FAILED)
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.show()
window.open_task(task.task_id)
project_filter = window.findChild(QComboBox, "projectFilter")
assert project_filter is not None
assert window.project_table.editTriggers() == QAbstractItemView.EditTrigger.NoEditTriggers
assert window.mapping_table.editTriggers() == QAbstractItemView.EditTrigger.NoEditTriggers
assert [project_filter.itemText(index) for index in range(project_filter.count())] == ["全部", "待处理", "已完成"]
project_filter.setCurrentText("已完成")
assert window.project_table.rowCount() == 1
project_filter.setCurrentText("待处理")
assert window.project_table.rowCount() == 1
project_filter.setCurrentText("全部")
assert window.project_table.rowCount() == 2
assert window.project_table.item(0, 3).text() in {"失败", "已完成"}
failed_row = next(
row for row in range(window.project_table.rowCount())
if window.project_table.item(row, 1).data(Qt.ItemDataRole.UserRole) == failed.project_id
)
window.project_table.selectRow(failed_row)
skip = window.findChild(QPushButton, "skipProjectButton")
assert skip is not None and skip.isEnabled()
QTest.mouseClick(skip, Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: next(project for project in service.projects(task.task_id) if project.project_id == failed.project_id).status is ProjectStatus.SKIPPED, timeout=3000)
def test_worker_completion_is_ignored_after_opening_a_different_task_without_exposing_probe_controls(qtbot, tmp_path: Path) -> None:
"""A late worker completion must not paint task A's result into task B's workspace."""
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service = _service(tmp_path)
first = service.create_task("First")
second = service.create_task("Second")
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.show()
window.open_task(first.task_id)
called: list[str] = []
gate = Event()
window._run_async(lambda: (gate.wait(), "late")[1], lambda value: called.append(value), expected_task_id=first.task_id)
window.open_task(second.task_id)
QTimer.singleShot(0, gate.set)
qtbot.waitUntil(lambda: not window._workers, timeout=3000)
assert called == []
assert window.findChild(__import__("PySide6.QtWidgets", fromlist=["QLineEdit"]).QLineEdit, "probePath") is None
assert window.findChild(__import__("PySide6.QtWidgets", fromlist=["QPushButton"]).QPushButton, "chooseProbeButton") is None
def test_worker_completion_does_not_touch_widgets_after_window_destruction(qtbot, tmp_path: Path) -> None:
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service = _service(tmp_path)
task = service.create_task("Closing")
window = TrialTaskCenterWindow(service)
window.show()
window.open_task(task.task_id)
entered = Event()
release = Event()
button = window.scan_projects_button
window._run_async(
lambda: (entered.set(), release.wait())[1],
lambda _result: None,
button,
expected_task_id=task.task_id,
)
qtbot.waitUntil(entered.is_set, timeout=3000)
window.deleteLater()
qtbot.waitUntil(lambda: not isValid(window), timeout=3000)
assert not isValid(button)
release.set()
qtbot.waitUntil(lambda: not window._workers, timeout=3000)
def test_refresh_does_not_replace_open_task_with_previous_list_selection(qtbot, tmp_path: Path) -> None:
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service = _service(tmp_path)
first = service.create_task("First")
second = service.create_task("Second")
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.show()
window._select_task_item(first.task_id)
window.open_task(second.task_id)
window._refresh_task_list()
assert window._task_id == second.task_id
assert window.task_list.current_task_id() == second.task_id
@pytest.mark.parametrize("fails", [False, True])
def test_background_queue_completion_refreshes_current_task_without_losing_failure(qtbot, tmp_path: Path, monkeypatch, fails) -> None:
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service, store = _service_and_store(tmp_path)
first = service.create_task("First")
second = service.create_task("Second")
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.show()
window.open_task(first.task_id)
gate = Event()
applied = []
diagnostics = []
show_error = window._show_error
def capture_error(error, **context):
diagnostics.append((error, context))
show_error(error, **context)
monkeypatch.setattr(window, "_show_error", capture_error)
def run_queue():
gate.wait(5)
store.set_task_status(first.task_id, TaskStatus.RUNNING)
if fails:
store.set_task_status(first.task_id, TaskStatus.PAUSED)
raise TaskCenterError("quick_run_execution", "background diagnostic")
store.set_task_status(first.task_id, TaskStatus.COMPLETED)
return "first result"
window._run_async(run_queue, applied.append, window.run_panel.quick_run_button, expected_task_id=first.task_id)
window.open_task(second.task_id)
try:
assert not window.task_list.delete_button.isEnabled()
finally:
gate.set()
qtbot.waitUntil(lambda: not window._workers, timeout=10000)
assert window._task_id == second.task_id
assert window.task_list.delete_button.isEnabled()
assert applied == []
listed = [window.task_list.list.item(index).data(Qt.ItemDataRole.UserRole) for index in range(window.task_list.list.count())]
assert (first.task_id in listed) is fails
if fails:
assert len(diagnostics) == 1
assert diagnostics[0][0].message == "background diagnostic"
assert diagnostics[0][1]["task_id"] == first.task_id
assert "background diagnostic" not in window.run_panel.operator_band.text()
assert window._last_error_task_id == first.task_id
assert window._last_error_project_id is None
def test_newer_worker_keeps_shared_button_locked_until_its_own_completion(qtbot, tmp_path: Path) -> None:
"""An older completion must not re-enable a button owned by a newer dispatch."""
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service = _service(tmp_path)
task = service.create_task("Trial")
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.show()
window.open_task(task.task_id)
first_gate, second_gate = Event(), Event()
applied: list[str] = []
button = window.scan_projects_button
window._run_async(lambda: (first_gate.wait(), "old")[1], applied.append, button, expected_task_id=task.task_id)
window._run_async(lambda: (second_gate.wait(), "new")[1], applied.append, button, expected_task_id=task.task_id)
first_gate.set()
qtbot.waitUntil(lambda: len(window._workers) == 1, timeout=3000)
assert not button.isEnabled()
second_gate.set()
qtbot.waitUntil(lambda: not window._workers, timeout=3000)
assert button.isEnabled()
assert applied == ["new"]
def test_selection_commands_lock_each_other_and_paused_capture_after_uses_selected_project(qtbot, tmp_path: Path, monkeypatch) -> None:
"""Batch selection cannot overlap, and paused verification still targets the selected awaiting project."""
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
root = tmp_path / "projects"
root.mkdir()
(root / "one.prj").touch()
service, store = _service_and_store(tmp_path)
task = service.create_task("Trial")
project = service.scan_projects(task.task_id, root)[0]
entered, release = Event(), Event()
original_select_all = service.select_all_projects
def slow_select_all(task_id: str):
entered.set()
release.wait()
return original_select_all(task_id)
monkeypatch.setattr(service, "select_all_projects", slow_select_all)
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.show()
window.open_task(task.task_id)
window._select_all_projects()
qtbot.waitUntil(entered.is_set, timeout=3000)
assert not window.select_all_projects_button.isEnabled()
assert not window.clear_projects_button.isEnabled()
release.set()
qtbot.waitUntil(lambda: not window._workers, timeout=3000)
store.set_task_status(task.task_id, TaskStatus.RUNNING)
store.set_project_status(project.project_id, ProjectStatus.CAPTURING_BEFORE)
store.set_project_status(project.project_id, ProjectStatus.AWAITING_OPERATOR)
store.set_task_status(task.task_id, TaskStatus.PAUSED)
window.open_task(task.task_id)
window.project_table.selectRow(0)
assert window.run_panel.capture_after_button.isEnabled()
def test_project_checkbox_keeps_scroll_position_after_async_reload(qtbot, tmp_path: Path) -> None:
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service = _service(tmp_path)
task = service.create_task("Scrollable")
root = tmp_path / "projects"
root.mkdir()
paths = tuple(root / f"project-{index:03d}.prj" for index in range(80))
for path in paths:
path.write_text(
'SECTION DesignInfo\nKEY FrontEndSnapshot "DxD"\nENDSECTION\n'
'SECTION iCDB\nKEY iCDBDir ".\\database"\nENDSECTION\n',
encoding="utf-8",
)
service.scan_projects(task.task_id, root)
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.resize(900, 600)
window.show()
window.open_task(task.task_id)
scroll_bar = window.project_table.verticalScrollBar()
qtbot.waitUntil(lambda: scroll_bar.maximum() > 0, timeout=3000)
target = max(1, scroll_bar.maximum() // 2)
scroll_bar.setValue(target)
visible_row = window.project_table.rowAt(window.project_table.viewport().height() // 2)
checkbox = window.project_table.cellWidget(visible_row, 0)
checkbox.setChecked(not checkbox.isChecked())
qtbot.waitUntil(lambda: not window._workers, timeout=3000)
assert scroll_bar.value() == target
def test_empty_project_scan_explains_that_non_schematic_projects_are_ignored(qtbot, tmp_path: Path) -> None:
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service = _service(tmp_path)
task = service.create_task("Schematic only")
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.open_task(task.task_id)
window._project_scan_finished(())
assert "未发现可用的 DxDesigner 原理图工程" in window.run_panel.operator_band.text()
assert "PCB 工程和其他 .prj 文件已忽略" in window.run_panel.operator_band.text()
def test_failure_diagnostics_keep_a_stable_id_without_evidence_button(qtbot, tmp_path: Path) -> None:
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
store = TaskStore(tmp_path / "task-center.db")
service = TaskCenterService(store, configure_logging(tmp_path / "storage"))
root = tmp_path / "projects"
root.mkdir()
(root / "failed.prj").touch()
task = service.create_task("Trial")
project = service.scan_projects(task.task_id, root)[0]
store.set_task_status(task.task_id, TaskStatus.RUNNING)
store.set_project_status(project.project_id, ProjectStatus.CAPTURING_BEFORE)
store.set_project_status(project.project_id, ProjectStatus.FAILED)
store.set_task_status(task.task_id, TaskStatus.FAILED)
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.open_task(task.task_id)
window.project_table.selectRow(0)
window._show_error(RuntimeError("boom"))
assert "错误编号:DXT-" in window.run_panel.operator_band.text()
assert not hasattr(window.run_panel, "open_evidence_button")
def test_workers_on_different_buttons_complete_without_cancelling_each_other(qtbot, tmp_path: Path) -> None:
"""A newer operation in another button domain must not discard the first result."""
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service = _service(tmp_path)
task = service.create_task("Trial")
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.open_task(task.task_id)
first_gate, second_gate = Event(), Event()
applied: list[str] = []
window._run_async(lambda: (first_gate.wait(), "scan")[1], applied.append, window.scan_projects_button, expected_task_id=task.task_id)
window._run_async(lambda: (second_gate.wait(), "browse")[1], applied.append, window.browse_directory_button, expected_task_id=task.task_id)
first_gate.set()
qtbot.waitUntil(lambda: "scan" in applied, timeout=3000)
assert window.scan_projects_button.isEnabled()
assert not window.browse_directory_button.isEnabled()
second_gate.set()
qtbot.waitUntil(lambda: not window._workers, timeout=3000)
assert applied == ["scan", "browse"]
assert window.browse_directory_button.isEnabled()
def test_window_refuses_to_close_while_regular_worker_is_running(qtbot, tmp_path: Path) -> None:
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service = _service(tmp_path)
task = service.create_task("Trial")
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.show()
window.open_task(task.task_id)
entered = Event()
release = Event()
window._run_async(lambda: (entered.set(), release.wait())[1], lambda _result: None)
qtbot.waitUntil(entered.is_set, timeout=3000)
assert window.close() is False
assert window.isVisible()
assert "后台操作尚未结束" in window.run_panel.operator_band.text()
release.set()
qtbot.waitUntil(lambda: not window._workers, timeout=3000)
assert window.close() is True
def test_selection_domain_and_unrelated_worker_complete_independently(qtbot, tmp_path: Path) -> None:
"""Selection ownership must not be stranded by an unrelated worker generation."""
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow
service = _service(tmp_path)
task = service.create_task("Trial")
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.open_task(task.task_id)
selection_gate, scan_gate = Event(), Event()
applied: list[str] = []
window._run_async(lambda: (selection_gate.wait(), "selection")[1], applied.append, expected_task_id=task.task_id, selection_operation=True)
window._run_async(lambda: (scan_gate.wait(), "scan")[1], applied.append, window.scan_projects_button, expected_task_id=task.task_id)
selection_gate.set()
qtbot.waitUntil(lambda: "selection" in applied, timeout=3000)
assert window.select_all_projects_button.isEnabled()
assert not window.scan_projects_button.isEnabled()
scan_gate.set()
qtbot.waitUntil(lambda: not window._workers, timeout=3000)
assert applied == ["selection", "scan"]
assert window.scan_projects_button.isEnabled()
+115
View File
@@ -0,0 +1,115 @@
from pathlib import Path
from threading import Event
from PySide6.QtCore import QPoint, Qt
from PySide6.QtTest import QTest
from PySide6.QtWidgets import QCheckBox, QToolButton
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.ui.main_window import TrialTaskCenterWindow, _MappingDialog
def make_window(qtbot, tmp_path):
service = TaskCenterService(TaskStore(tmp_path / 'tasks.db'), configure_logging(tmp_path / 'data'))
first = service.create_task('First')
second = service.create_task('Second')
window = TrialTaskCenterWindow(service)
qtbot.addWidget(window)
window.show()
window.open_task(first.task_id)
return window, service, first, second
def test_value_checkbox_is_task_scoped_and_defaults_off(qtbot, tmp_path):
window, service, first, second = make_window(qtbot, tmp_path)
checkbox = window.findChild(QCheckBox, 'copyPartNumberToValue')
assert checkbox is not None
assert checkbox.text() == '替换后将 Part Label 写入 Value'
assert not checkbox.isChecked()
assert checkbox.isEnabled()
QTest.mouseClick(checkbox, Qt.MouseButton.LeftButton, pos=QPoint(8, checkbox.height() // 2))
qtbot.waitUntil(lambda: service.get_task(first.task_id).copy_part_number_to_value)
qtbot.waitUntil(lambda: not window._workers)
window.open_task(second.task_id)
assert not checkbox.isChecked()
window.open_task(first.task_id)
assert checkbox.isChecked()
def test_mapping_dialog_exposes_custom_value_and_nc_controls(qtbot):
dialog = _MappingDialog(None, "OLD", "NEW", True, True, "22uF", False)
qtbot.addWidget(dialog)
assert dialog.custom_value_check.isChecked()
assert dialog.custom_value_edit.isEnabled()
assert dialog.custom_value_edit.text() == "22uF"
assert not dialog.sync_nc_check.isChecked()
assert dialog.values() == ("OLD", "NEW", True, True, "22uF", False)
def test_small_window_has_useful_drag_range_and_collapsible_log(qtbot, tmp_path):
window, _, _, _ = make_window(qtbot, tmp_path)
window.resize(900, 600)
qtbot.wait(20)
splitter = window.detail_splitter
lower, upper = splitter.getRange(1)
assert upper - lower >= 90
splitter.setSizes((230, 140, 190))
before = splitter.sizes()[0]
handle = splitter.handle(1)
center = handle.rect().center()
QTest.mousePress(handle, Qt.MouseButton.LeftButton, pos=center)
QTest.mouseMove(handle, center + QPoint(0, 60), delay=20)
QTest.mouseRelease(handle, Qt.MouseButton.LeftButton, pos=center + QPoint(0, 60))
assert splitter.sizes()[0] - before >= 40
toggle = window.findChild(QToolButton, 'toggleLogButton')
assert toggle is not None and not window.run_panel.log_view.isVisible()
QTest.mouseClick(toggle, Qt.MouseButton.LeftButton)
assert window.run_panel.log_view.isVisible()
def test_splitter_remains_draggable_while_background_work_is_running(qtbot, tmp_path):
window, service, _, _ = make_window(qtbot, tmp_path)
started = Event()
release = Event()
def work():
started.set()
release.wait(3)
return None
window._run_async(work, lambda _result: None, window.run_panel.quick_run_button)
qtbot.waitUntil(started.is_set, timeout=1000)
splitter = window.detail_splitter
splitter.setSizes((230, 140, 190))
before = splitter.sizes()[0]
handle = splitter.handle(1)
center = handle.rect().center()
QTest.mousePress(handle, Qt.MouseButton.LeftButton, pos=center)
QTest.mouseMove(handle, center + QPoint(0, 60), delay=20)
QTest.mouseRelease(handle, Qt.MouseButton.LeftButton, pos=center + QPoint(0, 60))
assert splitter.sizes()[0] - before >= 40
release.set()
qtbot.waitUntil(lambda: not window._workers, timeout=3000)
window.close()
service._store.close()
def test_layout_and_column_width_survive_window_recreation(qtbot, tmp_path):
window, service, _, _ = make_window(qtbot, tmp_path)
window.workspace_splitter.setSizes((320, 740))
window.detail_splitter.setSizes((380, 190, 160))
window.project_table.horizontalHeader().resizeSection(2, 240)
qtbot.wait(20)
expected = window.detail_splitter.sizes()
window.close()
recreated = TrialTaskCenterWindow(service)
qtbot.addWidget(recreated)
recreated.show()
qtbot.wait(20)
assert abs(recreated.detail_splitter.sizes()[0] - expected[0]) <= 3
assert recreated.project_table.columnWidth(2) == 240
assert Path(service.layout_settings_path).is_relative_to(tmp_path)
assert recreated.findChild(QToolButton, 'resetLayoutButton') is not None
+136
View File
@@ -0,0 +1,136 @@
Option Explicit
Const ForReading = 1
Const TristateFalse = 0
Dim Fso
Dim RepoRoot
Dim HelperPath
Dim HelperSource
Dim TestRoot
Dim DataPath
Dim UnicodeText
Dim EscapedText
Dim ResolvedPath
Dim Shell
Dim JunctionPath
Dim JunctionTarget
Dim JunctionCommand
Dim JunctionExitCode
Dim JunctionRejected
Set Fso = CreateObject("Scripting.FileSystemObject")
RepoRoot = Fso.GetParentFolderName(Fso.GetParentFolderName( _
Fso.GetParentFolderName(WScript.ScriptFullName)))
HelperPath = Fso.BuildPath(RepoRoot, _
"integration\dxdesigner795\BridgeCommon.vbs")
If Not Fso.FileExists(HelperPath) Then
Fail "missing helper: " & HelperPath
End If
HelperSource = Fso.OpenTextFile(HelperPath, ForReading, False, _
TristateFalse).ReadAll
ExecuteGlobal HelperSource
TestRoot = Fso.BuildPath(Fso.GetSpecialFolder(2), Fso.GetTempName)
Fso.CreateFolder TestRoot
DataPath = Fso.BuildPath(TestRoot, "roundtrip.json")
UnicodeText = "prefix-" & ChrW(&H6D4B) & ChrW(&H8BD5) & _
ChrW(&H8DEF) & ChrW(&H5F84) & "-suffix"
DxWriteUtf8Atomic DataPath, "old"
DxWriteUtf8Atomic DataPath, UnicodeText
AssertEqual UnicodeText, DxReadUtf8(DataPath), _
"UTF-8 text must survive an atomic overwrite"
AssertEqual 1, Fso.GetFolder(TestRoot).Files.Count, _
"atomic write must not leave a sibling temporary file"
UnicodeText = ChrW(&H6D4B) & ChrW(&H8BD5) & _
ChrW(-10179) & ChrW(-8576)
AssertEqual UnicodeText, DxJsonEscape(UnicodeText), _
"JSON escaping must preserve complete UTF-16 units"
EscapedText = DxJsonEscape(Chr(34) & "\" & Chr(8) & Chr(9) & _
Chr(10) & Chr(12) & Chr(13) & Chr(1))
AssertEqual "\" & Chr(34) & "\\" & "\b\t\n\f\r\u0001", _
EscapedText, "JSON escaping must cover quotes, slashes, and controls"
AssertEqual "1234.5", DxInvariantNumber(1234.5), _
"positive decimal formatting must use a period"
AssertEqual "-0.25", DxInvariantNumber(-0.25), _
"negative decimal formatting must use a period"
AssertEqual "0", DxInvariantNumber(0), _
"integer formatting must not add a decimal separator"
ResolvedPath = DxResolveRunPath(TestRoot, "nested\run.json")
AssertEqual Fso.GetAbsolutePathName(Fso.BuildPath(TestRoot, _
"nested\run.json")), ResolvedPath, _
"run-relative paths must resolve beneath the supplied root"
AssertResolveFails TestRoot, "..\escape.json", _
"parent traversal must be rejected"
AssertResolveFails TestRoot, Fso.GetAbsolutePathName(DataPath), _
"absolute paths must be rejected"
AssertResolveFails TestRoot, "C:\escape.json", _
"drive-qualified paths must be rejected"
AssertResolveFails TestRoot, "\\server\share\escape.json", _
"UNC paths must be rejected"
AssertResolveFails TestRoot, "", _
"empty run-relative paths must be rejected"
JunctionTarget = TestRoot & "-outside"
JunctionPath = Fso.BuildPath(TestRoot, "junction")
Fso.CreateFolder JunctionTarget
Set Shell = CreateObject("WScript.Shell")
JunctionCommand = DxCommandQuote( _
Shell.ExpandEnvironmentStrings("%ComSpec%")) & _
" /d /s /c " & Chr(34) & "mklink /J " & _
DxCommandQuote(JunctionPath) & " " & DxCommandQuote(JunctionTarget) & _
" >nul" & Chr(34)
JunctionExitCode = Shell.Run(JunctionCommand, 0, True)
If JunctionExitCode <> 0 Then
Fso.DeleteFolder JunctionTarget, True
Fail "junction setup failed"
End If
JunctionRejected = ResolveFails(TestRoot, "junction\escape.json")
JunctionCommand = DxCommandQuote( _
Shell.ExpandEnvironmentStrings("%ComSpec%")) & _
" /d /s /c " & Chr(34) & "rmdir " & _
DxCommandQuote(JunctionPath) & Chr(34)
JunctionExitCode = Shell.Run(JunctionCommand, 0, True)
If JunctionExitCode <> 0 Then Fail "junction cleanup failed"
Fso.DeleteFolder JunctionTarget, True
If Not JunctionRejected Then
Fail "junction path components must be rejected"
End If
Fso.DeleteFolder TestRoot, True
WScript.Echo "PASS: BridgeCommon cscript behavior"
Sub AssertEqual(ByVal Expected, ByVal Actual, ByVal Message)
If CStr(Expected) <> CStr(Actual) Then
Fail Message & ": expected [" & CStr(Expected) & _
"], got [" & CStr(Actual) & "]"
End If
End Sub
Sub AssertResolveFails(ByVal RootPath, ByVal RelativePath, ByVal Message)
If Not ResolveFails(RootPath, RelativePath) Then
Fail Message
End If
End Sub
Function ResolveFails(ByVal RootPath, ByVal RelativePath)
Dim Ignored
Dim ErrorNumber
On Error Resume Next
Ignored = DxResolveRunPath(RootPath, RelativePath)
ErrorNumber = Err.Number
Err.Clear
On Error GoTo 0
ResolveFails = (ErrorNumber <> 0)
End Function
Sub Fail(ByVal Message)
WScript.Echo "FAIL: " & Message
WScript.Quit 1
End Sub