fix: serialize ready diagnostic close and exact native prompt handling

This commit is contained in:
阿白叔 committed 2026-11-17 04:20:05 +08:00
1 parent eaff46e50e
commit fd50805380
6 files changed
+233 -16

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
import json
from pathlib import Path
import pytest
from test_verify_runner import fixture, request, PORTS_OK
@pytest.mark.parametrize('fault', ['', 'no_event', 'wrong_pid', 'wrong_operation', 'wrong_project', 'wrong_desktop', 'ordinary'])
def test_only_current_diagnostic_close_leaves_prompt_actions_to_checker(tmp_path, monkeypatch, fault):
from cbb_refresh_verify import desktop_worker
from cbb_refresh_verify.verify_runner import run_verify
from cbb_refresh_verify.dialog_supervisor import DialogPollResult
fixture(tmp_path); polls = []
class Worker:
desktop = None
pid = 700
companion_pids = []
returncode = None
count = 0
def __init__(self, command, name):
self.name = name
path = Path(command[-1]); job = json.loads(path.read_text())
event = dict(stage='diagnostic_wm_close', pcb_pid=901, hwnd=900,
operation_id=job['operation_id'], desktop=job['desktop'], project=job['project'], pcb=job['pcb'])
for condition, key, value in [('wrong_pid','pcb_pid',999),('wrong_operation','operation_id','foreign'),
('wrong_project','project','foreign.prj'),('wrong_desktop','desktop','Default')]:
if fault == condition: event[key] = value
events = [dict(stage='pcb_worker_started', pcb_pid=901)]
if fault != 'no_event': events.append(event)
path.with_name('events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events))
path.with_name('outcome.json').write_text(json.dumps({'status':'FAIL','safe_to_continue':False,
'stderr':'DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown prompt retained'}))
def poll(self):
self.count += 1
if self.count > 2: self.returncode = 1
return self.returncode
def close(self): pass
def wait(self, timeout=5): self.returncode = 1; return 1
class Supervisor:
def poll(self, *args):
polls.append(True)
return DialogPollResult(error_code='UNKNOWN_DIALOG', detail='competing save prompt')
monkeypatch.setattr(desktop_worker, 'DesktopWorker', Worker)
result = run_verify(request(tmp_path, diagnostic_only=fault!='ordinary'), port_check=PORTS_OK,
dialog_supervisor_factory=lambda **kwargs:Supervisor())
assert result.status == 'FAIL'
assert json.loads(result.evidence_path.with_name('outcome.json').read_text())['safe_to_continue'] is False
if not fault:
assert polls == []
assert 'DIAGNOSTIC_CLOSE_UNCONFIRMED' in result.stderr
else:
assert polls and 'UNKNOWN_DIALOG' in result.stderr
+86
View File
@@ -83,6 +83,58 @@ def test_target_title_without_target_mdi_does_not_pass(diagnostic, job):
assert diagnostic._target_frame([window], Path(job['pcb']).stem) is None
def test_visible_loading_progress_is_not_ready_for_diagnostic_close(diagnostic, job):
window = frame(job)
progress = {'hwnd': 13, 'class': 'msctls_progress32', 'text': '', 'visible': True}
window['children'].append(progress)
assert diagnostic._target_frame([window], 'IP101GR') is None
progress['visible'] = False
assert diagnostic._target_frame([window], 'IP101GR') == window
@pytest.mark.parametrize('cancel', [False, True])
def test_persistent_loading_progress_keeps_deadline_and_never_closes(diagnostic, job, monkeypatch, cancel):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
signal = Path(job['root']).parent/'cancel-progress'
job['cancel_signal'] = str(signal)
target = frame(job)
target['children'].append({'hwnd':13,'class':'msctls_progress32','text':'','visible':True})
def windows(pid):
if cancel: signal.touch()
return [target]
monkeypatch.setattr(diagnostic,'_NativeSession',Session)
monkeypatch.setattr(diagnostic,'_windows',windows)
with pytest.raises(RuntimeError, match='VERIFY_CANCELLED' if cancel else 'DIAGNOSTIC_OPEN_UNCONFIRMED'):
diagnostic.check_target_window(job,42,emit=lambda **event:None,error_reader=lambda:None)
assert Session.instances[-1].posted == []
def test_diagnostic_waits_for_startup_forward_no_before_close(diagnostic, job, monkeypatch):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job); job['timeout'] = 1
class ForwardSession(Session):
declined = False
def post(self, hwnd, message):
self.posted.append((hwnd,message))
if hwnd == 31: self.declined = True
else: self.alive = False
def windows(pid):
state = Session.instances[-1]
target = frame(job)
if state.declined: return [target] if state.alive else []
target['enabled'] = False
target['children'].append({'hwnd':13,'class':'msctls_progress32','text':'','visible':True})
return [target, {'hwnd':20,'pid':42,'class':'#32770','text':'Expedition PCB','owner':10,
'children':[{'hwnd':30,'class':'Static','id':6172,'text':'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'},
{'hwnd':31,'class':'Button','id':7,'text':'&No','enabled':True},
{'hwnd':32,'class':'Button','id':6,'text':'&Yes','enabled':True}]}]
monkeypatch.setattr(diagnostic,'_NativeSession',ForwardSession)
monkeypatch.setattr(diagnostic,'_windows',windows)
assert diagnostic.check_target_window(job,42,emit=lambda **event:None,error_reader=lambda:None)['status']=='PASS'
assert Session.instances[-1].posted == [(31,0xF5),(10,0x10)]
class Session:
instances = []
def __init__(self, job, pid, launcher):
@@ -417,3 +469,37 @@ def test_recycled_window_from_another_pid_never_receives_close(diagnostic, monke
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 99))
with pytest.raises(RuntimeError, match='DIAGNOSTIC_STALE_WINDOW'):
session.post(10, 0x10)
@pytest.mark.parametrize('fault', ['', 'foreign_pid', 'cycle', 'other_frame', 'visible', 'enabled', 'class', 'title', 'desktop', 'incomplete', 'filename'])
def test_diagnostic_save_accepts_only_complete_hidden_owner_chain(diagnostic, job, fault):
target = frame(job)
owner = {'hwnd': 15, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB',
'owner': 10, 'visible': False, 'enabled': False, 'same_desktop': True}
end = {**target, 'same_desktop': True}
window = {'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB',
'owner': 15, 'owner_chain': [owner, end], 'children': [
{'hwnd': 30, 'class': 'Static', 'text': 'Save changes to IP101GR.pcb?', 'id': -1},
{'hwnd': 31, 'class': 'Button', 'text': '否(&N)', 'id': 7},
{'hwnd': 32, 'class': 'Button', 'text': '是(&Y)', 'id': 6},
{'hwnd': 33, 'class': 'Button', 'text': '取消', 'id': 2}]}
if fault == 'foreign_pid': owner['pid'] = 99
if fault == 'cycle': owner['owner'] = 15
if fault == 'other_frame': end['hwnd'] = 99
if fault == 'visible': owner['visible'] = True
if fault == 'enabled': owner['enabled'] = True
if fault == 'class': owner['class'] = 'VendorDialog'
if fault == 'title': owner['text'] = 'Unknown recovery'
if fault == 'desktop': owner['same_desktop'] = False
if fault == 'incomplete': window['owner_chain'] = [owner]
if fault == 'filename': window['children'][0]['text'] = 'Save changes to Foreign.pcb?'
session = Session(job, 42, None)
action = lambda:diagnostic._pending_prompt([window], closing=True, frame=target,
session=session, clicked=set(), pcb_name='IP101GR.pcb')
if not fault:
assert action() is False
assert session.posted == [(31, 0xF5)]
else:
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
action()
assert session.posted == []
+9
View File
@@ -15,6 +15,15 @@ from cbb_refresh_verify.dialog_rules import (
ASSETS = Path(__file__).resolve().parents[1] / "src" / "cbb_refresh_verify" / "assets"
def test_diagnostic_forward_prompt_is_observed_while_ordinary_verify_still_confirms():
text = 'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'
snapshot = prompt(text)
ordinary = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json'))
diagnostic = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json', diagnostic_only=True))
assert ordinary.action == 'confirm_forward_annotation'
assert diagnostic.category == 'OBSERVE_PROGRESS' and not diagnostic.action
def prompt(text, *, phase=DialogPhase.PCB_STARTING, window_class="#32770",
control_types=("Text", "Button")):
controls = tuple(