Files
dxdesigner-part-replacement/tests/integration/test_automatic_replacement_regression.py
T

485 lines
20 KiB
Python

import importlib.util
import inspect
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import call, patch
ROOT = Path(__file__).resolve().parents[2]
RUNTIME = ROOT / "integration" / "dxdesigner795"
SPEC = importlib.util.spec_from_file_location(
"native", ROOT / "src" / "dx_productivity" / "trial_task_center" / "native_helper.py"
)
native = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(native)
FAKES = r"""
Class TestPoint
Public X, Y
End Class
Class TestAttribute
Public Name, Value, InstanceValue, Font, Size, Visible, IgnoreColor
Private ColorValue, OrientationValue, Point
Private Sub Class_Initialize()
Set Point = New TestPoint
Point.X = 0
Point.Y = 0
ColorValue = 0
IgnoreColor = False
OrientationValue = 0
End Sub
Public Property Get Color
Color = ColorValue
End Property
Public Property Let Color(ByVal NewValue)
If Not IgnoreColor Then ColorValue = NewValue
End Property
Public Property Get Orientation
Orientation = OrientationValue
End Property
Public Property Let Orientation(ByVal NewValue)
If NewValue <> OrientationValue Then
Point.X = Point.X - 6
Point.Y = Point.Y + 8
End If
OrientationValue = NewValue
End Property
Public Function GetLocation()
Set GetLocation = Point
End Function
Public Sub SetLocation(ByVal LocationX, ByVal LocationY)
Point.X = LocationX
Point.Y = LocationY
End Sub
End Class
Class TestComponent
Public UID, Refdes, Orientation, Scale, LocationX, LocationY
Public Function GetLocation()
Dim Point
Set Point = New TestPoint
Point.X = LocationX
Point.Y = LocationY
Set GetLocation = Point
End Function
End Class
Class TestView
Public Components, Block
Public Function Query(ByVal Flags, ByVal Selection)
Set Query = Components
End Function
Public Function GetName(ByVal Mode)
GetName = "Main"
End Function
End Class
Class TestBlock
Public SheetNum
End Class
Class TestProjectData
Public Function GetProjectFilePath()
GetProjectFilePath = "C:\test\project.prj"
End Function
End Class
Class TestApplication
Public ActiveView
Public Function GetProjectData()
Set GetProjectData = New TestProjectData
End Function
End Class
Function StyleRecord()
Dim Record
Set Record = CreateObject("Scripting.Dictionary")
Record.Add "name", "Value"
Record.Add "x", "103"
Record.Add "y", "204"
Record.Add "color", "4"
Record.Add "font", "0"
Record.Add "size", "12"
Record.Add "orientation", "2"
Record.Add "visible", "3"
Set StyleRecord = Record
End Function
Sub Require(ByVal Condition, ByVal Message)
If Not Condition Then Err.Raise 500, "Regression", Message
End Sub
"""
class NativeTests(unittest.TestCase):
def test_native_command_does_not_use_physical_mouse_fallback(self):
source = inspect.getsource(native.run_native)
self.assertIn("replacement_command_from_resources(executable)", source)
self.assertNotIn("win32api.SetCursorPos", source)
self.assertNotIn("mouse_event", source)
self.assertNotIn("win32gui.SetCursorPos(screen_point)", source)
def test_snapshot_batch_is_reselected_before_the_strict_selection_gate(self):
app = object()
api = object()
metadata = ["M"]
first = type("Component", (), {"UID": "wanted"})()
other = type("Component", (), {"UID": "other"})()
records = [["C", "wanted"]]
with patch.object(native, "check_context", side_effect=([first, other], [first, other])) as check:
with patch.object(native, "selection") as select:
result = native.select_snapshot_batch(app, api, metadata, records)
self.assertEqual(result, [first, other])
self.assertEqual(check.call_args_list[0], call(app, api, metadata, records, require_selection=False))
self.assertEqual(check.call_args_list[1], call(app, api, metadata, records))
self.assertEqual(select.call_args_list, [call(first, True), call(other, False)])
def test_snapshot_escape_format(self):
self.assertEqual(native.decode("a%0009b%000Ac%0025"), "a\tb\nc%")
self.assertEqual(native.decode("%0025000A"), "%000A")
self.assertEqual(native.decode("emoji:%D83D%DE00"), "emoji:\U0001f600")
for malformed in ("%D83D", "%DE00", "%D83Dtext"):
with self.subTest(malformed=malformed), self.assertRaises(ValueError):
native.decode(malformed)
def test_library_unique_exact_match(self):
row = (object(), ["Resistors", "R0805", "Discrete:RES"])
self.assertIs(native.exact_target([row], "R0805"), row)
def test_library_waits_for_an_exact_target_and_stable_rows(self):
target = (object(), ["Resistors", "R0805", "Discrete:RES"])
states = [[], [(object(), ["Resistors", "OTHER", "Discrete:RES"])], [target]]
def rows():
return states.pop(0) if len(states) > 1 else states[0]
self.assertEqual(
native.wait_for_library_rows(rows, "R0805", timeout=1, stable_for=0, poll_interval=0),
[target],
)
def test_multislot_symbol_suffix_must_be_within_target_slots(self):
self.assertTrue(native.target_symbol_matches("Discrete:RES", "Discrete:RES", 4))
self.assertTrue(native.target_symbol_matches("Discrete:RES.4", "Discrete:RES", 4))
self.assertFalse(native.target_symbol_matches("Discrete:RES.5", "Discrete:RES", 4))
self.assertFalse(native.target_symbol_matches("Discrete:OTHER.1", "Discrete:RES", 4))
def test_pin_number_promotion_covers_every_target_slot(self):
component = type("Component", (), {"UID": "uid"})()
pin = type("Pin", (), {"Component": component, "Number": "1"})()
item = type("PinItem", (), {"_oleobj_": object()})()
block = unittest.mock.Mock()
view = type("View", (), {"Block": block, "Query": lambda self, *_args: [item]})()
app = type("Application", (), {"ActiveView": view})()
api = type("Api", (), {"IVdCmpPin": staticmethod(lambda _item: pin)})()
with patch.object(native, "components_on_sheet", return_value=[component]), patch.object(native, "selection") as select:
promoted = native.promote_pin_numbers(app, api, ["uid"], 3)
self.assertEqual(block.PromoteSymbolNumbers.call_args_list, [call(1, 1), call(1, 2), call(1, 3)])
self.assertEqual(promoted, [{"uid": "uid", "number": "1"}])
self.assertEqual(select.call_args_list, [call(component, True), call(component, False)])
def test_part_label_is_only_required_by_part_label_value_mode(self):
component = type("Component", (), {"UID": "uid", "Refdes": "R1"})()
records = [["C", "uid", "R1"]]
def value(_component, name):
return {"Part Number": "NEW", "Part Name": "RES", "Part Label": ""}[name]
with patch.object(native, "attribute_value", side_effect=value):
self.assertEqual(native.replacement_matches([component], records, "NEW", False), ["uid"])
with self.assertRaisesRegex(ValueError, "Part Label readback failed"):
native.replacement_matches([component], records, "NEW", True)
self.assertEqual(native.snapshot_value_mode(["M", "project", "OLD", "NEW", "sheet"]), "part_label")
self.assertEqual(native.snapshot_value_mode(["M", "project", "OLD", "NEW", "sheet", "custom"]), "custom")
def test_replace_symbol_menu_title_supports_localized_accelerators(self):
self.assertTrue(native.is_replace_symbol_title("替换符号(&R)..."))
self.assertTrue(native.is_replace_symbol_title("Replace &Symbol..."))
self.assertFalse(native.is_replace_symbol_title("符号更新(&U)"))
def test_native_error_sidecar_is_written_and_cleared(self):
with tempfile.TemporaryDirectory() as directory:
snapshot = Path(directory) / "snapshot.tsv"
error_path = Path(str(snapshot) + ".native.error.txt")
native.save_report(snapshot, {"ok": False, "error": "focus failed"})
self.assertEqual(error_path.read_text(encoding="utf-8"), "focus failed")
native.save_report(snapshot, {"ok": True})
self.assertFalse(error_path.exists())
def test_failed_atomic_report_publish_preserves_previous_report(self):
with tempfile.TemporaryDirectory() as directory:
snapshot = Path(directory) / "snapshot.tsv"
report_path = Path(str(snapshot) + ".native.json")
report_path.write_text('{"stage":"previous"}', encoding="utf-8")
with patch.object(native.os, "replace", side_effect=OSError("locked")):
with self.assertRaises(OSError):
native.save_report(snapshot, {"stage": "replacement", "ok": False})
self.assertEqual(report_path.read_text(encoding="utf-8"), '{"stage":"previous"}')
self.assertEqual(tuple(report_path.parent.glob(f".{report_path.name}.*.tmp")), ())
def test_library_ambiguous_gate_is_rejected(self):
row = (None, ["Resistors", "R0805", "Discrete:RES"])
with self.assertRaises(ValueError):
native.exact_target([row, row], "R0805")
def test_library_missing_or_wrong_part_is_rejected(self):
for rows in ([], [(None, ["Resistors", "R08050", "Discrete:RES"])]):
with self.subTest(rows=rows), self.assertRaises(ValueError):
native.exact_target(rows, "R0805")
def test_library_blank_symbol_is_rejected(self):
with self.assertRaises(ValueError):
native.exact_target([(None, ["Resistors", "R0805", ""])], "R0805")
def test_snapshot_duplicate_uid_is_rejected(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "snapshot.tsv"
path.write_text("M\tproject\told\tnew\tsheet\n" + "C\tuid\tR1\t0\t0\t0\t1\tnet\n" * 2)
with self.assertRaises(ValueError):
native.read_snapshot(path)
def test_snapshot_accepts_explicit_part_label_value_policy(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "snapshot.tsv"
path.write_text("M\tproject\told\tnew\tsheet\tpart_label\nC\tuid\tR1\t0\t0\t0\t1\tnet\n")
metadata, components = native.read_snapshot(path)
self.assertEqual(metadata[5], "part_label")
self.assertEqual(components[0][1], "uid")
def test_no_op_rule_is_rejected(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "snapshot.tsv"
path.write_text("M\tproject\tSAME\tsame\tsheet\nC\tuid\tR1\t0\t0\t0\t1\tnet\n")
with self.assertRaises(ValueError):
native.read_snapshot(path)
class VBScriptTests(unittest.TestCase):
def test_old_unassigned_pins_accept_target_numbers_only_with_same_network(self):
self.run_vbs('Require QPConnectionsMatch("1|500|550|NET1|VCC" & vbLf, "|500|550|NET1|VCC" & vbLf), "unassigned source blocked"')
def test_assigned_pin_number_changes_are_rejected(self):
self.run_vbs('Require Not QPConnectionsMatch("2|500|550|NET1|VCC" & vbLf, "1|500|550|NET1|VCC" & vbLf), "assigned pin number changed"')
def test_unassigned_target_or_changed_net_is_rejected(self):
self.run_vbs('Require Not QPConnectionsMatch("|500|550|NET1|VCC" & vbLf, "|500|550|NET1|VCC" & vbLf), "target remains unassigned"\nRequire Not QPConnectionsMatch("1|500|550|NET2|GND" & vbLf, "|500|550|NET1|VCC" & vbLf), "net changed"')
def test_unassigned_pins_reject_geometry_and_net_identity_changes(self):
self.run_vbs('Require Not QPConnectionsMatch("1|1330|1170|NEWUID|SYS_RESET_N" & vbLf & "2|1330|1140|OTHERUID|GND" & vbLf, "|1328|1144|OLDUID|GND" & vbLf & "|1328|1174|OLDUID2|SYS_RESET_N" & vbLf), "network names alone falsely proved pin mapping"')
def test_missing_old_value_gets_hidden_style(self):
self.run_vbs("""Dim Attr, Style, Original
Set Attr = New TestAttribute
Set Original = StyleRecord()
QPRestoreDisplay Attr, Original, "R1"
Set Style = QPHiddenValueStyle(Attr)
Require Style("name") = "Value" And Style("visible") = "0", "new value is not hidden"
Require Style("x") = Original("x") And Style("y") = Original("y"), "fallback location changed"
""")
def test_rollback_snapshot_ignores_attribute_enumeration_order(self):
self.run_vbs('Require QPSortSnapshotLines("B" & vbCrLf & "A" & vbCrLf) = QPSortSnapshotLines("A" & vbCrLf & "B" & vbCrLf), "unstable rollback fingerprint"')
def test_final_display_readback_rejects_later_drift(self):
self.run_vbs("""Dim Attr, Record, Failure
Set Attr = New TestAttribute
Set Record = StyleRecord()
QPRestoreDisplay Attr, Record, "R1"
Attr.SetLocation 999, 999
On Error Resume Next
QPVerifyDisplay Attr, Record, "R1"
Failure = Err.Number
Err.Clear
On Error GoTo 0
Require Failure <> 0, "later display drift falsely passed"
""")
def test_attribute_coordinate_readback_accepts_ten_unit_grid_drift(self):
self.run_vbs("""Dim Attr, Record
Set Attr = New TestAttribute
Set Record = StyleRecord()
QPRestoreDisplay Attr, Record, "R1"
Attr.SetLocation 113, 194
QPVerifyDisplay Attr, Record, "R1"
""")
def test_attribute_coordinate_readback_rejects_larger_drift_with_context(self):
self.run_vbs("""Dim Attr, Record, Failure, Description
Set Attr = New TestAttribute
Set Record = StyleRecord()
Record("name") = "Part Label"
Record.Add "uid", "uid"
QPRestoreDisplay Attr, Record, "R1"
Attr.SetLocation 114, 204
On Error Resume Next
QPVerifyDisplay Attr, Record, "R1"
Failure = Err.Number
Description = Err.Description
Err.Clear
On Error GoTo 0
Require Failure <> 0, "attribute drift beyond tolerance falsely passed"
Require InStr(Description, "Part Label") > 0, "attribute name missing from failure"
Require InStr(Description, "refdes=R1") > 0, "refdes missing from failure"
Require InStr(Description, "uid=uid") > 0, "uid missing from failure"
Require InStr(Description, "x=103->114") > 0, "coordinate difference missing from failure"
""")
def test_component_coordinate_readback_accepts_ten_unit_grid_drift(self):
self.run_vbs("""Dim Comp, Record
Set Comp = New TestComponent
Comp.UID = "uid": Comp.Refdes = "R1": Comp.Orientation = 0: Comp.Scale = 1
Comp.LocationX = 110: Comp.LocationY = 190
Set Record = CreateObject("Scripting.Dictionary")
Record.Add "uid", "uid": Record.Add "refdes", "R1"
Record.Add "x", "100": Record.Add "y", "200"
Record.Add "orientation", "0": Record.Add "scale", "1"
QPVerifyTransform Comp, Record
""")
def test_component_coordinate_readback_rejects_more_than_ten_units(self):
self.run_vbs("""Dim Comp, Record, Failure
Set Comp = New TestComponent
Comp.UID = "uid": Comp.Refdes = "R1": Comp.Orientation = 0: Comp.Scale = 1
Comp.LocationX = 111: Comp.LocationY = 200
Set Record = CreateObject("Scripting.Dictionary")
Record.Add "uid", "uid": Record.Add "refdes", "R1"
Record.Add "x", "100": Record.Add "y", "200"
Record.Add "orientation", "0": Record.Add "scale", "1"
On Error Resume Next
QPVerifyTransform Comp, Record
Failure = Err.Number
Err.Clear
On Error GoTo 0
Require Failure <> 0, "component drift beyond tolerance falsely passed"
""")
def test_component_orientation_readback_remains_strict(self):
self.run_vbs("""Dim Comp, Record, Failure
Set Comp = New TestComponent
Comp.UID = "uid": Comp.Refdes = "R1": Comp.Orientation = 1: Comp.Scale = 1
Comp.LocationX = 100: Comp.LocationY = 200
Set Record = CreateObject("Scripting.Dictionary")
Record.Add "uid", "uid": Record.Add "refdes", "R1"
Record.Add "x", "100": Record.Add "y", "200"
Record.Add "orientation", "0": Record.Add "scale", "1"
On Error Resume Next
QPVerifyTransform Comp, Record
Failure = Err.Number
Err.Clear
On Error GoTo 0
Require Failure <> 0, "orientation mismatch falsely passed"
""")
def run_vbs(self, body):
source = (RUNTIME / "QuickPartReplace.vbs").read_text(encoding="utf-8-sig")
header = source[:source.index("Set QP_Fso =")]
routines = source[source.index("Sub QPMain()") :]
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "regression.vbs"
script = header + '\nSet QP_Fso = CreateObject("Scripting.FileSystemObject")\n'
script += 'QP_Root = "' + directory + '"\n' + body + '\nWScript.Echo "PASS"\nWScript.Quit 0\n' + FAKES + routines
path.write_text(script, encoding="utf-8")
result = subprocess.run(["cscript.exe", "//nologo", str(path)], capture_output=True, timeout=15)
self.assertEqual(result.returncode, 0, (result.stdout + result.stderr).decode(errors="replace"))
self.assertIn(b"PASS", result.stdout)
def test_display_restore_and_readback(self):
self.run_vbs("""Dim Attr, Record
Set Attr = New TestAttribute
Set Record = StyleRecord()
QPRestoreDisplay Attr, Record, "R1"
Require Attr.Color = 4 And Attr.Size = 12 And Attr.Orientation = 2, "style not restored"
QPVerifyDisplay Attr, Record, "R1"
""")
def test_silent_display_setter_failure_is_rejected(self):
self.run_vbs("""Dim Attr, Record, Failure
Set Attr = New TestAttribute
Attr.IgnoreColor = True
Set Record = StyleRecord()
On Error Resume Next
QPRestoreDisplay Attr, Record, "R1"
Failure = Err.Number
Err.Clear
On Error GoTo 0
Require Failure <> 0, "silent no-op setter falsely passed"
""")
def test_incomplete_style_is_rejected(self):
self.run_vbs("""Dim Attr, Record, Failure
Set Attr = New TestAttribute
Set Record = StyleRecord()
Record("x") = ""
On Error Resume Next
QPRestoreDisplay Attr, Record, "R1"
Failure = Err.Number
Err.Clear
On Error GoTo 0
Require Failure <> 0, "incomplete style falsely passed"
""")
def test_target_identity_is_not_instance_owned(self):
self.run_vbs("""Require QPIsInstanceAttribute("User_Comment"), "custom instance not preserved"
Require QPIsInstanceAttribute("Notes"), "notes not preserved"
Require Not QPIsInstanceAttribute("Part Number"), "old PN may overwrite target"
Require Not QPIsInstanceAttribute("Part Label"), "old label may overwrite target"
Require Not QPIsInstanceAttribute("Tolerance"), "old electrical data may overwrite target"
""")
def test_uid_association_precedes_overlapping_position(self):
self.run_vbs("""Dim First, Second, Record, View, Found
Set First = New TestComponent
First.UID = "original"
First.Refdes = "R1"
First.LocationX = 100
First.LocationY = 100
Set Second = New TestComponent
Second.UID = "other"
Second.Refdes = "R2"
Second.LocationX = 100
Second.LocationY = 100
Set Record = StyleRecord()
Record.Add "uid", "original"
Record.Add "refdes", "R1"
Set View = New TestView
Set View.Components = CreateObject("Scripting.Dictionary")
Set View.Block = New TestBlock
View.Block.SheetNum = "1"
View.Components.Add First, True
View.Components.Add Second, True
Set QP_App = New TestApplication
Set QP_App.ActiveView = View
Set Found = QPFindUniqueByOldLocation(Record)
Require Found.UID = "original", "UID association failed"
""")
def test_ambiguous_refdes_is_rejected(self):
self.run_vbs("""Dim First, Second, Record, View, Found, Failure
Set First = New TestComponent
First.UID = "new1"
First.Refdes = "R1"
Set Second = New TestComponent
Second.UID = "new2"
Second.Refdes = "R1"
Set Record = StyleRecord()
Record.Add "uid", "old"
Record.Add "refdes", "R1"
Set View = New TestView
Set View.Components = CreateObject("Scripting.Dictionary")
View.Components.Add First, True
View.Components.Add Second, True
Set QP_App = New TestApplication
Set QP_App.ActiveView = View
On Error Resume Next
Set Found = QPFindUniqueByOldLocation(Record)
Failure = Err.Number
Err.Clear
On Error GoTo 0
Require Failure <> 0, "ambiguous identity falsely passed"
""")
if __name__ == "__main__":
unittest.main(verbosity=2)