From 282be7be7f1f23e80ff556081a162e60f3f20fae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Thu, 5 Nov 2026 23:25:25 +0800 Subject: [PATCH 1/3] feat: integrate independent background checks and native management UI --- docs/reviews/2026-11-05-ui-integration.md | 9 + src/cbb_refresh_verify/application.py | 299 +-- src/cbb_refresh_verify/ui/backup_notice.py | 5 + .../ui/backup_recovery_dialog.py | 37 +- src/cbb_refresh_verify/ui/icdb_check_task.py | 115 + src/cbb_refresh_verify/ui/main_window.py | 2147 ++++++++++++----- .../ui/management_dialog.py | 235 ++ .../ui/pcb_restore_dialog.py | 31 + tests/test_background_icdb.py | 75 + tests/test_background_queue_regressions.py | 122 + tests/test_backup_recovery_dialog.py | 22 +- tests/test_extended_safety.py | 13 + tests/test_icdb_batch_check.py | 159 ++ tests/test_independent_operations.py | 181 ++ tests/test_maintenance_review.py | 171 ++ tests/test_maintenance_ui.py | 75 + tests/test_management_ui.py | 113 + tests/test_manual_backup_ui.py | 51 + tests/test_native_backup.py | 263 ++ tests/test_native_occupancy.py | 360 +-- tests/test_navigation_tabs.py | 43 + tests/test_pcb_restore_prompt.py | 132 + tests/test_reimport_recovery.py | 242 ++ tests/test_ui.py | 77 +- tests/test_ui_batch_safety.py | 247 ++ tests/test_ui_filters.py | 291 +++ tests/test_ui_lease_lifecycle.py | 133 + 27 files changed, 4716 insertions(+), 932 deletions(-) create mode 100644 docs/reviews/2026-11-05-ui-integration.md create mode 100644 src/cbb_refresh_verify/ui/backup_notice.py create mode 100644 src/cbb_refresh_verify/ui/icdb_check_task.py create mode 100644 src/cbb_refresh_verify/ui/management_dialog.py create mode 100644 src/cbb_refresh_verify/ui/pcb_restore_dialog.py create mode 100644 tests/test_background_icdb.py create mode 100644 tests/test_background_queue_regressions.py create mode 100644 tests/test_icdb_batch_check.py create mode 100644 tests/test_independent_operations.py create mode 100644 tests/test_maintenance_review.py create mode 100644 tests/test_maintenance_ui.py create mode 100644 tests/test_management_ui.py create mode 100644 tests/test_manual_backup_ui.py create mode 100644 tests/test_native_backup.py create mode 100644 tests/test_navigation_tabs.py create mode 100644 tests/test_pcb_restore_prompt.py create mode 100644 tests/test_reimport_recovery.py create mode 100644 tests/test_ui_batch_safety.py create mode 100644 tests/test_ui_filters.py create mode 100644 tests/test_ui_lease_lifecycle.py diff --git a/docs/reviews/2026-11-05-ui-integration.md b/docs/reviews/2026-11-05-ui-integration.md new file mode 100644 index 0000000..bbe49b2 --- /dev/null +++ b/docs/reviews/2026-11-05-ui-integration.md @@ -0,0 +1,9 @@ +# Application integration review unit + +Base: codex/review-native-backend. Behavior: verification, ICDB batch checking and CBB management have separate tabs; background checks yield between items, keep browsing responsive and let other native tasks queue. READY targets are excluded at execution, status refresh is scoped, and manual version/copy decisions remain explicit. + +Failure safety: a released item failure can continue independent targets; uncertain native ownership retains evidence and mappings. There is no residual-session release backend in this review stage: its button and result actions are hidden, and its callback is inert. The next PR restores the complete release entry together with its tested backend, rather than exposing a button with a missing import. No automatic Repair or native version selection is added. + +Rollback: revert this UI commit before its dependent release PR; after dependents, revert in reverse order or close the current program and use the prior candidate. This does not roll back library writes. + +Validation: 1,545 passed (one existing pywinauto COM-threading warning), compileall and diff checks passed. Release-specific tests are introduced in the dependent PR, never discarded from the final tree. Windows 10, real shared-library concurrency and field ICDB recovery remain pending. diff --git a/src/cbb_refresh_verify/application.py b/src/cbb_refresh_verify/application.py index 3ec1905..8d2fb88 100644 --- a/src/cbb_refresh_verify/application.py +++ b/src/cbb_refresh_verify/application.py @@ -1,148 +1,151 @@ -from __future__ import annotations -import argparse, os, sys -from pathlib import Path -from typing import Sequence -from .runtime_logging import configure - - -def configure_qt_application(app): - """Apply a predictable light palette across machines and Qt themes.""" - from PySide6.QtGui import QColor, QPalette - - app.setStyle('Fusion') - palette = app.palette() - colors = { - QPalette.ColorRole.Window: '#f5f6f8', - QPalette.ColorRole.WindowText: '#202124', - QPalette.ColorRole.Base: '#ffffff', - QPalette.ColorRole.AlternateBase: '#eef1f5', - QPalette.ColorRole.Text: '#202124', - QPalette.ColorRole.Button: '#eef1f5', - QPalette.ColorRole.ButtonText: '#202124', - QPalette.ColorRole.Highlight: '#2f6fed', - QPalette.ColorRole.HighlightedText: '#ffffff', - QPalette.ColorRole.ToolTipBase: '#ffffff', - QPalette.ColorRole.ToolTipText: '#202124', - QPalette.ColorRole.PlaceholderText: '#6b7280', - } - for role, color in colors.items(): - palette.setColor(role, QColor(color)) - app.setPalette(palette) - app.setStyleSheet( - 'QWidget { color: #202124; }' - 'QTableWidget, QLineEdit, QTextEdit, QSpinBox { ' - 'background: #ffffff; color: #202124; selection-color: #202124; }' - 'QHeaderView::section { background: #e9edf2; color: #202124; }' - 'QPushButton, QToolButton { color: #202124; }' - ) - return app - -def resolve_data_root(cli_value: Path | None) -> Path: - if cli_value is not None: return cli_value.expanduser().resolve() - if getattr(sys, "frozen", False): return Path(sys.executable).resolve().parent / "data" - local = os.environ.get("LOCALAPPDATA") - return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve() - -def main(argv: Sequence[str] | None = None) -> int: - parser = argparse.ArgumentParser(prog="CbbRefreshVerify") - parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS) - parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS) - parser.add_argument('--owner-probe', type=Path, help=argparse.SUPPRESS) - parser.add_argument('--native-backup-worker', type=Path, help=argparse.SUPPRESS) - parser.add_argument('--management-worker', type=Path, help=argparse.SUPPRESS) - parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS) - parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS) - parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS) - parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS) - parser.add_argument('--libspec', default='', help=argparse.SUPPRESS) - parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS) - parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS) - parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS) - args = parser.parse_args(list(argv) if argv is not None else None) - if args.owner_probe: - from .owner_probe import owner_probe_main - return owner_probe_main(args.owner_probe) - if args.native_backup_worker: - from .native_backup import native_backup_worker_main - return native_backup_worker_main(args.native_backup_worker) - if args.management_worker: - from .native_management import management_worker_main - return management_worker_main(args.management_worker) - if args.repair_worker: - from .native_repair_ui import repair_worker_main - return repair_worker_main(args.repair_worker) - if args.collect_failure_logs: - from .verify_diagnostics import failure_logs_main - return failure_logs_main(args.collect_failure_logs) - if args.dialog_agent: - from .dialog_agent import dialog_agent_main - return dialog_agent_main(args.dialog_agent) - if args.verify_worker: - from .mentor_adapter import worker_main - import contextlib - with args.verify_worker.with_name('worker.log').open('a', encoding='utf-8') as log: - with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log): - return worker_main(args.verify_worker) - context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start") - try: - if args.batch_lmc: - from .verify_runner import (VerifyRequest, native_lm_verify_enabled, - run_batch, write_batch_report, failure_report_path) - from .library_reader import read_library_fast - from .batch_status import authoritative_status_map - from .network_path import LibraryPathLease, select_library_file - with LibraryPathLease.acquire(args.batch_lmc) as lease: - mentor_path = select_library_file(lease.mentor_path) - logger.info( - 'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s', - lease.display_path, mentor_path, lease.drive or '-', - lease.remote_root or '-', lease.created) - names = list(args.block) - if not names: - library = read_library_fast( - mentor_path, - status_reader=lambda path, names: authoritative_status_map( - names, path, context.root/'status-scan.jsonl'), - ) - if library.error: raise RuntimeError(library.error) - names = [record.name for record in library.records if record.status != 'READY'] - if not names: raise RuntimeError('中心库未读取到需要校验的 CBB') - requests = [VerifyRequest(mentor_path, name, context.root/'evidence', - libspec=args.libspec, dms_login_config=args.dms_login_config, - mentor_bin=args.mentor_bin, logging_context=context, - mapped_drive=lease.drive, - mapped_remote_root=lease.remote_root, - native_lm_verify=native_lm_verify_enabled()) - for name in names] - try: - results = run_batch(requests) - except Exception: - lease.retain_for_recovery() - raise - if any(not result.safe_to_continue for result in results): - lease.retain_for_recovery() - report = write_batch_report(requests, results, context.root/'reports') - logger.info('batch_report path=%s', report) - logger.info('failure_report path=%s', failure_report_path(report)) - code = 0 if all(result.status == 'PASS' for result in results) else 2 - logger.info('application_clean_shutdown exit_code=%s', code) - return code - from .ui.main_window import MainWindow, application_icon_path - if args.smoke_test: - os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen') - from PySide6.QtWidgets import QApplication - app = QApplication.instance() or QApplication([sys.executable]) - configure_qt_application(app) - window = MainWindow(logging_context=context); window.show() - icon_path = application_icon_path() - if icon_path.is_file(): - from PySide6.QtGui import QIcon - app.setWindowIcon(QIcon(str(icon_path))) - if args.smoke_test: - from PySide6.QtCore import QTimer - logger.info('gui_smoke_window_created title=%s', window.windowTitle()) - QTimer.singleShot(250, app.quit) - code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code - except Exception: logger.exception("application_startup_failure"); return 1 - finally: - for handler in logger.handlers: handler.flush() +from __future__ import annotations +import argparse, os, sys +from pathlib import Path +from typing import Sequence +from .runtime_logging import configure + + +def configure_qt_application(app): + """Apply a predictable light palette across machines and Qt themes.""" + from PySide6.QtGui import QColor, QPalette + + app.setStyle('Fusion') + palette = app.palette() + colors = { + QPalette.ColorRole.Window: '#f5f6f8', + QPalette.ColorRole.WindowText: '#202124', + QPalette.ColorRole.Base: '#ffffff', + QPalette.ColorRole.AlternateBase: '#eef1f5', + QPalette.ColorRole.Text: '#202124', + QPalette.ColorRole.Button: '#eef1f5', + QPalette.ColorRole.ButtonText: '#202124', + QPalette.ColorRole.Highlight: '#2f6fed', + QPalette.ColorRole.HighlightedText: '#ffffff', + QPalette.ColorRole.ToolTipBase: '#ffffff', + QPalette.ColorRole.ToolTipText: '#202124', + QPalette.ColorRole.PlaceholderText: '#6b7280', + } + for role, color in colors.items(): + palette.setColor(role, QColor(color)) + for role in (QPalette.ColorRole.WindowText, QPalette.ColorRole.Text, QPalette.ColorRole.ButtonText): + palette.setColor(QPalette.ColorGroup.Disabled, role, QColor('#858b94')) + app.setPalette(palette) + app.setStyleSheet( + 'QWidget { color: #202124; }' + 'QTableWidget, QLineEdit, QTextEdit, QSpinBox { ' + 'background: #ffffff; color: #202124; selection-color: #202124; }' + 'QHeaderView::section { background: #e9edf2; color: #202124; }' + 'QPushButton, QToolButton { color: #202124; }' + 'QPushButton:disabled, QToolButton:disabled { color: #858b94; background: #e3e6eb; }' + ) + return app + +def resolve_data_root(cli_value: Path | None) -> Path: + if cli_value is not None: return cli_value.expanduser().resolve() + if getattr(sys, "frozen", False): return Path(sys.executable).resolve().parent / "data" + local = os.environ.get("LOCALAPPDATA") + return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve() + +def main(argv: Sequence[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="CbbRefreshVerify") + parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS) + parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS) + parser.add_argument('--owner-probe', type=Path, help=argparse.SUPPRESS) + parser.add_argument('--native-backup-worker', type=Path, help=argparse.SUPPRESS) + parser.add_argument('--management-worker', type=Path, help=argparse.SUPPRESS) + parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS) + parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS) + parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS) + parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS) + parser.add_argument('--libspec', default='', help=argparse.SUPPRESS) + parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS) + parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS) + parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS) + args = parser.parse_args(list(argv) if argv is not None else None) + if args.owner_probe: + from .owner_probe import owner_probe_main + return owner_probe_main(args.owner_probe) + if args.native_backup_worker: + from .native_backup import native_backup_worker_main + return native_backup_worker_main(args.native_backup_worker) + if args.management_worker: + from .native_management import management_worker_main + return management_worker_main(args.management_worker) + if args.repair_worker: + from .native_repair_ui import repair_worker_main + return repair_worker_main(args.repair_worker) + if args.collect_failure_logs: + from .verify_diagnostics import failure_logs_main + return failure_logs_main(args.collect_failure_logs) + if args.dialog_agent: + from .dialog_agent import dialog_agent_main + return dialog_agent_main(args.dialog_agent) + if args.verify_worker: + from .mentor_adapter import worker_main + import contextlib + with args.verify_worker.with_name('worker.log').open('a', encoding='utf-8') as log: + with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log): + return worker_main(args.verify_worker) + context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start") + try: + if args.batch_lmc: + from .verify_runner import (VerifyRequest, native_lm_verify_enabled, + run_batch, write_batch_report, failure_report_path) + from .library_reader import read_library_fast + from .batch_status import authoritative_status_map + from .network_path import LibraryPathLease, select_library_file + with LibraryPathLease.acquire(args.batch_lmc) as lease: + mentor_path = select_library_file(lease.mentor_path) + logger.info( + 'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s', + lease.display_path, mentor_path, lease.drive or '-', + lease.remote_root or '-', lease.created) + names = list(args.block) + if not names: + library = read_library_fast( + mentor_path, + status_reader=lambda path, names: authoritative_status_map( + names, path, context.root/'status-scan.jsonl'), + ) + if library.error: raise RuntimeError(library.error) + names = [record.name for record in library.records if record.status != 'READY'] + if not names: raise RuntimeError('中心库未读取到需要校验的 CBB') + requests = [VerifyRequest(mentor_path, name, context.root/'evidence', + libspec=args.libspec, dms_login_config=args.dms_login_config, + mentor_bin=args.mentor_bin, logging_context=context, + mapped_drive=lease.drive, + mapped_remote_root=lease.remote_root, + native_lm_verify=native_lm_verify_enabled()) + for name in names] + try: + results = run_batch(requests) + except Exception: + lease.retain_for_recovery() + raise + if any(not result.safe_to_continue for result in results): + lease.retain_for_recovery() + report = write_batch_report(requests, results, context.root/'reports') + logger.info('batch_report path=%s', report) + logger.info('failure_report path=%s', failure_report_path(report)) + code = 0 if all(result.status == 'PASS' for result in results) else 2 + logger.info('application_clean_shutdown exit_code=%s', code) + return code + from .ui.main_window import MainWindow, application_icon_path + if args.smoke_test: + os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen') + from PySide6.QtWidgets import QApplication + app = QApplication.instance() or QApplication([sys.executable]) + configure_qt_application(app) + window = MainWindow(logging_context=context); window.show() + icon_path = application_icon_path() + if icon_path.is_file(): + from PySide6.QtGui import QIcon + app.setWindowIcon(QIcon(str(icon_path))) + if args.smoke_test: + from PySide6.QtCore import QTimer + logger.info('gui_smoke_window_created title=%s', window.windowTitle()) + QTimer.singleShot(250, app.quit) + code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code + except Exception: logger.exception("application_startup_failure"); return 1 + finally: + for handler in logger.handlers: handler.flush() diff --git a/src/cbb_refresh_verify/ui/backup_notice.py b/src/cbb_refresh_verify/ui/backup_notice.py new file mode 100644 index 0000000..c4e3f75 --- /dev/null +++ b/src/cbb_refresh_verify/ui/backup_notice.py @@ -0,0 +1,5 @@ +"""Shared wording for user-managed backups before write operations.""" + +MANUAL_BACKUP_NOTICE = ( + '应用不会自动备份。请先手动备份中心库及相关工程,并确认备份可用于恢复。' +) diff --git a/src/cbb_refresh_verify/ui/backup_recovery_dialog.py b/src/cbb_refresh_verify/ui/backup_recovery_dialog.py index 635ee27..66024bb 100644 --- a/src/cbb_refresh_verify/ui/backup_recovery_dialog.py +++ b/src/cbb_refresh_verify/ui/backup_recovery_dialog.py @@ -1,11 +1,13 @@ """Small, asynchronous entry point for recovery from a healthy CBB project.""" from pathlib import Path +from threading import Event from PySide6.QtCore import QObject, QThreadPool, Signal from PySide6.QtWidgets import (QComboBox, QDialog, QFileDialog, QFormLayout, - QHBoxLayout, QLabel, QLineEdit, QPushButton) + QHBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox) from .workers import ServiceWorker +from .backup_notice import MANUAL_BACKUP_NOTICE class RecoverySignals(QObject): @@ -22,6 +24,8 @@ class BackupRecoveryDialog(QDialog): self.resize(620, 230) self.request_factory = request_factory self.recoverer = recoverer + self.native_queue = None + self.stop = Event() self.busy = False self.pool = QThreadPool(self) self.pool.setMaxThreadCount(1) @@ -37,7 +41,10 @@ class BackupRecoveryDialog(QDialog): self.restore_button.clicked.connect(self._restore) self.close_button = QPushButton('关闭') self.close_button.clicked.connect(self.reject) - self.status_label = QLabel('使用所选备份版本恢复同名 CBB。先在库副本中验证,原工程与完整库副本会保留;需要额外磁盘空间。') + self.cancel_queue_button = QPushButton('取消排队') + self.cancel_queue_button.setEnabled(False) + self.cancel_queue_button.clicked.connect(self.stop.set) + self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 所选备份先在隔离库中验证;安装时旧 Work 仅改名保留。') self.status_label.setWordWrap(True) layout = QFormLayout(self) layout.addRow('目标 CBB', self.block_combo) @@ -49,6 +56,7 @@ class BackupRecoveryDialog(QDialog): buttons = QHBoxLayout() buttons.addStretch() buttons.addWidget(self.restore_button) + buttons.addWidget(self.cancel_queue_button) buttons.addWidget(self.close_button) layout.addRow(buttons) @@ -77,12 +85,30 @@ class BackupRecoveryDialog(QDialog): except Exception as error: self.status_label.setText(str(error)) return + if QMessageBox.question(self, '确认从备份恢复', + f'{MANUAL_BACKUP_NOTICE}\n\n目标库:{request.lmc_file}\nCBB:{name}\n来源:{source}' + '\n\n将创建用于校验的隔离库副本,校验通过后替换目标工程。确认继续?', + QMessageBox.Yes | QMessageBox.No, QMessageBox.No) != QMessageBox.Yes: + return self.busy = True + self.stop.clear() self._set_enabled(False) self.status_label.setText('正在准备恢复…') self.started.emit(name) - self.worker = ServiceWorker(lambda: recoverer( - request, source, progress=self.signals.progress.emit)) + def execute(): + action = lambda: recoverer(request, source, progress=self.signals.progress.emit) + if self.native_queue is None: return action() + from ..operation_queue import QueueCancelled + def restore(): + self.signals.progress.emit({'stage': 'queue_acquired'}) + return action() + try: + return self.native_queue.run(restore, stop=self.stop, waiting=lambda: self.signals.progress.emit( + {'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'})) + except QueueCancelled as error: + from ..verify_runner import VerifyResult + return VerifyResult('CANCELLED', stderr=str(error)) + self.worker = ServiceWorker(execute) self.worker.signals.succeeded.connect(lambda result: self._result(name, result)) self.worker.signals.failed.connect(lambda error: self._failed(name, error)) self.worker.signals.finished.connect(self._finished) @@ -95,6 +121,8 @@ class BackupRecoveryDialog(QDialog): def _progress(self, event): if isinstance(event, dict): + if event.get('stage') in ('waiting_native_slot', 'queue_acquired'): + self.cancel_queue_button.setEnabled(event['stage'] == 'waiting_native_slot') message = event.get('message') or event.get('detail') if message: self.status_label.setText(str(message)) @@ -115,6 +143,7 @@ class BackupRecoveryDialog(QDialog): def _finished(self): self.busy = False + self.cancel_queue_button.setEnabled(False) self._set_enabled(True) def reject(self): diff --git a/src/cbb_refresh_verify/ui/icdb_check_task.py b/src/cbb_refresh_verify/ui/icdb_check_task.py new file mode 100644 index 0000000..997e33e --- /dev/null +++ b/src/cbb_refresh_verify/ui/icdb_check_task.py @@ -0,0 +1,115 @@ +"""A check batch owns its snapshot and yields the native queue after each CBB.""" +from threading import Event +from PySide6.QtCore import QObject, QThreadPool, Signal +from .workers import ServiceWorker +from ..operation_queue import QueueCancelled +from ..verify_runner import VerifyResult, run_verify, write_batch_report +from ..icdb_maintenance import write_maintenance_report + + +class IcdbCheckTask(QObject): + event = Signal(object) + item_done = Signal(str, object) + finished = Signal(object) + + def __init__(self, requests, queue, report_root, *, verifier=None, path_lease=None, parent=None): + super().__init__(parent) + self.requests = tuple(requests) + self.queue, self.report_root = queue, report_root + self.path_lease = path_lease + self.verifier = verifier or (lambda req: run_verify(req, progress=self.event.emit, stop=self.stop)) + self.results = [] + self.stop = Event() + self.active = False + self.paused = False + self.invalidated = set() + self.ready_names = set() + self.running = False + self.report = None + self.report_error = '' + self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1) + + def start(self): + self.active = True + self._next() + + def cancel(self): + self.stop.set(); self.queue.wake() + if not self.running and self.active: self._next() + + def pause(self): + self.paused = True + + def invalidate(self, names): + self.invalidated.update(names) + + def update_statuses(self, statuses): + self.ready_names = (self.ready_names - statuses.keys()) | { + name for name, status in statuses.items() if status == 'READY'} + + def resume(self): + self.paused = False; self.queue.wake() + if not self.running and self.active: self._next() + + def _next(self): + if self.running or not self.active: return + if self.stop.is_set() or self.results and not self.results[-1].safe_to_continue: + self.results.extend(VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB') + for _ in self.requests[len(self.results):]) + if len(self.results) == len(self.requests): + self._report(); return + if self.paused: return + request = self.requests[len(self.results)] + def check(): + try: + def execute(): + if request.block_name in self.ready_names: + return VerifyResult('SKIPPED', stderr='工程已为 READY,跳过 ICDB 检查。') + if request.block_name in self.invalidated: + return VerifyResult('SKIPPED', stderr='目标已有后续管理操作,请重新检查。') + self.event.emit({'stage': 'icdb_check_start', 'block': request.block_name}) + return self.verifier(request) + return self.queue.run(execute, stop=self.stop, ready=lambda: not self.paused, + waiting=lambda: self.event.emit({'stage': 'waiting_native_slot', 'block': request.block_name, + 'detail': '已排队,等待当前原生操作结束'})) + except QueueCancelled as error: + return VerifyResult('CANCELLED', stderr=str(error)) + except Exception as error: + return VerifyResult('FAIL', stderr=str(error), safe_to_continue=False, + error_category='ICDB_INSPECTION_UNCONFIRMED') + self.running = True + self.worker = ServiceWorker(check) + self.worker.signals.succeeded.connect(self._record) + self.worker.signals.finished.connect(self._item_finished) + self.pool.start(self.worker) + + def _record(self, result): + name = self.requests[len(self.results)].block_name + self.results.append(result) + if result.status in ('CANCELLED', 'QUEUE_STOP'): self.stop.set() + self.item_done.emit(name, result) + + def _item_finished(self): + self.running = False + self._next() + + def _report(self): + self.running = True + def write(): + try: + report = write_batch_report(self.requests, self.results, self.report_root) + write_maintenance_report(self.requests, self.results, report, ()) + return report, '' + except Exception as error: + return None, str(error) + self.worker = ServiceWorker(write) + self.worker.signals.succeeded.connect(self._report_ready) + self.worker.signals.finished.connect(self._complete) + self.pool.start(self.worker) + + def _report_ready(self, payload): + self.report, self.report_error = payload + + def _complete(self): + self.running = self.active = False + self.finished.emit(self) diff --git a/src/cbb_refresh_verify/ui/main_window.py b/src/cbb_refresh_verify/ui/main_window.py index 3aaad5d..e9f3178 100644 --- a/src/cbb_refresh_verify/ui/main_window.py +++ b/src/cbb_refresh_verify/ui/main_window.py @@ -1,572 +1,1575 @@ -from pathlib import Path -from threading import Event -import os -import time -from collections import Counter - -from PySide6.QtCore import QObject, QThreadPool, Signal, Qt -from PySide6.QtGui import QColor, QIcon -from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout, - QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton, - QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QGroupBox, QVBoxLayout, QProgressBar) -from PySide6.QtWidgets import QStyle -try: - from dx_productivity.trial_task_center.ui.workers import ServiceWorker -except ImportError: - from cbb_refresh_verify.ui.workers import ServiceWorker -from cbb_refresh_verify.library_reader import read_library_fast, scan_open_library_status -from cbb_refresh_verify.batch_status import authoritative_status_map -from cbb_refresh_verify.defaults import DEFAULT_TIMEOUT_SECONDS -from cbb_refresh_verify.network_path import LibraryPathLease, select_library_file -from cbb_refresh_verify.verify_runner import (VerifyRequest, preflight_skip_reason, run_verify, - run_batch, write_batch_report, failure_report_path, - native_lm_verify_enabled) - - -class ProgressSignals(QObject): - event = Signal(object) - - -STATUS_LABELS = { - 'READY': '绿色 / Ready', - 'PENDING': '待校验', - 'UNKNOWN': '未知 / 需确认', - 'UNAVAILABLE': '状态桥不可用', - 'ERROR': '状态读取失败', - 'TIMEOUT': '状态读取超时', - 'MALFORMED': '状态桥协议错误', - 'CRASHED': '状态桥崩溃', -} - - -def application_icon_path(): - return Path(__file__).resolve().parents[1] / 'assets' / 'cbb_refresh_verify.ico' - - -class MainWindow(QWidget): - def __init__(self, reader=None, verifier=None, logging_context=None, data_root=None, - authoritative_status=True, path_lease_factory=None): - super().__init__() - self.setWindowTitle('CBB 刷新校验') - icon_path = application_icon_path() - if icon_path.is_file(): - self.setWindowIcon(QIcon(str(icon_path))) - self.resize(850, 560) - self.verifier = verifier - self.logging_context = logging_context - self.path_lease_factory = path_lease_factory or LibraryPathLease.acquire - self.library_lease = None - self.mentor_lmc_path = None - self.data_root = Path(data_root or (logging_context.root if logging_context else Path(os.environ.get('LOCALAPPDATA', '.'))/'CbbRefreshVerify')) - if reader is not None: - self.reader = reader - elif authoritative_status and os.environ.get('CBB_STATUS_BRIDGE_MODE', 'authoritative').casefold() != 'legacy': - self.reader = lambda path: read_library_fast( - path, - status_reader=lambda p, names: authoritative_status_map( - names, p, self.data_root / 'status-scan.jsonl'), - ) - else: - # Legacy icon/filesystem reader remains opt-in until the bridge is - # accepted on the target Mentor installation. It cannot override - # the authoritative path when that path is enabled explicitly. - self.reader = lambda path: read_library_fast( - path, - status_reader=lambda p, names: scan_open_library_status( - p, names, mapping_store=self.data_root/'image-status-map.json'), - ) - self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1) - self.busy = False; self.loaded_path = None; self.stop = Event(); self.ready_names = set() - self._row_by_name = {} - self.skipped_names = set(); self.skip_reasons = {} - self._global_icdb_run = False - self._icdb_completed = 0 - self.signals = ProgressSignals(self); self.signals.event.connect(self._progress) - self.lmc_edit = QLineEdit() - self.libspec_edit = QLineEdit(os.environ.get('CBB_LIBSPEC', 'EE7.9')) - self.dms_edit = QLineEdit(os.environ.get('CBB_DMS_LOGIN_CONFIG', '')) - self.mentor_bin_edit = QLineEdit(os.environ.get('SDD_LM_BIN', '')) - self.native_lm_verify_check = QCheckBox('使用 Library Manager 原生 Verify(Win10 兼容测试)') - self.native_lm_verify_check.setChecked(native_lm_verify_enabled()) - self.native_lm_verify_check.setToolTip( - '仅在 Win10 兼容测试时启用;默认仍使用已验证的 ReusableCircuit 直接流程。') - self.advanced_toggle = QToolButton(); self.advanced_toggle.setText('高级设置') - self.advanced_toggle.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TitleBarUnshadeButton)) - self.advanced_toggle.setCheckable(True); self.advanced_toggle.setChecked(False) - self.advanced_panel = QWidget() - advanced_layout = QFormLayout(self.advanced_panel) - advanced_layout.addRow('LibSpec', self.libspec_edit) - advanced_layout.addRow('DMS 登录配置', self.dms_edit) - advanced_layout.addRow('Mentor bin', self.mentor_bin_edit) - advanced_layout.addRow('触发方式', self.native_lm_verify_check) - self.advanced_panel.setVisible(False) - self.advanced_toggle.toggled.connect(self.advanced_panel.setVisible) - self.cbb_table = QTableWidget(0, 4) - self.cbb_table.setHorizontalHeaderLabels(['CBB 名称', '分区', '状态', '环境检查']) - self.cbb_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch) - for column in (1, 2, 3): - self.cbb_table.horizontalHeader().setSectionResizeMode(column, QHeaderView.ResizeToContents) - self.cbb_table.setSelectionBehavior(QTableWidget.SelectRows) - self.cbb_table.setMinimumHeight(150) - self.cbb_table.itemChanged.connect(lambda _item: self._update()) - self.timeout_spin = QSpinBox(); self.timeout_spin.setRange(30, 1800); self.timeout_spin.setValue(DEFAULT_TIMEOUT_SECONDS); self.timeout_spin.setSuffix(' 秒 / 无进展') - self.load_button = QPushButton('读取 CBB'); self.load_button.clicked.connect(self.load_library) - self.browse_button = QPushButton('选择'); self.browse_button.clicked.connect(self.choose_library) - self.selected_batch_button = QPushButton('批量校验已选'); self.selected_batch_button.clicked.connect(self.verify_selected) - self.batch_button = QPushButton('批量校验全部 CBB'); self.batch_button.clicked.connect(self.verify_all) - self.icdb_repair_button = QPushButton('全库 ICDB 检查与修复'); self.icdb_repair_button.clicked.connect(self.repair_icdb_all) - self.icdb_repair_button.setToolTip('重新检查所有可用 CBB,包含 Ready 项;确认工程数据库失联后备份并尝试原生修复。') - self.backup_restore_button = QPushButton('从备份恢复 CBB…') - self.backup_restore_button.clicked.connect(self.restore_backup) - self.stop_button = QPushButton('当前项完成后停止'); self.stop_button.clicked.connect(self.request_stop) - self.logs_button = QPushButton('打开日志目录'); self.logs_button.clicked.connect(self.open_logs) - self.recovery_button = QPushButton('打开异常证据'); self.recovery_button.setEnabled(False) - style = self.style() - self.load_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_BrowserReload)) - self.browse_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon)) - self.selected_batch_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_ArrowRight)) - self.batch_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MediaPlay)) - self.icdb_repair_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_BrowserReload)) - self.stop_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MediaStop)) - self.logs_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon)) - self.recovery_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MessageBoxWarning)) - self.recovery_button.setToolTip('打开当前异常 CBB 的证据目录,不切换 Windows 桌面。') - self.recovery_button.clicked.connect(self.recover) - self.recovery_path = None - self.status_label = QLabel('请选择并读取中心库。校验期间可以使用其他前台应用。') - self.status_label.setWordWrap(True) - self.status_label.setMinimumHeight(self.status_label.fontMetrics().lineSpacing()*2) - self.output = QTextEdit(); self.output.setReadOnly(True) - # Integration emits repeated status snapshots. Keep the visible - # diagnostic buffer bounded so a 3,000-CBB run cannot grow the GUI - # document without limit. - self.output.document().setMaximumBlockCount(2000) - layout = QFormLayout(self) - row = QHBoxLayout(); row.addWidget(self.lmc_edit); row.addWidget(self.browse_button); row.addWidget(self.load_button) - layout.addRow('中心库 .lmc', row); layout.addRow(self.advanced_toggle); layout.addRow(self.advanced_panel) - layout.addRow('CBB 清单(勾选后可批量)', self.cbb_table); layout.addRow('超时', self.timeout_spin) - layout.addRow(QLabel('逐个刷新:命令行启动 ReusableCircuit PCB → Project Integration → 保存并关闭,全程不切换桌面、不移动鼠标。' - '填写 LibSpec 与 DMS 登录配置后,会先执行一次 ReuseBlockImporter 内容检查。')) - controls = QHBoxLayout() - for widget in (self.selected_batch_button, self.batch_button, self.stop_button, self.logs_button): controls.addWidget(widget) - layout.addRow(controls) - maintenance = QGroupBox('数据库维护') - maintenance_layout = QVBoxLayout(maintenance) - maintenance_row = QHBoxLayout() - maintenance_row.addWidget(self.icdb_repair_button) - description = QLabel('包含 Ready 项,逐个重新校验。确认工程数据库失联后,先备份再修复。\n共享符号库需另行处理;无法确认会话安全时停止。') - description.setWordWrap(True) - maintenance_row.addWidget(description, 1) - maintenance_layout.addLayout(maintenance_row) - maintenance_layout.addWidget(self.backup_restore_button) - self.icdb_progress = QProgressBar() - self.icdb_progress.setVisible(False) - self.icdb_phase = QLabel('') - self.icdb_phase.setWordWrap(True) - self.icdb_phase.setVisible(False) - maintenance_layout.addWidget(self.icdb_progress) - maintenance_layout.addWidget(self.icdb_phase) - layout.addRow(maintenance) - layout.addRow(self.status_label); layout.addRow(self.output) - layout.addRow(self.recovery_button) - self.lmc_edit.textChanged.connect(self._invalidate) - for field in (self.libspec_edit, self.dms_edit, self.mentor_bin_edit): - field.textChanged.connect(lambda _text: self._update()) - self.native_lm_verify_check.toggled.connect(lambda _checked: self._update()) - self._update() - - def _invalidate(self): - if self.loaded_path is not None and self.lmc_edit.text() != self.loaded_path: - self._release_library_lease() - self.loaded_path = None; self.mentor_lmc_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {} - self.ready_names = set(); self.skipped_names = set(); self.skip_reasons = {}; self._update() - self._global_icdb_run = False - self.icdb_progress.hide(); self.icdb_phase.hide() - - def _release_library_lease(self): - lease, self.library_lease = self.library_lease, None - if lease is None: - return - try: - lease.close() - except Exception as error: - if self.logging_context: - self.logging_context.logger.warning('library_lease_release_failed error=%s', error) - - def _update(self): - # The refresh flow needs only the library and a CBB; LibSpec/DMS config - # are optional and only enable the extra contents check. - ready = not self.busy and self.loaded_path == self.lmc_edit.text() and self.cbb_table.rowCount() > 0 - self.batch_button.setEnabled(ready and any(self.cbb_table.item(row, 0).text() not in self.ready_names - and self.cbb_table.item(row, 0).text() not in self.skipped_names - for row in range(self.cbb_table.rowCount()))) - self.selected_batch_button.setEnabled(ready and bool(self._selected_names())) - self.icdb_repair_button.setEnabled(ready and any( - self.cbb_table.item(row, 0).text() not in self.skipped_names - for row in range(self.cbb_table.rowCount()))) - self.backup_restore_button.setEnabled(ready) - for widget in (self.lmc_edit, self.browse_button, self.load_button, self.cbb_table, - self.timeout_spin, self.advanced_toggle, self.advanced_panel): - widget.setEnabled(not self.busy) - self.stop_button.setEnabled(self.busy and self.loaded_path is not None and not self.stop.is_set()) - - def choose_library(self): - path = QFileDialog.getOpenFileName(self, '选择中心库', '', 'LMC (*.lmc)')[0] - if path: self.lmc_edit.setText(path); self.load_library() - - def _start(self, action, callback): - self.busy = True; self._update() - self.worker = ServiceWorker(action) - self.worker.signals.succeeded.connect(callback) - self.worker.signals.failed.connect(self._failed) - self.worker.signals.finished.connect(self._finished) - self.pool.start(self.worker) - - def load_library(self): - if self.busy or not self.lmc_edit.text(): return - self._global_icdb_run = False - self.icdb_progress.hide(); self.icdb_phase.hide() - self._release_library_lease() - self.loaded_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}; self.ready_names = set() - self.skipped_names = set(); self.skip_reasons = {} - path = self.lmc_edit.text() - self.status_label.setText('正在读取中心库…') - def read(): - import pythoncom - started = time.monotonic() - if self.logging_context: - self.logging_context.logger.info('library_load_start path=%s', path) - pythoncom.CoInitialize() - try: - lease = self.path_lease_factory(Path(path)) - mentor_path = (select_library_file(lease.mentor_path) - if lease.mentor_path.is_dir() else lease.mentor_path) - if self.logging_context: - self.logging_context.logger.info( - 'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s', - lease.display_path, mentor_path, lease.drive or '-', - lease.remote_root or '-', lease.created) - result = self.reader(mentor_path) - if self.logging_context: - statuses = Counter(record.status for record in result.records) - unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}] - self.logging_context.logger.info( - 'library_scan_result records=%s elapsed_ms=%s statuses=%s unknown_sample=%s', - len(result.records), int((time.monotonic() - started) * 1000), - dict(statuses), unknown[:20]) - skip_reasons = {} - if not result.error: - for record in result.records: - reason = preflight_skip_reason(mentor_path, record.name) - if reason: - skip_reasons[record.name] = reason - return result, skip_reasons, lease, mentor_path - except Exception: - if 'lease' in locals(): - lease.close() - raise - finally: pythoncom.CoUninitialize() - def loaded(payload): - result, skip_reasons, lease, mentor_path = payload - if path != self.lmc_edit.text(): - lease.close() - return - if result.error: - lease.close() - self.status_label.setText(result.error); return - self.library_lease = lease - self.mentor_lmc_path = mentor_path - self.loaded_path = path - self.cbb_table.setRowCount(0) - self.ready_names = {r.name for r in result.records if r.status == 'READY' and r.name not in skip_reasons} - self.skip_reasons = dict(skip_reasons) - self.skipped_names = set(skip_reasons) - # Populating a large library emits itemChanged for every cell. - # Block those signals and refresh controls once after the batch; - # otherwise _update() repeatedly scans the growing table (O(n^2)). - self.cbb_table.blockSignals(True) - self.cbb_table.setUpdatesEnabled(False) - try: - self.cbb_table.setRowCount(len(result.records)) - for row, record in enumerate(result.records): - self._row_by_name[record.name] = row - item = QTableWidgetItem(record.name) - if record.status == 'READY' or record.name in self.skipped_names: - # Already green: nothing left to verify, so it cannot be queued. - item.setFlags(item.flags() & ~Qt.ItemIsUserCheckable) - else: - item.setFlags(item.flags() | Qt.ItemIsUserCheckable) - item.setCheckState(Qt.Unchecked) - self.cbb_table.setItem(row, 0, item) - self.cbb_table.setItem(row, 1, QTableWidgetItem(record.partition_name)) - status_text = STATUS_LABELS.get(record.status, record.status) - if record.name in self.skipped_names: - status_text = '跳过:缺少工程/PCB' - self.cbb_table.setItem(row, 2, QTableWidgetItem(status_text)) - # Preflight touches each CBB's project and was previously run - # synchronously in this GUI callback, making large libraries - # appear frozen. The verify worker performs it when queued. - self.cbb_table.setItem(row, 3, QTableWidgetItem('未检查')) - if record.status == 'READY' and record.name not in self.skipped_names: - self._mark_row_ready(row) - elif record.name in self.skipped_names: - self.cbb_table.item(row, 0).setToolTip(self.skip_reasons[record.name]) - self.cbb_table.item(row, 2).setToolTip(self.skip_reasons[record.name]) - self.cbb_table.item(row, 3).setText('跳过') - for column in range(self.cbb_table.columnCount()): - cell = self.cbb_table.item(row, column) - if cell is not None: - cell.setBackground(QColor('#FFF8E1')) - finally: - self.cbb_table.setUpdatesEnabled(True) - self.cbb_table.blockSignals(False) - ready_count = len(self.ready_names) - unavailable_count = sum(record.status == 'UNAVAILABLE' for record in result.records) - read_error_count = sum(record.status in {'ERROR', 'TIMEOUT', 'MALFORMED', 'CRASHED'} - for record in result.records) - suffix = '' - if unavailable_count: - suffix += f' 状态桥不可用 {unavailable_count} 个。' - if read_error_count: - suffix += f' 状态读取失败 {read_error_count} 个。' - self.status_label.setText( - f'已读取 {len(result.records)} 个 CBB,其中 Ready {ready_count} 个,' - f'缺文件跳过 {len(self.skipped_names)} 个。{suffix}') - self._start(read, loaded) - - def _request(self, name): - return VerifyRequest(Path(self.mentor_lmc_path or self.loaded_path), name, self.data_root/'evidence', - libspec=self.libspec_edit.text().strip(), - dms_login_config=self.dms_edit.text().strip(), - mentor_bin=self.mentor_bin_edit.text().strip(), - mapped_drive=getattr(self.library_lease, 'drive', ''), - mapped_remote_root=getattr(self.library_lease, 'remote_root', ''), - timeout_seconds=self.timeout_spin.value(), logging_context=self.logging_context, - native_lm_verify=self.native_lm_verify_check.isChecked()) - - def _selected_names(self): - names = [] - for row in range(self.cbb_table.rowCount()): - item = self.cbb_table.item(row, 0) - if item and item.checkState() == Qt.Checked and (item.flags() & Qt.ItemIsUserCheckable): - names.append(item.text()) - return names - - def verify_selected(self): - self._run(self._selected_names()) - - def verify_all(self): - names = [self.cbb_table.item(row, 0).text() for row in range(self.cbb_table.rowCount())] - self._run([name for name in names if name not in self.ready_names and name not in self.skipped_names]) - - def repair_icdb_all(self): - if self.busy or not self.loaded_path: return - names = [self.cbb_table.item(row, 0).text() for row in range(self.cbb_table.rowCount()) - if self.cbb_table.item(row, 0).text() not in self.skipped_names] - if not names: return - answer = QMessageBox.question(self, '全库 ICDB 检查与修复', - f'当前中心库:{self.loaded_path}\n\n' - f'将检查 {len(names)} 个 CBB,其中 Ready {len(self.ready_names)} 个;' - f'缺少工程文件跳过 {len(self.skipped_names)} 个。\n' - '操作会重新校验并保存工程。确认失联问题后,完整备份目标工程并尝试一次原生修复。\n' - '共享符号库不支持自动修复。若原生工具恢复了旧备份,需人工核对版本;' - '会话安全无法确认时停止队列。\n\n是否开始检查与修复?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) - if answer == QMessageBox.Yes: - self._run(names, include_ready=True) - - def restore_backup(self): - if self.busy or not self.loaded_path: - return - from .backup_recovery_dialog import BackupRecoveryDialog - names = [self.cbb_table.item(row, 0).text() for row in range(self.cbb_table.rowCount())] - if not names: - return - self.backup_dialog = BackupRecoveryDialog(names, self._request, self) - row = self.cbb_table.currentRow() - if row >= 0: - self.backup_dialog.block_combo.setCurrentText(self.cbb_table.item(row, 0).text()) - self.backup_dialog.started.connect(self._backup_started) - self.backup_dialog.completed.connect(self._backup_completed) - self.backup_dialog.finished.connect(lambda _code: self._finished()) - self.backup_dialog.setModal(True) - self.backup_dialog.show() - - def _backup_started(self, name): - self.busy = True - self._global_icdb_run = False - self.ready_names.discard(name) - row = self._row_by_name.get(name) - if row is not None: - self.cbb_table.item(row, 2).setText('恢复中 / 需确认') - self.cbb_table.item(row, 0).setFlags( - self.cbb_table.item(row, 0).flags() | Qt.ItemIsUserCheckable) - for column in range(self.cbb_table.columnCount()): - self.cbb_table.item(row, column).setBackground(QColor('#FFF8E1')) - self._update() - self.stop_button.setEnabled(False) - - def _backup_completed(self, name, result): - if not result.safe_to_continue and self.library_lease is not None: - self.library_lease.retain_for_recovery() - row = self._row_by_name.get(name) - if row is not None and result.status != 'PASS': - self.cbb_table.item(row, 2).setText('未知 / 需确认') - self._progress({'block': name, 'stage': result.status, 'detail': result.stderr, - 'evidence': str(result.evidence_path or '')}) - - def _run(self, names, *, include_ready=False): - if self.busy or not self.loaded_path: return - names = [name for name in names if (include_ready or name not in self.ready_names) and name not in self.skipped_names] - if not names: - self.status_label.setText('没有需要校验的 CBB(全部已经是绿色 / Ready)。') - self._update() - return - requests = [self._request(name) for name in names] - self._global_icdb_run = include_ready - self._icdb_completed = 0 - self.icdb_progress.setVisible(include_ready) - self.icdb_phase.setVisible(include_ready) - if include_ready: - self.icdb_progress.setRange(0, len(requests)) - self.icdb_progress.setValue(0) - self.icdb_progress.setFormat('已处理 %v / %m 个 CBB') - self.icdb_phase.setText('准备检查…') - self.stop.clear(); self.recovery_path = None; self.recovery_button.setEnabled(False) - self.output.clear(); self.status_label.setText( - f'正在全库 ICDB 检查与修复:共 {len(names)} 个 CBB' if include_ready - else f'正在校验:共 {len(names)} 个 CBB') - def action(): - from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify - verify = self.verifier or (lambda req: run_verify( - req, progress=lambda e: self.signals.event.emit(e), - flag_reader=read_library_flag_if_available)) - def verifier(req): - if include_ready: - self.signals.event.emit({'block': req.block_name, 'stage': 'icdb_check_start'}) - return verify(req) - results = run_batch(requests, verifier=verifier, stop=self.stop, - progress=lambda name, result: self.signals.event.emit({'block': name, 'stage': result.status, 'detail': result.stderr, 'evidence': str(result.evidence_path or '')})) - report = write_batch_report(requests, results, self.data_root/'reports') - if include_ready: - from cbb_refresh_verify.icdb_maintenance import write_maintenance_report - write_maintenance_report(requests, results, report, self.skipped_names) - return results, report - self._start(action, self._batch_done) - - def _progress(self, event): - line = f"{event.get('block', '')} | {event.get('stage', '')}" - for key in ('detail', 'error', 'action', 'statuses', 'evidence'): - if event.get(key): line += f' | {event[key]}' - self.output.append(line) - block = event.get('block'); stage = event.get('stage') - if self._global_icdb_run: - if stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED', 'QUEUE_STOP'}: - self._icdb_completed += 1 - self.icdb_progress.setValue(self._icdb_completed) - phases = {'icdb_check_start': '检查工程数据库与校验状态', - 'native_repair_start': '准备完整备份与原生修复', - 'complete_backup_verified': '完整备份已校验', - 'native_repair_requested': '正在原生修复', - 'native_repair_confirmed': '正在原生修复', - 'native_repair_finished': '原生修复已结束,正在核对结果'} - if stage in phases: - self.icdb_phase.setText(f'{block or ""} · {phases[stage]}') - if block and stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED'}: - row = self._row_by_name.get(block) - if row is not None: - if stage == 'PASS': - self.cbb_table.item(row, 2).setText('绿色 / Ready') - self.cbb_table.item(row, 3).setText('PASS') - self.ready_names.add(block) - self._mark_row_ready(row) - else: - if getattr(self, '_global_icdb_run', False) and stage != 'SKIPPED': - self.ready_names.discard(block) - self.cbb_table.item(row, 2).setText('未知 / 需确认') - item = self.cbb_table.item(row, 0) - item.setFlags(item.flags() | Qt.ItemIsUserCheckable) - for column in range(self.cbb_table.columnCount()): - self.cbb_table.item(row, column).setBackground(QColor('#FFF8E1')) - detail = str(event.get('detail') or event.get('error') or '').strip() - label = str(stage) if not detail else f'{stage}: {detail[:96]}' - self.cbb_table.item(row, 3).setText(label) - if detail: - self.cbb_table.item(row, 3).setToolTip(detail) - if self.logging_context: self.logging_context.logger.info('cbb_progress %s', line) - - def _mark_row_ready(self, row): - """Make a verified row visibly complete and remove it from the queue.""" - name_item = self.cbb_table.item(row, 0) - if name_item is None: - return - name_item.setCheckState(Qt.Unchecked) - name_item.setFlags(name_item.flags() & ~Qt.ItemIsUserCheckable) - for column in range(self.cbb_table.columnCount()): - cell = self.cbb_table.item(row, column) - if cell is not None: - cell.setBackground(QColor('#E8F5E9')) - - def _batch_done(self, outcome): - results, report = outcome - if self.library_lease is not None and any(not result.safe_to_continue for result in results): - self.library_lease.retain_for_recovery() - for result in results: - if not result.safe_to_continue and result.evidence_path: - self.recovery_path = result.evidence_path.parent - self.recovery_button.setEnabled(self.recovery_path.is_dir()) - passed = sum(r.status == 'PASS' for r in results) - skipped = sum(r.status == 'SKIPPED' for r in results) - failed = len(results)-passed-skipped - text = (f'已结束:成功 {passed},失败 {failed},预检跳过 {len(self.skipped_names)},' - f'队列未执行 {skipped}。\n完整日志:{report}\n仅失败日志:{failure_report_path(report)}') - if self._global_icdb_run: - from cbb_refresh_verify.icdb_maintenance import maintenance_counts - counts = maintenance_counts(results) - text = ('全库 ICDB 检查已结束\n' - f'校验通过 {passed},失败/受阻 {failed},队列未执行 {skipped},预检跳过 {len(self.skipped_names)}\n' - f'原生修复完成 {counts["repaired"]},恢复备份待复核 {counts["review_required"]},' - f'修复未确认 {counts["repair_unconfirmed"]}\n' - f'完整日志:{report}\n仅失败日志:{failure_report_path(report)}') - self.icdb_phase.setText('已停止,存在待处理项目' if failed or skipped else '已完成全库检查') - if any(not result.safe_to_continue for result in results): - text += '\n未确认数据库或会话安全,已停止剩余校验。请查看恢复现场。' - status_text = text - if self._global_icdb_run: - status_text = (f'全库检查结束:通过 {passed},失败/受阻 {failed},未执行 {skipped}。\n' - f'原生修复 {counts["repaired"]},恢复备份待复核 {counts["review_required"]},' - f'修复未确认 {counts["repair_unconfirmed"]}。') - self.status_label.setText(status_text); self.output.append(text) - self.summary = QMessageBox(self) - self.summary.setWindowTitle('全库 ICDB 检查与修复结果' if self._global_icdb_run else 'CBB 校验结果'); self.summary.setText(text) - self.summary.setIcon(QMessageBox.Warning if failed else QMessageBox.Information) - # Modeless notification: do not force activation or steal keyboard focus. - from PySide6.QtCore import Qt - self.summary.setAttribute(Qt.WA_ShowWithoutActivating) - self.summary.show() - - def request_stop(self): - self.stop.set(); self.status_label.setText('已请求停止;当前 CBB 完成或超时后停止队列。'); self._update() - - def _failed(self, error): - if self.library_lease is not None: - self.library_lease.retain_for_recovery() - self.status_label.setText(str(error)); self.output.append(str(error)) - if self.logging_context: self.logging_context.logger.error('cbb_worker_failed %s', error) - - def _finished(self): - self.busy = False; self._update() - - def open_logs(self): - self.data_root.mkdir(parents=True, exist_ok=True); os.startfile(str(self.data_root)) - - def recover(self): - if not self.recovery_path: return - try: os.startfile(str(self.recovery_path)) - except Exception as error: self._failed(error) - - def closeEvent(self, event): - if self.busy: - self.request_stop(); event.ignore() - else: - self._release_library_lease() - event.accept() +from pathlib import Path +from threading import Event +import os +import ntpath +import time +from collections import Counter +from dataclasses import replace + +from PySide6.QtCore import QObject, QThreadPool, Signal, Qt, QTimer +from PySide6.QtGui import QColor, QIcon +from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout, + QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton, + QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QVBoxLayout, QProgressBar, QComboBox, + QTabBar, QStackedWidget, QSizePolicy) +from PySide6.QtWidgets import QStyle + + +def _path_key(value): + """Compare local and unavailable UNC paths without touching the network.""" + raw = str(value or '') + if not raw: + return '' + return os.path.normcase(os.path.normpath(os.path.abspath(raw))) + + +def _library_path_keys(value, lease=None): + """Use known mapping aliases without resolving unavailable network paths.""" + if not value: + return set() + keys = {_path_key(value)} + mentor = getattr(lease, 'mentor_path', None) + display = getattr(lease, 'display_path', None) + if mentor and display: + for source, alias in ((mentor, display), (display, mentor)): + if _path_key(value) == _path_key(source): + keys.add(_path_key(alias)) + elif _path_key(Path(value).parent) == _path_key(source): + keys.add(_path_key(Path(alias)/Path(value).name)) + drive, tail = ntpath.splitdrive(str(value)) + if (getattr(lease, 'remote_root', '') and drive + and drive.upper() == getattr(lease, 'drive', '').upper()): + keys.add(_path_key(lease.remote_root + tail)) + return keys +try: + from dx_productivity.trial_task_center.ui.workers import ServiceWorker +except ImportError: + from cbb_refresh_verify.ui.workers import ServiceWorker +from cbb_refresh_verify.library_reader import read_library_fast, scan_open_library_status +from cbb_refresh_verify.batch_status import authoritative_status_map +from cbb_refresh_verify.defaults import DEFAULT_TIMEOUT_SECONDS +from cbb_refresh_verify.network_path import LibraryPathLease, select_library_file +from cbb_refresh_verify.verify_runner import (VerifyRequest, preflight_skip_reason, run_verify, + run_batch, write_batch_report, failure_report_path, + native_lm_verify_enabled) + + +class ProgressSignals(QObject): + event = Signal(object) + version_choice = Signal(object) + + +STATUS_LABELS = { + 'READY': '绿色 / Ready', + 'PENDING': '待校验', + 'UNKNOWN': '未知 / 需确认', + 'UNAVAILABLE': '状态桥不可用', + 'ERROR': '状态读取失败', + 'TIMEOUT': '状态读取超时', + 'MALFORMED': '状态桥协议错误', + 'CRASHED': '状态桥崩溃', +} + + +def application_icon_path(): + return Path(__file__).resolve().parents[1] / 'assets' / 'cbb_refresh_verify.ico' + + +class MainWindow(QWidget): + def __init__(self, reader=None, verifier=None, logging_context=None, data_root=None, + authoritative_status=True, path_lease_factory=None, status_refresher=None, + management_adapter=None, native_backup_launcher=None): + super().__init__() + self.setWindowTitle('CBB 刷新校验') + icon_path = application_icon_path() + if icon_path.is_file(): + self.setWindowIcon(QIcon(str(icon_path))) + self.resize(850, 560) + self.verifier = verifier + self.logging_context = logging_context + self.path_lease_factory = path_lease_factory or LibraryPathLease.acquire + self.library_lease = None + self.mentor_lmc_path = None + self.data_root = Path(data_root or (logging_context.root if logging_context else Path(os.environ.get('LOCALAPPDATA', '.'))/'CbbRefreshVerify')) + from cbb_refresh_verify.native_management import NativeManagementAdapter + self.management_adapter = management_adapter or NativeManagementAdapter() + self.management_capabilities = self.management_adapter.capabilities() + self._management_unsafe = False + self._management_unsafe_library = None + self._management_unsafe_libraries = set() + self._management_operation_library = None + self._maintenance_recovery_view = False + self._reload_after_maintenance = False + self._reimport_offers = () + self._batch_requests = () + self._batch_records = {} + self._reimport_summary_action = None + self.native_backup_launcher = native_backup_launcher + self._native_backup_session = None + self.native_backup_timer = QTimer(self) + self.native_backup_timer.setInterval(400) + self.native_backup_timer.timeout.connect(self._poll_native_backup) + if reader is not None: + self.reader = reader + elif authoritative_status and os.environ.get('CBB_STATUS_BRIDGE_MODE', 'authoritative').casefold() != 'legacy': + self.reader = lambda path: read_library_fast( + path, + status_reader=lambda p, names: authoritative_status_map( + names, p, self.data_root / 'status-scan.jsonl'), + ) + else: + # Legacy icon/filesystem reader remains opt-in until the bridge is + # accepted on the target Mentor installation. It cannot override + # the authoritative path when that path is enabled explicitly. + self.reader = lambda path: read_library_fast( + path, + status_reader=lambda p, names: scan_open_library_status( + p, names, mapping_store=self.data_root/'image-status-map.json'), + ) + self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1) + self._lease_pending = 0 + self._lease_workers = set() + self._mapping_busy = 0 + self._mapping_auto_idle = False + self._mapping_finish_waiters = [] + self._closing = self._close_ready = False + from cbb_refresh_verify.operation_queue import NativeQueue + self.native_queue = NativeQueue() + self.icdb_task = None + self.icdb_tasks = [] + self.busy = False; self.loaded_path = None; self.stop = Event(); self.ready_names = set() + self._row_by_name = {} + self._records_by_name = {} + self.status_refresher = status_refresher or (lambda names, path: authoritative_status_map( + names, path, self.data_root / 'status-refresh.jsonl')) + self.skipped_names = set(); self.skip_reasons = {} + self._global_icdb_run = False + self._icdb_completed = 0 + self.signals = ProgressSignals(self); self.signals.event.connect(self._progress) + self.signals.version_choice.connect(self._show_version_choice) + self.version_dialog = None + self.lmc_edit = QLineEdit() + self.libspec_edit = QLineEdit(os.environ.get('CBB_LIBSPEC', 'EE7.9')) + self.dms_edit = QLineEdit(os.environ.get('CBB_DMS_LOGIN_CONFIG', '')) + self.mentor_bin_edit = QLineEdit(os.environ.get('SDD_LM_BIN', '')) + self.native_lm_verify_check = QCheckBox('使用 Library Manager 原生 Verify(Win10 兼容测试)') + self.native_lm_verify_check.setChecked(native_lm_verify_enabled()) + self.native_lm_verify_check.setToolTip( + '仅在 Win10 兼容测试时启用;默认仍使用已验证的 ReusableCircuit 直接流程。') + self.advanced_toggle = QToolButton(); self.advanced_toggle.setText('高级设置') + self.advanced_toggle.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TitleBarUnshadeButton)) + self.advanced_toggle.setCheckable(True); self.advanced_toggle.setChecked(False) + self.advanced_panel = QWidget() + advanced_layout = QFormLayout(self.advanced_panel) + advanced_layout.addRow('LibSpec', self.libspec_edit) + advanced_layout.addRow('DMS 登录配置', self.dms_edit) + advanced_layout.addRow('Mentor bin', self.mentor_bin_edit) + advanced_layout.addRow('触发方式', self.native_lm_verify_check) + self.advanced_panel.setVisible(False) + self.advanced_toggle.toggled.connect(self.advanced_panel.setVisible) + self.cbb_table = QTableWidget(0, 4) + self.cbb_table.setHorizontalHeaderLabels(['CBB 名称', '分区', '状态', '备注']) + self.cbb_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch) + self.cbb_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch) + for column in (1, 2): + self.cbb_table.horizontalHeader().setSectionResizeMode(column, QHeaderView.ResizeToContents) + self.cbb_table.setSelectionBehavior(QTableWidget.SelectRows) + self.cbb_table.setMinimumHeight(150) + self.cbb_table.itemChanged.connect(lambda _item: self._update()) + self.search_edit = QLineEdit() + self.search_edit.setPlaceholderText('按 CBB 名称或分区搜索') + self.status_filter = QComboBox() + for label, key in (('全部', 'all'), ('READY', 'ready'), ('非 READY(含未确认)', 'non_ready'), + ('PENDING', 'pending'), ('未知 / 读取异常', 'errors'), ('缺少工程', 'missing')): + self.status_filter.addItem(label, key) + self.counts_label = QLabel() + self.select_visible_button = QPushButton('选择可见项') + self.clear_selection_button = QPushButton('清空选择') + self.select_visible_button.clicked.connect(lambda: self._check_visible(Qt.Checked)) + self.clear_selection_button.clicked.connect(lambda: self._check_visible(Qt.Unchecked)) + self.search_edit.textChanged.connect(self._apply_filters) + self.status_filter.currentIndexChanged.connect(self._apply_filters) + self.timeout_spin = QSpinBox(); self.timeout_spin.setRange(30, 1800); self.timeout_spin.setValue(DEFAULT_TIMEOUT_SECONDS); self.timeout_spin.setSuffix(' 秒 / 无进展') + self.load_button = QPushButton('读取 CBB'); self.load_button.clicked.connect(self.load_library) + self.browse_button = QPushButton('选择'); self.browse_button.clicked.connect(self.choose_library) + self.selected_batch_button = QPushButton('批量校验已选'); self.selected_batch_button.clicked.connect(self.verify_selected) + self.batch_button = QPushButton('校验可见非 READY'); self.batch_button.clicked.connect(self.verify_all) + self.icdb_repair_button = QPushButton('ICDB 批量检查'); self.icdb_repair_button.clicked.connect(self.repair_icdb_all) + self.icdb_repair_button.setToolTip('检查可见的非 READY 工程;有勾选时仅检查勾选项。') + self.backup_restore_button = QPushButton('从备份恢复 CBB…') + self.backup_restore_button.clicked.connect(self.restore_backup) + self.reimport_button = QPushButton('选择工程副本恢复失败项…') + self.reimport_button.clicked.connect(self.reimport_failed) + self.reimport_button.hide() + self.stop_button = QPushButton('当前项完成后停止'); self.stop_button.clicked.connect(self.request_stop) + self.logs_button = QPushButton('打开日志目录'); self.logs_button.clicked.connect(self.open_logs) + self.recovery_button = QPushButton('打开异常证据'); self.recovery_button.setEnabled(False) + style = self.style() + self.load_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_BrowserReload)) + self.browse_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon)) + self.selected_batch_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_ArrowRight)) + self.batch_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MediaPlay)) + self.icdb_repair_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_BrowserReload)) + self.stop_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MediaStop)) + self.logs_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_DirOpenIcon)) + self.recovery_button.setIcon(style.standardIcon(QStyle.StandardPixmap.SP_MessageBoxWarning)) + self.recovery_button.setToolTip('打开当前异常 CBB 的证据目录,不切换 Windows 桌面。') + self.recovery_button.clicked.connect(self.recover) + self.recovery_path = None + self.status_label = QLabel('请选择并读取中心库。校验期间可以使用其他前台应用。') + self.status_label.setWordWrap(True) + self.status_label.setMinimumHeight(self.status_label.fontMetrics().lineSpacing()*2) + self.status_label.setMaximumHeight(self.status_label.fontMetrics().lineSpacing()*3 + 4) + self.status_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) + self.output = QTextEdit(); self.output.setReadOnly(True) + # Integration emits repeated status snapshots. Keep the visible + # diagnostic buffer bounded so a 3,000-CBB run cannot grow the GUI + # document without limit. + self.output.document().setMaximumBlockCount(2000) + self.output.setMaximumHeight(180) + layout = QVBoxLayout(self) + row = QHBoxLayout(); row.addWidget(QLabel('中心库')); row.addWidget(self.lmc_edit) + row.addWidget(self.browse_button); row.addWidget(self.load_button) + layout.addLayout(row) + self.library_notice = QLabel() + self.library_notice.setWordWrap(True) + self.library_notice.setTextFormat(Qt.PlainText) + self.library_notice.setStyleSheet('QLabel { color: #8a4b08; background: #fff3d6; padding: 6px; }') + self.library_notice.hide() + layout.addWidget(self.library_notice) + self.section_tabs = QTabBar() + self.section_tabs.setExpanding(True) + for name in ('检验', 'ICDB 维护', '中心库管理'): + self.section_tabs.addTab(name) + layout.addWidget(self.section_tabs) + filters = QHBoxLayout() + for widget in (self.search_edit, self.status_filter, self.select_visible_button, self.clear_selection_button): + filters.addWidget(widget) + layout.addLayout(filters) + layout.addWidget(self.counts_label) + layout.addWidget(self.cbb_table, 1) + self.section_stack = QStackedWidget() + self.section_stack.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum) + self.section_tabs.currentChanged.connect(self.section_stack.setCurrentIndex) + verify_page = QWidget() + verify_layout = QVBoxLayout(verify_page); verify_layout.setContentsMargins(0, 0, 0, 0) + controls = QHBoxLayout() + for widget in (self.selected_batch_button, self.batch_button): controls.addWidget(widget) + controls.addStretch(); controls.addWidget(QLabel('超时')); controls.addWidget(self.timeout_spin) + controls.addWidget(self.advanced_toggle) + verify_layout.addLayout(controls); verify_layout.addWidget(self.advanced_panel) + self.section_stack.addWidget(verify_page) + maintenance = QWidget() + maintenance_layout = QVBoxLayout(maintenance) + maintenance_layout.setContentsMargins(0, 0, 0, 0) + self.native_backup_button = QPushButton('版本历史与备份…') + self.native_backup_button.setToolTip('勾选一个非 READY CBB,打开原生备份列表并选择回退版本。') + self.native_backup_button.clicked.connect(self.open_native_backup) + maintenance_layout.addWidget(self.native_backup_button) + maintenance_row = QHBoxLayout() + maintenance_row.addWidget(self.icdb_repair_button) + self.icdb_stop_button = QPushButton('停止检查') + self.icdb_stop_button.clicked.connect(self._stop_icdb_check) + maintenance_row.addWidget(self.icdb_stop_button) + maintenance_row.addWidget(self.backup_restore_button) + maintenance_row.addWidget(self.reimport_button) + maintenance_layout.addLayout(maintenance_row) + self.icdb_progress = QProgressBar() + self.icdb_progress.setVisible(False) + self.icdb_phase = QLabel('') + self.icdb_phase.setWordWrap(True) + self.icdb_phase.setVisible(False) + maintenance_layout.addWidget(self.icdb_progress) + maintenance_layout.addWidget(self.icdb_phase) + self.section_stack.addWidget(maintenance) + management = QWidget() + management_layout = QVBoxLayout(management) + management_layout.setContentsMargins(0, 0, 0, 0) + management_buttons = QHBoxLayout() + self.add_button = QPushButton('新增 CBB…') + self.update_button = QPushButton('用工程替换已选 CBB…') + self.remove_button = QPushButton('移除已选…') + for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)): + widget.clicked.connect(lambda _=False, op=operation: self.manage_cbb(op)) + widget.setToolTip(self.management_capabilities[operation].reason) + management_buttons.addWidget(widget) + management_layout.addLayout(management_buttons) + self.management_capability_label = QLabel() + self.management_capability_label.setWordWrap(True) + management_layout.insertWidget(0, self.management_capability_label) + self.unfinished_label = QLabel(); self.unfinished_label.setWordWrap(True) + management_layout.addWidget(self.unfinished_label) + self.release_library_button = QPushButton('释放残留会话…') + self.release_library_button.clicked.connect(self.check_library_release) + management_buttons.addWidget(self.release_library_button) + self.release_library_button.hide() + self.section_stack.addWidget(management) + layout.addWidget(self.section_stack) + layout.addWidget(self.status_label) + self.runtime_log_toggle = QToolButton(); self.runtime_log_toggle.setText('查看运行日志') + self.runtime_log_toggle.setCheckable(True) + self.runtime_log_toggle.toggled.connect(self.output.setVisible) + self.output.hide() + footer = QHBoxLayout() + for widget in (self.stop_button, self.runtime_log_toggle, self.logs_button, self.recovery_button): + footer.addWidget(widget) + layout.addLayout(footer); layout.addWidget(self.output) + self.lmc_edit.textChanged.connect(self._invalidate) + for field in (self.libspec_edit, self.dms_edit, self.mentor_bin_edit): + field.textChanged.connect(lambda _text: self._update()) + self.native_lm_verify_check.toggled.connect(lambda _checked: self._update()) + self._show_unfinished_management() + self._update() + + def _invalidate(self): + self._reimport_offers = () + if self.loaded_path is not None and self.lmc_edit.text() != self.loaded_path: + self._release_library_lease() + self.loaded_path = None; self.mentor_lmc_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {} + self._records_by_name = {} + self.ready_names = set(); self.skipped_names = set(); self.skip_reasons = {}; self._update() + self._global_icdb_run = False + if not self._icdb_active(): + self.icdb_progress.hide(); self.icdb_phase.hide() + + def _release_library_lease(self): + lease, self.library_lease = self.library_lease, None + if self._native_backup_session is not None and self._native_backup_session.path_lease is lease: + return # The visible native session still needs this mapping. + if self._icdb_active() and self.icdb_task.path_lease is lease: + return # This background task still uses its captured mapping. + if lease is None: + return + try: + self._close_path_lease(lease) + except Exception as error: + if self.logging_context: + self.logging_context.logger.warning('library_lease_release_failed error=%s', error) + + def _close_path_lease(self, lease): + self._lease_action(lease.close, hold_busy=self.busy) + + def _retain_path_lease(self, lease, *, hold_busy=False): + if lease is not None: + self._lease_action(lease.retain_for_recovery, hold_busy=hold_busy) + + def _lease_action(self, action, completed=None, failed=None, *, hold_busy=False): + # The serial pool orders retain before every subsequent close. + self._lease_pending += 1 + if hold_busy: + if not self._mapping_busy and not self.busy: + self._mapping_auto_idle = True + self._mapping_busy += 1 + self.busy = True + self._update() + worker = ServiceWorker(action) + self._lease_workers.add(worker) + if completed is not None: worker.signals.succeeded.connect(completed) + worker.signals.failed.connect(failed or self._display_error) + def finished(): + self._lease_workers.discard(worker) + self._lease_pending -= 1 + if hold_busy: self._mapping_busy -= 1 + if not self._mapping_busy: + callbacks, self._mapping_finish_waiters = self._mapping_finish_waiters, [] + auto_idle, self._mapping_auto_idle = self._mapping_auto_idle, False + for callback in callbacks: callback() + if auto_idle and not callbacks: self._finished() + self._update() + worker.signals.finished.connect(finished) + self.pool.start(worker) + + def _defer_mapping_finish(self, callback): + if not self._mapping_busy: return False + if callback not in self._mapping_finish_waiters: + self._mapping_finish_waiters.append(callback) + return True + + def _update(self): + # The refresh flow needs only the library and a CBB; LibSpec/DMS config + # are optional and only enable the extra contents check. + ready = not self.busy and self.loaded_path == self.lmc_edit.text() and self.cbb_table.rowCount() > 0 + selected = self.selected_records() + native_target = self._native_backup_target() + self.native_backup_button.setEnabled(ready and self._native_backup_session is None + and native_target is not None) + ready = ready and not self._native_backup_same_library() + self.batch_button.setEnabled(ready and bool(self._eligible_names())) + self.selected_batch_button.setEnabled(ready and bool(self._eligible_names(checked_only=True))) + self.icdb_repair_button.setEnabled(ready and not self._icdb_active() and bool(self._maintenance_names())) + self.icdb_stop_button.setEnabled(self._icdb_active() and not self.icdb_task.stop.is_set()) + self.backup_restore_button.setEnabled(ready and bool( + self._eligible_names(checked_only=bool(self.selected_records())))) + self.release_library_button.setEnabled(False) + reasons = [] + for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)): + reason = self._management_block_reason(operation) + widget.setEnabled(not reason) + widget.setToolTip(reason or self.management_capabilities[operation].reason) + if reason: + reasons.append(reason) + self.management_capability_label.setText('\n'.join(dict.fromkeys(reasons))) + current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None + notice = ('上次操作结果待复查,执行前将重新检查占用。' + if self._management_library_unsafe(current_library) else '') + self.library_notice.setText(notice) + self.library_notice.setVisible(bool(notice)) + for widget in (self.lmc_edit, self.browse_button, self.load_button, + self.timeout_spin, self.advanced_toggle, self.advanced_panel): + widget.setEnabled(not self.busy) + counts = self.visible_counts() + self.counts_label.setText(f'可见 {counts["visible"]} / {len(self._records_by_name)} · ' + f'READY {counts["ready"]} · 异常/待确认 {counts["error"]}') + self.stop_button.setEnabled((self.busy and self.loaded_path is not None and not self.stop.is_set()) + or self._icdb_active() and not self.icdb_task.stop.is_set()) + self.stop_button.setText('取消当前任务并停止队列') + available = bool(self._reimport_offers) and not self.busy and self.management_capabilities['update'].supported + self.reimport_button.setVisible(bool(self._reimport_offers)) + self.reimport_button.setEnabled(available) + self.reimport_button.setToolTip(self.management_capabilities['update'].reason) + if self._reimport_summary_action is not None: + self._reimport_summary_action.setEnabled(available) + if getattr(self, '_residual_release_action', None) is not None: + self._residual_release_action.setEnabled(not self.busy) + if getattr(self, '_resume_batch_action', None) is not None: + pending = getattr(self, '_resume_batch', None) + same = bool(pending and _library_path_keys(pending['library'], self.library_lease) + & _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)) + self._resume_batch_action.setEnabled(not self.busy and same and pending['released']) + + def _show_unfinished_management(self): + from cbb_refresh_verify.management import unfinished_operations + unfinished = unfinished_operations(self.data_root/'management') + self.unfinished_label.setText(f'发现 {len(unfinished)} 项未完成或需恢复的管理任务;只显示记录,不自动重放。' + if unfinished else '') + for item in unfinished: + self.output.append(f'未完成:{item.get("name", "")} {item.get("status", "")} ' + f'{item.get("stage", "")}\n{item["evidence_path"]}') + + def check_library_release(self): + return # Release entry arrives with the next review PR. + + def _release_dialog_finished(self, _=None): + if self._defer_mapping_finish(self._release_dialog_finished): return + self._finished() + pending = getattr(self, '_resume_batch', None) + if pending and pending['released']: + self.summary.setText('会话已释放,可以继续未执行项。') + self.summary.show() + + def _complete_library_release(self, library, result): + from cbb_refresh_verify.network_path import release_retained_path_leases + try: + if (not isinstance(result, dict) or result.get('status') != 'RELEASE_CONFIRMED' + or not (_library_path_keys(result.get('library'), self.library_lease) + & _library_path_keys(library, self.library_lease))): + raise ValueError('RELEASE_PROOF_UNCONFIRMED: 释放证明未确认或不属于当前中心库。') + except Exception as error: + self._failed(error) + return + lease = self.library_lease + def release(): + try: + release_retained_path_leases(result, current_lease=lease) + except Exception: + if lease is not None: lease.retain_for_recovery() + raise + self._lease_action(release, lambda _: self._library_release_ready(library, result), + self._display_error, hold_busy=True) + + def _library_release_ready(self, library, result): + current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text().strip()) + if current_library == _path_key(library): + self._management_unsafe = False + self._management_unsafe_library = None + self._management_unsafe_libraries.discard(_path_key(library)) + session = self._native_backup_session + if self._native_backup_matches_library(library) and session.process.poll() is not None: + self._release_native_backup_session(session) + pending = getattr(self, '_resume_batch', None) + if pending and (_library_path_keys(pending['library'], self.library_lease) + & _library_path_keys(library, self.library_lease)): + pending['released'] = True + message = f'相关会话已释放,可以重试未完成的项目。\n{result["evidence_path"]}' + self.status_label.setText(message); self.output.append(message) + + def _resume_released_batch(self): + pending = getattr(self, '_resume_batch', None) + if self.busy or not pending or not pending['released']: return + if not (_library_path_keys(pending['library'], self.library_lease) + & _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)): + return + self._resume_batch = None + self._run(pending['names'], maintenance=pending['maintenance']) + + def _management_library_unsafe(self, library): + if self._management_unsafe and self._management_unsafe_library is not None: + self._management_unsafe_libraries.add(_path_key(self._management_unsafe_library)) + return _path_key(library) in self._management_unsafe_libraries + + def _management_block_reason(self, operation): + if self.busy: + return '当前任务尚未结束,请等待后再执行库管理操作。' + if self._native_backup_same_library(): + return '该库的版本与备份窗口仍在使用,关闭后可执行写入操作。' + capability = self.management_capabilities[operation] + if not capability.supported: + return capability.reason + if not self.loaded_path or self.loaded_path != self.lmc_edit.text(): + return '请先选择并读取中心库。' + if operation != 'add' and not self.selected_records(): + return '替换和移除需要先勾选当前可见的 CBB。' + return '' + + def manage_cbb(self, operation): + reason = self._management_block_reason(operation) + if reason: + self.status_label.setText(reason) + return + from cbb_refresh_verify.management import ManagementRequest + records = self.selected_records() + if operation != 'add' and not records: + return + def request(name, partition): + return ManagementRequest(operation, Path(self.mentor_lmc_path or self.loaded_path), name, + partition, evidence_dir=self.data_root/'management', timeout_seconds=self.timeout_spin.value(), + mapped_drive=getattr(self.library_lease, 'drive', ''), + mapped_remote_root=getattr(self.library_lease, 'remote_root', '')) + requests = ([request('', 'Logical-Physical')] if operation == 'add' else + [request(record.name, 'Logical-Physical' if record.logical_type == 'LP' + and record.partition_name in ('Reusable Blocks', 'LP') else record.partition_name) + for record in records]) + self._open_management_dialog(requests) + + def _open_management_dialog(self, requests, *, recovery_from=None): + from .management_dialog import ManagementDialog + self._global_icdb_run = False + self.stop.clear() + self._management_is_recovery = bool(recovery_from) + self._management_operation_library = _path_key(requests[0].library) if requests else None + requests = [replace(request, check_previous_release=True) if self._management_library_unsafe(request.library) + else request for request in requests] + self.management_dialog = ManagementDialog(requests, self, adapter=self.management_adapter, + recovery_from=recovery_from) + self.management_dialog.native_queue = self.native_queue + self.management_dialog.before_execute.connect(lambda names: self._invalidate_check_targets(requests[0].library, names)) + self._management_results = [] + self.management_dialog.completed.connect(self._management_completed) + self.management_dialog.finished.connect(self._management_closed) + self.busy = True; self._update() + self.management_dialog.show() + + def reimport_failed(self): + if self.busy or not self._reimport_offers or not self.management_capabilities['update'].supported: + return + from cbb_refresh_verify.management import ManagementRequest + requests, previous = [], {} + library = Path(self.mentor_lmc_path or self.loaded_path) + for req, record, result in self._reimport_offers: + if req.lmc_file != library: + return + partition = ('Logical-Physical' if record.logical_type == 'LP' + and record.partition_name in ('Reusable Blocks', 'LP') else record.partition_name) + requests.append(ManagementRequest('update', library, record.name, partition, + evidence_dir=self.data_root/'management', timeout_seconds=self.timeout_spin.value(), + mapped_drive=getattr(self.library_lease, 'drive', ''), + mapped_remote_root=getattr(self.library_lease, 'remote_root', ''))) + previous[record.name] = str(result.evidence_path) + self._reload_after_maintenance = False + if getattr(self, 'summary', None): self.summary.close() + self._open_management_dialog(requests, recovery_from=previous) + + def _management_completed(self, results): + self._management_results = results + proofs = [result.release_proof for result in results if isinstance(getattr(result, 'release_proof', None), dict) + and result.release_proof.get('status') == 'RELEASE_CONFIRMED' + and bool(_library_path_keys(result.release_proof.get('library'), self.library_lease) + & _library_path_keys(self._management_operation_library, self.library_lease)) + ] + safe = all(result.safe_to_continue for result in results) + lease = self.library_lease + if proofs and safe: + from cbb_refresh_verify.network_path import release_retained_path_leases + def release(): + try: + release_retained_path_leases(proofs[-1], current_lease=lease) + except Exception: + if lease is not None: lease.retain_for_recovery() + raise + def failed(error): + self._management_unsafe = True + self._management_unsafe_library = self._management_operation_library + self._management_unsafe_libraries.add(_path_key(self._management_operation_library)) + self._display_error(error) + self._management_results_ready(results, proofs, False) + self._lease_action(release, lambda _: self._management_results_ready(results, proofs, True), + failed, hold_busy=True) + elif not safe and lease is not None: + self._lease_action(lease.retain_for_recovery, + lambda _: self._management_results_ready(results, proofs, True), + lambda error: (self._display_error(error), self._management_results_ready(results, proofs, False)), + hold_busy=True) + else: + self._management_results_ready(results, proofs, True) + + def _management_results_ready(self, results, proofs, mapping_released): + if (mapping_released and (getattr(self, '_management_is_recovery', False) or proofs) and results + and all(result.safe_to_continue for result in results)): + self._management_unsafe_libraries.discard(_path_key(self._management_operation_library)) + self._management_unsafe = False + self._management_unsafe_library = None + self._maintenance_recovery_view = False + restored = {result.name for result in results if result.status == 'UPLOADED_VERIFIED'} + self._reimport_offers = tuple(offer for offer in self._reimport_offers if offer[1].name not in restored) + from .management_dialog import RESULT_LABELS + for result in results: + self.output.append(f'{result.name}:{RESULT_LABELS.get(result.status, result.status)} ' + f'{result.detail}\n{result.evidence_path or ""}') + if self.logging_context: + self.logging_context.logger.info('management_result operation=%s block=%s status=%s safe=%s evidence=%s detail=%s', + result.operation, result.name, result.status, result.safe_to_continue, result.evidence_path, result.detail) + if getattr(self, '_management_is_recovery', False) and result.status == 'UPLOADED_VERIFIED': + self.output.append('副本恢复校验通过,版本待核对。') + if False: # Release entry arrives with the next review PR. + self._management_unsafe = True + self._management_unsafe_library = self._management_operation_library + self._management_unsafe_libraries.add(_path_key(self._management_operation_library)) + self.status_label.setText('管理操作需要人工确认恢复/释放;已停止写入,未再次读取原生目录。') + self._show_unfinished_management() + + def _management_closed(self, *_): + if self._defer_mapping_finish(self._management_closed): return + from PySide6.QtCore import QTimer + self.busy = False; self._update() + changed = any(result.status in {'REMOVED', 'UPLOADED', 'UPLOADED_VERIFIED', 'UPLOADED_VERIFY_FAILED', 'RECOVERY_REQUIRED'} + for result in self._management_results) + if changed and not self._management_library_unsafe(self.mentor_lmc_path or self.loaded_path): + # Whole catalog reload is necessary for inserted/deleted identities; + # existing local search/filter controls are intentionally retained. + QTimer.singleShot(0, self.load_library) + + def visible_records(self): + """Cached records in table order, restricted to the current local view.""" + return tuple(record for name, record in self._records_by_name.items() + if not self.cbb_table.isRowHidden(self._row_by_name[name])) + + def selected_records(self): + """Visible checked management records, including READY/missing projects.""" + return tuple(record for record in self.visible_records() + if self.cbb_table.item(self._row_by_name[record.name], 0).checkState() == Qt.Checked) + + def visible_counts(self): + records = self.visible_records() + return {'visible': len(records), 'ready': sum(r.status == 'READY' for r in records), + 'error': sum(r.status not in {'READY', 'PENDING'} or r.name in self.skipped_names + for r in records)} + + def _eligible_names(self, *, checked_only=False): + records = self.selected_records() if checked_only else self.visible_records() + return [r.name for r in records if r.status != 'READY' and r.name not in self.skipped_names] + + def _maintenance_names(self): + records = self.selected_records() or self.visible_records() + return [record.name for record in records + if record.status != 'READY' and record.name not in self.skipped_names] + + def _native_backup_target(self): + selected = self.selected_records() + if selected: + return selected[0] if len(selected) == 1 and selected[0].status != 'READY' else None + row = self.cbb_table.currentRow() + if row < 0 or self.cbb_table.isRowHidden(row): + return None + item = self.cbb_table.item(row, 0) + record = self._records_by_name.get(item.text()) if item is not None else None + return record if record is not None and record.status != 'READY' else None + + def _check_visible(self, state): + self.cbb_table.blockSignals(True) + try: + for record in self.visible_records(): + self.cbb_table.item(self._row_by_name[record.name], 0).setCheckState(state) + finally: + self.cbb_table.blockSignals(False) + self._update() + + def _apply_filters(self, *_): + keyword = self.search_edit.text().strip().casefold() + mode = self.status_filter.currentData() + self.cbb_table.blockSignals(True) + self.cbb_table.setUpdatesEnabled(False) + try: + for name, record in self._records_by_name.items(): + matches = (not keyword or keyword in record.name.casefold() + or keyword in record.partition_name.casefold()) + matches = matches and (mode == 'all' + or mode == 'ready' and record.status == 'READY' + or mode == 'non_ready' and record.status != 'READY' + or mode == 'pending' and record.status == 'PENDING' + or mode == 'errors' and record.status not in {'READY', 'PENDING'} + or mode == 'missing' and name in self.skipped_names) + row = self._row_by_name[name] + if not matches: + self.cbb_table.item(row, 0).setCheckState(Qt.Unchecked) + self.cbb_table.setRowHidden(row, not matches) + finally: + self.cbb_table.setUpdatesEnabled(True) + self.cbb_table.blockSignals(False) + self._update() + + def choose_library(self): + path = QFileDialog.getOpenFileName(self, '选择中心库', '', 'LMC (*.lmc)')[0] + if path: self.lmc_edit.setText(path); self.load_library() + + def _start(self, action, callback): + self.stop.clear() + self.busy = True; self._update() + self.worker = ServiceWorker(self._queued_action(action)) + self.worker.signals.succeeded.connect(callback) + self.worker.signals.failed.connect(self._failed) + self.worker.signals.finished.connect(self._finished) + self.pool.start(self.worker) + + def _queued_action(self, action): + return lambda: self.native_queue.run(action, stop=self.stop, + waiting=lambda: self.signals.event.emit({'stage': 'waiting_native_slot', + 'detail': '已排队,等待当前原生操作结束'})) + + def _icdb_active(self): + return self.icdb_task is not None and self.icdb_task.active + + def _check_matches_library(self, library): + return self._icdb_active() and bool(_library_path_keys(library, self.library_lease) + & _library_path_keys(self.icdb_task.requests[0].lmc_file, self.icdb_task.path_lease)) + + def _invalidate_check_targets(self, library, names): + names = set(names) + for task in self.icdb_tasks: + if not (_library_path_keys(library, self.library_lease) + & _library_path_keys(task.requests[0].lmc_file, task.path_lease)): continue + task.invalidate(names) + if hasattr(task, 'summary'): + prefix = '已更新的工程:'+', '.join(sorted(task.invalidated))+'。下列为此前检查记录。\n' + task.summary.setDetailedText(prefix+task.summary.detailedText()) + if names & getattr(task, 'recovery_names', set()): + task.recovery_action.setEnabled(False) + task.recovery_action.setToolTip('工程已有后续管理操作,请重新检查。') + self._reimport_offers = tuple(offer for offer in self._reimport_offers if offer[0].block_name not in names + or not (_library_path_keys(library, self.library_lease) & _library_path_keys(offer[0].lmc_file))) + + def _stop_icdb_check(self): + if self._icdb_active(): + self.icdb_task.cancel() + self.icdb_phase.setText('正在停止检查,等待本项退出…') + self._update() + + def _publish_check_statuses(self, library, statuses, lease=None): + for task in tuple(self.icdb_tasks): + if task.active and (_library_path_keys(library, lease or self.library_lease) + & _library_path_keys(task.requests[0].lmc_file, task.path_lease)): + task.update_statuses(statuses) + + def _start_icdb_check(self, names): + if self.busy or self._icdb_active() or not self.loaded_path or self._native_backup_same_library(): return + eligible = set(self._maintenance_names()) + names = [name for name in names if name in eligible] + if not names: return + from .icdb_check_task import IcdbCheckTask + requests = tuple(replace(self._request(name), maintenance=True, auto_repair=False) for name in names) + task = IcdbCheckTask(requests, self.native_queue, self.data_root/'reports', + verifier=self.verifier, path_lease=self.library_lease, parent=self) + task.records = {name: self._records_by_name[name] for name in names} + self.icdb_task = task + self.icdb_tasks.append(task) + task.event.connect(lambda event: self._icdb_event(task, event)) + task.item_done.connect(lambda name, result: self._icdb_item_done(task, name, result)) + task.finished.connect(self._icdb_done) + self.icdb_progress.setVisible(True); self.icdb_phase.setVisible(True) + self.icdb_progress.setRange(0, len(requests)); self.icdb_progress.setValue(0) + self.icdb_progress.setFormat('已处理 %v / %m 个 CBB') + self.icdb_phase.setText('准备后台检查…') + task.start(); self._update() + + def _icdb_event(self, task, event): + name, stage = str(event.get('block', '')), str(event.get('stage', '')) + detail = str(event.get('detail') or stage) + self.icdb_phase.setText(f'{name} · '+({'icdb_check_start': '正在检查', + 'icdb_startup_check': '正在打开工程', 'waiting_native_slot': '已排队,等待执行'}.get(stage, detail))) + if not self.busy: self.status_label.setText('后台 ICDB 检查:'+self.icdb_phase.text()) + if self.logging_context: + self.logging_context.logger.info('icdb_background block=%s stage=%s detail=%s', name, stage, detail) + + def _icdb_item_done(self, task, name, result): + self.icdb_progress.setValue(len(task.results)) + if not (_library_path_keys(task.requests[0].lmc_file, task.path_lease) + & _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)): + return + row = self._row_by_name.get(name) + if row is None: return + if not result.safe_to_continue: self._defer_status_refresh([name]) + if name in task.invalidated: + text = '内容已更新,待重新检查' + elif result.status == 'CHECKED': text = '未发现 ICDB 错误' + elif result.error_category == 'ICDB_REPAIR_REQUIRED': text = '发现 ICDB 错误' + elif result.status == 'CANCELLED': text = '检查已取消' + elif result.status == 'SKIPPED': + text = '已为 READY,跳过检查' if name in task.ready_names else '未检查' + elif result.error_category == 'DATABASE_SAFETY_STOP': + if 'read/write access permission' in result.stderr.casefold(): + text = '未确认:需处理读写确认' + elif not result.safe_to_continue: + text = '未确认:会话释放未确认' + else: + text = '未确认:会话或数据库状态待确认' + elif result.error_category == 'PCB_VERSION_CHOICE_REQUIRED': text = '未确认:需选择工程版本' + else: text = '未确认:'+(result.stderr.splitlines()[0][:120] if result.stderr else result.status) + cell = self.cbb_table.item(row, 3) + cell.setText(text); cell.setToolTip(result.stderr or result.stdout) + cell.setBackground(QColor('#E8F5E9' if result.status == 'CHECKED' and name not in task.invalidated + else '#FFEBEE' if result.error_category == 'ICDB_REPAIR_REQUIRED' else '#FFF8E1')) + + def _icdb_done(self, task): + from cbb_refresh_verify.icdb_maintenance import maintenance_counts + counts = maintenance_counts(task.results) + lease = task.path_lease + if lease is not None: + if any(not result.safe_to_continue for result in task.results): self._retain_path_lease(lease) + held_by_native = self._native_backup_session is not None and self._native_backup_session.path_lease is lease + if lease is not self.library_lease and not held_by_native: + self._close_path_lease(lease) + for request, result in zip(task.requests, task.results): + if result.status == 'SKIPPED': self._icdb_item_done(task, request.block_name, result) + text = (f'ICDB 检查结束:未发现异常 {counts["checked_without_repair"]},发现问题 {counts["issues_found"]},' + f'占用 {counts["in_use"]},无法确认 {counts["unconfirmed"]},取消 {counts["cancelled"]},未执行 {counts["skipped"]}') + from cbb_refresh_verify.reimport_recovery import offers_reimport + offers = tuple((req, task.records[req.block_name], result) for req, result in zip(task.requests, task.results) + if req.block_name not in task.invalidated and offers_reimport(result)) + same_library = bool(_library_path_keys(task.requests[0].lmc_file, task.path_lease) + & _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)) + if offers: text += '\n可选择工程副本恢复。' + if same_library and not self.busy: self._reimport_offers = offers + self.icdb_phase.setText(text) + if not self.busy: self.status_label.setText(text) + self.output.append(text+'\n'+str(task.report or task.report_error)) + summary = QMessageBox(self); self.icdb_summary = summary + task.summary = summary + if not self.busy: self.summary = summary + summary.setWindowTitle('ICDB 批量检查结果'); summary.setText(text) + summary.setDetailedText(str(task.report or task.report_error)+'\n'+'\n'.join( + req.block_name+':'+('内容已更新,以下为旧检查结果:' if req.block_name in task.invalidated else '') + +(result.stderr or result.stdout or result.status) + for req, result in zip(task.requests, task.results))) + summary.setTextFormat(Qt.PlainText); summary.setAttribute(Qt.WA_ShowWithoutActivating) + if False: # Release entry arrives with the next review PR. + def release_task(): + if not (_library_path_keys(task.requests[0].lmc_file, task.path_lease) + & _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)): + self.status_label.setText(f'请切回 {task.requests[0].lmc_file} 后释放该检查的残留。') + return + self.check_library_release() + summary.addButton('查看残留并释放…', QMessageBox.ActionRole).clicked.connect(release_task) + if offers: + action = summary.addButton('选择副本恢复…', QMessageBox.ActionRole) + task.recovery_action = action + task.recovery_names = {req.block_name for req, _, _ in offers} + def recover(): + if task.recovery_names & task.invalidated: return + if self.busy or not (_library_path_keys(task.requests[0].lmc_file, task.path_lease) + & _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)): return + self._reimport_offers = offers + self.reimport_failed() + action.clicked.connect(recover) + summary.show(); self._update() + + def load_library(self): + if self.busy or not self.lmc_edit.text(): return + self._maintenance_recovery_view = False + self._global_icdb_run = False + if self._management_unsafe_library is not None: + self._management_library_unsafe(self._management_unsafe_library) + requested_library = _path_key(self.lmc_edit.text()) + if requested_library != _path_key(self._management_unsafe_library): + self._management_unsafe = False + self._management_unsafe_library = None + if not self._icdb_active(): + self.icdb_progress.hide(); self.icdb_phase.hide() + self._release_library_lease() + self.loaded_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}; self.ready_names = set() + self._records_by_name = {} + self.skipped_names = set(); self.skip_reasons = {} + path = self.lmc_edit.text() + self.status_label.setText('正在读取中心库…') + def read(): + import pythoncom + started = time.monotonic() + if self.logging_context: + self.logging_context.logger.info('library_load_start path=%s', path) + pythoncom.CoInitialize() + try: + lease = self.path_lease_factory(Path(path)) + mentor_path = (select_library_file(lease.mentor_path) + if lease.mentor_path.is_dir() else lease.mentor_path) + if isinstance(lease, LibraryPathLease): + lease.mentor_path = mentor_path + if self.logging_context: + self.logging_context.logger.info( + 'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s', + lease.display_path, mentor_path, lease.drive or '-', + lease.remote_root or '-', lease.created) + recovery_view = False + result = self.reader(mentor_path) + if not result.error: + self._publish_check_statuses(mentor_path, + {record.name: record.status for record in result.records}, lease) + if self.logging_context: + statuses = Counter(record.status for record in result.records) + unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}] + self.logging_context.logger.info( + 'library_scan_result records=%s elapsed_ms=%s statuses=%s unknown_sample=%s', + len(result.records), int((time.monotonic() - started) * 1000), + dict(statuses), unknown[:20]) + skip_reasons = {} + if not result.error: + for record in result.records: + reason = preflight_skip_reason(mentor_path, record.name) + if reason: + skip_reasons[record.name] = reason + return result, skip_reasons, lease, mentor_path, recovery_view + except Exception: + if 'lease' in locals(): + lease.close() + raise + finally: pythoncom.CoUninitialize() + def loaded(payload): + result, skip_reasons, lease, mentor_path, recovery_view = payload + if path != self.lmc_edit.text(): + self._close_path_lease(lease) + return + if result.error: + self._close_path_lease(lease) + self.status_label.setText(result.error); return + self.library_lease = lease + self._maintenance_recovery_view = recovery_view + self.mentor_lmc_path = mentor_path + self.loaded_path = path + self.cbb_table.setRowCount(0) + self.ready_names = {r.name for r in result.records if r.status == 'READY' and r.name not in skip_reasons} + self.skip_reasons = dict(skip_reasons) + self.skipped_names = set(skip_reasons) + self._records_by_name = {record.name: record for record in result.records} + # Populating a large library emits itemChanged for every cell. + # Block those signals and refresh controls once after the batch; + # otherwise _update() repeatedly scans the growing table (O(n^2)). + self.cbb_table.blockSignals(True) + self.cbb_table.setUpdatesEnabled(False) + try: + self.cbb_table.setRowCount(len(result.records)) + for row, record in enumerate(result.records): + self._row_by_name[record.name] = row + item = QTableWidgetItem(record.name) + # Management selection includes READY and missing projects; + # operation queues independently enforce eligibility. + item.setFlags(item.flags() | Qt.ItemIsUserCheckable) + item.setCheckState(Qt.Unchecked) + self.cbb_table.setItem(row, 0, item) + self.cbb_table.setItem(row, 1, QTableWidgetItem(record.partition_name)) + status_text = STATUS_LABELS.get(record.status, record.status) + if record.name in self.skipped_names: + status_text += ' · 缺少工程/PCB' + self.cbb_table.setItem(row, 2, QTableWidgetItem(status_text)) + # Preflight touches each CBB's project and was previously run + # synchronously in this GUI callback, making large libraries + # appear frozen. The verify worker performs it when queued. + self.cbb_table.setItem(row, 3, QTableWidgetItem('未检查')) + if record.status == 'READY' and record.name not in self.skipped_names: + self._mark_row_ready(row) + elif record.name in self.skipped_names: + self.cbb_table.item(row, 0).setToolTip(self.skip_reasons[record.name]) + self.cbb_table.item(row, 2).setToolTip(self.skip_reasons[record.name]) + self.cbb_table.item(row, 3).setText('跳过') + for column in range(self.cbb_table.columnCount()): + cell = self.cbb_table.item(row, column) + if cell is not None: + cell.setBackground(QColor('#FFF8E1')) + finally: + self.cbb_table.setUpdatesEnabled(True) + self.cbb_table.blockSignals(False) + ready_count = len(self.ready_names) + unavailable_count = sum(record.status == 'UNAVAILABLE' for record in result.records) + read_error_count = sum(record.status in {'ERROR', 'TIMEOUT', 'MALFORMED', 'CRASHED'} + for record in result.records) + suffix = '' + if unavailable_count: + suffix += f' 状态桥不可用 {unavailable_count} 个。' + if read_error_count: + suffix += f' 状态读取失败 {read_error_count} 个。' + self.status_label.setText( + f'已读取 {len(result.records)} 个 CBB,其中 Ready {ready_count} 个,' + f'缺文件跳过 {len(self.skipped_names)} 个。{suffix}') + if recovery_view: + self.status_label.setText('协调阻止恢复视图:仅按目录显示工程,状态未确认(UNKNOWN),不代表损坏。' + '仅可明确执行 ICDB 维护或释放检查,其他写入与原生状态读取已禁用。') + self._apply_filters() + self._start(read, loaded) + + def _request(self, name): + return VerifyRequest(Path(self.mentor_lmc_path or self.loaded_path), name, self.data_root/'evidence', + libspec=self.libspec_edit.text().strip(), + dms_login_config=self.dms_edit.text().strip(), + mentor_bin=self.mentor_bin_edit.text().strip(), + mapped_drive=getattr(self.library_lease, 'drive', ''), + mapped_remote_root=getattr(self.library_lease, 'remote_root', ''), + timeout_seconds=self.timeout_spin.value(), logging_context=self.logging_context, + native_lm_verify=self.native_lm_verify_check.isChecked()) + + def _selected_names(self): + return [record.name for record in self.selected_records()] + + def verify_selected(self): + self._confirm_verify(self._eligible_names(checked_only=True)) + + def verify_all(self): + self._confirm_verify(self._eligible_names()) + + def _confirm_verify(self, names): + from .backup_notice import MANUAL_BACKUP_NOTICE + if self.busy or not self.loaded_path or self._native_backup_same_library() or not names: + return + if QMessageBox.question(self, '确认批量校验', + f'{MANUAL_BACKUP_NOTICE}\n\n目标库:{self.loaded_path}\n' + f'将校验 {len(names)} 个可见非 READY CBB 并保存结果。确认继续?', + QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes: + self._run(names) + + def repair_icdb_all(self): + if self.busy or not self.loaded_path: return + names = self._maintenance_names() + if not names: return + answer = QMessageBox.question(self, 'ICDB 批量检查', + f'当前中心库:{self.loaded_path}\n\n' + f'将检查 {len(names)} 个可见非 READY CBB' + f'{"(仅勾选项)" if self.selected_records() else ""}。\n' + '仅检查 ICDB 状态,不执行修复或回退。\n\n是否开始?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) + if answer == QMessageBox.Yes: + self._run(names, maintenance=True) + + def _native_backup_same_library(self): + return self._native_backup_matches_library(self.mentor_lmc_path or self.lmc_edit.text()) + + def _native_backup_matches_library(self, library, lease=None): + session = self._native_backup_session + return session is not None and bool( + _library_path_keys(library, lease or self.library_lease) + & _library_path_keys(session.library, getattr(session, 'path_lease', None))) + + def open_native_backup(self): + if self.busy or not self.loaded_path or self._native_backup_session is not None: + return + target = self._native_backup_target() + if target is None: + self.status_label.setText('请勾选一个非 READY CBB。') + return + from cbb_refresh_verify.native_backup import launch_native_backup + request = self._request(target.name) + launcher = self.native_backup_launcher or launch_native_backup + self._global_icdb_run = False + self._reimport_offers = () + self.status_label.setText(f'正在打开 {request.block_name} 的版本与备份…') + paused_check = self.icdb_task if self._check_matches_library(request.lmc_file) else None + if paused_check is not None: + paused_check.pause(); paused_check.invalidate([request.block_name]) + def opened(session): + session.path_lease = self.library_lease + self._native_backup_session = session + self.native_backup_timer.start() + self.status_label.setText(f'正在打开 {session.block} 的原生备份窗口,请在其中选择版本。') + self.output.append(f'{session.block} · 原生版本与备份\n{session.job}') + self.busy = True; self._update() + self.stop.clear() + self.worker = ServiceWorker(self._queued_action(lambda: launcher(request))) + self.worker.signals.succeeded.connect(opened) + def failed(error): + self.status_label.setText(f'无法打开版本与备份:{error}') + if paused_check is not None: paused_check.resume() + self.worker.signals.failed.connect(failed) + self.worker.signals.finished.connect(self._finished) + self.pool.start(self.worker) + + def _release_native_backup_session(self, session): + self._native_backup_session = None + if session.path_lease is not None and session.path_lease is not self.library_lease: + self._close_path_lease(session.path_lease) + if self._icdb_active(): self.icdb_task.resume() + + def _poll_native_backup(self): + session = self._native_backup_session + if session is None or self.busy or session.process.poll() is None: + return + self.native_backup_timer.stop() + same_library = self._native_backup_same_library() + def read_result(): + import json + result = json.loads(session.job.with_name('result.json').read_text('utf-8')) + if (not self._native_backup_matches_library(result['library'], getattr(session, 'path_lease', None)) + or result['block'] != session.block): + raise ValueError('原生会话返回的工程身份不一致。') + refresh = (self._read_affected_records((session.block,)) + if result.get('safe_to_continue') is True and same_library else None) + return result, refresh + def completed(payload): + result, refresh = payload + if result.get('safe_to_continue') is not True: + unconfirmed(result.get('detail', '未取得会话释放结果。')) + return + self._release_native_backup_session(session) + if refresh is not None: + self._apply_refreshed_records(refresh) + message = ('原生备份窗口已关闭。需要时可单独运行校验。' if result.get('status') == 'CLOSED' + else '原生备份操作未结束:' + result.get('detail', '请检查原生窗口。')) + self.status_label.setText(message) + self.output.append(f'{session.block} · {message}\n{session.job.with_name("result.json")}') + if same_library and session.block in self._row_by_name: + self.cbb_table.item(self._row_by_name[session.block], 3).setText(message) + def unconfirmed(error): + self.status_label.setText('原生窗口退出尚未确认,请关闭窗口后检查释放。') + self.output.append(f'{session.block} · 退出尚未确认:{error}\n{session.job}') + self.busy = True; self._update() + self.stop.clear() + self.worker = ServiceWorker(self._queued_action(read_result)) + self.worker.signals.succeeded.connect(completed) + self.worker.signals.failed.connect(unconfirmed) + self.worker.signals.finished.connect(self._finished) + self.pool.start(self.worker) + + def restore_backup(self): + if self.busy or not self.loaded_path or self._native_backup_same_library(): + return + from .backup_recovery_dialog import BackupRecoveryDialog + names = self._eligible_names(checked_only=bool(self.selected_records())) + if not names: + return + self.backup_dialog = BackupRecoveryDialog(names, self._backup_request, self) + self.backup_dialog.native_queue = self.native_queue + row = self.cbb_table.currentRow() + if row >= 0 and self.cbb_table.item(row, 0).text() in names: + self.backup_dialog.block_combo.setCurrentText(self.cbb_table.item(row, 0).text()) + self.backup_dialog.started.connect(self._backup_started) + self.backup_dialog.completed.connect(self._backup_completed) + self.backup_dialog.finished.connect(lambda _code: self._backup_dialog_closed()) + self.backup_dialog.setModal(True) + self.backup_dialog.show() + + def _backup_request(self, name): + # A still-open dialog must recheck a target after an earlier recovery + # or an authoritative refresh changed its eligibility. + if self.busy or self._native_backup_same_library() or name not in self._eligible_names(checked_only=bool(self.selected_records())): + raise ValueError('目标需为当前可见、可用的非 READY CBB;请重新选择。') + return self._request(name) + + def _backup_started(self, name): + self._invalidate_check_targets(self.mentor_lmc_path or self.loaded_path, [name]) + self.busy = True + self._global_icdb_run = False + self.ready_names.discard(name) + if name in self._records_by_name: + self._records_by_name[name] = replace(self._records_by_name[name], status='UNKNOWN') + row = self._row_by_name.get(name) + if row is not None: + self.cbb_table.item(row, 2).setText('恢复中 / 需确认') + self.cbb_table.item(row, 0).setFlags( + self.cbb_table.item(row, 0).flags() | Qt.ItemIsUserCheckable) + for column in range(self.cbb_table.columnCount()): + self.cbb_table.item(row, column).setBackground(QColor('#FFF8E1')) + self._update() + self.stop_button.setEnabled(False) + + def _backup_completed(self, name, result): + if not result.safe_to_continue and self.library_lease is not None: + self._retain_path_lease(self.library_lease, hold_busy=True) + row = self._row_by_name.get(name) + if row is not None and result.status != 'PASS': + self.cbb_table.item(row, 2).setText('未知 / 需确认') + self._progress({'block': name, 'stage': result.status, 'detail': result.stderr, + 'evidence': str(result.evidence_path or '')}) + if result.safe_to_continue: + self.busy = False + self.refresh_affected_records([name]) + else: + self._defer_status_refresh([name]) + + def _backup_dialog_closed(self): + if not getattr(self, '_refreshing_records', False): + self._finished() + + def _run(self, names, *, maintenance=False): + if maintenance: return self._start_icdb_check(names) + if self.busy or not self.loaded_path: return + if self._native_backup_same_library(): + self.status_label.setText('请先关闭该库的版本与备份窗口。') + return + eligible = set(self._maintenance_names() if maintenance else self._eligible_names()) + names = [name for name in names if name in eligible] + if not names: + self.status_label.setText('当前可见选择中没有可校验的非 READY CBB。') + self._update() + return + requests = [replace(self._request(name), maintenance=maintenance, auto_repair=False) for name in names] + self._batch_requests = tuple(requests) + self._batch_records = {name: self._records_by_name[name] for name in names} + self._reimport_offers = () + self._global_icdb_run = maintenance + self._icdb_completed = 0 + self.icdb_progress.setVisible(maintenance or self._icdb_active()) + self.icdb_phase.setVisible(maintenance or self._icdb_active()) + if maintenance: + self.icdb_progress.setRange(0, len(requests)) + self.icdb_progress.setValue(0) + self.icdb_progress.setFormat('已处理 %v / %m 个 CBB') + self.icdb_phase.setText('准备检查…') + self.stop.clear(); self.recovery_path = None; self.recovery_button.setEnabled(False) + self.output.clear(); self.status_label.setText( + f'正在 ICDB 批量检查:共 {len(names)} 个 CBB' if maintenance + else f'正在校验:共 {len(names)} 个 CBB') + def action(): + from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify + verify = self.verifier or (lambda req: run_verify( + req, progress=lambda e: self.signals.event.emit(e), + flag_reader=read_library_flag_if_available, + version_prompt=self.signals.version_choice.emit, stop=self.stop)) + def verifier(req): + if maintenance: + self.signals.event.emit({'block': req.block_name, 'stage': 'icdb_check_start'}) + return verify(req) + results = run_batch(requests, verifier=verifier, stop=self.stop, + progress=lambda name, result: self.signals.event.emit({'block': name, 'stage': result.status, + 'error_category': result.error_category, 'evidence': str(result.evidence_path or ''), + 'detail': result.stderr or result.stdout})) + report = None + try: + report = write_batch_report(requests, results, self.data_root/'reports') + if maintenance: + from cbb_refresh_verify.icdb_maintenance import write_maintenance_report + write_maintenance_report(requests, results, report, ()) + except Exception as error: + self.signals.event.emit({'stage': 'report_failed', 'detail': str(error)}) + affected = [req.block_name for req, result in zip(requests, results) if result.status != 'SKIPPED'] + safe = all(result.safe_to_continue for result in results) + refresh = self._read_affected_records(affected) if safe else None + return results, report, affected, refresh + self._start(action, self._batch_done) + + def _read_affected_records(self, names): + """Worker-only read; never derive library state from action outcomes.""" + import pythoncom + pythoncom.CoInitialize() + try: + path = Path(self.mentor_lmc_path or self.loaded_path) + try: + statuses = self.status_refresher(tuple(names), path) + # Publish before yielding the native queue, ahead of Qt callbacks. + self._publish_check_statuses(path, statuses) + reasons = {name: reason for name in names + if (reason := preflight_skip_reason(path, name))} + return tuple(names), statuses, reasons, '' + except Exception as error: + return tuple(names), {}, None, str(error) + finally: + pythoncom.CoUninitialize() + + def _apply_refreshed_records(self, payload): + names, statuses, reasons, error = payload + self._publish_check_statuses(self.mentor_lmc_path or self.loaded_path, + {name: statuses.get(name, 'UNKNOWN') for name in names}) + self.cbb_table.blockSignals(True) + try: + for name in names: + if name not in self._records_by_name: + continue + status = statuses.get(name, 'UNKNOWN') + if status not in STATUS_LABELS: + status = 'UNKNOWN' + self._records_by_name[name] = replace(self._records_by_name[name], status=status) + self.ready_names.discard(name) + if reasons is not None: + self.skip_reasons.pop(name, None) + if name in reasons: + self.skip_reasons[name] = reasons[name] + self.skipped_names = set(self.skip_reasons) + row = self._row_by_name[name] + text = STATUS_LABELS[status] + if name in self.skipped_names: + text += ' · 缺少工程/PCB' + self.cbb_table.item(row, 2).setText(text) + self.cbb_table.item(row, 2).setToolTip(error or self.skip_reasons.get(name, '')) + if status == 'READY' and name not in self.skipped_names: + self.ready_names.add(name) + # A status transition invalidates a maintenance target; + # clear its old check so the repeatable diagnostic entry + # point does not become disabled merely because the user + # selected the row for the previous run. + self.cbb_table.item(row, 0).setCheckState(Qt.Unchecked) + self._mark_row_ready(row) + else: + for column in range(self.cbb_table.columnCount()): + self.cbb_table.item(row, column).setBackground(QColor('#FFF8E1')) + finally: + self.cbb_table.blockSignals(False) + if error: + self.output.append(f'状态复核未完成 / 需确认:{error}') + self._apply_filters() + return tuple(self._records_by_name[name] for name in names if name in self._records_by_name) + + def _defer_status_refresh(self, names): + self._apply_refreshed_records((tuple(names), {}, None, + '会话或数据库安全未确认;暂缓原生状态复核,请确认释放后重新读取。')) + + def refresh_affected_records(self, names, callback=None): + """Start an affected-only authoritative refresh once native owners release. + + Return True if scheduled, False if busy/unloaded/empty. Callback receives + tuple[CbbRecord, ...] on the GUI thread after applying refreshed statuses + (UNKNOWN on read failure). It runs before the worker's finished signal. + Search, filter, original logical_type and action-result cells are retained. + """ + if self.busy or not self.loaded_path or self._native_backup_same_library(): + return False + targets = tuple(dict.fromkeys(name for name in names if name in self._records_by_name)) + if not targets: + return False + self._refreshing_records = True + def refreshed(payload): + records = self._apply_refreshed_records(payload) + self._refreshing_records = False + if callback: + callback(records) + self._start(lambda: self._read_affected_records(targets), refreshed) + return True + + def _progress(self, event): + line = f"{event.get('block', '')} | {event.get('stage', '')}" + for key in ('detail', 'error', 'action', 'statuses', 'evidence'): + if event.get(key): line += f' | {event[key]}' + self.output.append(line) + block = event.get('block'); stage = event.get('stage') + if self._global_icdb_run: + if stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED', 'QUEUE_STOP', 'CHECKED', 'CANCELLED', 'REPAIRED'}: + self._icdb_completed += 1 + self.icdb_progress.setValue(self._icdb_completed) + phases = {'icdb_check_start': '检查工程数据库与校验状态', + 'icdb_startup_check': '正在尝试打开工程', + 'icdb_ownership_check': '正在打开原生检查工具', + 'native_started': '等待原生工具加载工程', + 'native_occupancy_wait': '等待原生检查结果', + 'native_repair_complete': '原生修复完成,待单独校验', + 'native_repair_start': '核对占用并准备原生修复', + 'native_repair_requested': '正在原生修复', + 'native_repair_confirmed': '正在原生修复', + 'native_repair_finished': '原生修复已结束,正在核对结果'} + if stage in phases: + self.icdb_phase.setText(f'{block or ""} · {phases[stage]}') + if block and stage in {'PASS', 'FAIL', 'BLOCKED', 'TIMEOUT', 'SKIPPED', 'CHECKED', 'REPAIRED', 'CANCELLED'}: + row = self._row_by_name.get(block) + if row is not None: + detail = str(event.get('detail') or event.get('error') or '').strip() + if event.get('error_category') == 'ICDB_REPAIR_REQUIRED' and detail: + detail = 'ICDB 问题:' + detail + label = str(stage) if not detail else f'{stage}: {detail[:96]}' + self.cbb_table.item(row, 3).setText(label) + self.cbb_table.item(row, 3).setToolTip(detail) + if self.logging_context: self.logging_context.logger.info('cbb_progress %s', line) + + def _mark_row_ready(self, row): + """Color authoritative READY rows while retaining management selection.""" + name_item = self.cbb_table.item(row, 0) + if name_item is None: + return + name_item.setFlags(name_item.flags() | Qt.ItemIsUserCheckable) + for column in range(self.cbb_table.columnCount()): + cell = self.cbb_table.item(row, column) + if cell is not None: + cell.setBackground(QColor('#E8F5E9')) + + def _batch_done(self, outcome): + results, report = outcome[:2] + failure_report = failure_report_path(report) if report is not None else '未写入' + report = report if report is not None else '未写入' + from cbb_refresh_verify.reimport_recovery import offers_reimport + self._reimport_offers = tuple((req, self._batch_records[req.block_name], result) + for req, result in zip(self._batch_requests, results) + if req.maintenance and req.block_name in self._batch_records and offers_reimport(result)) + if len(outcome) > 2: + _, _, affected, refresh = outcome + if refresh is None: + self._defer_status_refresh(affected) + else: + self._apply_refreshed_records(refresh) + if self.library_lease is not None and any(not result.safe_to_continue for result in results): + self._retain_path_lease(self.library_lease, hold_busy=True) + for result in results: + if not result.safe_to_continue and result.evidence_path: + self.recovery_path = result.evidence_path.parent + self.recovery_button.setEnabled(self.recovery_path.is_dir()) + passed = sum(r.status == 'PASS' for r in results) + skipped = sum(r.status == 'SKIPPED' for r in results) + checked = sum(r.status == 'CHECKED' for r in results) + repaired = sum(r.status == 'REPAIRED' for r in results) + failed = len(results)-passed-skipped-checked-repaired + text = (f'已结束:成功 {passed},失败 {failed},预检跳过 {len(self.skipped_names)},' + f'队列未执行 {skipped}。\n完整日志:{report}\n仅失败日志:{failure_report}') + if self._global_icdb_run: + from cbb_refresh_verify.icdb_maintenance import maintenance_counts + counts = maintenance_counts(results) + text = ('ICDB 批量检查已结束\n' + f'未发现异常 {counts["checked_without_repair"]},发现问题 {counts["issues_found"]},' + f'占用 {counts["in_use"]},无法确认 {counts["unconfirmed"]},' + f'取消 {counts["cancelled"]},队列未执行 {skipped}\n' + f'完整日志:{report}\n仅失败日志:{failure_report}') + self.icdb_phase.setText('批量检查已结束') + if False: # Release entry arrives with the next review PR. + text += '\n未确认数据库或会话安全,已停止剩余校验。请查看恢复现场。' + status_text = (f'已结束:通过 {passed},失败/受阻 {failed},' + f'仅检查 {checked},未执行 {skipped + len(self.skipped_names)}。') + if self._global_icdb_run: + status_text = (f'检查结束:未发现异常 {counts["checked_without_repair"]},' + f'发现问题 {counts["issues_found"]},占用 {counts["in_use"]},' + f'无法确认 {counts["unconfirmed"]},取消 {counts["cancelled"]},未执行 {skipped}。') + if repaired and not self._global_icdb_run: + status_text += f'\n原生 ICDB 修复完成 {repaired},待单独校验。' + first_failure = next((result.stderr for result in results + if result.status not in ('PASS', 'SKIPPED', 'CHECKED', 'REPAIRED') and result.stderr), '') + if first_failure: + text += '\n首个未完成原因:' + first_failure + if any(result.error_category == 'CBB_REIMPORT_REQUIRED' for result in results): + status_text += '\nMentor 不允许对此已验证过的 CBB 反标注,校验未通过。' + else: + status_text += '\n部分项目未完成,请查看详情。' + if False: # Release entry arrives with the next review PR. + status_text += '\n后续操作已暂停。' + if self._reimport_offers: + guidance = '\n修复未完成,可选择工程副本恢复。' + text += guidance + status_text += guidance + self.status_label.setText(status_text.replace('\n', ' ')); self.output.append(text) + self.summary = QMessageBox(self) + self.summary.setWindowTitle('ICDB 批量检查结果' if self._global_icdb_run else 'CBB 校验结果') + self.summary.setText(status_text) + self.summary.setDetailedText(text) + self.summary.setIcon(QMessageBox.Warning if failed else QMessageBox.Information) + self._reimport_summary_action = None + self._residual_release_action = None + self._resume_batch_action = None + self._resume_batch = None + if False: # Release entry arrives with the next review PR. + self._residual_release_action = self.summary.addButton('查看残留并释放…', QMessageBox.ActionRole) + self._residual_release_action.clicked.connect(self.check_library_release) + self._residual_release_action.setEnabled(False) + names = [req.block_name for req, result in zip(self._batch_requests, results) + if result.status == 'SKIPPED'] + if names: + self._resume_batch = {'library': self._batch_requests[0].lmc_file, 'names': names, + 'maintenance': self._global_icdb_run, 'released': False} + self._resume_batch_action = self.summary.addButton('继续未执行项', QMessageBox.ActionRole) + self._resume_batch_action.clicked.connect(self._resume_released_batch) + self._resume_batch_action.setEnabled(False) + if self._reimport_offers: + self.summary.setStandardButtons(QMessageBox.Close) + self._reimport_summary_action = self.summary.addButton('选择副本恢复…', QMessageBox.ActionRole) + self._reimport_summary_action.clicked.connect(self.reimport_failed) + self._reimport_summary_action.setEnabled(False) # Enabled after the worker finishes. + # Modeless notification: do not force activation or steal keyboard focus. + from PySide6.QtCore import Qt + self.summary.setTextFormat(Qt.PlainText) + self.summary.setAttribute(Qt.WA_ShowWithoutActivating) + self.summary.show() + + def _show_version_choice(self, choice): + from .pcb_restore_dialog import PcbRestoreDialog + if not self.busy or self.stop.is_set(): + choice.choose('cancel') + return + self.version_dialog = PcbRestoreDialog(choice, self) + self.status_label.setText(f'{choice.block}:等待选择 PCB 恢复版本。') + self.icdb_phase.setText(f'{choice.block} · 等待选择 PCB 恢复版本') + self.version_dialog.show() + + def request_stop(self): + if self._icdb_active(): + self._stop_icdb_check() + if not self.busy: return + if self.version_dialog is not None: + self.version_dialog.reject() + management = getattr(self, 'management_dialog', None) + if management is not None and management.isVisible(): + management.stop.set() + self.stop.set(); self.status_label.setText('已请求取消 ICDB 检查。' if self._global_icdb_run else + '已请求取消;检查将停止,原生写入只等待安全结束,不强制终止。'); self._update() + + def _failed(self, error): + from cbb_refresh_verify.operation_queue import QueueCancelled + if self.library_lease is not None and not isinstance(error, QueueCancelled): + self._retain_path_lease(self.library_lease, hold_busy=True) + self._display_error(error) + + def _display_error(self, error): + self.status_label.setText(str(error)); self.output.append(str(error)) + if self.logging_context: self.logging_context.logger.error('cbb_worker_failed %s', error) + + def _finished(self): + if self._defer_mapping_finish(self._finished): return + if self.version_dialog is not None: + self.version_dialog.reject() + self.version_dialog = None + self.busy = False; self._update() + if self._reload_after_maintenance: + from PySide6.QtCore import QTimer + self._reload_after_maintenance = False + QTimer.singleShot(0, self.load_library) + + def open_logs(self): + self.data_root.mkdir(parents=True, exist_ok=True); os.startfile(str(self.data_root)) + + def recover(self): + if not self.recovery_path: return + try: os.startfile(str(self.recovery_path)) + except Exception as error: self._display_error(error) + + def closeEvent(self, event): + if self._close_ready: + event.accept() + elif self._closing: + event.ignore() + elif self._icdb_active(): + self._stop_icdb_check(); event.ignore() + elif self.busy: + self.request_stop(); event.ignore() + else: + self._closing = True + self.busy = True; self._update() + retained = None + if self._native_backup_session is not None: + self.native_backup_timer.stop() + retained = self._native_backup_session.path_lease + lease, self.library_lease = self.library_lease, None + def release(): + if retained is not None: retained.retain_for_recovery() + if lease is not None and lease is not retained: lease.close() + self._lease_action(release) + self._close_when_idle() + event.ignore() + + def _close_when_idle(self): + owners = [self, *self.icdb_tasks] + for name in ('management_dialog', 'backup_dialog', 'release_dialog'): + owners.append(getattr(self, name, None)) + active = False + for owner in owners: + try: + pool = getattr(owner, 'pool', None) + active = active or bool(pool is not None and pool.activeThreadCount()) + except RuntimeError: + pass # Qt may already have deleted a closed dialog's pool. + if self._lease_pending or active: + QTimer.singleShot(20, self._close_when_idle) + return + self._close_ready = True + self.close() diff --git a/src/cbb_refresh_verify/ui/management_dialog.py b/src/cbb_refresh_verify/ui/management_dialog.py new file mode 100644 index 0000000..59bad6b --- /dev/null +++ b/src/cbb_refresh_verify/ui/management_dialog.py @@ -0,0 +1,235 @@ +"""Explicit preview and asynchronous, checkpointed CBB management batch.""" +from dataclasses import replace +from pathlib import Path +from threading import Event + +from PySide6.QtCore import QObject, QThreadPool, Signal, Qt +from PySide6.QtWidgets import (QCheckBox, QDialog, QFileDialog, QHBoxLayout, QLabel, + QMessageBox, QPushButton, QTableWidget, QTableWidgetItem, QTextEdit, QVBoxLayout) + +from .workers import ServiceWorker +from .backup_notice import MANUAL_BACKUP_NOTICE +from ..management import run_management_batch, validate_name + +RESULT_LABELS = { + 'REMOVED': '已移除', 'UPLOADED': '已上传 / 未自动校验', + 'UPLOADED_VERIFIED': '已上传且校验通过', 'UPLOADED_VERIFY_FAILED': '已上传但校验未通过', + 'UPLOAD_FAILED': '上传失败', 'RECOVERY_REQUIRED': '需要人工恢复 / 队列已停止', + 'BLOCKED': '操作被阻止', 'UNSUPPORTED': '当前环境不支持', +} +STAGE_LABELS = { + 'prepare_identity': '正在核对来源工程内容', + 'catalog_before': '正在核对原生目录', 'baseline': '正在记录中心库内容基线', + 'stage_source': '正在复制并检查来源工程', 'native_remove': '正在移除', + 'removed': '原条目已移除', 'native_add': '正在上传', 'uploaded': '上传已确认', + 'verify': '正在校验上传结果', 'verified': '校验已返回', 'copy': '正在准备来源副本', + 'hash': '正在校验主要文件', + 'release_check': '正在检查工程是否被占用', +} + + +class ManagementSignals(QObject): + progress = Signal(object) + + +class ManagementDialog(QDialog): + completed = Signal(object) + before_execute = Signal(object) + + def __init__(self, requests, parent=None, *, adapter=None, runner=None, recovery_from=None): + super().__init__(parent) + self.templates = tuple(requests) + self.template = self.templates[0] + self.operation = self.template.operation + self.adapter = adapter + self.native_queue = None + self.recovery_from = dict(recovery_from or {}) + self.runner = runner or run_management_batch + if self.recovery_from and runner is None: + from ..reimport_recovery import run_reimport_recovery + self.runner = lambda requests, **kwargs: run_reimport_recovery(requests, + previous_evidence=self.recovery_from, + evidence_dir=self.template.evidence_dir.parent/'reimport-recovery', **kwargs) + self.busy = False + self.executed = False + self.stop = Event() + self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1) + self.signals = ManagementSignals(self) + self.signals.progress.connect(self._progress) + self.setWindowTitle({'add': '新增 CBB', 'update': '同名更新 CBB', 'remove': '移除 CBB'}[self.operation]) + self.resize(850, 450) + self.table = QTableWidget(0, 4) + self.table.setHorizontalHeaderLabels(['CBB 名称', '分区', '来源 PRJ(完整工程)', '顶层块(空白时读取工程)']) + self.table.horizontalHeader().setStretchLastSection(True) + self.table.setColumnWidth(2, 300) + self.sources_button = QPushButton('选择来源工程…') + self.sources_button.setVisible(self.operation != 'remove') + self.sources_button.clicked.connect(self._browse) + self.auto_verify = QCheckBox('本批次上传后自动校验') + self.auto_verify.setChecked(self.template.auto_verify) + self.auto_verify.setVisible(self.operation != 'remove') + self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 更新会先移除再重新导入,失败时请使用手动备份恢复。') + self.status_label.setWordWrap(True) + self.output = QTextEdit(); self.output.setReadOnly(True) + self.output.document().setMaximumBlockCount(2000) + self.output.hide() + self.logs_button = QPushButton('查看日志') + self.logs_button.setCheckable(True) + self.logs_button.toggled.connect(self.output.setVisible) + if self.recovery_from: + self.setWindowTitle('从副本恢复 CBB') + self.status_label.setText('修复未完成。请选择完整工程副本(.prj)。所列 CBB 将替换为副本中的版本。\n' + + MANUAL_BACKUP_NOTICE) + self.output.append('\n'.join(f'原失败记录 {name}:{path}' for name, path in self.recovery_from.items())) + self.execute_button = QPushButton('预览并确认执行…') + self.execute_button.clicked.connect(self._execute) + self.stop_button = QPushButton('当前项结束后停止'); self.stop_button.setEnabled(False) + self.stop_button.clicked.connect(self.stop.set) + self.close_button = QPushButton('关闭'); self.close_button.clicked.connect(self.reject) + layout = QVBoxLayout(self) + layout.addWidget(QLabel(f'目标库:{self.template.library}')) + layout.addWidget(self.table) + layout.addWidget(self.sources_button); layout.addWidget(self.auto_verify) + layout.addWidget(self.status_label); layout.addWidget(self.logs_button); layout.addWidget(self.output) + buttons = QHBoxLayout() + for widget in (self.execute_button, self.stop_button, self.close_button): buttons.addWidget(widget) + layout.addLayout(buttons) + for request in self.templates: + if request.name: + self._append(request) + + def _append(self, request): + row = self.table.rowCount(); self.table.insertRow(row) + for column, value in enumerate((request.name, request.partition, str(request.source or ''), request.top_level_block)): + item = QTableWidgetItem(value) + if column == 1 or column == 0 and self.operation != 'add' or self.operation == 'remove': + item.setFlags(item.flags() & ~Qt.ItemIsEditable) + self.table.setItem(row, column, item) + + def add_sources(self, sources): + if self.operation == 'add': + for source in sources: + source = Path(source) + self._append(replace(self.template, name=source.stem, source=source)) + elif self.operation == 'update' and sources: + row = max(0, self.table.currentRow()) + self.table.item(row, 2).setText(str(sources[0])) + + def _browse(self): + if self.operation == 'add': + paths, _ = QFileDialog.getOpenFileNames(self, '选择完整来源工程', '', '工程 (*.prj)') + else: + path, _ = QFileDialog.getOpenFileName(self, '为当前行选择同名更新来源', '', '工程 (*.prj)') + paths = [path] if path else [] + self.add_sources(paths) + + def requests(self): + result = [] + for row in range(self.table.rowCount()): + name, partition, source, top = (self.table.item(row, i).text().strip() for i in range(4)) + result.append(replace(self.template, name=name, partition=partition, + source=Path(source) if source else None, top_level_block=top, + auto_verify=self.operation != 'remove' and self.auto_verify.isChecked())) + return result + + def _execute(self): + if self.busy or self.executed: + return + requests = self.requests() + try: + if not requests: + raise ValueError('请先选择来源工程。') + for request in requests: + validate_name(request.name) + if request.operation != 'remove' and (request.source is None or not request.source.is_file()): + raise ValueError(f'{request.name}:请选择完整来源 PRJ。') + if len({(r.partition.casefold(), r.name.casefold()) for r in requests}) != len(requests): + raise ValueError('批次包含重复目标名称。') + except ValueError as error: + self.status_label.setText(str(error)); return + preview = '\n'.join(f'{r.partition} / {r.name}' + (f' ← {r.source}' if r.source else '') for r in requests) + description = ('同名更新会原生移除并重新导入;导入失败需要使用手动备份恢复。' if self.operation == 'update' + else '将通过原生操作移除所列 CBB;恢复时需要使用手动备份。' if self.operation == 'remove' + else '新增同名冲突会拒绝覆盖,完整来源工程将先复制到暂存区。') + if self.recovery_from: + description = ('将用所选副本替换这些 CBB。操作会先移除原条目,再导入副本;' + '导入失败时需要用备份恢复。请确认副本版本。') + answer = QMessageBox.question(self, '确认管理操作', + f'{MANUAL_BACKUP_NOTICE}\n{description}\n\n目标库:{self.template.library}\n{preview}\n\n' + '确认继续执行?', QMessageBox.Yes | QMessageBox.No, + QMessageBox.No) + if answer != QMessageBox.Yes: + return + self.busy = True; self.executed = True + self._enabled(False) + self.before_execute.emit([r.name for r in requests]) + def execute(): + action = lambda: self.runner(requests, adapter=self.adapter, stop=self.stop, + progress=self.signals.progress.emit) + if self.native_queue is None: return action() + from ..operation_queue import QueueCancelled + try: + return self.native_queue.run(action, stop=self.stop, waiting=lambda: self.signals.progress.emit( + {'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'})) + except QueueCancelled as error: + from ..management import ManagementResult + return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source, r.auto_verify, + 'complete', 'BLOCKED', True, str(error)) for r in requests] + self.worker = ServiceWorker(execute) + self.worker.signals.succeeded.connect(self._result) + self.worker.signals.failed.connect(self._failed) + self.worker.signals.finished.connect(self._finished) + self.pool.start(self.worker) + + def _enabled(self, enabled): + for widget in (self.table, self.sources_button, self.auto_verify, self.close_button): + widget.setEnabled(enabled) + self.execute_button.setEnabled(enabled and not self.executed) + self.stop_button.setEnabled(not enabled) + + def _progress(self, event): + stage = str(event.get('stage', '')) + text = f'{event.get("block", "")} {STAGE_LABELS.get(stage, RESULT_LABELS.get(stage, "正在处理"))}' + if stage == 'waiting_native_slot': text = str(event.get('detail', '已排队,等待执行')) + self.output.append(str(event)) + if 'copied_files' in event: + text += f' {event["copied_files"]}/{event.get("total_files", "?")}' + elif 'hashed_files' in event: + text += f' {event["hashed_files"]}/{event.get("total_files", "?")} · {event.get("hashed_bytes", 0)} 字节' + self.status_label.setText(text) + + def _result(self, results): + lines, summaries = [], [] + for result in results: + summary = f'{result.name}:{RESULT_LABELS.get(result.status, result.status)}' + text = f'{summary} — {result.detail}' + if self.recovery_from and result.status == 'UPLOADED_VERIFIED': + summary += ',版本待核对。' + elif result.status not in ('UPLOADED', 'UPLOADED_VERIFIED', 'REMOVED'): + summary += ',详情请查看日志。' + summaries.append(summary) + if result.evidence_path: + text += f'\n记录:{result.evidence_path}' + lines.append(text) + message = '\n'.join(lines) if lines else '队列已取消,未执行任何项。' + self.status_label.setText('\n'.join(summaries) if summaries else message); self.output.append(message) + self.completed.emit(results) + + def _failed(self, error): + from ..management import ManagementResult + request = self.template + self._result([ManagementResult(request.operation, request.library, request.name, request.partition, + request.source, request.auto_verify, 'complete', 'RECOVERY_REQUIRED', False, str(error))]) + + def _finished(self): + self.busy = False; self._enabled(True) + + def reject(self): + if not self.busy: + super().reject() + + def closeEvent(self, event): + if self.busy: + self.stop.set(); event.ignore() + else: + super().closeEvent(event) diff --git a/src/cbb_refresh_verify/ui/pcb_restore_dialog.py b/src/cbb_refresh_verify/ui/pcb_restore_dialog.py new file mode 100644 index 0000000..bb3c57b --- /dev/null +++ b/src/cbb_refresh_verify/ui/pcb_restore_dialog.py @@ -0,0 +1,31 @@ +"""Show the native version dates without preselecting a recovery version.""" +from PySide6.QtWidgets import QMessageBox + + +class PcbRestoreDialog(QMessageBox): + def __init__(self, choice, parent=None): + super().__init__(parent) + self.choice = choice + self.setWindowTitle('选择 PCB 恢复版本') + self.setIcon(QMessageBox.Question) + candidates = {c['kind']: c for c in choice.candidates} + manual, auto = candidates['last_user_saved'], candidates['autosave'] + self.setText(f'CBB:{choice.block}\n中心库:{choice.library}\n\n' + '原生程序检测到上次异常退出,需要选择 PCB 恢复版本。\n' + f'最后手动保存:{manual["date"]}\n自动保存:{auto["date"]}\n\n' + '选择历史版本可能丢失此版本之后的修改。选择后继续校验、保存和状态确认;恢复版本仍需核对。' + '\n取消将停止本项并保留原生现场,不自动选取版本。') + self.manual_button = self.addButton(f'最后手动保存({manual["date"]})', QMessageBox.ActionRole) + self.auto_button = self.addButton(f'自动保存({auto["date"]})', QMessageBox.ActionRole) + self.manual_button.setEnabled(manual['enabled']) + self.auto_button.setEnabled(auto['enabled']) + self.cancel_button = self.addButton(QMessageBox.Cancel) + self.setDefaultButton(self.cancel_button) + self.setEscapeButton(self.cancel_button) + self.buttonClicked.connect(self._chosen) + self.finished.connect(lambda _: choice.choose('cancel')) + self.setModal(True) + + def _chosen(self, button): + self.choice.choose('last_user_saved' if button is self.manual_button else + 'autosave' if button is self.auto_button else 'cancel') diff --git a/tests/test_background_icdb.py b/tests/test_background_icdb.py new file mode 100644 index 0000000..5411d3c --- /dev/null +++ b/tests/test_background_icdb.py @@ -0,0 +1,75 @@ +from threading import Event, Thread +import time + + +def test_native_queue_is_fifo_and_waiting_cancel_never_runs_action(): + from cbb_refresh_verify.operation_queue import NativeQueue, QueueCancelled + queue = NativeQueue() + holding, release, waiting, cancelled = Event(), Event(), Event(), Event() + order = [] + first = Thread(target=lambda: queue.run(lambda: (holding.set(), release.wait(3), order.append('first')))) + first.start(); assert holding.wait(1) + def second(): + try: queue.run(lambda: order.append('cancelled'), stop=cancelled, waiting=waiting.set) + except QueueCancelled: pass + second_thread = Thread(target=second); second_thread.start(); assert waiting.wait(1) + cancelled.set(); second_thread.join(1); assert not second_thread.is_alive() + third = Thread(target=lambda: queue.run(lambda: order.append('third'))) + third.start(); release.set(); first.join(2); third.join(2) + assert order == ['first', 'third'] + + +def test_background_scan_keeps_ui_usable_and_yields_between_projects(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + from cbb_refresh_verify.verify_runner import VerifyResult + started, release = Event(), Event() + order = [] + def verify(request): + order.append(request.block_name) + if request.block_name == 'Beta': + started.set(); release.wait(3) + return VerifyResult('CHECKED') + window = load_window(qtbot, tmp_path, monkeypatch, verifier=verify) + window._run(['Beta', 'Gamma'], maintenance=True) + try: + qtbot.waitUntil(started.is_set) + assert not window.busy and window.search_edit.isEnabled() and window.load_button.isEnabled() + window.search_edit.setText('Gamma') + assert [r.name for r in window.visible_records()] == ['Gamma'] + window._start(lambda: order.append('foreground'), lambda _: None) + qtbot.wait(30) + assert order == ['Beta'] + release.set() + qtbot.waitUntil(lambda: not window.icdb_task.active and not window.busy) + assert order == ['Beta', 'foreground', 'Gamma'] + assert window.search_edit.text() == 'Gamma' + assert window.icdb_repair_button.isEnabled() + finally: + release.set() + + +def test_unconfirmed_open_is_amber_and_does_not_claim_icdb_damage(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + from cbb_refresh_verify.verify_runner import VerifyResult + window = load_window(qtbot, tmp_path, monkeypatch, verifier=lambda _: VerifyResult('FAIL', + error_category='DATABASE_SAFETY_STOP', stderr='Continue to open read/write?')) + window._run(['Beta'], maintenance=True) + qtbot.waitUntil(lambda: not window.icdb_task.active) + cell = window.cbb_table.item(window._row_by_name['Beta'], 3) + assert '未确认' in cell.text() and 'ICDB 错误' not in cell.text() + assert cell.background().color().name() == '#fff8e1' + + + + +def test_later_management_invalidates_old_recovery_offer(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + from test_reimport_recovery import failed_repair + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda _: failed_repair(tmp_path/'old/result.json', safe=True)) + window._run(['Beta'], maintenance=True) + qtbot.waitUntil(lambda: not window._icdb_active()) + action = next(b for b in window.icdb_summary.buttons() if '副本' in b.text()) + assert action.isEnabled() + window._invalidate_check_targets('test.lmc', ['Beta']) + assert not action.isEnabled() and not window._reimport_offers diff --git a/tests/test_background_queue_regressions.py b/tests/test_background_queue_regressions.py new file mode 100644 index 0000000..8120c07 --- /dev/null +++ b/tests/test_background_queue_regressions.py @@ -0,0 +1,122 @@ +"""Background check and foreground queue interaction regressions.""" +from threading import Event + +import pytest + +from test_ui_filters import load_window +from cbb_refresh_verify.verify_runner import VerifyResult + + +def background(window, qtbot): + started, release = Event(), Event() + calls=[] + def verify(request): + calls.append(request.block_name) + if request.block_name=='Beta': + started.set() + assert release.wait(5) + return VerifyResult('CHECKED') + window.verifier=verify + window._run(['Beta','Gamma'],maintenance=True) + qtbot.waitUntil(started.is_set) + return release,calls + + +def finish(window, qtbot, release): + release.set() + window.icdb_task.resume() + qtbot.waitUntil(lambda:not window._icdb_active() and not window.busy) + qtbot.waitUntil(lambda:window.pool.activeThreadCount()==0) + + +def test_stop_whole_queue_does_not_resume_background_checks(qtbot,tmp_path,monkeypatch): + window=load_window(qtbot,tmp_path,monkeypatch) + release,calls=background(window,qtbot) + try: + window._start(lambda:None,lambda _:None) + qtbot.waitUntil(lambda:bool(window.native_queue.pending)) + window.stop_button.click() + release.set() + qtbot.waitUntil(lambda:not window._icdb_active() and not window.busy) + assert calls==['Beta'],f'Cancelled queue still ran: {calls}' + finally:finish(window,qtbot,release) + + +def test_check_progress_survives_queued_verify(qtbot,tmp_path,monkeypatch): + window=load_window(qtbot,tmp_path,monkeypatch, + status_refresher=lambda names,path:{name:'PENDING' for name in names}) + release,calls=background(window,qtbot) + try: + assert not window.icdb_progress.isHidden() + window._run(['Gamma']) + assert not window.icdb_progress.isHidden(),'Queued verify hid the active check progress' + finally:finish(window,qtbot,release) + + +def test_release_failure_is_not_labelled_as_read_write_prompt(qtbot,tmp_path,monkeypatch): + window=load_window(qtbot,tmp_path,monkeypatch,verifier=lambda request:VerifyResult( + 'FAIL',error_category='DATABASE_SAFETY_STOP',safe_to_continue=False, + stderr='PCB_RELEASE_UNCONFIRMED: launcher still running')) + window._run(['Beta'],maintenance=True) + qtbot.waitUntil(lambda:not window._icdb_active()) + cell=window.cbb_table.item(window._row_by_name['Beta'],3) + assert '读写确认' not in cell.text(),cell.text() + + +def test_pending_check_skips_a_target_that_has_become_ready(qtbot,tmp_path,monkeypatch): + window=load_window(qtbot,tmp_path,monkeypatch) + release,calls=background(window,qtbot) + try: + window.icdb_task.pause() + release.set() + qtbot.waitUntil(lambda:len(window.icdb_task.results)==1 and not window.icdb_task.running) + window._apply_refreshed_records((('Gamma',),{'Gamma':'READY'},{},'')) + assert 'Gamma' in window.ready_names + window.icdb_task.resume() + qtbot.waitUntil(lambda:not window._icdb_active()) + assert calls==['Beta'],f'Already READY target was opened again: {calls}' + finally:finish(window,qtbot,release) + + +def test_worker_refresh_excludes_ready_before_any_gui_result_callback(qtbot,tmp_path,monkeypatch): + window=load_window(qtbot,tmp_path,monkeypatch, + status_refresher=lambda names,path:{name:'READY' for name in names}) + release,calls=background(window,qtbot) + try: + window._start(lambda:window._read_affected_records(('Gamma',)),lambda payload:None) + qtbot.waitUntil(lambda:bool(window.native_queue.pending)) + release.set() + qtbot.waitUntil(lambda:not window._icdb_active() and not window.busy) + assert window._records_by_name['Gamma'].status=='UNKNOWN' + assert calls==['Beta'] + assert window.icdb_task.results[1].status=='SKIPPED' + assert 'READY' in window.icdb_task.results[1].stderr + finally:finish(window,qtbot,release) + + +def test_another_library_ready_status_cannot_skip_this_library_target(qtbot,tmp_path,monkeypatch): + window=load_window(qtbot,tmp_path,monkeypatch) + release,calls=background(window,qtbot) + try: + window._publish_check_statuses('other.lmc',{'Gamma':'READY'}) + release.set() + qtbot.waitUntil(lambda:not window._icdb_active()) + assert calls==['Beta','Gamma'] + finally:finish(window,qtbot,release) + + +@pytest.mark.parametrize('detail,safe,expected',[ + ('Continue to open the design with read/write access permission?',True,'读写确认'), + ('PCB_RELEASE_UNCONFIRMED: launcher still running',False,'释放未确认'), + ('ICDB_RELEASE_UNCONFIRMED: database still occupied',False,'释放未确认'), + ('PCB_SESSION_ACTIVE: target already open',True,'会话或数据库状态待确认'), +]) +def test_safety_stop_label_tracks_actual_reason(qtbot,tmp_path,monkeypatch,detail,safe,expected): + window=load_window(qtbot,tmp_path,monkeypatch,verifier=lambda request:VerifyResult( + 'FAIL',error_category='DATABASE_SAFETY_STOP',safe_to_continue=safe,stderr=detail)) + window._run(['Beta'],maintenance=True) + qtbot.waitUntil(lambda:not window._icdb_active()) + cell=window.cbb_table.item(window._row_by_name['Beta'],3) + assert expected in cell.text() + assert cell.toolTip()==detail + assert cell.background().color().name()=='#fff8e1' diff --git a/tests/test_backup_recovery_dialog.py b/tests/test_backup_recovery_dialog.py index 071dfe6..03e747d 100644 --- a/tests/test_backup_recovery_dialog.py +++ b/tests/test_backup_recovery_dialog.py @@ -2,6 +2,13 @@ from pathlib import Path from threading import Event from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult +import pytest + + +@pytest.fixture(autouse=True) +def accept_manual_backup_reminder(monkeypatch): + from PySide6.QtWidgets import QMessageBox + monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) def test_backup_dialog_requires_a_project_and_passes_selected_target(qtbot, tmp_path): @@ -51,11 +58,12 @@ def test_backup_dialog_keeps_ui_responsive_and_cannot_close_during_restore(qtbot assert dialog.close_button.isEnabled() -def test_main_window_opens_simple_dialog_and_failure_clears_ready(qtbot, tmp_path): +def test_main_window_opens_non_ready_dialog_and_failure_retains_ready_untargeted(qtbot, tmp_path): from cbb_refresh_verify.ui.main_window import MainWindow from cbb_refresh_verify.library_reader import CbbRecord, LibraryReadResult window = MainWindow(reader=lambda _: LibraryReadResult(( - CbbRecord('A', 'LP', status='READY'), CbbRecord('B', 'LP'))), data_root=tmp_path) + CbbRecord('A', 'LP', status='READY'), CbbRecord('B', 'LP'))), data_root=tmp_path, + status_refresher=lambda names, _: {name: 'UNKNOWN' for name in names}) qtbot.addWidget(window) window.lmc_edit.setText('lib.lmc'); window.load_library() qtbot.waitUntil(lambda: not window.busy) @@ -63,12 +71,12 @@ def test_main_window_opens_simple_dialog_and_failure_clears_ready(qtbot, tmp_pat window.backup_restore_button.click() dialog = window.backup_dialog assert dialog.isVisible() - assert dialog.block_combo.currentText() == 'A' - dialog.started.emit('A') + assert dialog.block_combo.currentText() == 'B' + dialog.started.emit('B') assert window.busy - assert 'A' not in window.ready_names - dialog.completed.emit('A', VerifyResult('FAIL', stderr='损坏')) - assert window.cbb_table.item(0, 2).text() == '未知 / 需确认' + assert 'A' in window.ready_names + dialog.completed.emit('B', VerifyResult('FAIL', stderr='无法确认', safe_to_continue=False)) + assert window.cbb_table.item(1, 2).text() == '未知 / 需确认' dialog.reject() qtbot.waitUntil(lambda: not window.busy) diff --git a/tests/test_extended_safety.py b/tests/test_extended_safety.py index 307fb91..b72ac7a 100644 --- a/tests/test_extended_safety.py +++ b/tests/test_extended_safety.py @@ -174,6 +174,19 @@ def test_cli_unsafe_batch_preserves_created_drive(tmp_path, monkeypatch): assert lease.drive in backend.existing +def test_ui_unsafe_batch_preserves_created_drive(qtbot, tmp_path): + from test_network_path import FakeWNet + from cbb_refresh_verify.network_path import LibraryPathLease + from cbb_refresh_verify.ui.main_window import MainWindow + backend = FakeWNet() + lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend) + window = MainWindow(data_root=tmp_path) + qtbot.addWidget(window) + window.library_lease = lease + window._batch_done(([VerifyResult('FAIL', safe_to_continue=False)], tmp_path/'batch.log')) + window.close() + assert not backend.cancelled + assert lease.drive in backend.existing def test_legacy_library_reader_only_requests_owned_window_close(monkeypatch): diff --git a/tests/test_icdb_batch_check.py b/tests/test_icdb_batch_check.py new file mode 100644 index 0000000..6fb3112 --- /dev/null +++ b/tests/test_icdb_batch_check.py @@ -0,0 +1,159 @@ +"""Batch ICDB checks open diagnostically without dispatching Repair.""" +from dataclasses import replace +import json + +import pytest + +from test_maintenance_entry import case, no_native_launch + + +@pytest.mark.parametrize('scenario,status,category,safe', [ + ('healthy', 'CHECKED', '', True), + ('fault', 'FAIL', 'ICDB_REPAIR_REQUIRED', True), + ('generic', 'FAIL', 'MENTOR_DATABASE_LOAD_FAILED', True), + ('unreleased', 'FAIL', 'MENTOR_DATABASE_LOAD_FAILED', False), + ('cancelled', 'CANCELLED', '', True), +]) +def test_batch_check_opens_pcb_without_repair(case, monkeypatch, scenario, status, category, safe): + from cbb_refresh_verify import verify_runner as runner, native_repair, maintenance_entry as entry + from test_icdb_open_check import NATIVE_ERROR + request, _, address = case + calls = [] + def open_pcb(probe, **kwargs): + assert probe.diagnostic_only and not probe.maintenance and not probe.auto_repair + calls.append('open') + return runner.VerifyResult('PASS' if scenario=='healthy' else 'CANCELLED' if scenario=='cancelled' else 'FAIL', + stderr=NATIVE_ERROR if scenario=='fault' else '' if scenario in ('healthy','cancelled') else 'Failed to open document.', + error_category='' if scenario in ('healthy','cancelled') else 'MENTOR_DATABASE_LOAD_FAILED', + safe_to_continue=scenario!='unreleased') + monkeypatch.setattr(runner,'_run_verify_serialized',open_pcb) + monkeypatch.setattr(native_repair,'run_native_repair',lambda *a,**k:pytest.fail('scan requested Project Backup')) + monkeypatch.setattr(entry,'assert_native_idle',lambda:pytest.fail('scan used host-wide owner gate')) + result=runner.run_verify(replace(request,auto_repair=True)) + assert calls==['open'] + assert (result.status,result.error_category,result.safe_to_continue)==(status,category,safe) + assert result.library_flag=='UNKNOWN' and result.recovery_attempts==() + assert address.read_bytes()==b'old server address - preserved' + record=json.loads(result.evidence_path.read_text('utf-8')) + assert record['operation']=='icdb_batch_check' and record['automatic_repair'] is False + + +@pytest.mark.parametrize('before_launch',[True,False]) +def test_cancellation_never_dispatches_repair_or_reports_a_clean_check(case,monkeypatch,before_launch): + from threading import Event + from cbb_refresh_verify import verify_runner as runner + request,_,_=case + stop=Event();calls=[] + if before_launch:stop.set() + def open_pcb(probe,**kwargs): + calls.append('open');stop.set() + return runner.VerifyResult('PASS') + monkeypatch.setattr(runner,'_run_verify_serialized',open_pcb) + result=runner.run_verify(request,stop=stop) + assert result.status=='CANCELLED' and result.safe_to_continue + assert calls==([] if before_launch else ['open']) + + +def test_released_icdb_fault_continues_the_check_batch(case,monkeypatch): + from cbb_refresh_verify import verify_runner as runner + from test_icdb_open_check import NATIVE_ERROR + request,_,_=case + calls=[] + def open_pcb(probe,**kwargs): + calls.append('open') + return runner.VerifyResult('FAIL',stderr=NATIVE_ERROR) if len(calls)==1 else runner.VerifyResult('PASS') + monkeypatch.setattr(runner,'_run_verify_serialized',open_pcb) + results=runner.run_batch([request,request]) + assert calls==['open','open'] + assert [result.status for result in results]==['FAIL','CHECKED'] + + +def test_inspection_ignores_other_pcb_and_skips_exclusive_repair_probe(tmp_path, monkeypatch): + import win32con + from test_native_repair import repair_worker_fixture + from test_native_occupancy import output + ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active') + data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True + job.write_text(json.dumps(data), encoding='utf-8') + monkeypatch.setattr('cbb_refresh_verify.mentor_adapter.pcb_processes', lambda: [(999, 'other.pcb', '')]) + monkeypatch.setattr('cbb_refresh_verify.native_repair.check_repair_access', + lambda *a: pytest.fail('inspection used exclusive Repair admission')) + monkeypatch.setattr(ui, '_repair_command', lambda *a: pytest.fail('inspection resolved Repair command')) + monkeypatch.setattr(ui, '_native_output', lambda *_: output(data['project'], data['database'], busy=True)) + assert ui.repair_worker_main(job) == 0 + assert actions == [(100, win32con.WM_CLOSE)] + + +def test_ui_check_summary_reports_findings_and_never_claims_repair(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + from cbb_refresh_verify.verify_runner import VerifyResult + from PySide6.QtWidgets import QMessageBox + requests, prompts = [], [] + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda req: (requests.append(req) or VerifyResult('FAIL', + error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。')), + status_refresher=lambda names, _: {name: 'PENDING' for name in names}) + monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (prompts.append(a[2]) or QMessageBox.Yes)) + window.search_edit.setText('Beta') + window.icdb_repair_button.click(); qtbot.waitUntil(lambda: not window._icdb_active()) + assert requests[0].maintenance and not requests[0].auto_repair + assert '批量检查' in window.icdb_repair_button.text() + assert not any('手动备份' in text for text in prompts) + assert window.summary.windowTitle() == 'ICDB 批量检查结果' + assert '发现问题 1' in window.summary.text() + assert '修复并校验通过' not in window.summary.detailedText() + + +@pytest.mark.parametrize('category,label', [('ICDB_DATABASE_IN_USE', '占用 1'), + ('ICDB_INSPECTION_UNCONFIRMED', '无法确认 1')]) +def test_busy_or_unknown_inspection_is_not_labelled_as_database_damage(qtbot, tmp_path, monkeypatch, category, label): + from test_ui_filters import load_window + from cbb_refresh_verify.verify_runner import VerifyResult + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda _: VerifyResult('FAIL', error_category=category, stderr='暂未完成检查。'), + status_refresher=lambda names, _: {name: 'PENDING' for name in names}) + window.search_edit.setText('Beta') + window.icdb_repair_button.click(); qtbot.waitUntil(lambda: not window._icdb_active()) + assert label in window.summary.text() + assert 'ICDB 问题' not in window.cbb_table.item(window._row_by_name['Beta'], 3).text() + + +def test_missing_pcb_is_skipped_from_icdb_batch_check_and_restore(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + from cbb_refresh_verify.models import CbbRecord + from cbb_refresh_verify.verify_runner import VerifyResult + calls = [] + window = load_window(qtbot, tmp_path, monkeypatch, + records=(CbbRecord('Missing', 'Power', status='PENDING'),), + verifier=lambda req: (calls.append(req.block_name) or VerifyResult('CHECKED')), + status_refresher=lambda names, _: {name: 'PENDING' for name in names}) + assert not window.icdb_repair_button.isEnabled() + assert not window.batch_button.isEnabled() and not window.backup_restore_button.isEnabled() + assert calls == [] + + +def test_missing_project_rows_are_excluded_from_icdb_batch_check(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + from cbb_refresh_verify.models import CbbRecord + from cbb_refresh_verify.verify_runner import VerifyResult + window = load_window(qtbot, tmp_path, monkeypatch, + records=(CbbRecord('Missing', 'Power', status='PENDING'), + CbbRecord('Good', 'Power', status='PENDING')), + verifier=lambda req: VerifyResult('CHECKED'), + status_refresher=lambda names, _: {name: 'PENDING' for name in names}) + window.skipped_names.add('Missing') + window._update() + assert window._maintenance_names() == ['Good'] + + +def test_check_reports_describe_inspection_without_pcb_verification(case, tmp_path): + from cbb_refresh_verify.verify_runner import write_batch_report, failure_report_path, VerifyResult + request, _, _ = case + report = write_batch_report([request], [VerifyResult('FAIL', + error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。')], tmp_path/'reports') + full = report.read_text('utf-8-sig') + failed = failure_report_path(report).read_text('utf-8-sig') + assert 'ICDB 批量检查' in full and 'Project Integration' not in full + assert 'PCB 打开检查' in full and 'Project Backup 加载检查' not in full + assert 'ICDB 检查异常' in failed and '发现问题: 1' in failed + assert 'ICDB已修复待校验' not in failed diff --git a/tests/test_independent_operations.py b/tests/test_independent_operations.py new file mode 100644 index 0000000..276e94b --- /dev/null +++ b/tests/test_independent_operations.py @@ -0,0 +1,181 @@ +from pathlib import Path + +import pytest +from test_maintenance_entry import case + + +def test_verify_defaults_to_no_repair_and_does_not_retain_a_failure_lock(tmp_path, monkeypatch): + from cbb_refresh_verify import verify_runner as runner, library_lock as locks, native_repair + library = tmp_path / 'library.lmc'; library.touch() + req = runner.VerifyRequest(library, 'CBB', tmp_path / 'evidence') + assert req.auto_repair is False + marker = locks.blocker_path(library) + marker.write_text('historical diagnostic record') + calls = [] + result = runner.VerifyResult('FAIL', stderr='ICDB_REPAIR_REQUIRED: session lost', + error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=True) + monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: (calls.append('verify') or result)) + monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **k: pytest.fail('verify requested Repair')) + assert runner.run_verify(req) is result + assert runner.run_verify(req) is result + assert calls == ['verify', 'verify'] + assert marker.read_text() == 'historical diagnostic record' + assert locks._key(tmp_path / '.library.cbb-upload.lock') not in locks._owners + + +def test_catalog_checkpoint_does_not_disable_ordinary_verify(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + from cbb_refresh_verify.verify_runner import VerifyResult + calls = [] + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda req: (calls.append(req) or VerifyResult('FAIL', stderr='ICDB_REPAIR_REQUIRED: lost', + error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=True)), + status_refresher=lambda names, _: {name: 'PENDING' for name in names}) + window._maintenance_recovery_view = True + window._management_unsafe = True + window.search_edit.setText('Beta'); window.select_visible_button.click(); window._update() + assert window.selected_batch_button.isEnabled() + window.verify_selected(); qtbot.waitUntil(lambda: not window.busy) + assert len(calls) == 1 and not calls[0].maintenance and not calls[0].auto_repair + assert window.selected_batch_button.isEnabled() + assert 'ICDB' in window.cbb_table.item(window._row_by_name['Beta'], 3).text() + + +def test_management_release_block_is_scoped_to_the_loaded_library(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + from cbb_refresh_verify.management import Capability + adapter = type('Adapter', (), { + 'capabilities': lambda self: {name: Capability(True, 'available') + for name in ('add', 'update', 'remove')}})() + window = load_window(qtbot, tmp_path, monkeypatch, management_adapter=adapter) + window._management_unsafe = True + window._management_unsafe_library = (tmp_path/'library-a.lmc').resolve() + window.lmc_edit.setText(str(tmp_path/'library-b.lmc')) + window.loaded_path = str(tmp_path/'library-b.lmc') + window.mentor_lmc_path = Path(window.loaded_path) + window.select_visible_button.click() + window._update() + assert window.add_button.isEnabled() + assert '上次管理操作' not in window._management_block_reason('update') + + +def test_loading_a_different_library_clears_old_management_block(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + window = load_window(qtbot, tmp_path, monkeypatch) + old = (tmp_path/'library-a.lmc').resolve() + window._management_unsafe = True + window._management_unsafe_library = old + window.lmc_edit.setText(str(tmp_path/'library-b.lmc')) + window.load_library() + qtbot.waitUntil(lambda: not window.busy) + assert not window._management_unsafe + assert window._management_unsafe_library is None + + +def test_targeted_native_idle_ignores_unrelated_native_command(tmp_path, monkeypatch): + from cbb_refresh_verify import maintenance_entry as entry + from cbb_refresh_verify.native_repair import RepairTarget + work = tmp_path/'target/Work'; work.mkdir(parents=True) + library = tmp_path/'library.lmc'; library.touch() + project = work/'target.prj' + project.write_text(f'KEY CentralLibrary "{library}"\n', encoding='utf-8') + other_pcb = tmp_path/'other/Work/PCB/other.pcb' + monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names: [ + {'pid': 10, 'name': 'ExpeditionPCB.exe', 'command': f'ExpeditionPCB.exe "{other_pcb}"'}, + ]) + entry.assert_native_idle(RepairTarget(project, work/'database')) + + +def test_maintenance_guard_does_not_scan_other_cbb_projects(case, monkeypatch): + from cbb_refresh_verify import maintenance_entry as entry + from cbb_refresh_verify import scoped_manifest as manifests + req, project, _ = case + scans = [] + scan = manifests.scan_tree + monkeypatch.setattr(manifests, 'scan_tree', lambda root, **kw: (scans.append(Path(root)) or scan(root, **kw))) + with entry.maintenance_target_guard(req): + pass + assert req.lmc_file.parent not in scans + assert scans.count(project.parent) == 2 + + +def test_repair_finishes_without_calling_verify(case, monkeypatch): + from cbb_refresh_verify import native_repair, verify_runner as runner + from test_maintenance_entry import patch_verification_after_fault, run_legacy_maintenance + from test_native_repair import complete_native_success + req, _, address = case + def repair(target, *a, **kw): + address.unlink() + return complete_native_success(target) + monkeypatch.setattr(native_repair, 'run_native_repair', repair) + monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release']) + patch_verification_after_fault(monkeypatch, runner, lambda *a, **k: pytest.fail('maintenance started CBB verification')) + result = run_legacy_maintenance(req) + assert result.status == 'REPAIRED' and result.safe_to_continue + assert result.library_flag == 'UNKNOWN' + assert result.recovery_attempts[0]['validation_passed'] is False + + +@pytest.mark.parametrize('stage,expected_safe', [('PCB_STARTING', True), ('back_annotation', True)]) +def test_released_failure_can_continue_from_icdb_diagnosis(tmp_path, monkeypatch, stage, expected_safe): + import json + from cbb_refresh_verify import verify_runner as runner + library = tmp_path/'library.lmc'; library.touch() + evidence = tmp_path/'evidence'; evidence.mkdir() + report = evidence/'result.json'; report.write_text('{}') + (evidence/'session-release.json').write_text(json.dumps({'library': str(library), + 'block': 'CBB', 'worker_exited': True, 'safe_to_continue': True})) + failure = runner.VerifyResult('FAIL', stderr='ICDB_REPAIR_REQUIRED: lost session', + error_stage=stage, safe_to_continue=False, evidence_path=report) + monkeypatch.setattr(runner, '_run_verify', lambda *a, **k: failure) + result = runner._run_verify_serialized(runner.VerifyRequest(library, 'CBB', evidence)) + assert result.status == 'FAIL' and result.error_category == 'ICDB_REPAIR_REQUIRED' + assert result.safe_to_continue is expected_safe + + +def test_live_writer_keeps_execution_lock_without_a_permanent_diagnostic_blocker(tmp_path, monkeypatch): + import win32con, win32file + from cbb_refresh_verify import library_lock as locks, verify_runner as runner + library = tmp_path/'lib.lmc'; library.touch() + monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: + runner.VerifyResult('TIMEOUT', safe_to_continue=False)) + result = runner.run_verify(runner.VerifyRequest(library, 'CBB', tmp_path/'evidence')) + lock = locks.LibraryLock(library) + try: + assert not result.safe_to_continue and not locks.blocker_path(library).exists() + with pytest.raises(Exception): + win32file.CreateFile(str(lock.path), win32con.GENERIC_READ | win32con.GENERIC_WRITE, + 0, None, win32con.OPEN_ALWAYS, 0, None) + finally: + with locks._guard: + owner = locks._owners.pop(lock.key, None) + if owner: owner['handle'].Close() + + +def test_healthy_open_with_old_address_does_not_lock_management(case, monkeypatch): + from cbb_refresh_verify import native_repair, verify_runner as runner, library_lock as locks + request, project, address = case + monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **kw: runner.VerifyResult('PASS')) + monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **kw: pytest.fail('scan requested Project Backup')) + result = runner.run_verify(request) + assert result.status == 'CHECKED' and result.safe_to_continue and address.exists() + assert not result.stderr and '未发现 ICDB 错误' in result.stdout + assert not locks.blocker_path(request.lmc_file).exists() + with locks.LibraryLock(request.lmc_file): pass + + +@pytest.mark.parametrize('operation', ['verify', 'maintenance']) +def test_retained_execution_lease_can_retry_after_its_actual_client_exits(tmp_path, operation): + from contextlib import contextmanager + from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy + library = tmp_path/'library.lmc'; library.touch() + released = [False] + with LibraryLock(library, checkpoint=False, safe_to_release=lambda: released[0]): pass + with pytest.raises(LibraryBusy): + with LibraryLock(library, checkpoint=False): pass + released[0] = True + @contextmanager + def guard(): yield {'target': 'isolated fixture'} + lock = (LibraryLock(library, checkpoint=False) if operation == 'verify' else + LibraryLock.for_maintenance(library, tmp_path/'archive', guard, safe_to_release=lambda: True)) + with lock: pass diff --git a/tests/test_maintenance_review.py b/tests/test_maintenance_review.py new file mode 100644 index 0000000..0c20183 --- /dev/null +++ b/tests/test_maintenance_review.py @@ -0,0 +1,171 @@ +from pathlib import Path +import pytest +from PySide6.QtCore import Qt + + +def test_ready_rows_never_enter_maintenance_even_when_unchecked(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window, MIXED + window = load_window(qtbot, tmp_path, monkeypatch, records=(MIXED[0],)) + assert window._maintenance_names() == [] + assert not window.icdb_repair_button.isEnabled() + assert not window.backup_restore_button.isEnabled() + window.select_visible_button.click() + assert window._maintenance_names() == [] + + +def test_selected_ready_rows_are_ignored_in_mixed_maintenance(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + window = load_window(qtbot, tmp_path, monkeypatch) + window.select_visible_button.click() + assert window._maintenance_names() == ['Beta', 'Gamma', 'Delta'] + window._apply_refreshed_records((('Beta', 'Gamma'), {'Beta': 'READY', 'Gamma': 'READY'}, {}, '')) + assert window._maintenance_names() == ['Delta'] + assert window.icdb_repair_button.isEnabled() + + +def test_diagnostic_worker_closes_without_integration_save_or_config_edit(tmp_path, monkeypatch): + from test_verify_worker_stability import exercise_worker + from cbb_refresh_verify import mentor_adapter as adapter + job, events, execute = diagnostic_worker(tmp_path, monkeypatch) + job['diagnostic_only'] = True + def forbidden(*args, **kwargs): + pytest.fail('diagnosis attempted integration/save/config rewrite') + monkeypatch.setattr(adapter, 'ensure_pcb_central_library', forbidden) + monkeypatch.setattr(adapter, 'pcb_log_reports_integration_error', forbidden) + original_read = Path.read_bytes + def read_bytes(path): + if path.name in ('ForwardAnnotation.txt', 'MsgBoxResponse.log', 'PartPkg.log'): + pytest.fail('opening check read unrelated integration history') + return original_read(path) + monkeypatch.setattr(Path, 'read_bytes', read_bytes) + monkeypatch.setattr('cbb_refresh_verify.integration.refresh_integration', forbidden) + monkeypatch.setattr('cbb_refresh_verify.desktop_worker.launch_save_helper', forbidden) + monkeypatch.setattr('cbb_refresh_verify.pcb_bridge.wait_for_target_document', forbidden) + monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document', forbidden) + closes = [] + def check(job, pid, **kw): + assert pid == 2 and kw['launcher_process'].pid == 1 + assert job['diagnostic_log_baseline']['started_ns'] + closes.append(job) + kw['emit'](stage='diagnostic_wm_close') + return {'status': 'PASS', 'native_processes_exited': True} + monkeypatch.setattr('cbb_refresh_verify.diagnostic_open.check_target_window', check) + result = execute() + from cbb_refresh_verify.verify_runner import VerifyResult + assert VerifyResult(**result).status == 'PASS' + assert result['status'] == 'PASS' + assert len(closes) == 1 + assert not any(e['stage'] in ('save_start', 'saved_and_closed') for e in events) + + +def test_diagnostic_close_failure_never_returns_healthy(tmp_path, monkeypatch): + from test_verify_worker_stability import exercise_worker + job, events, execute = diagnostic_worker(tmp_path, monkeypatch) + job['diagnostic_only'] = True + closes = [] + def check(*a, **kw): + closes.append(a) + kw['emit'](stage='diagnostic_wm_close') + raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED') + monkeypatch.setattr('cbb_refresh_verify.diagnostic_open.check_target_window', check) + monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_startup', + lambda *a, **kw: pytest.fail('must not send another close after WM_CLOSE')) + with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'): + execute() + assert len(closes) == 1 + + +@pytest.mark.parametrize('prefix', ['KEY CentralLibrary ', ' KEY CentralLibrary ', 'KEY\tCentralLibrary\t']) +def test_diagnosis_rejects_foreign_library_reference_before_native_launch(tmp_path, monkeypatch, prefix): + from test_verify_worker_stability import exercise_worker + from cbb_refresh_verify import mentor_adapter as adapter + job, events, execute = diagnostic_worker(tmp_path, monkeypatch) + job['diagnostic_only'] = True + project = Path(job['project']) + project.write_text(prefix + '"foreign.lmc"\n') + monkeypatch.setattr(adapter, 'launch_pcb_process', lambda *a: pytest.fail('foreign library opened')) + with pytest.raises(ValueError, match='DIAGNOSTIC_LIBRARY_MISMATCH'): + execute() + +def diagnostic_worker(tmp_path, monkeypatch): + from test_verify_worker_stability import exercise_worker + job, events, execute = exercise_worker(tmp_path, monkeypatch) + (Path(job['pcb']).parent/'pcb.prj').write_text( + 'KEY CentralLibrary "' + job['lmc_file'] + '"\n', encoding='utf-8') + monkeypatch.setattr('cbb_refresh_verify.diagnostic_open.check_target_window', + lambda *a, **kw: {'status': 'PASS', 'native_processes_exited': True}) + return job, events, execute + + +def test_diagnostic_runner_skips_importer_and_ready_verification(tmp_path, monkeypatch): + import json + from test_verify_runner import fixture, request, PORTS_OK + from cbb_refresh_verify.verify_runner import run_verify + fixture(tmp_path) + captured = {} + class FinishedWorker: + desktop = None + returncode = 0 + def __init__(self, command, name, **kwargs): + job = Path(command[-1]) + captured.update(json.loads(job.read_text('utf-8'))) + job.with_name('outcome.json').write_text('{"status":"PASS"}', encoding='utf-8') + def poll(self): return 0 + def close(self): pass + monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', FinishedWorker) + def forbidden(*a, **kw): pytest.fail('diagnosis must not run importer or query READY') + result = run_verify(request(tmp_path, diagnostic_only=True, auto_repair=False, + libspec='configured', dms_login_config='configured'), port_check=PORTS_OK, + flag_reader=forbidden, process_runner=forbidden) + assert result.status == 'PASS' and result.library_flag == 'UNKNOWN' + assert captured['diagnostic_only'] is True + + +def test_diagnostic_cannot_pass_with_unconfirmed_process_exit(tmp_path, monkeypatch): + from cbb_refresh_verify import mentor_adapter as adapter + job, events, execute = diagnostic_worker(tmp_path, monkeypatch) + job['diagnostic_only'] = True + monkeypatch.setattr(adapter, 'cleanup_verify_processes', + lambda *a, **kw: {'safe_to_continue': False, 'remaining_pids': [2]}) + with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'): + execute() + + +@pytest.mark.parametrize('when', ['document_ready', 'closing']) +def test_diagnostic_checks_late_startup_errors_before_declaring_healthy(tmp_path, monkeypatch, when): + from cbb_refresh_verify import mentor_adapter as adapter + job, events, execute = diagnostic_worker(tmp_path, monkeypatch) + job['diagnostic_only'] = True + source = Path(job['pcb']).parent/'LogFiles/PCBLogFile.txt' + def late_fault(): + source.parent.mkdir(exist_ok=True) + source.write_text("The last server session on different server machine lost the connection to the database. " + f"Machine:[fixture] Path:[{Path(job['project']).parent/'database'}] session:[current]", encoding='utf-8') + closes = [] + def check(*a, **kw): + if when == 'document_ready': + late_fault() + raise RuntimeError(kw['error_reader']()) + closes.append(True) + kw['emit'](stage='diagnostic_wm_close') + late_fault() + return {'status': 'PASS', 'native_processes_exited': True} + monkeypatch.setattr('cbb_refresh_verify.diagnostic_open.check_target_window', check) + monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_startup', + lambda *a, **kw: {'status': 'CLOSED'}) + with pytest.raises(RuntimeError, match='ICDB_REPAIR_REQUIRED'): + execute() + assert len(closes) == (1 if when == 'closing' else 0) + assert not any(e['stage'] == 'diagnostic_complete' for e in events) + + +def test_diagnostic_snapshot_is_before_launch(tmp_path, monkeypatch): + from cbb_refresh_verify import mentor_adapter as adapter + job, events, execute = diagnostic_worker(tmp_path, monkeypatch) + job['diagnostic_only'] = True + def launch(*a): + assert job.get('diagnostic_log_baseline', {}).get('started_ns') + from types import SimpleNamespace + return SimpleNamespace(pid=1) + monkeypatch.setattr(adapter, 'launch_pcb_process', launch) + assert execute()['status'] == 'PASS' diff --git a/tests/test_maintenance_ui.py b/tests/test_maintenance_ui.py new file mode 100644 index 0000000..cc5ec08 --- /dev/null +++ b/tests/test_maintenance_ui.py @@ -0,0 +1,75 @@ +import json +from pathlib import Path + +import pytest +from PySide6.QtCore import Qt +from PySide6.QtWidgets import QMessageBox + + +def test_only_confirmed_maintenance_sets_explicit_flag(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + from cbb_refresh_verify.verify_runner import VerifyResult + calls = [] + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda req: (calls.append(req) or VerifyResult('FAIL', safe_to_continue=True)), + status_refresher=lambda names, path: {name: 'PENDING' for name in names}) + window.search_edit.setText('Beta') + window.verify_all(); qtbot.waitUntil(lambda: not window.busy) + assert calls and calls[-1].maintenance is False + monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.No) + window.repair_icdb_all(); assert len(calls) == 1 + monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) + window.repair_icdb_all(); qtbot.waitUntil(lambda: not window._icdb_active()) + assert len(calls) == 2 and calls[-1].maintenance is True + + + + +def test_maintenance_summary_exposes_first_failure_reason(qtbot, tmp_path): + from cbb_refresh_verify.ui.main_window import MainWindow + from cbb_refresh_verify.verify_runner import VerifyResult + window = MainWindow(data_root=tmp_path) + qtbot.addWidget(window) + window._global_icdb_run = True + detail = 'MAINTENANCE_TARGET_UNCONFIRMED: PCB 引用与当前工程不一致' + window._batch_done(([VerifyResult('BLOCKED', stderr=detail, safe_to_continue=False)], tmp_path/'batch.log')) + assert detail in window.summary.detailedText() + assert detail in window.output.toPlainText() + assert detail not in window.summary.text() + assert str(tmp_path) not in window.summary.text() + assert detail not in window.status_label.text() + assert '无法确认 1' in window.summary.text() + + +def test_open_check_preserves_verify_state_without_starting_an_extra_catalog_read(qtbot, tmp_path, monkeypatch): + from cbb_refresh_verify.library_lock import LibraryLock, blocker_path, _owners, _guard + from cbb_refresh_verify.ui.main_window import MainWindow + from cbb_refresh_verify.models import LibraryReadResult, CbbRecord + from cbb_refresh_verify.verify_runner import VerifyResult + import cbb_refresh_verify.ui.main_window as ui + library = tmp_path/'library/mentor.lmc'; library.parent.mkdir(); library.touch() + (library.parent/'ReusableBlocksLP/IP101GR').mkdir(parents=True) + with LibraryLock(library, safe_to_release=lambda: False) as lease: pass + with _guard: + owner = _owners.pop(lease.key, None) + if owner: owner['handle'].Close() + reads = [] + def reader(path): + reads.append(path) + return LibraryReadResult((CbbRecord('IP101GR', 'Reusable Blocks', status='PENDING'),)) + def verify(req): + assert req.maintenance + blocker_path(library).unlink() # Simulate normal cleanup at the injected boundary. + return VerifyResult('CHECKED') + monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *a: None) + monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) + window = MainWindow(reader=reader, verifier=verify, data_root=tmp_path/'data', + status_refresher=lambda *a: pytest.fail('An open check must not start a second native status read')) + qtbot.addWidget(window) + window.lmc_edit.setText(str(library)); window.load_library(); qtbot.waitUntil(lambda: not window.busy) + assert len(reads) == 1 + window.search_edit.setText('IP101') + window.repair_icdb_all() + qtbot.waitUntil(lambda: not window._icdb_active()) + assert window.visible_records()[0].status == 'PENDING' and len(reads) == 1 + assert not window._maintenance_recovery_view and window.search_edit.text() == 'IP101' diff --git a/tests/test_management_ui.py b/tests/test_management_ui.py new file mode 100644 index 0000000..5166bc0 --- /dev/null +++ b/tests/test_management_ui.py @@ -0,0 +1,113 @@ +from dataclasses import replace +from pathlib import Path +from types import SimpleNamespace + +from PySide6.QtCore import Qt +from PySide6.QtWidgets import QMessageBox + +from cbb_refresh_verify.models import CbbRecord, LibraryReadResult + + +def test_management_can_select_ready_and_capability_disabled_explanation(qtbot, tmp_path, monkeypatch): + from cbb_refresh_verify.management import Capability + from cbb_refresh_verify.ui.main_window import MainWindow + caps = {name: Capability(name == 'remove', name + ' not validated') for name in ('add', 'update', 'remove')} + window = MainWindow(reader=lambda _: LibraryReadResult((CbbRecord('Ready', 'Logical-Physical', status='READY'),)), + data_root=tmp_path, management_adapter=SimpleNamespace(capabilities=lambda: caps)) + qtbot.addWidget(window) + window.lmc_edit.setText('library.lmc'); window.load_library() + qtbot.waitUntil(lambda: not window.busy) + window.select_visible_button.click() + assert window.remove_button.isEnabled() + assert not window.add_button.isEnabled() and not window.update_button.isEnabled() + assert 'not validated' in window.management_capability_label.text() + assert not window.selected_batch_button.isEnabled() + window.remove_button.click() + assert window.management_dialog.requests()[0].name == 'Ready' + assert window.management_dialog.requests()[0].partition == 'Logical-Physical' + window.management_dialog.reject() + + +def test_management_dialog_preview_confirmation_and_result_status(qtbot, tmp_path, monkeypatch): + from cbb_refresh_verify.management import ManagementRequest, ManagementResult + from cbb_refresh_verify.ui.management_dialog import ManagementDialog + requests = [ManagementRequest('remove', tmp_path/'lib.lmc', 'Block', evidence_dir=tmp_path/'out')] + calls, confirmations = [], [] + def runner(items, **_): + calls.extend(items) + return [ManagementResult('remove', items[0].library, 'Block', 'Logical-Physical', None, + False, 'complete', 'REMOVED', True, 'removed', tmp_path/'checkpoint.json')] + dialog = ManagementDialog(requests, runner=runner) + qtbot.addWidget(dialog) + monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (confirmations.append(a[2]) or QMessageBox.No)) + dialog.execute_button.click() + assert not calls and 'Block' in confirmations[0] and '手动备份' in confirmations[0] + monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) + dialog.execute_button.click() + qtbot.waitUntil(lambda: not dialog.busy) + assert len(calls) == 1 and '已移除' in dialog.status_label.text() + assert str(tmp_path/'checkpoint.json') in dialog.output.toPlainText() + assert not dialog.execute_button.isEnabled() + + +def test_add_dialog_default_auto_verify_and_source_identity_rows(qtbot, tmp_path): + from cbb_refresh_verify.management import ManagementRequest + from cbb_refresh_verify.ui.management_dialog import ManagementDialog + dialog = ManagementDialog([ManagementRequest('add', tmp_path/'lib.lmc', '', evidence_dir=tmp_path/'out')]) + qtbot.addWidget(dialog) + dialog.add_sources([tmp_path/'One.prj', tmp_path/'Two.prj']) + requests = dialog.requests() + assert [r.name for r in requests] == ['One', 'Two'] + assert all(r.auto_verify and r.source.suffix == '.prj' for r in requests) + dialog.auto_verify.setChecked(False) + assert not any(r.auto_verify for r in dialog.requests()) + dialog._progress({'stage': 'prepare_identity', 'block': 'One'}) + assert '正在核对来源工程内容' in dialog.status_label.text() + assert 'prepare_identity' not in dialog.status_label.text() + + +def test_restart_shows_unfinished_without_starting_worker(qtbot, tmp_path): + import json + from cbb_refresh_verify.management import Capability + from cbb_refresh_verify.ui.main_window import MainWindow + checkpoint = tmp_path/'management/interrupted/checkpoint.json' + checkpoint.parent.mkdir(parents=True) + checkpoint.write_text(json.dumps({'status': 'RUNNING', 'stage': 'native_remove', 'name': 'Block'}), encoding='utf-8') + adapter = SimpleNamespace(capabilities=lambda: {n: Capability(False, 'disabled') for n in ('add', 'update', 'remove')}) + window = MainWindow(data_root=tmp_path, management_adapter=adapter) + qtbot.addWidget(window) + assert '未完成' in window.unfinished_label.text() and not window.busy + assert 'Block' in window.output.toPlainText() + + +def test_previous_unsafe_result_allows_retry_and_requires_matching_release_proof(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + from cbb_refresh_verify.management import Capability, ManagementResult + adapter = SimpleNamespace(capabilities=lambda: {op: Capability(True, 'available') + for op in ('add', 'update', 'remove')}) + window = load_window(qtbot, tmp_path, monkeypatch, management_adapter=adapter) + library = Path(window.mentor_lmc_path or window.loaded_path) + from cbb_refresh_verify.network_path import LibraryPathLease + current = LibraryPathLease(library, library) + current.retain_for_recovery() + window.library_lease = current + window._management_unsafe = True + window._management_unsafe_library = library + window.select_visible_button.click() + assert window.remove_button.isEnabled(), 'A historical flag must not disable the fresh release check' + window.remove_button.click() + requests = window.management_dialog.requests() + assert requests and all(r.check_previous_release for r in requests) + result = ManagementResult('remove', library, 'Beta', 'Logical-Physical', None, + False, 'complete', 'BLOCKED', True, 'prelaunch failure') + window._management_completed([result]) + assert window._management_library_unsafe(library), 'An input failure does not prove the previous session released' + assert current._retained_for_recovery + proof = {'status': 'RELEASE_CONFIRMED', 'library': str(library), 'evidence_path': 'proof.json'} + window._management_completed([replace(result, release_proof=proof)]) + qtbot.waitUntil(lambda: window._mapping_busy == 0) + assert not window._management_library_unsafe(library) + assert not current._retained_for_recovery + window.management_dialog.reject() + + diff --git a/tests/test_manual_backup_ui.py b/tests/test_manual_backup_ui.py new file mode 100644 index 0000000..636371f --- /dev/null +++ b/tests/test_manual_backup_ui.py @@ -0,0 +1,51 @@ +from pathlib import Path +import pytest +from PySide6.QtWidgets import QMessageBox + + +@pytest.mark.parametrize('operation', ['add', 'update', 'remove']) +def test_management_prompts_for_manual_backup_and_cancel_starts_nothing(qtbot, tmp_path, monkeypatch, operation): + from cbb_refresh_verify.management import ManagementRequest + from cbb_refresh_verify.ui.management_dialog import ManagementDialog + source = tmp_path/'Block.prj'; source.touch() + seen, calls = [], [] + monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (seen.append(a[2]) or QMessageBox.No)) + dialog = ManagementDialog([ManagementRequest(operation, tmp_path/'lib.lmc', 'Block', source=source)], + runner=lambda *a, **k: calls.append(a)) + qtbot.addWidget(dialog) + dialog.execute_button.click() + assert not calls and not dialog.busy + assert len(seen) == 1 and '手动备份' in seen[0] and '不会自动备份' in seen[0] + assert '完整备份与检查点' not in seen[0] + + +@pytest.mark.parametrize('action', ['verify_all', 'verify_selected']) +def test_batch_prompts_once_for_manual_backup_and_cancel_does_not_start(qtbot, tmp_path, monkeypatch, action): + from cbb_refresh_verify.ui.main_window import MainWindow + from cbb_refresh_verify.models import CbbRecord, LibraryReadResult + window = MainWindow(reader=lambda _: LibraryReadResult((CbbRecord('Block', 'LP'),)), data_root=tmp_path) + qtbot.addWidget(window) + window.lmc_edit.setText('library.lmc'); window.load_library() + qtbot.waitUntil(lambda: not window.busy) + window.select_visible_button.click() + seen, calls = [], [] + monkeypatch.setattr(window, '_run', lambda *a, **k: calls.append(a)) + monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (seen.append(a[2]) or QMessageBox.No)) + getattr(window, action)() + assert not calls + assert len(seen) == 1 and '手动备份' in seen[0] and '不会自动备份' in seen[0] + + +def test_restore_prompts_for_manual_backup_before_starting_worker(qtbot, tmp_path, monkeypatch): + from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult + from cbb_refresh_verify.ui.backup_recovery_dialog import BackupRecoveryDialog + calls, seen = [], [] + source = tmp_path/'Block.prj'; source.touch() + monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (seen.append(a[2]) or QMessageBox.No)) + dialog = BackupRecoveryDialog(['Block'], lambda n: VerifyRequest(tmp_path/'lib.lmc', n, tmp_path/'out'), + recoverer=lambda *a, **k: (calls.append(a) or VerifyResult('PASS'))) + qtbot.addWidget(dialog) + dialog.source_edit.setText(str(source)); dialog.restore_button.click() + qtbot.waitUntil(lambda: not dialog.busy) + assert not calls + assert len(seen) == 1 and '手动备份' in seen[0] and '不会自动备份' in seen[0] diff --git a/tests/test_native_backup.py b/tests/test_native_backup.py new file mode 100644 index 0000000..dec97e3 --- /dev/null +++ b/tests/test_native_backup.py @@ -0,0 +1,263 @@ +"""Native backup entry: user owns version choice, restoration and confirmation.""" +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest +import win32con +import win32file + + +def project_fixture(tmp_path): + from cbb_refresh_verify.verify_runner import VerifyRequest + library = tmp_path/'library/library.lmc'; library.parent.mkdir(); library.touch() + work = library.parent/'ReusableBlocksLP/Block/Work'; work.mkdir(parents=True) + project = work/'Block.prj'; project.write_text('KEY iCDBDir "database"\n') + return VerifyRequest(library, 'Block', tmp_path/'evidence'), project + + +def test_backup_entry_can_open_project_without_layout_data(tmp_path, monkeypatch): + from cbb_refresh_verify import native_backup as native + request, project = project_fixture(tmp_path) + executable = tmp_path/'iCDBProjectBackup.exe'; executable.touch() + monkeypatch.setattr(native, 'native_backup_executable', lambda *_: executable) + calls = [] + monkeypatch.setattr(native.subprocess, 'Popen', lambda command, **kw: + (calls.append(command) or SimpleNamespace(pid=123, poll=lambda: None))) + session = native.launch_native_backup(request) + record = json.loads(session.job.read_text('utf-8')) + assert record['project'] == str(project) + assert calls[0][-2] == '--native-backup-worker' + assert calls[0][-1] == str(session.job) + assert session.library == request.lmc_file and session.block == 'Block' + + +def test_native_session_closure_does_not_claim_restore_success(tmp_path, monkeypatch): + from cbb_refresh_verify import native_backup as native + from cbb_refresh_verify.library_lock import LibraryLock + request, project = project_fixture(tmp_path) + executable = tmp_path/'iCDBProjectBackup.exe'; executable.touch() + monkeypatch.setattr(native, 'native_backup_executable', lambda *_: executable) + job = request.evidence_dir/'request.json'; job.parent.mkdir() + job.write_text(json.dumps({'library': str(request.lmc_file), 'block': 'Block', + 'project': str(project), 'mentor_bin': ''})) + calls = [] + class NativeProcess: + pid = 456 + def __init__(self, command, cwd): + calls.append(command) + lock = LibraryLock(request.lmc_file) + with pytest.raises(Exception): + win32file.CreateFile(str(lock.path), win32con.GENERIC_READ | win32con.GENERIC_WRITE, + 0, None, win32con.OPEN_ALWAYS, 0, None) + def poll(self): return 0 + def session_pids(self): return [] + def close(self): pass + assert native.native_backup_worker_main(job, process_factory=NativeProcess) == 0 + assert calls == [[str(executable), '-p', str(project)]] + result = json.loads(job.with_name('result.json').read_text('utf-8')) + assert result['status'] == 'CLOSED' and result['restore_confirmed'] is False + assert result['native_exit_code'] == 0 and result['safe_to_continue'] is True + with LibraryLock(request.lmc_file): pass + + +def test_changed_project_identity_is_rejected_before_native_launch(tmp_path, monkeypatch): + from cbb_refresh_verify import native_backup as native + request, project = project_fixture(tmp_path) + job = request.evidence_dir/'request.json'; job.parent.mkdir() + job.write_text(json.dumps({'library': str(request.lmc_file), 'block': 'Block', + 'project': str(project.parent/'Other.prj'), 'mentor_bin': ''})) + assert native.native_backup_worker_main(job, + process_factory=lambda *a, **k: pytest.fail('native launch on mismatched project')) == 1 + assert json.loads(job.with_name('result.json').read_text('utf-8'))['status'] == 'FAILED' + + +@pytest.mark.parametrize('all_evidence_failed', [False, True]) +def test_state_log_failure_does_not_abandon_live_native_session(tmp_path, monkeypatch, all_evidence_failed): + from cbb_refresh_verify import native_backup as native, management + request, project = project_fixture(tmp_path) + executable = tmp_path/'iCDBProjectBackup.exe'; executable.touch() + monkeypatch.setattr(native, 'native_backup_executable', lambda *_: executable) + job = request.evidence_dir/'request.json'; job.parent.mkdir() + job.write_text(json.dumps({'library': str(request.lmc_file), 'block': 'Block', + 'project': str(project), 'mentor_bin': ''})) + write = management._write_json + def broken_state(path, value): + if all_evidence_failed or Path(path).name == 'state.json': raise OSError('state log unavailable') + write(path, value) + monkeypatch.setattr(management, '_write_json', broken_state) + observations = [] + class NativeProcess: + pid = 456 + def __init__(self, *a): pass + def poll(self): return 0 + def session_pids(self): + observations.append(True) + return [456] if len(observations) == 1 else [] + def close(self): pass + assert native.native_backup_worker_main(job, process_factory=NativeProcess) == 0 + assert len(observations) >= 2 + if not all_evidence_failed: + assert json.loads(job.with_name('result.json').read_text('utf-8'))['status'] == 'CLOSED' + + +def test_native_backup_ui_keeps_catalog_interactive_and_refreshes_after_close(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + requests, refreshes = [], [] + result = tmp_path/'native/result.json'; result.parent.mkdir() + job = result.with_name('request.json'); job.write_text('{}') + session = SimpleNamespace(library=Path('test.lmc'), block='Beta', job=job, + process=SimpleNamespace(poll=lambda: None)) + window = load_window(qtbot, tmp_path, monkeypatch, + native_backup_launcher=lambda req: (requests.append(req) or session), + verifier=lambda _: pytest.fail('native backup must not run Verify'), + status_refresher=lambda names, _: (refreshes.append(names) or {n: 'PENDING' for n in names})) + window.search_edit.setText('Beta'); window.select_visible_button.click() + assert window.native_backup_button.isEnabled() + window.native_backup_button.click(); qtbot.waitUntil(lambda: not window.busy) + assert len(requests) == 1 and requests[0].block_name == 'Beta' + assert window.search_edit.isEnabled() and window.section_tabs.isEnabled() + window.section_tabs.setCurrentIndex(2) + window.search_edit.setText('Gamma') + assert not window.busy + result.write_text(json.dumps({'status': 'CLOSED', 'safe_to_continue': True, + 'library': str(session.library), 'block': session.block, 'native_exit_code': 0, + 'restore_confirmed': False})) + session.process.poll = lambda: 0 + window._poll_native_backup() + qtbot.waitUntil(lambda: not window.busy) + assert refreshes == [('Beta',)] + assert window.search_edit.text() == 'Gamma' + assert 'PASS' not in window.cbb_table.item(window._row_by_name['Beta'], 3).text() + + +def test_native_backup_selection_requires_one_visible_non_ready_item(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + window = load_window(qtbot, tmp_path, monkeypatch, + native_backup_launcher=lambda _: pytest.fail('unexpected launch')) + assert not window.native_backup_button.isEnabled() + + +def test_native_backup_can_use_current_non_ready_row_without_checkbox(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + window = load_window(qtbot, tmp_path, monkeypatch, + native_backup_launcher=lambda _: pytest.fail('unexpected launch')) + row = window._row_by_name['Beta'] + window.cbb_table.setCurrentCell(row, 0) + window._update() + assert window.native_backup_button.isEnabled() + window.search_edit.setText('Alpha'); window.select_visible_button.click() + assert not window.native_backup_button.isEnabled() + window.search_edit.clear(); window.select_visible_button.click() + assert not window.native_backup_button.isEnabled() + + +def test_closing_app_keeps_manual_native_window_and_mapping(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + window = load_window(qtbot, tmp_path, monkeypatch) + retained = [] + lease = SimpleNamespace(retain_for_recovery=lambda: retained.append(True), + close=lambda: pytest.fail('mapping released before native session ends')) + session = SimpleNamespace(library=Path('test.lmc'), block='Beta', path_lease=lease, + process=SimpleNamespace(poll=lambda: None, terminate=lambda: pytest.fail('native UI terminated'))) + window.library_lease = lease + window._native_backup_session = session + window.show(); window.close() + qtbot.waitUntil(lambda: not window.isVisible()) + assert retained == [True] and session.process.poll() is None + + +def test_native_launch_failure_does_not_poison_other_features(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + def missing(_): raise ValueError('未找到 iCDB Project Backup') + window = load_window(qtbot, tmp_path, monkeypatch, native_backup_launcher=missing) + window.search_edit.setText('Beta'); window.select_visible_button.click() + window.native_backup_button.click(); qtbot.waitUntil(lambda: not window.busy) + assert '未找到' in window.status_label.text() + assert window.selected_batch_button.isEnabled() and window.native_backup_button.isEnabled() + assert not window._management_unsafe + + +@pytest.mark.parametrize('evidence', ['unconfirmed', 'missing', 'malformed', 'wrong_identity']) +def test_unconfirmed_supervisor_exit_keeps_session_conflict_and_mapping(qtbot, tmp_path, monkeypatch, evidence): + from test_ui_filters import load_window + window = load_window(qtbot, tmp_path, monkeypatch) + job = tmp_path/'native/request.json'; job.parent.mkdir(); job.write_text('{}') + if evidence != 'missing': + job.with_name('result.json').write_text('invalid' if evidence == 'malformed' else json.dumps({ + 'status': 'FAILED', 'safe_to_continue': evidence == 'wrong_identity', + 'library': 'other.lmc' if evidence == 'wrong_identity' else 'test.lmc', + 'block': 'Beta', 'detail': 'unconfirmed'})) + session = SimpleNamespace(library=Path('test.lmc'), block='Beta', job=job, + path_lease=window.library_lease, process=SimpleNamespace(poll=lambda: 1)) + window._native_backup_session = session + window._poll_native_backup(); qtbot.waitUntil(lambda: not window.busy) + assert window._native_backup_session is session + assert not window.batch_button.isEnabled() and window.search_edit.isEnabled() + assert not window.native_backup_timer.isActive() + + +def test_confirmed_native_close_transfers_mapping_to_current_library(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + from test_network_path import FakeWNet + from cbb_refresh_verify.network_path import LibraryPathLease + window = load_window(qtbot, tmp_path, monkeypatch) + backend = FakeWNet() + old = LibraryPathLease.acquire(r'\\server\share\A\library.lmc', backend=backend) + current = LibraryPathLease.acquire(r'\\server\share\B\library.lmc', backend=backend) + window.library_lease = current + job = tmp_path/'request.json' + job.with_name('result.json').write_text(json.dumps({'status': 'CLOSED', 'safe_to_continue': True, + 'library': str(old.mentor_path), 'block': 'Beta'})) + window._native_backup_session = SimpleNamespace(library=old.mentor_path, block='Beta', job=job, + path_lease=old, process=SimpleNamespace(poll=lambda: 0)) + window._poll_native_backup(); qtbot.waitUntil(lambda: not window.busy) + assert window._native_backup_session is None + assert backend.cancelled == [] and current.created + window.close() + qtbot.waitUntil(lambda: backend.cancelled == [current.drive]) + + +def test_native_mapping_ownership_transfers_to_new_library_on_same_share(): + from test_network_path import FakeWNet + from cbb_refresh_verify.network_path import LibraryPathLease + backend = FakeWNet() + old = LibraryPathLease.acquire(r'\\server\share\A\library.lmc', backend=backend) + current = LibraryPathLease.acquire(r'\\server\share\B\library.lmc', backend=backend) + assert old.created and not current.created + old.transfer_ownership(current) + old.close() + assert backend.cancelled == [] and current.created + current.close() + assert backend.cancelled == [current.drive] + + +def test_native_process_job_waits_for_its_children_without_killing_them(tmp_path): + import sys, time + from cbb_refresh_verify.native_backup import _NativeBackupProcess + pythonw = Path(sys.executable).with_name('pythonw.exe') + child = tmp_path/'child.pid' + script = tmp_path/'parent.py' + script.write_text('import subprocess,sys,time\nfrom pathlib import Path\n' + 'p=subprocess.Popen([sys.executable,"-c","import time;time.sleep(1)"])\n' + f'Path({str(child)!r}).write_text(str(p.pid))\n' + 'time.sleep(.2)\n', encoding='utf-8') + native = _NativeBackupProcess([str(pythonw), str(script)], tmp_path) + try: + deadline = time.monotonic()+10 + seen_child = False + seen_parent_exit_before_child = False + while time.monotonic() < deadline: + pids = native.session_pids() + assert isinstance(pids, (list, tuple)) + if child.exists(): + pid = int(child.read_text()) + seen_child = seen_child or pid in pids + seen_parent_exit_before_child = seen_parent_exit_before_child or native.poll() == 0 and pid in pids + if native.poll() == 0 and not pids: + break + time.sleep(.05) + assert seen_child and seen_parent_exit_before_child + assert not native.session_pids() + finally: + native.close() diff --git a/tests/test_native_occupancy.py b/tests/test_native_occupancy.py index e4c0fda..c0270e5 100644 --- a/tests/test_native_occupancy.py +++ b/tests/test_native_occupancy.py @@ -1,169 +1,191 @@ -import json -from pathlib import Path -import pytest - - -def output(project, database, *, fault=False, busy=False): - text = f'Loading project file [{project}].\nChecking if project is in use.\n' - if fault: - text += (f'Project database [{database}] is inconsistent. It has been manually copied while the iCDB Server was running. ' - "Please use iCDB Project Backup 'Repair project' functionality to fix this issue.\n") - return text + ('Project is in use.\n' if busy else - "Project is not in use. Full iCDB Project Backup's functionality is available.\nBackup information loaded correctly.\n") - - -@pytest.mark.parametrize('fault,busy,status,repair', [ - (False, False, 'NOT_IN_USE', False), (True, False, 'NOT_IN_USE', True), - (True, True, 'IN_USE', False), (False, True, 'IN_USE', False)]) -def test_native_ownership_and_repair_need_are_separate(tmp_path, fault, busy, status, repair): - from cbb_refresh_verify.native_occupancy import classify_inspection - project, database = tmp_path/'A.prj', tmp_path/'database' - result = classify_inspection(project, database, output(project, database, fault=fault, busy=busy)) - assert result['status'] == status - assert result['repair_required'] is repair - - -@pytest.mark.parametrize('case', ['progress', 'wrong_project', 'wrong_database', 'stale_verdict', 'generic_repair']) -def test_incomplete_or_foreign_output_cannot_authorize_repair(tmp_path, case): - from cbb_refresh_verify.native_occupancy import classify_inspection - project, database = tmp_path/'A.prj', tmp_path/'database' - text = output(project, database, fault=True) - if case == 'progress': text = f'Loading project file [{project}].\nChecking if project is in use.' - if case == 'wrong_project': text = output(tmp_path/'Other.prj', database, fault=True) - if case == 'wrong_database': text = output(project, tmp_path/'other', fault=True) - if case == 'stale_verdict': text += 'Checking if project is in use.\n' - if case == 'generic_repair': text = output(project, database) + 'Please try to repair the project!' - assert classify_inspection(project, database, text)['repair_required'] is False - - -@pytest.mark.parametrize('fault,busy', [(False, False), (True, False), (False, True)]) -def test_inspection_mode_only_observes_and_closes_its_tool(tmp_path, monkeypatch, fault, busy): - import win32con - from test_native_repair import repair_worker_fixture - ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active') - data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True - job.write_text(json.dumps(data), encoding='utf-8') - monkeypatch.setattr(ui, '_repair_command', lambda *a: pytest.fail('inspection resolved Repair command')) - monkeypatch.setattr(ui, '_native_output', lambda *_: output(data['project'], data['database'], fault=fault, busy=busy)) - assert ui.repair_worker_main(job) == 0 - result = json.loads((root/'repair-result.json').read_text('utf-8')) - assert result['status'] == ('IN_USE' if busy else 'NOT_IN_USE') - assert result['release']['native_exited'] is True - assert result['repair_required'] is (fault and not busy) - assert actions == [(100, win32con.WM_CLOSE)] - - -def test_generic_project_backup_shell_is_accepted_as_the_single_target_window(tmp_path, monkeypatch): - import json - from test_native_repair import repair_worker_fixture - ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active') - data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True - job.write_text(json.dumps(data), encoding='utf-8') - monkeypatch.setattr(ui, '_native_output', lambda windows: ( - f'Loading project file [{data["project"]}].\nChecking if project is in use.\n' - "Project is not in use. Full iCDB Project Backup's functionality is available.\n" - 'Backup information loaded correctly.')) - assert ui.repair_worker_main(job) == 0 - - -def test_only_check_never_counts_as_repair_success(): - from cbb_refresh_verify.icdb_maintenance import maintenance_counts - from cbb_refresh_verify.verify_runner import VerifyResult - counts = maintenance_counts([VerifyResult('CHECKED', safe_to_continue=True)]) - assert counts['passed'] == counts['repaired'] == 0 - assert counts['checked_without_repair'] == 1 - - -def test_cancelled_probe_returns_within_grace_without_killing_native(tmp_path, monkeypatch): - from threading import Event - from types import SimpleNamespace - from cbb_refresh_verify import native_repair as native - from cbb_refresh_verify.native_repair import RepairTarget - stop = Event(); ticks = [0.0]; actions = [] - def sleep(seconds): - ticks[0] += seconds - stop.set() - monkeypatch.setattr(native, 'time', SimpleNamespace(monotonic=lambda: ticks[0], sleep=sleep)) - class Worker: - pid = 123 - def __init__(self, *a): pass - def bind_cancellation(self, p): pass - def poll(self): return None - def request_stop(self): actions.append('cancel') - def close(self): actions.append('close_handles') - def kill(self): pytest.fail('native owner must not be killed') - monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker) - result = native.run_native_repair(RepairTarget(tmp_path/'A.prj', tmp_path/'database'), - tmp_path/'evidence', timeout_seconds=600, inspection_only=True, stop=stop) - assert ticks[0] < 6 - assert result['status'] == 'CANCELLED_UNRELEASED' - assert result['release']['safe_to_continue'] is False - assert actions[-1] == 'close_handles' - - - - -@pytest.mark.parametrize('extra', ['foreign_session', 'extra_error']) -def test_foreign_or_additional_fault_is_never_a_clean_inspection(tmp_path, extra): - from cbb_refresh_verify.native_occupancy import classify_inspection - project, database = tmp_path/'A.prj', tmp_path/'database' - text = output(project, database, fault=extra == 'extra_error') - if extra == 'foreign_session': - text += ('The last server session on different server machine lost the connection to the database. ' - 'Machine:[SERVER] Path:[C:/Other/Work/database] session:[old]') - else: - text += 'ERROR: shared symbol database unavailable' - assert classify_inspection(project, database, text)['status'] == 'UNCONFIRMED' - - -def test_unconfirmed_inspection_closes_known_main_at_timeout(tmp_path, monkeypatch): - import win32con - from test_native_repair import repair_worker_fixture - ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active') - data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True - job.write_text(json.dumps(data), encoding='utf-8') - monkeypatch.setattr(ui, '_native_output', lambda *_: 'Unrecognized response') - assert ui.repair_worker_main(job) == 1 - result = json.loads((root/'repair-result.json').read_text('utf-8')) - assert result['status'] == 'UNCONFIRMED' - assert result['release']['native_exited'] is True - assert actions == [(100, win32con.WM_CLOSE)] - - -def test_directory_scan_honors_cancel_between_entries(tmp_path): - from cbb_refresh_verify.scoped_manifest import scan_tree - for i in range(10): (tmp_path/f'{i}.dat').touch() - calls = [] - def cancel(): - calls.append(True) - if len(calls) == 3: raise RuntimeError('CANCELLED') - with pytest.raises(RuntimeError, match='CANCELLED'): - scan_tree(tmp_path, check=cancel) - assert len(calls) == 3 - - -def test_cancel_during_final_guard_cannot_launch_native_tool(tmp_path, monkeypatch): - from contextlib import contextmanager - from test_native_repair import repair_worker_fixture - from cbb_refresh_verify.native_repair import RepairTarget - ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active') - data = json.loads(job.read_text('utf-8')) - data['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'} - job.write_text(json.dumps(data), encoding='utf-8') - calls = [] - @contextmanager - def guard(*a, **kw): - calls.append(True) - yield {'target': RepairTarget(Path(data['project']), Path(data['database']))} - Path(data['cancel_signal']).touch() - monkeypatch.setattr('cbb_refresh_verify.maintenance_entry.maintenance_target_guard', guard) - monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('late native launch')) - assert ui.repair_worker_main(job) == 1 - assert len(calls) == 1 and not actions - - -def test_verified_cbb_refusal_is_not_hidden_by_secondary_release_failure(): - from cbb_refresh_verify.verify_runner import classify_failure_category - detail = ('BackAnnotate: Back Annotation is not allowed on verified (or once verified) Reusable Blocks.' - '\nPCB_RELEASE_UNCONFIRMED: not released') - assert classify_failure_category(detail) == 'CBB_REIMPORT_REQUIRED' +import json +from pathlib import Path +import pytest + + +def output(project, database, *, fault=False, busy=False): + text = f'Loading project file [{project}].\nChecking if project is in use.\n' + if fault: + text += (f'Project database [{database}] is inconsistent. It has been manually copied while the iCDB Server was running. ' + "Please use iCDB Project Backup 'Repair project' functionality to fix this issue.\n") + return text + ('Project is in use.\n' if busy else + "Project is not in use. Full iCDB Project Backup's functionality is available.\nBackup information loaded correctly.\n") + + +@pytest.mark.parametrize('fault,busy,status,repair', [ + (False, False, 'NOT_IN_USE', False), (True, False, 'NOT_IN_USE', True), + (True, True, 'IN_USE', False), (False, True, 'IN_USE', False)]) +def test_native_ownership_and_repair_need_are_separate(tmp_path, fault, busy, status, repair): + from cbb_refresh_verify.native_occupancy import classify_inspection + project, database = tmp_path/'A.prj', tmp_path/'database' + result = classify_inspection(project, database, output(project, database, fault=fault, busy=busy)) + assert result['status'] == status + assert result['repair_required'] is repair + + +@pytest.mark.parametrize('case', ['progress', 'wrong_project', 'wrong_database', 'stale_verdict', 'generic_repair']) +def test_incomplete_or_foreign_output_cannot_authorize_repair(tmp_path, case): + from cbb_refresh_verify.native_occupancy import classify_inspection + project, database = tmp_path/'A.prj', tmp_path/'database' + text = output(project, database, fault=True) + if case == 'progress': text = f'Loading project file [{project}].\nChecking if project is in use.' + if case == 'wrong_project': text = output(tmp_path/'Other.prj', database, fault=True) + if case == 'wrong_database': text = output(project, tmp_path/'other', fault=True) + if case == 'stale_verdict': text += 'Checking if project is in use.\n' + if case == 'generic_repair': text = output(project, database) + 'Please try to repair the project!' + assert classify_inspection(project, database, text)['repair_required'] is False + + +@pytest.mark.parametrize('fault,busy', [(False, False), (True, False), (False, True)]) +def test_inspection_mode_only_observes_and_closes_its_tool(tmp_path, monkeypatch, fault, busy): + import win32con + from test_native_repair import repair_worker_fixture + ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active') + data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True + job.write_text(json.dumps(data), encoding='utf-8') + monkeypatch.setattr(ui, '_repair_command', lambda *a: pytest.fail('inspection resolved Repair command')) + monkeypatch.setattr(ui, '_native_output', lambda *_: output(data['project'], data['database'], fault=fault, busy=busy)) + assert ui.repair_worker_main(job) == 0 + result = json.loads((root/'repair-result.json').read_text('utf-8')) + assert result['status'] == ('IN_USE' if busy else 'NOT_IN_USE') + assert result['release']['native_exited'] is True + assert result['repair_required'] is (fault and not busy) + assert actions == [(100, win32con.WM_CLOSE)] + + +def test_generic_project_backup_shell_is_accepted_as_the_single_target_window(tmp_path, monkeypatch): + import json + from test_native_repair import repair_worker_fixture + ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active') + data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True + job.write_text(json.dumps(data), encoding='utf-8') + monkeypatch.setattr(ui, '_native_output', lambda windows: ( + f'Loading project file [{data["project"]}].\nChecking if project is in use.\n' + "Project is not in use. Full iCDB Project Backup's functionality is available.\n" + 'Backup information loaded correctly.')) + assert ui.repair_worker_main(job) == 0 + + +def test_only_check_never_counts_as_repair_success(): + from cbb_refresh_verify.icdb_maintenance import maintenance_counts + from cbb_refresh_verify.verify_runner import VerifyResult + counts = maintenance_counts([VerifyResult('CHECKED', safe_to_continue=True)]) + assert counts['passed'] == counts['repaired'] == 0 + assert counts['checked_without_repair'] == 1 + + +def test_cancelled_probe_returns_within_grace_without_killing_native(tmp_path, monkeypatch): + from threading import Event + from types import SimpleNamespace + from cbb_refresh_verify import native_repair as native + from cbb_refresh_verify.native_repair import RepairTarget + stop = Event(); ticks = [0.0]; actions = [] + def sleep(seconds): + ticks[0] += seconds + stop.set() + monkeypatch.setattr(native, 'time', SimpleNamespace(monotonic=lambda: ticks[0], sleep=sleep)) + class Worker: + pid = 123 + def __init__(self, *a): pass + def bind_cancellation(self, p): pass + def poll(self): return None + def request_stop(self): actions.append('cancel') + def close(self): actions.append('close_handles') + def kill(self): pytest.fail('native owner must not be killed') + monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker) + result = native.run_native_repair(RepairTarget(tmp_path/'A.prj', tmp_path/'database'), + tmp_path/'evidence', timeout_seconds=600, inspection_only=True, stop=stop) + assert ticks[0] < 6 + assert result['status'] == 'CANCELLED_UNRELEASED' + assert result['release']['safe_to_continue'] is False + assert actions[-1] == 'close_handles' + + +def test_ui_keeps_processing_events_and_passes_cancel_to_native_task(qtbot, tmp_path, monkeypatch): + from threading import Event + from PySide6.QtCore import QTimer + from test_ui_filters import load_window + from cbb_refresh_verify.verify_runner import VerifyResult + entered = Event(); cancelled = Event(); ticks = [] + def verify(req, *, stop, **kw): + entered.set() + if stop.wait(3): cancelled.set() + return VerifyResult('CANCELLED') + monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_verify', verify) + window = load_window(qtbot, tmp_path, monkeypatch, + status_refresher=lambda names, _: {name: 'PENDING' for name in names}) + window.search_edit.setText('Beta') + timer = QTimer(window); timer.setInterval(10); timer.timeout.connect(lambda: ticks.append(True)); timer.start() + window.repair_icdb_all() + qtbot.waitUntil(entered.is_set) + qtbot.waitUntil(lambda: len(ticks) >= 3) + assert not window.busy and window._icdb_active() and window.stop_button.isEnabled() + window.stop_button.click() + qtbot.waitUntil(lambda: not window._icdb_active()) + assert cancelled.is_set() + + +@pytest.mark.parametrize('extra', ['foreign_session', 'extra_error']) +def test_foreign_or_additional_fault_is_never_a_clean_inspection(tmp_path, extra): + from cbb_refresh_verify.native_occupancy import classify_inspection + project, database = tmp_path/'A.prj', tmp_path/'database' + text = output(project, database, fault=extra == 'extra_error') + if extra == 'foreign_session': + text += ('The last server session on different server machine lost the connection to the database. ' + 'Machine:[SERVER] Path:[C:/Other/Work/database] session:[old]') + else: + text += 'ERROR: shared symbol database unavailable' + assert classify_inspection(project, database, text)['status'] == 'UNCONFIRMED' + + +def test_unconfirmed_inspection_closes_known_main_at_timeout(tmp_path, monkeypatch): + import win32con + from test_native_repair import repair_worker_fixture + ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active') + data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True + job.write_text(json.dumps(data), encoding='utf-8') + monkeypatch.setattr(ui, '_native_output', lambda *_: 'Unrecognized response') + assert ui.repair_worker_main(job) == 1 + result = json.loads((root/'repair-result.json').read_text('utf-8')) + assert result['status'] == 'UNCONFIRMED' + assert result['release']['native_exited'] is True + assert actions == [(100, win32con.WM_CLOSE)] + + +def test_directory_scan_honors_cancel_between_entries(tmp_path): + from cbb_refresh_verify.scoped_manifest import scan_tree + for i in range(10): (tmp_path/f'{i}.dat').touch() + calls = [] + def cancel(): + calls.append(True) + if len(calls) == 3: raise RuntimeError('CANCELLED') + with pytest.raises(RuntimeError, match='CANCELLED'): + scan_tree(tmp_path, check=cancel) + assert len(calls) == 3 + + +def test_cancel_during_final_guard_cannot_launch_native_tool(tmp_path, monkeypatch): + from contextlib import contextmanager + from test_native_repair import repair_worker_fixture + from cbb_refresh_verify.native_repair import RepairTarget + ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active') + data = json.loads(job.read_text('utf-8')) + data['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'} + job.write_text(json.dumps(data), encoding='utf-8') + calls = [] + @contextmanager + def guard(*a, **kw): + calls.append(True) + yield {'target': RepairTarget(Path(data['project']), Path(data['database']))} + Path(data['cancel_signal']).touch() + monkeypatch.setattr('cbb_refresh_verify.maintenance_entry.maintenance_target_guard', guard) + monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('late native launch')) + assert ui.repair_worker_main(job) == 1 + assert len(calls) == 1 and not actions + + +def test_verified_cbb_refusal_is_not_hidden_by_secondary_release_failure(): + from cbb_refresh_verify.verify_runner import classify_failure_category + detail = ('BackAnnotate: Back Annotation is not allowed on verified (or once verified) Reusable Blocks.' + '\nPCB_RELEASE_UNCONFIRMED: not released') + assert classify_failure_category(detail) == 'CBB_REIMPORT_REQUIRED' diff --git a/tests/test_navigation_tabs.py b/tests/test_navigation_tabs.py new file mode 100644 index 0000000..e7b972b --- /dev/null +++ b/tests/test_navigation_tabs.py @@ -0,0 +1,43 @@ +from PySide6.QtCore import Qt + + +def test_three_horizontal_sections_keep_one_catalog_and_only_their_actions(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + window = load_window(qtbot, tmp_path, monkeypatch) + window.show() + assert [window.section_tabs.tabText(i) for i in range(window.section_tabs.count())] == [ + '检验', 'ICDB 维护', '中心库管理'] + window.search_edit.setText('Beta') + window.select_visible_button.click() + for index, visible, hidden in ( + (0, window.batch_button, window.icdb_repair_button), + (1, window.icdb_repair_button, window.add_button), + (2, window.add_button, window.batch_button), + ): + window.section_tabs.setCurrentIndex(index) + assert visible.isVisible() and not hidden.isVisible() + assert window.cbb_table.isVisible() + assert window.search_edit.text() == 'Beta' + assert [record.name for record in window.selected_records()] == ['Beta'] + assert window.minimumSizeHint().height() <= 650 + + +def test_long_status_does_not_expand_the_window(qtbot, tmp_path): + from cbb_refresh_verify.ui.main_window import MainWindow + window = MainWindow(data_root=tmp_path) + qtbot.addWidget(window) + window.resize(1000, 650); window.show() + window.status_label.setText('错误说明\n' * 80) + qtbot.wait(20) + assert window.height() <= 650 + assert window.status_label.height() <= window.status_label.fontMetrics().lineSpacing() * 3 + 4 + + +def test_failure_detail_keeps_catalog_name_readable(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + window = load_window(qtbot, tmp_path, monkeypatch) + window.resize(1000, 650); window.show() + window.cbb_table.item(0, 3).setText('BackAnnotate: ' + 'long exception ' * 100) + qtbot.wait(20) + assert window.cbb_table.columnWidth(0) >= 200 + assert window.cbb_table.horizontalHeader().length() <= window.cbb_table.viewport().width() diff --git a/tests/test_pcb_restore_prompt.py b/tests/test_pcb_restore_prompt.py new file mode 100644 index 0000000..3805118 --- /dev/null +++ b/tests/test_pcb_restore_prompt.py @@ -0,0 +1,132 @@ +from dataclasses import replace +import json +from pathlib import Path +from types import SimpleNamespace +import pytest + +from test_pcb_version_choice import captured +from test_post_repair_consent import context, no_native_launch + + +@pytest.fixture +def session(context, monkeypatch): + from cbb_refresh_verify import post_repair_consent as consent + from cbb_refresh_verify.pcb_restore_prompt import RestoreController + _, _, proof, job = context + consent.prepare_launch(job, ['C:/Mentor/common/win32/bin/ExpeditionPCB.exe', job['pcb'], '-ReusableCircuit']) + monkeypatch.setattr(consent, '_validate_current_processes', lambda *a: None) + snapshot = captured() + controller = RestoreController(job) + prompts, calls = [], [] + def perform(snap, payload, phase): + calls.append(payload) + return SimpleNamespace(accepted_controls=(payload['target']['control_id'],), + channel='win32_button_click', error_code='', detail='') + def poll(snap=snapshot, snapshots=None): + return controller.handle(snap, snapshots or (snap,), target_pid=snapshot.pid, + launcher_pid=10, worker_pid=__import__('os').getpid(), companion_pids=(), + show=prompts.append, perform=perform) + return controller, snapshot, prompts, calls, poll, job + + +def test_waits_for_user_once_and_rechecks_radio_before_confirm(session): + controller, snapshot, prompts, calls, poll, job = session + assert not poll().error_code + poll() + assert len(prompts) == 1 and not calls + prompts[0].choose('last_user_saved') + assert poll().action_sent and calls[-1]['target']['control_id'] == 6213 + assert not poll().action_sent and len(calls) == 1 + selected = replace(snapshot, controls=tuple(replace(c, checked=c.control_id == 6213, + selected=c.control_id == 6213) if c.control_id in (6213, 6206) else c for c in snapshot.controls)) + assert poll(selected).action_sent and calls[-1]['target']['control_id'] == 1 + assert not poll(selected).action_sent and len(calls) == 2 + result = json.loads((Path(job['root'])/'pcb-version-restoration.json').read_text(encoding='utf-8')) + assert result['choice'] == 'last_user_saved' and result['date'] == '2026/9/24 23:06' + assert result['historical_restore'] and result['confirm_sent'] + + +def test_cancel_never_selects_or_confirms_a_version(session): + _, _, prompts, calls, poll, _ = session + poll(); prompts[0].choose('cancel') + result = poll() + assert result.error_code == 'PCB_VERSION_CHOICE_REQUIRED' + assert '取消' in result.detail and not calls + + +@pytest.mark.parametrize('change', ['date', 'pid', 'window', 'extra']) +def test_changed_native_choice_invalidates_user_answer(session, change): + _, snapshot, prompts, calls, poll, _ = session + poll(); prompts[0].choose('last_user_saved') + changed = snapshot + if change == 'date': + changed = replace(snapshot, controls=tuple(replace(c, name=c.name.replace('23:06', '23:07')) + if c.control_id == 6213 else c for c in snapshot.controls)) + if change == 'pid': changed = replace(snapshot, pid=snapshot.pid + 1) + if change == 'window': changed = replace(snapshot, hwnd=snapshot.hwnd + 1) + result = poll(changed, (changed, changed) if change == 'extra' else None) + assert result.error_code and not calls + + +def test_native_action_failure_never_retries_or_confirms(session): + controller, snapshot, prompts, calls, poll, _ = session + poll(); prompts[0].choose('last_user_saved') + def failed(*a): + return SimpleNamespace(accepted_controls=(), channel='', error_code='ACTION_CHANNEL_FAILED', detail='timeout') + result = controller.handle(snapshot, (snapshot,), target_pid=snapshot.pid, launcher_pid=10, + worker_pid=__import__('os').getpid(), companion_pids=(), show=prompts.append, perform=failed) + assert result.error_code == 'ACTION_CHANNEL_FAILED' + assert poll().error_code and not calls + + +def test_version_dialog_shows_dates_and_explicit_choices(qtbot): + from cbb_refresh_verify.pcb_restore_prompt import RestoreChoice + from cbb_refresh_verify.ui.pcb_restore_dialog import PcbRestoreDialog + from cbb_refresh_verify.dialog_rules import pcb_version_choice + choice = RestoreChoice('Block', 'library.lmc', pcb_version_choice(captured())['candidates']) + dialog = PcbRestoreDialog(choice) + qtbot.addWidget(dialog) + assert '2026/9/24 23:06' in dialog.text() + assert choice.decision is None + dialog.manual_button.click() + assert choice.decision == 'last_user_saved' + + +def test_closing_version_dialog_is_cancel_not_a_default_selection(qtbot): + from cbb_refresh_verify.pcb_restore_prompt import RestoreChoice + from cbb_refresh_verify.ui.pcb_restore_dialog import PcbRestoreDialog + from cbb_refresh_verify.dialog_rules import pcb_version_choice + choice = RestoreChoice('Block', 'library.lmc', pcb_version_choice(captured())['candidates']) + dialog = PcbRestoreDialog(choice) + qtbot.addWidget(dialog) + dialog.reject() + assert choice.decision == 'cancel' + + +@pytest.mark.parametrize('change', ['', 'desktop', 'pid', 'date', 'disabled', 'selection', 'channel']) +def test_private_agent_rechecks_live_version_before_confirmation(monkeypatch, change): + import win32gui, win32process + from cbb_refresh_verify.dialog_agent import DialogActionExecutor + from cbb_refresh_verify.dialog_rules import pcb_version_choice + snapshot = replace(captured(), controls=tuple(replace(c, checked=c.control_id == 6213, + selected=c.control_id == 6213) if c.control_id in (6213, 6206) else c for c in captured().controls)) + controls = {c.handle: c for c in snapshot.controls if c.handle and c.class_name in ('Static', 'Button')} + monkeypatch.setattr('cbb_refresh_verify.native_repair_ui._current_desktop_name', + lambda: 'Default' if change == 'desktop' else 'CbbVerify_fixture') + monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda h: (1, snapshot.pid + (change == 'pid'))) + monkeypatch.setattr(win32gui, 'GetClassName', lambda h: snapshot.window_class if h == snapshot.hwnd else controls[h].class_name) + monkeypatch.setattr(win32gui, 'GetWindowText', lambda h: snapshot.title if h == snapshot.hwnd else + controls[h].name.replace('23:06', '23:07') if change == 'date' else controls[h].name) + monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda h: True) + monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda h: not (change == 'disabled' and controls[h].control_id == 6213)) + monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda h: controls[h].control_id) + monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda h, callback, arg: [callback(c, arg) for c in controls]) + monkeypatch.setattr(win32gui, 'SendMessageTimeout', lambda h, *a: int(controls[h].control_id == (6206 if change == 'selection' else 6213))) + calls = [] + monkeypatch.setattr(win32gui, 'PostMessage', lambda *a: calls.append(a)) + action = {'action': 'user_selected_pcb_version', 'channels': ['uia_invoke' if change == 'channel' else 'win32_button_click'], + 'target': {'control_id': 1}, 'pid': snapshot.pid, 'desktop': 'CbbVerify_fixture', + 'choice': 'last_user_saved', 'candidates': pcb_version_choice(snapshot)['candidates']} + result = DialogActionExecutor().perform(snapshot, action) + assert bool(result.accepted_controls) is (change == '') + assert len(calls) == (1 if change == '' else 0) diff --git a/tests/test_reimport_recovery.py b/tests/test_reimport_recovery.py new file mode 100644 index 0000000..f292cd4 --- /dev/null +++ b/tests/test_reimport_recovery.py @@ -0,0 +1,242 @@ +from dataclasses import replace +from pathlib import Path +from threading import Event +from types import SimpleNamespace + +import pytest +from PySide6.QtCore import QTimer +from PySide6.QtWidgets import QMessageBox + +from cbb_refresh_verify.management import Capability, ManagementRequest, ManagementResult +from cbb_refresh_verify.verify_runner import VerifyResult + + +def failed_repair(path, *, safe=False): + return VerifyResult('FAIL', error_category='CBB_REIMPORT_REQUIRED', + stderr='Back Annotation is not allowed on verified (or once verified) Reusable Blocks.', + evidence_path=path, safe_to_continue=safe, + recovery_attempts=({'native_status': 'REPAIRED', 'status': 'REPAIR_VALIDATION_FAILED', + 'validation_passed': False},)) + + +def recovery_window(qtbot, tmp_path, monkeypatch, result=None): + from test_ui_filters import load_window + adapter = SimpleNamespace(capabilities=lambda: {op: Capability(True, 'available') + for op in ('add', 'update', 'remove')}) + result = result or failed_repair(tmp_path/'maintenance/result.json') + window = load_window(qtbot, tmp_path, monkeypatch, management_adapter=adapter, + verifier=lambda _: result, status_refresher=lambda names, path: {n: 'PENDING' for n in names}) + window.search_edit.setText('Beta') + window.repair_icdb_all() + qtbot.waitUntil(lambda: not window._icdb_active()) + return window, result + + +def test_failed_repair_offers_copy_import_bound_to_failed_target(qtbot, tmp_path, monkeypatch): + window, failed = recovery_window(qtbot, tmp_path, monkeypatch) + assert '副本' in window.summary.text() + action = next(b for b in window.summary.buttons() if '副本' in b.text()) + window.search_edit.setText('Alpha') + window.select_visible_button.click() + action.click() + dialog = window.management_dialog + requests = dialog.requests() + assert len(requests) == 1 and requests[0].name == 'Beta' + assert requests[0].partition == 'Power' and requests[0].operation == 'update' + assert requests[0].source is None and requests[0].auto_verify + assert '修复未完成' in dialog.status_label.text() + assert '手动备份' in dialog.status_label.text() + assert str(failed.evidence_path) in dialog.output.toPlainText() + dialog.reject() + assert failed.status == 'FAIL' + assert window.reimport_button.isEnabled() + + +def test_declining_reimport_confirmation_does_not_check_release_or_write(qtbot, tmp_path, monkeypatch): + import cbb_refresh_verify.library_lock as locks + window, _ = recovery_window(qtbot, tmp_path, monkeypatch) + window.summary.close() + window.reimport_button.click() + dialog = window.management_dialog + source = tmp_path/'copy/test.prj'; source.parent.mkdir(); source.touch() + dialog.add_sources([source]) + monkeypatch.setattr(locks, 'release_retained_library', lambda *a: pytest.fail('unconfirmed release')) + confirmations = [] + monkeypatch.setattr(QMessageBox, 'question', lambda *a, **kw: + confirmations.append(a[2]) or QMessageBox.No) + dialog.execute_button.click() + assert not dialog.busy and not dialog.executed + assert 'Beta' in confirmations[0] and str(source) in confirmations[0] + assert '副本' in confirmations[0] and '先移除' in confirmations[0] + dialog.reject() + + +@pytest.mark.parametrize('result', [VerifyResult('CHECKED'), VerifyResult('PASS', library_flag='GREEN'), + VerifyResult('BLOCKED', error_category='ICDB_DATABASE_IN_USE', safe_to_continue=False), + VerifyResult('FAIL', stderr='unknown error')]) +def test_no_reimport_offer_for_unconfirmed_diagnosis_or_success(qtbot, tmp_path, monkeypatch, result): + window, _ = recovery_window(qtbot, tmp_path, monkeypatch, result) + assert not window.reimport_button.isVisible() + assert not any('副本' in b.text() for b in window.summary.buttons()) + + +def test_changing_library_invalidates_old_reimport_offer(qtbot, tmp_path, monkeypatch): + window, _ = recovery_window(qtbot, tmp_path, monkeypatch) + old_action = next(b for b in window.summary.buttons() if '副本' in b.text()) + window.lmc_edit.setText('another.lmc') + old_action.click() + assert not getattr(window, 'management_dialog', None) + assert not window.reimport_button.isVisible() + + +def request(tmp_path): + library = tmp_path/'lib/mentor.lmc'; library.parent.mkdir(); library.touch() + source = tmp_path/'copy/Block.prj'; source.parent.mkdir(); source.touch() + return ManagementRequest('update', library, 'Block', source=source, evidence_dir=tmp_path/'management') + + +def test_release_failure_preserves_failure_and_never_dispatches_management(tmp_path, monkeypatch): + from cbb_refresh_verify.reimport_recovery import run_reimport_recovery + import cbb_refresh_verify.library_lock as locks + import cbb_refresh_verify.management as management + req = request(tmp_path) + monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block')) + def denied(*a): raise locks.LibraryBusy('PCB still active: 123') + monkeypatch.setattr(locks, 'release_retained_library', denied) + monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: pytest.fail('unsafe write')) + results = run_reimport_recovery([req], previous_evidence={'Block': tmp_path/'old/result.json'}, + evidence_dir=tmp_path/'reimport') + assert results[0].status == 'BLOCKED' and not results[0].safe_to_continue + assert '123' in results[0].detail + import json + record = json.loads(results[0].evidence_path.read_text('utf-8')) + assert record['previous_evidence']['Block'] == str(tmp_path/'old/result.json') + assert record['stage'] == 'release_failed' + + +def test_cancel_during_release_prevents_import(tmp_path, monkeypatch): + from cbb_refresh_verify.reimport_recovery import run_reimport_recovery + import cbb_refresh_verify.library_lock as locks + import cbb_refresh_verify.management as management + req = request(tmp_path); stop = Event() + monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block')) + def release(*a): + stop.set() + return {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'} + monkeypatch.setattr(locks, 'release_retained_library', release) + monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: pytest.fail('cancelled write')) + results = run_reimport_recovery([req], previous_evidence={'Block': 'old.json'}, + evidence_dir=tmp_path/'reimport', stop=stop) + assert results == [] + + +@pytest.mark.parametrize('uploaded_status', ['UPLOADED', 'UPLOADED_VERIFY_FAILED', 'UPLOADED_VERIFIED']) +def test_copy_recovery_keeps_native_management_outcome_and_original_evidence(tmp_path, monkeypatch, uploaded_status): + from cbb_refresh_verify.reimport_recovery import run_reimport_recovery + import cbb_refresh_verify.library_lock as locks + import cbb_refresh_verify.management as management + import json + req = request(tmp_path) + old = tmp_path/'old.json'; old.write_text('{"status":"FAIL"}', encoding='utf-8') + before = old.read_bytes() + monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block')) + monkeypatch.setattr(locks, 'release_retained_library', lambda *a: + {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'}) + expected = ManagementResult('update', req.library, req.name, req.partition, req.source, + True, 'complete', uploaded_status, True) + monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: [expected]) + results = run_reimport_recovery([req], previous_evidence={'Block': str(old)}, + evidence_dir=tmp_path/'reimport') + assert results == [expected] and old.read_bytes() == before + record = json.loads(next((tmp_path/'reimport').glob('*/recovery.json')).read_text('utf-8')) + assert record['original_repair_succeeded'] is False + assert record['results'][0]['status'] == uploaded_status and record['version_review_required'] + + +def test_incomplete_copy_never_releases_or_removes_target(tmp_path, monkeypatch): + from cbb_refresh_verify.reimport_recovery import run_reimport_recovery + import cbb_refresh_verify.library_lock as locks + req = request(tmp_path) # Empty PRJ is deliberately incomplete. + monkeypatch.setattr(locks, 'release_retained_library', lambda *a: pytest.fail('incomplete source')) + results = run_reimport_recovery([req], previous_evidence={'Block': 'old.json'}, + evidence_dir=tmp_path/'reimport') + assert results[0].status == 'BLOCKED' and results[0].stage == 'preflight' + + +def test_recovery_uses_background_release_then_existing_management(qtbot, tmp_path, monkeypatch): + from cbb_refresh_verify.ui.management_dialog import ManagementDialog + import cbb_refresh_verify.library_lock as locks + import cbb_refresh_verify.management as management + req = request(tmp_path); entered, finish = Event(), Event(); calls = [] + monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block')) + def release(*a): + entered.set(); assert finish.wait(5) + calls.append('release') + return {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'} + monkeypatch.setattr(locks, 'release_retained_library', release) + def run(items, **kw): + calls.append('management') + return [ManagementResult('update', req.library, req.name, req.partition, req.source, + True, 'complete', 'UPLOADED_VERIFIED', True)] + monkeypatch.setattr(management, 'run_management_batch', run) + monkeypatch.setattr(QMessageBox, 'question', lambda *a, **kw: QMessageBox.Yes) + dialog = ManagementDialog([req], recovery_from={'Block': 'old.json'}) + qtbot.addWidget(dialog) + ticks = [] + timer = QTimer(); timer.setInterval(10); timer.timeout.connect(lambda: ticks.append(1)); timer.start() + try: + dialog.execute_button.click() + qtbot.waitUntil(entered.is_set) + qtbot.waitUntil(lambda: len(ticks) >= 3) + assert calls == [] and dialog.busy + finally: + finish.set() + qtbot.waitUntil(lambda: not dialog.busy) + timer.stop() + assert calls == ['release', 'management'] + assert '版本待核对' in dialog.status_label.text() + + +def test_recovery_dialog_keeps_internal_details_in_optional_log(qtbot, tmp_path): + from cbb_refresh_verify.ui.management_dialog import ManagementDialog + req = request(tmp_path) + dialog = ManagementDialog([req], recovery_from={'Block': 'old-result.json'}) + qtbot.addWidget(dialog); dialog.show() + assert dialog.output.isHidden() + assert not any(word in dialog.status_label.text() for word in ('原生', '证据', '检查点', '记录保留')) + detail = 'OWNER_QUERY_TIMEOUT: diagnostic internals' + result = ManagementResult('update', req.library, req.name, req.partition, req.source, + True, 'release_check', 'BLOCKED', False, detail, tmp_path/'recovery.json') + dialog._result([result]) + assert detail not in dialog.status_label.text() + assert '日志' in dialog.status_label.text() + dialog.logs_button.click() + assert dialog.output.isVisible() and detail in dialog.output.toPlainText() + + +def test_main_stop_during_recovery_release_cancels_import(qtbot, tmp_path, monkeypatch): + import cbb_refresh_verify.library_lock as locks + import cbb_refresh_verify.management as management + window, _ = recovery_window(qtbot, tmp_path, monkeypatch) + window.summary.close(); window.reimport_button.click() + dialog = window.management_dialog + source = tmp_path/'copy/source.prj'; source.parent.mkdir(); source.touch() + dialog.add_sources([source]) + monkeypatch.setattr(management, 'source_project', lambda *a: (source, source, 'Beta')) + entered, finish = Event(), Event() + def release(*args): + entered.set(); assert finish.wait(5) + return {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'} + monkeypatch.setattr(locks, 'release_retained_library', release) + dispatched = [] + monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: dispatched.append(a) or []) + dialog.execute_button.click() + try: + qtbot.waitUntil(entered.is_set) + window.stop_button.click() + assert dialog.stop.is_set() + finally: + finish.set(); qtbot.waitUntil(lambda: not dialog.busy) + dialog.reject() + assert dispatched == [] + diff --git a/tests/test_ui.py b/tests/test_ui.py index 52e6b2b..305c47c 100644 --- a/tests/test_ui.py +++ b/tests/test_ui.py @@ -1,4 +1,5 @@ import os +import pytest from pathlib import Path os.environ.setdefault('QT_QPA_PLATFORM','offscreen') from cbb_refresh_verify.models import CbbRecord, LibraryReadResult @@ -21,7 +22,17 @@ def test_application_palette_keeps_table_text_readable(qtbot): def fake_reader(_): return LibraryReadResult((CbbRecord('CBB1','Reusable Blocks'),)) -def test_global_icdb_action_confirms_and_includes_ready_rows(qtbot, tmp_path, monkeypatch): + +@pytest.fixture(autouse=True) +def isolate_authoritative_native_refresh(monkeypatch): + from PySide6.QtWidgets import QMessageBox + monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) + # Production refresh crosses the native Mentor boundary; these are UI tests. + monkeypatch.setattr('cbb_refresh_verify.ui.main_window.authoritative_status_map', + lambda names, *_: {name: 'READY' for name in names}) + + +def test_global_icdb_action_confirms_and_excludes_ready_rows(qtbot, tmp_path, monkeypatch): from PySide6.QtWidgets import QMessageBox calls = [] window = MainWindow(reader=lambda _: LibraryReadResult(( @@ -36,8 +47,8 @@ def test_global_icdb_action_confirms_and_includes_ready_rows(qtbot, tmp_path, mo assert calls == [] monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) window.icdb_repair_button.click() - qtbot.waitUntil(lambda: not window.busy) - assert calls == ['READY', 'PENDING'] + qtbot.waitUntil(lambda: not window._icdb_active()) + assert calls == ['PENDING'] def test_global_icdb_action_disabled_without_library_or_while_busy(qtbot): window = MainWindow(reader=fake_reader) @@ -49,11 +60,11 @@ def test_global_icdb_action_disabled_without_library_or_while_busy(qtbot): window.busy = True; window._update() assert not window.icdb_repair_button.isEnabled() -def test_global_icdb_failure_clears_ready_and_stops_queue(qtbot, tmp_path, monkeypatch): +def test_global_icdb_failure_preserves_untargeted_ready_and_stops_queue(qtbot, tmp_path, monkeypatch): from PySide6.QtWidgets import QMessageBox calls = [] window = MainWindow(reader=lambda _: LibraryReadResult(( - CbbRecord('A', 'LP', status='READY'), CbbRecord('B', 'LP'))), + CbbRecord('A', 'LP', status='READY'), CbbRecord('B', 'LP'), CbbRecord('C', 'LP'))), verifier=lambda req: (calls.append(req.block_name) or VerifyResult( 'FAIL', stderr='unconfirmed', safe_to_continue=False)), data_root=tmp_path) qtbot.addWidget(window) @@ -61,13 +72,13 @@ def test_global_icdb_failure_clears_ready_and_stops_queue(qtbot, tmp_path, monke qtbot.waitUntil(lambda: not window.busy) monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) window.icdb_repair_button.click() - qtbot.waitUntil(lambda: not window.busy) - assert calls == ['A'] - assert 'A' not in window.ready_names - assert window.cbb_table.item(0, 2).text() == '未知 / 需确认' - assert window.cbb_table.item(1, 3).text().startswith('SKIPPED') + qtbot.waitUntil(lambda: not window._icdb_active()) + assert calls == ['B'] + assert 'A' in window.ready_names + assert window.cbb_table.item(1, 2).text() == '未知 / 需确认' + assert window.cbb_table.item(2, 3).text() == '未检查' -def test_global_icdb_progress_and_repair_summary(qtbot, tmp_path, monkeypatch): +def test_global_icdb_progress_and_check_summary(qtbot, tmp_path, monkeypatch): from PySide6.QtWidgets import QMessageBox confirmations = [] def confirm(*args, **kwargs): @@ -81,13 +92,14 @@ def test_global_icdb_progress_and_repair_summary(qtbot, tmp_path, monkeypatch): window.lmc_edit.setText('lib.lmc'); window.load_library() qtbot.waitUntil(lambda: not window.busy) window.icdb_repair_button.click() - qtbot.waitUntil(lambda: not window.busy) + qtbot.waitUntil(lambda: not window._icdb_active()) assert 'lib.lmc' in confirmations[0] - assert 'Ready' in confirmations[0] + assert '非 READY' in confirmations[0] assert window.icdb_progress.value() == 1 assert window.icdb_progress.maximum() == 1 - assert '恢复备份待复核 1' in window.status_label.text() - assert window.summary.windowTitle() == '全库 ICDB 检查与修复结果' + assert '无法确认 1' in window.status_label.text() + assert '恢复备份待复核' not in window.status_label.text() + assert window.summary.windowTitle() == 'ICDB 批量检查结果' reports = list((tmp_path/'reports').glob('icdb-*.json')) assert len(reports) == 1 @@ -102,7 +114,7 @@ def test_ready_row_missing_project_is_skipped_by_global_maintenance(qtbot, tmp_p assert window.skipped_names == {'MISSING'} assert 'MISSING' not in window.ready_names assert not window.icdb_repair_button.isEnabled() - assert window.cbb_table.item(0, 2).text().startswith('跳过') + assert '缺少工程' in window.cbb_table.item(0, 2).text() def test_verify_requires_loaded_library_and_invalidates_on_path_change(qtbot): window=MainWindow(reader=fake_reader, verifier=lambda _: VerifyResult('PASS')); qtbot.addWidget(window) @@ -156,8 +168,8 @@ def test_import_incomplete_rows_are_skipped_and_disabled(qtbot, tmp_path): window.lmc_edit.setText(str(lmc)) window.load_library() qtbot.waitUntil(lambda: window.batch_button.isEnabled()) - assert window.cbb_table.item(0, 2).text().startswith('跳过:') - assert not (window.cbb_table.item(0, 0).flags() & Qt.ItemIsUserCheckable) + assert '缺少工程' in window.cbb_table.item(0, 2).text() + assert window.cbb_table.item(0, 0).flags() & Qt.ItemIsUserCheckable window.verify_all() qtbot.waitUntil(lambda: not window.busy) assert calls == ['VALID_CBB'] @@ -218,7 +230,7 @@ def test_large_library_load_does_not_update_controls_for_every_table_cell(qtbot, assert window._row_by_name['CBB_0299'] == 299 assert len(calls) < 20 -def test_ready_rows_show_status_and_cannot_be_selected_or_verified(qtbot, tmp_path): +def test_ready_rows_allow_management_selection_but_cannot_be_verified(qtbot, tmp_path): def reader(_): return LibraryReadResult((CbbRecord('READY_CBB', 'LP', status='READY'), CbbRecord('PENDING_CBB', 'LP', status='PENDING'))) calls = [] @@ -229,15 +241,16 @@ def test_ready_rows_show_status_and_cannot_be_selected_or_verified(qtbot, tmp_pa qtbot.waitUntil(lambda: window.batch_button.isEnabled()) assert window.cbb_table.columnCount() == 4 assert window.cbb_table.item(0, 2).text() == '绿色 / Ready' - assert not (window.cbb_table.item(0, 0).flags() & Qt.ItemIsUserCheckable) + assert window.cbb_table.item(0, 0).flags() & Qt.ItemIsUserCheckable assert window.cbb_table.item(0, 0).background().color().name().lower() == '#e8f5e9' window.cbb_table.item(0, 0).setCheckState(Qt.Checked) - assert 'READY_CBB' not in window._selected_names() + assert 'READY_CBB' in window._selected_names() + assert not window.selected_batch_button.isEnabled() window.verify_all() qtbot.waitUntil(lambda: not window.busy) assert calls == ['PENDING_CBB'] assert window.cbb_table.item(1, 0).checkState() == Qt.Unchecked - assert not (window.cbb_table.item(1, 0).flags() & Qt.ItemIsUserCheckable) + assert window.cbb_table.item(1, 0).flags() & Qt.ItemIsUserCheckable assert window.cbb_table.item(1, 0).background().color().name().lower() == '#e8f5e9' @@ -271,7 +284,7 @@ def test_unc_library_uses_mentor_path_for_read_and_verify_and_releases_on_close( assert calls == [lease.mentor_path] assert window._request('CBB1').lmc_file == lease.mentor_path window.close() - assert lease.closed + qtbot.waitUntil(lambda: lease.closed) def test_advanced_options_are_copied_to_verify_request(qtbot, tmp_path): @@ -340,12 +353,12 @@ def test_ui_default_timeout_matches_request_and_labels_inactivity(qtbot): assert window.timeout_spin.value() == 600 assert window.timeout_spin.value() == VerifyRequest(Path('lib.lmc'), 'CBB1', Path('data')).timeout_seconds assert '无进展' in window.timeout_spin.suffix() - - -def test_batch_summary_exposes_failures_only_report(qtbot, tmp_path): - window = MainWindow(reader=fake_reader, data_root=tmp_path) - qtbot.addWidget(window) - report=tmp_path/'reports/batch-20260929-test.log' - window._batch_done(([VerifyResult('FAIL',stderr='Mentor error')],report)) - assert '仅失败日志' in window.summary.text() - assert str(report.with_name('failures-20260929-test.log')) in window.summary.text() + + +def test_batch_summary_exposes_failures_only_report(qtbot, tmp_path): + window = MainWindow(reader=fake_reader, data_root=tmp_path) + qtbot.addWidget(window) + report=tmp_path/'reports/batch-20260929-test.log' + window._batch_done(([VerifyResult('FAIL',stderr='Mentor error')],report)) + assert '仅失败日志' in window.summary.detailedText() + assert str(report.with_name('failures-20260929-test.log')) in window.summary.detailedText() diff --git a/tests/test_ui_batch_safety.py b/tests/test_ui_batch_safety.py new file mode 100644 index 0000000..a180568 --- /dev/null +++ b/tests/test_ui_batch_safety.py @@ -0,0 +1,247 @@ +"""No native applications or shared execution mutex are used by these regressions.""" +import json +from dataclasses import replace +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from cbb_refresh_verify import verify_runner as runner +from cbb_refresh_verify.status_bridge import BridgeResult +from test_verify_runner import fixture, request, PORTS_OK + + +@pytest.fixture +def isolated_verify(tmp_path, monkeypatch): + import win32event + fixture(tmp_path) + monkeypatch.setattr(win32event, 'CreateMutex', lambda *_: SimpleNamespace(Close=lambda: None)) + monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *_: 0) + monkeypatch.setattr(win32event, 'ReleaseMutex', lambda *_: None) + monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k: + {'safe_to_continue': True, 'remaining_pids': []}) + monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *_: None) + monkeypatch.setattr(runner, 'read_library_flag_if_available', + lambda *_: BridgeResult('READY', 'IsVerifiedReuseBlock', 1)) + return request(tmp_path) + + +def test_invalid_proof_is_safe_before_worker_launch(isolated_verify, monkeypatch): + monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', + lambda *_: pytest.fail('invalid proof launched a worker')) + req = replace(isolated_verify, post_repair_proof=object()) + results = runner.run_batch([req, req], verifier=lambda r: runner.run_verify(r, port_check=PORTS_OK)) + assert [r.status for r in results] == ['BLOCKED', 'BLOCKED'] + assert all(r.safe_to_continue for r in results) + + +@pytest.mark.parametrize('failure', ['directory', 'runtime', 'request', 'worker_log']) +def test_prelaunch_disk_failure_does_not_stop_independent_items(isolated_verify, monkeypatch, failure): + class FinishedWorker: + desktop = None + returncode = 0 + def __init__(self, command, *_a, **_k): + Path(command[-1]).with_name('outcome.json').write_text('{"status":"PASS"}') + def poll(self): return 0 + def close(self): pass + monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', FinishedWorker) + mkdir, write, open_file = Path.mkdir, Path.write_text, Path.open + def make(path, *a, **k): + if failure == 'directory' and path.name.startswith('verify-'): + raise OSError('evidence volume unavailable') + return mkdir(path, *a, **k) + def save(path, *a, **k): + if path.name == {'runtime': 'runtime.json', 'request': 'request.json'}.get(failure): + raise OSError('evidence volume unavailable') + return write(path, *a, **k) + def opening(path, *a, **k): + if failure == 'worker_log' and path.name == 'worker.log': + raise OSError('evidence volume unavailable') + return open_file(path, *a, **k) + monkeypatch.setattr(Path, 'mkdir', make) + monkeypatch.setattr(Path, 'write_text', save) + monkeypatch.setattr(Path, 'open', opening) + from cbb_refresh_verify import library_lock as locks + try: + results = runner.run_batch([isolated_verify, isolated_verify], + verifier=lambda r: runner.run_verify(r, port_check=PORTS_OK)) + assert all(r.safe_to_continue for r in results) + assert [r.status for r in results] == (['PASS', 'PASS'] if failure == 'runtime' else ['FAIL', 'FAIL']) + assert locks.LibraryLock(isolated_verify.lmc_file).key not in locks._owners + finally: + owner = locks._owners.pop(locks.LibraryLock(isolated_verify.lmc_file).key, None) + if owner: owner['handle'].Close() + + +def test_coordination_permission_failure_does_not_manufacture_native_owner(isolated_verify, monkeypatch): + from cbb_refresh_verify.library_lock import LibraryLock + def denied(_): raise PermissionError('coordination directory is read-only') + monkeypatch.setattr(LibraryLock, '__enter__', denied) + monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', + lambda *_: pytest.fail('permission failure launched native work')) + results = runner.run_batch([isolated_verify, isolated_verify], + verifier=lambda r: runner.run_verify(r, port_check=PORTS_OK)) + assert [r.status for r in results] == ['FAIL', 'FAIL'] + assert all(r.safe_to_continue and r.error_category == 'LIBRARY_ACCESS_FAILED' for r in results) + + +@pytest.mark.parametrize('launch_state', ['never_created', 'unknown', 'partially_created']) +def test_constructor_release_evidence_controls_batch_continuation(isolated_verify, monkeypatch, launch_state): + proven_rollback = launch_state == 'never_created' + launches = [] + def fail_launch(*_a, **_k): + launches.append(True) + error = RuntimeError('worker launch failed') + if launch_state != 'unknown': + error.worker_launch_release = {'safe_to_continue': True, 'worker_exited': True, + 'remaining_pids': [], 'process_created': not proven_rollback} + raise error + monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', fail_launch) + from cbb_refresh_verify import library_lock as locks + try: + results = runner.run_batch([isolated_verify, isolated_verify], + verifier=lambda r: runner.run_verify(r, port_check=PORTS_OK)) + assert len(launches) == (2 if proven_rollback else 1) + assert results[0].safe_to_continue is proven_rollback + if proven_rollback: + proof = json.loads(results[0].evidence_path.with_name('session-release.json').read_text('utf-8')) + assert proof['worker_exited'] and proof['safe_to_continue'] + assert locks.LibraryLock(isolated_verify.lmc_file).key not in locks._owners + finally: + with locks._guard: + owner = locks._owners.pop(locks.LibraryLock(isolated_verify.lmc_file).key, None) + if owner: + owner['handle'].Close() + + +@pytest.mark.parametrize('filename', ['result.json', 'performance.json', 'bridge-status.json']) +def test_optional_evidence_write_failure_preserves_released_result(isolated_verify, monkeypatch, filename): + class FinishedWorker: + desktop = None + returncode = 0 + def __init__(self, command, *_a, **_k): + Path(command[-1]).with_name('outcome.json').write_text('{"status":"PASS"}') + def poll(self): return 0 + def close(self): pass + monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', FinishedWorker) + original = Path.write_text + def write(path, *a, **k): + if path.name == filename: + raise OSError('report disk unavailable') + return original(path, *a, **k) + monkeypatch.setattr(Path, 'write_text', write) + results = runner.run_batch([isolated_verify, isolated_verify], + verifier=lambda r: runner.run_verify(r, port_check=PORTS_OK)) + assert [r.status for r in results] == ['PASS', 'PASS'] + assert all(r.safe_to_continue for r in results) + + +def test_progress_failure_does_not_stop_safe_batch(isolated_verify): + def failed_progress(*_): + raise RuntimeError('view was closed') + results = runner.run_batch([isolated_verify, isolated_verify], + verifier=lambda _: runner.VerifyResult('FAIL', safe_to_continue=True), progress=failed_progress) + assert len(results) == 2 and all(r.safe_to_continue for r in results) + + +def test_performance_progress_failure_preserves_release(isolated_verify, monkeypatch): + root = isolated_verify.evidence_dir + root.mkdir() + result = runner.VerifyResult('FAIL', safe_to_continue=True, evidence_path=root/'result.json') + monkeypatch.setattr(runner, '_run_verify', lambda *a, **k: result) + def progress(event): + if event['stage'] == 'performance': + raise RuntimeError('view was closed') + actual = runner._run_verify_serialized(isolated_verify, progress=progress) + assert actual.safe_to_continue and actual.status == 'FAIL' + + +def test_performance_logger_failure_preserves_release(isolated_verify, monkeypatch): + def unavailable_log(*_a, **_k): + raise OSError('log destination unavailable') + req = replace(isolated_verify, logging_context=SimpleNamespace(logger=SimpleNamespace(info=unavailable_log))) + monkeypatch.setattr(runner, '_run_verify', lambda *a, **k: runner.VerifyResult('FAIL', safe_to_continue=True)) + result = runner._run_verify_serialized(req) + assert result.safe_to_continue and result.status == 'FAIL' + + +def test_management_unsafe_survives_switching_back_to_library(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + from cbb_refresh_verify.management import Capability + adapter = SimpleNamespace(capabilities=lambda: {op: Capability(True, 'available') + for op in ('add', 'update', 'remove')}) + window = load_window(qtbot, tmp_path, monkeypatch, management_adapter=adapter) + window.path_lease_factory = lambda path: SimpleNamespace(mentor_path=path, close=lambda: None, + retain_for_recovery=lambda: None) + library_a = tmp_path/'a.lmc' + library_b = tmp_path/'b.lmc' + window._management_unsafe = True + window._management_unsafe_library = library_a + for library, blocked in [(library_b, False), (library_a, True)]: + window.lmc_edit.setText(str(library)) + window.load_library() + qtbot.waitUntil(lambda: not window.busy) + assert window._management_library_unsafe(library) is blocked + assert not window._management_block_reason('add') + assert window.batch_button.isEnabled() + + +@pytest.mark.parametrize('released', [True, False]) +def test_batch_report_failure_preserves_ui_outcomes(qtbot, tmp_path, monkeypatch, released): + from test_ui_filters import load_window + import cbb_refresh_verify.ui.main_window as ui + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda _: runner.VerifyResult('FAIL', stderr='item failed', safe_to_continue=released), + status_refresher=lambda names, _: {name: 'PENDING' for name in names}) + retained = [] + window.library_lease.retain_for_recovery = lambda: retained.append(True) + monkeypatch.setattr(ui, 'write_batch_report', lambda *_: (_ for _ in ()).throw(OSError('report unavailable'))) + window._run(['Beta', 'Gamma']) + qtbot.waitUntil(lambda: not window.busy) + assert bool(retained) is not released + assert 'report unavailable' in window.output.toPlainText() + assert 'item failed' in window.output.toPlainText() + assert window.batch_button.isEnabled() + + + + +@pytest.mark.parametrize('alias', ['absolute', 'mapped']) +def test_native_backup_session_matches_library_alias_without_network_resolution(qtbot, tmp_path, monkeypatch, alias): + from test_ui_filters import load_window + window = load_window(qtbot, tmp_path, monkeypatch) + if alias == 'absolute': + current = Path.cwd()/'test.lmc' + session_library = Path('test.lmc') + session_lease = None + else: + current = Path('T:/folder/lib.lmc') + session_library = Path('S:/folder/lib.lmc') + window.library_lease = SimpleNamespace(mentor_path=current, display_path=current, + drive='T:', remote_root=r'\\server\share', close=lambda: None) + session_lease = SimpleNamespace(mentor_path=session_library, display_path=session_library, + drive='S:', remote_root=r'\\server\share') + window.mentor_lmc_path = current + window._native_backup_session = SimpleNamespace(library=session_library, path_lease=session_lease) + try: + with monkeypatch.context() as context: + context.setattr(Path, 'resolve', lambda *_a, **_k: pytest.fail('UI touched network resolution')) + assert window._native_backup_same_library() + finally: + window._native_backup_session = None + + + + +def test_opening_evidence_failure_does_not_retain_library(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + window = load_window(qtbot, tmp_path, monkeypatch) + retained = [] + window.library_lease.retain_for_recovery = lambda: retained.append(True) + window.recovery_path = tmp_path + def cannot_open(*_): + raise OSError('file viewer unavailable') + monkeypatch.setattr('os.startfile', cannot_open) + window.recover() + assert not retained + assert 'file viewer unavailable' in window.output.toPlainText() diff --git a/tests/test_ui_filters.py b/tests/test_ui_filters.py new file mode 100644 index 0000000..b8d8ff2 --- /dev/null +++ b/tests/test_ui_filters.py @@ -0,0 +1,291 @@ +"""Local catalog scope and authoritative status refresh regression tests.""" +import json +import time +from threading import Event +from pathlib import Path +from types import SimpleNamespace + +import pytest +from PySide6.QtCore import Qt +from PySide6.QtWidgets import QMessageBox + +from cbb_refresh_verify.models import CbbRecord, LibraryReadResult +from cbb_refresh_verify.ui.main_window import MainWindow +from cbb_refresh_verify.verify_runner import VerifyResult + + +MIXED = ( + CbbRecord('Alpha', 'Power', status='READY'), + CbbRecord('Beta', 'Power', status='PENDING'), + CbbRecord('Gamma', 'Analog', status='UNKNOWN'), + CbbRecord('Delta', 'Analog', status='ERROR'), + CbbRecord('Missing', 'Power', status='READY'), +) + + +def load_window(qtbot, tmp_path, monkeypatch, records=MIXED, **kwargs): + monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes) + import cbb_refresh_verify.ui.main_window as ui + monkeypatch.setattr(ui, 'preflight_skip_reason', + lambda _, name: 'missing project' if name == 'Missing' else None) + lease = SimpleNamespace(mentor_path=Path('test.lmc'), close=lambda: None, + retain_for_recovery=lambda: None) + window = MainWindow(reader=lambda _: LibraryReadResult(records), data_root=tmp_path, + path_lease_factory=lambda _: lease, **kwargs) + qtbot.addWidget(window) + window.lmc_edit.setText('test.lmc') + window.load_library() + qtbot.waitUntil(lambda: not window.busy) + return window + + +def names(records): + return [record.name for record in records] + + +def test_search_and_filters_use_cached_catalog_and_count_visible_states(qtbot, tmp_path, monkeypatch): + window = load_window(qtbot, tmp_path, monkeypatch) + window.reader = lambda _: pytest.fail('filter reread Mentor') + assert window.visible_counts() == {'visible': 5, 'ready': 2, 'error': 3} + expected = { + 'ready': ['Alpha', 'Missing'], 'non_ready': ['Beta', 'Gamma', 'Delta'], + 'pending': ['Beta'], 'errors': ['Gamma', 'Delta'], 'missing': ['Missing'], + } + for mode, wanted in expected.items(): + window.status_filter.setCurrentIndex(window.status_filter.findData(mode)) + assert names(window.visible_records()) == wanted + window.status_filter.setCurrentIndex(window.status_filter.findData('all')) + window.search_edit.setText(' ANALOG ') + assert names(window.visible_records()) == ['Gamma', 'Delta'] + assert window.visible_counts() == {'visible': 2, 'ready': 0, 'error': 2} + window.search_edit.setText('aLpH') + assert names(window.visible_records()) == ['Alpha'] + assert '1' in window.counts_label.text() + + +def test_management_selection_includes_ready_and_missing_but_hiding_clears_checks(qtbot, tmp_path, monkeypatch): + window = load_window(qtbot, tmp_path, monkeypatch) + window.select_visible_button.click() + assert names(window.selected_records()) == ['Alpha', 'Beta', 'Gamma', 'Delta', 'Missing'] + assert window.selected_records()[0].logical_type == 'LP' + window.search_edit.setText('power') + assert names(window.selected_records()) == ['Alpha', 'Beta', 'Missing'] + window.search_edit.clear() + assert names(window.selected_records()) == ['Alpha', 'Beta', 'Missing'] + window.clear_selection_button.click() + assert window.selected_records() == () + + +def test_verify_all_and_selected_only_target_visible_non_ready_with_projects(qtbot, tmp_path, monkeypatch): + calls = [] + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')), + status_refresher=lambda names, _: {name: 'READY' for name in names}) + window.search_edit.setText('power') + window.select_visible_button.click() + window.verify_selected() + qtbot.waitUntil(lambda: not window.busy) + assert calls == ['Beta'] + window.search_edit.setText('analog') + window.verify_all() + qtbot.waitUntil(lambda: not window.busy) + assert calls == ['Beta', 'Gamma', 'Delta'] + + +def test_maintenance_confirmation_progress_and_report_use_visible_checked_subset(qtbot, tmp_path, monkeypatch): + calls, confirmations, refreshes = [], [], [] + def refresh(targets, _): + refreshes.append(tuple(targets)) + return {name: 'PENDING' for name in targets} + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda req: (calls.append(req.block_name) or VerifyResult('CHECKED')), + status_refresher=refresh) + window.search_edit.setText('analog') + window.cbb_table.item(3, 0).setCheckState(Qt.Checked) + monkeypatch.setattr(QMessageBox, 'question', lambda *args, **_: ( + confirmations.append(args[2]) or QMessageBox.Yes)) + window.repair_icdb_all() + qtbot.waitUntil(lambda: not window._icdb_active()) + assert calls == ['Delta'] + assert refreshes == [] + assert '1' in confirmations[0] and '非 READY' in confirmations[0] + assert window.icdb_progress.maximum() == 1 and window.icdb_progress.value() == 1 + report = json.loads(next((tmp_path/'reports').glob('icdb-*.json')).read_text(encoding='utf-8')) + assert report['includes_ready'] is False + assert report['target_names'] == ['Delta'] + assert report['preflight_skipped'] == [] + assert report['counts']['total'] == 1 + assert window.search_edit.text() == 'analog' + assert window.cbb_table.item(3, 3).text() == '未发现 ICDB 错误' + assert names(window.visible_records()) == ['Gamma', 'Delta'] + assert window.visible_records()[1].status == 'ERROR' + + +def test_maintenance_defaults_to_visible_eligible_and_ready_only_checks_do_not_fallback(qtbot, tmp_path, monkeypatch): + calls = [] + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')), + status_refresher=lambda targets, _: {name: 'PENDING' for name in targets}) + monkeypatch.setattr(QMessageBox, 'question', lambda *_, **__: QMessageBox.Yes) + window.cbb_table.item(0, 0).setCheckState(Qt.Checked) + window.repair_icdb_all() + assert not window.busy and calls == [] + window.clear_selection_button.click() + window.search_edit.setText('power') + window.repair_icdb_all() + qtbot.waitUntil(lambda: not window._icdb_active()) + assert calls == ['Beta'] + + +def test_recovery_defaults_to_visible_checked_non_ready_and_skips_ready(qtbot, tmp_path, monkeypatch): + window = load_window(qtbot, tmp_path, monkeypatch) + window.search_edit.setText('power') + window.restore_backup() + assert [window.backup_dialog.block_combo.itemText(i) + for i in range(window.backup_dialog.block_combo.count())] == ['Beta'] + window.backup_dialog.reject() + window.search_edit.clear() + window.cbb_table.item(3, 0).setCheckState(Qt.Checked) + window.restore_backup() + assert window.backup_dialog.block_combo.currentText() == 'Delta' + assert window.backup_dialog.block_combo.count() == 1 + window.backup_dialog.reject() + + +def test_action_pass_does_not_promote_pending_without_authoritative_ready(qtbot, tmp_path, monkeypatch): + entered = [] + window = load_window(qtbot, tmp_path, monkeypatch, + status_refresher=lambda targets, _: (entered.extend(targets) or {'Beta': 'READY'})) + window.status_filter.setCurrentIndex(window.status_filter.findData('pending')) + window.cbb_table.item(1, 0).setCheckState(Qt.Checked) + window._progress({'block': 'Beta', 'stage': 'PASS'}) + assert names(window.visible_records()) == ['Beta'] + assert window.visible_records()[0].status == 'PENDING' + window.refresh_affected_records(['Beta']) + qtbot.waitUntil(lambda: not window.busy) + assert entered == ['Beta'] + assert window.visible_records() == () + assert window.selected_records() == () + assert window.status_filter.currentData() == 'pending' + window.status_filter.setCurrentIndex(window.status_filter.findData('ready')) + assert names(window.visible_records()) == ['Alpha', 'Beta', 'Missing'] + assert window.cbb_table.item(1, 3).text() == 'PASS' + + +def test_refresh_failure_demotes_affected_without_losing_other_statuses(qtbot, tmp_path, monkeypatch): + def fail(*_): + raise OSError('bridge unavailable') + window = load_window(qtbot, tmp_path, monkeypatch, status_refresher=fail) + window.refresh_affected_records(['Alpha']) + qtbot.waitUntil(lambda: not window.busy) + assert window.visible_records()[0].status == 'UNKNOWN' + assert window.visible_records()[1].status == 'PENDING' + assert 'Alpha' not in window.ready_names + assert 'bridge unavailable' in window.output.toPlainText() + + +def test_unsafe_result_defers_native_refresh_and_retains_action_evidence(qtbot, tmp_path, monkeypatch): + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda _: VerifyResult('FAIL', stderr='owner release unconfirmed', + safe_to_continue=False, evidence_path=tmp_path/'evidence.json'), + status_refresher=lambda *_: pytest.fail('unsafe owner was reopened')) + window.search_edit.setText('beta') + window.verify_all() + qtbot.waitUntil(lambda: not window.busy) + assert window.visible_records()[0].status == 'UNKNOWN' + assert window.cbb_table.item(1, 3).text() == 'FAIL: owner release unconfirmed' + assert str(tmp_path/'evidence.json') in window.output.toPlainText() + assert '暂缓原生状态复核' in window.cbb_table.item(1, 2).toolTip() + + +def test_refresh_callback_uses_only_known_affected_records_and_preserves_logical_type(qtbot, tmp_path, monkeypatch): + observed, callbacks = [], [] + def refresh(targets, path): + observed.append((targets, path)) + return {'X': 'READY'} + window = load_window(qtbot, tmp_path, monkeypatch, + records=(CbbRecord('X', 'Display label', logical_type='RULP', status='PENDING'),), + status_refresher=refresh) + assert window.refresh_affected_records(['unknown']) is False + assert window.refresh_affected_records(['X', 'X', 'unknown'], callbacks.append) is True + assert window.refresh_affected_records(['X']) is False + qtbot.waitUntil(lambda: not window.busy) + assert observed == [(('X',), Path('test.lmc'))] + assert callbacks == [(CbbRecord('X', 'Display label', logical_type='RULP', status='READY'),)] + + +def test_backup_completion_refreshes_status_without_dialog_close_unlocking_pending_refresh(qtbot, tmp_path, monkeypatch): + entered, release = Event(), Event() + def refresh(targets, _): + entered.set() + release.wait(3) + return {name: 'PENDING' for name in targets} + window = load_window(qtbot, tmp_path, monkeypatch, status_refresher=refresh) + window.search_edit.setText('beta') + window.restore_backup() + window.backup_dialog.started.emit('Beta') + window.backup_dialog.completed.emit('Beta', VerifyResult('PASS')) + try: + qtbot.waitUntil(entered.is_set) + window.backup_dialog.reject() + assert window.busy + finally: + release.set() + qtbot.waitUntil(lambda: not window.busy) + assert window.visible_records()[0].status == 'PENDING' + assert window.cbb_table.item(1, 3).text() == 'PASS' + + +def test_missing_project_keeps_explicit_authoritative_status(qtbot, tmp_path, monkeypatch): + window = load_window(qtbot, tmp_path, monkeypatch) + assert 'Ready' in window.cbb_table.item(4, 2).text() + assert '缺少工程' in window.cbb_table.item(4, 2).text() + + +def test_open_backup_dialog_cannot_restore_target_that_became_ready(qtbot, tmp_path, monkeypatch): + calls = [] + window = load_window(qtbot, tmp_path, monkeypatch, + status_refresher=lambda targets, _: {name: 'READY' for name in targets}) + window.search_edit.setText('beta') + window.restore_backup() + dialog = window.backup_dialog + source = tmp_path/'Beta.prj' + source.touch() + dialog.source_edit.setText(str(source)) + dialog.recoverer = lambda *_, **__: (calls.append('restore') or VerifyResult('PASS')) + window.refresh_affected_records(['Beta']) + qtbot.waitUntil(lambda: not window.busy) + dialog.restore_button.click() + qtbot.waitUntil(lambda: not dialog.busy) + assert calls == [] + assert '非 READY' in dialog.status_label.text() + dialog.reject() + + +@pytest.mark.parametrize('status', ['UNKNOWN', 'UNAVAILABLE', 'ERROR', 'TIMEOUT', 'MALFORMED', 'CRASHED', + 'UNRECOGNIZED']) +def test_unconfirmed_statuses_are_non_ready_and_error_filter_candidates(qtbot, tmp_path, monkeypatch, status): + window = load_window(qtbot, tmp_path, monkeypatch, records=(CbbRecord('X', 'LP', status=status),)) + window.status_filter.setCurrentIndex(window.status_filter.findData('non_ready')) + assert names(window.visible_records()) == ['X'] + window.status_filter.setCurrentIndex(window.status_filter.findData('errors')) + assert names(window.visible_records()) == ['X'] + + +@pytest.mark.parametrize('size', [381, 3000]) +def test_large_catalog_local_filter_and_selection_remain_responsive(qtbot, tmp_path, monkeypatch, size): + records = tuple(CbbRecord(f'CBB{i:04}', 'Power' if i % 2 else 'Analog', + status='READY' if i % 3 == 0 else 'PENDING') for i in range(size)) + start = time.perf_counter() + window = load_window(qtbot, tmp_path, monkeypatch, records=records) + loaded = time.perf_counter() - start + window.reader = lambda _: pytest.fail('local actions reread Mentor') + start = time.perf_counter() + window.search_edit.setText('power') + window.select_visible_button.click() + window.status_filter.setCurrentIndex(window.status_filter.findData('pending')) + window.clear_selection_button.click() + elapsed = time.perf_counter() - start + print(f'catalog rows={size} load={loaded:.3f}s local_actions={elapsed:.3f}s') + assert elapsed < 2.0 + assert window.selected_records() == () diff --git a/tests/test_ui_lease_lifecycle.py b/tests/test_ui_lease_lifecycle.py new file mode 100644 index 0000000..cc0466d --- /dev/null +++ b/tests/test_ui_lease_lifecycle.py @@ -0,0 +1,133 @@ +"""Lease calls may wait on WNet; the Qt event loop must never wait for them.""" +from pathlib import Path +from threading import Event, get_ident +from types import SimpleNamespace + +from PySide6.QtCore import QTimer + +from test_ui_filters import load_window + + +def slow_lease(main_thread): + entered, release, closed = Event(), Event(), Event() + calls = [] + def retain(): + assert get_ident() != main_thread, 'retain blocked the Qt thread' + calls.append('retain') + entered.set() + assert release.wait(3) + def close(): + assert get_ident() != main_thread, 'close blocked the Qt thread' + calls.append('close') + closed.set() + lease = SimpleNamespace(mentor_path=Path('test.lmc'), retain_for_recovery=retain, close=close) + return lease, entered, release, closed, calls + + +def test_unsafe_background_retains_before_a_later_cross_library_close(qtbot, tmp_path, monkeypatch): + from cbb_refresh_verify.verify_runner import VerifyResult + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda _: VerifyResult('FAIL', safe_to_continue=False)) + lease, entered, release, closed, calls = slow_lease(get_ident()) + window.library_lease = lease + try: + window._run(['Beta'], maintenance=True) + qtbot.waitUntil(entered.is_set) + ticks = [] + QTimer.singleShot(0, lambda: ticks.append(True)) + window.lmc_edit.setText('other.lmc') + qtbot.waitUntil(lambda: bool(ticks)) + assert window.search_edit.isEnabled() and not closed.is_set() + release.set() + qtbot.waitUntil(closed.is_set) + assert calls == ['retain', 'close'] + finally: + release.set() + qtbot.waitUntil(lambda: window.pool.activeThreadCount() == 0) + + +def test_management_dialog_finish_waits_for_mapping_cleanup_without_freezing_filters(qtbot, tmp_path, monkeypatch): + from cbb_refresh_verify.management import ManagementResult + window = load_window(qtbot, tmp_path, monkeypatch) + library = Path(window.mentor_lmc_path) + window._management_operation_library = library + window._management_unsafe = True + window._management_unsafe_library = library + window.busy = True + entered, release = Event(), Event() + main_thread = get_ident() + def restore(*args, **kwargs): + assert get_ident() != main_thread, 'mapping release blocked the Qt thread' + entered.set() + assert release.wait(3) + monkeypatch.setattr('cbb_refresh_verify.network_path.release_retained_path_leases', restore) + proof = {'status': 'RELEASE_CONFIRMED', 'library': str(library)} + result = ManagementResult('remove', library, 'Beta', 'Logical-Physical', None, False, + 'complete', 'BLOCKED', True, release_proof=proof) + try: + window._management_completed([result]) + window._management_closed() + qtbot.waitUntil(entered.is_set) + assert window.busy and window.search_edit.isEnabled() and window.status_filter.isEnabled() + assert window._management_library_unsafe(library) + release.set() + qtbot.waitUntil(lambda: not window.busy) + assert not window._management_library_unsafe(library) + finally: + release.set() + qtbot.waitUntil(lambda: window.pool.activeThreadCount() == 0) + + + + +def test_window_close_waits_asynchronously_for_retain_and_all_pool_work(qtbot, tmp_path, monkeypatch): + window = load_window(qtbot, tmp_path, monkeypatch) + lease, entered, release, closed, calls = slow_lease(get_ident()) + window.library_lease = SimpleNamespace(mentor_path=Path('other.lmc'), close=lease.close) + window._native_backup_session = SimpleNamespace(path_lease=lease, library=Path('test.lmc')) + window.show() + try: + window.close() + qtbot.waitUntil(entered.is_set) + ticks = [] + QTimer.singleShot(0, lambda: ticks.append(True)) + qtbot.waitUntil(lambda: bool(ticks)) + assert window.isVisible() and not closed.is_set() + release.set() + qtbot.waitUntil(lambda: not window.isVisible()) + assert calls == ['retain', 'close'] + assert window.pool.activeThreadCount() == 0 + finally: + release.set() + qtbot.waitUntil(lambda: window.pool.activeThreadCount() == 0) + window._native_backup_session = None + + +def test_duplicate_dialog_finish_schedules_only_one_catalog_reload(qtbot, tmp_path, monkeypatch): + from cbb_refresh_verify.management import ManagementResult + window = load_window(qtbot, tmp_path, monkeypatch) + library = Path(window.mentor_lmc_path) + window._management_operation_library = library + window.busy = True + entered, release = Event(), Event() + reloads = [] + monkeypatch.setattr(window, 'load_library', lambda: reloads.append(True)) + def restore(*args, **kwargs): + entered.set() + assert release.wait(3) + monkeypatch.setattr('cbb_refresh_verify.network_path.release_retained_path_leases', restore) + result = ManagementResult('remove', library, 'Beta', 'Logical-Physical', None, False, + 'complete', 'REMOVED', True, release_proof={'status': 'RELEASE_CONFIRMED', 'library': str(library)}) + try: + window._management_completed([result]) + window._management_closed(); window._management_closed() + qtbot.waitUntil(entered.is_set) + release.set() + qtbot.waitUntil(lambda: not window.busy) + qtbot.waitUntil(lambda: bool(reloads)) + assert reloads == [True] + finally: + release.set() + qtbot.waitUntil(lambda: window.pool.activeThreadCount() == 0) + + -- 2.39.5 From 8c2c60fab1837fb31c382d33f48662f46dcd0b2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Fri, 6 Nov 2026 11:36:19 +0800 Subject: [PATCH 2/3] fix: distinguish native outcomes from report and item recovery status --- docs/reviews/2026-11-06-ui-followup.md | 7 +++++ .../ui/management_dialog.py | 17 +++++++++- tests/test_independent_operations.py | 14 ++++++--- tests/test_review_management_ui_followup.py | 31 +++++++++++++++++++ 4 files changed, 64 insertions(+), 5 deletions(-) create mode 100644 docs/reviews/2026-11-06-ui-followup.md create mode 100644 tests/test_review_management_ui_followup.py diff --git a/docs/reviews/2026-11-06-ui-followup.md b/docs/reviews/2026-11-06-ui-followup.md new file mode 100644 index 0000000..f72ed9e --- /dev/null +++ b/docs/reviews/2026-11-06-ui-followup.md @@ -0,0 +1,7 @@ +# 评论 275/283:结果口径接入 + +管理进度显示历史占用复核;结果分别呈现已确认的原生动作、变更清单完整性和历史会话释放事实。单项 RECOVERY_REQUIRED 但 safe_to_continue=True 时,不再声称整个队列停止;记录失败不伪装成原生上传/移除失败。 + +独立操作回归更新为实际历史记录归档流程:先证明当前占用已释放、保留归档字节,再进行普通验证;不自动 Repair,失败后不遗留新的占用锁。 + +本阶段相关 UI/独立操作/后端回归 29 passed。后端完整回归与最终集成回归另见验证记录。没有执行真实 Mentor 写操作;回退按依赖逆序,不代表恢复原生事务。 diff --git a/src/cbb_refresh_verify/ui/management_dialog.py b/src/cbb_refresh_verify/ui/management_dialog.py index 59bad6b..f883fad 100644 --- a/src/cbb_refresh_verify/ui/management_dialog.py +++ b/src/cbb_refresh_verify/ui/management_dialog.py @@ -14,7 +14,7 @@ from ..management import run_management_batch, validate_name RESULT_LABELS = { 'REMOVED': '已移除', 'UPLOADED': '已上传 / 未自动校验', 'UPLOADED_VERIFIED': '已上传且校验通过', 'UPLOADED_VERIFY_FAILED': '已上传但校验未通过', - 'UPLOAD_FAILED': '上传失败', 'RECOVERY_REQUIRED': '需要人工恢复 / 队列已停止', + 'UPLOAD_FAILED': '上传失败', 'RECOVERY_REQUIRED': '需要人工恢复', 'BLOCKED': '操作被阻止', 'UNSUPPORTED': '当前环境不支持', } STAGE_LABELS = { @@ -25,6 +25,9 @@ STAGE_LABELS = { 'verify': '正在校验上传结果', 'verified': '校验已返回', 'copy': '正在准备来源副本', 'hash': '正在校验主要文件', 'release_check': '正在检查工程是否被占用', + 'previous_release_check': '正在复核历史占用', + 'previous_release_confirmed': '历史会话已确认释放', + 'previous_release_unconfirmed': '占用复核未通过', } @@ -203,6 +206,18 @@ class ManagementDialog(QDialog): for result in results: summary = f'{result.name}:{RESULT_LABELS.get(result.status, result.status)}' text = f'{summary} — {result.detail}' + changes = getattr(result, 'change_report', None) + if changes: + if changes.get('status') == 'RECORDED': + text += (f'\n变更:新增 {len(changes["added"])}、删除 {len(changes["deleted"])}、' + f'修改 {len(changes["modified"])} 个主要文件。') + else: + summary += ',变更清单待核对' + text += '\n'+changes.get('detail', '变更清单未确认') + if getattr(result, 'release_proof', None): + text += '\n历史会话已释放;历史工程数据的恢复状态需另行核对。' + if not result.safe_to_continue: + summary += ',原生会话释放待确认' if self.recovery_from and result.status == 'UPLOADED_VERIFIED': summary += ',版本待核对。' elif result.status not in ('UPLOADED', 'UPLOADED_VERIFIED', 'REMOVED'): diff --git a/tests/test_independent_operations.py b/tests/test_independent_operations.py index 276e94b..d1baa44 100644 --- a/tests/test_independent_operations.py +++ b/tests/test_independent_operations.py @@ -6,7 +6,7 @@ from test_maintenance_entry import case def test_verify_defaults_to_no_repair_and_does_not_retain_a_failure_lock(tmp_path, monkeypatch): from cbb_refresh_verify import verify_runner as runner, library_lock as locks, native_repair - library = tmp_path / 'library.lmc'; library.touch() + library = tmp_path / 'library/library.lmc'; library.parent.mkdir(); library.touch() req = runner.VerifyRequest(library, 'CBB', tmp_path / 'evidence') assert req.auto_repair is False marker = locks.blocker_path(library) @@ -16,11 +16,17 @@ def test_verify_defaults_to_no_repair_and_does_not_retain_a_failure_lock(tmp_pat error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=True) monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: (calls.append('verify') or result)) monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **k: pytest.fail('verify requested Repair')) - assert runner.run_verify(req) is result + monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: []) + monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: []) + first = runner.run_verify(req) + assert first.status == result.status and first.error_category == result.error_category + assert first.release_proof['status'] == 'RELEASE_CONFIRMED' assert runner.run_verify(req) is result assert calls == ['verify', 'verify'] - assert marker.read_text() == 'historical diagnostic record' - assert locks._key(tmp_path / '.library.cbb-upload.lock') not in locks._owners + assert not marker.exists() + archive = Path(first.release_proof['evidence_path']).with_name('blocker-before-0.json') + assert archive.read_text() == 'historical diagnostic record' + assert locks._key(library.parent / '.library.cbb-upload.lock') not in locks._owners def test_catalog_checkpoint_does_not_disable_ordinary_verify(qtbot, tmp_path, monkeypatch): diff --git a/tests/test_review_management_ui_followup.py b/tests/test_review_management_ui_followup.py new file mode 100644 index 0000000..ef34087 --- /dev/null +++ b/tests/test_review_management_ui_followup.py @@ -0,0 +1,31 @@ +from dataclasses import replace + +from test_management import setup + + +def test_released_item_failure_does_not_claim_entire_queue_stopped(qtbot, setup): + from cbb_refresh_verify.management import ManagementResult + from cbb_refresh_verify.ui.management_dialog import ManagementDialog + request, _, _ = setup + dialog=ManagementDialog([request]);qtbot.addWidget(dialog) + result=ManagementResult(request.operation,request.library,request.name,request.partition, + None,False,'complete','RECOVERY_REQUIRED',True,'native add failed') + dialog._result([result]) + assert '需要人工恢复' in dialog.status_label.text() + assert '队列已停止' not in dialog.status_label.text() + + +def test_report_failure_is_visible_without_inventing_native_failure(qtbot, setup): + from cbb_refresh_verify.management import ManagementResult + from cbb_refresh_verify.ui.management_dialog import ManagementDialog + request, _, _=setup + dialog=ManagementDialog([request]);qtbot.addWidget(dialog) + result=ManagementResult(request.operation,request.library,request.name,request.partition, + None,False,'complete','REMOVED',True,'removed',release_proof={ + 'status':'RELEASE_CONFIRMED','data_recovery_confirmed':False}, + change_report={'status':'UNCONFIRMED','detail':'report disk full'}) + dialog._result([result]) + assert '已移除' in dialog.status_label.text() and '变更清单待核对' in dialog.status_label.text() + assert '历史会话已释放' in dialog.output.toPlainText() + dialog._progress({'stage':'previous_release_check','block':request.name}) + assert '正在复核历史占用' in dialog.status_label.text() -- 2.39.5 From 342a7266c710a9c69ab70ad997054abb4a3f04a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Mon, 9 Nov 2026 13:51:32 +0800 Subject: [PATCH 3/3] fix: retire result dialogs and clarify batch lifecycle --- docs/releases/2026-11-09-pr11-review345.md | 38 ++++ src/cbb_refresh_verify/application.py | 28 ++- src/cbb_refresh_verify/ui/main_window.py | 76 ++++---- .../ui/management_dialog.py | 4 +- tests/test_review345_ui_cli.py | 166 ++++++++++++++++++ tests/test_review_management_ui_followup.py | 14 ++ 6 files changed, 284 insertions(+), 42 deletions(-) create mode 100644 docs/releases/2026-11-09-pr11-review345.md create mode 100644 tests/test_review345_ui_cli.py diff --git a/docs/releases/2026-11-09-pr11-review345.md b/docs/releases/2026-11-09-pr11-review345.md new file mode 100644 index 0000000..8eb3ddd --- /dev/null +++ b/docs/releases/2026-11-09-pr11-review345.md @@ -0,0 +1,38 @@ +# PR11 review 345 follow-up + +Repeated CBB verification and ICDB check runs replace the previous result dialog +for the same operation. Closing a result retires its Qt widgets and action +references, while the check task keeps its requests, results, invalidated targets, +and recovery context. A result for the other operation stays available. + +During application shutdown, the title and status show that background work and +path release are pending. After approximately 120 seconds a second notice says +the application is still waiting. This is a notice interval, not a deadline; +shutdown still waits for existing workers and never forces native tools to stop. + +The batch CLI accepts an optional positive `--limit`: + +```powershell +python -m cbb_refresh_verify --batch-lmc 'Z:\library\library.lmc' --limit 2 +``` + +The limit selects the first requested names in their existing order. With no +`--block`, the existing non-READY selection supplies those names; repeated +`--block` options retain their explicit order. Omitting `--limit` retains the +existing all-requested behavior. `batch_selection` logs selected, total, and +remaining counts. On batch exceptions or unconfirmed native release, +`batch_drive_retained` identifies the drive, remote share, display library and +Mentor path, and directs the operator to the confirmed-release entry. It never +disconnects a mapping while a native writer may still be active. + +Management change counts explicitly cover the compared engineering files only. + +Removed from the standalone PR11 head: all five `if False` blocks for the later +release flow, and `_reload_after_maintenance` assignments and its unused reload +branch. The hidden release control and existing method signatures remain for +the later PR12 implementation. When integrating forward, preserve PR12's live +release/resume behavior and retire its dialog-owned action references as well. +Preserve PR13's asynchronous close and lease guards when adding the wait notice. + +Validation uses the isolated offscreen review wrapper with fake native boundaries; +it does not open Mentor, kill native processes, invoke Repair, or back up a library. diff --git a/src/cbb_refresh_verify/application.py b/src/cbb_refresh_verify/application.py index 8d2fb88..8fe6dad 100644 --- a/src/cbb_refresh_verify/application.py +++ b/src/cbb_refresh_verify/application.py @@ -46,6 +46,16 @@ def resolve_data_root(cli_value: Path | None) -> Path: local = os.environ.get("LOCALAPPDATA") return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve() +def _positive_int(value): + try: + number = int(value) + except ValueError: + raise argparse.ArgumentTypeError('must be a positive integer') from None + if number <= 0: + raise argparse.ArgumentTypeError('must be a positive integer') + return number + + def main(argv: Sequence[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="CbbRefreshVerify") parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS) @@ -57,6 +67,7 @@ def main(argv: Sequence[str] | None = None) -> int: parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS) parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS) parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS) + parser.add_argument('--limit', type=_positive_int, help='Maximum requested CBB names for --batch-lmc (default: all)') parser.add_argument('--libspec', default='', help=argparse.SUPPRESS) parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS) parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS) @@ -110,6 +121,11 @@ def main(argv: Sequence[str] | None = None) -> int: if library.error: raise RuntimeError(library.error) names = [record.name for record in library.records if record.status != 'READY'] if not names: raise RuntimeError('中心库未读取到需要校验的 CBB') + total = len(names) + if args.limit is not None: + names = names[:args.limit] + logger.info('batch_selection selected=%s total=%s remaining=%s limit=%s', + len(names), total, total - len(names), args.limit or 'all') requests = [VerifyRequest(mentor_path, name, context.root/'evidence', libspec=args.libspec, dms_login_config=args.dms_login_config, mentor_bin=args.mentor_bin, logging_context=context, @@ -117,13 +133,21 @@ def main(argv: Sequence[str] | None = None) -> int: mapped_remote_root=lease.remote_root, native_lm_verify=native_lm_verify_enabled()) for name in names] + def retain_mapping(reason): + lease.retain_for_recovery() + logger.warning( + 'batch_drive_retained drive=%s remote=%s display=%s mentor=%s reason=%s ' + 'guidance=请打开此中心库的“释放残留会话…”入口,确认原生会话安全释放后再释放映射;' + '原生写入仍可能运行时请保留映射。', + lease.drive or '-', lease.remote_root or '-', lease.display_path, + mentor_path, reason) try: results = run_batch(requests) except Exception: - lease.retain_for_recovery() + retain_mapping('batch_exception') raise if any(not result.safe_to_continue for result in results): - lease.retain_for_recovery() + retain_mapping('native_release_unconfirmed') report = write_batch_report(requests, results, context.root/'reports') logger.info('batch_report path=%s', report) logger.info('failure_report path=%s', failure_report_path(report)) diff --git a/src/cbb_refresh_verify/ui/main_window.py b/src/cbb_refresh_verify/ui/main_window.py index e9f3178..34e1a92 100644 --- a/src/cbb_refresh_verify/ui/main_window.py +++ b/src/cbb_refresh_verify/ui/main_window.py @@ -99,7 +99,6 @@ class MainWindow(QWidget): self._management_unsafe_libraries = set() self._management_operation_library = None self._maintenance_recovery_view = False - self._reload_after_maintenance = False self._reimport_offers = () self._batch_requests = () self._batch_records = {} @@ -133,6 +132,10 @@ class MainWindow(QWidget): self._mapping_auto_idle = False self._mapping_finish_waiters = [] self._closing = self._close_ready = False + self.close_wait_timer = QTimer(self) + self.close_wait_timer.setSingleShot(True) + self.close_wait_timer.setInterval(120_000) + self.close_wait_timer.timeout.connect(self._show_close_wait_notice) from cbb_refresh_verify.operation_queue import NativeQueue self.native_queue = NativeQueue() self.icdb_task = None @@ -575,7 +578,6 @@ class MainWindow(QWidget): mapped_drive=getattr(self.library_lease, 'drive', ''), mapped_remote_root=getattr(self.library_lease, 'remote_root', ''))) previous[record.name] = str(result.evidence_path) - self._reload_after_maintenance = False if getattr(self, 'summary', None): self.summary.close() self._open_management_dialog(requests, recovery_from=previous) @@ -630,11 +632,6 @@ class MainWindow(QWidget): result.operation, result.name, result.status, result.safe_to_continue, result.evidence_path, result.detail) if getattr(self, '_management_is_recovery', False) and result.status == 'UPLOADED_VERIFIED': self.output.append('副本恢复校验通过,版本待核对。') - if False: # Release entry arrives with the next review PR. - self._management_unsafe = True - self._management_unsafe_library = self._management_operation_library - self._management_unsafe_libraries.add(_path_key(self._management_operation_library)) - self.status_label.setText('管理操作需要人工确认恢复/释放;已停止写入,未再次读取原生目录。') self._show_unfinished_management() def _management_closed(self, *_): @@ -751,7 +748,7 @@ class MainWindow(QWidget): if hasattr(task, 'summary'): prefix = '已更新的工程:'+', '.join(sorted(task.invalidated))+'。下列为此前检查记录。\n' task.summary.setDetailedText(prefix+task.summary.detailedText()) - if names & getattr(task, 'recovery_names', set()): + if names & getattr(task, 'recovery_names', set()) and hasattr(task, 'recovery_action'): task.recovery_action.setEnabled(False) task.recovery_action.setToolTip('工程已有后续管理操作,请重新检查。') self._reimport_offers = tuple(offer for offer in self._reimport_offers if offer[0].block_name not in names @@ -851,7 +848,7 @@ class MainWindow(QWidget): self.icdb_phase.setText(text) if not self.busy: self.status_label.setText(text) self.output.append(text+'\n'+str(task.report or task.report_error)) - summary = QMessageBox(self); self.icdb_summary = summary + summary = self._new_result_summary('icdb_summary') task.summary = summary if not self.busy: self.summary = summary summary.setWindowTitle('ICDB 批量检查结果'); summary.setText(text) @@ -860,14 +857,6 @@ class MainWindow(QWidget): +(result.stderr or result.stdout or result.status) for req, result in zip(task.requests, task.results))) summary.setTextFormat(Qt.PlainText); summary.setAttribute(Qt.WA_ShowWithoutActivating) - if False: # Release entry arrives with the next review PR. - def release_task(): - if not (_library_path_keys(task.requests[0].lmc_file, task.path_lease) - & _library_path_keys(self.mentor_lmc_path or self.loaded_path, self.library_lease)): - self.status_label.setText(f'请切回 {task.requests[0].lmc_file} 后释放该检查的残留。') - return - self.check_library_release() - summary.addButton('查看残留并释放…', QMessageBox.ActionRole).clicked.connect(release_task) if offers: action = summary.addButton('选择副本恢复…', QMessageBox.ActionRole) task.recovery_action = action @@ -1389,6 +1378,28 @@ class MainWindow(QWidget): if cell is not None: cell.setBackground(QColor('#E8F5E9')) + def _new_result_summary(self, attribute): + previous = getattr(self, attribute, None) + if previous is not None: + previous.close() + summary = QMessageBox(self) + setattr(self, attribute, summary) + summary.setAttribute(Qt.WA_DeleteOnClose) + summary.finished.connect(lambda _: self._forget_result_summary(summary)) + return summary + + def _forget_result_summary(self, summary): + if getattr(self, '_batch_summary', None) is summary: + self._reimport_summary_action = None + for attribute in ('summary', '_batch_summary', 'icdb_summary'): + if getattr(self, attribute, None) is summary: + setattr(self, attribute, None) + for task in self.icdb_tasks: + if getattr(task, 'summary', None) is summary: + del task.summary + if hasattr(task, 'recovery_action'): + del task.recovery_action + def _batch_done(self, outcome): results, report = outcome[:2] failure_report = failure_report_path(report) if report is not None else '未写入' @@ -1425,8 +1436,6 @@ class MainWindow(QWidget): f'取消 {counts["cancelled"]},队列未执行 {skipped}\n' f'完整日志:{report}\n仅失败日志:{failure_report}') self.icdb_phase.setText('批量检查已结束') - if False: # Release entry arrives with the next review PR. - text += '\n未确认数据库或会话安全,已停止剩余校验。请查看恢复现场。' status_text = (f'已结束:通过 {passed},失败/受阻 {failed},' f'仅检查 {checked},未执行 {skipped + len(self.skipped_names)}。') if self._global_icdb_run: @@ -1443,14 +1452,12 @@ class MainWindow(QWidget): status_text += '\nMentor 不允许对此已验证过的 CBB 反标注,校验未通过。' else: status_text += '\n部分项目未完成,请查看详情。' - if False: # Release entry arrives with the next review PR. - status_text += '\n后续操作已暂停。' if self._reimport_offers: guidance = '\n修复未完成,可选择工程副本恢复。' text += guidance status_text += guidance self.status_label.setText(status_text.replace('\n', ' ')); self.output.append(text) - self.summary = QMessageBox(self) + self.summary = self._new_result_summary('_batch_summary') self.summary.setWindowTitle('ICDB 批量检查结果' if self._global_icdb_run else 'CBB 校验结果') self.summary.setText(status_text) self.summary.setDetailedText(text) @@ -1459,18 +1466,6 @@ class MainWindow(QWidget): self._residual_release_action = None self._resume_batch_action = None self._resume_batch = None - if False: # Release entry arrives with the next review PR. - self._residual_release_action = self.summary.addButton('查看残留并释放…', QMessageBox.ActionRole) - self._residual_release_action.clicked.connect(self.check_library_release) - self._residual_release_action.setEnabled(False) - names = [req.block_name for req, result in zip(self._batch_requests, results) - if result.status == 'SKIPPED'] - if names: - self._resume_batch = {'library': self._batch_requests[0].lmc_file, 'names': names, - 'maintenance': self._global_icdb_run, 'released': False} - self._resume_batch_action = self.summary.addButton('继续未执行项', QMessageBox.ActionRole) - self._resume_batch_action.clicked.connect(self._resume_released_batch) - self._resume_batch_action.setEnabled(False) if self._reimport_offers: self.summary.setStandardButtons(QMessageBox.Close) self._reimport_summary_action = self.summary.addButton('选择副本恢复…', QMessageBox.ActionRole) @@ -1520,10 +1515,6 @@ class MainWindow(QWidget): self.version_dialog.reject() self.version_dialog = None self.busy = False; self._update() - if self._reload_after_maintenance: - from PySide6.QtCore import QTimer - self._reload_after_maintenance = False - QTimer.singleShot(0, self.load_library) def open_logs(self): self.data_root.mkdir(parents=True, exist_ok=True); os.startfile(str(self.data_root)) @@ -1545,6 +1536,9 @@ class MainWindow(QWidget): else: self._closing = True self.busy = True; self._update() + self.setWindowTitle('CBB 刷新校验 · 等待任务安全结束') + self.status_label.setText('正在等待后台任务和路径释放完成,完成后关闭。') + self.close_wait_timer.start() retained = None if self._native_backup_session is not None: self.native_backup_timer.stop() @@ -1557,6 +1551,11 @@ class MainWindow(QWidget): self._close_when_idle() event.ignore() + def _show_close_wait_notice(self): + if self._closing and not self._close_ready: + self.setWindowTitle('CBB 刷新校验 · 仍在等待任务安全结束') + self.status_label.setText('仍在等待后台任务或路径释放完成;原生操作不会强制终止,完成后关闭。') + def _close_when_idle(self): owners = [self, *self.icdb_tasks] for name in ('management_dialog', 'backup_dialog', 'release_dialog'): @@ -1571,5 +1570,6 @@ class MainWindow(QWidget): if self._lease_pending or active: QTimer.singleShot(20, self._close_when_idle) return + self.close_wait_timer.stop() self._close_ready = True self.close() diff --git a/src/cbb_refresh_verify/ui/management_dialog.py b/src/cbb_refresh_verify/ui/management_dialog.py index f883fad..1f4249c 100644 --- a/src/cbb_refresh_verify/ui/management_dialog.py +++ b/src/cbb_refresh_verify/ui/management_dialog.py @@ -209,8 +209,8 @@ class ManagementDialog(QDialog): changes = getattr(result, 'change_report', None) if changes: if changes.get('status') == 'RECORDED': - text += (f'\n变更:新增 {len(changes["added"])}、删除 {len(changes["deleted"])}、' - f'修改 {len(changes["modified"])} 个主要文件。') + text += (f'\n已比对的工程文件:新增 {len(changes["added"])}、删除 {len(changes["deleted"])}、' + f'修改 {len(changes["modified"])};范围仅限报告列出的工程文件。') else: summary += ',变更清单待核对' text += '\n'+changes.get('detail', '变更清单未确认') diff --git a/tests/test_review345_ui_cli.py b/tests/test_review345_ui_cli.py new file mode 100644 index 0000000..d3bf41d --- /dev/null +++ b/tests/test_review345_ui_cli.py @@ -0,0 +1,166 @@ +from pathlib import Path +from threading import Event +from types import SimpleNamespace + +import pytest +from PySide6.QtCore import QCoreApplication, QEvent +from PySide6.QtWidgets import QMessageBox +from shiboken6 import isValid + +from cbb_refresh_verify.verify_runner import VerifyResult + + +def flush_deletes(): + QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete) + + +def test_repeated_batch_results_retire_previous_dialog(qtbot, tmp_path): + from cbb_refresh_verify.ui.main_window import MainWindow + window = MainWindow(data_root=tmp_path) + qtbot.addWidget(window) + window._batch_done(([VerifyResult('FAIL')], tmp_path/'report.log')) + previous = window.summary + window._batch_done(([VerifyResult('PASS')], tmp_path/'report2.log')) + flush_deletes() + assert not isValid(previous) + assert len(window.findChildren(QMessageBox)) == 1 + current = window.summary + current.close() + flush_deletes() + assert not isValid(current) + window._update() # No retained reference to deleted result actions. + + +def test_repeated_icdb_results_preserve_latest_recovery_task(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + from test_reimport_recovery import failed_repair + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda _: failed_repair(tmp_path/'result.json', safe=True)) + window._run(['Beta'], maintenance=True) + qtbot.waitUntil(lambda: not window._icdb_active()) + first_task, previous = window.icdb_task, window.icdb_summary + window._run(['Gamma'], maintenance=True) + qtbot.waitUntil(lambda: not window._icdb_active()) + flush_deletes() + assert not isValid(previous) + assert not hasattr(first_task, 'summary') + assert len(window.findChildren(QMessageBox)) == 1 + assert window.icdb_task.summary is window.icdb_summary + action = next(b for b in window.icdb_summary.buttons() if '副本' in b.text()) + action.click() + assert [request.name for request in window.management_dialog.requests()] == ['Gamma'] + window.management_dialog.reject() + window._invalidate_check_targets('test.lmc', ['Beta', 'Gamma']) + window._update() + + +def test_batch_replacement_preserves_independent_icdb_result(qtbot, tmp_path, monkeypatch): + from test_ui_filters import load_window + window = load_window(qtbot, tmp_path, monkeypatch, + verifier=lambda _: VerifyResult('CHECKED')) + window._run(['Beta'], maintenance=True) + qtbot.waitUntil(lambda: not window._icdb_active()) + icdb_summary = window.icdb_summary + window._batch_done(([VerifyResult('PASS')], tmp_path/'first.log')) + old_batch = window.summary + window._batch_done(([VerifyResult('PASS')], tmp_path/'second.log')) + flush_deletes() + assert not isValid(old_batch) + assert isValid(icdb_summary) and icdb_summary.isVisible() + assert window.icdb_task.summary is icdb_summary + assert len(window.findChildren(QMessageBox)) == 2 + + +def test_close_wait_notice_remains_visible_and_timer_stops_on_idle(qtbot, tmp_path): + from cbb_refresh_verify.ui.main_window import MainWindow + entered, release = Event(), Event() + def close_lease(): + entered.set() + release.wait(5) + window = MainWindow(data_root=tmp_path) + qtbot.addWidget(window) + window.library_lease = SimpleNamespace(close=close_lease) + window.show() + try: + window.close() + qtbot.waitUntil(entered.is_set) + assert window.isVisible() and '等待' in window.windowTitle() + timer = window.close_wait_timer + assert timer.isActive() and timer.interval() == 120_000 + timer.start(10) + qtbot.waitUntil(lambda: '仍在等待' in window.windowTitle()) + assert '仍在等待' in window.status_label.text() + window.close() + assert window.isVisible() + finally: + release.set() + qtbot.waitUntil(lambda: not window.isVisible()) + assert not timer.isActive() + + +@pytest.fixture +def batch_cli(tmp_path, monkeypatch): + import cbb_refresh_verify.application as application + import cbb_refresh_verify.library_reader as reader + import cbb_refresh_verify.network_path as network + import cbb_refresh_verify.verify_runner as runner + from cbb_refresh_verify.models import CbbRecord, LibraryReadResult + log, requested, retained = [], [], [] + def record(message, *args, **kwargs): + log.append(message % args if args else message) + logger = SimpleNamespace(info=record, warning=record, exception=record, handlers=()) + monkeypatch.setattr(application, 'configure', lambda *_: SimpleNamespace(root=tmp_path, logger=logger)) + class Lease: + display_path = Path(r'\\server\share\library') + mentor_path = tmp_path/'lib.lmc' + drive, remote_root, created = 'Z:', r'\\server\share', True + def __enter__(self): return self + def __exit__(self, *_): pass + def retain_for_recovery(self): retained.append(self.drive) + monkeypatch.setattr(network.LibraryPathLease, 'acquire', lambda _: Lease()) + monkeypatch.setattr(network, 'select_library_file', lambda path: path) + monkeypatch.setattr(reader, 'read_library_fast', lambda *a, **kw: LibraryReadResult(( + CbbRecord('Ready', 'LP', status='READY'), CbbRecord('One', 'LP'), + CbbRecord('Two', 'LP'), CbbRecord('Three', 'LP')))) + def run(requests): + requested.extend(request.block_name for request in requests) + return [VerifyResult('PASS') for _ in requests] + monkeypatch.setattr(runner, 'run_batch', run) + monkeypatch.setattr(runner, 'write_batch_report', lambda *a: tmp_path/'batch.log') + return application, runner, log, requested, retained + + +@pytest.mark.parametrize('extra, expected, counts', [ + ([], ['One', 'Two', 'Three'], (3, 3, 0)), + (['--limit', '2'], ['One', 'Two'], (2, 3, 1)), + (['--block', 'Three', '--block', 'One', '--limit', '1'], ['Three'], (1, 2, 1)), +]) +def test_batch_cli_limit_is_optional_and_reports_selection(batch_cli, extra, expected, counts): + app, _, log, requested, _ = batch_cli + assert app.main(['--batch-lmc', 'lib.lmc', *extra]) == 0 + assert requested == expected + assert any(all(f'{key}={value}' in line for key, value in zip( + ('selected', 'total', 'remaining'), counts)) for line in log) + + +@pytest.mark.parametrize('value', ['0', '-1', 'no']) +def test_batch_cli_rejects_nonpositive_limit(batch_cli, value): + app, _, _, requested, _ = batch_cli + with pytest.raises(SystemExit) as error: + app.main(['--batch-lmc', 'lib.lmc', '--limit', value]) + assert error.value.code == 2 and not requested + + +@pytest.mark.parametrize('raised', [False, True]) +def test_retained_mapping_logs_context_and_confirmed_release_guidance(batch_cli, monkeypatch, raised): + app, runner, log, _, retained = batch_cli + def run(_): + if raised: raise RuntimeError('native writer status unknown') + return [VerifyResult('FAIL', safe_to_continue=False)] + monkeypatch.setattr(runner, 'run_batch', run) + assert app.main(['--batch-lmc', 'lib.lmc', '--block', 'One']) == (1 if raised else 2) + assert retained == ['Z:'] + notice = next(line for line in log if 'batch_drive_retained' in line) + assert 'Z:' in notice and r'\\server\share' in notice + assert '释放残留会话' in notice and '确认' in notice + assert 'net use' not in notice.lower() diff --git a/tests/test_review_management_ui_followup.py b/tests/test_review_management_ui_followup.py index ef34087..21dd401 100644 --- a/tests/test_review_management_ui_followup.py +++ b/tests/test_review_management_ui_followup.py @@ -29,3 +29,17 @@ def test_report_failure_is_visible_without_inventing_native_failure(qtbot, setup assert '历史会话已释放' in dialog.output.toPlainText() dialog._progress({'stage':'previous_release_check','block':request.name}) assert '正在复核历史占用' in dialog.status_label.text() + + +def test_recorded_counts_identify_compared_engineering_file_scope(qtbot, setup): + from cbb_refresh_verify.management import ManagementResult + from cbb_refresh_verify.ui.management_dialog import ManagementDialog + request, _, _ = setup + dialog = ManagementDialog([request]); qtbot.addWidget(dialog) + result = ManagementResult(request.operation, request.library, request.name, request.partition, + None, False, 'complete', 'REMOVED', True, 'removed', + change_report={'status': 'RECORDED', 'added': ['a'], 'deleted': [], 'modified': ['b']}) + dialog._result([result]) + text = dialog.output.toPlainText() + assert '已比对的工程文件' in text + assert '新增 1' in text and '删除 0' in text and '修改 1' in text -- 2.39.5