fix: address PR review identity and snapshot safety gaps

This commit is contained in:
阿白叔 committed 2026-10-30 17:48:08 +08:00
1 parent 131b6dbbb3
commit f0a0131aac
15 files changed
+312 -64

No files matched your search

@@ -26,7 +26,7 @@ def test_quick_part_replace_is_an_ascii_current_sheet_automatic_contract() -> No
"Comp.Orientation",
"Comp.Scale",
"QP_App.ActiveView.Query(VDM_COMPPIN, VD_ALL)",
"CmpPin.Component.UID",
"QPComponentIdentityKey(CmpPin.Component)",
"Set Connection = CmpPin.Connection",
"Set Net = Connection.Net",
"Net.UID",
+22 -1
View File
@@ -14,7 +14,7 @@ FAKES = next(ast.literal_eval(statement.value) for statement in TREE.body
for target in statement.targets))
EXTRA = r'''
Class ValueComponent
Public UID, Refdes, Orientation, Scale, Attributes, AddCount
Public UID, Refdes, Orientation, Scale, Attributes, AddCount, Selected
Private Point
Private Sub Class_Initialize()
Set Point=New TestPoint
@@ -371,6 +371,27 @@ Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"saved_ok")>0,"
''', routines_transform=_batch_readback_fixture)
def test_missing_uid_capture_restore_save_and_reopen(tmp_path):
run_vbs(tmp_path, 'part_number', '''
Dim FullChecks, Captured
FullChecks=0
Command.Add "project_path",QPProjectPath()
Comp.FindAttribute("Part Number").Value="OLD"
QPCaptureAndSelect Command,SnapshotPath
Set Captured=QPReadSnapshot(SnapshotPath)
Require Captured.Item("components").Item("0")("uid")="@REFDES|R1","fallback lost in snapshot"
Require Captured.Item("untouched").Count=0,"target incorrectly captured as untouched"
Comp.FindAttribute("Part Number").Value="NEW"
QP_BatchMode=True:QP_SessionMode=False
QP_OwnedProject=True:QP_OwnedProjectPath=QPProjectPath()
QPRestoreAfterOperatorReplace Command,SnapshotPath
QPFinishBatchItem
Require QP_App.SaveCount=1,"replacement was not saved exactly once"
Require Len(QP_App.ProjectPath)=0,"reopened project was not closed"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"saved_ok")>0,"missing saved readback proof"
''', before='Comp.UID=""', 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
+56 -4
View File
@@ -128,12 +128,12 @@ End Class
''') == '1234'
def test_optional_attribute_fields_degrade_to_safe_defaults(tmp_path):
def test_unreadable_display_fields_retain_missing_state(tmp_path):
output = run_vbs(tmp_path, ['QPOptionalAttributeField', 'QPReadOptionalAttributeValue'], '''
Dim Attr
Set Attr = New BrokenOptionalAttribute
WScript.Echo QPOptionalAttributeField(Attr, "color")
WScript.Echo QPOptionalAttributeField(Attr, "location_x")
WScript.Echo "color=" & QPOptionalAttributeField(Attr, "color")
WScript.Echo "x=" & QPOptionalAttributeField(Attr, "location_x")
WScript.Echo QPReadOptionalAttributeValue(Attr)
''', LOG_STUB + '''
Class BrokenOptionalAttribute
@@ -155,7 +155,7 @@ Class BrokenOptionalAttribute
End Property
End Class
''')
assert output.splitlines() == ['0', '0']
assert output.splitlines() == ['color=', 'x=']
def test_optional_component_label_read_failure_is_not_identity_failure(tmp_path):
@@ -415,6 +415,58 @@ WScript.Echo Replace(Text,vbCrLf,"")
assert output.splitlines() == ['1', 'A\tu1\tValue\tSAME\tSAME\t0\t0\t1\t2\t3\t0\t1']
@pytest.mark.parametrize('field', ['Color', 'Font', 'Size', 'Orientation', 'Visible', 'location'])
def test_unreadable_style_blocks_snapshot_and_never_writes_default(tmp_path, field):
fake = FULL_FAKE
if field == 'location':
fake = fake.replace('Function GetLocation()\n Dim Point:',
'Function GetLocation()\n If FailRead Then Err.Raise 1234,"FakeCOM","unavailable"\n Dim Point:', 1)
record_field = 'x'
else:
fake = fake.replace('Color, Font, Size, Orientation, Visible',
', '.join(x for x in ['Color', 'Font', 'Size', 'Orientation', 'Visible'] if x != field), 1)
marker = ' Private Sub Class_Initialize\n Name = "Value"'
fake = fake.replace(marker, f''' Private Stored
Property Get {field}
If FailRead Then Err.Raise 1234,"FakeCOM","unavailable"
{field}=Stored
End Property
Property Let {field}(ByVal NewValue)
Stored=NewValue:Writes=Writes+1
End Property
Private Sub Class_Initialize
Name = "Value"''', 1)
record_field = field.lower()
output = run_vbs(tmp_path, ['QPSnapshotAttribute', 'QPOptionalAttributeField', 'QPEncode',
'QPRestoreDisplay'], f'''
Dim Attr,Text,Failure,Record,Key,FailRead,Writes
FailRead=False
Set Attr=New FullAttribute
Writes=0:FailRead=True
On Error Resume Next
Text=QPSnapshotAttribute("u1",Attr)
Failure=Err.Number:Err.Clear
On Error GoTo 0
WScript.Echo CStr(Failure<>0)
FailRead=False
Set Record=CreateObject("Scripting.Dictionary")
For Each Key In Array("x","y","color","font","size","orientation","visible")
Record.Add Key,"1"
Next
Record("{record_field}")=""
On Error Resume Next
QPRestoreDisplay Attr,Record,"R1"
Failure=Err.Number:Err.Clear
On Error GoTo 0
WScript.Echo CStr(Failure<>0)
WScript.Echo Writes
''', LOG_STUB + fake + '''
Sub QPVerifyDisplay(ByRef Attr,ByRef Record,ByVal Refdes)
End Sub
''')
assert output.splitlines() == ['True', 'True', '0']
@pytest.mark.parametrize('instance', ['', 'OVERRIDE'])
def test_snapshot_preserves_base_value_separately_from_instance_override(tmp_path, instance):
output = run_vbs(tmp_path, ['QPSnapshotAttribute', 'QPOptionalAttributeField', 'QPEncode'], f'''
@@ -43,6 +43,46 @@ def test_native_readback_checks_each_unselected_attribute_once(tmp_path, target_
assert other.reads == {'Part Number': 1, 'Value': 1, 'Part Name': 1, 'Part Label': 1}
@pytest.mark.parametrize('others,changed', [(0, False), (2, False), (2, True)])
def test_legacy_readback_checks_every_unselected_component(tmp_path, others, changed):
target = Component('u1', 'R1', **{'Part Number': 'NEW', 'Part Name': 'TARGET'})
components, baseline = [target], {}
for index in range(others):
uid, refdes = f'u{index + 2}', f'R{index + 2}'
baseline[uid] = (refdes, 'OLD', 'V0', 'NAME', 'LABEL')
components.append(Component(uid, refdes, **{'Part Number': 'OLD',
'Value': 'CHANGED' if changed and index == 0 else 'V0',
'Part Name': 'NAME', 'Part Label': 'LABEL'}))
def verify():
return native.verify_replacement_readback(tmp_path / 'snapshot.tsv', components,
['M', 'project', 'OLD', 'NEW', 'sheet', 'preserve'], [['C', 'u1', 'R1']],
{c.UID for c in components}, baseline, False, None, ['u1'])
if changed:
with pytest.raises(ValueError, match='unselected component'):
verify()
else:
assert verify() == ['u1']
@pytest.mark.parametrize('count', [1, 2])
def test_missing_uid_matches_flow_into_pin_promotion(monkeypatch, count):
components = [Component('', f'R{i+1}', **{'Part Number': 'NEW', 'Part Name': 'TARGET'})
for i in range(count)]
records = [['C', f'@REFDES|R{i+1}', f'R{i+1}'] for i in range(count)]
matches = native.replacement_matches(components, records, 'NEW', False)
assert matches == [row[1] for row in records]
pins = [SimpleNamespace(Component=c, Number='1') for c in components]
for pin in pins:
pin._oleobj_ = pin
app = SimpleNamespace(ActiveView=SimpleNamespace(
Block=SimpleNamespace(PromoteSymbolNumbers=lambda *args: None),
Query=lambda *args: pins))
monkeypatch.setattr(native, 'components_on_sheet', lambda *args: components)
monkeypatch.setattr(native, 'selection', lambda *args: None)
promoted = native.promote_pin_numbers(app, SimpleNamespace(IVdCmpPin=lambda p: p), matches)
assert [pin['uid'] for pin in promoted] == matches
def test_preselection_context_does_not_query_an_unused_selection(monkeypatch):
target = Component('u1', 'R1', **{'Part Number': 'OLD', 'Value': 'V0'})
target._oleobj_ = target
+21 -1
View File
@@ -135,7 +135,8 @@ def test_repeated_force_does_not_terminate_twice(tmp_path):
from types import SimpleNamespace
from dx_productivity.trial_task_center.batch_supervisor import _force_owned_supervisor
calls = []
process = SimpleNamespace(terminate=lambda: calls.append('terminate'))
process = SimpleNamespace(terminate=lambda: calls.append('terminate'),
poll=lambda: 0 if calls else None)
journal = {'operation': 'execute_task_queue', 'batch_id': 'a' * 32, 'attempt_id': 'b' * 32,
'task_ids': ['task'], 'state': 'running'}
_force_owned_supervisor(tmp_path, journal, process)
@@ -144,6 +145,25 @@ def test_repeated_force_does_not_terminate_twice(tmp_path):
assert journal['force_state'] == 'termination_requested'
def test_force_retry_terminates_again_if_process_is_still_alive(tmp_path):
from types import SimpleNamespace
from dx_productivity.trial_task_center.batch_supervisor import _force_owned_supervisor
calls = []
process = SimpleNamespace(terminate=lambda: calls.append('terminate'), poll=lambda: None)
journal = {'operation': 'execute_task_queue', 'batch_id': 'a' * 32, 'attempt_id': 'b' * 32,
'task_ids': ['task'], 'state': 'running', 'force_state': 'termination_requested'}
_force_owned_supervisor(tmp_path, journal, process)
assert calls == ['terminate']
def test_empty_interruption_marker_is_repaired_before_force(tmp_path):
from dx_productivity.trial_task_center.stop_control import protect_interruption
marker = tmp_path / 'uncertain.flag'
marker.touch()
protect_interruption(tmp_path, 'reason=interrupted')
assert marker.read_text(encoding='utf-8') == 'reason=interrupted'
def test_force_already_performed_remains_forced_when_exit_diagnostics_fail(tmp_path):
from types import SimpleNamespace
from dx_productivity.trial_task_center.batch_supervisor import _force_owned_supervisor
+30
View File
@@ -1,6 +1,36 @@
import pytest
@pytest.mark.parametrize('content', ['{bad', '[]', '{"cad_shutdown": 5}',
'{"cad_shutdown": {"cleanup_errors": [1]}}'])
def test_corrupt_shutdown_evidence_keeps_result_and_blocks(tmp_path, monkeypatch, content):
from dx_productivity.trial_task_center import batch_resources
from dx_productivity.trial_task_center.batch_supervisor import _finish_response
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.supervisor_protocol import encode
journal = {'operation': 'probe', 'batch_id': 'a' * 32}
root = tmp_path / 'batch-resources' / journal['batch_id']
root.mkdir(parents=True)
(root / 'session.json').write_text(content, encoding='utf-8')
monkeypatch.setattr(batch_resources, 'cleanup_pending_resources', lambda *args, **kwargs: ())
response = {'business_succeeded': True, 'status': 'ok', 'result': encode({'verified': True})}
with pytest.raises(TaskCenterError) as caught:
_finish_response(tmp_path, journal, response, configure_logging(tmp_path))
assert caught.value.code == 'application_shutdown_failed'
assert caught.value.completed_result == {'verified': True}
assert journal['state'] == 'blocked'
def test_failed_progress_publish_emits_warning(tmp_path, monkeypatch, caplog):
from dx_productivity.trial_task_center import worker_monitor
def fail(*args):
raise OSError('disk full')
monkeypatch.setattr(worker_monitor, '_atomic_text', fail)
worker_monitor._publish_progress(tmp_path / 'progress.json', {'stage': 'awaiting_reconciliation'})
assert 'worker_progress_publish_failed' in caplog.text
@pytest.mark.parametrize('body', [None, {}, {'status':'ok','business_succeeded':'yes','result':'bad'},
{'status':'ok','business_succeeded':True,'result':'wrong type'}])
def test_invalid_result_cannot_finish_resource_gate(tmp_path, body):