fix: clear late owned startup tips after normal close

This commit is contained in:
阿白叔 committed 2026-11-17 07:07:18 +08:00
1 parent 4402486baa
commit a64636ba0d
4 files changed
+278 -6

No files matched your search

+9 -2
View File
@@ -7,8 +7,9 @@ from cbb_refresh_verify import failed_session, mentor_adapter
def startup_fixture(tmp_path, monkeypatch):
import win32gui, win32process
from cbb_refresh_verify import native_repair_ui
from contextlib import nullcontext
import win32gui, win32process, win32event, win32con
from cbb_refresh_verify import native_repair_ui, residual_sessions
job = {'root': str(tmp_path), 'pcb': str(tmp_path/'PCB/CBB.pcb'),
'project': str(tmp_path/'CBB.prj'), 'lmc_file': str(tmp_path/'lib.lmc'),
'desktop': 'CbbVerify_test'}
@@ -20,6 +21,12 @@ def startup_fixture(tmp_path, monkeypatch):
records = [(12, r'C:\Mentor\wg\ExpeditionPCB.exe',
f'ExpeditionPCB.exe "{job["pcb"]}" -ReusableCircuit', 11)]
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: list(records))
monkeypatch.setattr(residual_sessions, '_process_handle', lambda *a, **kw: nullcontext(123))
monkeypatch.setattr(residual_sessions, '_handle_identity', lambda h:
{'created_handle': 'original', 'image': r'C:\Mentor\wg\ExpeditionPCB.exe'})
monkeypatch.setattr(residual_sessions, '_process_windows', lambda pids: {12: []})
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *a:
win32con.WAIT_TIMEOUT if records else win32con.WAIT_OBJECT_0)
monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'CbbVerify_test')
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: fn(100, arg))
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda *args: None)
+174
View File
@@ -0,0 +1,174 @@
"""A late, owned Tip must not strand the single pending normal close."""
from contextlib import nullcontext
from copy import deepcopy
from types import SimpleNamespace
import pytest
from cbb_refresh_verify import failed_session, residual_sessions as sessions
from test_failed_startup import startup_fixture
def late_tip_fixture(tmp_path, monkeypatch):
import win32con, win32event, win32gui
job, records, messages = startup_fixture(tmp_path, monkeypatch)
identity = {'created_handle': 'original', 'image': records[0][1]}
state = {'ticks': 0., 'tip': False, 'exited': False}
windows = [dict(hwnd=100, title='Expedition PCB', **{'class': 'Afx:main'},
desktop=job['desktop'], enabled=False, children=[], documents=[]),
dict(hwnd=200, title='Tip of the Day', **{'class': '#32770'},
desktop=job['desktop'], enabled=True, documents=[], children=[
{'hwnd': 201, 'class': 'Button', 'id': 1, 'text': 'OK', 'enabled': True}])]
monkeypatch.setattr(sessions, '_process_handle', lambda *a, **kw: nullcontext(123))
monkeypatch.setattr(sessions, '_handle_identity', lambda h: dict(identity))
def wait(handle, ms):
state['ticks'] += ms/1000
return win32con.WAIT_OBJECT_0 if state['exited'] else win32con.WAIT_TIMEOUT
monkeypatch.setattr(win32event, 'WaitForSingleObject', wait)
def advance(seconds):
state['ticks'] += seconds
if state['ticks'] >= .2: state['tip'] = True
clock = SimpleNamespace(monotonic=lambda: state['ticks'], sleep=advance)
monkeypatch.setattr(failed_session, 'time', clock)
monkeypatch.setattr(sessions, 'time', clock)
monkeypatch.setattr(sessions, '_process_windows', lambda pids: {
12: deepcopy(windows if state['tip'] else [dict(windows[0], enabled=True)])})
def post(hwnd, message, *_):
messages.append((hwnd, message))
if hwnd == 201 and message == win32con.BM_CLICK:
state['exited'] = True
records.clear()
monkeypatch.setattr(win32gui, 'PostMessage', post)
monkeypatch.setattr(sessions, '_post_window_message',
lambda w, hwnd, pid, msg: post(hwnd, msg))
monkeypatch.setattr(sessions, '_window_desktop', lambda *a, **kw: nullcontext())
# Revalidation reads native controls, independently of the initial snapshot.
from cbb_refresh_verify.dialog_models import WindowSnapshot, ControlSnapshot, DialogPhase
def snapshot(hwnd, pid):
w = next(w for w in windows if w['hwnd'] == hwnd)
return WindowSnapshot(hwnd, pid, 'ExpeditionPCB.exe', 'pcb', w['class'], w['title'],
DialogPhase.PCB_STARTING, tuple(ControlSnapshot(c['hwnd'], c['id'], c['class'],
c['text'], enabled=c['enabled']) for c in w['children']))
monkeypatch.setattr(failed_session, '_startup_snapshot', snapshot)
row = dict(pid=12, name='ExpeditionPCB.exe', scope_confirmed=True,
library=job['lmc_file'], **identity)
return job, row, records, messages, windows, state, identity
@pytest.mark.parametrize('launcher_exits', [True, False])
def test_late_tip_after_first_close_exits_without_a_second_close(tmp_path, monkeypatch, launcher_exits):
import win32con
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
launcher = SimpleNamespace(pid=11, poll=lambda:
0 if launcher_exits and state['exited'] and state['ticks'] >= .6 else None)
events = []
result = failed_session.close_failed_startup(job, 12, launcher_process=launcher,
timeout_seconds=1, emit=lambda **event: events.append(event))
assert messages == [(100, win32con.WM_CLOSE), (201, win32con.BM_CLICK)]
assert result['release']['pcb_exited'] and not records
assert result['status'] == ('CLOSED' if launcher_exits else 'RETAINED')
assert result['release']['safe_to_continue'] is launcher_exits
assert .6 <= state['ticks'] <= 1.2
assert sum(e['stage'] == 'startup_tip_dismissed' for e in events) == 1
def test_normal_release_clears_owned_tip_and_waits_for_existing_close(tmp_path, monkeypatch):
import win32con
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
state['tip'] = True # Earlier cancelled startup has already posted WM_CLOSE.
result = sessions._request_close(row)
assert result['release_status'] == 'RELEASED'
assert messages == [(201, win32con.BM_CLICK)]
@pytest.mark.parametrize('obstacle', ['foreign_desktop', 'unknown', 'document', 'progress',
'write', 'identity', 'scope', 'changed_prompt', 'disabled_tip', 'incomplete'])
def test_release_tip_never_overrides_unconfirmed_or_writing_state(tmp_path, monkeypatch, obstacle):
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
state['tip'] = True
if obstacle == 'foreign_desktop': windows[1]['desktop'] = 'Default'
if obstacle == 'unknown': windows.append(dict(windows[1], hwnd=300, title='Unknown action'))
if obstacle == 'document': windows[0]['documents'] = [300]
if obstacle == 'progress': windows[0]['children'] = [{'class': 'msctls_progress32'}]
if obstacle == 'write': row['runtime_phase'] = 'NATIVE_CALL'
if obstacle == 'identity': identity['created_handle'] = 'replacement'
if obstacle == 'scope': row['scope_confirmed'] = False
if obstacle == 'changed_prompt':
original = failed_session._startup_snapshot
from dataclasses import replace
monkeypatch.setattr(failed_session, '_startup_snapshot',
lambda h, p: replace(original(h, p), title='New question'))
if obstacle == 'disabled_tip': windows[1]['children'][0]['enabled'] = False
if obstacle == 'incomplete':
captured = sessions._WindowSnapshot({12}); captured[12] = windows
captured.incomplete[12] = 'unreadable'
monkeypatch.setattr(sessions, '_process_windows', lambda pids: captured)
assert sessions._request_close(row)['release_status'] in ('WAITING', 'IDENTITY_CHANGED')
assert not messages and records
def test_startup_late_tip_does_not_extend_original_close_budget(tmp_path, monkeypatch):
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
# Tip survives acknowledgement; no re-click and no second WM_CLOSE.
import win32gui, win32con
def record(hwnd, message, *_): messages.append((hwnd, message))
monkeypatch.setattr(win32gui, 'PostMessage', record)
monkeypatch.setattr(sessions, '_post_window_message', lambda w,h,p,m: record(h,m))
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
assert result['status'] == 'RETAINED'
assert messages == [(100, win32con.WM_CLOSE), (201, win32con.BM_CLICK)]
assert 1 <= state['ticks'] <= 1.2
@pytest.mark.parametrize('obstacle', ['identity', 'desktop', 'document', 'progress', 'unknown'])
def test_late_tip_after_close_preserves_changed_or_busy_owner(tmp_path, monkeypatch, obstacle):
import win32con, win32gui
from cbb_refresh_verify import native_repair_ui
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
original = win32gui.PostMessage
if obstacle == 'desktop':
monkeypatch.setattr(native_repair_ui, '_current_desktop_name',
lambda: 'Default' if messages else job['desktop'])
def post(hwnd, message, *args):
original(hwnd, message, *args)
if message != win32con.WM_CLOSE: return
if obstacle == 'identity': identity['created_handle'] = 'replacement'
if obstacle == 'document': windows[0]['documents'] = [300]
if obstacle == 'progress': windows[0]['children'] = [{'class': 'msctls_progress32'}]
if obstacle == 'unknown': windows.append(dict(windows[1], hwnd=300, title='Unknown action'))
monkeypatch.setattr(win32gui, 'PostMessage', post)
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
assert result['status'] == 'RETAINED' and records
assert messages == [(100, win32con.WM_CLOSE)]
def test_transient_missing_wmi_pid_is_not_exit_of_held_startup_process(tmp_path, monkeypatch):
import win32gui
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
monkeypatch.setattr(win32gui, 'PostMessage', lambda *args: records.clear())
result = failed_session.close_failed_startup(job, 12, timeout_seconds=1)
assert result['status'] == 'RETAINED'
assert not result['release']['safe_to_continue']
def test_release_rechecks_live_write_record_before_tip_action(tmp_path, monkeypatch):
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
state['tip'] = True
monkeypatch.setattr('cbb_refresh_verify.session_record.active_write_records',
lambda _: [{'phase': 'NATIVE_CALL'}])
assert sessions._request_close(row)['release_status'] == 'WAITING'
assert not messages
def test_release_tip_ack_never_stacks_another_close_while_process_still_exits(tmp_path, monkeypatch):
import win32con
job, row, records, messages, windows, state, identity = late_tip_fixture(tmp_path, monkeypatch)
state['tip'] = True
def dismiss(window, hwnd, pid, message):
messages.append((hwnd, message))
state['tip'] = False
monkeypatch.setattr(sessions, '_post_window_message', dismiss)
result = sessions._request_close(row)
assert result['release_status'] == 'WAITING' and records
assert messages == [(201, win32con.BM_CLICK)]
assert 3 <= state['ticks'] < 3.2