"""Click every owned control; use real dialogs and controlled native outcomes.""" from pathlib import Path from threading import Event from types import SimpleNamespace import json import pytest from PySide6.QtCore import Qt from PySide6.QtWidgets import QMessageBox, QPushButton, QTextEdit from shiboken6 import isValid from button_simulation import modal_click, press, tab from cbb_refresh_verify.management import Capability, ManagementRequest, ManagementResult from cbb_refresh_verify.models import CbbRecord, LibraryReadResult from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult @pytest.fixture def controls(qtbot, tmp_path, monkeypatch, qapp): import cbb_refresh_verify.ui.main_window as ui from cbb_refresh_verify import library_lock old_native = qapp.testAttribute(Qt.AA_DontUseNativeDialogs) qapp.setAttribute(Qt.AA_DontUseNativeDialogs, True) library = tmp_path/'library.lmc' library.touch() source = tmp_path/'Beta.prj' source.write_text('KEY iCDBDir "database"\n', encoding='utf-8') state = SimpleNamespace(library=library, source=source, reads=[], runs=[], opened=[], entered=Event(), finish=Event(), native=[], result=None) state.finish.set() records = (CbbRecord('Ready', 'Power', status='READY'), CbbRecord('Beta', 'Power', status='PENDING'), CbbRecord('Gamma', 'Analog', status='UNKNOWN')) lease = SimpleNamespace(mentor_path=library, display_path=library, drive='', remote_root='', close=lambda: None, retain_for_recovery=lambda: None) def verify(request): state.runs.append(request) state.entered.set() assert state.finish.wait(5) return state.result or VerifyResult('CHECKED' if request.maintenance else 'PASS') monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *_: None) monkeypatch.setattr(ui.os, 'startfile', lambda path: state.opened.append(Path(path))) monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda path: dict(library=str(path), sessions=[])) adapter = SimpleNamespace(capabilities=lambda: {op: Capability(True, 'validated fixture') for op in ('add', 'update', 'remove')}) window = ui.MainWindow(reader=lambda path: (state.reads.append(path) or LibraryReadResult(records)), verifier=verify, data_root=tmp_path/'data', path_lease_factory=lambda _: lease, status_refresher=lambda names, _: {name:'PENDING' for name in names}, management_adapter=adapter) state.window = window window.show() window.lmc_edit.setText(str(library)) press(qtbot, window.load_button) qtbot.waitUntil(lambda: not window.busy) yield state state.finish.set() window.stop.set() if window._icdb_active(): window.icdb_task.cancel() window.native_queue.wake() if window._closing: qtbot.waitUntil(lambda: not isValid(window) or not window.isVisible()) if isValid(window): window.deleteLater() qtbot.waitUntil(lambda: not isValid(window)) qapp.setAttribute(Qt.AA_DontUseNativeDialogs, old_native) return dialog = getattr(window, 'management_dialog', None) if dialog is not None and isValid(dialog): dialog.stop.set() qtbot.waitUntil(lambda: not window.busy or (dialog is not None and not dialog.busy)) for child in window.findChildren(QMessageBox): if isValid(child): child.close() for name in ('management_dialog', 'backup_dialog', 'release_dialog'): child = getattr(window, name, None) if child is not None and isValid(child): qtbot.waitUntil(lambda child=child: not child.busy) child.close() qtbot.waitUntil(lambda: not window.busy and not window._icdb_active()) window.close() qtbot.waitUntil(lambda: not isValid(window) or not window.isVisible()) if isValid(window): window.deleteLater() qtbot.waitUntil(lambda: not isValid(window)) qapp.setAttribute(Qt.AA_DontUseNativeDialogs, old_native) def test_main_navigation_selection_and_toggles(controls, qtbot): w = controls.window for index in (2, 1, 0, 2, 0): tab(qtbot, w, index) press(qtbot, w.select_visible_button) assert len(w.selected_records()) == 3 press(qtbot, w.clear_selection_button) assert w.selected_records() == () press(qtbot, w.advanced_toggle) assert w.advanced_panel.isVisible() original = w.native_lm_verify_check.isChecked() press(qtbot, w.native_lm_verify_check) assert w.native_lm_verify_check.isChecked() != original press(qtbot, w.native_lm_verify_check) press(qtbot, w.advanced_toggle) assert not w.advanced_panel.isVisible() press(qtbot, w.runtime_log_toggle) assert w.output.isVisible() press(qtbot, w.runtime_log_toggle) assert not w.output.isVisible() @pytest.mark.parametrize('cancel', [True, False]) def test_main_library_chooser_real_open_and_cancel(controls, qtbot, cancel): w = controls.window before = len(controls.reads) with modal_click(qtbot, file=None if cancel else controls.library, cancel_file=cancel): press(qtbot, w.browse_button) qtbot.waitUntil(lambda: not w.busy) assert len(controls.reads) == before + (0 if cancel else 1) press(qtbot, w.load_button) qtbot.waitUntil(lambda: not w.busy) assert len(controls.reads) == before + (1 if cancel else 2) def test_main_logs_and_evidence_buttons_open_the_correct_paths(controls, qtbot): w = controls.window press(qtbot, w.logs_button) evidence = controls.library.parent/'evidence' evidence.mkdir() w.recovery_path = evidence w.recovery_button.setEnabled(True) press(qtbot, w.recovery_button) assert controls.opened == [w.data_root/'logs', evidence] @pytest.mark.parametrize('attribute', ['selected_batch_button', 'batch_button', 'icdb_repair_button']) @pytest.mark.parametrize('answer', [QMessageBox.No, QMessageBox.Yes]) def test_main_check_buttons_have_real_confirm_and_cancel_paths(controls, qtbot, attribute, answer): w = controls.window if attribute == 'icdb_repair_button': tab(qtbot, w, 1) w.search_edit.setText('Beta') press(qtbot, w.select_visible_button) with modal_click(qtbot, answer): press(qtbot, getattr(w, attribute)) qtbot.waitUntil(lambda: not w.busy and not w._icdb_active()) assert [request.block_name for request in controls.runs] == ([] if answer == QMessageBox.No else ['Beta']) if controls.runs: assert controls.runs[0].auto_repair is False summary = w.summary details = next((b for b in summary.findChildren(QPushButton) if 'Details' in b.text()), None) assert details is not None press(qtbot, details) assert summary.findChild(QTextEdit).isVisible() press(qtbot, summary.button(QMessageBox.Close)) assert not isValid(summary) or not summary.isVisible() @pytest.mark.parametrize('background', [True, False]) def test_main_stop_buttons_stop_additional_items(controls, qtbot, background): w = controls.window controls.finish.clear() if background: tab(qtbot, w, 1) button = w.icdb_repair_button if background else w.batch_button try: with modal_click(qtbot, QMessageBox.Yes): press(qtbot, button) qtbot.waitUntil(controls.entered.is_set) stop = w.icdb_stop_button if background else w.stop_button press(qtbot, stop) assert (w.icdb_task.stop if background else w.stop).is_set() finally: controls.finish.set() qtbot.waitUntil(lambda: not w.busy and not w._icdb_active()) assert [request.block_name for request in controls.runs] == ['Beta'] @pytest.mark.parametrize('operation', ['add', 'update', 'remove']) def test_main_management_buttons_open_the_requested_operation(controls, qtbot, operation): w = controls.window tab(qtbot, w, 2) w.search_edit.setText('Beta') press(qtbot, w.select_visible_button) press(qtbot, getattr(w, operation+'_button')) dialog = w.management_dialog assert dialog.operation == operation and w.busy if operation != 'add': assert [request.name for request in dialog.requests()] == ['Beta'] press(qtbot, dialog.close_button) qtbot.waitUntil(lambda: not w.busy) def test_main_backup_restore_and_release_entries(controls, qtbot): w = controls.window tab(qtbot, w, 1) w.search_edit.setText('Beta') press(qtbot, w.select_visible_button) press(qtbot, w.backup_restore_button) assert w.backup_dialog.block_combo.currentText() == 'Beta' press(qtbot, w.backup_dialog.close_button) tab(qtbot, w, 2) press(qtbot, w.release_library_button) qtbot.waitUntil(lambda: not w.release_dialog.busy) assert w.release_dialog.plan['library'] == str(controls.library) press(qtbot, w.release_dialog.close_button) qtbot.waitUntil(lambda: not w.busy) def test_native_backup_entry_starts_once_and_reenables_after_receipt(controls, qtbot): w = controls.window tab(qtbot, w, 1) w.search_edit.setText('Beta') press(qtbot, w.select_visible_button) job = controls.library.parent/'request.json' job.write_text('{}', encoding='utf-8') ended = Event() session = SimpleNamespace(library=controls.library, block='Beta', job=job, process=SimpleNamespace(poll=lambda: 0 if ended.is_set() else None)) w.native_backup_launcher = lambda request: (controls.native.append(request) or session) press(qtbot, w.native_backup_button) qtbot.waitUntil(lambda: not w.busy) for _ in range(5): qtbot.mouseClick(w.native_backup_button, Qt.LeftButton) assert len(controls.native) == 1 and not w.native_backup_button.isEnabled() job.with_name('result.json').write_text(json.dumps(dict(status='CLOSED', safe_to_continue=True, library=str(controls.library), block='Beta', restore_confirmed=False)), encoding='utf-8') ended.set() qtbot.waitUntil(lambda: w._native_backup_session is None and not w.busy, timeout=3000) assert w.native_backup_button.isEnabled() assert 'PASS' not in w.cbb_table.item(w._row_by_name['Beta'], 3).text() @pytest.mark.parametrize('operation', ['add', 'update']) @pytest.mark.parametrize('cancel', [True, False]) def test_management_source_chooser_and_auto_verify_toggle(controls, qtbot, operation, cancel): from cbb_refresh_verify.ui.management_dialog import ManagementDialog req = ManagementRequest(operation, controls.library, '' if operation == 'add' else 'Beta') dialog = ManagementDialog([req]) qtbot.addWidget(dialog) dialog.show() with modal_click(qtbot, file=None if cancel else controls.source, cancel_file=cancel): press(qtbot, dialog.sources_button) assert dialog.table.rowCount() == (0 if operation == 'add' and cancel else 1) if not cancel: assert dialog.requests()[0].source == controls.source checked = dialog.auto_verify.isChecked() press(qtbot, dialog.auto_verify) assert dialog.auto_verify.isChecked() != checked press(qtbot, dialog.logs_button) assert dialog.output.isVisible() press(qtbot, dialog.logs_button) assert not dialog.output.isVisible() press(qtbot, dialog.close_button) assert not dialog.isVisible() def test_management_confirm_cancel_execute_stop_and_repeated_click(controls, qtbot): from cbb_refresh_verify.ui.management_dialog import ManagementDialog entered, finish = Event(), Event() calls = [] def runner(requests, **kwargs): calls.extend(requests) entered.set() assert finish.wait(5) return [ManagementResult('remove', controls.library, 'Beta', 'Logical-Physical', None, False, 'complete', 'REMOVED', True)] dialog = ManagementDialog([ManagementRequest('remove', controls.library, 'Beta')], runner=runner) qtbot.addWidget(dialog) dialog.show() with modal_click(qtbot, QMessageBox.No): press(qtbot, dialog.execute_button) assert calls == [] and not dialog.executed try: with modal_click(qtbot, QMessageBox.Yes): press(qtbot, dialog.execute_button) qtbot.waitUntil(entered.is_set) for _ in range(5): qtbot.mouseClick(dialog.execute_button, Qt.LeftButton) qtbot.mouseClick(dialog.close_button, Qt.LeftButton) assert len(calls) == 1 and dialog.isVisible() press(qtbot, dialog.stop_button) assert dialog.context.stop_after_current.is_set() and not dialog.stop.is_set() finally: finish.set() qtbot.waitUntil(lambda: not dialog.busy) assert '已移除' in dialog.status_label.text() press(qtbot, dialog.close_button) @pytest.mark.parametrize('cancel', [True, False]) def test_recovery_real_source_chooser_and_confirmation_options(controls, qtbot, cancel): from cbb_refresh_verify.ui.backup_recovery_dialog import BackupRecoveryDialog calls = [] def recover(request, source, **kwargs): calls.append((request.block_name, source)) return VerifyResult('PASS') dialog = BackupRecoveryDialog(['Beta'], lambda name: VerifyRequest(controls.library, name, controls.library.parent/'evidence'), recoverer=recover) qtbot.addWidget(dialog) dialog.show() with modal_click(qtbot, file=None if cancel else controls.source, cancel_file=cancel): press(qtbot, dialog.browse_button) if cancel: assert dialog.source_edit.text() == '' else: assert Path(dialog.source_edit.text()) == controls.source if cancel: press(qtbot, dialog.restore_button) assert '有效' in dialog.status_label.text() and not dialog.busy else: with modal_click(qtbot, QMessageBox.No): press(qtbot, dialog.restore_button) assert calls == [] with modal_click(qtbot, QMessageBox.Yes): press(qtbot, dialog.restore_button) qtbot.waitUntil(lambda: not dialog.busy) assert calls == [('Beta', controls.source)] assert '恢复完成' in dialog.status_label.text() press(qtbot, dialog.close_button) assert not dialog.isVisible() def test_recovery_cancel_queue_never_calls_native_restore(controls, qtbot): from cbb_refresh_verify.operation_queue import NativeQueue from cbb_refresh_verify.ui.backup_recovery_dialog import BackupRecoveryDialog calls = [] queue = NativeQueue() queue.active = True dialog = BackupRecoveryDialog(['Beta'], lambda name: VerifyRequest(controls.library, name, controls.library.parent/'evidence'), recoverer=lambda *a, **k: calls.append(a)) dialog.native_queue = queue qtbot.addWidget(dialog) dialog.show() dialog.source_edit.setText(str(controls.source)) with modal_click(qtbot, QMessageBox.Yes): press(qtbot, dialog.restore_button) qtbot.waitUntil(dialog.cancel_queue_button.isEnabled) press(qtbot, dialog.cancel_queue_button) qtbot.waitUntil(lambda: not dialog.busy) assert calls == [] and dialog.stop.is_set() press(qtbot, dialog.close_button) @pytest.mark.parametrize('attribute, expected', [('manual_button','last_user_saved'), ('auto_button','autosave'), ('cancel_button','cancel')]) def test_version_choice_buttons_choose_only_the_clicked_version(qtbot, attribute, expected): from cbb_refresh_verify.pcb_restore_prompt import RestoreChoice from cbb_refresh_verify.ui.pcb_restore_dialog import PcbRestoreDialog choice = RestoreChoice('Beta', 'fixture.lmc', [dict(kind=kind, enabled=True, date='2026/11/11 10:00') for kind in ('last_user_saved','autosave')]) dialog = PcbRestoreDialog(choice) qtbot.addWidget(dialog) dialog.show() press(qtbot, getattr(dialog, attribute)) assert choice.decision == expected dialog.close() assert choice.decision == expected @pytest.fixture def residual(controls, qtbot, monkeypatch): from cbb_refresh_verify import library_lock, residual_sessions from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog row = dict(project='Beta', name='ExpeditionPCB.exe', pid=10, detail='fixture session', scope_confirmed=True, owner_sid='S-1-fixture', session_id=1, force_user_confirmed=True, image='C:/Fixture/ExpeditionPCB.exe', created_handle='fixture-created', native_activity=dict(status='IDLE', detail='fixture returned'), desktops=['CbbFixture'], windows=[dict(title='Fixture native prompt', output='Fixture details')], prompt=dict(text='Save the changed fixture?'), cancel_prompt=dict(text='Cancel fixture')) plan = dict(library=str(controls.library), sessions=[row]) state = SimpleNamespace(scans=[], releases=[], cancels=[], saves=[], row=row, plan=plan, entered=Event(), finish=Event(), hold=False) def inspect(library): state.scans.append(library) return plan def release(actual, folder, **kwargs): state.releases.append(kwargs) if state.hold: state.entered.set() assert state.finish.wait(5) return dict(status='PARTIAL', sessions=[dict(row, release_status='WAITING', consent_allowed=True)]) def cancel(actual, library, folder, **kwargs): state.cancels.append(actual) return dict(status='PARTIAL', detail='Fixture cancel received', sessions=[dict(row, release_status='WAITING')]) monkeypatch.setattr(library_lock, 'inspect_residual_sessions', inspect) monkeypatch.setattr(library_lock, 'release_residual_sessions', release) monkeypatch.setattr(residual_sessions, 'request_native_cancel', cancel) monkeypatch.setattr(residual_sessions, 'answer_save_question', lambda actual, code: state.saves.append((actual['pid'], code))) dialog = ResidualReleaseDialog(controls.library, controls.library.parent/'release-evidence') qtbot.addWidget(dialog) dialog.show() qtbot.waitUntil(lambda: not dialog.busy) state.dialog = dialog yield state state.finish.set() qtbot.waitUntil(lambda: not dialog.busy) def test_residual_refresh_details_confirm_and_close(residual, qtbot): d = residual.dialog press(qtbot, d.refresh_button) qtbot.waitUntil(lambda: not d.busy) assert len(residual.scans) == 2 and d.table.rowCount() == 1 press(qtbot, d.details_button) details = d.native_details assert 'Fixture native prompt' in details.detailedText() expand = next(b for b in details.findChildren(QPushButton) if 'Details' in b.text()) press(qtbot, expand) assert details.findChild(QTextEdit).isVisible() press(qtbot, details.button(QMessageBox.Close)) press(qtbot, d.confirm_button) qtbot.waitUntil(lambda: not d.busy) assert len(residual.releases) == 1 and residual.releases[0]['force'] is False assert d.table.item(0, 6).text() == '允许' assert d.table.item(0, 7).text() == '未释放' press(qtbot, d.close_button) assert not d.isVisible() @pytest.mark.parametrize('answer, code', [(QMessageBox.Yes,6),(QMessageBox.No,7),(QMessageBox.Cancel,2)]) def test_residual_save_prompt_buttons_preserve_the_users_choice(residual, qtbot, answer, code): d = residual.dialog with modal_click(qtbot, answer): press(qtbot, d.prompt_button) qtbot.waitUntil(lambda: not d.busy) assert residual.saves == [(10, code)] assert d.isVisible() and residual.releases == [] @pytest.mark.parametrize('answer', [QMessageBox.No,QMessageBox.Yes]) def test_residual_native_cancel_confirm_and_decline(residual, qtbot, answer): d = residual.dialog with modal_click(qtbot, answer): press(qtbot, d.cancel_native_button) qtbot.waitUntil(lambda: not d.busy) assert len(residual.cancels) == (1 if answer == QMessageBox.Yes else 0) assert residual.releases == [] @pytest.mark.parametrize('answer', [QMessageBox.Cancel,QMessageBox.Yes]) def test_residual_force_buttons_require_actual_confirmation(residual, qtbot, answer): d = residual.dialog with modal_click(qtbot, answer): press(qtbot, d.force_button) qtbot.waitUntil(lambda: not d.busy) assert [call['force'] for call in residual.releases] == ([True] if answer == QMessageBox.Yes else []) def test_residual_busy_repeated_clicks_and_stop_release(residual, qtbot): d = residual.dialog residual.hold = True try: press(qtbot, d.confirm_button) qtbot.waitUntil(residual.entered.is_set) for _ in range(5): qtbot.mouseClick(d.confirm_button, Qt.LeftButton) qtbot.mouseClick(d.refresh_button, Qt.LeftButton) assert len(residual.releases) == 1 and len(residual.scans) == 1 press(qtbot, d.close_button) assert d.stop.is_set() and d.isVisible() finally: residual.finish.set() qtbot.waitUntil(lambda: not d.busy) press(qtbot, d.close_button) def test_result_release_and_resume_buttons_run_only_unexecuted_items(controls, qtbot, monkeypatch): from cbb_refresh_verify import library_lock w = controls.window controls.result = VerifyResult('FAIL', safe_to_continue=False, stderr='Fixture release unconfirmed') with modal_click(qtbot, QMessageBox.Yes): press(qtbot, w.batch_button) qtbot.waitUntil(lambda: not w.busy) assert [request.block_name for request in controls.runs] == ['Beta'] assert not w._resume_batch_action.isEnabled() proof = dict(status='RELEASE_CONFIRMED', library=str(controls.library), evidence_path='fixture-proof.json') monkeypatch.setattr(library_lock, 'release_residual_sessions', lambda *a, **k: dict(status='RELEASE_CONFIRMED', proof=proof, sessions=[])) press(qtbot, w._residual_release_action) qtbot.waitUntil(lambda: not w.release_dialog.busy) press(qtbot, w.release_dialog.confirm_button) qtbot.waitUntil(lambda: not w.release_dialog.busy) press(qtbot, w.release_dialog.close_button) qtbot.waitUntil(lambda: not w.busy) controls.result = VerifyResult('PASS') press(qtbot, w._resume_batch_action) qtbot.waitUntil(lambda: not w.busy) assert [request.block_name for request in controls.runs] == ['Beta','Gamma'] @pytest.mark.parametrize('entry', ['icdb_copy', 'icdb_release', 'batch_copy', 'batch_close']) def test_result_recovery_and_release_entries_stay_bound_to_failed_cbb(controls, qtbot, entry): from dataclasses import replace from test_reimport_recovery import failed_repair w = controls.window if entry.startswith('icdb'): tab(qtbot, w, 1) w.search_edit.setText('Beta') controls.result = failed_repair(controls.library.parent/'failure.json', safe=entry=='icdb_copy') with modal_click(qtbot, QMessageBox.Yes): press(qtbot, w.icdb_repair_button) qtbot.waitUntil(lambda: not w._icdb_active()) label = '查看残留并释放…' if entry=='icdb_release' else '选择副本恢复…' press(qtbot, next(b for b in w.icdb_summary.buttons() if b.text()==label)) else: # This is the supported legacy maintenance-result shape; current UI # maintenance uses the independent IcdbCheckTask route above. req = replace(w._request('Beta'), maintenance=True) w._batch_requests = (req,) w._batch_records = {'Beta':w._records_by_name['Beta']} w._batch_done(([failed_repair(controls.library.parent/'failure.json',safe=True)], None)) w._update() if entry=='batch_close': summary = w.summary press(qtbot, summary.button(QMessageBox.Close)) assert not isValid(summary) or not summary.isVisible() return press(qtbot, w._reimport_summary_action) if entry=='icdb_release': qtbot.waitUntil(lambda: not w.release_dialog.busy) assert w.release_dialog.library == controls.library press(qtbot, w.release_dialog.close_button) else: dialog = w.management_dialog assert [req.name for req in dialog.requests()] == ['Beta'] assert Path(dialog.recovery_from['Beta']) == controls.library.parent/'failure.json' press(qtbot, dialog.close_button) qtbot.waitUntil(lambda: not w.busy) if entry=='icdb_copy': tab(qtbot,w,1) press(qtbot,w.reimport_button) assert [req.name for req in w.management_dialog.requests()] == ['Beta'] press(qtbot,w.management_dialog.close_button) def test_invalidated_catalog_buttons_ignore_clicks(controls, qtbot): w = controls.window w.lmc_edit.setText('not-loaded.lmc') for index, attributes in [(0,['selected_batch_button','batch_button']), (1,['icdb_repair_button','native_backup_button','backup_restore_button']), (2,['add_button','update_button','remove_button'])]: tab(qtbot,w,index) for attribute in attributes: button = getattr(w,attribute) assert not button.isEnabled() qtbot.mouseClick(button,Qt.LeftButton) assert controls.runs == [] and controls.native == [] assert getattr(w,'management_dialog',None) is None @pytest.mark.parametrize('attribute, failure', [('logs_button','shell'), ('logs_button','directory'),('recovery_button','shell')]) def test_log_and_evidence_buttons_report_external_failure(controls,qtbot,monkeypatch,attribute,failure): import cbb_refresh_verify.ui.main_window as ui def fail(path): raise OSError('Fixture shell access denied') w = controls.window if failure=='shell': monkeypatch.setattr(ui.os,'startfile',fail) expected = 'Fixture shell access denied' else: w.data_root = controls.source/'logs' expected = 'Beta.prj' if attribute=='recovery_button': w.recovery_path = controls.library.parent w.recovery_button.setEnabled(True) press(qtbot,getattr(w,attribute)) assert expected in w.status_label.text() assert controls.opened == []