fix(execution): verify exact identity connections and untouched state

This commit is contained in:
阿白叔 committed 2026-10-19 09:00:04 +08:00
1 parent b646a9a88a
commit 11810eca4c
7 files changed
+673 -133

No files matched your search

+106 -94
View File
@@ -1059,7 +1059,8 @@ Sub QPRollbackNativeReplacement(ByVal SnapshotPath)
Expected = ""
For LineIndex = 1 To UBound(Lines)
If Len(Replace(Lines(LineIndex), vbCr, "")) > 0 Then
If Left(CStr(Lines(LineIndex)), 2) <> "U" & vbTab Then _
If Left(CStr(Lines(LineIndex)), 2) = "C" & vbTab Or _
Left(CStr(Lines(LineIndex)), 2) = "A" & vbTab Then _
Expected = Expected & Replace(Lines(LineIndex), vbCr, "") & vbCrLf
End If
Next
@@ -1087,7 +1088,7 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
Dim PartAttr
Dim Snapshot
Dim Index
Dim Selectors, Selector, Uid, ValueAttr, ValueText
Dim Selectors, Selector, Uid, ValueAttr, ValueText, MatchedUids, UntouchedCount
If StrComp(CStr(Command("old_part_number")), CStr(Command("new_part_number")), vbTextCompare) = 0 Then _
Err.Raise vbObjectError + 829, "QuickPartReplace", "source and target must differ"
@@ -1152,12 +1153,23 @@ Sub QPCaptureAndSelect(ByRef Command, ByVal SnapshotPath)
Snapshot = Snapshot & QPSnapshotComponent(Comp)
QPProgress "capture", Index + 1, Matches.Count
Next
If Not Selectors Is Nothing Then
For Each Comp In Components
If Not Selectors.Exists(CStr(Comp.UID)) Then _
Snapshot = Snapshot & QPUntouchedComponent(Comp)
Next
End If
' U remains the seven-field native-helper identity baseline. X/G extend it
' with complete unselected state for every scope, including all-match jobs.
Snapshot = Snapshot & "X" & vbTab & "untouched_full_v1" & vbCrLf
Set MatchedUids = CreateObject("Scripting.Dictionary")
For Index = 0 To Matches.Count - 1
Set Comp = Matches.Item(CStr(Index))
MatchedUids.Add CStr(Comp.UID), True
Next
UntouchedCount = 0
For Each Comp In Components
If Not MatchedUids.Exists(CStr(Comp.UID)) Then
QPProgress "capture_untouched", UntouchedCount, Components.Count - Matches.Count
Snapshot = Snapshot & QPUntouchedComponent(Comp)
UntouchedCount = UntouchedCount + 1
QPProgress "capture_untouched", UntouchedCount, Components.Count - Matches.Count
End If
Next
QPWriteUtf8 SnapshotPath, Snapshot
For Each Comp In Components
@@ -1179,6 +1191,30 @@ Function QPUntouchedComponent(ByRef Comp)
QPEncode(QPEffectiveComponentAttribute(Comp, "Value")) & vbTab & _
QPEncode(QPEffectiveComponentAttribute(Comp, "Part Name")) & vbTab & _
QPEncode(QPEffectiveComponentAttribute(Comp, "Part Label")) & vbCrLf
QPUntouchedComponent = QPUntouchedComponent & "G" & vbTab & QPEncode(CStr(Comp.UID)) & _
vbTab & QPEncode(QPUntouchedFullState(Comp)) & vbCrLf
End Function
Function QPUntouchedFullState(ByRef Comp)
Dim Point, Pins, Connections, Attr, AttributeText, Result
Set Point = Comp.GetLocation()
Set Pins = QPComponentPins(Comp)
If Pins.Count = 0 Then
' A genuinely empty query is valid for annotation symbols; COM errors
' still propagate. Selected replacement symbols continue to require pins.
Connections = "NO_PINS"
Else
Connections = QPConnectionSignature(Comp)
End If
Result = "C" & vbTab & QPEncode(CStr(Comp.UID)) & vbTab & QPEncode(CStr(Comp.Refdes)) & _
vbTab & QPEncode(CStr(Point.X)) & vbTab & QPEncode(CStr(Point.Y)) & _
vbTab & QPEncode(CStr(Comp.Orientation)) & vbTab & QPEncode(CStr(Comp.Scale)) & _
vbTab & QPEncode(Connections) & vbCrLf
AttributeText = ""
For Each Attr In Comp.Attributes
AttributeText = AttributeText & QPSnapshotAttribute(CStr(Comp.UID), Attr)
Next
QPUntouchedFullState = Result & QPSortSnapshotLines(AttributeText)
End Function
Function QPEffectiveComponentAttribute(ByRef Comp, ByVal Name)
@@ -1189,9 +1225,16 @@ Function QPEffectiveComponentAttribute(ByRef Comp, ByVal Name)
End Function
Sub QPVerifyUntouched(ByRef Records)
Dim Baseline, Components, Comp, Uid, Actual, Matched, Total, Seen
If Not Records.Item("meta").Exists("target_scope") Then Exit Sub
Dim Baseline, FullBaseline, Components, Comp, Uid, Actual, Expected, Matched, Total, Seen
If Not Records.Exists("untouched_full_version") Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "legacy snapshot has no complete unselected-state proof; recovery requires manual verification"
Set Baseline = Records.Item("untouched")
Set FullBaseline = Records.Item("untouched_full")
If Baseline.Count <> FullBaseline.Count Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "unselected full-state baseline is incomplete"
' Read new component/pin proxies after each native mutation, restore or reopen.
QPInvalidatePinIndex
QPInvalidateComponentIndex
Set Components = QP_App.ActiveView.Query(VDM_COMP, VD_ALL)
Matched = 0
Total = 0
@@ -1203,10 +1246,16 @@ Sub QPVerifyUntouched(ByRef Records)
"QuickPartReplace.Target", "duplicate component UID"
Seen.Add Uid, True
If Baseline.Exists(Uid) Then
QPProgress "verify_untouched", Matched, Baseline.Count
Matched = Matched + 1
Actual = Replace(QPUntouchedComponent(Comp), vbCrLf, "")
If Actual <> CStr(Baseline.Item(Uid)) Then _
If Not FullBaseline.Exists(Uid) Then Err.Raise vbObjectError + 874, _
"QuickPartReplace.Target", "unselected full-state baseline is missing"
Actual = QPUntouchedComponent(Comp)
Expected = CStr(Baseline.Item(Uid)) & vbCrLf & "G" & vbTab & QPEncode(Uid) & _
vbTab & QPEncode(CStr(FullBaseline.Item(Uid))) & vbCrLf
If Actual <> Expected Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "unselected component changed"
QPProgress "verify_untouched", Matched, Baseline.Count
End If
Next
If Total <> Baseline.Count + Records.Item("components").Count Then _
@@ -1311,7 +1360,6 @@ End Function
Function QPSnapshotAttribute(ByVal ComponentUid, ByRef Attr)
Dim Instance
Dim InstanceWarning
Dim LocationX
Dim LocationY
Dim Color
@@ -1320,18 +1368,7 @@ Function QPSnapshotAttribute(ByVal ComponentUid, ByRef Attr)
Dim Orientation
Dim Visible
InstanceWarning = ""
On Error Resume Next
Instance = Attr.InstanceValue
If Err.Number <> 0 Then
Err.Clear
Instance = Attr.Value
InstanceWarning = "instance_value_fallback"
End If
On Error GoTo 0
If Len(InstanceWarning) > 0 Then
QPLog QP_Root, "WARN", InstanceWarning & " name=" & CStr(Attr.Name)
End If
LocationX = QPOptionalAttributeField(Attr, "location_x")
LocationY = QPOptionalAttributeField(Attr, "location_y")
Color = QPOptionalAttributeField(Attr, "color")
@@ -1507,14 +1544,22 @@ Sub QPRestorePlans(ByRef Command, ByRef Records, ByRef Plans)
QPProgress "restore_attributes", Index + 1, Plans.Count
Next
QPVerifyRestoredPlans Command, Records, Plans, ValueStates
QPVerifyUntouched Records
End Sub
Sub QPVerifyRestoredPlans(ByRef Command, ByRef Records, ByRef Plans, ByRef ValueStates)
Dim Index, ComponentRecord, Candidate, AttributeIndex, Record, Attr
Dim Index, ComponentRecord, Candidate, AttributeIndex, Record, Attr, Before
QPProgress "verify_restoration", 0, Plans.Count
For Index = 0 To Plans.Count - 1
Set ComponentRecord = Records.Item("components").Item(CStr(Index))
Set Candidate = Plans.Item(CStr(Index))
' Captured only after native library identity validation (or recovery
' command validation), before restoration/save; never derive this expected
' identity from the reopened result or from its current Value.
Set Before = ValueStates.Item(CStr(Index))
If QPRequiredAttributeValue(Candidate, "Part Name") <> CStr(Before("part_name")) Or _
QPEffectiveComponentAttribute(Candidate, "Part Label") <> CStr(Before("part_label")) Then _
Err.Raise vbObjectError + 865, "QuickPartReplace", "target library identity changed during restoration or save"
QPRestorePreflight Candidate, ComponentRecord, Records.Item("attributes"), _
CStr(Command("new_part_number")), QPValueMode(Command)
QPVerifyTransform Candidate, ComponentRecord
@@ -1568,11 +1613,12 @@ Sub QPRecoverSavedJob(ByRef Command, ByVal SnapshotPath)
ElseIf StrComp(PartNumber, CStr(Command("new_part_number")), vbTextCompare) = 0 Then
NewCount = NewCount + 1
If StrComp(QPRequiredAttributeValue(Candidate, "Part Name"), _
CStr(Command("recovery_part_name")), vbTextCompare) <> 0 Then _
CStr(Command("recovery_part_name")), vbBinaryCompare) <> 0 Then _
Err.Raise vbObjectError + 865, "QuickPartReplace.Recovery", "saved target library identity differs"
If QPValueMode(Command) <> "preserve" Then
If StrComp(QPRequiredAttributeValue(Candidate, "Part Label"), _
CStr(Command("recovery_part_label")), vbTextCompare) <> 0 Then _
If Len(CStr(Command("recovery_part_label"))) > 0 Or _
QPValueMode(Command) = "part_label" Or QPValueMode(Command) = "legacy_part_label" Then
If StrComp(QPEffectiveComponentAttribute(Candidate, "Part Label"), _
CStr(Command("recovery_part_label")), vbBinaryCompare) <> 0 Then _
Err.Raise vbObjectError + 865, "QuickPartReplace.Recovery", "saved target library identity differs"
End If
QPRestorePreflight Candidate, Record, Records.Item("attributes"), _
@@ -1662,6 +1708,9 @@ Sub QPRestorePreflight(ByRef Comp, ByRef ComponentRecord, _
Dim CurrentConnections
Dim SavedConnections
If CStr(Comp.UID) <> CStr(ComponentRecord("uid")) Or _
CStr(Comp.Refdes) <> CStr(ComponentRecord("refdes")) Then _
Err.Raise vbObjectError + 831, "QuickPartReplace", "replacement component UID or Refdes differs from snapshot; no restoration writes allowed"
If StrComp(QPRequiredAttributeValue(Comp, "Part Number"), _
CStr(NewPartNumber), vbTextCompare) <> 0 Then
Err.Raise vbObjectError + 800, "QuickPartReplace", _
@@ -2072,6 +2121,8 @@ Function QPCaptureValueState(ByRef Comp)
State.Add "exists", Not (Attr Is Nothing)
State.Add "value", ""
State.Add "nc_required", False
State.Add "part_name", QPRequiredAttributeValue(Comp, "Part Name")
State.Add "part_label", QPEffectiveComponentAttribute(Comp, "Part Label")
If Not Attr Is Nothing Then State("value") = QPEffectiveAttributeValue(Attr)
Set QPCaptureValueState = State
End Function
@@ -2161,15 +2212,20 @@ Function QPConnectionsMatch(ByVal Current, ByVal Saved)
Exit Function
End If
Next
If QPAllSavedNumbersBlank(Expected) Then _
QPConnectionsMatch = QPConnectionsMatchTopology(Actual, Expected)
' Unknown source numbers permit only the same one-to-one physical/net map,
' up to one common translation. Network counts alone cannot prove pin mapping.
End Function
Function QPConnectionLineValid(ByVal Line, ByVal RequireNumber)
Dim Fields, X, Y, ErrorNumber
QPConnectionLineValid = False
Fields = Split(CStr(Line), "|")
If UBound(Fields) < 3 Then Exit Function
If UBound(Fields) <> 3 And UBound(Fields) <> 4 Then Exit Function
If UBound(Fields) = 3 Then
If CStr(Fields(3)) <> "UNCONNECTED" Then Exit Function
Else
If Len(CStr(Fields(3))) = 0 Then Exit Function
End If
If RequireNumber And Len(Trim(CStr(Fields(0)))) = 0 Then Exit Function
If Len(Trim(CStr(Fields(1)))) = 0 Or Len(Trim(CStr(Fields(2)))) = 0 Then Exit Function
On Error Resume Next
@@ -2197,7 +2253,11 @@ End Function
Function QPConnectionNetIdentity(ByVal Line)
Dim Fields
Fields = Split(CStr(Line), "|")
QPConnectionNetIdentity = Trim(CStr(Fields(UBound(Fields))))
If UBound(Fields) = 3 Then
QPConnectionNetIdentity = "UNCONNECTED"
Else
QPConnectionNetIdentity = CStr(Fields(3)) & "|" & CStr(Fields(4))
End If
End Function
Function QPConnectionsMatchOffset(ByRef Actual, ByRef Expected, ByVal OffsetX, ByVal OffsetY)
@@ -2215,7 +2275,7 @@ Function QPConnectionsMatchOffset(ByRef Actual, ByRef Expected, ByVal OffsetX, B
Abs(QPConnectionCoordinate(Candidate, 2) - _
QPConnectionCoordinate(SavedLine, 2) - OffsetY) < 0.0001 And _
StrComp(QPConnectionNetIdentity(Candidate), _
QPConnectionNetIdentity(SavedLine), vbTextCompare) = 0)
QPConnectionNetIdentity(SavedLine), vbBinaryCompare) = 0)
Number = QPConnectionNumber(SavedLine)
If Len(Trim(Number)) > 0 Then _
Match = Match And StrComp(QPConnectionNumber(Candidate), Number, vbBinaryCompare) = 0
@@ -2231,53 +2291,6 @@ Function QPConnectionsMatchOffset(ByRef Actual, ByRef Expected, ByVal OffsetX, B
QPConnectionsMatchOffset = True
End Function
Function QPAllSavedNumbersBlank(ByRef Expected)
Dim Index
QPAllSavedNumbersBlank = True
For Index = 0 To Expected.Count - 1
If Len(Trim(QPConnectionNumber(Expected.Item(CStr(Index))))) > 0 Then
QPAllSavedNumbersBlank = False
Exit Function
End If
Next
End Function
Function QPConnectionsMatchTopology(ByRef Actual, ByRef Expected)
Dim ActualNets, ExpectedNets, Index, Key, Value
Set ActualNets = CreateObject("Scripting.Dictionary")
Set ExpectedNets = CreateObject("Scripting.Dictionary")
ActualNets.CompareMode = vbTextCompare
ExpectedNets.CompareMode = vbTextCompare
For Index = 0 To Actual.Count - 1
Key = QPConnectionNetIdentity(Actual.Item(CStr(Index)))
If ActualNets.Exists(Key) Then
ActualNets(Key) = ActualNets(Key) + 1
Else
ActualNets.Add Key, 1
End If
Next
For Index = 0 To Expected.Count - 1
Key = QPConnectionNetIdentity(Expected.Item(CStr(Index)))
If ExpectedNets.Exists(Key) Then
ExpectedNets(Key) = ExpectedNets(Key) + 1
Else
ExpectedNets.Add Key, 1
End If
Next
QPConnectionsMatchTopology = (ActualNets.Count = ExpectedNets.Count)
If Not QPConnectionsMatchTopology Then Exit Function
For Each Key In ExpectedNets.Keys
If Not ActualNets.Exists(Key) Then
QPConnectionsMatchTopology = False
Exit Function
End If
If ActualNets(Key) <> ExpectedNets(Key) Then
QPConnectionsMatchTopology = False
Exit Function
End If
Next
End Function
Sub QPRestoreDisplay(ByRef Attr, ByRef Record, ByVal Refdes)
Dim Point, Field
For Each Field In Array("x", "y", "color", "font", "size", "orientation", "visible")
@@ -2333,16 +2346,7 @@ End Sub
Function QPFindCurrentAttribute(ByRef Comp, ByVal Name)
Dim Attr
On Error Resume Next
Set Attr = Comp.FindAttribute(CStr(Name))
If Err.Number <> 0 Then
QPLog QP_Root, "WARN", "find_attribute name=" & CStr(Name) & _
" number=" & Err.Number & " source=" & Err.Source & _
" description=" & Err.Description
Err.Clear
Set Attr = Nothing
End If
On Error GoTo 0
Set QPFindCurrentAttribute = Attr
End Function
@@ -2375,9 +2379,7 @@ Function QPEffectiveAttributeValue(ByRef Attr)
Exit Function
End If
If ErrorNumber <> 0 Then
QPLog QP_Root, "WARN", "instance_value_fallback number=" & _
ErrorNumber & " source=" & ErrorSource & " description=" & _
ErrorDescription
Err.Raise ErrorNumber, ErrorSource, ErrorDescription
End If
On Error Resume Next
Value = CStr(Attr.Value)
@@ -2689,7 +2691,7 @@ Function QPReadSnapshot(ByVal Path)
Dim Result
Dim Components
Dim Attributes
Dim Untouched
Dim Untouched, UntouchedFull
Dim Fields
Dim Index
Dim Record
@@ -2699,6 +2701,7 @@ Function QPReadSnapshot(ByVal Path)
Set Components = CreateObject("Scripting.Dictionary")
Set Attributes = CreateObject("Scripting.Dictionary")
Set Untouched = CreateObject("Scripting.Dictionary")
Set UntouchedFull = CreateObject("Scripting.Dictionary")
Lines = Split(QPReadUtf8(Path), vbLf)
For Index = 0 To UBound(Lines)
If Len(Replace(Lines(Index), vbCr, "")) > 0 Then
@@ -2757,6 +2760,14 @@ Function QPReadSnapshot(ByVal Path)
If Untouched.Exists(QPDecode(Fields(1))) Then Err.Raise vbObjectError + 874, _
"QuickPartReplace.Target", "duplicate unselected component UID"
Untouched.Add QPDecode(Fields(1)), Replace(Lines(Index), vbCr, "")
Case "X"
If UBound(Fields) <> 1 Or Fields(1) <> "untouched_full_v1" Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "invalid unselected-state protocol"
Result.Add "untouched_full_version", CStr(Fields(1))
Case "G"
If UBound(Fields) <> 2 Or Len(QPDecode(Fields(1))) = 0 Or Len(QPDecode(Fields(2))) = 0 Then _
Err.Raise vbObjectError + 874, "QuickPartReplace.Target", "invalid unselected full-state snapshot"
UntouchedFull.Add QPDecode(Fields(1)), QPDecode(Fields(2))
End Select
End If
Next
@@ -2766,6 +2777,7 @@ Function QPReadSnapshot(ByVal Path)
Result.Add "components", Components
Result.Add "attributes", Attributes
Result.Add "untouched", Untouched
Result.Add "untouched_full", UntouchedFull
Set QPReadSnapshot = Result
End Function
@@ -328,30 +328,10 @@ def select_snapshot_batch(app, api, metadata, records):
def existing_replacement_uids(components, records, target, binding, require_part_label=True):
current_by_uid = {str(component.UID): component for component in components}
target_key = target.casefold()
current_by_refdes = {}
for component in components:
if attribute_value(component, "Part Number").casefold() == target_key:
current_by_refdes.setdefault(str(component.Refdes), []).append(component)
library_row = binding["library_row"]
expected_part_name = str(library_row[4]).strip().casefold()
expected_part_label = str(library_row[5]).strip().casefold()
matches = []
for record in records:
candidate = current_by_uid.get(record[1])
if candidate is None or attribute_value(candidate, "Part Number").casefold() != target_key:
candidates = current_by_refdes.get(record[2], ())
if len(candidates) != 1:
raise ValueError("Source batch changed since snapshot")
candidate = candidates[0]
part_name = attribute_value(candidate, "Part Name").strip().casefold()
part_label = attribute_value(candidate, "Part Label").strip().casefold()
if part_name != expected_part_name or (require_part_label and part_label != expected_part_label):
raise ValueError("Existing replacement does not match the recorded target library identity")
matches.append(str(candidate.UID))
if len(set(matches)) != len(records):
raise ValueError("Duplicate replacement association")
matches = replacement_matches(components, records, target, require_part_label,
library_row=binding['library_row'])
if matches is None:
raise ValueError('Source batch changed since snapshot')
return matches
@@ -392,31 +372,38 @@ def _promotion_phase(snapshot, report, phase):
save_report(snapshot, report)
def replacement_matches(components, records, target, require_part_label):
def replacement_matches(components, records, target, require_part_label, *, library_row=None):
current_by_uid = {str(component.UID): component for component in components}
current_by_refdes = {}
for component in components:
current_by_refdes.setdefault(str(component.Refdes), []).append(component)
if len(current_by_uid) != len(components):
raise ValueError('Duplicate component UID on sheet')
expected_name = expected_label = None
if library_row is not None:
if (len(library_row) < 6 or str(library_row[1]).casefold() != target.casefold()
or not str(library_row[4]).strip()):
raise ValueError('Recorded target library identity is incomplete or inconsistent')
expected_name, expected_label = str(library_row[4]), str(library_row[5])
matches = []
for record in records:
candidate = current_by_uid.get(record[1])
if candidate is None:
candidates = current_by_refdes.get(record[2], ())
if len(candidates) != 1:
raise ValueError("Native replacement lost component identity")
candidate = candidates[0]
raise ValueError('Native replacement lost component UID identity')
if attribute_value(candidate, "Part Number").casefold() != target.casefold():
return None
identity = str(candidate.Refdes).strip() or f"UID={candidate.UID}"
if not attribute_value(candidate, "Part Name"):
part_name = attribute_value(candidate, 'Part Name')
if not part_name:
raise ValueError(
f"Native replacement Part Name readback failed; refdes={identity}; uid={candidate.UID}"
)
if require_part_label and not attribute_value(candidate, "Part Label"):
part_label = attribute_value(candidate, 'Part Label') if require_part_label or expected_label else ''
if require_part_label and not part_label:
raise ValueError(
f"Native replacement Part Label readback failed; refdes={identity}; uid={candidate.UID}; "
"Part Label is required by the selected Value policy"
)
if expected_name is not None and (part_name != expected_name
or (expected_label and part_label != expected_label)):
raise ValueError(f'Native replacement does not match the selected target library identity; uid={candidate.UID}')
matches.append(str(candidate.UID))
if len(set(matches)) != len(records):
raise ValueError("Duplicate replacement association")
@@ -625,12 +612,12 @@ def run_native(snapshot, report):
replacement_poll_count += 1
selected = [api.IVdComp(component._oleobj_) for component in app.ActiveView.Query(128, 1)]
if len(selected) == len(records):
matches = replacement_matches(selected, records, metadata[3], require_part_label)
matches = replacement_matches(selected, records, metadata[3], require_part_label, library_row=columns)
if matches is not None:
return matches
if replacement_poll_count % 7 == 0:
return replacement_matches(
components_on_sheet(app, api), records, metadata[3], require_part_label
components_on_sheet(app, api), records, metadata[3], require_part_label, library_row=columns
)
return None
@@ -671,7 +658,7 @@ def run_native(snapshot, report):
)
if current_identity != identity:
raise ValueError("An unselected component was changed")
verified_uids = replacement_matches(current, records, metadata[3], require_part_label)
verified_uids = replacement_matches(current, records, metadata[3], require_part_label, library_row=columns)
if verified_uids is None or set(verified_uids) != set(report["replaced_uids"]):
raise ValueError("Native replacement verification changed after completion")
report["stage"] = "native_replace_applied"
@@ -7,6 +7,7 @@ STAGES = {
'query_components': '读取器件', 'index_components': '建立器件索引',
'find_components': '定位目标位号', 'index_pins': '建立引脚索引',
'snapshot_attributes': '记录原始属性', 'capture': '采集替换前快照',
'capture_untouched': '记录未选中器件状态', 'verify_untouched': '核验未选中器件',
'before_native': '准备原生替换', 'native_replace': '执行原生替换',
'restore_preflight': '检查属性恢复条件',
'before_restore_transaction': '准备恢复属性',
@@ -265,8 +265,8 @@ class VBScriptTests(unittest.TestCase):
def test_unassigned_target_or_changed_net_is_rejected(self):
self.run_vbs('Require Not QPConnectionsMatch("|500|550|NET1|VCC" & vbLf, "|500|550|NET1|VCC" & vbLf), "target remains unassigned"\nRequire Not QPConnectionsMatch("1|500|550|NET2|GND" & vbLf, "|500|550|NET1|VCC" & vbLf), "net changed"')
def test_unassigned_pins_accept_library_geometry_translation_and_change(self):
self.run_vbs('Require QPConnectionsMatch("1|1330|1170|NEWUID|SYS_RESET_N" & vbLf & "2|1330|1140|OTHERUID|GND" & vbLf, "|1328|1144|OLDUID|GND" & vbLf & "|1328|1174|OLDUID2|SYS_RESET_N" & vbLf), "valid topology was rejected after library geometry changed"')
def test_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
@@ -174,6 +174,7 @@ Command.Add "sync_nc","__SYNC_NC__"
__BEFORE__
SnapshotPath=QPJobSnapshotPath(QP_CurrentJobId)
Snapshot="M" & vbTab & QPEncode(QPProjectPath()) & vbTab & "OLD" & vbTab & "NEW" & vbTab & QPEncode(QPSheetIdentity()) & vbTab & "__MODE__" & vbTab & QPEncode("__CUSTOM__") & vbTab & "__SYNC_NC__" & vbCrLf & QPSnapshotComponent(Comp)
Snapshot=Snapshot & "X" & vbTab & "untouched_full_v1" & vbCrLf
QPWriteUtf8 SnapshotPath,Snapshot
Set Attr=Comp.FindAttribute("Part Number"): Attr.Value="NEW"
Set Attr=Comp.FindAttribute("Part Name"): Attr.Value="NEW_NAME"
@@ -215,6 +216,19 @@ Require QP_App.UndoCount=0,"recovery undid prior CAD work"
''')
@pytest.mark.parametrize('change', ['Comp.UID="imposter"', 'Comp.Refdes="R99"'])
def test_restore_rejects_changed_component_identity_before_any_write(tmp_path, change):
run_vbs(tmp_path, 'part_number', '''
On Error Resume Next
QPRestoreAfterOperatorReplace Command,SnapshotPath
Failure=Err.Number
Err.Clear
On Error GoTo 0
Require Failure<>0,"changed component identity was accepted"
Require QP_App.TransactionCount=0,"identity failure must precede CAD writes"
''', after=change)
@pytest.mark.parametrize('mode', ['preserve', 'part_label', 'part_number'])
def test_recovery_repairs_attributes_without_native_replace(tmp_path, mode):
run_vbs(tmp_path, mode, '''
+489
View File
@@ -0,0 +1,489 @@
"""Run extracted production VBScript guards against small COM-shaped fakes."""
from pathlib import Path
import re
import shutil
import subprocess
import pytest
SOURCE = Path(__file__).resolve().parents[2] / 'integration/dxdesigner795/QuickPartReplace.vbs'
pytestmark = pytest.mark.skipif(shutil.which('cscript.exe') is None, reason='Windows VBScript required')
def routine(name):
source = SOURCE.read_text(encoding='ascii')
match = re.search(rf'(?mi)^(Function|Sub) {name.lstrip("?")}\([^\n]*\n[\s\S]*?^End \1\s*$', source)
if not match and name.startswith('?'):
return ''
assert match, name
return match[0]
def run_vbs(tmp_path, names, body, prelude=''):
script = tmp_path / 'guard.vbs'
script.write_text(prelude + '\n' + '\n'.join(routine(name) for name in names) + '\n' + body,
encoding='ascii')
result = subprocess.run(['cscript.exe', '//nologo', str(script)], capture_output=True,
text=True, timeout=15)
assert result.returncode == 0, result.stdout + result.stderr
return result.stdout.strip()
LOG_STUB = '''
Dim QP_Root
Sub QPLog(ByVal Root, ByVal Level, ByVal Message)
End Sub
'''
def test_attribute_com_failure_propagates_instead_of_missing(tmp_path):
output = run_vbs(tmp_path, ['QPFindCurrentAttribute'], '''
Dim Comp, Attr
Set Comp = New BrokenComponent
On Error Resume Next
Set Attr = QPFindCurrentAttribute(Comp, "Part Number")
WScript.Echo Err.Number
''', LOG_STUB + '''
Class BrokenComponent
Function FindAttribute(ByVal Name)
Err.Raise 1234, "FakeCOM", "read denied"
End Function
End Class
''')
assert output == '1234'
def test_actual_missing_attribute_remains_missing(tmp_path):
assert run_vbs(tmp_path, ['QPFindCurrentAttribute'], '''
Dim Comp, Attr
Set Comp = New MissingComponent
Set Attr = QPFindCurrentAttribute(Comp, "Part Number")
WScript.Echo CStr(Attr Is Nothing)
''', LOG_STUB + '''
Class MissingComponent
Function FindAttribute(ByVal Name)
Set FindAttribute = Nothing
End Function
End Class
''') == 'True'
def test_instance_value_com_failure_cannot_fallback_to_base_value(tmp_path):
assert run_vbs(tmp_path, ['QPEffectiveAttributeValue'], '''
Dim Attr, Value
Set Attr = New BrokenAttribute
On Error Resume Next
Value = QPEffectiveAttributeValue(Attr)
WScript.Echo Err.Number
''', LOG_STUB + '''
Class BrokenAttribute
Public Value
Private Sub Class_Initialize
Value = "OLD"
End Sub
Public Property Get InstanceValue
Err.Raise 1234, "FakeCOM", "read denied"
End Property
End Class
''') == '1234'
CONNECTION_ROUTINES = ['QPConnectionsMatch', 'QPConnectionLineValid', 'QPConnectionCoordinate',
'QPConnectionNumber', 'QPConnectionNetIdentity', 'QPConnectionsMatchOffset']
@pytest.mark.parametrize(('actual', 'saved', 'expected'), [
('1|0|0|NET_B|', '1|0|0|NET_A|', 'False'),
('1|0|0|NB|B\\n2|100|0|NA|A', '|0|0|NA|A\\n|100|0|NB|B', 'False'),
('1|10|20|NA|A\\n2|110|20|NB|B', '|0|0|NA|A\\n|100|0|NB|B', 'True'),
('1|0|0|NA|A', '1|0|0|NA|A', 'True'),
('1|0|0|UNCONNECTED', '1|0|0|NA|', 'False'),
])
def test_pin_mapping_requires_identity_and_geometry(tmp_path, actual, saved, expected):
def expression(value):
return ' & vbLf & '.join('"' + line + '"' for line in value.split('\\n'))
assert run_vbs(tmp_path, CONNECTION_ROUTINES,
f'WScript.Echo CStr(CBool(QPConnectionsMatch({expression(actual)}, {expression(saved)})))') == expected
COMPONENT_FAKE = '''
Class FakeAttribute
Public InstanceValue, Value
End Class
Class FakeComponent
Public UID, Refdes, PartName, PartLabel, ValueText
Private Sub Class_Initialize
UID = "u1": Refdes = "R1": PartName = "LIB:PART": PartLabel = "1m": ValueText = "1m"
End Sub
Function FindAttribute(ByVal Name)
Dim Attr
Set Attr = New FakeAttribute
Select Case Name
Case "Value": Attr.Value = ValueText
Case "Part Number": Attr.Value = "NEW"
Case "Part Name": Attr.Value = PartName
Case "Part Label": Attr.Value = PartLabel
Case Else: Set FindAttribute = Nothing: Exit Function
End Select
Attr.InstanceValue = Attr.Value
Set FindAttribute = Attr
End Function
End Class
Sub QPProgress(ByVal Stage, ByVal Done, ByVal Total)
End Sub
'''
ATTRIBUTE_ROUTINES = ['QPFindCurrentAttribute', 'QPEffectiveAttributeValue',
'QPEffectiveComponentAttribute', 'QPRequiredAttributeValue', 'QPCaptureValueState']
@pytest.mark.parametrize('change', ['PartName = "WRONG"', 'PartLabel = "1M"', 'PartLabel = "WRONG"'])
def test_saved_readback_keeps_independent_library_identity(tmp_path, change):
output = run_vbs(tmp_path, ATTRIBUTE_ROUTINES + ['QPVerifyRestoredPlans'], '''
Dim Comp, State, States, Plans, Records, Components, Attributes, Record, Command
Set Comp = New FakeComponent
Set State = QPCaptureValueState(Comp)
Comp.''' + change + '''
Set States = CreateObject("Scripting.Dictionary"): States.Add "0", State
Set Plans = CreateObject("Scripting.Dictionary"): Plans.Add "0", Comp
Set Components = CreateObject("Scripting.Dictionary")
Set Record = CreateObject("Scripting.Dictionary"): Record.Add "uid", "u1": Components.Add "0", Record
Set Attributes = CreateObject("Scripting.Dictionary")
Set Records = CreateObject("Scripting.Dictionary")
Records.Add "components", Components: Records.Add "attributes", Attributes
Set Command = CreateObject("Scripting.Dictionary"): Command.Add "new_part_number", "NEW"
On Error Resume Next
QPVerifyRestoredPlans Command, Records, Plans, States
WScript.Echo CStr(Err.Number <> 0)
''', LOG_STUB + COMPONENT_FAKE + '''
Function QPValueMode(ByRef Command)
QPValueMode = "preserve"
End Function
Sub QPRestorePreflight(ByRef Comp, ByRef Record, ByRef Attributes, ByVal PN, ByVal Mode)
End Sub
Sub QPVerifyTransform(ByRef Comp, ByRef Record)
End Sub
Sub QPVerifyValuePolicy(ByRef Comp, ByVal Mode, ByRef Before)
End Sub
''')
assert output == 'True'
@pytest.mark.parametrize(('mode', 'label', 'expected'), [
('part_label', '1M', 'True'), ('preserve', 'WRONG', 'True'),
('custom', '1M', 'True'), ('preserve', '1m', 'False'),
])
def test_recovery_requires_recorded_library_label_exactly(tmp_path, mode, label, expected):
output = run_vbs(tmp_path, ATTRIBUTE_ROUTINES + ['QPRecoverSavedJob'], '''
Set FakeComp = New FakeComponent
FakeComp.PartLabel = "''' + label + '''"
Set FakeRecords = CreateObject("Scripting.Dictionary")
Dim Components, Record, Attributes, Command
Set Components = CreateObject("Scripting.Dictionary")
Set Record = CreateObject("Scripting.Dictionary"): Record.Add "uid", "u1": Components.Add "0", Record
Set Attributes = CreateObject("Scripting.Dictionary")
FakeRecords.Add "components", Components: FakeRecords.Add "attributes", Attributes
Set Command = CreateObject("Scripting.Dictionary")
Command.Add "old_part_number", "OLD": Command.Add "new_part_number", "NEW"
Command.Add "recovery_part_name", "LIB:PART": Command.Add "recovery_part_label", "1m"
On Error Resume Next
QPRecoverSavedJob Command, "unused"
WScript.Echo CStr(Err.Number <> 0)
''', LOG_STUB + COMPONENT_FAKE + '''
Dim FakeRecords, FakeComp, QP_CurrentJobId
Function QPReadSnapshot(ByVal Path)
Set QPReadSnapshot = FakeRecords
End Function
Function QPFindUniqueByOldLocation(ByRef Record)
Set QPFindUniqueByOldLocation = FakeComp
End Function
Function QPValueMode(ByRef Command)
QPValueMode = "''' + mode + '''"
End Function
Function QPSyncNc(ByRef Command)
QPSyncNc = False
End Function
Function QPCustomValue(ByRef Command)
QPCustomValue = ""
End Function
Sub QPRequireCommandSnapshot(ByRef Command, ByVal Path)
End Sub
Sub QPRequireSnapshotContext(ByVal Path)
End Sub
Sub QPVerifyUntouched(ByRef Records)
End Sub
Sub QPInvalidatePinIndex()
End Sub
Sub QPSetRequiredNc(ByRef State, ByRef Record, ByRef Attributes, ByVal Enabled)
End Sub
Sub QPRestorePreflight(ByRef Comp, ByRef Record, ByRef Attributes, ByVal PN, ByVal Mode)
End Sub
Sub QPVerifyRestoredPlans(ByRef Command, ByRef Records, ByRef Plans, ByRef States)
End Sub
Sub QPWriteStatus(ByVal Root, ByVal Job, ByVal State, ByVal Code, ByVal Message)
End Sub
''')
assert output == expected
FULL_FAKE = '''
Dim QP_App, QP_PinIndex, QP_PinContext, QP_Stage
Class FakePoint
Public X, Y
End Class
Class FullAttribute
Public Name, InstanceValue, Value, X, Y, Color, Font, Size, Orientation, Visible
Private Sub Class_Initialize
Name = "Value": Value = "SAME": InstanceValue = "SAME"
X = 0: Y = 0: Color = 1: Font = 2: Size = 3: Orientation = 0: Visible = 1
End Sub
Function GetLocation()
Dim Point: Set Point = New FakePoint: Point.X = X: Point.Y = Y: Set GetLocation = Point
End Function
End Class
Class FullComponent
Public UID, Refdes, X, Y, Orientation, Scale, Attributes, Selected, RaiseOnFind
Private Sub Class_Initialize
X = 0: Y = 0: Orientation = 0: Scale = 1
Set Attributes = CreateObject("Scripting.Dictionary")
End Sub
Function FindAttribute(ByVal Name)
Dim Attr
If RaiseOnFind Then Err.Raise 1234, "FakeCOM", "attribute unreadable"
For Each Attr In Attributes
If Attr.Name = Name Then Set FindAttribute = Attr: Exit Function
Next
Set FindAttribute = Nothing
End Function
Function GetLocation()
Dim Point: Set Point = New FakePoint: Point.X = X: Point.Y = Y: Set GetLocation = Point
End Function
End Class
Class FakeNet
Public UID, LogicalNetName
End Class
Class FakeConnection
Public Net
End Class
Class FakePin
Public Component, Number, Connection, X, Y
Function GetLocation()
Dim Point: Set Point = New FakePoint: Point.X = X: Point.Y = Y: Set GetLocation = Point
End Function
End Class
Class FakeView
Public Components, Pins, Queries
Private Sub Class_Initialize
Set Components = CreateObject("Scripting.Dictionary")
Set Pins = CreateObject("Scripting.Dictionary")
Queries = 0
End Sub
Function Query(ByVal Kind, ByVal Scope)
Queries = Queries + 1
If Kind = 128 Then Set Query = Components Else Set Query = Pins
End Function
End Class
Class FakeApp
Public ActiveView
Private Sub Class_Initialize
Set ActiveView = New FakeView
End Sub
Function ExecuteCommand(ByVal Command)
ExecuteCommand = 0
End Function
End Class
Function QPProjectPath()
QPProjectPath = "C:\\board.prj"
End Function
Function QPSheetIdentity()
QPSheetIdentity = "MAIN:1"
End Function
Function QPCanonicalPath(ByVal Path)
QPCanonicalPath = Path
End Function
Sub QPInvalidateComponentIndex()
End Sub
Sub QPProgress(ByVal Stage, ByVal Done, ByVal Total)
End Sub
Const VDM_COMP = 128
Const VDM_COMPPIN = 4096
Const VD_ALL = 0
'''
UNTOUCHED_ROUTINES = ['QPUntouchedComponent', '?QPUntouchedFullState', 'QPVerifyUntouched',
'QPReadSnapshot', 'QPWriteUtf8', 'QPReadUtf8', 'QPEncode', 'QPDecode',
'QPFindCurrentAttribute', 'QPEffectiveAttributeValue', 'QPEffectiveComponentAttribute',
'QPSnapshotAttribute', 'QPOptionalAttributeField', 'QPSortSnapshotLines',
'QPConnectionSignature', 'QPComponentPins', 'QPInvalidatePinIndex', 'QPAddSortedSignature']
@pytest.mark.parametrize(('mutation', 'expected'), [
('Comp.X = 20', 'True'), ('Comp.Orientation = 90', 'True'),
('Comp.Scale = 2', 'True'), ('Attr.Color = 99', 'True'),
('Attr.Font = 99', 'True'), ('Attr.InstanceValue = "CHANGED"', 'True'),
('Conn.Net.UID = "OTHER"', 'True'), ('Pin.X = 20', 'True'),
('QP_App.ActiveView.Pins.RemoveAll', 'True'), ('', 'False'),
('zero_pin_annotation', 'False'),
('protocol_duplicate_g', 'True'), ('protocol_duplicate_x', 'True'),
('protocol_missing_g', 'True'), ('protocol_missing_x', 'True'),
('protocol_wrong_g_uid', 'True'), ('protocol_extra_g', 'True'),
('protocol_missing_u', 'True'),
])
def test_unselected_full_readback_catches_collateral_changes(tmp_path, mutation, expected):
snapshot = str(tmp_path / 'snapshot.tsv').replace('"', '""')
setup = ''
if mutation == 'zero_pin_annotation':
setup, mutation = 'QP_App.ActiveView.Pins.RemoveAll: Comp.Attributes.RemoveAll', ''
protocol = mutation.startswith('protocol_')
protocol_change = {
'protocol_duplicate_g': 'Text = Text & ProtocolLines(UBound(ProtocolLines) - 1) & vbCrLf',
'protocol_duplicate_x': 'Text = Text & "X" & vbTab & "untouched_full_v1" & vbCrLf',
'protocol_missing_g': 'Text = Left(Text, InStr(Text, "G" & vbTab) - 1)',
'protocol_missing_x': 'Text = Replace(Text, "X" & vbTab & "untouched_full_v1" & vbCrLf, "")',
'protocol_wrong_g_uid': 'Text = Replace(Text, "G" & vbTab & "u2", "G" & vbTab & "unknown")',
'protocol_extra_g': 'Text = Text & Replace(ProtocolLines(UBound(ProtocolLines) - 1), "G" & vbTab & "u2", "G" & vbTab & "unknown") & vbCrLf',
'protocol_missing_u': 'Text = Replace(Text, ProtocolLines(UBound(ProtocolLines) - 2) & vbCrLf, "")',
}.get(mutation, '')
if protocol:
mutation = ''
output = run_vbs(tmp_path, UNTOUCHED_ROUTINES, '''
Dim Comp, SelectedComp, Attr, Pin, Conn, Net, Text, Records, QueriesBefore, ProtocolLines
Set QP_App = New FakeApp
Set Comp = New FullComponent: Comp.UID = "u2": Comp.Refdes = "R2"
Set SelectedComp = New FullComponent: SelectedComp.UID = "u1": SelectedComp.Refdes = "R1"
QP_App.ActiveView.Components.Add Comp, True
QP_App.ActiveView.Components.Add SelectedComp, True
Set Attr = New FullAttribute: Comp.Attributes.Add Attr, True
Set Net = New FakeNet: Net.UID = "NET_A": Net.LogicalNetName = "A"
Set Conn = New FakeConnection: Set Conn.Net = Net
Set Pin = New FakePin: Set Pin.Component = Comp: Pin.Number = "1": Pin.X = 0: Pin.Y = 0
Set Pin.Connection = Conn: QP_App.ActiveView.Pins.Add Pin, True
''' + setup + '''
Text = "M" & vbTab & "C:\\board.prj" & vbTab & "OLD" & vbTab & "NEW" & vbTab & "MAIN:1" & vbCrLf & _
"C" & vbTab & "u1" & vbTab & "R1" & vbTab & "0" & vbTab & "0" & vbTab & "0" & vbTab & "1" & vbTab & "" & vbCrLf & _
"A" & vbTab & "u1" & vbTab & "Value" & vbTab & "v" & vbTab & "v" & vbTab & "0" & vbTab & "0" & vbTab & "0" & vbTab & "0" & vbTab & "0" & vbTab & "0" & vbTab & "1" & vbCrLf & _
"X" & vbTab & "untouched_full_v1" & vbCrLf & QPUntouchedComponent(Comp)
ProtocolLines = Split(Text, vbCrLf)
''' + protocol_change + '''
QPWriteUtf8 "''' + snapshot + '''", Text
On Error Resume Next
Set Records = QPReadSnapshot("''' + snapshot + '''")
QueriesBefore = QP_App.ActiveView.Queries
''' + mutation + '''
If Err.Number = 0 Then QPVerifyUntouched Records
WScript.Echo CStr(Err.Number <> 0)
WScript.Echo CStr((QP_App.ActiveView.Queries - QueriesBefore >= 2) Or ''' + str(protocol) + ''')
''', LOG_STUB + FULL_FAKE)
assert output.splitlines() == [expected, 'True']
def test_unselected_zero_pin_annotation_is_verified_without_error(tmp_path):
output = run_vbs(tmp_path, UNTOUCHED_ROUTINES, '''
Dim Comp, Text
Set QP_App = New FakeApp
Set Comp = New FullComponent: Comp.UID = "note": Comp.Refdes = ""
QP_App.ActiveView.Components.Add Comp, True
Text = QPUntouchedComponent(Comp)
WScript.Echo CStr(InStr(Text, "G" & vbTab & "note" & vbTab) > 0)
''', LOG_STUB + FULL_FAKE)
assert output == 'True'
@pytest.mark.parametrize('read_failure', [False, True])
def test_all_match_capture_protects_unselected_and_does_not_hide_pn_error(tmp_path, read_failure):
snapshot = str(tmp_path / 'captured.tsv')
output = run_vbs(tmp_path, UNTOUCHED_ROUTINES + ['QPCaptureAndSelect', 'QPSnapshotComponent',
'QPCommandTargets', 'QPBooleanText', 'QPLogField'], '''
Dim Comp, Other, Attr, Pin, Command, Records
Set QP_App = New FakeApp
Set Comp = New FullComponent: Comp.UID = "u1": Comp.Refdes = "R1"
Set Other = New FullComponent: Other.UID = "u2": Other.Refdes = "R2"
Set Attr = New FullAttribute: Attr.Name = "Part Number": Attr.Value = "OLD": Attr.InstanceValue = "OLD"
Comp.Attributes.Add Attr, True
QP_App.ActiveView.Components.Add Comp, True: QP_App.ActiveView.Components.Add Other, True
Set Pin = New FakePin: Set Pin.Component = Comp: Pin.Number = "1": Pin.X = 0: Pin.Y = 0
Set Pin.Connection = Nothing: QP_App.ActiveView.Pins.Add Pin, True
Comp.RaiseOnFind = ''' + ('True' if read_failure else 'False') + '''
Set Command = CreateObject("Scripting.Dictionary")
Command.Add "job_id", "test": Command.Add "old_part_number", "OLD": Command.Add "new_part_number", "NEW"
On Error Resume Next
QPCaptureAndSelect Command, "''' + snapshot + '''"
WScript.Echo Err.Number
WScript.Echo CapturedState
Err.Clear
If CapturedState = "awaiting_native_replace" Then
Set Records = QPReadSnapshot("''' + snapshot + '''")
Other.X = 30
QPVerifyUntouched Records
WScript.Echo CStr(Err.Number <> 0)
End If
''', LOG_STUB + FULL_FAKE + '''
Dim CapturedState
Sub QPBuildComponentIndex(ByRef Components)
End Sub
Function QPValueMode(ByRef Command)
QPValueMode = "preserve"
End Function
Function QPCustomValue(ByRef Command)
QPCustomValue = ""
End Function
Function QPSyncNc(ByRef Command)
QPSyncNc = False
End Function
Sub QPWriteStatus(ByVal Root, ByVal Job, ByVal State, ByVal Code, ByVal Message)
CapturedState = State
End Sub
''')
if read_failure:
assert output == '1234'
else:
assert output.splitlines() == ['0', 'awaiting_native_replace', 'True']
def test_rollback_ignores_extension_rows_in_selected_state_comparison(tmp_path):
snapshot = str(tmp_path / 'rollback.tsv')
output = run_vbs(tmp_path, ['QPRollbackNativeReplacement', 'QPReadSnapshot', 'QPReadUtf8',
'QPWriteUtf8', 'QPEncode', 'QPDecode', 'QPInvalidatePinIndex'], '''
Dim Text
OriginalSelected = "C" & vbTab & "u1" & vbTab & "R1" & vbTab & "0" & vbTab & "0" & vbTab & "0" & vbTab & "1" & vbTab & "" & vbCrLf & _
"A" & vbTab & "u1" & vbTab & "Value" & vbTab & "v" & vbTab & "v" & vbTab & "0" & vbTab & "0" & vbTab & "0" & vbTab & "0" & vbTab & "0" & vbTab & "0" & vbTab & "1" & vbCrLf
Text = "M" & vbTab & "C:\\board.prj" & vbTab & "OLD" & vbTab & "NEW" & vbTab & "MAIN:1" & vbCrLf & _
OriginalSelected & "X" & vbTab & "untouched_full_v1" & vbCrLf
QPWriteUtf8 "''' + snapshot + '''", Text
Set QP_App = New FakeApp
QP_CurrentJobId = "test"
On Error Resume Next
QPRollbackNativeReplacement "''' + snapshot + '''"
WScript.Echo Err.Number
''', LOG_STUB + FULL_FAKE + '''
Dim QP_CurrentJobId, OriginalSelected, QP_NativeMutationPossible
Function QPJobSnapshotPath(ByVal Job)
QPJobSnapshotPath = "''' + snapshot + '''"
End Function
Sub QPRequireSnapshotContext(ByVal Path)
End Sub
Sub QPVerifyUntouched(ByRef Records)
End Sub
Function QPFindUniqueByOldLocation(ByRef Record)
Set QPFindUniqueByOldLocation = New FullComponent
End Function
Function QPSnapshotComponent(ByRef Comp)
QPSnapshotComponent = OriginalSelected
End Function
''')
assert output == '0'
def test_whole_vbs_compiles_with_option_explicit_without_starting_cad(tmp_path):
source = SOURCE.read_text(encoding='ascii')
# Compile every production routine with all real declarations, and stop
# before the top-level bootstrap can attach to or start an application.
declarations = source[:source.index('On Error Resume Next\nQPBootstrapSession')]
routines = re.findall(r'(?mi)^(Function|Sub) (\w+)\(', source)
script = tmp_path / 'compile.vbs'
script.write_text(declarations + '\n' + '\n'.join(routine(name) for _, name in routines)
+ '\nWScript.Echo "PARSED"\n', encoding='ascii')
result = subprocess.run(['cscript.exe', '//nologo', str(script)], capture_output=True,
text=True, timeout=15)
assert result.returncode == 0, result.stdout + result.stderr
assert result.stdout.strip() == 'PARSED'
@@ -0,0 +1,37 @@
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import native_helper as native
LIBRARY = ['RESISTOR', 'NEW', 'lib:res', '', 'RESC1608N', '1M']
RECORDS = [['C', '$2I100', 'R1', '0', '0', '0', '1', '']]
def component(*, uid='$2I100', refdes='R1', name='RESC1608N', label='1M'):
attrs = {'Part Number': 'NEW', 'Part Name': name, 'Part Label': label}
return SimpleNamespace(UID=uid, Refdes=refdes,
FindAttribute=lambda key: SimpleNamespace(InstanceValue=attrs[key], Value=attrs[key]))
@pytest.mark.parametrize('change', ['footprint', 'footprint_case', 'label', 'label_case'])
def test_normal_replacement_requires_the_selected_library_identity(change):
current = component(name='RESC1005N' if change == 'footprint' else 'resc1608n' if change == 'footprint_case' else 'RESC1608N',
label='10K' if change == 'label' else '1m' if change == 'label_case' else '1M')
with pytest.raises(ValueError, match='library identity'):
native.replacement_matches([current], RECORDS, 'NEW', True, library_row=LIBRARY)
def test_recovery_never_substitutes_a_different_uid_with_the_same_refdes():
with pytest.raises(ValueError, match='identity|UID'):
native.existing_replacement_uids([component(uid='$2I999')], RECORDS, 'NEW', {'library_row': LIBRARY})
def test_recovery_treats_part_label_case_as_significant():
with pytest.raises(ValueError, match='library identity'):
native.existing_replacement_uids([component(label='1m')], RECORDS, 'NEW', {'library_row': LIBRARY})
def test_normal_replacement_accepts_only_the_matching_library_record():
assert native.replacement_matches([component()], RECORDS, 'NEW', True, library_row=LIBRARY) == ['$2I100']