feat: add complete yiyezhqiu productivity suite

This commit is contained in:
阿白叔 committed 2026-10-10 17:10:32 +08:00
commit e422ca8b2a
155 files changed
+18959

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
from pathlib import Path
from dx_productivity.bridge import launcher
def test_compute_assembly_refdes_end_to_end(tmp_path: Path) -> None:
request = tmp_path / "request.txt"
output = tmp_path / "plan.txt"
request.write_text(
"T|0|1|1|1|C1|0|C1\n"
"T|1|2|1|1|NOTE|0|C1\n"
"T|2|1|1|1|R100|90|R100\n"
"C|C1|10|20|0.5|0.3\n"
"C|R100|5|6|0.4|0.9\n",
encoding="ascii",
)
exit_code = launcher.main(
[
"compute",
"assembly-refdes",
"--request",
str(request),
"--output",
str(output),
]
)
assert exit_code == 0
plan = output.read_text(encoding="ascii")
assert "MOVE|0|10.0000|20.0000|0.00|0.3000|Arial\n" in plan
assert "DELETE|1\n" in plan
assert "MOVE|2|5.0000|6.0000|90.00|0.4000|Arial\n" in plan
+105
View File
@@ -0,0 +1,105 @@
import json
import os
from pathlib import Path
import subprocess
import sys
def _environment() -> dict[str, str]:
environment = os.environ.copy()
environment["QT_QPA_PLATFORM"] = "offscreen"
return environment
def test_module_launcher_dispatches_probe_without_starting_qt(tmp_path: Path) -> None:
output = tmp_path / "兼容性 结果.json"
result = subprocess.run(
[
sys.executable,
"-m",
"dx_productivity",
"probe",
"--output",
str(output),
"--route",
"named",
"--payload-json",
'{"portable":true}',
],
capture_output=True,
text=True,
encoding="utf-8",
env=_environment(),
timeout=15,
check=False,
)
assert result.returncode == 0, result.stderr
assert json.loads(output.read_text(encoding="utf-8")) == {
"format_version": 1,
"route": "named",
"portable": True,
}
def test_module_launcher_runs_ui_smoke_test_and_exits(
fixture_path: Path,
) -> None:
result = subprocess.run(
[
sys.executable,
"-m",
"dx_productivity",
"ui",
"--request",
str(fixture_path / "request-basic.json"),
"--smoke-test-ms",
"50",
],
capture_output=True,
text=True,
encoding="utf-8",
env=_environment(),
timeout=15,
check=False,
)
assert result.returncode == 0, result.stderr
def test_module_launcher_dispatches_update_without_starting_qt(tmp_path: Path) -> None:
import sys
import zipfile
current = tmp_path / "portable"
current.mkdir()
(current / "DxDesignerTools.exe").write_bytes(b"old")
staged = tmp_path / "update.zip"
with zipfile.ZipFile(staged, "w") as archive:
archive.writestr("DxDesignerTools.exe", b"new")
plan = tmp_path / "install-plan.json"
plan.write_text(
json.dumps(
{
"current_root": str(current),
"staged_zip": str(staged),
"backup_root": str(tmp_path / "backups"),
"restart_command": [sys.executable, "-c", "raise SystemExit(0)"],
}
),
encoding="utf-8",
)
result = subprocess.run(
[sys.executable, "-m", "dx_productivity", "update", "--plan", str(plan)],
capture_output=True,
text=True,
encoding="utf-8",
env=_environment(),
timeout=15,
check=False,
)
assert result.returncode == 0, result.stderr
assert (current / "DxDesignerTools.exe").read_bytes() == b"new"
+314
View File
@@ -0,0 +1,314 @@
import json
import hashlib
from dataclasses import replace
from decimal import Decimal
from pathlib import Path
import pytest
from dx_productivity.bridge import protocol
from dx_productivity.bridge.protocol import (
ProtocolError,
load_apply_status,
load_request,
write_schedule,
)
from dx_productivity.domain import models
from dx_productivity.domain.models import ApplyStep, RunPaths
def test_load_request_parses_decimal_coordinates(fixture_path: Path) -> None:
snapshot = load_request(fixture_path / "request-basic.json")
assert snapshot.format_version == 2
assert snapshot.components[0].bridge_id == "c0001"
assert snapshot.components[0].x == Decimal("125.400")
assert snapshot.components[0].selected is True
def test_load_request_rejects_unsupported_version(
tmp_path: Path, fixture_path: Path
) -> None:
data = json.loads((fixture_path / "request-basic.json").read_text("utf-8"))
data["format_version"] = 3
request = tmp_path / "request.json"
request.write_text(json.dumps(data), encoding="utf-8")
with pytest.raises(ProtocolError, match="format_version"):
load_request(request)
def test_load_request_rejects_duplicate_bridge_ids(
tmp_path: Path, fixture_path: Path
) -> None:
data = json.loads((fixture_path / "request-basic.json").read_text("utf-8"))
data["components"][1]["bridge_id"] = "c0001"
request = tmp_path / "request.json"
request.write_text(json.dumps(data), encoding="utf-8")
with pytest.raises(ProtocolError, match="duplicate bridge_id"):
load_request(request)
def test_load_request_rejects_integer_in_boolean_field(
tmp_path: Path, fixture_path: Path
) -> None:
data = json.loads((fixture_path / "request-basic.json").read_text("utf-8"))
data["components"][0]["selected"] = 1
request = tmp_path / "request.json"
request.write_text(json.dumps(data), encoding="utf-8")
with pytest.raises(ProtocolError, match="selected"):
load_request(request)
def test_load_request_requires_stable_or_path_identity(
tmp_path: Path, fixture_path: Path
) -> None:
data = json.loads((fixture_path / "request-basic.json").read_text("utf-8"))
data["components"][0]["stable_uid"] = None
data["components"][0]["full_path"] = ""
request = tmp_path / "request.json"
request.write_text(json.dumps(data), encoding="utf-8")
with pytest.raises(ProtocolError, match="identity"):
load_request(request)
def test_load_request_preserves_empty_group_key_for_domain_validation(
tmp_path: Path, fixture_path: Path
) -> None:
data = json.loads((fixture_path / "request-basic.json").read_text("utf-8"))
data["components"][0]["stable_uid"] = None
data["components"][0]["logical_group_key"] = ""
request = tmp_path / "request.json"
request.write_text(json.dumps(data), encoding="utf-8")
snapshot = load_request(request)
assert snapshot.components[0].logical_group_key == ""
def test_write_schedule_is_contiguous_utf8_tsv(tmp_path: Path) -> None:
output = tmp_path / "result.tsv"
write_schedule(output, (ApplyStep(1, "c0001", "R?", "R1", "R1"),))
assert output.read_text(encoding="utf-8") == (
"1\trefdes\tc0001\t\tR?\tR1\tR1\n"
)
def test_write_schedule_rejects_sequence_gap(tmp_path: Path) -> None:
with pytest.raises(ProtocolError, match="contiguous"):
write_schedule(
tmp_path / "result.tsv",
(ApplyStep(2, "c0001", "R?", "R1", "R1"),),
)
def test_write_schedule_rejects_more_than_two_steps_per_component(
tmp_path: Path,
) -> None:
first = ApplyStep(1, "c0001", "R1", "R?", "R2")
schedule = (
first,
replace(first, sequence=2, expected_refdes="R?", new_refdes="R3"),
replace(first, sequence=3, expected_refdes="R3", new_refdes="R2"),
)
with pytest.raises(ProtocolError, match="at most twice"):
write_schedule(tmp_path / "result.tsv", schedule)
def test_write_schedule_rejects_tsv_control_characters(tmp_path: Path) -> None:
with pytest.raises(ProtocolError, match="tabs or line breaks"):
write_schedule(
tmp_path / "result.tsv",
(ApplyStep(1, "c0001\tbad", "R?", "R1", "R1"),),
)
def test_load_apply_status_parses_optional_failure_fields(tmp_path: Path) -> None:
status_path = tmp_path / "apply-status.json"
status_path.write_text(
json.dumps(
{
"format_version": 2,
"run_id": "run-basic",
"state": "rolled-back",
"changed_count": 0,
"backup_path": "C:\\Backups\\run-basic.json",
"failing_sequence": 2,
"error": "assignment failed",
"rollback_state": "verified",
}
),
encoding="utf-8",
)
status = load_apply_status(status_path)
assert status.state == "rolled-back"
assert status.failing_sequence == 2
assert status.backup_path == Path("C:\\Backups\\run-basic.json")
def test_apply_request_round_trip_preserves_unicode_absolute_backup(
tmp_path: Path,
) -> None:
backup = (tmp_path / "备份.json").resolve()
request = models.ApplyRequest(
protocol.FORMAT_VERSION,
"run-basic",
"snapshot-basic",
backup,
"a" * 64,
)
output = tmp_path / "apply-request.json"
protocol.write_apply_request(output, request)
assert protocol.load_apply_request(output) == request
assert "备份.json" in output.read_text(encoding="utf-8")
def test_apply_request_rejects_relative_backup_path(tmp_path: Path) -> None:
output = tmp_path / "apply-request.json"
output.write_text(
json.dumps(
{
"format_version": 2,
"run_id": "run-basic",
"snapshot_id": "snapshot-basic",
"backup_path": "relative.json",
"schedule_sha256": "a" * 64,
}
),
encoding="utf-8",
)
with pytest.raises(ProtocolError, match="absolute"):
protocol.load_apply_request(output)
def test_schedule_digest_matches_exact_written_utf8_bytes(tmp_path: Path) -> None:
schedule = (ApplyStep(1, "c0001", "R?", "R1", "R1"),)
output = tmp_path / "result.tsv"
protocol.write_schedule(output, schedule)
assert protocol.schedule_sha256(schedule) == hashlib.sha256(
b"1\trefdes\tc0001\t\tR?\tR1\tR1\n"
).hexdigest()
assert hashlib.sha256(output.read_bytes()).hexdigest() == (
protocol.schedule_sha256(schedule)
)
def test_run_paths_derives_apply_request_from_run_root(tmp_path: Path) -> None:
paths = RunPaths(
"run-basic",
tmp_path,
tmp_path / "request.json",
tmp_path / "result.tsv",
tmp_path / "locate.tsv",
tmp_path / "apply-status.json",
)
assert paths.apply_request == tmp_path / "apply-request.json"
def test_load_request_parses_attributes_and_nets(
tmp_path: Path, fixture_path: Path
) -> None:
data = json.loads((fixture_path / "request-basic.json").read_text("utf-8"))
data["components"][0]["attributes"] = [
{"name": "Value", "value": "10K", "visible": True},
{"name": "Part Name", "value": "RES", "visible": False},
]
data["nets"] = [{"name": "N1", "pages": [1, 2]}]
data["selected_nets"] = ["N1"]
request = tmp_path / "request.json"
request.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
snapshot = load_request(request)
assert snapshot.components[0].attributes == (
models.AttributeRecord(name="Value", value="10K", visible=True),
models.AttributeRecord(name="Part Name", value="RES", visible=False),
)
assert snapshot.nets[0].name == "N1"
assert snapshot.nets[0].pages == (1, 2)
assert snapshot.selected_nets == ("N1",)
def test_load_request_rejects_duplicate_net_names(
tmp_path: Path, fixture_path: Path
) -> None:
data = json.loads((fixture_path / "request-basic.json").read_text("utf-8"))
data["nets"] = [
{"name": "N1", "pages": [1]},
{"name": "n1", "pages": [2]},
]
request = tmp_path / "request.json"
request.write_text(json.dumps(data), encoding="utf-8")
with pytest.raises(ProtocolError, match="duplicate net"):
load_request(request)
def test_load_request_tolerates_missing_nets_and_attributes(
fixture_path: Path,
) -> None:
snapshot = load_request(fixture_path / "request-basic.json")
assert snapshot.nets == ()
assert snapshot.selected_nets == ()
assert all(c.attributes == () for c in snapshot.components)
def test_schedule_supports_property_operations(tmp_path: Path) -> None:
output = tmp_path / "result.tsv"
write_schedule(
output,
(
ApplyStep(
1, "c0001", "10K", "47K", "47K",
op=models.OpType.PROPERTY_VALUE, property_name="Value",
),
ApplyStep(
2, "c0001", "1", "0", "0",
op=models.OpType.PROPERTY_VISIBILITY, property_name="Part Name",
),
),
)
text = output.read_text(encoding="utf-8")
assert "1\tproperty\tc0001\tValue\t10K\t47K\t47K\n" in text
assert "2\tvisibility\tc0001\tPart Name\t1\t0\t0\n" in text
assert protocol.parse_schedule_text(text)[1].property_name == "Part Name"
def test_parse_schedule_text_rejects_legacy_five_columns(tmp_path: Path) -> None:
legacy = tmp_path / "legacy.tsv"
legacy.write_text("1\tc0001\tR?\tR1\tR1\n", encoding="utf-8")
with pytest.raises(ProtocolError, match="7 columns"):
protocol.parse_schedule_text(legacy.read_text(encoding="utf-8"))
def test_schedule_rejects_property_row_without_property_name(
tmp_path: Path,
) -> None:
with pytest.raises(ProtocolError, match="property name"):
write_schedule(
tmp_path / "result.tsv",
(
ApplyStep(
1, "c0001", "a", "b", "b",
op=models.OpType.PROPERTY_VALUE,
),
),
)
+106
View File
@@ -0,0 +1,106 @@
import json
from pathlib import Path
from dx_productivity.bridge.run_store import RunStore
from dx_productivity.domain.models import ApplyStatus
def test_create_run_returns_isolated_mailbox_paths(tmp_path: Path) -> None:
paths = RunStore(tmp_path).create_run()
assert paths.root.is_dir()
assert paths.root.parent == tmp_path / "runs"
assert paths.request == paths.root / "request.json"
assert paths.result == paths.root / "result.tsv"
assert paths.locate == paths.root / "locate.tsv"
assert paths.apply_status == paths.root / "apply-status.json"
def test_backup_contains_complete_old_and_new_mapping(
tmp_path, snapshot, plan
):
store = RunStore(tmp_path)
path = store.write_backup(snapshot, plan)
data = json.loads(path.read_text(encoding="utf-8"))
assert data["format_version"] == 2
assert data["design_id"] == snapshot.design_id
assert data["changes"][0] == {
"bridge_id": "c0001",
"stable_uid": "uid-c0001",
"full_path": "ROOT\\C0001",
"op": "refdes",
"property": "",
"old_value": "R?",
"new_value": "R1",
}
assert not list(path.parent.glob("*.tmp"))
def test_history_ignores_incomplete_temporary_files(tmp_path):
store = RunStore(tmp_path)
store.history_root.mkdir(parents=True)
(store.history_root / "orphan.tmp").write_text("partial", encoding="utf-8")
assert store.list_history("design-a") == ()
def test_record_status_creates_filterable_history(tmp_path, snapshot, plan):
store = RunStore(tmp_path)
backup = store.write_backup(snapshot, plan)
status = ApplyStatus(
format_version=1,
run_id=snapshot.run_id,
state="applied",
changed_count=1,
backup_path=backup,
)
store.record_status(status)
entries = store.list_history(snapshot.design_id)
assert len(entries) == 1
assert entries[0].state == "applied"
assert entries[0].backup_path == backup
assert store.list_history("other-design") == ()
def test_restore_request_contains_identity_preflight_and_old_value(
tmp_path, snapshot, plan
):
store = RunStore(tmp_path)
backup = store.write_backup(snapshot, plan)
status = ApplyStatus(1, snapshot.run_id, "applied", 1, backup)
store.record_status(status)
entry = store.list_history(snapshot.design_id)[0]
request = store.build_restore_settings(entry)
assert request.design_id == snapshot.design_id
assert request.source_backup == backup
assert len(request.changes) == 1
assert request.changes[0].bridge_id == "c0001"
assert request.changes[0].stable_uid == "uid-c0001"
assert request.changes[0].expected_value == "R1"
assert request.changes[0].restore_value == "R?"
assert request.changes[0].op.value == "refdes"
def test_backup_filename_does_not_contain_design_path_separators(
tmp_path, snapshot, plan
):
store = RunStore(tmp_path)
snapshot = type(snapshot)(
snapshot.format_version,
snapshot.run_id,
snapshot.snapshot_id,
"board:power/logic",
snapshot.design_path,
snapshot.components,
)
backup = store.write_backup(snapshot, plan)
assert "board_power_logic" in backup.name
assert ":" not in backup.name
+31
View File
@@ -0,0 +1,31 @@
from pathlib import Path
def test_generate_startup_assets_lists_all_feature_actions() -> None:
from dx_productivity.bridge.startup_assets import generate_startup_assets
assets = generate_startup_assets(Path("C:/portable/DxDesignerTools"))
assert set(assets.action_scripts) == {
"refdes",
"property-change",
"property-visibility",
"inspection",
"bom",
"compatibility",
"guide",
}
assert assets.action_scripts["refdes"] == "DxToolsOpenRefDes"
assert (
assets.action_scripts["property-change"]
== "DxToolsOpenPropertyChange"
)
assert assets.action_scripts["bom"] == "DxToolsOpenBom"
assert assets.action_scripts["compatibility"] == "DxToolsOpenCompatibility"
assert assets.action_scripts["guide"] == "DxToolsOpenGuide"
assert all(
"D:\\NET_CHECK" not in value for value in assets.action_scripts.values()
)
assert not any(
value.startswith("run ") for value in assets.action_scripts.values()
)
+159
View File
@@ -0,0 +1,159 @@
from dataclasses import replace
from decimal import Decimal
from pathlib import Path
import shutil
from typing import Any, Callable
import pytest
from dx_productivity.domain.models import (
AnnotationSettings,
ComponentRecord,
DesignSnapshot,
LogicalComponent,
PlanRow,
)
from dx_productivity.domain.planner import build_annotation_plan
@pytest.fixture
def fixture_path() -> Path:
return Path(__file__).parent / "fixtures"
@pytest.fixture
def component_factory() -> Callable[..., ComponentRecord]:
def factory(**overrides: Any) -> ComponentRecord:
defaults: dict[str, Any] = {
"bridge_id": "c0001",
"stable_uid": "uid-c0001",
"full_path": "ROOT\\C0001",
"logical_group_key": "uid-c0001",
"sheet_name": "1",
"sheet_number": 1,
"x": Decimal("10"),
"y": Decimal("10"),
"y_axis_up": True,
"refdes": "R?",
"symbol_refdes_default": "R?",
"selected": True,
"current_sheet": True,
"part_number": "PART",
"value": "10K",
"locked": False,
}
defaults.update(overrides)
return ComponentRecord(**defaults)
return factory
@pytest.fixture
def group_factory(
component_factory: Callable[..., ComponentRecord],
) -> Callable[..., LogicalComponent]:
def factory(key: str, **overrides: Any) -> LogicalComponent:
prefix = overrides.pop("prefix", "R")
sheet = overrides.pop("sheet", 1)
x = Decimal(str(overrides.pop("x", "10")))
y = Decimal(str(overrides.pop("y", "10")))
member = component_factory(
bridge_id=key,
stable_uid=key,
logical_group_key=key,
sheet_number=sheet,
x=x,
y=y,
**overrides,
)
normalized_y = y if member.y_axis_up else -y
return LogicalComponent(
key=key,
members=(member,),
prefix=prefix,
sheet_number=sheet,
x=x,
normalized_y=normalized_y,
)
return factory
@pytest.fixture
def settings() -> Callable[..., AnnotationSettings]:
def factory(**overrides: Any) -> AnnotationSettings:
return replace(AnnotationSettings(), **overrides)
return factory
@pytest.fixture
def snapshot_factory(
component_factory: Callable[..., ComponentRecord],
) -> Callable[..., DesignSnapshot]:
def factory(
target_ref: str = "R?", outside_ref: str | None = None, **overrides: Any
) -> DesignSnapshot:
components = [component_factory(refdes=target_ref)]
if outside_ref is not None:
components.append(
component_factory(
bridge_id="outside",
stable_uid="uid-outside",
full_path="ROOT\\OUTSIDE",
logical_group_key="uid-outside",
refdes=outside_ref,
selected=False,
x=Decimal("20"),
)
)
snapshot = DesignSnapshot(
format_version=2,
run_id="run-test",
snapshot_id="snapshot-test",
design_id="design-test",
design_path="C:\\Projects\\test.prj",
components=tuple(components),
)
return replace(snapshot, **overrides)
return factory
@pytest.fixture
def plan_row_factory() -> Callable[..., PlanRow]:
def factory(
bridge_id: str, old_refdes: str, new_refdes: str, **overrides: Any
) -> PlanRow:
prefix = "".join(char for char in new_refdes if char.isalpha()) or None
row = PlanRow(
logical_key=bridge_id,
bridge_ids=(bridge_id,),
full_path=f"ROOT\\{bridge_id}",
prefix=prefix,
old_refdes=old_refdes,
new_refdes=new_refdes,
status="pending",
changed=old_refdes.casefold() != new_refdes.casefold(),
)
return replace(row, **overrides)
return factory
@pytest.fixture
def powershell() -> str:
executable = shutil.which("pwsh") or shutil.which("powershell")
if executable is None:
pytest.skip("PowerShell is not available")
return executable
@pytest.fixture
def snapshot(snapshot_factory: Callable[..., DesignSnapshot]) -> DesignSnapshot:
return snapshot_factory()
@pytest.fixture
def plan(snapshot: DesignSnapshot) -> Any:
return build_annotation_plan(snapshot, AnnotationSettings())
+44
View File
@@ -0,0 +1,44 @@
from pathlib import Path
import zipfile
from xml.etree import ElementTree
GUIDE = Path("docs/user/DxDesigner_7.9.5_自动位号工具使用说明_v0.5.docx")
WORD_NS = {"w": "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
def _document_text() -> str:
with zipfile.ZipFile(GUIDE) as archive:
document = ElementTree.fromstring(archive.read("word/document.xml"))
return "\n".join(
text.text or "" for text in document.findall(".//w:t", WORD_NS)
)
def test_user_guide_documents_portable_offline_workflow() -> None:
text = _document_text()
for required in (
"解压整个目录",
"MenuAdd.vbs",
"无需安装 Python",
"%LOCALAPPDATA%\\DxProductivity",
"兼容性检测",
"自动回滚",
"重新导入",
):
assert required in text
def test_user_guide_does_not_instruct_legacy_installation() -> None:
text = _document_text()
for forbidden in (
"安装 64 位 Python",
"pip install",
"DXTOOLS_HOME",
"D:\\NET_CHECK",
"Install.ps1",
"Uninstall.ps1",
):
assert forbidden not in text
+102
View File
@@ -0,0 +1,102 @@
from dataclasses import replace
import pytest
from dx_productivity.bridge.protocol import load_request
from dx_productivity.domain.identity import (
group_logical_components,
is_fill_only_eligible,
is_reannotation_eligible,
resolve_prefix,
select_scope,
)
from dx_productivity.domain.models import ProcessingMode, Scope
@pytest.mark.parametrize(
("refdes", "symbol_default", "prefix", "resolved"),
[
("R?", None, "R", True),
("tp??", None, "TP", True),
("", "C?", "C", True),
("", None, None, False),
("R12", "R?", "R", True),
],
)
def test_resolve_prefix(
refdes, symbol_default, prefix, resolved, component_factory
):
result = resolve_prefix(
component_factory(
refdes=refdes, symbol_refdes_default=symbol_default
)
)
assert (result.prefix, result.resolved) == (prefix, resolved)
def test_selected_scope_does_not_fall_back_when_empty(component_factory):
records = (component_factory(selected=False),)
assert select_scope(records, Scope.SELECTED) == ()
def test_current_and_full_scope_are_explicit(component_factory):
current = component_factory(bridge_id="current", current_sheet=True)
other = component_factory(
bridge_id="other", stable_uid="other", current_sheet=False
)
records = (current, other)
assert select_scope(records, Scope.CURRENT_SHEET) == (current,)
assert select_scope(records, Scope.FULL_DESIGN) == records
def test_multiunit_symbols_form_one_logical_component(fixture_path):
records = load_request(fixture_path / "request-multiunit.json").components
groups = group_logical_components(records)
assert len(groups) == 1
assert {record.bridge_id for record in groups[0].members} == {"u1a", "u1b"}
assert groups[0].key == "uid-u1"
assert groups[0].identity_ambiguous is False
def test_missing_fallback_key_is_blocked_without_merging(component_factory):
first = component_factory(
bridge_id="a", stable_uid=None, logical_group_key="", full_path="ROOT\\A"
)
second = component_factory(
bridge_id="b", stable_uid=None, logical_group_key="", full_path="ROOT\\B"
)
groups = group_logical_components((first, second))
assert [group.key for group in groups] == ["ambiguous:a", "ambiguous:b"]
assert all(group.identity_ambiguous for group in groups)
@pytest.mark.parametrize(
("refdes", "locked", "expected"),
[("", False, True), ("R?", False, True), ("R12", False, False), ("R?", True, False)],
)
def test_fill_only_eligibility(refdes, locked, expected, component_factory):
record = component_factory(refdes=refdes, locked=locked)
assert is_fill_only_eligible(record) is expected
def test_reannotation_requires_unlocked_resolved_prefix(component_factory):
eligible = component_factory(refdes="R12")
locked = replace(eligible, locked=True)
unresolved = replace(eligible, refdes="", symbol_refdes_default=None)
assert is_reannotation_eligible(eligible) is True
assert is_reannotation_eligible(locked) is False
assert is_reannotation_eligible(unresolved) is False
def test_processing_mode_enum_values_remain_bridge_stable():
assert ProcessingMode.FILL_ONLY.value == "fill-only"
assert ProcessingMode.REANNOTATE.value == "reannotate"
+90
View File
@@ -0,0 +1,90 @@
import pytest
from dx_productivity.domain.models import NumberingMode
from dx_productivity.domain.numbering import allocate_numbers
def test_continuous_allocation_skips_occupied(group_factory, settings):
groups = (
group_factory("a", prefix="R"),
group_factory("b", prefix="R"),
)
result = allocate_numbers(groups, {"R1", "r3"}, settings(start_number=1))
assert result == {"a": "R2", "b": "R4"}
def test_continuous_sequences_are_independent_per_prefix(group_factory, settings):
groups = (
group_factory("r1", prefix="R"),
group_factory("c1", prefix="C"),
group_factory("r2", prefix="R"),
group_factory("c2", prefix="C"),
)
result = allocate_numbers(groups, set(), settings(start_number=1))
assert result == {"r1": "R1", "c1": "C1", "r2": "R2", "c2": "C2"}
def test_page_mode_starts_sheet_three_at_301(group_factory, settings):
groups = (group_factory("a", prefix="C", sheet=3),)
result = allocate_numbers(
groups,
set(),
settings(numbering_mode=NumberingMode.PAGE),
)
assert result == {"a": "C301"}
def test_page_mode_keeps_sheet_and_prefix_sequences_independent(
group_factory, settings
):
groups = (
group_factory("r2a", prefix="R", sheet=2),
group_factory("c2", prefix="C", sheet=2),
group_factory("r2b", prefix="R", sheet=2),
group_factory("r3", prefix="R", sheet=3),
)
result = allocate_numbers(
groups,
{"R201"},
settings(numbering_mode=NumberingMode.PAGE),
)
assert result == {
"r2a": "R202",
"c2": "C201",
"r2b": "R203",
"r3": "R301",
}
def test_page_mode_rejects_missing_numeric_sheet(group_factory, settings):
with pytest.raises(ValueError, match="numeric sheet"):
allocate_numbers(
(group_factory("a", sheet=None),),
set(),
settings(numbering_mode=NumberingMode.PAGE),
)
@pytest.mark.parametrize(
"overrides",
[
{"start_number": 0},
{"numbering_mode": NumberingMode.PAGE, "page_step": 0},
{"numbering_mode": NumberingMode.PAGE, "page_start": -1},
],
)
def test_invalid_numeric_ranges_are_rejected(overrides, group_factory, settings):
with pytest.raises(ValueError, match="number"):
allocate_numbers(
(group_factory("a"),),
set(),
settings(**overrides),
)
+78
View File
@@ -0,0 +1,78 @@
import random
from decimal import Decimal
import pytest
from dx_productivity.domain.models import SortOrder
from dx_productivity.domain.ordering import order_components
def test_default_order_is_sheet_top_to_bottom_then_left_to_right(
group_factory, settings
):
groups = (
group_factory("b", sheet=1, x="30", y="100"),
group_factory("a", sheet=1, x="10", y="100"),
group_factory("c", sheet=1, x="5", y="80"),
group_factory("d", sheet=2, x="1", y="500"),
)
ordered = order_components(groups, settings(row_tolerance=Decimal("5")))
assert [group.key for group in ordered] == ["a", "b", "c", "d"]
def test_row_clustering_uses_fixed_anchor_not_chain_drift(group_factory, settings):
groups = (
group_factory("a", x="30", y="100"),
group_factory("b", x="10", y="96"),
group_factory("c", x="20", y="92"),
)
ordered = order_components(groups, settings(row_tolerance=Decimal("5")))
assert [group.key for group in ordered] == ["b", "a", "c"]
@pytest.mark.parametrize(
("sort_order", "expected"),
[
(SortOrder.TOP_DOWN_LEFT_RIGHT, ["tl", "tr", "bl", "br"]),
(SortOrder.TOP_DOWN_RIGHT_LEFT, ["tr", "tl", "br", "bl"]),
(SortOrder.LEFT_RIGHT_TOP_DOWN, ["tl", "bl", "tr", "br"]),
(SortOrder.RIGHT_LEFT_TOP_DOWN, ["tr", "br", "tl", "bl"]),
],
)
def test_all_scan_directions(sort_order, expected, group_factory, settings):
groups = (
group_factory("br", x="100", y="0"),
group_factory("tl", x="0", y="100"),
group_factory("bl", x="0", y="0"),
group_factory("tr", x="100", y="100"),
)
ordered = order_components(
groups,
settings(sort_order=sort_order, row_tolerance=Decimal("5")),
)
assert [group.key for group in ordered] == expected
def test_order_is_deterministic_for_equal_coordinates(group_factory, settings):
original = [group_factory(key, x="10", y="10") for key in "dbca"]
expected = ["a", "b", "c", "d"]
randomizer = random.Random(795)
for _ in range(50):
randomizer.shuffle(original)
ordered = order_components(tuple(original), settings())
assert [group.key for group in ordered] == expected
def test_negative_tolerance_is_rejected(group_factory, settings):
with pytest.raises(ValueError, match="row_tolerance"):
order_components(
(group_factory("a"),),
settings(row_tolerance=Decimal("-1")),
)
+272
View File
@@ -0,0 +1,272 @@
from dataclasses import replace
from decimal import Decimal
from dx_productivity.bridge.protocol import load_request
from dx_productivity.domain.models import NumberingMode, Severity
from dx_productivity.domain.planner import build_annotation_plan
def test_plan_skips_collision_with_component_outside_scope(
snapshot_factory, settings
):
snapshot = snapshot_factory(target_ref="R?", outside_ref="R1")
plan = build_annotation_plan(snapshot, settings(start_number=1))
assert plan.rows[0].new_refdes == "R2"
assert not [
issue for issue in plan.issues if issue.severity is Severity.BLOCKING
]
def test_plan_blocks_unresolved_prefix(
component_factory, snapshot_factory, settings
):
unresolved = component_factory(refdes="", symbol_refdes_default=None)
snapshot = snapshot_factory(components=(unresolved,))
plan = build_annotation_plan(snapshot, settings())
assert any(issue.code == "missing-prefix" for issue in plan.issues)
assert plan.can_apply is False
def test_plan_accepts_explicit_prefix_override(
component_factory, snapshot_factory, settings
):
unresolved = component_factory(refdes="", symbol_refdes_default=None)
snapshot = snapshot_factory(components=(unresolved,))
plan = build_annotation_plan(
snapshot,
settings(prefix_overrides=((unresolved.logical_group_key, "TP"),)),
)
assert plan.rows[0].new_refdes == "TP1"
assert plan.can_apply is True
def test_empty_selected_scope_never_falls_back(snapshot_factory, settings):
snapshot = snapshot_factory()
snapshot = replace(
snapshot,
components=tuple(
replace(component, selected=False) for component in snapshot.components
),
)
plan = build_annotation_plan(snapshot, settings())
assert plan.rows == ()
assert any(issue.code == "empty-scope" for issue in plan.issues)
assert plan.can_apply is False
def test_multiunit_component_consumes_one_number(
fixture_path, settings
):
snapshot = load_request(fixture_path / "request-multiunit.json")
plan = build_annotation_plan(snapshot, settings())
assert len(plan.rows) == 1
assert plan.rows[0].bridge_ids == ("u1a", "u1b")
assert plan.rows[0].new_refdes == "U1"
def test_page_mode_uses_explicit_sheet_mapping(
component_factory, snapshot_factory, settings
):
component = component_factory(
sheet_name="Power", sheet_number=None, refdes="C?", x=Decimal("1")
)
snapshot = snapshot_factory(components=(component,))
plan = build_annotation_plan(
snapshot,
settings(
numbering_mode=NumberingMode.PAGE,
sheet_number_overrides=(("Power", 4),),
),
)
assert plan.rows[0].new_refdes == "C401"
assert plan.can_apply is True
def test_out_of_scope_multiunit_member_blocks_rename(
component_factory, snapshot_factory, settings
):
"""Regression: renaming the in-scope member while a claimed member of the
same logical component stays outside the scope silently duplicated U1."""
from dx_productivity.domain.models import Severity
in_scope = component_factory(
bridge_id="u1a",
stable_uid="uid-u1",
full_path="ROOT\\U1\\A",
logical_group_key="uid-u1",
refdes="U?",
sheet_number=1,
current_sheet=True,
)
out_scope = component_factory(
bridge_id="u1b",
stable_uid="uid-u1",
full_path="ROOT\\U1\\B",
logical_group_key="uid-u1",
refdes="U1",
symbol_refdes_default="U1",
sheet_number=2,
current_sheet=False,
selected=False,
)
snapshot = snapshot_factory(components=(in_scope, out_scope))
plan = build_annotation_plan(snapshot, settings())
assert not plan.can_apply
assert any(issue.code == "out-of-scope-member" for issue in plan.issues)
def test_out_of_scope_member_value_is_occupied(
component_factory, snapshot_factory, settings
):
out_scope = component_factory(
bridge_id="outside",
stable_uid="uid-u1",
full_path="ROOT\\U1",
logical_group_key="uid-u1",
refdes="R1",
selected=False,
x=Decimal("20"),
)
snapshot = snapshot_factory(
components=(
component_factory(refdes="R?"),
out_scope,
)
)
plan = build_annotation_plan(snapshot, settings(start_number=1))
assert plan.rows[0].new_refdes == "R2"
def test_out_of_scope_placeholder_member_allows_rename(
component_factory, snapshot_factory, settings
):
sibling = component_factory(
bridge_id="u1b",
stable_uid="uid-u1",
full_path="ROOT\\U1\\B",
logical_group_key="uid-u1",
refdes="U?",
sheet_number=2,
current_sheet=False,
selected=False,
)
snapshot = snapshot_factory(
components=(
component_factory(
bridge_id="u1a",
stable_uid="uid-u1",
full_path="ROOT\\U1\\A",
logical_group_key="uid-u1",
refdes="U?",
),
sibling,
)
)
plan = build_annotation_plan(snapshot, settings())
assert plan.can_apply
assert plan.rows[0].new_refdes == "U1"
def test_negative_row_tolerance_becomes_blocking_issue(
snapshot_factory, settings
):
from decimal import Decimal as D
from dx_productivity.domain.models import Severity
plan = build_annotation_plan(
snapshot_factory(), settings(row_tolerance=D("-1"))
)
assert not plan.can_apply
assert any(
issue.code == "invalid-settings"
and issue.severity is Severity.BLOCKING
for issue in plan.issues
)
def test_page_mode_overflow_warns(component_factory, snapshot_factory, settings):
from dx_productivity.domain.models import Severity
components = tuple(
component_factory(
bridge_id=f"r{i}",
stable_uid=f"uid-r{i}",
full_path=f"ROOT\\R{i}",
logical_group_key=f"uid-r{i}",
x=Decimal(10 + i),
)
for i in range(1, 4)
)
snapshot = snapshot_factory(components=components)
plan = build_annotation_plan(
snapshot,
settings(numbering_mode=NumberingMode.PAGE, page_step=2, start_number=1),
)
assert any(
issue.code == "page-overflow"
and issue.severity is Severity.WARNING
for issue in plan.issues
)
def test_page_mode_never_produces_zero_refdes(
component_factory, snapshot_factory, settings
):
component = component_factory(
bridge_id="r0",
stable_uid="uid-r0",
full_path="ROOT\\R0",
logical_group_key="uid-r0",
sheet_number=0,
)
snapshot = snapshot_factory(components=(component,))
plan = build_annotation_plan(
snapshot,
settings(numbering_mode=NumberingMode.PAGE, page_start=0),
)
assert not plan.can_apply
assert any(issue.code == "invalid-numbering" for issue in plan.issues)
def test_sheet_override_on_numbered_sheet_is_reported(
component_factory, snapshot_factory, settings
):
from dx_productivity.domain.models import Severity
component = component_factory(sheet_name="Power", refdes="C?")
snapshot = snapshot_factory(components=(component,))
plan = build_annotation_plan(
snapshot,
settings(sheet_number_overrides=(("Power", 9),)),
)
assert any(
issue.code == "sheet-override-ignored"
and issue.severity is Severity.INFORMATIONAL
for issue in plan.issues
)
+171
View File
@@ -0,0 +1,171 @@
import importlib
from pathlib import Path
from dx_productivity.domain.models import RestoreItem, RestoreRequest, Severity
def _request(restore_refdes: str) -> RestoreRequest:
return RestoreRequest(
design_id="design-test",
source_backup=Path("C:/Backups/run.json"),
changes=(
RestoreItem(
bridge_id="old-bridge-id",
stable_uid="uid-c0001",
full_path="ROOT\\C0001",
expected_value="R1",
restore_value=restore_refdes,
),
),
)
def test_restore_plan_matches_current_component_by_stable_identity(
snapshot_factory,
) -> None:
restore = importlib.import_module("dx_productivity.domain.restore")
snapshot = snapshot_factory(target_ref="R1")
plan = restore.build_restore_plan(snapshot, _request("R?"))
assert plan.can_apply
assert plan.rows[0].bridge_ids == ("c0001",)
assert plan.rows[0].old_refdes == "R1"
assert plan.rows[0].new_refdes == "R?"
assert plan.schedule[0].new_refdes == "R?"
def test_restore_plan_blocks_component_changed_after_backup(
snapshot_factory,
) -> None:
restore = importlib.import_module("dx_productivity.domain.restore")
snapshot = snapshot_factory(target_ref="R9")
plan = restore.build_restore_plan(snapshot, _request("R?"))
assert not plan.can_apply
assert any(
issue.code == "restore-stale"
and issue.severity is Severity.BLOCKING
for issue in plan.issues
)
def test_restore_plan_blocks_collision_outside_restore_set(
snapshot_factory,
) -> None:
restore = importlib.import_module("dx_productivity.domain.restore")
snapshot = snapshot_factory(target_ref="R1", outside_ref="R2")
plan = restore.build_restore_plan(snapshot, _request("R2"))
assert not plan.can_apply
assert any(issue.code == "restore-collision" for issue in plan.issues)
def test_restore_plan_can_restore_original_blank_reference(
snapshot_factory,
) -> None:
restore = importlib.import_module("dx_productivity.domain.restore")
snapshot = snapshot_factory(target_ref="R1")
plan = restore.build_restore_plan(snapshot, _request(""))
assert plan.can_apply
assert plan.schedule[0].new_refdes == ""
def test_restore_matches_multiunit_members_by_bridge_id(
snapshot_factory, component_factory
) -> None:
"""Regression: multi-unit backups share one stable_uid; matching by uid
alone made every item ambiguous and blocked the whole restore."""
restore = importlib.import_module("dx_productivity.domain.restore")
snapshot = snapshot_factory(
components=(
component_factory(
bridge_id="u1a",
stable_uid="uid-u1",
full_path="ROOT\\U1\\A",
logical_group_key="uid-u1",
refdes="U1",
symbol_refdes_default="U1",
sheet_number=1,
),
component_factory(
bridge_id="u1b",
stable_uid="uid-u1",
full_path="ROOT\\U1\\B",
logical_group_key="uid-u1",
refdes="U1",
symbol_refdes_default="U1",
sheet_number=2,
),
)
)
request = RestoreRequest(
design_id="design-test",
source_backup=Path("C:/Backups/run.json"),
changes=(
RestoreItem(
bridge_id="u1a",
stable_uid="uid-u1",
full_path="ROOT\\U1\\A",
expected_value="U1",
restore_value="U?",
),
RestoreItem(
bridge_id="u1b",
stable_uid="uid-u1",
full_path="ROOT\\U1\\B",
expected_value="U1",
restore_value="U?",
),
),
)
plan = restore.build_restore_plan(snapshot, request)
assert plan.can_apply
assert len(plan.rows) == 1
assert plan.rows[0].bridge_ids == ("u1a", "u1b")
assert plan.schedule[0].new_refdes == "U?"
def test_restore_blocks_locked_component(
snapshot_factory, component_factory
) -> None:
restore = importlib.import_module("dx_productivity.domain.restore")
snapshot = snapshot_factory(
components=(component_factory(refdes="R1", locked=True),)
)
plan = restore.build_restore_plan(snapshot, _request("R?"))
assert not plan.can_apply
assert any(issue.code == "restore-locked" for issue in plan.issues)
def test_restore_treats_already_restored_component_as_satisfied(
snapshot_factory,
) -> None:
restore = importlib.import_module("dx_productivity.domain.restore")
snapshot = snapshot_factory(target_ref="R?")
plan = restore.build_restore_plan(snapshot, _request("R?"))
assert not [
issue for issue in plan.issues if issue.severity is Severity.BLOCKING
]
assert plan.rows[0].changed is False
assert plan.schedule == ()
def test_restore_detects_suffixed_target_collision(snapshot_factory) -> None:
restore = importlib.import_module("dx_productivity.domain.restore")
snapshot = snapshot_factory(target_ref="R1", outside_ref="R1A")
plan = restore.build_restore_plan(snapshot, _request("R1A"))
assert not plan.can_apply
assert any(issue.code == "restore-collision" for issue in plan.issues)
+90
View File
@@ -0,0 +1,90 @@
from dx_productivity.domain.schedule import build_apply_schedule
def _triples(steps):
return [
(step.bridge_id, step.expected_refdes, step.new_refdes) for step in steps
]
def test_schedule_breaks_refdes_swap_with_prefix_placeholder(plan_row_factory):
rows = (
plan_row_factory("a", "R1", "R2"),
plan_row_factory("b", "R2", "R1"),
)
steps = build_apply_schedule(rows)
assert _triples(steps) == [
("a", "R1", "R?"),
("b", "R2", "R1"),
("a", "R?", "R2"),
]
assert [step.sequence for step in steps] == [1, 2, 3]
assert [step.final_refdes for step in steps] == ["R2", "R1", "R2"]
def test_schedule_orders_acyclic_dependency_from_tail(plan_row_factory):
rows = (
plan_row_factory("a", "R1", "R2"),
plan_row_factory("b", "R2", "R3"),
)
steps = build_apply_schedule(rows)
assert _triples(steps) == [("b", "R2", "R3"), ("a", "R1", "R2")]
def test_schedule_breaks_three_component_cycle_deterministically(plan_row_factory):
rows = (
plan_row_factory("c", "R3", "R1"),
plan_row_factory("b", "R2", "R3"),
plan_row_factory("a", "R1", "R2"),
)
steps = build_apply_schedule(rows)
assert _triples(steps) == [
("a", "R1", "R?"),
("c", "R3", "R1"),
("b", "R2", "R3"),
("a", "R?", "R2"),
]
def test_schedule_ignores_preserved_rows(plan_row_factory):
row = plan_row_factory("a", "R1", "R1", changed=False, status="preserved")
assert build_apply_schedule((row,)) == ()
def test_schedule_allows_restore_to_blank_reference(plan_row_factory):
row = plan_row_factory("a", "R1", "")
steps = build_apply_schedule((row,))
assert _triples(steps) == [("a", "R1", "")]
def test_schedule_rejects_duplicate_targets_across_rows(plan_row_factory):
rows = (
plan_row_factory("a", "R1", "R2"),
plan_row_factory("b", "R?", "R2"),
)
import pytest
with pytest.raises(ValueError, match="duplicate target"):
build_apply_schedule(rows)
def test_schedule_rejects_duplicate_suffixed_targets(plan_row_factory):
rows = (
plan_row_factory("a", "R1", "R2A"),
plan_row_factory("b", "R?", "R2A"),
)
import pytest
with pytest.raises(ValueError, match="duplicate target"):
build_apply_schedule(rows)
+81
View File
@@ -0,0 +1,81 @@
from dx_productivity.domain.models import Severity
from dx_productivity.domain.validation import validate_plan
def test_validation_blocks_duplicate_source_formal_refdes(
component_factory, snapshot_factory, plan_row_factory
):
first = component_factory(
bridge_id="a",
stable_uid="a",
logical_group_key="a",
refdes="R1",
)
second = component_factory(
bridge_id="b",
stable_uid="b",
logical_group_key="b",
refdes="r1",
)
snapshot = snapshot_factory(components=(first, second))
issues = validate_plan(snapshot, ())
assert any(
issue.code == "duplicate-source-refdes"
and issue.severity is Severity.BLOCKING
for issue in issues
)
def test_validation_blocks_duplicate_proposed_output(
snapshot_factory, plan_row_factory
):
rows = (
plan_row_factory("a", "R?", "R1", logical_key="a"),
plan_row_factory("b", "R?", "r1", logical_key="b"),
)
issues = validate_plan(snapshot_factory(), rows)
assert any(issue.code == "duplicate-proposed-refdes" for issue in issues)
def test_validation_blocks_output_occupied_outside_target(
component_factory, snapshot_factory, plan_row_factory
):
target = component_factory(refdes="R?")
outside = component_factory(
bridge_id="outside",
stable_uid="outside",
logical_group_key="outside",
refdes="R1",
selected=False,
)
snapshot = snapshot_factory(components=(target, outside))
rows = (plan_row_factory("c0001", "R?", "R1"),)
issues = validate_plan(snapshot, rows)
assert any(issue.code == "occupied-output" for issue in issues)
def test_validation_allows_same_refdes_on_members_of_one_logical_component(
component_factory, snapshot_factory
):
first = component_factory(
bridge_id="u1a",
stable_uid="u1",
logical_group_key="u1",
refdes="U1",
)
second = component_factory(
bridge_id="u1b",
stable_uid="u1",
logical_group_key="u1",
refdes="U1",
)
issues = validate_plan(snapshot_factory(components=(first, second)), ())
assert not [issue for issue in issues if issue.code == "duplicate-source-refdes"]
+124
View File
@@ -0,0 +1,124 @@
from dx_productivity.features.assembly_refdes.planner import (
ComponentFootprint,
DeletePlan,
FabricationText,
MovePlan,
plan_assembly_refdes,
render_plan,
)
def _text(index, **overrides):
defaults = dict(
index=index,
text_type=1,
side=1,
is_assembly=True,
text_string="C1",
orientation=0.0,
component_name="C1",
)
defaults.update(overrides)
return FabricationText(**defaults)
def test_refdes_moves_to_component_origin():
texts = [_text(0)]
footprints = {"C1": ComponentFootprint("C1", 10.0, 20.0, 0.5, 0.3)}
plans, processed = plan_assembly_refdes(texts, footprints)
assert processed == 1
plan = plans[0]
assert isinstance(plan, MovePlan)
assert (plan.x, plan.y) == (10.0, 20.0)
assert plan.rotation == 0
assert plan.height == 0.3 # within [0.1, 0.8] keeps the outline height
def test_small_and_large_heights_clamp_to_max():
texts = [_text(0), _text(1, text_string="R10000", component_name="R1")]
footprints = {
"C1": ComponentFootprint("C1", 0.0, 0.0, 0.5, 0.05),
"R1": ComponentFootprint("R1", 0.0, 0.0, 0.5, 2.0),
}
plans, _ = plan_assembly_refdes(texts, footprints)
assert all(isinstance(p, MovePlan) and p.height == 0.8 for p in plans)
def test_non_refdes_fab_text_is_deleted():
texts = [_text(0, text_type=0)]
footprints = {"C1": ComponentFootprint("C1", 0, 0, 1, 1)}
plans, processed = plan_assembly_refdes(texts, footprints)
assert processed == 0
assert isinstance(plans[0], DeletePlan)
def test_board_level_text_without_component_is_untouched():
texts = [_text(0, component_name="")]
plans, _ = plan_assembly_refdes(texts, {})
assert plans == ()
def test_bottom_side_vertical_text_gets_270():
texts = [_text(0, orientation=270, side=0)]
footprints = {"C1": ComponentFootprint("C1", 1, 2, 0.4, 0.5)}
plans, _ = plan_assembly_refdes(texts, footprints)
assert plans[0].rotation == 270
assert plans[0].height == 0.4 # x half span
def test_diagonal_uses_the_legacy_factor():
texts = [_text(0, orientation=45)]
footprints = {"C1": ComponentFootprint("C1", 0, 0, 1.0, 1.0)}
plans, _ = plan_assembly_refdes(texts, footprints)
# legacy: full span * 0.54 / 2 = half span * 0.54
assert plans[0].height == 0.54
def test_steep_angles_flip_orientation():
texts = [
_text(0, orientation=135, component_name="C1"),
_text(1, orientation=15, component_name="C2"),
]
footprints = {
"C1": ComponentFootprint("C1", 0, 0, 0.5, 0.5),
"C2": ComponentFootprint("C2", 0, 0, 0.5, 0.5),
}
plans, _ = plan_assembly_refdes(texts, footprints)
assert plans[0].rotation == 315 # 135 branch
assert plans[0].height == 0.27 # half span * 0.54
assert plans[1].rotation == 15 # else branch keeps ori
assert plans[1].height == 0.4 # generic branches force 0.4
def test_long_refdes_gets_narrow_font_and_fixed_height():
texts = [_text(0, text_string="R10000")]
footprints = {"C1": ComponentFootprint("C1", 0, 0, 0.5, 0.5)}
plans, _ = plan_assembly_refdes(texts, footprints)
assert plans[0].font == "Arial Narrow"
def test_render_plan_lines():
texts = [_text(0), _text(1, text_type=0)]
footprints = {"C1": ComponentFootprint("C1", 10.0, 20.0, 0.5, 0.3)}
plans, _ = plan_assembly_refdes(texts, footprints)
rendered = render_plan(plans)
assert rendered.startswith("MOVE|0|10.0000|20.0000|0.00|0.3000|Arial\n")
assert "DELETE|1\n" in rendered
+140
View File
@@ -0,0 +1,140 @@
from decimal import Decimal
from dx_productivity.domain.models import AttributeRecord
from dx_productivity.features.bom import BOMSettings, build_bom
def _component(component_factory, bridge_id, refdes, value, pn="P1", **kw):
return component_factory(
bridge_id=bridge_id,
stable_uid=f"uid-{bridge_id}",
full_path=f"ROOT\{bridge_id}",
logical_group_key=f"uid-{bridge_id}",
refdes=refdes,
symbol_refdes_default=refdes,
attributes=(
AttributeRecord(name="VALUE", value=value, visible=True),
AttributeRecord(name="Part Number", value=pn, visible=True),
),
**kw,
)
def test_same_page_same_part_merges(component_factory, snapshot_factory):
components = tuple(
_component(component_factory, f"c{i}", f"R{i}", "10K")
for i in range(1, 4)
)
snapshot = snapshot_factory(components=components)
result = build_bom(snapshot, BOMSettings())
assert len(result.rows) == 1
assert result.rows[0].qty == 3
assert result.rows[0].refdes == "R1,R2,R3"
assert result.rows[0].part_number == "P1"
def test_nc_filter_excludes_rows(component_factory, snapshot_factory):
nc = _component(component_factory, "c1", "R1", "NC CAP")
normal = _component(
component_factory, "c2", "R2", "10K", pn="P2"
)
snapshot = snapshot_factory(components=(nc, normal))
filtered = build_bom(snapshot, BOMSettings(exclude_nc=True))
unfiltered = build_bom(snapshot, BOMSettings(exclude_nc=False))
assert filtered.excluded_count == 1
assert len(filtered.rows) == 1
assert len(unfiltered.rows) == 2
def test_mark_rows_are_removed(component_factory, snapshot_factory):
marker = _component(
component_factory, "c1", "TP1", "TEST MARK", pn="MARK-1"
)
normal = _component(component_factory, "c2", "R2", "10K", pn="P2")
snapshot = snapshot_factory(components=(marker, normal))
result = build_bom(snapshot, BOMSettings())
assert [row.part_number for row in result.rows] == ["P2"]
def test_sections_are_grouped_by_page(component_factory, snapshot_factory):
from decimal import Decimal as D
p1 = _component(
component_factory, "c1", "R1", "10K", sheet_number=1, y=D(10)
)
p2 = _component(
component_factory, "c2", "R2", "10K", sheet_number=2, y=D(10)
)
snapshot = snapshot_factory(components=(p1, p2))
result = build_bom(snapshot, BOMSettings())
assert [page for page, _rows in result.sections] == [1, 2]
def test_duplicate_refdes_flagged(component_factory, snapshot_factory):
a = _component(component_factory, "c1", "R1", "10K", pn="P1")
b = _component(component_factory, "c2", "R1", "22K", pn="P2")
snapshot = snapshot_factory(components=(a, b))
result = build_bom(snapshot, BOMSettings())
flagged = [row for row in result.rows if row.duplicate_refdes]
assert len(flagged) == 2
def test_selected_scope_only_exports_selection(
component_factory, snapshot_factory
):
selected = _component(component_factory, "c1", "R1", "10K")
other = _component(
component_factory, "c2", "R2", "10K", selected=False
)
snapshot = snapshot_factory(components=(selected, other))
result = build_bom(snapshot, BOMSettings(scope="selected"))
assert len(result.rows) == 1
assert result.rows[0].refdes == "R1"
def test_part_label_description_source(component_factory, snapshot_factory):
component = component_factory(
bridge_id="c1",
attributes=(
AttributeRecord(name="VALUE", value="10K", visible=True),
AttributeRecord(name="Part Label", value="10K 1% RES", visible=True),
AttributeRecord(name="Part Number", value="410000010A20", visible=True),
),
)
snapshot = snapshot_factory(components=(component,))
result = build_bom(
snapshot, BOMSettings(description_source="part-label")
)
assert result.rows[0].description == "10K 1% RES"
def test_pvcheck_mismatch_flagged(component_factory, snapshot_factory):
component = component_factory(
bridge_id="c1",
attributes=(
AttributeRecord(name="VALUE", value="4.7R", visible=True),
AttributeRecord(
name="Part Number", value="410000010A20", visible=True
),
),
)
snapshot = snapshot_factory(components=(component,))
result = build_bom(snapshot, BOMSettings())
assert result.rows[0].part_number_mismatch is True
assert "1.02R" in result.rows[0].mismatch_reason
+147
View File
@@ -0,0 +1,147 @@
"""Table-driven PVCheck tests using the legacy EFM's own comment examples."""
import pytest
from dx_productivity.features.bom import pv_check
# (part_number, description, expected_description_contains)
RESISTOR_CASES = [
# VBScript comments: '10A2=1.02R 12A0=1.2R 10A0=1R
("410000010A20", "1.02R 1% RES", False),
("410000010A20", "1.0R 1% RES", True),
("410000012A00", "1.2R", False),
("410000010A00", "1R", False),
# '10D2=0.00102R 12D0=0.0012R 10D0=0.001R
("410000010D20", "0.00102R", False),
("410000012D00", "0.0012R", False),
("410000010D00", "0.001R", False),
# '1002=10.2R 1000=10R 0000=0R
("410000010020", "10.2R", False),
("410000010000", "10R", False),
# '1012=102R
("410000010120", "102R", False),
# '1022=1.02K 1220=1.2K 1020=1K
("410000010220", "1.02K", False),
("410000012200", "1.2K", False),
("410000010200", "1K", False),
# '1032=10.2K 1030=10K
("410000010320", "10.2K", False),
("410000010300", "10K", False),
# '1042=102K
("410000010420", "102K", False),
# '1052=1.02M 1250=1.2M 1050=1M
("410000010520", "1.02M", False),
("410000012500", "1.2M", False),
("410000010500", "1M", False),
# '1062=10.2M 1060=10M
("410000010620", "10.2M", False),
("410000010600", "10M", False),
]
CAPACITOR_CASES = [
# '12B=0.12P 10B=0.1P
("430000012B00", "0.12P", False),
("430000010B00", "0.1P", False),
# '12A=1.2P 10A=1P
("430000012A00", "1.2P", False),
("430000010A00", "1P", False),
# '100=10P 101=100P
("430000010000", "10P", False),
("430000010100", "100P", False),
# '122=1.2N 102=1N 103=10N 104=100N
("430000012200", "1.2N", False),
("430000010200", "1N", False),
("430000010300", "10N", False),
("430000010400", "100N", False),
# '475=4.7U 105=1U 106=10U 107=100U 108=1000U
("430000047500", "4.7U", False),
("430000010500", "1U", False),
("430000010600", "10U", False),
("430000010700", "100U", False),
("430000010800", "1000U", False),
]
COIL_CASES = [
# '47D=4.7N 10D=1N 12C=12N 12B=120N
("480000047D00", "4.7N", False),
("480000010D00", "1N", False),
("480000012C00", "12N", False),
("480000012B00", "120N", False),
# '47A=4.7U 10A=1U 100=10U 101=100U
("480000047A00", "4.7U", False),
("480000010A00", "1U", False),
("480000010000", "10U", False),
("480000010100", "100U", False),
# '122=1.2M 102=1M 103=10M 104=100M
("480000012200", "1.2M", False),
("480000010200", "1M", False),
("480000010300", "10M", False),
("480000010400", "100M", False),
]
@pytest.mark.parametrize(
"part_number,description",
[(pn, desc) for pn, desc, flag in RESISTOR_CASES if not flag],
)
def test_resistor_matching_descriptions_pass(part_number, description):
mismatch, _ = pv_check(part_number, description)
assert mismatch is False
@pytest.mark.parametrize("part_number,description,should_flag", RESISTOR_CASES)
def test_resistor_flag_expectation(part_number, description, should_flag):
mismatch, _ = pv_check(part_number, description)
assert mismatch is should_flag
@pytest.mark.parametrize("part_number,description", [(p, d) for p, d, _ in CAPACITOR_CASES])
def test_capacitor_matching_descriptions_pass(part_number, description):
mismatch, _ = pv_check(part_number, description)
assert mismatch is False
@pytest.mark.parametrize("part_number,description", [(p, d) for p, d, _ in COIL_CASES])
def test_coil_matching_descriptions_pass(part_number, description):
mismatch, _ = pv_check(part_number, description)
assert mismatch is False
def test_wrong_value_is_flagged():
mismatch, reason = pv_check("410000010A20", "4.7R 1%")
assert mismatch is True
assert "1.02R" in reason
def test_precision_mismatch_is_flagged():
# tail 2200 => 1% expected; description says %1 but not 1%
mismatch, reason = pv_check("410000010A2200", "1.02R %1")
assert mismatch is True
assert "精度" in reason
def test_precision_match_passes():
mismatch, _ = pv_check("410000010A2200", "1.02R 1%")
assert mismatch is False
def test_xx_part_numbers_are_skipped():
mismatch, _ = pv_check("41XX00010A20", "anything")
assert mismatch is False
def test_use_descriptions_are_skipped():
mismatch, _ = pv_check("410000010A20", "USE AS JUMPER")
assert mismatch is False
def test_unknown_prefix_passes():
mismatch, _ = pv_check("990000010A20", "whatever")
assert mismatch is False
def test_short_description_passes():
# legacy guard: Len(PartVal) > 1
mismatch, _ = pv_check("410000010A20", "R")
assert mismatch is False
+112
View File
@@ -0,0 +1,112 @@
from dx_productivity.domain.models import AttributeRecord, NetRecord
from dx_productivity.features.inspection import (
has_net_data,
missing_attribute_values,
net_cross_page,
net_list,
solitary_nets,
)
def _snapshot_factory(snapshot_factory, nets, components=()):
if not components and nets == ():
return snapshot_factory()
return snapshot_factory(components=components, nets=nets)
def test_solitary_nets_found(snapshot_factory, component_factory):
snapshot = snapshot_factory(
nets=(
NetRecord(name="N1", pages=(1,)),
NetRecord(name="N2", pages=(1, 2)),
)
)
rows = solitary_nets(snapshot)
assert len(rows) == 1
assert rows[0].name == "N1"
assert rows[0].locate_net is True
def test_net_list_covers_all(snapshot_factory):
snapshot = snapshot_factory(
nets=(
NetRecord(name="N1", pages=(1,)),
NetRecord(name="N2", pages=(1, 2)),
)
)
assert len(net_list(snapshot)) == 2
def test_cross_page_lookup(snapshot_factory):
snapshot = snapshot_factory(nets=(NetRecord(name="N2", pages=(1, 2)),))
rows = net_cross_page(snapshot, "n2")
assert [row.pages[0] for row in rows] == [1, 2]
assert net_cross_page(snapshot, "missing") == []
def test_value_miss_flags_empty_values_only_by_default(
component_factory, snapshot_factory
):
empty = component_factory(
bridge_id="c1",
attributes=(AttributeRecord(name="Value", value="", visible=True),),
)
missing = component_factory(
bridge_id="c2",
stable_uid="uid-c2",
full_path="ROOT\C2",
logical_group_key="uid-c2",
attributes=(),
)
ok = component_factory(
bridge_id="c3",
stable_uid="uid-c3",
full_path="ROOT\C3",
logical_group_key="uid-c3",
attributes=(AttributeRecord(name="Value", value="10K", visible=True),),
)
snapshot = snapshot_factory(components=(empty, missing, ok))
rows = missing_attribute_values(snapshot, "Value")
assert len(rows) == 1
assert rows[0].detail == "属性值为空"
assert rows[0].locate_bridge_id == "c1"
def test_value_miss_include_missing_option(component_factory, snapshot_factory):
missing = component_factory(
bridge_id="c2",
attributes=(),
)
snapshot = snapshot_factory(components=(missing,))
rows = missing_attribute_values(
snapshot, "Value", include_missing=True
)
assert len(rows) == 1
assert rows[0].detail == "属性缺失"
def test_unnamed_components_are_skipped(component_factory, snapshot_factory):
component = component_factory(
refdes="",
attributes=(AttributeRecord(name="Value", value="", visible=True),),
)
snapshot = snapshot_factory(components=(component,))
assert missing_attribute_values(snapshot, "Value") == []
def test_has_net_data(snapshot_factory):
empty = snapshot_factory()
populated = snapshot_factory(nets=(NetRecord(name="N1", pages=(1,)),))
assert has_net_data(empty) is False
assert has_net_data(populated) is True
+170
View File
@@ -0,0 +1,170 @@
from dx_productivity.features.property_change import (
PropertyChangeSettings,
build_property_change_plan,
)
from dx_productivity.domain.models import AttributeRecord, OpType, Severity
def _component_with_attributes(component_factory, attributes):
return component_factory(attributes=tuple(attributes))
def test_plan_rewrites_selected_components_with_attribute(
component_factory, snapshot_factory
):
component = _component_with_attributes(
component_factory,
(AttributeRecord(name="Value", value="10K", visible=True),),
)
snapshot = snapshot_factory(components=(component,))
plan = build_property_change_plan(
snapshot,
PropertyChangeSettings(
property_name="Value",
overrides=((component.bridge_id, "47K"),),
),
)
assert plan.can_apply
assert plan.rows[0].changed is True
assert plan.rows[0].new_refdes == "47K"
assert plan.schedule[0].op is OpType.PROPERTY_VALUE
assert plan.schedule[0].property_name == "Value"
assert plan.schedule[0].expected_refdes == "10K"
assert plan.schedule[0].new_refdes == "47K"
def test_missing_attribute_is_reported_not_silent(
component_factory, snapshot_factory
):
"""Legacy EFM silently skipped components without the attribute."""
component = _component_with_attributes(
component_factory, (AttributeRecord(name="Part Number", value="P1", visible=True),)
)
snapshot = snapshot_factory(components=(component,))
plan = build_property_change_plan(
snapshot,
PropertyChangeSettings(
property_name="Value",
overrides=((component.bridge_id, "47K"),),
),
)
assert plan.rows[0].new_refdes is None
assert any(issue.code == "skipped-missing" for issue in plan.issues)
def test_locked_components_are_skipped(component_factory, snapshot_factory):
component = _component_with_attributes(
component_factory,
(AttributeRecord(name="Value", value="10K", visible=True),),
locked=True,
) if False else component_factory(
attributes=(AttributeRecord(name="Value", value="10K", visible=True),),
locked=True,
)
snapshot = snapshot_factory(components=(component,))
plan = build_property_change_plan(
snapshot,
PropertyChangeSettings(
property_name="Value",
overrides=((component.bridge_id, "47K"),),
),
)
assert plan.rows[0].changed is False
assert any(issue.code == "skipped-locked" for issue in plan.issues)
def test_unselected_components_are_ignored(component_factory, snapshot_factory):
component = component_factory(
selected=False,
attributes=(AttributeRecord(name="Value", value="10K", visible=True),),
)
snapshot = snapshot_factory(components=(component,))
plan = build_property_change_plan(
snapshot,
PropertyChangeSettings(
property_name="Value",
overrides=((component.bridge_id, "47K"),),
),
)
assert plan.rows == ()
assert plan.schedule == ()
def test_duplicate_overrides_are_blocking(component_factory, snapshot_factory):
component = component_factory(
attributes=(AttributeRecord(name="Value", value="10K", visible=True),)
)
snapshot = snapshot_factory(components=(component,))
plan = build_property_change_plan(
snapshot,
PropertyChangeSettings(
property_name="Value",
overrides=(
(component.bridge_id, "47K"),
(component.bridge_id, "22K"),
),
),
)
assert any(
issue.code == "duplicate-override"
and issue.severity is Severity.BLOCKING
for issue in plan.issues
)
def test_clearing_value_is_a_change(component_factory, snapshot_factory):
component = component_factory(
attributes=(AttributeRecord(name="Value", value="10K", visible=True),)
)
snapshot = snapshot_factory(components=(component,))
plan = build_property_change_plan(
snapshot,
PropertyChangeSettings(
property_name="Value",
overrides=((component.bridge_id, ""),),
),
)
assert plan.can_apply
assert plan.rows[0].changed is True
assert plan.schedule[0].new_refdes == ""
def test_multiple_components_get_independent_schedule_rows(
component_factory, snapshot_factory
):
components = tuple(
component_factory(
bridge_id=f"c{i}",
stable_uid=f"uid-c{i}",
full_path=f"ROOT\C{i}",
logical_group_key=f"uid-c{i}",
x=__import__("decimal").Decimal(10 + i),
attributes=(AttributeRecord(name="Value", value="10K", visible=True),),
)
for i in range(1, 3)
)
snapshot = snapshot_factory(components=components)
plan = build_property_change_plan(
snapshot,
PropertyChangeSettings(
property_name="Value",
overrides=(("c1", "47K"), ("c2", "47K")),
),
)
assert plan.can_apply
assert len(plan.schedule) == 2
assert plan.schedule[0].bridge_id != plan.schedule[1].bridge_id
@@ -0,0 +1,96 @@
from decimal import Decimal
from dx_productivity.domain.models import AttributeRecord, OpType, Severity
from dx_productivity.features.property_visibility import (
PropertyVisibilitySettings,
build_property_visibility_plan,
)
def _component(component_factory, visible, **overrides):
return component_factory(
attributes=(
AttributeRecord(name="Part Name", value="RES", visible=visible),
),
**overrides,
)
def test_hide_selected_components(component_factory, snapshot_factory):
component = _component(component_factory, True)
snapshot = snapshot_factory(components=(component,))
plan = build_property_visibility_plan(
snapshot, PropertyVisibilitySettings(visible=False)
)
assert plan.can_apply
assert plan.rows[0].changed is True
assert plan.schedule[0].op is OpType.PROPERTY_VISIBILITY
assert plan.schedule[0].property_name == "Part Name"
assert plan.schedule[0].expected_refdes == "1"
assert plan.schedule[0].new_refdes == "0"
def test_show_restores_hidden_attribute(component_factory, snapshot_factory):
component = _component(component_factory, False)
snapshot = snapshot_factory(components=(component,))
plan = build_property_visibility_plan(
snapshot, PropertyVisibilitySettings(visible=True)
)
assert plan.can_apply
assert plan.schedule[0].new_refdes == "1"
def test_already_hidden_component_is_preserved(
component_factory, snapshot_factory
):
component = _component(component_factory, False)
snapshot = snapshot_factory(components=(component,))
plan = build_property_visibility_plan(
snapshot, PropertyVisibilitySettings(visible=False)
)
assert plan.rows[0].changed is False
assert plan.schedule == ()
assert not plan.can_apply
def test_missing_attribute_is_reported(component_factory, snapshot_factory):
component = component_factory(attributes=())
snapshot = snapshot_factory(components=(component,))
plan = build_property_visibility_plan(
snapshot, PropertyVisibilitySettings(visible=False)
)
assert any(issue.code == "skipped-missing" for issue in plan.issues)
def test_locked_components_are_skipped(component_factory, snapshot_factory):
component = _component(component_factory, True, locked=True)
snapshot = snapshot_factory(components=(component,))
plan = build_property_visibility_plan(
snapshot, PropertyVisibilitySettings(visible=False)
)
assert any(issue.code == "skipped-locked" for issue in plan.issues)
assert plan.rows[0].changed is False
def test_unselected_components_are_ignored(
component_factory, snapshot_factory
):
component = _component(component_factory, True, selected=False)
snapshot = snapshot_factory(components=(component,))
plan = build_property_visibility_plan(
snapshot, PropertyVisibilitySettings(visible=False)
)
assert plan.rows == ()
assert plan.schedule == ()
+45
View File
@@ -0,0 +1,45 @@
{
"format_version": 2,
"run_id": "run-basic",
"snapshot_id": "snapshot-basic",
"design_id": "design-a",
"design_path": "C:\\Projects\\Demo Board\\demo.prj",
"components": [
{
"bridge_id": "c0001",
"stable_uid": "uid-r-a",
"full_path": "ROOT\\R_A",
"logical_group_key": "uid-r-a",
"sheet_name": "1",
"sheet_number": 1,
"x": "125.400",
"y": "75.000",
"y_axis_up": true,
"refdes": "R?",
"symbol_refdes_default": "R?",
"selected": true,
"current_sheet": true,
"part_number": "RC0402",
"value": "10K",
"locked": false
},
{
"bridge_id": "c0002",
"stable_uid": "uid-c-a",
"full_path": "ROOT\\C_A",
"logical_group_key": "uid-c-a",
"sheet_name": "1",
"sheet_number": 1,
"x": "140.000",
"y": "75.000",
"y_axis_up": true,
"refdes": "C1",
"symbol_refdes_default": "C?",
"selected": false,
"current_sheet": true,
"part_number": "CC0402",
"value": "100nF",
"locked": false
}
]
}
+45
View File
@@ -0,0 +1,45 @@
{
"format_version": 2,
"run_id": "run-multiunit",
"snapshot_id": "snapshot-multiunit",
"design_id": "design-multiunit",
"design_path": "C:\\Projects\\Multi Unit\\multi.prj",
"components": [
{
"bridge_id": "u1a",
"stable_uid": "uid-u1",
"full_path": "ROOT\\U1\\A",
"logical_group_key": "uid-u1",
"sheet_name": "1",
"sheet_number": 1,
"x": "10",
"y": "100",
"y_axis_up": true,
"refdes": "U?",
"symbol_refdes_default": "U?",
"selected": true,
"current_sheet": true,
"part_number": "MCU",
"value": "MCU",
"locked": false
},
{
"bridge_id": "u1b",
"stable_uid": "uid-u1",
"full_path": "ROOT\\U1\\B",
"logical_group_key": "uid-u1",
"sheet_name": "2",
"sheet_number": 2,
"x": "20",
"y": "80",
"y_axis_up": true,
"refdes": "U?",
"symbol_refdes_default": "U?",
"selected": true,
"current_sheet": false,
"part_number": "MCU",
"value": "MCU",
"locked": false
}
]
}
@@ -0,0 +1,64 @@
import json
from pathlib import Path
import pytest
from dx_productivity.bridge.probe_host import main, write_probe_marker
def test_probe_marker_is_versioned_json(tmp_path: Path) -> None:
output = tmp_path / "compatibility.json"
write_probe_marker(output, "named", {"selected_query": True})
assert output.read_text(encoding="utf-8") == (
'{"format_version":1,"route":"named","selected_query":true}\n'
)
def test_probe_cli_merges_capability_payload(tmp_path: Path) -> None:
output = tmp_path / "compatibility.json"
exit_code = main(
[
"--output",
str(output),
"--route",
"named",
"--payload-json",
'{"yield_method":"Scripting.DoEvents","retained_reference":true}',
]
)
assert exit_code == 0
assert json.loads(output.read_text(encoding="utf-8"))["yield_method"] == (
"Scripting.DoEvents"
)
def test_probe_cli_rejects_non_object_payload(tmp_path: Path) -> None:
with pytest.raises(ValueError, match="JSON object"):
main(
[
"--output",
str(tmp_path / "compatibility.json"),
"--route",
"named",
"--payload-json",
"[]",
]
)
def test_startup_probe_uses_packaged_executable_and_records_portable_path() -> None:
text = Path("integration/dxdesigner795/CompatibilityProbe.vbs").read_text(
encoding="ascii"
)
assert "DxDesignerTools.exe" in text
assert '"script_path_source"' in text
assert '"portable_root_valid"' in text
assert "DXTOOLS_HOME" not in text
assert "py -3.12" not in text
assert "D:\\NET_CHECK" not in text
assert text.isascii()
+62
View File
@@ -0,0 +1,62 @@
from pathlib import Path
import subprocess
INTEGRATION_ROOT = Path("integration/dxdesigner795")
def test_menu_is_ascii_portable_and_uses_795_menu_bar() -> None:
text = (INTEGRATION_ROOT / "MenuAdd.vbs").read_text(encoding="ascii")
assert 'CommandBars("Sheet Menu Bar")' in text
assert "DxToolsResolveRoot" in text
assert "WScript.ScriptFullName" in text
assert "Scripting.CurrentScriptFullName" in text
assert "Scripting.ScriptFullName" in text
assert "DxDesignerTools.exe" in text
assert "DXTOOLS_HOME" not in text
assert "D:\\" not in text
assert text.isascii()
def test_menu_exposes_named_in_process_feature_actions() -> None:
text = (INTEGRATION_ROOT / "MenuAdd.vbs").read_text(encoding="ascii")
for action in (
"DxToolsOpenRefDes",
"DxToolsOpenPropertyChange",
"DxToolsOpenPropertyVisibility",
"DxToolsOpenInspection",
"DxToolsOpenBom",
"DxToolsOpenCompatibility",
"DxToolsOpenGuide",
):
assert f'OnAction = "{action}"' in text
assert "ExecuteGlobal" in text
assert "DxToolsStartFeature" in text
assert "LegacyMenu" not in text
def test_feature_menu_routes_through_design_bridge_entry() -> None:
text = (INTEGRATION_ROOT / "DesignBridge.vbs").read_text(encoding="ascii")
assert "DxToolsRunDesignBridge" in text
assert "DxToolsDesignBridgeStart" in text
assert "Snapshot.vbs" in text
assert "Transaction.vbs" in text
assert "Mailbox.vbs" in text
assert text.isascii()
def test_release_vbs_sources_are_ascii_only() -> None:
names = (
"MenuAdd.vbs",
"DesignBridge.vbs",
"BridgeCommon.vbs",
"CompatibilityProbe.vbs",
"core/Snapshot.vbs",
"core/Transaction.vbs",
"core/Mailbox.vbs",
)
for name in names:
assert (INTEGRATION_ROOT / name).read_bytes().isascii(), name
+91
View File
@@ -0,0 +1,91 @@
from pathlib import Path
import subprocess
INTEGRATION_ROOT = Path("integration/dxdesigner795")
def test_bridge_core_is_ascii_and_contains_transaction_stages() -> None:
common = (INTEGRATION_ROOT / "BridgeCommon.vbs").read_text(encoding="ascii")
transaction = (INTEGRATION_ROOT / "core" / "Transaction.vbs").read_text(
encoding="ascii"
)
snapshot = (INTEGRATION_ROOT / "core" / "Snapshot.vbs").read_text(
encoding="ascii"
)
mailbox = (INTEGRATION_ROOT / "core" / "Mailbox.vbs").read_text(
encoding="ascii"
)
entry = (INTEGRATION_ROOT / "DesignBridge.vbs").read_text(encoding="ascii")
assert "DxToolsParseScheduleRow" in common
assert "DxBridgeIdleWait" in common
for name in (
"DxExportSnapshot",
"DxRefreshSnapshot",
):
assert f"Function {name}" in snapshot
for name in (
"DxProcessApply",
"DxPreflightApply",
"DxApplySchedule",
"DxRollback",
):
assert f"Function {name}" in transaction
assert "DxBridgeMailboxLoop" in mailbox
assert "DxToolsRunDesignBridge" in entry
for text in (common, transaction, snapshot, mailbox, entry):
assert "ViewDraw.Application" not in text
assert "GetActiveObject" not in text
assert "DXTOOLS_HOME" not in text
assert text.isascii()
def test_real_vbs_bridge_transaction_harness_passes() -> None:
result = subprocess.run(
["cscript", "//nologo", "tests/vbs/test_refdes_bridge.vbs"],
capture_output=True,
text=True,
encoding="utf-8",
check=False,
timeout=30,
)
assert result.returncode == 0, result.stdout + result.stderr
assert "DesignBridge transaction assertions passed" in result.stdout
def test_real_vbs_snapshot_export_harness_passes() -> None:
result = subprocess.run(
["cscript", "//nologo", "tests/vbs/test_refdes_export.vbs"],
capture_output=True,
text=True,
encoding="utf-8",
check=False,
timeout=30,
)
assert result.returncode == 0, result.stdout + result.stderr
assert "RefDes export assertions passed" in result.stdout
def test_snapshot_export_uses_v2_protocol_fields() -> None:
snapshot = (INTEGRATION_ROOT / "core" / "Snapshot.vbs").read_text(
encoding="ascii"
)
assert '"format_version"": 2' in snapshot
assert '"attributes"' in snapshot
assert '"nets"' in snapshot
assert '"selected_nets"' in snapshot
assert '"locked"' in snapshot
def test_transaction_supports_property_operations() -> None:
transaction = (INTEGRATION_ROOT / "core" / "Transaction.vbs").read_text(
encoding="ascii"
)
assert 'Attributes.Item(' in transaction
assert '.Visible =' in transaction
assert 'DxBridgeNormalizeVisible' in transaction
+145
View File
@@ -0,0 +1,145 @@
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
REPO_ROOT = Path(__file__).resolve().parents[2]
RELEASE_ROOT = REPO_ROOT / "release" / "DxDesigner效率工具"
def _sanitized_environment() -> dict[str, str]:
environment = os.environ.copy()
windows = Path(os.environ.get("WINDIR", "C:/Windows"))
environment["PATH"] = os.pathsep.join(
(str(windows / "System32"), str(windows))
)
environment["QT_QPA_PLATFORM"] = "offscreen"
environment.pop("PYTHONHOME", None)
environment.pop("PYTHONPATH", None)
return environment
def test_release_contains_portable_runtime_and_root_scripts() -> None:
expected = (
"DxDesignerTools.exe",
"_runtime/python312.dll",
"_runtime/PySide6/plugins/platforms/qwindows.dll",
"_runtime/vbs/BridgeCommon.vbs",
"_runtime/vbs/Snapshot.vbs",
"_runtime/vbs/Transaction.vbs",
"_runtime/vbs/Mailbox.vbs",
"_runtime/vbs/BomExport.vbs",
"MenuAdd.vbs",
"DesignBridge.vbs",
"CompatibilityProbe.vbs",
"templates/BOM模板.xls",
"expedition/ExpeditionBridge.vbs",
"docs/DxDesigner_7.9.5_自动位号工具使用说明.docx",
)
for relative_path in expected:
assert (RELEASE_ROOT / relative_path).is_file(), relative_path
assert any(
path.suffix in {".ttf", ".otf"}
for path in (RELEASE_ROOT / "_runtime").rglob("*")
)
def test_release_does_not_bundle_foreign_icu_from_build_path() -> None:
runtime = RELEASE_ROOT / "_runtime"
assert not (runtime / "icuuc.dll").exists()
assert not list(runtime.glob("icudt*.dll"))
def test_packaged_probe_runs_without_python_on_path(tmp_path: Path) -> None:
output = tmp_path / "兼容性 结果.json"
result = subprocess.run(
[
str(RELEASE_ROOT / "DxDesignerTools.exe"),
"probe",
"--output",
str(output),
"--route",
"named",
"--payload-json",
'{"portable":true}',
],
env=_sanitized_environment(),
timeout=30,
check=False,
)
assert result.returncode == 0
assert json.loads(output.read_text(encoding="utf-8"))["portable"] is True
def test_packaged_ui_loads_request_without_python_on_path() -> None:
result = subprocess.run(
[
str(RELEASE_ROOT / "DxDesignerTools.exe"),
"ui",
"--request",
str(REPO_ROOT / "tests" / "fixtures" / "request-basic.json"),
"--smoke-test-ms",
"250",
],
env=_sanitized_environment(),
timeout=30,
check=False,
)
assert result.returncode == 0
def test_packaged_application_runs_from_chinese_path_with_spaces(
tmp_path: Path,
) -> None:
copied_root = tmp_path / "中文 工具"
shutil.copytree(RELEASE_ROOT, copied_root)
output = tmp_path / "兼容性 结果.json"
probe = subprocess.run(
[
str(copied_root / "DxDesignerTools.exe"),
"probe",
"--output",
str(output),
"--route",
"named",
"--payload-json",
'{"portable":true}',
],
env=_sanitized_environment(),
timeout=30,
check=False,
)
ui = subprocess.run(
[
str(copied_root / "DxDesignerTools.exe"),
"ui",
"--request",
str(REPO_ROOT / "tests" / "fixtures" / "request-basic.json"),
"--smoke-test-ms",
"250",
],
env=_sanitized_environment(),
timeout=30,
check=False,
)
assert probe.returncode == 0
assert json.loads(output.read_text(encoding="utf-8"))["portable"] is True
assert ui.returncode == 0
def test_release_archive_matches_sha256_manifest() -> None:
archive = REPO_ROOT / "release" / "DxDesigner效率工具_Win11_x64.zip"
manifest = REPO_ROOT / "release" / "SHA256SUMS.txt"
digest = hashlib.sha256(archive.read_bytes()).hexdigest()
assert manifest.read_text(encoding="utf-8").split()[0] == digest
@@ -0,0 +1,69 @@
from pathlib import Path
def test_spec_builds_onedir_with_private_runtime() -> None:
text = Path("packaging/DxDesignerTools.spec").read_text(encoding="utf-8")
assert "COLLECT(" in text
assert 'contents_directory="_runtime"' in text
assert 'name="DxDesignerTools"' in text
assert "console=False" in text
def test_build_script_assembles_portable_root_without_installing_packages() -> None:
text = Path("packaging/build_release.ps1").read_text(encoding="utf-8")
for name in (
"MenuAdd.vbs",
"DesignBridge.vbs",
"CompatibilityProbe.vbs",
"BridgeCommon.vbs",
"Snapshot.vbs",
"Transaction.vbs",
"Mailbox.vbs",
"BomExport.vbs",
"ExpeditionBridge.vbs",
"BOM模板.xls",
"DxDesignerTools.exe",
"DxDesigner效率工具_Win11_x64.zip",
"SHA256SUMS.txt",
):
assert name in text
assert "_runtime\\vbs" in text
assert "Compress-Archive" in text
assert "pip install" not in text.casefold()
assert "Invoke-WebRequest" not in text
def test_build_script_has_utf8_bom_for_windows_powershell_51() -> None:
data = Path("packaging/build_release.ps1").read_bytes()
assert data.startswith(b"\xef\xbb\xbf")
def test_build_dependencies_pin_pyinstaller_major_version() -> None:
text = Path("pyproject.toml").read_text(encoding="utf-8")
assert 'pyinstaller>=6.11,<7' in text
def test_build_script_no_longer_ships_legacy_compat_assets() -> None:
"""The legacy EFM/VBS compat layer is retired; only the BOM template and
the Expedition adapter ship with a release."""
text = Path("packaging/build_release.ps1").read_text(encoding="utf-8")
assert "legacy\\yiyezhqiu" not in text
assert "modules\\legacy" not in text
assert "LegacyMenu.vbs" not in text
assert "RefDesBridge.vbs" not in text
assert "D:\\NET_CHECK" not in text
assert "version.json" in text
assert "update-manifest.template.json" in text
def test_signing_tool_exists_and_is_documented() -> None:
text = Path("packaging/sign_manifest.py").read_text(encoding="utf-8")
assert "Ed25519PrivateKey" in text
assert "--package" in text
assert "--key" in text
+93
View File
@@ -0,0 +1,93 @@
import importlib
import json
from pathlib import Path
from dx_productivity.bridge.protocol import load_apply_request
from dx_productivity.bridge.run_store import RunStore
from dx_productivity.domain.models import ApplyStatus, RunPaths
from dx_productivity.domain.planner import build_annotation_plan
from dx_productivity.domain.models import AnnotationSettings
def _run_paths(tmp_path: Path, run_id: str) -> RunPaths:
root = tmp_path / "runs" / run_id
root.mkdir(parents=True)
return RunPaths(
run_id,
root,
root / "request.json",
root / "result.tsv",
root / "locate.tsv",
root / "apply-status.json",
)
def test_restore_creates_second_backup_before_publishing_result(
qtbot,
tmp_path,
snapshot_factory,
) -> None:
page_module = importlib.import_module("dx_productivity.ui.history_page")
controller_module = importlib.import_module(
"dx_productivity.ui.history_controller"
)
original = snapshot_factory(target_ref="R?")
applied = snapshot_factory(target_ref="R1")
store = RunStore(tmp_path / "local")
annotation_plan = build_annotation_plan(original, AnnotationSettings())
first_backup = store.write_backup(original, annotation_plan)
store.record_status(
ApplyStatus(1, original.run_id, "applied", 1, first_backup)
)
paths = _run_paths(tmp_path, applied.run_id)
paths.apply_status.write_text('{"stale":true}', encoding="utf-8")
page = page_module.HistoryPage()
qtbot.addWidget(page)
controller = controller_module.HistoryController(
page,
run_store=store,
run_paths=paths,
confirm_restore=lambda entry, count: True,
)
controller.load_snapshot(applied)
result = controller.restore_latest()
assert result == paths.result
assert result.read_text(encoding="utf-8") == "1\trefdes\tc0001\t\tR1\tR?\tR?\n"
metadata = load_apply_request(paths.apply_request)
assert metadata.backup_path.exists()
assert metadata.backup_path != first_backup
assert not paths.apply_status.exists()
controller.stop()
def test_restore_cancel_does_not_publish_transaction(
qtbot,
tmp_path,
snapshot_factory,
) -> None:
page_module = importlib.import_module("dx_productivity.ui.history_page")
controller_module = importlib.import_module(
"dx_productivity.ui.history_controller"
)
original = snapshot_factory(target_ref="R?")
applied = snapshot_factory(target_ref="R1")
store = RunStore(tmp_path / "local")
plan = build_annotation_plan(original, AnnotationSettings())
backup = store.write_backup(original, plan)
store.record_status(ApplyStatus(1, original.run_id, "applied", 1, backup))
paths = _run_paths(tmp_path, applied.run_id)
page = page_module.HistoryPage()
qtbot.addWidget(page)
controller = controller_module.HistoryController(
page,
run_store=store,
run_paths=paths,
confirm_restore=lambda entry, count: False,
)
controller.load_snapshot(applied)
assert controller.restore_latest() is None
assert not paths.result.exists()
assert not paths.apply_request.exists()
+43
View File
@@ -0,0 +1,43 @@
from datetime import datetime, timedelta, timezone
import importlib
from pathlib import Path
from dx_productivity.domain.models import HistoryEntry
def _entry(run_id: str, timestamp: datetime) -> HistoryEntry:
return HistoryEntry(
timestamp=timestamp,
run_id=run_id,
design_id="design-test",
backup_path=Path(f"C:/Backups/{run_id}.json"),
state="applied",
changed_count=3,
)
def test_history_page_shows_latest_entry_first(qtbot) -> None:
module = importlib.import_module("dx_productivity.ui.history_page")
page = module.HistoryPage()
qtbot.addWidget(page)
now = datetime.now(timezone.utc)
entries = (
_entry("newest", now),
_entry("older", now - timedelta(days=1)),
)
page.set_entries(entries)
assert page.row_run_id(0) == "newest"
assert page.selected_entry() == entries[0]
assert page.restore_button.isEnabled()
def test_history_page_disables_restore_when_empty(qtbot) -> None:
module = importlib.import_module("dx_productivity.ui.history_page")
page = module.HistoryPage()
qtbot.addWidget(page)
page.set_entries(())
assert not page.restore_button.isEnabled()
+117
View File
@@ -0,0 +1,117 @@
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QToolButton
from dx_productivity.ui.main_window import MainWindow
from dx_productivity.ui.app import create_application, create_main_window
from dx_productivity.ui.refdes_page import RefDesPage
from dx_productivity.ui.history_page import HistoryPage
from dx_productivity.ui.theme import Theme, contrast_ratio, theme_tokens
def test_main_window_has_approved_minimum_and_navigation(qtbot):
window = MainWindow()
qtbot.addWidget(window)
assert window.minimumWidth() == 1100
assert window.minimumHeight() == 700
assert window.navigation_items()[:3] == ["自动位号", "属性批改", "属性显示"]
assert window.apply_button.text() == "应用位号"
def test_icon_buttons_have_accessible_names(qtbot):
window = MainWindow()
qtbot.addWidget(window)
for button in window.findChildren(QToolButton):
assert button.accessibleName()
assert button.toolTip()
def test_light_and_dark_text_contrast_meets_normal_text_requirement():
for theme in (Theme.LIGHT, Theme.DARK):
tokens = theme_tokens(theme)
assert contrast_ratio(tokens.text_primary, tokens.canvas) >= 4.5
assert contrast_ratio(tokens.text_secondary, tokens.canvas) >= 4.5
def test_theme_toggle_changes_window_theme(qtbot):
window = MainWindow(theme=Theme.LIGHT)
qtbot.addWidget(window)
qtbot.mouseClick(window.theme_button, Qt.MouseButton.LeftButton)
assert window.theme is Theme.DARK
def test_minimum_layout_has_no_children_outside_window(qtbot):
window = MainWindow()
qtbot.addWidget(window)
window.resize(1100, 700)
window.show()
qtbot.waitExposed(window)
bounds = window.rect()
for child in window.findChildren(QToolButton):
top_left = child.mapTo(window, child.rect().topLeft())
bottom_right = child.mapTo(window, child.rect().bottomRight())
assert bounds.contains(top_left)
assert bounds.contains(bottom_right)
def test_request_opens_live_refdes_page(qtbot, fixture_path):
window = create_main_window(fixture_path / "request-basic.json")
qtbot.addWidget(window)
assert isinstance(window.pages.widget(0), RefDesPage)
assert window.refdes_controller.plan is not None
assert window.apply_button.isEnabled() is True
def test_request_connects_operation_history_to_same_snapshot(
qtbot, fixture_path, monkeypatch, tmp_path
):
monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))
window = create_main_window(fixture_path / "request-basic.json")
qtbot.addWidget(window)
assert isinstance(window.pages.widget(6), HistoryPage)
assert window.history_controller.snapshot is window.refdes_controller.snapshot
assert window.history_controller.run_paths is window.refdes_controller.run_paths
def test_application_loads_windows_chinese_ui_font(qapp):
from PySide6.QtGui import QFontDatabase
create_application([])
assert any("YaHei" in family for family in QFontDatabase.families())
def test_main_window_uses_yiyezhqiu_brand_and_feature_pages(qtbot):
from dx_productivity.ui.bom_page import BomPage
from dx_productivity.ui.inspection_page import InspectionPage
from dx_productivity.ui.property_change_page import PropertyChangePage
from dx_productivity.ui.property_visibility_page import (
PropertyVisibilityPage,
)
window = create_main_window()
qtbot.addWidget(window)
assert window.windowTitle() == "一叶知秋_重构版"
assert window.brand_label.text() == "一叶知秋_重构版"
assert isinstance(window.pages.widget(1), PropertyChangePage)
assert isinstance(window.pages.widget(2), PropertyVisibilityPage)
assert isinstance(window.pages.widget(3), InspectionPage)
assert isinstance(window.pages.widget(5), BomPage)
def test_main_window_wires_settings_page(qtbot):
from dx_productivity.ui.settings_page import SettingsPage
window = create_main_window()
qtbot.addWidget(window)
assert isinstance(window.pages.widget(7), SettingsPage)
assert window.settings_page.version_label.text().startswith("当前版本 0.1.0")
+187
View File
@@ -0,0 +1,187 @@
import hashlib
from dx_productivity.bridge.protocol import load_apply_request
from dx_productivity.bridge.run_store import RunStore
from dx_productivity.domain.models import RunPaths
from dx_productivity.ui import refdes_controller as controller_module
from dx_productivity.ui.refdes_controller import RefDesController
from dx_productivity.ui.refdes_page import RefDesPage
def test_blocking_issue_disables_apply(
qtbot, component_factory, snapshot_factory
):
page = RefDesPage()
qtbot.addWidget(page)
controller = RefDesController(page)
unresolved = component_factory(refdes="", symbol_refdes_default=None)
controller.load_snapshot(snapshot_factory(components=(unresolved,)))
assert controller.can_apply is False
assert page.issue_text() == "1 个阻断项"
def test_valid_plan_enables_apply(qtbot, snapshot_factory):
page = RefDesPage()
qtbot.addWidget(page)
controller = RefDesController(page)
controller.load_snapshot(snapshot_factory())
assert controller.can_apply is True
assert controller.plan is not None
assert controller.plan.rows[0].new_refdes == "R1"
def test_scope_change_recomputes_without_mutating_snapshot(
qtbot, snapshot_factory
):
page = RefDesPage()
qtbot.addWidget(page)
controller = RefDesController(page)
snapshot = snapshot_factory(target_ref="R?", outside_ref="R1")
controller.load_snapshot(snapshot)
page.full_design_button.click()
assert controller.snapshot is snapshot
assert controller.plan is not None
assert len(controller.plan.rows) == 2
def test_apply_writes_metadata_before_atomic_schedule(
qtbot, tmp_path, snapshot_factory, monkeypatch
):
page = RefDesPage()
qtbot.addWidget(page)
snapshot = snapshot_factory()
run_root = tmp_path / "runs" / snapshot.run_id
run_root.mkdir(parents=True)
paths = RunPaths(
snapshot.run_id,
run_root,
run_root / "request.json",
run_root / "result.tsv",
run_root / "locate.tsv",
run_root / "apply-status.json",
)
controller = RefDesController(page, run_store=RunStore(tmp_path), run_paths=paths)
controller.load_snapshot(snapshot)
paths.apply_status.write_text('{"stale": true}', encoding="utf-8")
write_schedule = controller_module.write_schedule
def guarded_write_schedule(path, schedule):
assert paths.apply_request.exists()
write_schedule(path, schedule)
monkeypatch.setattr(controller_module, "write_schedule", guarded_write_schedule)
result = controller.apply()
assert result == paths.result
assert not paths.apply_status.exists()
assert result.read_text(encoding="utf-8") == "1\trefdes\tc0001\t\tR?\tR1\tR1\n"
assert controller.pending_backup is not None
assert controller.pending_backup.exists()
apply_request = load_apply_request(paths.apply_request)
assert apply_request.run_id == snapshot.run_id
assert apply_request.snapshot_id == snapshot.snapshot_id
assert apply_request.backup_path == controller.pending_backup
assert apply_request.schedule_sha256 == hashlib.sha256(result.read_bytes()).hexdigest()
def test_locate_request_is_published_to_mailbox(qtbot, tmp_path, snapshot_factory):
page = RefDesPage()
qtbot.addWidget(page)
snapshot = snapshot_factory()
run_root = tmp_path / "run"
run_root.mkdir()
paths = RunPaths(
snapshot.run_id,
run_root,
run_root / "request.json",
run_root / "result.tsv",
run_root / "locate.tsv",
run_root / "apply-status.json",
)
controller = RefDesController(page, run_paths=paths)
controller.load_snapshot(snapshot)
page.locate_requested.emit("c0001")
assert paths.locate.read_text(encoding="utf-8") == "c0001\n"
def _make_controller(qtbot, tmp_path, snapshot, store=True):
page = RefDesPage()
qtbot.addWidget(page)
run_root = tmp_path / "runs" / snapshot.run_id
run_root.mkdir(parents=True)
paths = RunPaths(
snapshot.run_id,
run_root,
run_root / "request.json",
run_root / "result.tsv",
run_root / "locate.tsv",
run_root / "apply-status.json",
)
run_store = RunStore(tmp_path) if store else None
controller = RefDesController(page, run_store=run_store, run_paths=paths)
controller.load_snapshot(snapshot)
return controller
def test_rejected_status_without_backup_does_not_crash_polling(
qtbot, tmp_path, snapshot_factory
):
"""Regression: a rejected transaction writes backup_path=null; the old
record_status raised inside the polling slot and silently killed it."""
snapshot = snapshot_factory()
controller = _make_controller(qtbot, tmp_path, snapshot)
controller.run_paths.apply_status.write_text(
'{"format_version": 2, "run_id": "%s", "state": "rejected", '
'"changed_count": 0, "backup_path": null, "failing_sequence": null, '
'"error": "Apply schedule expected value is stale", '
'"rollback_state": null}' % snapshot.run_id,
encoding="utf-8",
)
with qtbot.waitSignal(controller.apply_completed, timeout=5000):
controller._poll_apply_status()
def test_corrupt_status_file_reports_failure(qtbot, tmp_path, snapshot_factory):
snapshot = snapshot_factory()
controller = _make_controller(qtbot, tmp_path, snapshot)
controller.run_paths.apply_status.write_text("{not json", encoding="utf-8")
with qtbot.waitSignal(controller.apply_failed, timeout=5000):
controller._poll_apply_status()
def test_apply_reentry_is_rejected_and_refresh_is_ignored(
qtbot, tmp_path, snapshot_factory
):
import pytest
snapshot = snapshot_factory()
controller = _make_controller(qtbot, tmp_path, snapshot)
controller._apply_in_flight = True
with pytest.raises(RuntimeError):
controller.apply()
def test_missing_heartbeat_fails_transaction(
qtbot, tmp_path, snapshot_factory
):
import time
snapshot = snapshot_factory()
controller = _make_controller(qtbot, tmp_path, snapshot)
controller._apply_in_flight = True
controller._apply_started_at = time.monotonic() - 3600
with qtbot.waitSignal(controller.apply_failed, timeout=5000):
controller._poll_apply_status()
+56
View File
@@ -0,0 +1,56 @@
from decimal import Decimal
from PySide6.QtCore import Qt
from dx_productivity.domain.models import (
NumberingMode,
ProcessingMode,
Scope,
SortOrder,
)
from dx_productivity.ui.refdes_page import RefDesPage
def test_refdes_defaults_match_approved_design(qtbot):
page = RefDesPage()
qtbot.addWidget(page)
assert page.scope() is Scope.SELECTED
assert page.processing_mode() is ProcessingMode.FILL_ONLY
assert page.numbering_mode() is NumberingMode.CONTINUOUS
assert page.sort_order() is SortOrder.TOP_DOWN_LEFT_RIGHT
assert page.start_number() == 1
assert page.row_tolerance() == Decimal("5")
def test_page_controls_emit_settings_changed(qtbot):
page = RefDesPage()
qtbot.addWidget(page)
with qtbot.waitSignal(page.settings_changed):
page.full_design_button.click()
assert page.scope() is Scope.FULL_DESIGN
def test_search_filters_preview_without_removing_plan_rows(
qtbot, snapshot_factory, settings
):
from dx_productivity.domain.planner import build_annotation_plan
page = RefDesPage()
qtbot.addWidget(page)
plan = build_annotation_plan(snapshot_factory(), settings())
page.set_plan(plan)
page.search_input.setText("no-match")
assert page.preview_model.rowCount() == 1
assert page.preview_table.isRowHidden(0) is True
def test_preview_table_has_stable_column_count(qtbot):
page = RefDesPage()
qtbot.addWidget(page)
assert page.preview_model.columnCount() == 8
assert page.preview_table.horizontalHeader().minimumSectionSize() >= 40
+97
View File
@@ -0,0 +1,97 @@
import json
from datetime import datetime, timedelta, timezone
from pathlib import Path
def test_settings_controller_persists_only_non_secret_values(tmp_path: Path):
from dx_productivity.ui.settings_controller import SettingsController
controller = SettingsController(settings_path=tmp_path / "settings.json")
controller.save_settings("https://example.invalid/manifest.json", "stable", True)
data = json.loads((tmp_path / "settings.json").read_text(encoding="utf-8"))
assert data == {
"source": "https://example.invalid/manifest.json",
"channel": "stable",
"auto_check": True,
}
def test_settings_controller_auto_check_is_due_after_24_hours(tmp_path: Path):
from dx_productivity.ui.settings_controller import SettingsController
controller = SettingsController(settings_path=tmp_path / "settings.json")
settings = {"source": "file:///manifest.json", "channel": "development", "auto_check": True}
now = datetime(2026, 9, 11, tzinfo=timezone.utc)
assert controller.auto_check_due(settings, now=now)
controller.save_settings("file:///manifest.json", "development", True)
controller.record_check(now=now)
settings = controller.load_settings()
assert not controller.auto_check_due(settings, now=now + timedelta(hours=23))
assert controller.auto_check_due(settings, now=now + timedelta(hours=25))
def test_settings_controller_check_emits_result_for_local_manifest(qtbot, tmp_path: Path):
import json
from dx_productivity.ui.settings_controller import SettingsController
manifest = tmp_path / "manifest.json"
manifest.write_text(
json.dumps(
{
"product": "yiyezhqiu-refactored",
"version": "1.1.0",
"channel": "development",
"min_supported_version": "1.0.0",
"package_url": "file:///release.zip",
"sha256": "a" * 64,
"release_notes": "test",
"published_at": "2026-09-11",
}
),
encoding="utf-8",
)
controller = SettingsController(current_version="1.0.0")
with qtbot.waitSignal(controller.check_finished, timeout=3000) as signal:
controller.check_updates(manifest.as_uri(), "development")
assert signal.args[0].status == "available"
assert controller._thread is None
def test_settings_controller_stages_update_before_install_request(qtbot, tmp_path: Path):
from dx_productivity.ui.settings_controller import SettingsController
from dx_productivity.update.models import UpdateManifest
class FakeStager:
def download_and_verify(self, manifest, destination):
destination.mkdir(parents=True, exist_ok=True)
staged = destination / "1.1.0.zip"
staged.write_bytes(b"verified")
return staged
manifest = UpdateManifest.from_mapping(
{
"product": "yiyezhqiu-refactored",
"version": "1.1.0",
"channel": "development",
"min_supported_version": "1.0.0",
"package_url": "file:///release.zip",
"sha256": "a" * 64,
"release_notes": "test",
"published_at": "2026-09-11",
}
)
controller = SettingsController(stager=FakeStager(), staging_path=tmp_path / "updates")
with qtbot.waitSignal(controller.stage_finished, timeout=3000) as signal:
controller.stage_update(manifest)
result = signal.args[0]
assert result.state == "ready"
assert result.staged_zip == tmp_path / "updates" / "1.1.0.zip"
assert controller._stage_thread is None
assert controller.staged_path(manifest) == result.staged_zip
+106
View File
@@ -0,0 +1,106 @@
from PySide6.QtWidgets import QMessageBox
def make_manifest(version: str = "1.1.0"):
from dx_productivity.update.models import UpdateManifest
return UpdateManifest.from_mapping(
{
"product": "yiyezhqiu-refactored",
"version": version,
"channel": "development",
"min_supported_version": "1.0.0",
"package_url": "file:///release.zip",
"sha256": "a" * 64,
"release_notes": "迁移旧版属性工具",
"published_at": "2026-09-11",
}
)
def test_settings_page_requires_second_confirmation_before_install(qtbot, monkeypatch):
from dx_productivity.ui.settings_page import SettingsPage
from dx_productivity.ui.settings_controller import UpdateStageResult
page = SettingsPage(current_version="1.0.0")
qtbot.addWidget(page)
page.show_update(make_manifest())
monkeypatch.setattr(
QMessageBox,
"question",
lambda *args, **kwargs: QMessageBox.StandardButton.Yes,
)
assert page.install_button.isEnabled()
assert page.install_requested_emissions == 0
page.install_button.click()
assert page.install_requested_emissions == 0
assert page.download_requested_emissions == 1
from pathlib import Path
page.show_stage_result(UpdateStageResult("ready", make_manifest(), Path("release.zip"), "ready"))
page.install_button.click()
assert page.install_requested_emissions == 1
def test_settings_page_does_not_offer_install_until_staging_finishes(qtbot, monkeypatch):
from dx_productivity.ui.settings_page import SettingsPage
from dx_productivity.ui.settings_controller import UpdateStageResult
from pathlib import Path
page = SettingsPage(current_version="1.0.0")
qtbot.addWidget(page)
manifest = make_manifest()
page.show_update(manifest)
monkeypatch.setattr(
QMessageBox,
"question",
lambda *args, **kwargs: QMessageBox.StandardButton.Yes,
)
page.install_button.click()
assert not page.install_button.isEnabled()
assert page.status_label.text() == "正在下载并校验"
page.show_stage_result(UpdateStageResult("failed", manifest, None, "网络不可用"))
assert not page.install_button.isEnabled()
assert page.status_label.text() == "网络不可用"
page.show_stage_result(UpdateStageResult("ready", manifest, Path("release.zip"), "ready"))
assert page.install_button.isEnabled()
assert page.install_button.text() == "确认安装"
def test_settings_page_disables_install_for_non_available_result(qtbot):
from dx_productivity.ui.settings_page import SettingsPage
from dx_productivity.update.service import UpdateCheckResult
from dx_productivity.update.models import SemVer
page = SettingsPage(current_version="1.0.0")
qtbot.addWidget(page)
page.show_result(UpdateCheckResult("up-to-date", SemVer.parse("1.0.0"), None, "latest"))
assert not page.install_button.isEnabled()
assert page.status_label.text() == "已是最新"
def test_settings_page_disables_unsigned_stable_install(qtbot):
from dx_productivity.ui.settings_page import SettingsPage
from dx_productivity.update.models import UpdateManifest
page = SettingsPage(current_version="1.0.0")
qtbot.addWidget(page)
manifest = UpdateManifest.from_mapping(
{
"product": "yiyezhqiu-refactored",
"version": "1.1.0",
"channel": "stable",
"min_supported_version": "1.0.0",
"package_url": "file:///release.zip",
"sha256": "a" * 64,
"release_notes": "test",
"published_at": "2026-09-11",
}
)
page.show_update(manifest)
assert not page.install_button.isEnabled()
assert "签名" in page.status_label.text()
+67
View File
@@ -0,0 +1,67 @@
import json
from pathlib import Path
import subprocess
import sys
import zipfile
def make_plan(tmp_path: Path, restart_probe_exit_code: int):
from dx_productivity.update.installer import InstallPlan
current = tmp_path / "portable"
current.mkdir()
(current / "DxDesignerTools.exe").write_bytes(b"old")
staged = tmp_path / "staged.zip"
with zipfile.ZipFile(staged, "w") as archive:
archive.writestr("DxDesignerTools.exe", b"new")
backup = tmp_path / "backups"
return InstallPlan(
current_root=current,
staged_zip=staged,
backup_root=backup,
restart_command=(
sys.executable,
"-c",
f"raise SystemExit({restart_probe_exit_code})",
),
)
def test_install_plan_restores_previous_root_when_restart_probe_fails(tmp_path: Path):
from dx_productivity.update.installer import UpdateInstaller
plan = make_plan(tmp_path, restart_probe_exit_code=1)
result = UpdateInstaller().install(plan)
assert result.state == "rolled-back"
assert (plan.current_root / "DxDesignerTools.exe").read_bytes() == b"old"
assert any(plan.backup_root.iterdir())
def test_install_plan_switches_to_verified_root_on_success(tmp_path: Path):
from dx_productivity.update.installer import UpdateInstaller
plan = make_plan(tmp_path, restart_probe_exit_code=0)
result = UpdateInstaller().install(plan)
assert result.state == "installed"
assert (plan.current_root / "DxDesignerTools.exe").read_bytes() == b"new"
def test_install_plan_rejects_missing_staged_zip(tmp_path: Path):
from dx_productivity.update.installer import InstallPlan, UpdateInstaller
plan = InstallPlan(
current_root=tmp_path / "portable",
staged_zip=tmp_path / "missing.zip",
backup_root=tmp_path / "backups",
restart_command=(sys.executable, "-c", "raise SystemExit(0)"),
)
plan.current_root.mkdir()
(plan.current_root / "DxDesignerTools.exe").write_bytes(b"old")
result = UpdateInstaller().install(plan)
assert result.state == "failed"
+71
View File
@@ -0,0 +1,71 @@
import hashlib
import json
from pathlib import Path
import sys
import zipfile
def make_local_release_pair(tmp_path: Path):
from dx_productivity.update.models import UpdateManifest
old_root = tmp_path / "portable"
old_root.mkdir()
(old_root / "DxDesignerTools.exe").write_bytes(b"old")
(old_root / "version.json").write_text('{"version":"1.0.0"}', encoding="utf-8")
new_root = tmp_path / "new-release"
new_root.mkdir()
(new_root / "DxDesignerTools.exe").write_bytes(b"new")
(new_root / "version.json").write_text('{"version":"1.1.0"}', encoding="utf-8")
new_zip = tmp_path / "release-1.1.0.zip"
with zipfile.ZipFile(new_zip, "w") as archive:
for path in new_root.iterdir():
archive.write(path, path.name)
digest = hashlib.sha256(new_zip.read_bytes()).hexdigest()
manifest_path = tmp_path / "manifest.json"
manifest_path.write_text(
json.dumps(
{
"product": "yiyezhqiu-refactored",
"version": "1.1.0",
"channel": "development",
"min_supported_version": "1.0.0",
"package_url": new_zip.as_uri(),
"sha256": digest,
"release_notes": "local test",
"published_at": "2026-09-11",
}
),
encoding="utf-8",
)
return old_root, new_zip, manifest_path
def run_update_check_and_install(root: Path, manifest: Path):
from dx_productivity.update.installer import InstallPlan, UpdateInstaller
from dx_productivity.update.service import UpdateService
from dx_productivity.update.stager import UpdateStager
result = UpdateService().check(manifest.as_uri(), read_version(root), channel="development")
assert result.status == "available"
assert result.manifest is not None
staged = UpdateStager().download_and_verify(result.manifest, root.parent / "updates")
plan = InstallPlan(
current_root=root,
staged_zip=staged,
backup_root=root.parent / "backups",
restart_command=(sys.executable, "-c", "raise SystemExit(0)"),
)
return UpdateInstaller().install(plan)
def read_version(root: Path) -> str:
return json.loads((root / "version.json").read_text(encoding="utf-8"))["version"]
def test_local_manifest_updates_older_portable_copy(tmp_path: Path):
old_root, _, manifest = make_local_release_pair(tmp_path)
result = run_update_check_and_install(old_root, manifest)
assert result.state == "installed"
assert read_version(old_root) == "1.1.0"
+51
View File
@@ -0,0 +1,51 @@
import pytest
def _mapping(**overrides):
data = {
"product": "yiyezhqiu-refactored",
"version": "1.1.0",
"channel": "stable",
"min_supported_version": "1.0.0",
"package_url": "file:///release.zip",
"sha256": "a" * 64,
"release_notes": "模块迁移",
"published_at": "2026-09-11",
}
data.update(overrides)
return data
def test_manifest_parses_semver_and_rejects_wrong_product():
from dx_productivity.update.models import UpdateManifest
manifest = UpdateManifest.from_mapping(_mapping())
assert manifest.version.is_newer_than(manifest.min_supported_version)
assert manifest.is_compatible_with("1.0.0")
with pytest.raises(ValueError, match="product"):
UpdateManifest.from_mapping(_mapping(product="other-product"))
def test_semver_orders_prerelease_before_release():
from dx_productivity.update.models import SemVer
assert SemVer.parse("1.0.0-rc.1") < SemVer.parse("1.0.0")
assert SemVer.parse("1.0.0-rc.2") > SemVer.parse("1.0.0-rc.1")
@pytest.mark.parametrize("value", ["1", "1.0", "01.0.0", "v1.0.0", "1.0.0+"])
def test_semver_requires_strict_three_part_version(value):
from dx_productivity.update.models import SemVer
with pytest.raises(ValueError, match="version"):
SemVer.parse(value)
def test_manifest_rejects_invalid_digest_and_incompatible_current_version():
from dx_productivity.update.models import UpdateManifest
with pytest.raises(ValueError, match="sha256"):
UpdateManifest.from_mapping(_mapping(sha256="bad"))
manifest = UpdateManifest.from_mapping(_mapping(min_supported_version="2.0.0"))
assert manifest.is_compatible_with("1.0.0") is False
+209
View File
@@ -0,0 +1,209 @@
import base64
import json
from pathlib import Path
import zipfile
import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from dx_productivity.update import keys
from dx_productivity.update.models import SemVer, UpdateManifest
from dx_productivity.update.stager import UpdateStager, UpdateVerificationError
def test_stager_uses_the_embedded_public_key_by_default():
stager = UpdateStager()
assert stager.public_key == keys.release_public_key()
def test_stable_channel_signed_package_passes_end_to_end(tmp_path):
private_key = Ed25519PrivateKey.generate()
public_key = private_key.public_key().public_bytes(
serialization.Encoding.Raw, serialization.PublicFormat.Raw
)
package = tmp_path / "pkg.zip"
with zipfile.ZipFile(package, "w") as archive:
archive.writestr("DxDesignerTools.exe", "binary")
from dx_productivity.update.verification import sha256_file
manifest = UpdateManifest.from_mapping(
{
"product": "yiyezhqiu-refactored",
"version": "0.2.0",
"channel": "stable",
"min_supported_version": "0.1.0",
"package_url": package.as_uri(),
"sha256": sha256_file(package),
"release_notes": "",
"published_at": "2026-09-29",
"signature": base64.b64encode(
private_key.sign(package.read_bytes())
).decode("ascii"),
}
)
staged = UpdateStager(public_key=public_key).download_and_verify(
manifest, tmp_path / "updates"
)
assert staged.is_file()
def test_staged_archive_is_reused_when_digest_matches(tmp_path):
package = tmp_path / "pkg.zip"
with zipfile.ZipFile(package, "w") as archive:
archive.writestr("DxDesignerTools.exe", "binary")
from dx_productivity.update.verification import sha256_file
manifest = UpdateManifest.from_mapping(
{
"product": "yiyezhqiu-refactored",
"version": "0.2.0",
"channel": "development",
"min_supported_version": "0.1.0",
"package_url": package.as_uri(),
"sha256": sha256_file(package),
"release_notes": "",
"published_at": "2026-09-29",
}
)
destination = tmp_path / "updates"
first = UpdateStager().download_and_verify(manifest, destination)
first_mtime = first.stat().st_mtime_ns
second = UpdateStager().download_and_verify(manifest, destination)
assert second == first
assert second.stat().st_mtime_ns == first_mtime
def test_corrupt_staged_archive_is_replaced(tmp_path):
package = tmp_path / "pkg.zip"
with zipfile.ZipFile(package, "w") as archive:
archive.writestr("DxDesignerTools.exe", "binary")
from dx_productivity.update.verification import sha256_file
manifest = UpdateManifest.from_mapping(
{
"product": "yiyezhqiu-refactored",
"version": "0.2.0",
"channel": "development",
"min_supported_version": "0.1.0",
"package_url": package.as_uri(),
"sha256": sha256_file(package),
"release_notes": "",
"published_at": "2026-09-29",
}
)
destination = tmp_path / "updates"
UpdateStager().download_and_verify(manifest, destination)
(destination / "0.2.0.zip").write_text("corrupted", encoding="utf-8")
staged = UpdateStager().download_and_verify(manifest, destination)
assert staged.read_bytes() == package.read_bytes()
def test_package_url_rejects_plain_http():
with pytest.raises(ValueError, match="not allowed"):
UpdateManifest.from_mapping(
{
"product": "yiyezhqiu-refactored",
"version": "0.2.0",
"channel": "development",
"min_supported_version": "0.1.0",
"package_url": "http://intranet/pkg.zip",
"sha256": "a" * 64,
"release_notes": "",
"published_at": "2026-09-29",
}
)
def test_semver_prerelease_multidigit_compare():
assert SemVer.parse("1.0.0-rc.10") > SemVer.parse("1.0.0-rc.9")
assert SemVer.parse("1.0.0-rc.9") < SemVer.parse("1.0.0")
assert SemVer.parse("1.0.0") > SemVer.parse("1.0.0-rc.99")
def test_installer_reverifies_staged_digest(tmp_path, monkeypatch):
from dx_productivity.update.installer import InstallPlan, UpdateInstaller
current = tmp_path / "app"
current.mkdir()
(current / "DxDesignerTools.exe").write_bytes(b"old")
staged_zip = tmp_path / "staged.zip"
with zipfile.ZipFile(staged_zip, "w") as archive:
archive.writestr("DxDesignerTools.exe", "binary")
plan = InstallPlan(
current_root=current,
staged_zip=staged_zip,
backup_root=tmp_path / "backups",
restart_command=("cmd", "/c", "exit", "0"),
sha256="b" * 64,
)
result = UpdateInstaller().install(plan)
assert result.state == "failed"
assert "digest" in result.message
def test_installer_waits_for_parent_exit(tmp_path):
from dx_productivity.update import installer as installer_module
from dx_productivity.update.installer import InstallPlan, UpdateInstaller
current = tmp_path / "app"
current.mkdir()
exe = current / "DxDesignerTools.exe"
exe.write_bytes(b"old")
staged_zip = tmp_path / "staged.zip"
with zipfile.ZipFile(staged_zip, "w") as archive:
archive.writestr("DxDesignerTools.exe", "new")
plan = InstallPlan(
current_root=current,
staged_zip=staged_zip,
backup_root=tmp_path / "backups",
restart_command=("cmd", "/c", "exit", "0"),
)
called = []
def fake_wait(self, exe_path):
called.append(exe_path)
return True
monkeypatch = pytest.MonkeyPatch()
monkeypatch.setattr(
installer_module.UpdateInstaller, "_wait_for_parent_exit", fake_wait
)
result = UpdateInstaller().install(plan)
monkeypatch.undo()
assert called == [exe]
assert result.state == "installed"
assert (current / "DxDesignerTools.exe").read_bytes() == b"new"
def test_installer_rollback_failure_is_reported(tmp_path, monkeypatch):
from dx_productivity.update.installer import InstallPlan, UpdateInstaller
current = tmp_path / "app"
current.mkdir()
(current / "DxDesignerTools.exe").write_bytes(b"old")
staged_zip = tmp_path / "staged.zip"
with zipfile.ZipFile(staged_zip, "w") as archive:
archive.writestr("DxDesignerTools.exe", "new")
plan = InstallPlan(
current_root=current,
staged_zip=staged_zip,
backup_root=tmp_path / "backups",
restart_command=("cmd", "/c", "exit", "3"), # failing probe
)
result = UpdateInstaller().install(plan)
assert result.state == "rolled-back"
assert (current / "DxDesignerTools.exe").read_bytes() == b"old"
+72
View File
@@ -0,0 +1,72 @@
import json
from pathlib import Path
def write_manifest(path: Path, package_url: str, version: str = "1.1.0") -> None:
path.write_text(
json.dumps(
{
"product": "yiyezhqiu-refactored",
"version": version,
"channel": "stable",
"min_supported_version": "1.0.0",
"package_url": package_url,
"sha256": "a" * 64,
"release_notes": "模块迁移",
"published_at": "2026-09-11",
},
ensure_ascii=False,
),
encoding="utf-8",
)
def test_check_returns_available_for_file_manifest(tmp_path: Path) -> None:
from dx_productivity.update.service import UpdateService
manifest_path = tmp_path / "manifest.json"
write_manifest(manifest_path, "file:///release.zip")
result = UpdateService().check(manifest_path.as_uri(), "1.0.0")
assert result.status == "available"
assert result.manifest is not None
assert str(result.manifest.version) == "1.1.0"
def test_check_returns_up_to_date_for_equal_version(tmp_path: Path) -> None:
from dx_productivity.update.service import UpdateService
manifest_path = tmp_path / "manifest.json"
write_manifest(manifest_path, "file:///release.zip", version="1.0.0")
result = UpdateService().check(manifest_path.as_uri(), "1.0.0")
assert result.status == "up-to-date"
def test_check_returns_error_for_offline_or_malformed_source(tmp_path: Path) -> None:
from dx_productivity.update.service import UpdateService
malformed = tmp_path / "bad.json"
malformed.write_text("not-json", encoding="utf-8")
result = UpdateService().check(malformed.as_uri(), "1.0.0")
assert result.status == "error"
assert result.manifest is None
assert result.message
def test_check_filters_development_manifest_from_stable_channel(tmp_path: Path) -> None:
from dx_productivity.update.service import UpdateService
manifest_path = tmp_path / "dev.json"
write_manifest(manifest_path, "file:///release.zip")
data = json.loads(manifest_path.read_text(encoding="utf-8"))
data["channel"] = "development"
manifest_path.write_text(json.dumps(data), encoding="utf-8")
result = UpdateService().check(manifest_path.as_uri(), "1.0.0", channel="stable")
assert result.status == "incompatible"
assert "channel" in result.message
+68
View File
@@ -0,0 +1,68 @@
import base64
import hashlib
from pathlib import Path
import zipfile
import pytest
def _make_manifest(package_url: str, sha256: str, signature: str | None = None):
from dx_productivity.update.models import UpdateManifest
return UpdateManifest.from_mapping(
{
"product": "yiyezhqiu-refactored",
"version": "1.1.0",
"channel": "development" if signature is None else "stable",
"min_supported_version": "1.0.0",
"package_url": package_url,
"sha256": sha256,
"release_notes": "test",
"published_at": "2026-09-11",
**({"signature": signature} if signature is not None else {}),
}
)
def _zip(path: Path, name: str = "DxDesignerTools.exe") -> bytes:
with zipfile.ZipFile(path, "w") as archive:
archive.writestr(name, b"new")
return path.read_bytes()
def test_download_and_verify_rejects_digest_mismatch(tmp_path: Path):
from dx_productivity.update.stager import UpdateStager, UpdateVerificationError
package_path = tmp_path / "release.zip"
payload = _zip(package_path)
manifest = _make_manifest(package_path.as_uri(), "0" * 64)
with pytest.raises(UpdateVerificationError, match="sha256"):
UpdateStager().download_and_verify(manifest, tmp_path / "download")
assert not list((tmp_path / "download").glob("*.part"))
def test_download_and_verify_accepts_development_package(tmp_path: Path):
from dx_productivity.update.stager import UpdateStager
package_path = tmp_path / "release.zip"
payload = _zip(package_path)
manifest = _make_manifest(package_path.as_uri(), hashlib.sha256(payload).hexdigest())
verified = UpdateStager().download_and_verify(manifest, tmp_path / "download")
assert verified.is_file()
assert verified.read_bytes() == payload
def test_download_and_verify_rejects_zip_path_traversal(tmp_path: Path):
from dx_productivity.update.stager import UpdateStager, UpdateVerificationError
package_path = tmp_path / "unsafe.zip"
with zipfile.ZipFile(package_path, "w") as archive:
archive.writestr("../escape.txt", b"bad")
payload = package_path.read_bytes()
manifest = _make_manifest(package_path.as_uri(), hashlib.sha256(payload).hexdigest())
with pytest.raises(UpdateVerificationError, match="path"):
UpdateStager().download_and_verify(manifest, tmp_path / "download")
+19
View File
@@ -0,0 +1,19 @@
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
def test_sha256_file_and_ed25519_verification(tmp_path):
from dx_productivity.update.verification import sha256_file, verify_ed25519
payload = b"release payload"
path = tmp_path / "payload.bin"
path.write_bytes(payload)
private_key = Ed25519PrivateKey.generate()
signature = private_key.sign(payload)
assert sha256_file(path) == "d11a02dfb3d8dfdc9229678b67f948c32aabeb9e5d409434b171cd7e5275774f"
assert verify_ed25519(
private_key.public_key().public_bytes_raw(), payload, signature
)
assert not verify_ed25519(
private_key.public_key().public_bytes_raw(), b"changed", signature
)
+75
View File
@@ -0,0 +1,75 @@
Option Explicit
Dim Fso
Dim ScriptRoot
Dim CommonPath
Dim CommonText
Dim Stream
Dim TempRoot
Dim Utf8Path
Dim Actual
Dim Sequence
Dim BridgeId
Dim Op
Dim PropertyName
Dim ExpectedRefdes
Dim NewRefdes
Dim FinalRefdes
Set Fso = CreateObject("Scripting.FileSystemObject")
ScriptRoot = Fso.GetParentFolderName(WScript.ScriptFullName)
CommonPath = Fso.GetAbsolutePathName( _
Fso.BuildPath(ScriptRoot, "..\..\integration\dxdesigner795\BridgeCommon.vbs"))
Set Stream = Fso.OpenTextFile(CommonPath, 1, False, 0)
CommonText = Stream.ReadAll
Stream.Close
ExecuteGlobal CommonText
Call AssertEqual(DxToolsQuote("C:\Tools Path\DxDesignerTools.exe"), _
Chr(34) & "C:\Tools Path\DxDesignerTools.exe" & Chr(34), "quote")
Call AssertEqual(DxToolsJson(Chr(34) & Chr(92) & vbCrLf & vbTab), _
Chr(92) & Chr(34) & Chr(92) & Chr(92) & Chr(92) & "r" & _
Chr(92) & "n" & Chr(92) & "t", "json")
TempRoot = Fso.BuildPath(Fso.GetSpecialFolder(2), _
"dx-tools-vbs-" & Replace(CStr(Timer), ".", "-"))
Fso.CreateFolder TempRoot
Utf8Path = Fso.BuildPath(TempRoot, "round-trip.txt")
Call DxToolsWriteUtf8Atomic(Utf8Path, ChrW(&H81EA) & ChrW(&H5B9A) & _
ChrW(&H4F4D) & ChrW(&H53F7))
Actual = DxToolsReadUtf8(Utf8Path)
Call AssertEqual(Actual, ChrW(&H81EA) & ChrW(&H5B9A) & ChrW(&H4F4D) & _
ChrW(&H53F7), "utf8")
If Not DxToolsParseScheduleRow("1" & vbTab & "refdes" & vbTab & _
"c000001" & vbTab & "" & vbTab & "R?" & vbTab & "R1" & vbTab & _
"R1", Sequence, Op, BridgeId, PropertyName, _
ExpectedRefdes, NewRefdes, FinalRefdes) Then
Call Fail("valid schedule row")
End If
Call AssertEqual(Sequence, 1, "sequence")
Call AssertEqual(Op, "refdes", "schedule op")
Call AssertEqual(BridgeId, "c000001", "bridge id")
Call AssertEqual(ExpectedRefdes, "R?", "expected value")
If DxToolsParseScheduleRow("1" & vbTab & "c000001" & vbTab & "R?", _
Sequence, Op, BridgeId, PropertyName, _
ExpectedRefdes, NewRefdes, FinalRefdes) Then
Call Fail("malformed schedule row")
End If
Fso.DeleteFolder TempRoot, True
WScript.Echo "BridgeCommon assertions passed"
Sub AssertEqual(actualValue, expectedValue, label)
If CStr(actualValue) <> CStr(expectedValue) Then
Call Fail(label & ": expected [" & CStr(expectedValue) & _
"] got [" & CStr(actualValue) & "]")
End If
End Sub
Sub Fail(message)
WScript.Echo "FAIL: " & message
WScript.Quit 1
End Sub
+163
View File
@@ -0,0 +1,163 @@
Option Explicit
Const cmdControlPopup = 10
Dim Fso
Dim SourceRoot
Dim TempRoot
Dim SourceMenu
Dim TargetMenu
Dim MenuText
Dim Stream
Dim Scripting
Dim FakeMenuBar
Dim DxToolsCommonLoads
Dim DxToolsProbeRuns
Dim RuntimeRoot
Dim RuntimeVbsRoot
Class FakeScriptingHost
Public CurrentScriptFullName
Public ScriptFullName
End Class
Class FakeControl
Public Caption
Public OnAction
Public Controls
Private ParentControls
Private Sub Class_Initialize()
Set Controls = New FakeControlsCollection
End Sub
Public Property Set Parent(value)
Set ParentControls = value
End Property
Public Sub Delete()
ParentControls.Remove Me
End Sub
End Class
Class FakeControlsCollection
Private Items
Private Sub Class_Initialize()
Set Items = CreateObject("Scripting.Dictionary")
End Sub
Public Property Get Count()
Count = Items.Count
End Property
Public Function Add()
Dim control
Set control = New FakeControl
Set control.Parent = Me
Items.Add CStr(Items.Count + 1), control
Set Add = control
End Function
Public Property Get Item(index)
Set Item = Items(CStr(index))
End Property
Public Sub Remove(target)
Dim index
Dim found
Dim count
count = Items.Count
found = 0
For index = 1 To count
If Items(CStr(index)) Is target Then found = index
Next
If found = 0 Then Exit Sub
For index = found To count - 1
Set Items(CStr(index)) = Items(CStr(index + 1))
Next
Items.Remove CStr(count)
End Sub
End Class
Function CommandBars(name)
If name <> "Sheet Menu Bar" Then Call Fail("unexpected menu bar")
Set CommandBars = FakeMenuBar
End Function
Set Fso = CreateObject("Scripting.FileSystemObject")
SourceRoot = Fso.GetAbsolutePathName(Fso.BuildPath( _
Fso.GetParentFolderName(WScript.ScriptFullName), _
"..\..\integration\dxdesigner795"))
TempRoot = Fso.BuildPath(Fso.GetSpecialFolder(2), _
"dx-tools-menu-" & Replace(CStr(Timer), ".", "-"))
Fso.CreateFolder TempRoot
SourceMenu = Fso.BuildPath(SourceRoot, "MenuAdd.vbs")
TargetMenu = Fso.BuildPath(TempRoot, "MenuAdd.vbs")
Fso.CopyFile SourceMenu, TargetMenu
Call Fso.CreateTextFile(Fso.BuildPath(TempRoot, "DesignBridge.vbs"), True).Close
Call Fso.CreateTextFile(Fso.BuildPath(TempRoot, "DxDesignerTools.exe"), True).Close
RuntimeRoot = Fso.BuildPath(TempRoot, "_runtime")
RuntimeVbsRoot = Fso.BuildPath(RuntimeRoot, "vbs")
Fso.CreateFolder RuntimeRoot
Fso.CreateFolder RuntimeVbsRoot
Set Stream = Fso.CreateTextFile( _
Fso.BuildPath(RuntimeVbsRoot, "BridgeCommon.vbs"), True)
Stream.WriteLine "DxToolsCommonLoads = DxToolsCommonLoads + 1"
Stream.Close
Set Stream = Fso.CreateTextFile( _
Fso.BuildPath(TempRoot, "CompatibilityProbe.vbs"), True)
Stream.WriteLine "Sub DxToolsRunCompatibilityProbe()"
Stream.WriteLine " DxToolsProbeRuns = DxToolsProbeRuns + 1"
Stream.WriteLine "End Sub"
Stream.Close
Set Scripting = New FakeScriptingHost
Scripting.CurrentScriptFullName = TargetMenu
Scripting.ScriptFullName = ""
Set FakeMenuBar = New FakeControl
Set Stream = Fso.OpenTextFile(TargetMenu, 1, False, 0)
MenuText = Stream.ReadAll
Stream.Close
MenuText = Replace(MenuText, ".Controls.Add(cmdControlPopup)", _
".Controls.Add")
ExecuteGlobal MenuText
Call AssertEqual(DxToolsHome, TempRoot, "portable root")
Call AssertEqual(DxToolsScriptPathSource, _
"Scripting.CurrentScriptFullName", "path source")
Call AssertEqual(FakeMenuBar.Controls.Count, 1, "top menu count")
Call AssertEqual(FakeMenuBar.Controls.Item(1).Controls.Count, 7, _
"command count")
Call AssertEqual(FakeMenuBar.Controls.Item(1).Controls.Item(1).OnAction, _
"DxToolsOpenRefDes", "refdes action")
Call AssertEqual(FakeMenuBar.Controls.Item(1).Controls.Item(2).OnAction, _
"DxToolsOpenPropertyChange", "property change action")
Call AssertEqual(FakeMenuBar.Controls.Item(1).Controls.Item(5).OnAction, _
"DxToolsOpenBom", "bom action")
Call DxToolsInstallMenu()
Call AssertEqual(FakeMenuBar.Controls.Count, 1, "idempotent menu count")
DxToolsCommonLoads = 0
DxToolsProbeRuns = 0
Call DxToolsOpenCompatibility()
Call DxToolsOpenCompatibility()
Call AssertEqual(DxToolsCommonLoads, 1, "common script load count")
Call AssertEqual(DxToolsProbeRuns, 2, "probe execution count")
Fso.DeleteFolder TempRoot, True
WScript.Echo "MenuAdd assertions passed"
Sub AssertEqual(actualValue, expectedValue, label)
If CStr(actualValue) <> CStr(expectedValue) Then
Call Fail(label & ": expected [" & CStr(expectedValue) & _
"] got [" & CStr(actualValue) & "]")
End If
End Sub
Sub Fail(message)
WScript.Echo "FAIL: " & message
WScript.Quit 1
End Sub
+256
View File
@@ -0,0 +1,256 @@
Option Explicit
Dim Fso
Dim ScriptRoot
Dim IntegrationRoot
Dim TempRoot
Dim ObjectMap
Dim OriginalsMap
Dim Component
Dim State
Dim DxToolsHome
Class FakeAttribute
Private CurrentValue
Private CurrentVisible
Public Property Get Value()
Value = CurrentValue
End Property
Public Property Let Value(newValue)
If CStr(newValue) = CStr(FailValue) Then
Err.Raise vbObjectError + 901, "FakeAttribute", "injected failure"
End If
CurrentValue = CStr(newValue)
End Property
Public Property Get Visible()
Visible = CurrentVisible
End Property
Public Property Let Visible(newValue)
CurrentVisible = newValue
End Property
Public Sub Initialize(value, visible)
CurrentValue = CStr(value)
CurrentVisible = visible
FailValue = Chr(0)
End Sub
Public FailValue
End Class
Class FakeAttributes
Private Items
Public Sub Initialize()
Set Items = CreateObject("Scripting.Dictionary")
End Sub
Public Sub AddAttribute(name, value, visible)
Dim attribute
Set attribute = New FakeAttribute
Call attribute.Initialize(value, visible)
If Items.Exists(LCase(CStr(name))) Then
Items.Remove LCase(CStr(name))
End If
Items.Add LCase(CStr(name)), attribute
End Sub
Public Property Get Item(name)
If Not Items.Exists(LCase(CStr(name))) Then
Err.Raise vbObjectError + 902, "FakeAttributes", _
"attribute not found: " & CStr(name)
End If
Set Item = Items(LCase(CStr(name)))
End Property
End Class
Class FakeComponent
Private CurrentRefdes
Public FailTarget
Public Attributes
Public Property Get Refdes()
Refdes = CurrentRefdes
End Property
Public Property Let Refdes(value)
If CStr(value) = CStr(FailTarget) Then
Err.Raise vbObjectError + 901, "FakeComponent", "injected failure"
End If
CurrentRefdes = CStr(value)
End Property
Public Sub Initialize(value)
CurrentRefdes = CStr(value)
FailTarget = Chr(0)
Set Attributes = New FakeAttributes
Call Attributes.Initialize()
End Sub
End Class
Set Fso = CreateObject("Scripting.FileSystemObject")
ScriptRoot = Fso.GetParentFolderName(WScript.ScriptFullName)
IntegrationRoot = Fso.GetAbsolutePathName(Fso.BuildPath( _
ScriptRoot, "..\..\integration\dxdesigner795"))
Call LoadGlobal(Fso.BuildPath(IntegrationRoot, "BridgeCommon.vbs"))
Call LoadGlobal(Fso.BuildPath(IntegrationRoot, "core\Transaction.vbs"))
Call LoadGlobal(Fso.BuildPath(IntegrationRoot, "core\Mailbox.vbs"))
TempRoot = Fso.BuildPath(Fso.GetSpecialFolder(2), _
"dx-tools-bridge-" & Replace(CStr(Timer), ".", "-"))
Fso.CreateFolder TempRoot
DxToolsHome = TempRoot & "\Tool Root"
Call AssertEqual(DxBridgeUiCommand(TempRoot, "bom"), _
DxToolsQuote(DxToolsHome & "\DxDesignerTools.exe") & _
" ui --request " & DxToolsQuote(TempRoot & "\request.json") & _
" --feature " & DxToolsQuote("bom"), "ui command with feature")
Call AssertEqual(DxBridgeUiCommand(TempRoot, ""), _
DxToolsQuote(DxToolsHome & "\DxDesignerTools.exe") & _
" ui --request " & DxToolsQuote(TempRoot & "\request.json"), _
"ui command without feature")
Set ObjectMap = CreateObject("Scripting.Dictionary")
Set OriginalsMap = CreateObject("Scripting.Dictionary")
Set Component = New FakeComponent
Component.Initialize "R?"
ObjectMap.Add "c000001", Component
Call WriteTransaction(TempRoot, "refdes", "", "R?", "R1")
State = DxProcessApply(TempRoot, "run-vbs", "snapshot-vbs", _
ObjectMap, OriginalsMap)
Call AssertEqual(State, "applied", "successful state")
Call AssertEqual(Component.Refdes, "R1", "successful refdes")
Call AssertContains(DxToolsReadUtf8(Fso.BuildPath( _
TempRoot, "apply-status.json")), """state"": ""applied""", _
"successful status")
Component.Initialize "R?"
Component.FailTarget = "R9"
Call WriteTransaction(TempRoot, "refdes", "", "R?", "R9")
State = DxProcessApply(TempRoot, "run-vbs", "snapshot-vbs", _
ObjectMap, OriginalsMap)
Call AssertEqual(State, "rolled-back", "rollback state")
Call AssertEqual(Component.Refdes, "R?", "rollback refdes")
Component.Initialize "R8"
Component.FailTarget = Chr(0)
Call WriteTransaction(TempRoot, "refdes", "", "R?", "R2")
State = DxProcessApply(TempRoot, "run-vbs", "snapshot-vbs", _
ObjectMap, OriginalsMap)
Call AssertEqual(State, "rejected", "stale state")
Call AssertEqual(Component.Refdes, "R8", "stale refdes unchanged")
Component.Initialize "R8"
Component.Attributes.AddAttribute "Value", "10K", "1"
Call WriteTransaction(TempRoot, "property", "Value", "10K", "47K")
State = DxProcessApply(TempRoot, "run-vbs", "snapshot-vbs", _
ObjectMap, OriginalsMap)
Call AssertEqual(State, "applied", "property state")
Call AssertEqual(Component.Attributes.Item("Value").Value, "47K", _
"property value written")
Component.Initialize "R8"
Component.Attributes.AddAttribute "Part Name", "RES", "1"
Call WriteTransaction(TempRoot, "visibility", "Part Name", "1", "0")
State = DxProcessApply(TempRoot, "run-vbs", "snapshot-vbs", _
ObjectMap, OriginalsMap)
Call AssertEqual(State, "applied", "visibility state")
Call AssertEqual(DxBridgeNormalizeVisible( _
Component.Attributes.Item("Part Name").Visible), "0", _
"visibility written")
Component.Initialize "R8"
Component.Attributes.AddAttribute "Missing", "x", "1"
Call WriteTransaction(TempRoot, "property", "Absent", "x", "y")
State = DxProcessApply(TempRoot, "run-vbs", "snapshot-vbs", _
ObjectMap, OriginalsMap)
Call AssertEqual(State, "rejected", "missing attribute rejected")
Call TestClaimAndCleanup
Fso.DeleteFolder TempRoot, True
WScript.Echo "DesignBridge transaction assertions passed"
Sub TestClaimAndCleanup
Dim runsRoot
Dim index
Dim folderPath
Dim sourcePath
Dim claimPath
runsRoot = Fso.BuildPath(TempRoot, "runs")
Fso.CreateFolder runsRoot
For index = 1 To 25
folderPath = Fso.BuildPath(runsRoot, "run-" & _
Right("00" & CStr(index), 3))
Fso.CreateFolder folderPath
Next
Call DxBridgeCleanupRuns(runsRoot, "run-025")
Call AssertEqual(Fso.GetFolder(runsRoot).SubFolders.Count, 20, _
"run cleanup keeps 20")
Call AssertEqual(Fso.FolderExists(Fso.BuildPath(runsRoot, "run-025")), _
True, "run cleanup keeps current")
sourcePath = Fso.BuildPath(TempRoot, "claim-source.tsv")
claimPath = Fso.BuildPath(TempRoot, "claim-target.tsv")
Call Fso.CreateTextFile(sourcePath, True, False).Close
Call AssertEqual(DxBridgeClaimFile(Fso, sourcePath, claimPath), _
True, "claim moves source")
Call AssertEqual(Fso.FileExists(sourcePath), False, "claim removes source")
Call AssertEqual(Fso.FileExists(claimPath), True, "claim creates target")
End Sub
Sub WriteTransaction(root, op, propertyName, expectedValue, newValue)
Dim resultPath
Dim backupPath
Dim requestPath
Dim resultStream
Dim requestText
resultPath = Fso.BuildPath(root, "result.tsv")
backupPath = Fso.BuildPath(root, "backup.json")
requestPath = Fso.BuildPath(root, "apply-request.json")
Set resultStream = Fso.CreateTextFile(resultPath, True, False)
resultStream.WriteLine "1" & vbTab & op & vbTab & "c000001" & vbTab & _
propertyName & vbTab & expectedValue & vbTab & newValue & vbTab & _
newValue
resultStream.Close
Call Fso.CreateTextFile(backupPath, True, False).Close
requestText = "{" & vbCrLf & _
" ""format_version"": 2," & vbCrLf & _
" ""run_id"": ""run-vbs""," & vbCrLf & _
" ""snapshot_id"": ""snapshot-vbs""," & vbCrLf & _
" ""backup_path"": """ & DxToolsJson(backupPath) & """," & vbCrLf & _
" ""schedule_sha256"": """ & DxToolsSha256File(resultPath) & _
"""" & vbCrLf & "}" & vbCrLf
Call DxToolsWriteUtf8Atomic(requestPath, requestText)
End Sub
Sub LoadGlobal(path)
Dim stream
Dim text
Set stream = Fso.OpenTextFile(path, 1, False, 0)
text = stream.ReadAll
stream.Close
ExecuteGlobal text
End Sub
Sub AssertEqual(actualValue, expectedValue, label)
If CStr(actualValue) <> CStr(expectedValue) Then
Call Fail(label & ": expected [" & CStr(expectedValue) & _
"] got [" & CStr(actualValue) & "]")
End If
End Sub
Sub AssertContains(actualValue, expectedValue, label)
If InStr(CStr(actualValue), CStr(expectedValue)) = 0 Then
Call Fail(label & ": missing [" & CStr(expectedValue) & "]")
End If
End Sub
Sub Fail(message)
WScript.Echo "FAIL: " & message
WScript.Quit 1
End Sub
+171
View File
@@ -0,0 +1,171 @@
Option Explicit
Const VDM_COMP = 1
Const VD_SELECTED = 2
Const SHORT_NAME = 3
Dim Fso
Dim Shell
Dim ScriptRoot
Dim TempRoot
Dim ObjectMap
Dim OriginalMap
Dim RunRoot
Dim RunId
Dim SnapshotId
Dim Component
Dim ParentBlock
Dim Application
Dim ActiveView
Dim RequestText
Class FakeParentBlock
Public Name
Public SheetNum
End Class
Class FakeComponent
Public Refdes
Public UID
Public Parent
Public X
Public Y
Public PartNumber
Public Value
Public ComponentName
Public Function GetName(kind)
GetName = ComponentName
End Function
End Class
Class FakeDesignNames
Public Function GetItem(index)
GetItem = "Design-A"
End Function
End Class
Class FakeProjectData
Public Function GetiCDBDesigns()
Set GetiCDBDesigns = New FakeDesignNames
End Function
Public Function GetiCDBDesignRootBlock(name)
GetiCDBDesignRootBlock = "TOP"
End Function
End Class
Class FakeApplicationHost
Public TheComponent
Public ProjectPath
Public Function GetProjectData()
Set GetProjectData = New FakeProjectData
End Function
Public Function DesignComponents(a, b, c, d, e)
Dim values(0)
Set values(0) = TheComponent
DesignComponents = values
End Function
End Class
Class FakeBlock
Public SheetNum
End Class
Class FakeActiveView
Public TheComponent
Public Block
Public Function Query(a, b)
Dim values(0)
Set values(0) = TheComponent
Query = values
End Function
End Class
Set Fso = CreateObject("Scripting.FileSystemObject")
Set Shell = CreateObject("WScript.Shell")
ScriptRoot = Fso.GetParentFolderName(WScript.ScriptFullName)
Call LoadGlobal(Fso.GetAbsolutePathName(Fso.BuildPath( _
ScriptRoot, "..\..\integration\dxdesigner795\BridgeCommon.vbs")))
Call LoadGlobal(Fso.GetAbsolutePathName(Fso.BuildPath( _
ScriptRoot, "..\..\integration\dxdesigner795\core\Snapshot.vbs")))
TempRoot = Fso.BuildPath(Fso.GetSpecialFolder(2), _
"dx-tools-export-" & Replace(CStr(Timer), ".", "-"))
Fso.CreateFolder TempRoot
Shell.Environment("PROCESS")("LOCALAPPDATA") = TempRoot
Set ParentBlock = New FakeParentBlock
ParentBlock.Name = "ROOT"
ParentBlock.SheetNum = 3
Set Component = New FakeComponent
Component.Refdes = "R?"
Component.UID = "uid-1"
Set Component.Parent = ParentBlock
Component.X = 12.5
Component.Y = 42.25
Component.PartNumber = "PN-1"
Component.Value = "10K"
Component.ComponentName = "R1"
Set Application = New FakeApplicationHost
Set Application.TheComponent = Component
Application.ProjectPath = "C:\Projects\board.prj"
Set ActiveView = New FakeActiveView
Set ActiveView.TheComponent = Component
Set ActiveView.Block = New FakeBlock
ActiveView.Block.SheetNum = 3
Set ObjectMap = CreateObject("Scripting.Dictionary")
Set OriginalMap = CreateObject("Scripting.Dictionary")
If Not DxExportSnapshot(ObjectMap, OriginalMap, RunRoot, RunId, _
SnapshotId) Then
Call Fail("snapshot export returned false")
End If
Call AssertEqual(ObjectMap.Count, 1, "object count")
RequestText = DxToolsReadUtf8(Fso.BuildPath(RunRoot, "request.json"))
Call AssertContains(RequestText, """bridge_id"": ""c000001""", "bridge id")
Call AssertContains(RequestText, """stable_uid"": ""uid-1""", "stable uid")
Call AssertContains(RequestText, """sheet_number"": 3", "sheet number")
Call AssertContains(RequestText, """selected"": true", "selected")
Call AssertContains(RequestText, """current_sheet"": true", "current sheet")
Call AssertContains(RequestText, """x"": ""12.5""", "x coordinate")
Call AssertContains(RequestText, """format_version"": 2", "format version")
Call AssertContains(RequestText, """attributes"": []", "attributes field")
Call AssertContains(RequestText, """nets"": []", "nets field")
Call AssertContains(RequestText, """selected_nets"": []", "selected nets field")
Call AssertContains(RequestText, """locked"": false", "locked field")
Fso.DeleteFolder TempRoot, True
WScript.Echo "RefDes export assertions passed"
Sub LoadGlobal(path)
Dim stream
Dim text
Set stream = Fso.OpenTextFile(path, 1, False, 0)
text = stream.ReadAll
stream.Close
ExecuteGlobal text
End Sub
Sub AssertEqual(actualValue, expectedValue, label)
If CStr(actualValue) <> CStr(expectedValue) Then
Call Fail(label & ": expected [" & CStr(expectedValue) & _
"] got [" & CStr(actualValue) & "]")
End If
End Sub
Sub AssertContains(actualValue, expectedValue, label)
If InStr(CStr(actualValue), CStr(expectedValue)) = 0 Then
Call Fail(label & ": missing [" & CStr(expectedValue) & "]")
End If
End Sub
Sub Fail(message)
WScript.Echo "FAIL: " & message
WScript.Quit 1
End Sub