import json from pathlib import Path import pytest 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 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'} diagnostics = tmp_path/'diagnostics' diagnostics.mkdir() (diagnostics/'icdb-recovery.json').write_text(json.dumps({ 'error_code': 'ICDB_REPAIR_REQUIRED', 'scope': 'project', 'database_path': str(tmp_path/'database'), 'session': 'lost-session'})) 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(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) monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (1, 12)) monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda _: True) monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda _: True) monkeypatch.setattr(win32gui, 'GetWindowText', lambda _: 'Expedition PCB') monkeypatch.setattr(win32gui, 'GetClassName', lambda _: 'Afx:main') messages = [] def post(hwnd, message, wparam, lparam): messages.append((hwnd, message)) records.clear() monkeypatch.setattr(win32gui, 'PostMessage', post) return job, records, messages @pytest.mark.parametrize('title', ['Expedition PCB', 'Expedition PCB - Reusable Block']) def test_failed_startup_normally_closes_owned_empty_pcb(tmp_path, monkeypatch, title): import win32con import win32gui job, records, messages = startup_fixture(tmp_path, monkeypatch) monkeypatch.setattr(win32gui, 'GetWindowText', lambda _: title) result = failed_session.close_failed_startup(job, 12, baseline_pids=(), timeout_seconds=0) assert result['status'] == 'CLOSED' assert not records assert messages == [(100, win32con.WM_CLOSE)] assert json.loads((tmp_path/'startup-close.json').read_text())['status'] == 'CLOSED' @pytest.mark.parametrize('obstacle', ['baseline', 'wrong_path', 'path_prefix', 'desktop', 'address', 'dialog', 'document_title', 'mdi_document', 'disabled', 'no_diagnosis']) def test_failed_startup_preserves_unconfirmed_or_busy_session(tmp_path, monkeypatch, obstacle): import win32gui from cbb_refresh_verify import native_repair_ui job, records, messages = startup_fixture(tmp_path, monkeypatch) baseline = () if obstacle == 'baseline': baseline = (12,) if obstacle == 'wrong_path': records[0] = (12, records[0][1], 'other.pcb -ReusableCircuit', 11) if obstacle == 'path_prefix': records[0] = (12, records[0][1], f'pcb.exe "{job["pcb"]}.other" -ReusableCircuit', 11) if obstacle == 'desktop': monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'Default') if obstacle == 'address': address = tmp_path/'database/cdbsvr/sAddress.adr' address.parent.mkdir(parents=True) address.write_text('owner') if obstacle == 'dialog': monkeypatch.setattr(win32gui, 'GetClassName', lambda _: '#32770') if obstacle == 'document_title': monkeypatch.setattr(win32gui, 'GetWindowText', lambda _: 'CBB.pcb - Expedition PCB') if obstacle == 'mdi_document': monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, fn, arg: fn(101, arg)) monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: 'MDIClient' if hwnd == 101 else 'Afx:main') monkeypatch.setattr(win32gui, 'GetWindow', lambda *args: 102) if obstacle == 'disabled': monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda _: False) if obstacle == 'no_diagnosis': (tmp_path/'diagnostics/icdb-recovery.json').unlink() result = failed_session.close_failed_startup(job, 12, baseline_pids=baseline, timeout_seconds=0) assert result['status'] == 'RETAINED' assert records assert not messages def test_requested_close_without_exit_is_not_reported_closed(tmp_path, monkeypatch): import win32gui job, records, messages = startup_fixture(tmp_path, monkeypatch) monkeypatch.setattr(win32gui, 'PostMessage', lambda hwnd, message, *_: messages.append((hwnd, message))) result = failed_session.close_failed_startup(job, 12, timeout_seconds=0) assert result['status'] == 'RETAINED' assert 'STARTUP_EXIT_UNCONFIRMED' in result['detail'] assert len(messages) == 1 assert records @pytest.mark.parametrize('obstacle', ['address', 'dialog', 'process']) def test_startup_close_waits_for_native_state_transitions(tmp_path, monkeypatch, obstacle): from types import SimpleNamespace import win32gui job, records, messages = startup_fixture(tmp_path, monkeypatch) ticks = [0] address = tmp_path/'database/cdbsvr/sAddress.adr' if obstacle == 'address': address.parent.mkdir(parents=True) address.write_text('owner') if obstacle == 'dialog': monkeypatch.setattr(win32gui, 'GetClassName', lambda _: '#32770' if ticks[0] == 0 else 'Afx:main') if obstacle == 'process': monkeypatch.setattr(win32gui, 'PostMessage', lambda hwnd, message, *_: messages.append((hwnd, message))) def advance(seconds): ticks[0] += seconds if obstacle == 'address' and address.exists(): address.unlink() if obstacle == 'process' and messages: records.clear() monkeypatch.setattr(failed_session, 'time', SimpleNamespace( monotonic=lambda: ticks[0], sleep=advance)) result = failed_session.close_failed_startup(job, 12, timeout_seconds=1) assert ticks[0] > 0 assert result['status'] == 'CLOSED' assert len(messages) == 1 assert not records def test_worker_closes_startup_failure_before_document_identity(tmp_path, monkeypatch): from test_verify_worker_stability import exercise_worker job, events, execute = exercise_worker(tmp_path, monkeypatch) job['desktop'] = 'CbbVerify_test' def fail_open(*args, **kwargs): raise RuntimeError('VERIFY_CANCELLED: database open failed') monkeypatch.setattr('cbb_refresh_verify.pcb_bridge.wait_for_target_document', fail_open) # Native process/window behavior is covered above; here verify the worker # actually reaches startup cleanup instead of requiring a loaded document. def close(job, pid, **kwargs): kwargs['emit'](stage='startup_close_result', status='CLOSED', pcb_pid=pid) return {'status': 'CLOSED'} monkeypatch.setattr(failed_session, 'close_failed_startup', close, raising=False) with pytest.raises(RuntimeError, match='VERIFY_CANCELLED'): execute() assert any(e['stage'] == 'startup_close_result' and e['pcb_pid'] == 2 for e in events) assert not any(e['stage'] == 'save_start' for e in events) def test_failed_startup_accepts_current_owned_database_failure_dialog(tmp_path, monkeypatch): job, records, messages = startup_fixture(tmp_path, monkeypatch) (tmp_path/'diagnostics/icdb-recovery.json').unlink() (tmp_path/'dialogs.jsonl').write_text(json.dumps({ 'pid': 12, 'phase': 'PCB_STARTING', 'error_code': 'MENTOR_DATABASE_LOAD_FAILED'})+'\n') result = failed_session.close_failed_startup(job, 12, timeout_seconds=0) assert result['status'] == 'CLOSED' assert not records @pytest.mark.parametrize('pid,phase', [(99, 'PCB_STARTING'), (12, 'SAVING')]) def test_failed_startup_rejects_unrelated_failure_dialog(tmp_path, monkeypatch, pid, phase): job, records, messages = startup_fixture(tmp_path, monkeypatch) (tmp_path/'diagnostics/icdb-recovery.json').unlink() (tmp_path/'dialogs.jsonl').write_text(json.dumps({ 'pid': pid, 'phase': phase, 'error_code': 'MENTOR_DATABASE_LOAD_FAILED'})+'\n') assert failed_session.close_failed_startup(job, 12, timeout_seconds=0)['status'] == 'RETAINED' assert not messages @pytest.mark.parametrize('exits', [True, False]) def test_startup_close_waits_for_launcher_after_empty_pcb_exit(tmp_path, monkeypatch, exits): from types import SimpleNamespace job, records, messages = startup_fixture(tmp_path, monkeypatch) ticks = [0.0] launcher = SimpleNamespace(pid=11, poll=lambda: 0 if exits and ticks[0] >= .4 else None) monkeypatch.setattr(failed_session, 'time', SimpleNamespace( monotonic=lambda: ticks[0], sleep=lambda seconds: ticks.__setitem__(0, ticks[0]+seconds))) result = failed_session.close_failed_startup(job, 12, launcher_process=launcher, timeout_seconds=1) assert ticks[0] >= .4 assert result['status'] == ('CLOSED' if exits else 'RETAINED') assert result['release']['launcher_exited'] is exits assert result['release']['pcb_exited'] is True assert len(messages) == 1 def test_startup_exit_does_not_hide_late_database_address(tmp_path, monkeypatch): import win32gui job, records, messages = startup_fixture(tmp_path, monkeypatch) def close(*args): records.clear() address = tmp_path/'database/cdbsvr/sAddress.adr' address.parent.mkdir(parents=True) address.write_text('still owned') monkeypatch.setattr(win32gui, 'PostMessage', close) result = failed_session.close_failed_startup(job, 12, timeout_seconds=0) assert result['status'] == 'RETAINED' assert result['release']['addresses'] @pytest.mark.parametrize('window_class,title', [('CustomPrompt', 'Database action pending'), ('Afx:tool', ''), ('UAC_InputIndicatorOverlayWnd', 'Unknown prompt'), ('UAC Input Indicator', ' ')]) def test_enabled_empty_main_with_unaccounted_owned_window_is_never_closed(tmp_path, monkeypatch, window_class, title): import win32gui job, records, messages = startup_fixture(tmp_path, monkeypatch) monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(hwnd, arg) for hwnd in (100, 200)]) monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: 'Afx:main' if hwnd == 100 else window_class) monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else title) result = failed_session.close_failed_startup(job, 12, timeout_seconds=0) assert result['status'] == 'RETAINED' and not result['release']['safe_to_continue'] assert messages == [] and records assert result['unknown_windows'] == [{'hwnd': 200, 'class': window_class, 'title': title, 'enabled': True}] assert json.loads((tmp_path/'startup-close.json').read_text(encoding='utf-8'))['unknown_windows'] == result['unknown_windows'] def test_empty_title_known_uac_windows_are_accounted_for_before_normal_close(tmp_path, monkeypatch): import win32gui, win32con job, records, messages = startup_fixture(tmp_path, monkeypatch) classes = {100: 'Afx:main', 200: 'UAC_InputIndicatorOverlayWnd', 201: 'UAC Input Indicator'} monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(hwnd, arg) for hwnd in classes]) monkeypatch.setattr(win32gui, 'GetClassName', classes.__getitem__) monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else '') result = failed_session.close_failed_startup(job, 12, timeout_seconds=0) assert result['status'] == 'CLOSED' and messages == [(100, win32con.WM_CLOSE)] assert result['unknown_windows'] == [] assert [entry['hwnd'] for entry in result['benign_auxiliary_windows']] == [200, 201] def test_custom_prompt_must_disappear_before_main_close(tmp_path, monkeypatch): from types import SimpleNamespace import win32gui job, records, messages = startup_fixture(tmp_path, monkeypatch) ticks = [0.0] monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(hwnd, arg) for hwnd in ((100, 200) if ticks[0] == 0 else (100,))]) monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: 'Afx:main' if hwnd == 100 else 'CustomPrompt') monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else 'Still processing') monkeypatch.setattr(failed_session, 'time', SimpleNamespace(monotonic=lambda: ticks[0], sleep=lambda seconds: ticks.__setitem__(0, ticks[0] + seconds))) result = failed_session.close_failed_startup(job, 12, timeout_seconds=1) assert result['status'] == 'CLOSED' and ticks[0] > 0 assert len(messages) == 1 @pytest.mark.parametrize('obstacle', ['', 'title', 'area', 'children', 'near_class']) def test_only_exact_empty_zero_area_childless_ie_infrastructure_is_benign(tmp_path, monkeypatch, obstacle): import win32gui, win32con job, records, messages = startup_fixture(tmp_path, monkeypatch) monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(hwnd, arg) for hwnd in (100, 200)]) monkeypatch.setattr(win32gui, 'GetClassName', lambda hwnd: 'Afx:main' if hwnd == 100 else 'Internet Explorer_Hidden_other' if obstacle == 'near_class' else 'Internet Explorer_Hidden') monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Expedition PCB' if hwnd == 100 else 'Active prompt' if obstacle == 'title' else '') monkeypatch.setattr(win32gui, 'GetWindowRect', lambda hwnd: (0, 0, 100, 50) if obstacle == 'area' else (0, 0, 0, 0)) monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, fn, arg: fn(201, arg) if hwnd == 200 and obstacle == 'children' else None) result = failed_session.close_failed_startup(job, 12, timeout_seconds=0) if obstacle: assert result['status'] == 'RETAINED' and messages == [] assert result['unknown_windows'][0]['hwnd'] == 200 else: assert result['status'] == 'CLOSED' and messages == [(100, win32con.WM_CLOSE)] entry = result['benign_auxiliary_windows'][0] assert entry['class'] == 'Internet Explorer_Hidden' and entry['rect'] == [0, 0, 0, 0] assert entry['children'] == []