Compare commits

..
31 changed files with 5017 additions and 932 deletions

No files matched your search

@@ -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.
@@ -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.
+7
View File
@@ -0,0 +1,7 @@
# 评论 275/283:结果口径接入
管理进度显示历史占用复核;结果分别呈现已确认的原生动作、变更清单完整性和历史会话释放事实。单项 RECOVERY_REQUIRED 但 safe_to_continue=True 时,不再声称整个队列停止;记录失败不伪装成原生上传/移除失败。
独立操作回归更新为实际历史记录归档流程:先证明当前占用已释放、保留归档字节,再进行普通验证;不自动 Repair,失败后不遗留新的占用锁。
本阶段相关 UI/独立操作/后端回归 29 passed。后端完整回归与最终集成回归另见验证记录。没有执行真实 Mentor 写操作;回退按依赖逆序,不代表恢复原生事务。
+175 -148
View File
@@ -1,148 +1,175 @@
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 _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)
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('--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)
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')
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,
mapped_drive=lease.drive,
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:
retain_mapping('batch_exception')
raise
if any(not result.safe_to_continue for result in results):
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))
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()
@@ -0,0 +1,5 @@
"""Shared wording for user-managed backups before write operations."""
MANUAL_BACKUP_NOTICE = (
'应用不会自动备份。请先手动备份中心库及相关工程,并确认备份可用于恢复。'
)
@@ -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):
@@ -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)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,250 @@
"""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': '正在检查工程是否被占用',
'previous_release_check': '正在复核历史占用',
'previous_release_confirmed': '历史会话已确认释放',
'previous_release_unconfirmed': '占用复核未通过',
}
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}'
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'):
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)
@@ -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')
+75
View File
@@ -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
+122
View File
@@ -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'
+15 -7
View File
@@ -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)
+13
View File
@@ -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):
+159
View File
@@ -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
+187
View File
@@ -0,0 +1,187 @@
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/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)
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'))
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 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):
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
+171
View File
@@ -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'
+75
View File
@@ -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'
+113
View File
@@ -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()
+51
View File
@@ -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]
+263
View File
@@ -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()
+191 -169
View File
@@ -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'
+43
View File
@@ -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()
+132
View File
@@ -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)
+242
View File
@@ -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 == []
+166
View File
@@ -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()
@@ -0,0 +1,45 @@
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()
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
+45 -32
View File
@@ -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()
+247
View File
@@ -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()
+291
View File
@@ -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() == ()
+133
View File
@@ -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)