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

883 lines
37 KiB
Python

import ast
from pathlib import Path
import re
import subprocess
import pytest
ROOT = Path(__file__).resolve().parents[2]
SOURCE = ROOT / 'integration/dxdesigner795/QuickPartReplace.vbs'
TREE = ast.parse((Path(__file__).with_name('test_automatic_replacement_regression.py')).read_text(encoding='utf-8'))
FAKES = next(ast.literal_eval(statement.value) for statement in TREE.body
if isinstance(statement, ast.Assign) and any(isinstance(target, ast.Name) and target.id == 'FAKES'
for target in statement.targets))
EXTRA = r'''
Class ValueComponent
Public UID, Refdes, Orientation, Scale, Attributes, AddCount
Private Point
Private Sub Class_Initialize()
Set Point=New TestPoint
Point.X=0: Point.Y=0
AddCount=0
Set Attributes=CreateObject("Scripting.Dictionary")
End Sub
Public Function GetLocation()
Set GetLocation=Point
End Function
Public Sub SetLocation(ByVal LocationX,ByVal LocationY)
Point.X=LocationX: Point.Y=LocationY
End Sub
Public Function FindAttribute(ByVal Name)
Dim Attr
Set FindAttribute=Nothing
For Each Attr In Attributes
If Attr.Name=Name Then Set FindAttribute=Attr
Next
End Function
Public Sub RemoveAttribute(ByVal Name)
Dim Attr
For Each Attr In Attributes
If Attr.Name=Name Then
Attributes.Remove Attr
Exit Sub
End If
Next
End Sub
Public Function AddAttribute(ByVal Text, ByVal LocationX, ByVal LocationY, ByVal Visibility)
Dim Separator, Attr
Separator=InStr(Text,"=")
Set Attr=AddValueAttr(Me,Left(Text,Separator-1),Mid(Text,Separator+1))
Attr.SetLocation LocationX,LocationY
Attr.Visible=Visibility
AddCount=AddCount+1
Set AddAttribute=Attr
End Function
End Class
Class ValuePin
Public Component, Number
Public Property Get Connection
Set Connection=Me
End Property
Public Property Get Net
Set Net=Me
End Property
Public Property Get UID
UID="NET1"
End Property
Public Property Get LogicalNetName
LogicalNetName="VCC"
End Property
Public Function GetLocation()
Dim Point
Set Point=New TestPoint
Point.X=10: Point.Y=10
Set GetLocation=Point
End Function
End Class
Class ValueApp
Public Components, Pins, ProjectPath, UndoCount, PinQueries, TransactionOpen, TransactionCount
Public DocumentCount, CloseCount, SaveCalled, SaveCount, RefuseClose
Public Function SchematicSheetDocuments()
Set SchematicSheetDocuments=Me
End Function
Public Property Get Count
Count=DocumentCount
End Property
Public Function Item(ByVal DocumentIndex)
Require DocumentIndex=1,"unexpected document index"
Set Item=Me
End Function
Public Sub Close(ByVal SaveChanges,ByVal FileName)
CloseCount=CloseCount+1
If SaveChanges Then
SaveCalled=True
SaveCount=SaveCount+1
End If
End Sub
Public Sub CloseProject()
Require CloseCount=1,"project closed before document"
If Not RefuseClose Then ProjectPath=""
End Sub
Public Property Get ActiveView
Set ActiveView=Me
End Property
Public Property Get Block
Set Block=Me
End Property
Public Property Get SheetNum
SheetNum=1
End Property
Public Function GetName(ByVal Flags)
GetName="A"
End Function
Public Function GetProjectData()
Set GetProjectData=Me
End Function
Public Function GetProjectFilePath()
GetProjectFilePath=ProjectPath
End Function
Public Function Query(ByVal Flags,ByVal Selection)
If Flags=128 Then
Set Query=Components
Else
PinQueries=PinQueries+1
Set Query=Pins
End If
End Function
Public Sub StartUndoTransaction()
TransactionCount=TransactionCount+1
TransactionOpen=True
End Sub
Public Sub EndUndoTransaction()
TransactionOpen=False
End Sub
Public Function ExecuteCommand(ByVal Command)
UndoCount=UndoCount+1
ExecuteCommand=True
End Function
End Class
Function AddValueAttr(ByRef Comp,ByVal Name,ByVal Text)
Dim Attr
Set Attr=New TestAttribute
Attr.Name=Name: Attr.Value=Text: Attr.InstanceValue=""
Attr.Font=0: Attr.Size=10: Attr.Visible=1
Comp.Attributes.Add Attr,True
Set AddValueAttr=Attr
End Function
'''
SETUP = r'''
Dim Comp, Pin, Attr, Ignored, Command, Snapshot, SnapshotPath, Failure, Saved
Set QP_Fso=CreateObject("Scripting.FileSystemObject")
QP_Root="__ROOT__"
QP_CurrentJobId="value-job"
Set QP_App=New ValueApp
QP_App.ProjectPath="C:\value-test\one.prj": QP_App.UndoCount=0
QP_App.DocumentCount=1: QP_App.CloseCount=0: QP_App.SaveCalled=False: QP_App.RefuseClose=False
Set QP_App.Components=CreateObject("Scripting.Dictionary")
Set QP_App.Pins=CreateObject("Scripting.Dictionary")
Set Comp=New ValueComponent
Comp.UID="recorded": Comp.Refdes="R1": Comp.Orientation=0: Comp.Scale=1
QP_App.Components.Add Comp,True
Set Pin=New ValuePin
Set Pin.Component=Comp: Pin.Number="1"
QP_App.Pins.Add Pin,True
Set Ignored=AddValueAttr(Comp,"Part Number","OLD")
Set Ignored=AddValueAttr(Comp,"Part Name","OLD_NAME")
Set Ignored=AddValueAttr(Comp,"Part Label","OLD_LABEL")
Set Attr=AddValueAttr(Comp,"Value","OLD_VALUE")
Set Saved=StyleRecord()
QPRestoreDisplay Attr,Saved,"R1"
Set Command=CreateObject("Scripting.Dictionary")
Command.Add "job_id","value-job"
Command.Add "old_part_number","OLD"
Command.Add "new_part_number","NEW"
Command.Add "value_mode","__MODE__"
Command.Add "custom_value","__CUSTOM__"
Command.Add "sync_nc","__SYNC_NC__"
__BEFORE__
SnapshotPath=QPJobSnapshotPath(QP_CurrentJobId)
Snapshot="M" & vbTab & QPEncode(QPProjectPath()) & vbTab & "OLD" & vbTab & "NEW" & vbTab & QPEncode(QPSheetIdentity()) & vbTab & "__MODE__" & vbTab & QPEncode("__CUSTOM__") & vbTab & "__SYNC_NC__" & vbCrLf & QPSnapshotComponent(Comp)
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"
Set Attr=Comp.FindAttribute("Part Label"): Attr.Value="NEW_LABEL"
Comp.RemoveAttribute "Value"
Set Attr=AddValueAttr(Comp,"Value","TARGET_VALUE")
Attr.SetLocation 900,901
__AFTER__
'''
def run_vbs(tmp_path, mode, body, *, before='', after='', custom_value='', sync_nc=True, routines_transform=None):
source = SOURCE.read_text(encoding='utf-8-sig')
header = source[:source.index('Set QP_Fso =')]
routines = source[source.index('Sub QPMain()'):]
if routines_transform is not None:
routines = routines_transform(routines)
setup = (SETUP.replace('__ROOT__', str(tmp_path)).replace('__MODE__', mode)
.replace('__CUSTOM__', custom_value).replace('__SYNC_NC__', '1' if sync_nc else '0')
.replace('__BEFORE__', before).replace('__AFTER__', after))
wrapper = tmp_path / 'value-regression.vbs'
wrapper.write_text(header + setup + body + '\nWScript.Echo "PASS"\nWScript.Quit 0\n' + FAKES + EXTRA + routines, encoding='ascii')
result = subprocess.run(['cscript.exe', '//nologo', str(wrapper)], capture_output=True, timeout=15,
creationflags=subprocess.CREATE_NO_WINDOW)
assert result.returncode == 0, (result.stdout + result.stderr).decode(errors='replace')
assert b'PASS' in result.stdout
def test_recovery_of_saved_result_does_not_write_again(tmp_path):
run_vbs(tmp_path, 'part_number', '''
Command.Add "recovery_part_name","NEW_NAME"
Command.Add "recovery_part_label","NEW_LABEL"
QPRestoreAfterOperatorReplace Command,SnapshotPath
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"status.tsv"),"job_id" & vbTab & "state" & vbTab & "code" & vbTab & "message" & vbCrLf
QPRecoverSavedJob Command,SnapshotPath
Require QP_App.TransactionCount=1,"already restored task wrote to CAD again"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"recovery_verified")>0,"did not identify already saved completion"
Require QP_App.UndoCount=0,"recovery undid prior CAD work"
''')
@pytest.mark.parametrize('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)
def _batch_readback_fixture(routines, *, fault=''):
# Exercise real restore/finish/guards, replacing only the external open and
# command transport with an in-memory CAD-shaped application.
routines = re.sub(r'(?ms)^Function QPReadCommand\([^\n]*\n.*?^End Function', '''Function QPReadCommand(ByVal Path)
Set QPReadCommand=Command
End Function''', routines)
routines = re.sub(r'(?ms)^Sub QPEnsureProject\([^\n]*\n.*?^End Sub', '''Sub QPEnsureProject(ByRef App, ByVal TargetPath)
App.ProjectPath=TargetPath
App.CloseCount=0
QP_OwnedProject=True
QP_OwnedProjectPath=TargetPath
''' + ('Set Attr=Other.FindAttribute("Value"): Attr.Value="DRIFT"' if fault == 'after_reopen' else '') + '''
End Sub''', routines)
injection = 'FullChecks=FullChecks+1\n'
if fault == 'before_save':
injection += 'If FullChecks=1 Then Other.FindAttribute("Value").Value="DRIFT"\n'
return routines.replace('Sub QPVerifyUntouched(ByRef Records)\n',
'Sub QPVerifyUntouched(ByRef Records)\n' + injection)
@pytest.mark.parametrize('fault', ['', 'before_save', 'after_reopen'])
def test_owned_batch_checks_full_state_at_save_and_disk_boundaries(tmp_path, fault):
run_vbs(tmp_path, 'part_number', '''
Dim FullChecks
FullChecks=0
Command.Add "project_path",QPProjectPath()
QP_BatchMode=True: QP_SessionMode=True
QP_SessionToken=String(32,"b")
QP_OwnedProject=True: QP_OwnedProjectPath=QPProjectPath()
QPRestoreAfterOperatorReplace Command,SnapshotPath
Require FullChecks=0,"full scans repeated before the commit boundary"
On Error Resume Next
QPFinishBatchItem
Failure=Err.Number
Err.Clear
On Error GoTo 0
''' + ('''
Require Failure=0,"valid batch failed"
Require FullChecks=2,"expected one full check before save and one after reopen"
Require QP_App.SaveCalled,"valid batch did not save"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"project-session-result.tsv")),"saved_ok")>0,"no verified result"
''' if not fault else '''
Require Failure<>0,"unselected drift passed the commit guard"
Require Not QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root,"project-session-result.tsv")),"failure published a completion"
Require QP_App.SaveCalled=''' + ('True' if fault == 'after_reopen' else 'False') + ''',"wrong save boundary"
Require QP_BatchSaveCommitted=''' + ('True' if fault == 'after_reopen' else 'False') + ''',"saved uncertainty marker is wrong"
'''), after='''
Dim Other
Set Other=New ValueComponent
Other.UID="unselected": Other.Refdes="R2": Other.Orientation=0: Other.Scale=1
Set Ignored=AddValueAttr(Other,"Value","SAFE")
QP_App.Components.Add Other,True
QPWriteUtf8 SnapshotPath,QPReadUtf8(SnapshotPath) & QPUntouchedComponent(Other)
''', routines_transform=lambda routines: _batch_readback_fixture(routines, fault=fault))
@pytest.mark.parametrize('refuse_close', [False, True])
def test_verified_disk_recovery_closes_without_saving_or_reopening(tmp_path, refuse_close):
run_vbs(tmp_path, 'part_number', '''
Command.Add "recovery_part_name","NEW_NAME"
Command.Add "recovery_part_label","NEW_LABEL"
Command.Add "project_path",QPProjectPath()
QPRestoreAfterOperatorReplace Command,SnapshotPath
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"status.tsv"),"job_id" & vbTab & "state" & vbTab & "code" & vbTab & "message" & vbCrLf
QP_BatchMode=True
QP_OwnedProject=True: QP_OwnedProjectPath=QPProjectPath()
QP_App.RefuseClose=''' + ('True' if refuse_close else 'False') + '''
On Error Resume Next
QPRecoverSavedJob Command,SnapshotPath
Failure=Err.Number
Err.Clear
On Error GoTo 0
Require Not QP_App.SaveCalled,"read-only disk recovery saved again"
''' + ('''
Require Failure<>0,"unconfirmed recovery close was accepted"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"recovery_saved_verified")=0,"failure published proof"
''' if refuse_close else '''
Require Failure=0,"valid disk recovery failed"
Require Not QP_BatchMode,"read-only recovery will trigger a duplicate finish/save"
Require QP_App.CloseCount=1 And Len(QP_App.ProjectPath)=0,"verified recovery did not close"
Require Not QP_OwnedProject,"closed recovery retains stale ownership"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"recovery_saved_verified")>0,"missing disk proof"
'''))
def test_command_snapshot_validation_reads_the_file_once(tmp_path):
def count_reads(routines):
return routines.replace('Function QPReadSnapshot(ByVal Path)\n',
'Function QPReadSnapshot(ByVal Path)\n SnapshotReads=SnapshotReads+1\n')
run_vbs(tmp_path, 'part_number', '''
Dim SnapshotReads
SnapshotReads=0
QPRequireCommandSnapshot Command,SnapshotPath
Require SnapshotReads=1,"same boundary parsed its snapshot twice"
''', routines_transform=count_reads)
def test_non_session_batch_saves_once_and_closes_disk_readback_without_saving(tmp_path):
run_vbs(tmp_path, 'part_number', '''
Dim FullChecks
FullChecks=0
Command.Add "project_path",QPProjectPath()
QP_BatchMode=True: QP_SessionMode=False
QP_OwnedProject=True: QP_OwnedProjectPath=QPProjectPath()
QPRestoreAfterOperatorReplace Command,SnapshotPath
QPFinishBatchItem
Require QP_App.SaveCount=1,"read-only disk verification saved the project again"
Require Len(QP_App.ProjectPath)=0,"batch did not close the readback project"
Require QP_BatchSaveCommitted,"real replacement save was not recorded"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"saved_ok")>0,"no completion proof"
''', routines_transform=_batch_readback_fixture)
def test_non_session_no_match_closes_without_any_save(tmp_path):
run_vbs(tmp_path, 'part_number', '''
Dim FullChecks
FullChecks=0
Command.Add "project_path",QPProjectPath()
QP_BatchMode=True: QP_SessionMode=False
QP_OwnedProject=True: QP_OwnedProjectPath=QPProjectPath()
QPCaptureAndSelect Command,SnapshotPath
QPFinishBatchItem
Require Not QP_App.SaveCalled,"no-match project was saved despite no replacement writes"
Require Not QP_BatchSaveCommitted,"no-match was recorded as a save"
Require Len(QP_App.ProjectPath)=0,"no-match owned project did not close"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"no_match")>0,"no-match proof missing"
''', routines_transform=_batch_readback_fixture)
@pytest.mark.parametrize('mode', ['preserve', 'part_label', 'part_number'])
def test_recovery_repairs_attributes_without_native_replace(tmp_path, mode):
run_vbs(tmp_path, mode, '''
Command.Add "recovery_part_name","NEW_NAME"
Command.Add "recovery_part_label","NEW_LABEL"
QPRecoverSavedJob Command,SnapshotPath
Require QP_App.TransactionCount=1,"did not restore in one owned transaction"
Require Not QP_App.TransactionOpen,"recovery transaction remains open"
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),QP_CurrentJobId)="restored_ok","recovery failed"
Require QP_App.UndoCount=0,"recovery undid native transaction"
''')
def test_recovery_of_unsaved_result_only_prepares_retry(tmp_path):
run_vbs(tmp_path, 'part_number', '''
Set Attr=Comp.FindAttribute("Part Number"): Attr.Value="OLD"
Set Attr=Comp.FindAttribute("Part Name"): Attr.Value="OLD_NAME"
Set Attr=Comp.FindAttribute("Part Label"): Attr.Value="OLD_LABEL"
Set Attr=Comp.FindAttribute("Value"): Attr.Value="OLD_VALUE"
QPRestoreDisplay Attr,Saved,"R1"
QPRecoverSavedJob Command,SnapshotPath
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),QP_CurrentJobId)="retry_ready","original source not recognized"
Require Not QP_App.TransactionOpen,"unchanged source was modified"
Require QP_App.UndoCount=0,"unchanged source was undone"
Require QP_App.CloseCount=1,"read-only document was not closed"
Require Not QP_App.SaveCalled,"read-only recovery saved unexpectedly"
Require Len(QP_App.ProjectPath)=0,"retry would be blocked by an open recovery project"
''')
@pytest.mark.parametrize('change', ['QP_App.DocumentCount=2', 'QP_App.RefuseClose=True'])
def test_readonly_recovery_does_not_unlock_if_document_ownership_or_close_fails(tmp_path, change):
run_vbs(tmp_path, 'part_number', '''
Set Attr=Comp.FindAttribute("Part Number"): Attr.Value="OLD"
Set Attr=Comp.FindAttribute("Part Name"): Attr.Value="OLD_NAME"
Set Attr=Comp.FindAttribute("Part Label"): Attr.Value="OLD_LABEL"
Set Attr=Comp.FindAttribute("Value"): Attr.Value="OLD_VALUE"
QPRestoreDisplay Attr,Saved,"R1"
''' + change + '''
On Error Resume Next
QPRecoverSavedJob Command,SnapshotPath
Failure=Err.Number
Err.Clear
On Error GoTo 0
Require Failure<>0,"unsafe close did not fail"
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),QP_CurrentJobId)<>"retry_ready","unsafe close unlocked retry"
Require Not QP_App.SaveCalled,"unsafe close saved project"
''')
@pytest.mark.parametrize('change', ['Pin.Number="2"', 'Set Attr=Comp.FindAttribute("Part Name"): Attr.Value="OTHER"'])
def test_recovery_rejects_connection_or_identity_changes(tmp_path, change):
run_vbs(tmp_path, 'part_number', '''
Command.Add "recovery_part_name","NEW_NAME"
Command.Add "recovery_part_label","NEW_LABEL"
''' + change + '''
On Error Resume Next
QPRecoverSavedJob Command,SnapshotPath
Failure=Err.Number
Err.Clear
On Error GoTo 0
Require Failure<>0,"unsafe target accepted"
Require Not QP_App.TransactionOpen,"unsafe recovery wrote to CAD"
Require QP_App.UndoCount=0,"unsafe recovery undid work"
''')
def test_recovery_read_error_does_not_trigger_restore(tmp_path):
def broken_verification(routines):
signature = 'Sub QPVerifyRestoredPlans(ByRef Command, ByRef Records, ByRef Plans, ByRef ValueStates)'
return routines.replace(signature, signature + '\n Err.Raise 440,"Test","COM read failed"')
run_vbs(tmp_path, 'part_number', '''
Command.Add "recovery_part_name","NEW_NAME"
Command.Add "recovery_part_label","NEW_LABEL"
On Error Resume Next
QPRecoverSavedJob Command,SnapshotPath
Failure=Err.Number
Err.Clear
On Error GoTo 0
Require Failure=440,"COM read error was swallowed"
Require Not QP_App.TransactionOpen,"COM failure triggered writes"
''', routines_transform=broken_verification)
def test_zero_match_reports_without_snapshot_or_selection_writes(tmp_path):
run_vbs(tmp_path, 'preserve', r'''
QP_Fso.DeleteFile SnapshotPath
QP_NativeMutationPossible=False
QPCaptureAndSelect Command, SnapshotPath
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),"value-job")="no_match","zero match state"
Require Not QP_Fso.FileExists(SnapshotPath),"no snapshot for no match"
Require Comp.FindAttribute("Part Number").Value="NEW","component untouched"
Require Not QP_NativeMutationPossible,"no native mutation"
''')
def test_zero_match_does_not_read_unused_component_geometry(tmp_path, monkeypatch):
counted = EXTRA.replace('Public UID, Refdes, Orientation, Scale, Attributes, AddCount',
'Public UID, Refdes, Orientation, Scale, Attributes, AddCount, LocationReads')
counted = counted.replace('Set GetLocation=Point',
'LocationReads=LocationReads+1\n Set GetLocation=Point', 1)
monkeypatch.setattr(f'{__name__}.EXTRA', counted)
run_vbs(tmp_path, 'preserve', '''
QP_Fso.DeleteFile SnapshotPath
Comp.LocationReads=0
QPCaptureAndSelect Command,SnapshotPath
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),"value-job")="no_match","no-match state"
Require Comp.LocationReads=0,"no-match read geometry for an index that is never consumed"
Require Not QP_Fso.FileExists(SnapshotPath),"no-match generated a snapshot"
''')
def test_component_lookup_reads_fallback_geometry_only_when_needed(tmp_path, monkeypatch):
counted = EXTRA.replace('Public UID, Refdes, Orientation, Scale, Attributes, AddCount',
'Public UID, Refdes, Orientation, Scale, Attributes, AddCount, LocationReads')
counted = counted.replace('Set GetLocation=Point',
'LocationReads=LocationReads+1\n Set GetLocation=Point', 1)
monkeypatch.setattr(f'{__name__}.EXTRA', counted)
run_vbs(tmp_path, 'preserve', '''
Dim Records, Record, Candidate
Set Records=QPReadSnapshot(SnapshotPath)
Set Record=Records.Item("components").Item("0")
QPInvalidateComponentIndex
Comp.LocationReads=0
Set Candidate=QPFindUniqueByOldLocation(Record)
Require Candidate Is Comp,"UID lookup returned wrong component"
Require Comp.LocationReads=0,"UID lookup eagerly read fallback geometry"
Record("uid")="missing"
Set Candidate=QPFindUniqueByOldLocation(Record)
Require Candidate Is Comp,"refdes fallback returned wrong component"
Require Comp.LocationReads=0,"refdes lookup eagerly read location fallback"
Record("refdes")="missing"
Set Candidate=QPFindUniqueByOldLocation(Record)
Require Candidate Is Comp,"location fallback returned wrong component"
Require Comp.LocationReads=1,"location fallback did not read geometry exactly once"
Set Candidate=QPFindUniqueByOldLocation(Record)
Require Comp.LocationReads=1,"same read context rebuilt its fallback index"
QPInvalidateComponentIndex
Set Candidate=QPFindUniqueByOldLocation(Record)
Require Candidate Is Comp,"fresh location fallback returned wrong component"
Require Comp.LocationReads=2,"invalidated index reused stale geometry"
''')
def test_pin_index_avoids_repeated_full_sheet_queries(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QPInvalidatePinIndex
QP_App.PinQueries=0
Dim Repeated, Signature
For Repeated=1 To 67
Signature=QPConnectionSignature(Comp)
Next
Require QP_App.PinQueries=1,"rescanned whole sheet for each component check"
''')
def test_pin_index_is_rebuilt_after_mutation_boundary(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QPInvalidatePinIndex
QP_App.PinQueries=0
Dim Signature
Signature=QPConnectionSignature(Comp)
Set QP_App.Pins=CreateObject("Scripting.Dictionary")
Set Pin=New ValuePin
Set Pin.Component=Comp: Pin.Number="2"
QP_App.Pins.Add Pin,True
QPInvalidatePinIndex
Signature=QPConnectionSignature(Comp)
Require QP_App.PinQueries=2,"mutation did not invalidate index"
Require Left(Signature,2)="2|","stale pin reused"
''')
def test_pin_index_is_invalidated_by_project_change(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QPInvalidatePinIndex
QP_App.PinQueries=0
Dim Signature
Signature=QPConnectionSignature(Comp)
QP_App.ProjectPath="C:\\value-test\\two.prj"
Set QP_App.Pins=CreateObject("Scripting.Dictionary")
Set Pin=New ValuePin
Set Pin.Component=Comp: Pin.Number="2"
QP_App.Pins.Add Pin,True
Signature=QPConnectionSignature(Comp)
Require QP_App.PinQueries=2,"cross-project index reuse"
Require Left(Signature,2)="2|","cross-project stale pin"
''')
def test_cancel_is_deferred_while_native_helper_is_active(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QP_AttemptToken=String(32,"a")
QP_ExpectedJobId=QP_CurrentJobId
QP_NativeMutationPossible=False
QP_NativeCallActive=True
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"monitor-" & QP_AttemptToken & ".stop"),QP_AttemptToken
QPProgress "native_replace",0,1
Require Not QP_NativeMutationPossible,"helper start was mistaken for mutation evidence"
''')
def test_stale_cancel_token_does_not_stop_current_attempt(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QP_AttemptToken=String(32,"a")
QP_ExpectedJobId=QP_CurrentJobId
QP_NativeMutationPossible=False
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"monitor-" & QP_AttemptToken & ".stop"),String(32,"b")
QPProgress "capture",0,1
''')
def test_restoration_closes_transaction_and_reuses_pin_index_for_verification(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QP_App.PinQueries=0
QPRestoreAfterOperatorReplace Command,SnapshotPath
Require Not QP_App.TransactionOpen,"transaction left open"
Require Not QP_RestoreTransactionOpen,"worker transaction flag left open"
Require QP_App.PinQueries=1,"restoration should reuse the post-replacement pin index"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")), _
"Replacements: R1 OLD -> NEW")>0,"replacement mapping status missing"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"quick-part-replace.log")), _
"replacement R1 OLD -> NEW")>0,"replacement mapping log missing"
''')
def test_cancel_during_restoration_is_deferred_until_safe_completion(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QP_AttemptToken=String(32,"a")
QP_ExpectedJobId=QP_CurrentJobId
QP_NativeMutationPossible=True
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"monitor-" & QP_AttemptToken & ".stop"),QP_AttemptToken
QPRestoreAfterOperatorReplace Command,SnapshotPath
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),QP_CurrentJobId)="restored_ok","cancel interrupted restoration"
Require Not QP_App.TransactionOpen,"cancel left transaction open"
''')
def test_cancel_before_mutation_stops_at_checkpoint(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QP_AttemptToken=String(32,"a")
QP_ExpectedJobId=QP_CurrentJobId
QP_NativeMutationPossible=False
QP_RestoreTransactionOpen=False
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"monitor-" & QP_AttemptToken & ".stop"),QP_AttemptToken
On Error Resume Next
QPProgress "capture",0,1
Failure=Err.Source
Err.Clear
On Error GoTo 0
Require Failure="QuickPartReplace.SafeStop","stop was not acknowledged safely"
Require Not QP_App.TransactionOpen,"unexpected transaction"
''')
def test_native_launch_failure_never_claims_mutation_or_undo(tmp_path):
def replace_shell(routines):
return routines.replace('Set Shell = CreateObject("WScript.Shell")', 'Set Shell = New FailingLaunchShell') + '''
Class FailingLaunchShell
Public Function Run(ByVal CommandLine, ByVal WindowStyle, ByVal Wait)
Err.Raise 51000,"FailingLaunchShell","launch refused"
End Function
End Class
'''
run_vbs(tmp_path, 'part_number', '''
QP_HelperExecutable=WScript.FullName
QP_HelperScript=""
QP_NativeMutationPossible=False
On Error Resume Next
QPNativeReplace Command,SnapshotPath
Failure=Err.Source
Err.Clear
On Error GoTo 0
Require Failure="FailingLaunchShell","did not reach launch failure"
Require Not QP_NativeMutationPossible,"launch failure was mistaken for a replacement"
Require QP_App.UndoCount=0,"launch failure invoked undo"
''', routines_transform=replace_shell)
def test_main_continues_after_zero_match_without_calling_native_helper(tmp_path):
run_vbs(tmp_path, 'preserve', r'''
QP_Fso.DeleteFile SnapshotPath
QP_NativeMutationPossible=False
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"command.tsv"), _
"task_id" & vbTab & "job_id" & vbTab & "project_path" & vbTab & "old_part" & vbTab & "new_part" & vbTab & "value_mode" & vbCrLf & _
"task" & vbTab & "value-job" & vbTab & QPProjectPath() & vbTab & "OLD" & vbTab & "NEW" & vbTab & "preserve" & vbCrLf & _
"task" & vbTab & "second-job" & vbTab & QPProjectPath() & vbTab & "OTHER" & vbTab & "OTHER_NEW" & vbTab & "preserve" & vbCrLf
QP_ExpectedJobId="value-job"
QPMain
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),"value-job")="no_match","first item not reported"
QP_ExpectedJobId="second-job"
QPMain
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),"second-job")="no_match","second item blocked"
Require Not QP_Fso.FileExists(SnapshotPath),"unexpected first snapshot"
Require Not QP_Fso.FileExists(QPJobSnapshotPath("second-job")),"unexpected second snapshot"
Require QP_App.UndoCount=0,"unexpected rollback"
''')
@pytest.mark.parametrize('mode,expected', [
('preserve', 'TARGET_VALUE'),
('part_label', 'NEW_LABEL'),
('part_number', 'NEW'),
])
def test_value_content_policy_preserves_original_display(tmp_path, mode, expected):
run_vbs(tmp_path, mode, f'''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="{expected}","Value content policy failed"
QPVerifyDisplay Attr,Saved,"R1"
Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),"value-job")="restored_ok","final verification failed"
''')
def test_unchecked_does_not_create_missing_target_value(tmp_path):
run_vbs(tmp_path, 'preserve', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require Attr Is Nothing,"unchecked created Value"
Require Comp.AddCount=0,"unchecked called AddAttribute"
''', after='Comp.RemoveAttribute "Value"')
def test_checked_creates_value_from_part_label_with_old_style(tmp_path):
run_vbs(tmp_path, 'part_label', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="NEW_LABEL","missing Value not created correctly"
QPVerifyDisplay Attr,Saved,"R1"
''', after='Comp.RemoveAttribute "Value"')
def test_custom_value_overrides_global_source_and_keeps_old_style(tmp_path):
run_vbs(tmp_path, 'custom', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="47k","custom Value was not written"
QPVerifyDisplay Attr,Saved,"R1"
''', custom_value='47k', after='Comp.RemoveAttribute "Value"')
def test_no_old_value_keeps_native_style_when_unchecked(tmp_path):
run_vbs(tmp_path, 'preserve', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="TARGET_VALUE","unexpected content write"
Require Attr.GetLocation().X=900 And Attr.GetLocation().Y=901,"invented old Value style"
''', before='Comp.RemoveAttribute "Value"')
def test_policy_change_is_rejected_before_restore_writes(tmp_path):
run_vbs(tmp_path, 'preserve', '''
Command("value_mode")="part_number"
On Error Resume Next
QPRestoreAfterOperatorReplace Command,SnapshotPath
Failure=Err.Description
Err.Clear
On Error GoTo 0
Require InStr(Failure,"policy mismatch")>0,"snapshot did not bind policy"
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="TARGET_VALUE","wrote before policy validation"
Require QP_App.UndoCount=0,"unexpected Undo"
''')
def test_policy_change_is_rejected_before_native_helper(tmp_path):
run_vbs(tmp_path, 'preserve', '''
Command("value_mode")="part_number"
On Error Resume Next
QPAutomaticReplaceAndRestore Command,SnapshotPath
Failure=Err.Description
Err.Clear
On Error GoTo 0
Require InStr(Failure,"policy mismatch")>0,"called native helper before policy validation"
''')
def test_wrong_active_project_is_rejected_by_vbs_before_selection(tmp_path):
run_vbs(tmp_path, 'preserve', r'''
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"command.tsv"), _
"task_id" & vbTab & "job_id" & vbTab & "project_path" & vbTab & "old_part" & vbTab & "new_part" & vbTab & "value_mode" & vbCrLf & _
"task" & vbTab & "expected-job" & vbTab & "C:\value-test\other.prj" & vbTab & "OLD" & vbTab & "NEW" & vbTab & "preserve" & vbCrLf & _
"task" & vbTab & "other-job" & vbTab & QPProjectPath() & vbTab & "OLD" & vbTab & "NEW" & vbTab & "preserve" & vbCrLf
QP_ExpectedJobId="expected-job"
QP_CurrentJobId=""
On Error Resume Next
Set Command=QPReadCommand(QP_Fso.BuildPath(QP_Root,"command.tsv"))
Failure=Err.Description
Err.Clear
On Error GoTo 0
Require InStr(Failure,"confirmed queue job")>0,"selected different queued project"
Require QP_CurrentJobId="","claimed a job before confirmation validation"
Require QP_App.UndoCount=0,"unexpected Undo"
''')
def test_checked_without_any_old_value_uses_hidden_fallback(tmp_path):
run_vbs(tmp_path, 'part_label', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="NEW_LABEL","wrong created Value"
Require Attr.Visible=0,"missing old Value should not invent a visible style"
''', before='Comp.RemoveAttribute "Value"', after='Comp.RemoveAttribute "Value"')
@pytest.mark.parametrize('native_value', ['', 'INSTANCE_OVERRIDE'])
def test_unchecked_preserves_blank_or_instance_value(tmp_path, native_value):
run_vbs(tmp_path, 'preserve', f'''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="{native_value}","unchecked changed native content"
QPVerifyDisplay Attr,Saved,"R1"
''', after=f'Set Attr=Comp.FindAttribute("Value"): Attr.Value="": Attr.InstanceValue="{native_value}"')
@pytest.mark.parametrize('part_label_setup', [
'Comp.RemoveAttribute "Part Label"',
'Set Attr=Comp.FindAttribute("Part Label"): Attr.Value="": Attr.InstanceValue=""',
])
def test_unchecked_does_not_require_target_part_label(tmp_path, part_label_setup):
run_vbs(tmp_path, 'preserve', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="TARGET_VALUE","unchecked changed native Value"
Require QP_App.UndoCount=0,"unchecked Part Label handling triggered rollback"
''', after=part_label_setup)
@pytest.mark.parametrize('part_label_setup', [
'Comp.RemoveAttribute "Part Label"',
'Set Attr=Comp.FindAttribute("Part Label"): Attr.Value="": Attr.InstanceValue=""',
])
def test_checked_requires_nonblank_target_part_label(tmp_path, part_label_setup):
run_vbs(tmp_path, 'part_label', '''
On Error Resume Next
QPRestoreAfterOperatorReplace Command,SnapshotPath
Failure=Err.Description
Err.Clear
On Error GoTo 0
Require InStr(Failure,"Part Label")>0,"checked mode accepted unavailable Part Label"
Require InStr(Failure,"refdes=R1")>0,"Part Label failure omitted the affected refdes"
Require QP_App.TransactionCount=0,"invalid Part Label reached restoration transaction"
''', after=part_label_setup)
@pytest.mark.parametrize('mode', ['preserve', 'part_label'])
def test_nc_marker_is_synchronized_for_both_value_modes(tmp_path, mode):
run_vbs(tmp_path, mode, '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="R0805/NC","NC marker was not synchronized"
QPVerifyDisplay Attr,Saved,"R1"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"quick-part-replace.log")), _
"nc_sync R1 R0603/NC -> R0805/NC")>0,"NC synchronization log missing"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")), _
"NC synced: R1 R0603/NC -> R0805/NC")>0,"NC synchronization status missing"
''',
before='Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0603/NC"',
after='Set Attr=Comp.FindAttribute("Part Label"): Attr.Value="R0805": '
'Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0805"')
def test_nc_marker_is_not_duplicated(tmp_path):
run_vbs(tmp_path, 'preserve', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="R0805/NC","NC marker was duplicated"
Require Attr.InstanceValue="","existing NC marker created a redundant instance override"
''',
before='Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0603/NC"',
after='Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0805/NC"')
def test_nc_marker_is_not_detected_when_rule_option_is_unchecked(tmp_path):
run_vbs(tmp_path, 'preserve', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="R0805","unchecked NC option changed Value"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"quick-part-replace.log")),"nc_sync")=0,"unchecked NC option logged synchronization"
''',
sync_nc=False,
before='Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0603/NC"',
after='Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0805"')
def test_nc_marker_creates_missing_native_value_with_old_style(tmp_path):
run_vbs(tmp_path, 'preserve', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="/NC","missing target Value did not retain NC"
QPVerifyDisplay Attr,Saved,"R1"
''',
before='Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0603/NC"',
after='Comp.RemoveAttribute "Value"')
@pytest.mark.parametrize('source_value', ['NC', 'R0603/NCM', 'R0603/NC_OPTION'])
def test_similar_text_is_not_treated_as_nc_marker(tmp_path, source_value):
run_vbs(tmp_path, 'preserve', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Set Attr=Comp.FindAttribute("Value")
Require QPEffectiveAttributeValue(Attr)="R0805","non-NC text triggered synchronization"
''',
before=f'Set Attr=Comp.FindAttribute("Value"): Attr.Value="{source_value}"',
after='Set Attr=Comp.FindAttribute("Value"): Attr.Value="R0805"')
def test_final_value_verification_rejects_wrong_part_number(tmp_path):
run_vbs(tmp_path, 'part_number', '''
Dim Before
Set Before=QPCaptureValueState(Comp)
On Error Resume Next
QPVerifyValuePolicy Comp,"part_number",Before
Failure=Err.Description
Err.Clear
On Error GoTo 0
Require InStr(Failure,"final Value mismatch")>0,"wrong target Value falsely passed"
''')