fix: bind UI jobs and recovery actions to captured scope

This commit is contained in:
阿白叔 committed 2026-11-16 22:11:17 +08:00
1 parent 601dd7b6b2
commit cd7a5e0ca1
20 files changed
+1570 -297

No files matched your search

+17 -12
View File
@@ -203,20 +203,22 @@ def filesystem_status_map(library: Path, names):
return {name: details['status'] for name, details in filesystem_evidence_map(library, names).items()}
def read_library_fast(path: Path, *, status_reader=None):
"""List CBBs from ReusableBlocksLP without touching COM or the .lmc.
Useful when Library Manager is unavailable or already running: the folder
is the same source the LM tree shows, and an optional status_reader can
supply each item's flag without a full COM session.
"""
"""Discover directories; this does not validate native format/registration."""
try:
path = Path(path)
if path.suffix.casefold() != '.lmc':
return LibraryReadResult((), 'INPUT_SUFFIX: 请选择 .lmc 中心库文件。')
if not path.is_file():
return LibraryReadResult((), f'中心库不存在: {path}')
return LibraryReadResult((), f'INPUT_MISSING: 中心库不存在或不是文件: {path}')
with path.open('rb') as stream:
if not stream.read(1):
return LibraryReadResult((), 'INPUT_EMPTY: 中心库文件为空。')
if any(lock.is_dir() for lock in (path.with_suffix('.lock'), path.with_name('.'+path.stem+'.cbb-upload.lock'))):
return LibraryReadResult((), 'INPUT_LOCK_DIRECTORY: 中心库锁路径是目录。')
folder = path.parent/'ReusableBlocksLP'
if not folder.is_dir():
return LibraryReadResult((), f'缺少 ReusableBlocksLP 目录: {folder}')
entries = [entry for entry in folder.iterdir() if entry.is_dir()]
if folder.exists() and not folder.is_dir():
return LibraryReadResult((), f'INPUT_DIRECTORY: ReusableBlocksLP 不是目录: {folder}')
entries = [entry for entry in folder.iterdir() if entry.is_dir()] if folder.is_dir() else []
names = tuple(sorted((entry.name for entry in entries), key=str.casefold))
statuses = {}
if status_reader is not None and names:
@@ -240,8 +242,11 @@ def read_library_fast(path: Path, *, status_reader=None):
status = str(statuses.get(entry.name, 'UNKNOWN') or 'UNKNOWN')
if status not in {'READY', 'PENDING', 'UNKNOWN', 'UNAVAILABLE', 'ERROR', 'TIMEOUT'}:
status = 'UNKNOWN'
records.append(CbbRecord(entry.name, 'Reusable Blocks', status=status))
return LibraryReadResult(tuple(sorted(records, key=lambda item: item.name)))
records.append(CbbRecord(entry.name, 'Reusable Blocks', status=status,
catalog_source='directory', status_source='status_reader' if status_reader else 'unknown'))
return LibraryReadResult(tuple(sorted(records, key=lambda item: item.name)), directory_count=len(entries))
except PermissionError as error:
return LibraryReadResult((), f'INPUT_PERMISSION: 无权读取中心库: {error}')
except Exception as error:
return LibraryReadResult((), str(error))
+7
View File
@@ -7,8 +7,15 @@ class CbbRecord:
partition_name: str
logical_type: str = "LP"
status: str = "UNKNOWN"
catalog_source: str = "provided"
status_source: str = "provided"
missing_reason: str = ""
@dataclass(frozen=True)
class LibraryReadResult:
records: tuple[CbbRecord, ...]
error: str | None = None
directory_count: int | None = None
native_count: int | None = None
missing_project_count: int | None = None
catalog_verified: bool = False
+6 -3
View File
@@ -63,6 +63,7 @@ def request_library_keys(request, context=None):
class _Call:
context: object
external_stop: object = None
metadata_only: bool = False
done: Event = field(default_factory=Event)
abandoned: bool = False
native_depth: int = 0
@@ -120,6 +121,8 @@ def hold_native_handoff(process, session_record_path):
def native_phase():
"""Never abandon a transaction between native writes (including Remove/Add)."""
call = getattr(_local, 'call', None)
if call is not None and call.metadata_only:
raise RuntimeError('A metadata-only call cannot enter native work')
with _tasks_guard:
check_active()
if call is not None:
@@ -224,14 +227,14 @@ class BatchTaskContext:
call.abandoned = True
return self.snapshot()
def run(self, action, *, stop=None, timeout_seconds=10):
def run(self, action, *, stop=None, timeout_seconds=10, metadata_only=False):
self.check_active()
if current_context() is self:
return action() # Preserve nested lease and mutex thread identity.
aliases = {_path_key(v) for v in (self.library, *self.aliases)}
call = _Call(self, stop)
call = _Call(self, stop, metadata_only=metadata_only)
with _tasks_guard:
if any(c.abandoned and aliases.intersection(
if not metadata_only and any(c.abandoned and not c.metadata_only and aliases.intersection(
_path_key(v) for v in (c.context.library, *c.context.aliases))
for c in _calls.values()):
raise TaskHandoff(self)
@@ -2,13 +2,14 @@
from pathlib import Path
from threading import Event
from PySide6.QtCore import QObject, QThreadPool, Signal
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
from PySide6.QtWidgets import (QComboBox, QDialog, QFileDialog, QFormLayout,
QHBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox)
from .workers import ServiceWorker
from .backup_notice import MANUAL_BACKUP_NOTICE
from . import timed_prompt
from ..operation_queue import BatchTaskContext
class RecoverySignals(QObject):
@@ -28,13 +29,17 @@ class BackupRecoveryDialog(QDialog):
self.recoverer = recoverer
self.native_queue = None
self.stop = Event()
self.context = None
self.ui_job = None
self.admit = None
self.setWindowModality(Qt.NonModal)
self.busy = False
self.pool = QThreadPool(self)
self.pool.setMaxThreadCount(1)
self.signals = RecoverySignals(self)
self.signals.progress.connect(self._progress)
if parent is not None and hasattr(parent, '_show_version_choice'):
self.signals.choice.connect(parent._show_version_choice)
self._choice_handler = getattr(parent, '_show_version_choice', None)
self.signals.choice.connect(self._choice)
self.block_combo = QComboBox()
self.block_combo.addItems(list(names))
self.source_edit = QLineEdit()
@@ -47,7 +52,7 @@ class BackupRecoveryDialog(QDialog):
self.close_button.clicked.connect(self.reject)
self.cancel_queue_button = QPushButton('取消排队')
self.cancel_queue_button.setEnabled(False)
self.cancel_queue_button.clicked.connect(self.stop.set)
self.cancel_queue_button.clicked.connect(lambda:self.stop.set())
self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 所选备份先在隔离库中验证;安装时旧 Work 仅改名保留。')
self.status_label.setWordWrap(True)
layout = QFormLayout(self)
@@ -94,37 +99,64 @@ class BackupRecoveryDialog(QDialog):
'\n\n将创建用于校验的隔离库副本,校验通过后替换目标工程。确认继续?',
QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) != QMessageBox.Yes:
return
if self.admit is not None and not self.admit((request, source)):
self.status_label.setText('相同任务已提交,未重复执行。')
return
self.busy = True
self.stop.clear()
self.context = BatchTaskContext(str(request.lmc_file), targets=(name,))
context = self.context
self.stop = context.stop
self._set_enabled(False)
self.status_label.setText('正在准备恢复…')
self.started.emit(name)
def execute():
options = {'version_prompt': self.signals.choice.emit,'stop':self.stop} if self.recoverer is None else {}
action = lambda: recoverer(request, source, progress=self.signals.progress.emit, **options)
if self.native_queue is None: return action()
options = {'version_prompt': lambda choice:self._emit(context, 'choice',choice),'stop':context.stop} if self.recoverer is None else {}
action = lambda: recoverer(request, source, progress=lambda event:self._emit(context, 'progress',event), **options)
if self.native_queue is None: return context.run(action)
from ..operation_queue import QueueCancelled
def restore():
self.signals.progress.emit({'stage': 'queue_acquired'})
self._emit(context, 'progress',{'stage': 'queue_acquired'})
return action()
try:
return self.native_queue.run(restore, stop=self.stop, waiting=lambda: self.signals.progress.emit(
return self.native_queue.run(restore, stop=context.stop, context=context, waiting=lambda: self._emit(context, 'progress',
{'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'}))
except QueueCancelled as error:
from ..verify_runner import VerifyResult
from ..operation_queue import TaskHandoff
from ..verify_runner import VerifyResult, _handoff_verify_result
if isinstance(error, TaskHandoff): return _handoff_verify_result(error)
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)
self.worker.signals.succeeded.connect(context.guard_callback(lambda result: self._result(name, result), current=lambda:self.context))
self.worker.signals.failed.connect(context.guard_callback(lambda error: self._failed(name, error), current=lambda:self.context))
self.worker.signals.finished.connect(lambda:self._finished() if self.context is context else None)
self.pool.start(self.worker)
def _emit(self, context, signal, value):
if context is not self.context or not self.busy or signal == 'choice' and context.stop.is_set():
if signal == 'choice': value.choose('cancel')
return
try:
delivered = context.guard_callback(lambda:getattr(self.signals, signal).emit((context,value)) or True)()
if not delivered and signal == 'choice': value.choose('cancel')
except RuntimeError:
if signal == 'choice': value.choose('cancel')
def _choice(self, payload):
context, choice = payload
if context is not self.context or not self.busy or context.stop.is_set() or self._choice_handler is None:
choice.choose('cancel')
return
self._choice_handler((self.ui_job,choice) if self.ui_job else choice)
def _set_enabled(self, enabled):
for widget in (self.block_combo, self.source_edit, self.browse_button,
self.restore_button, self.close_button):
widget.setEnabled(enabled)
def _progress(self, event):
if isinstance(event, tuple):
context, event = event
if context is not self.context or not self.busy: return
if isinstance(event, dict):
if event.get('stage') in ('waiting_native_slot', 'queue_acquired'):
self.cancel_queue_button.setEnabled(event['stage'] == 'waiting_native_slot')
@@ -160,6 +192,7 @@ class BackupRecoveryDialog(QDialog):
def closeEvent(self, event):
if self.busy:
self.stop.set()
event.ignore()
else:
super().closeEvent(event)
+31 -10
View File
@@ -1,8 +1,7 @@
"""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 ..operation_queue import QueueCancelled, BatchTaskContext
from ..verify_runner import VerifyResult, run_verify, write_batch_report
from ..icdb_maintenance import write_maintenance_report
@@ -12,14 +11,17 @@ class IcdbCheckTask(QObject):
item_done = Signal(str, object)
finished = Signal(object)
def __init__(self, requests, queue, report_root, *, verifier=None, path_lease=None, parent=None):
def __init__(self, requests, queue, report_root, *, verifier=None, path_lease=None, parent=None, status_reader=None, choice_prompt=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.context = BatchTaskContext(str(self.requests[0].lmc_file), targets=tuple(r.block_name for r in self.requests))
self.status_reader = status_reader
self.verifier = verifier or (lambda req: run_verify(req, progress=self._emit_event,
stop=self.stop, version_prompt=choice_prompt))
self.results = []
self.stop = Event()
self.stop = self.context.stop
self.active = False
self.paused = False
self.invalidated = set()
@@ -30,6 +32,12 @@ class IcdbCheckTask(QObject):
self.retained_libraries = set()
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
def _emit_event(self, event):
try:
self.context.guard_callback(self.event.emit)(event)
except RuntimeError:
pass
def start(self):
self.active = True
self._next()
@@ -68,23 +76,31 @@ class IcdbCheckTask(QObject):
from ..session_record import library_available, library_wait_reason
try:
def execute():
if self.status_reader is not None:
statuses = self.status_reader((request.block_name,), request.lmc_file)
self.update_statuses(statuses)
if statuses.get(request.block_name) == 'NOT_REGISTERED':
return VerifyResult('SKIPPED', stderr='仅发现目录,原生目录未登记此 CBB。')
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})
self._emit_event({'stage': 'icdb_check_start', 'block': request.block_name})
result = self.verifier(request)
if not result.safe_to_continue:
from ..operation_lifecycle import recheck_failed_release
result = recheck_failed_release(request.lmc_file, request.block_name, result)
return result
return self.queue.run(execute, stop=self.stop,
return self.queue.run(execute, stop=self.stop, context=self.context,
wait_state=lambda: (self.paused, library_wait_reason(request.lmc_file)),
ready=lambda: not self.paused and library_available(request.lmc_file),
waiting=lambda: self.event.emit({'stage': 'waiting_native_slot', 'block': request.block_name,
ready=lambda: not self.paused,
waiting=lambda: self._emit_event({'stage': 'waiting_native_slot', 'block': request.block_name,
'library': str(request.lmc_file), 'retained': not library_available(request.lmc_file),
'detail': library_wait_reason(request.lmc_file) or '已排队,等待当前原生操作结束'}))
except QueueCancelled as error:
from ..operation_queue import TaskHandoff
from ..verify_runner import _handoff_verify_result
if isinstance(error, TaskHandoff): return _handoff_verify_result(error)
return VerifyResult('CANCELLED', stderr=str(error))
except Exception as error:
return VerifyResult('FAIL', stderr=str(error), safe_to_continue=False,
@@ -117,7 +133,12 @@ class IcdbCheckTask(QObject):
return report, ''
except Exception as error:
return None, str(error)
self.worker = ServiceWorker(write)
def bounded_write():
try:
return BatchTaskContext(str(self.requests[0].lmc_file)).run(write)
except Exception as error:
return None, str(error)
self.worker = ServiceWorker(bounded_write)
self.worker.signals.succeeded.connect(self._report_ready)
self.worker.signals.finished.connect(self._complete)
self.pool.start(self.worker)
File diff suppressed because it is too large. Load diff
+51 -21
View File
@@ -1,7 +1,6 @@
"""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,
@@ -11,6 +10,7 @@ from .workers import ServiceWorker
from .backup_notice import MANUAL_BACKUP_NOTICE
from . import timed_prompt
from ..management import run_management_batch
from ..operation_queue import BatchTaskContext
RESULT_LABELS = {
'REMOVED': '已移除', 'UPLOADED': '已上传 / 未自动校验',
@@ -59,12 +59,16 @@ class ManagementDialog(QDialog):
evidence_dir=self.template.evidence_dir.parent/'reimport-recovery', **kwargs)
self.busy = False
self.executed = False
self.stop = Event()
self.context = BatchTaskContext(str(self.template.library))
self.stop = self.context.stop
self.ui_job = None
self.admit = None
self.setWindowModality(Qt.NonModal)
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
self.signals = ManagementSignals(self)
self.signals.progress.connect(self._progress)
if parent is not None and hasattr(parent, '_show_version_choice'):
self.signals.choice.connect(parent._show_version_choice)
self._choice_handler = getattr(parent, '_show_version_choice', None)
self.signals.choice.connect(self._choice)
self.setWindowTitle({'add': '新增 CBB', 'update': '同名更新 CBB', 'remove': '移除 CBB'}[self.operation])
self.resize(850, 450)
self.table = QTableWidget(0, 4)
@@ -96,7 +100,7 @@ class ManagementDialog(QDialog):
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.stop_button.clicked.connect(lambda:self.stop.set())
self.close_button = QPushButton('关闭'); self.close_button.clicked.connect(self.reject)
layout = QVBoxLayout(self)
layout.addWidget(QLabel(f'目标库:{self.template.library}'))
@@ -170,44 +174,67 @@ class ManagementDialog(QDialog):
QMessageBox.Yes)
if answer != QMessageBox.Yes:
return
if self.admit is not None and not self.admit(tuple(requests)):
self.status_label.setText('相同任务已提交,未重复执行。')
return
self.context = BatchTaskContext(str(self.template.library), targets=tuple(r.name for r in requests))
context = self.context
self.stop = context.stop
self.busy = True; self.executed = True
self._enabled(False)
self.before_execute.emit([r.name for r in requests])
def execute():
choices={'version_prompt':self.signals.choice.emit} if self.runner is run_management_batch or self.recovery_from else {}
action = lambda: self.runner(requests, adapter=self.adapter, stop=self.stop,
progress=self.signals.progress.emit,**choices)
if self.native_queue is None: return action()
choices={'version_prompt':lambda choice:self._emit(context, 'choice',choice)} if self.runner is run_management_batch or self.recovery_from else {}
action = lambda: self.runner(requests, adapter=self.adapter, stop=context.stop,
progress=lambda event:self._emit(context, 'progress',event),**choices)
if self.native_queue is None: return context.run(action)
from ..operation_queue import QueueCancelled
from ..session_record import library_available, library_wait_reason
try:
if self.runner is run_management_batch:
def item(request, action):
return self.native_queue.run(action, stop=self.stop,
ready=lambda: library_available(request.library),
return self.native_queue.run(action, stop=context.stop, context=context,
wait_state=lambda: library_wait_reason(request.library),
waiting=lambda: self.signals.progress.emit({'stage': 'waiting_native_slot',
waiting=lambda: self._emit(context, 'progress',{'stage': 'waiting_native_slot',
'retained': not library_available(request.library),
'detail': library_wait_reason(request.library) or '已排队,等待当前原生操作结束'}))
return self.runner(requests, adapter=self.adapter, stop=self.stop,
progress=self.signals.progress.emit, item_executor=item,
version_prompt=self.signals.choice.emit)
return self.native_queue.run(action, stop=self.stop, waiting=lambda: self.signals.progress.emit(
return self.runner(requests, adapter=self.adapter, stop=context.stop,
progress=lambda event:self._emit(context, 'progress',event), item_executor=item,
version_prompt=lambda choice:self._emit(context, 'choice',choice), context=context)
return self.native_queue.run(action, stop=context.stop, context=context, waiting=lambda: self._emit(context, 'progress',
{'stage': 'waiting_native_slot',
'retained': not library_available(self.template.library),
'detail': library_wait_reason(self.template.library) or '已排队,等待当前检查结束'}),
ready=lambda: library_available(self.template.library),
wait_state=lambda: library_wait_reason(self.template.library))
except QueueCancelled as error:
from ..operation_queue import TaskHandoff
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]
'complete', 'RECOVERY_REQUIRED' if isinstance(error,TaskHandoff) else 'CANCELLED',
not isinstance(error,TaskHandoff), 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.worker.signals.succeeded.connect(context.guard_callback(self._result, current=lambda:self.context))
self.worker.signals.failed.connect(context.guard_callback(self._failed, current=lambda:self.context))
self.worker.signals.finished.connect(lambda:self._finished() if self.context is context else None)
self.pool.start(self.worker)
def _emit(self, context, signal, value):
if context is not self.context or not self.busy or signal == 'choice' and context.stop.is_set():
if signal == 'choice': value.choose('cancel')
return
try:
delivered = context.guard_callback(lambda:getattr(self.signals, signal).emit((context,value)) or True)()
if not delivered and signal == 'choice': value.choose('cancel')
except RuntimeError:
if signal == 'choice': value.choose('cancel')
def _choice(self, payload):
context, choice = payload
if context is not self.context or not self.busy or context.stop.is_set() or self._choice_handler is None:
choice.choose('cancel')
return
self._choice_handler((self.ui_job,choice) if self.ui_job else choice)
def _enabled(self, enabled):
for widget in (self.table, self.sources_button, self.auto_verify, self.close_button):
widget.setEnabled(enabled)
@@ -215,6 +242,9 @@ class ManagementDialog(QDialog):
self.stop_button.setEnabled(not enabled)
def _progress(self, event):
if isinstance(event, tuple):
context, event = event
if context is not self.context or not self.busy: return
stage = str(event.get('stage', ''))
self.release_wait_button.setVisible(stage == 'waiting_native_slot' and bool(event.get('retained')))
text = f'{event.get("block", "")} {STAGE_LABELS.get(stage, RESULT_LABELS.get(stage, "正在处理"))}'
@@ -2,13 +2,14 @@
from pathlib import Path
from threading import Event
from PySide6.QtCore import QThreadPool, Signal
from PySide6.QtCore import QThreadPool, Signal, Qt
from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox)
from .workers import ServiceWorker
from .timed_prompt import arm_default
from . import timed_prompt
from ..operation_queue import BatchTaskContext
from ..residual_sessions import force_block_reason, release_targets_complete
@@ -24,10 +25,12 @@ class ResidualReleaseDialog(QDialog):
self.release_finalizer = None
self.busy = False
self.stop = Event()
self.context = None
self._workers = set()
self._refresh_after = False
self.pool = QThreadPool(self)
self.setWindowTitle('释放残留会话')
self.setModal(True)
self.setWindowModality(Qt.NonModal)
self.resize(1040, 400)
layout = QVBoxLayout(self)
self.message = QLabel('正在检查当前库关联的会话…')
@@ -66,6 +69,8 @@ class ResidualReleaseDialog(QDialog):
self.refresh()
def _start(self, action, completed):
context = BatchTaskContext(str(self.library))
self.context, self.stop = context, context.stop
self.busy = True
self.confirm_button.setEnabled(False)
self.refresh_button.setEnabled(False)
@@ -73,10 +78,12 @@ class ResidualReleaseDialog(QDialog):
self.force_button.setEnabled(False)
self.cancel_native_button.setEnabled(False)
self.close_button.setText('停止释放')
self.worker = ServiceWorker(action)
self.worker.signals.succeeded.connect(completed)
self.worker.signals.failed.connect(lambda error: self.message.setText(str(error)))
self.worker.signals.finished.connect(self._finished)
self.worker = ServiceWorker(lambda:context.run(action))
worker = self.worker
self._workers.add(worker)
self.worker.signals.succeeded.connect(context.guard_callback(completed, current=lambda:self.context))
self.worker.signals.failed.connect(context.guard_callback(lambda error: self.message.setText(str(error)), current=lambda:self.context))
self.worker.signals.finished.connect(lambda:(self._workers.discard(worker), self._finished() if self.context is context else None))
self.pool.start(self.worker)
def _finished(self):
@@ -130,6 +137,7 @@ class ResidualReleaseDialog(QDialog):
details.extend(c.get('text', '') for c in window.get('children', [])
if c.get('class') == 'Static')
box.setDetailedText('\n'.join(details))
box.setWindowModality(Qt.NonModal)
box.setStandardButtons(QMessageBox.Close)
arm_default(box, box.button(QMessageBox.Close))
box.show()
@@ -146,7 +154,7 @@ class ResidualReleaseDialog(QDialog):
QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
if answer != QMessageBox.Yes: return
from cbb_refresh_verify.residual_sessions import request_native_cancel
self.before_release.emit(); self.stop.clear()
self.before_release.emit(); self.stop = Event()
def execute():
action = lambda: self._finalize_release_result(
request_native_cancel(session, self.library, self.evidence_dir, stop=self.stop))
@@ -246,7 +254,7 @@ class ResidualReleaseDialog(QDialog):
def confirm_release(self, checked=False, *, force=False):
if self.busy or self.plan is None: return
from cbb_refresh_verify.library_lock import release_residual_sessions
self.stop.clear()
self.stop = Event()
plan = self.plan
self.before_release.emit()
self.message.setText('正在逐项释放,请稍候…')
+3 -1
View File
@@ -45,7 +45,8 @@ class _Countdown(QObject):
def stop(self):
self.done = True
self.timer.stop()
self.button.setText(self.label)
from shiboken6 import isValid
if isValid(self.button): self.button.setText(self.label)
@Slot()
def tick(self):
@@ -57,6 +58,7 @@ class _Countdown(QObject):
self.button.setText(f'{self.label}({ceil(remaining / 1000)} 秒)')
return
self.timer.stop()
self.done = True
if not self.button.isEnabled():
self.box.setProperty('selectionOrigin', 'timeout_default')
self.box.reject()
+1 -1
View File
@@ -130,7 +130,7 @@ def test_main_logs_and_evidence_buttons_open_the_correct_paths(controls, qtbot):
w.recovery_path = evidence
w.recovery_button.setEnabled(True)
press(qtbot, w.recovery_button)
assert controls.opened == [w.data_root, evidence]
assert controls.opened == [w.data_root/'logs', evidence]
@pytest.mark.parametrize('attribute', ['selected_batch_button', 'batch_button', 'icdb_repair_button'])
+3 -2
View File
@@ -69,9 +69,10 @@ def test_completed_old_library_result_does_not_release_new_library(qtbot, tmp_pa
qtbot.waitUntil(lambda: not window._icdb_active())
summary = window.icdb_summary
window.lmc_edit.setText('other.lmc')
message = window.status_label.text()
next(button for button in summary.buttons() if '释放' in button.text()).click()
assert getattr(window, 'release_dialog', None) is None
assert '切' in window.status_label.text()
assert window.status_label.text() == message
def test_later_management_invalidates_old_recovery_offer(qtbot, tmp_path, monkeypatch):
@@ -109,4 +110,4 @@ def test_check_release_action_tracks_busy_and_retained_queue(qtbot, tmp_path, mo
assert opened == [{'queued': True}]
window.busy = False
window._update()
assert action.isEnabled()
assert not action.isEnabled(), 'A dismissed one-shot result cannot be reactivated'
+38
View File
@@ -0,0 +1,38 @@
from threading import Event
import pytest
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff, native_phase
def test_metadata_can_refresh_while_abandoned_native_scope_stays_protected():
entered, release = Event(), Event()
old = BatchTaskContext('a.lmc')
def stalled():
entered.set(); release.wait(3)
try:
with pytest.raises(TaskHandoff): old.run(stalled, timeout_seconds=.01)
assert entered.is_set()
new = BatchTaskContext('a.lmc')
assert new.run(lambda: 'metadata', metadata_only=True) == 'metadata'
with pytest.raises(TaskHandoff): new.run(lambda: 'native')
finally:
release.set(); old.close(timeout_seconds=1)
def test_metadata_cannot_escalate_into_native_phase():
context = BatchTaskContext('a.lmc')
def escalate():
with native_phase():
pytest.fail('metadata admitted native action')
with pytest.raises(RuntimeError, match='metadata'):
context.run(escalate, metadata_only=True)
def test_abandoned_metadata_does_not_block_next_native_admission():
release = Event()
old = BatchTaskContext('a.lmc')
try:
with pytest.raises(TaskHandoff):
old.run(lambda: release.wait(3), timeout_seconds=.01, metadata_only=True)
assert BatchTaskContext('a.lmc').run(lambda: 'admitted') == 'admitted'
finally:
release.set(); old.close(timeout_seconds=1)
+8 -1
View File
@@ -241,7 +241,14 @@ def test_common_admission_refusal_publishes_bound_receipt_and_ui_can_reopen(qtbo
session.process.poll = lambda: 1
launched = []
window = load_window(qtbot, tmp_path, monkeypatch,
native_backup_launcher=lambda req: (launched.append(req) or session))
native_backup_launcher=lambda req: (launched.append(req) or session),
status_refresher=lambda names, _: {name:'UNKNOWN' for name in names})
# Deliver the receipt to its actual library view; a foreign view must not
# receive an old session's status label after Task 4's callback isolation.
window.path_lease_factory = lambda path: SimpleNamespace(mentor_path=path, display_path=path,
drive='', remote_root='', close=lambda:None, retain_for_recovery=lambda:None)
window.lmc_edit.setText(str(session.library)); window.load_library()
qtbot.waitUntil(lambda:not window.busy)
session.block = 'Beta'; record['block'] = 'Beta'
session.job.with_name('result.json').write_text(json.dumps(record), encoding='utf-8')
window._native_backup_session = session
+651
View File
@@ -0,0 +1,651 @@
"""Task-bound UI delivery and filesystem/native catalog separation."""
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
from PySide6.QtCore import Qt
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
def window_for(qtbot, tmp_path, monkeypatch, *, reader=None, **kwargs):
monkeypatch.setattr('cbb_refresh_verify.ui.main_window.preflight_skip_reason', lambda *_: None)
def lease(path):
return SimpleNamespace(mentor_path=path, display_path=path, drive='', remote_root='',
close=lambda: None, retain_for_recovery=lambda: None)
window = MainWindow(reader=reader or (lambda _: LibraryReadResult((CbbRecord('A', 'LP'),))),
path_lease_factory=lease, data_root=tmp_path, **kwargs)
qtbot.addWidget(window)
window.show()
return window
def load(window, qtbot, path='a.lmc'):
window.lmc_edit.setText(path)
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
def test_first_read_can_cancel_and_keeps_navigation_live(qtbot, tmp_path, monkeypatch):
entered, release = Event(), Event()
def reader(_):
entered.set(); release.wait(5)
return LibraryReadResult((CbbRecord('Late', 'LP'),))
window = window_for(qtbot, tmp_path, monkeypatch, reader=reader)
window.lmc_edit.setText('a.lmc'); window.load_library()
qtbot.waitUntil(entered.is_set)
try:
assert window.stop_button.isEnabled()
assert window.lmc_edit.isEnabled() and window.load_button.isEnabled()
window.stop_button.click()
qtbot.waitUntil(lambda: not window.busy, timeout=2000)
assert window.loaded_path is None
finally:
release.set(); window.pool.waitForDone(6000)
def test_failed_read_preserves_stale_table_without_write_eligibility(qtbot, tmp_path, monkeypatch):
window = window_for(qtbot, tmp_path, monkeypatch)
load(window, qtbot)
window.reader = lambda _: LibraryReadResult((), 'INPUT_EMPTY: 空文件')
load(window, qtbot, 'bad.lmc')
assert window.cbb_table.rowCount() == 1
assert window.loaded_path is None
assert not window.batch_button.isEnabled()
assert '失效' in window.library_notice.text()
def test_successful_path_is_local_and_only_prefilled(qtbot, tmp_path, monkeypatch):
window = window_for(qtbot, tmp_path, monkeypatch)
load(window, qtbot, 'remember.lmc')
calls = []
other = window_for(qtbot, tmp_path, monkeypatch, reader=lambda p: calls.append(p))
assert other.lmc_edit.text() == 'remember.lmc'
assert not calls and other.loaded_path is None
isolated = window_for(qtbot, tmp_path/'other', monkeypatch)
assert isolated.lmc_edit.text() == ''
def test_result_nonmodal_and_safe_cancel_evidence_and_logs(qtbot, tmp_path, monkeypatch):
window = window_for(qtbot, tmp_path, monkeypatch)
load(window, qtbot)
evidence = tmp_path/'evidence'/'result.json'
evidence.parent.mkdir(); evidence.write_text('{}')
window._batch_done(([VerifyResult('CANCELLED', safe_to_continue=True, evidence_path=evidence)], None))
assert window.summary.windowModality() == Qt.NonModal
assert window.recovery_button.isEnabled()
opened = []
monkeypatch.setattr('os.startfile', opened.append)
window.open_logs()
assert Path(opened[-1]) == tmp_path/'logs'
def test_read_does_not_wait_forever_on_old_retained_cache(qtbot, tmp_path, monkeypatch):
calls = []
monkeypatch.setattr('cbb_refresh_verify.session_record.library_available', lambda _: False)
monkeypatch.setattr('cbb_refresh_verify.session_record.library_wait_reason', lambda _: 'old retained')
window = window_for(qtbot, tmp_path, monkeypatch, reader=lambda p: (
calls.append(p) or LibraryReadResult((CbbRecord('A', 'LP'),))))
window.lmc_edit.setText('a.lmc'); window.load_library()
try:
qtbot.waitUntil(lambda: bool(calls), timeout=1500)
finally:
window.request_stop(); window.pool.waitForDone(3000)
@pytest.mark.parametrize('filename,content,category', [
('wrong.txt', b'library', 'INPUT_SUFFIX'), ('empty.lmc', b'', 'INPUT_EMPTY')])
def test_fast_read_rejects_invalid_input(tmp_path, filename, content, category):
from cbb_refresh_verify.library_reader import read_library_fast
path = tmp_path/filename; path.write_bytes(content)
(tmp_path/'ReusableBlocksLP').mkdir()
result = read_library_fast(path)
assert result.error and category in result.error
def test_fast_read_distinguishes_unknown_native_count(tmp_path):
from cbb_refresh_verify.library_reader import read_library_fast
path = tmp_path/'lib.lmc'; path.write_bytes(b'not-a-native-validation')
(tmp_path/'ReusableBlocksLP'/'Orphan').mkdir(parents=True)
result = read_library_fast(path)
assert result.directory_count == 1 and result.native_count is None
assert result.records[0].catalog_source == 'directory'
assert result.records[0].status == 'UNKNOWN'
def test_late_read_a_b_a_cannot_replace_newer_snapshot(qtbot, tmp_path, monkeypatch):
entered, release = Event(), Event()
count = 0
def reader(path):
nonlocal count
count += 1
if count == 1:
entered.set(); release.wait(5)
return LibraryReadResult((CbbRecord('Old', 'LP'),))
return LibraryReadResult((CbbRecord('New', 'LP'),))
window = window_for(qtbot, tmp_path, monkeypatch, reader=reader)
window.lmc_edit.setText('a.lmc'); window.load_library()
qtbot.waitUntil(entered.is_set)
try:
window.lmc_edit.setText('b.lmc'); window.lmc_edit.setText('a.lmc')
window.load_library()
qtbot.waitUntil(lambda: window.loaded_path == 'a.lmc', timeout=2000)
release.set(); qtbot.wait(100)
assert tuple(window._records_by_name) == ('New',)
finally:
release.set(); window.pool.waitForDone(6000)
def test_batch_result_cannot_modify_reloaded_library_and_current_cancel_displays(qtbot, tmp_path, monkeypatch):
entered, release = Event(), Event()
def verify(_):
entered.set(); release.wait(5)
return VerifyResult('CANCELLED', stderr='old A cancelled')
window = window_for(qtbot, tmp_path, monkeypatch, verifier=verify,
status_refresher=lambda names, _: {name:'PENDING' for name in names})
load(window, qtbot)
try:
window._run(['A']); qtbot.waitUntil(entered.is_set)
load(window, qtbot, 'b.lmc'); load(window, qtbot, 'a.lmc')
release.set(); qtbot.wait(200)
assert 'old A cancelled' not in window.status_label.text()
assert window.cbb_table.item(0,3).text() == '未检查'
window._run(['A']); qtbot.waitUntil(lambda:not window.busy)
assert '取消' in window.output.toPlainText() or 'CANCELLED' in window.output.toPlainText()
finally:
release.set(); window.pool.waitForDone(6000)
def test_catalog_union_keeps_registration_source_and_counts(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.management import Catalog, CatalogEntry
entered, release = Event(), Event()
def catalog(path, evidence):
entered.set(); release.wait(5)
return Catalog(path,1,(CatalogEntry('A','Logical-Physical'),CatalogEntry('NativeOnly','Logical-Physical')))
window = window_for(qtbot,tmp_path,monkeypatch, reader=lambda _:LibraryReadResult(
(CbbRecord('A','LP',catalog_source='directory'), CbbRecord('Orphan','LP',catalog_source='directory')),
directory_count=2), catalog_reader=catalog, status_refresher=lambda names,_:{name:'READY' for name in names})
try:
load(window,qtbot)
qtbot.waitUntil(entered.is_set)
assert '未知' in window.counts_label.text()
assert window.batch_button.isEnabled()
release.set()
qtbot.waitUntil(lambda:'NativeOnly' in window._records_by_name)
assert window._records_by_name['Orphan'].catalog_source == 'directory_only'
assert window._records_by_name['NativeOnly'].catalog_source == 'native_only'
assert window._records_by_name['A'].status_source == 'authoritative'
assert '原生 2' in window.counts_label.text()
finally:
release.set(); window.pool.waitForDone(6000)
def test_execution_rechecks_ready_when_directory_snapshot_was_unknown(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.management import Catalog, CatalogEntry
calls=[]
window=window_for(qtbot,tmp_path,monkeypatch, verifier=lambda r:(calls.append(r.block_name) or VerifyResult('PASS')),
catalog_reader=lambda p,e:Catalog(p,1,(CatalogEntry('A','Logical-Physical'),)),
status_refresher=lambda names,_:{name:'READY' for name in names})
load(window,qtbot)
window._run(['A'])
qtbot.waitUntil(lambda:not window.busy)
assert calls == []
def test_active_a_choice_defaults_after_switch_to_b(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.pcb_open_consent import OpenChoice
from cbb_refresh_verify.ui import timed_prompt
monkeypatch.setattr(timed_prompt,'DEFAULT_TIMEOUT_MS',80)
window=window_for(qtbot,tmp_path,monkeypatch)
load(window,qtbot)
job=window._new_job('verify',targets=('A',))
load(window,qtbot,'b.lmc')
choice=OpenChoice('A',Path('a.lmc'))
window._emit_job(job,'version_choice',choice)
qtbot.waitUntil(lambda:choice.decision is not None)
assert choice.decision == 'skip'
window._finish_job(job)
@pytest.mark.parametrize('mode',['versions','repair'])
def test_native_session_outlives_launcher_and_cleans_up_after_a_b_a(qtbot,tmp_path,monkeypatch,mode):
import json
exited=Event(); calls=[]
job_file=tmp_path/'native'/'job.json'; job_file.parent.mkdir(); job_file.write_text('{}')
def launcher(request, **options):
calls.append(options.get('mode','versions'))
return SimpleNamespace(process=SimpleNamespace(poll=lambda:0 if exited.is_set() else None),
job=job_file,library=request.lmc_file,block=request.block_name,path_lease=None,operation_id='native-1')
window=window_for(qtbot,tmp_path,monkeypatch,native_backup_launcher=launcher,
status_refresher=lambda names,_:{name:'PENDING' for name in names})
load(window,qtbot); window.cbb_table.setCurrentCell(0,0)
button=window.native_backup_button if mode=='versions' else window.native_repair_button
button.click(); qtbot.waitUntil(lambda:window._native_backup_session is not None)
qtbot.waitUntil(lambda:not window.busy)
assert calls == [mode]
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
message=window.status_label.text()
job_file.with_name('result.json').write_text(json.dumps(dict(operation_id='native-1',
library='a.lmc',block='A',safe_to_continue=True,status='CLOSED')))
exited.set(); window._poll_native_backup()
qtbot.waitUntil(lambda:window._native_backup_session is None)
assert window.status_label.text() == message
window.cbb_table.setCurrentCell(0,0)
assert window.native_backup_button.isEnabled()
def test_close_during_first_read_finishes_and_late_emit_is_harmless(qtbot,tmp_path,monkeypatch):
entered, release=Event(),Event()
def reader(_):
entered.set(); release.wait(5)
return LibraryReadResult((CbbRecord('Late','LP'),))
window=window_for(qtbot,tmp_path,monkeypatch,reader=reader)
window.lmc_edit.setText('a.lmc'); window.load_library(); qtbot.waitUntil(entered.is_set)
job=window._current_job
try:
window.close()
qtbot.waitUntil(lambda:not window.isVisible(),timeout=2000)
window._emit_job(job,'event',{'stage':'late'})
finally: release.set()
def test_input_lock_directory_and_permissions_are_classified(tmp_path,monkeypatch):
from cbb_refresh_verify.library_reader import read_library_fast
path=tmp_path/'lib.lmc'; path.write_bytes(b'library')
(tmp_path/'ReusableBlocksLP').mkdir(); path.with_suffix('.lock').mkdir()
assert 'INPUT_LOCK_DIRECTORY' in read_library_fast(path).error
original=Path.open
def denied(self,*a,**k):
if self == path: raise PermissionError('denied')
return original(self,*a,**k)
monkeypatch.setattr(Path,'open',denied)
assert 'INPUT_PERMISSION' in read_library_fast(path).error
def test_management_completion_after_switch_preserves_current_table(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.management import Capability, ManagementResult
from PySide6.QtWidgets import QMessageBox
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
entered,release=Event(),Event()
adapter=SimpleNamespace(capabilities=lambda:{op:Capability(True,'available') for op in ('add','update','remove')})
window=window_for(qtbot,tmp_path,monkeypatch,management_adapter=adapter)
load(window,qtbot); window.select_visible_button.click(); window.manage_cbb('remove')
dialog=window.management_dialog
def runner(requests,**kwargs):
entered.set(); release.wait(5)
r=requests[0]
return [ManagementResult('remove',r.library,r.name,r.partition,None,False,'complete','REMOVED',True,'old remove')]
dialog.runner=runner
try:
dialog.execute_button.click(); qtbot.waitUntil(entered.is_set)
assert dialog.windowModality()==Qt.NonModal
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
message=window.status_label.text()
release.set(); qtbot.waitUntil(lambda:not dialog.busy)
dialog.close(); qtbot.wait(100)
assert window.status_label.text()==message
assert window.cbb_table.item(0,3).text()=='未检查'
finally: release.set(); dialog.pool.waitForDone(6000)
def test_recovery_dialog_binds_original_library_and_is_nonmodal(qtbot,tmp_path,monkeypatch):
from PySide6.QtWidgets import QMessageBox
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
entered,release=Event(),Event(); calls=[]
window=window_for(qtbot,tmp_path,monkeypatch)
load(window,qtbot); window.restore_backup(); dialog=window.backup_dialog
source=tmp_path/'A.prj'; source.write_text('project')
dialog.source_edit.setText(str(source))
def recover(request,source,**kwargs):
calls.append(request.lmc_file); entered.set(); release.wait(5)
return VerifyResult('FAIL',stderr='old recovery',safe_to_continue=True)
dialog.recoverer=recover
try:
assert dialog.windowModality()==Qt.NonModal
load(window,qtbot,'b.lmc')
dialog.restore_button.click(); qtbot.waitUntil(entered.is_set)
message=window.status_label.text()
release.set(); qtbot.waitUntil(lambda:not dialog.busy)
assert calls == [Path('a.lmc')]
assert window.status_label.text()==message
finally: release.set(); dialog.pool.waitForDone(6000)
def test_icdb_does_not_wait_on_stale_retained_and_late_result_is_scoped(qtbot,tmp_path,monkeypatch):
entered,release=Event(),Event()
monkeypatch.setattr('cbb_refresh_verify.session_record.library_available',lambda _:False)
monkeypatch.setattr('cbb_refresh_verify.session_record.library_wait_reason',lambda _:'historical')
def verify(_):
entered.set(); release.wait(5)
return VerifyResult('CHECKED',safe_to_continue=True)
window=window_for(qtbot,tmp_path,monkeypatch,verifier=verify)
load(window,qtbot); window._start_icdb_check(['A'])
try:
qtbot.waitUntil(entered.is_set,timeout=1500)
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
message=window.status_label.text()
release.set(); qtbot.waitUntil(lambda:not window._icdb_active())
assert window.status_label.text()==message
assert window.cbb_table.item(0,3).text()=='未检查'
finally:
release.set(); window._stop_icdb_check(); window.icdb_task.pool.waitForDone(6000)
def test_default_reentrant_tick_commits_one_choice(qtbot,monkeypatch):
from PySide6.QtWidgets import QMessageBox
from cbb_refresh_verify.ui.timed_prompt import arm_default
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.DEFAULT_TIMEOUT_MS',50)
box=QMessageBox(); qtbot.addWidget(box); box.setStandardButtons(QMessageBox.Yes|QMessageBox.No)
choices=[]
def clicked(button):
choices.append(button)
if len(choices)==1: countdown.tick()
box.buttonClicked.connect(clicked)
countdown=arm_default(box,box.button(QMessageBox.Yes))
box.show(); qtbot.wait(120)
assert len(choices) == 1
def test_release_dialog_is_available_during_task_and_stale_receipt_keeps_view(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
monkeypatch.setattr(ResidualReleaseDialog,'refresh',lambda self:None)
released=[]
monkeypatch.setattr('cbb_refresh_verify.network_path.release_retained_path_leases',lambda proof,**kw:released.append(proof))
window=window_for(qtbot,tmp_path,monkeypatch)
load(window,qtbot); window.busy=True; window._update()
window.release_library_button.click()
dialog=window.release_dialog
assert dialog.isVisible() and dialog.windowModality()==Qt.NonModal
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc'); message=window.status_label.text()
dialog.released.emit(dict(status='RELEASE_CONFIRMED',library='a.lmc',evidence_path='proof.json'))
qtbot.waitUntil(lambda:bool(released))
dialog.close(); qtbot.wait(100)
assert window.status_label.text()==message
@pytest.mark.parametrize('kind',['read','lease'])
def test_source_process_exits_after_stalled_bookkeeping(tmp_path,kind):
import subprocess,sys,os,time
script=tmp_path/'close_app.py'
script.write_text('''from threading import Event
from pathlib import Path
import sys
from PySide6.QtWidgets import QApplication
from PySide6.QtCore import QTimer
from cbb_refresh_verify.ui.main_window import MainWindow
app=QApplication([])
MainWindow._show_unfinished_management=lambda self:None
block=Event()
w=MainWindow(reader=lambda _:block.wait(90),data_root=Path(sys.argv[2]))
w.show()
if sys.argv[1]=='read':
w.lmc_edit.setText('stalled.lmc'); w.load_library()
else: w._lease_action(lambda:block.wait(90))
QTimer.singleShot(150,w.close)
app.exec()
print('APP_RETURNED',flush=True)
''',encoding='utf-8')
env=dict(os.environ,QT_QPA_PLATFORM='offscreen')
started=__import__('time').monotonic()
process=subprocess.Popen([sys.executable,'-X','utf8',str(script),kind,str(tmp_path/'data')],
stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,encoding='utf-8',env=env)
try:
stdout,stderr=process.communicate(timeout=8)
assert process.returncode==0,stderr
assert 'APP_RETURNED' in stdout
assert time.monotonic()-started < 8
finally:
if process.poll() is None:
process.kill(); process.communicate()
def test_old_library_mapping_cleanup_does_not_keep_new_library_busy(qtbot,tmp_path,monkeypatch):
entered,release=Event(),Event(); calls=[]
window=window_for(qtbot,tmp_path,monkeypatch,verifier=lambda r:(calls.append(r.lmc_file) or VerifyResult('PASS')),
status_refresher=lambda names,_:{name:'PENDING' for name in names})
load(window,qtbot)
def cleanup(): entered.set(); release.wait(5)
window._lease_action(cleanup,hold_busy=True)
qtbot.waitUntil(entered.is_set)
try:
window.lmc_edit.setText('b.lmc'); window.load_library()
qtbot.waitUntil(lambda:window.loaded_path=='b.lmc' and not window.busy,timeout=1000)
window._run(['A'])
qtbot.waitUntil(lambda:bool(calls),timeout=1000)
assert calls == [Path('b.lmc')]
finally:
release.set(); qtbot.waitUntil(lambda:window._lease_pending==0)
@pytest.mark.parametrize('kind',['recovery','management'])
def test_dialog_handoff_is_not_claimed_as_safe_cancellation(qtbot,tmp_path,monkeypatch,kind):
from cbb_refresh_verify.operation_queue import TaskHandoff,BatchTaskContext
from cbb_refresh_verify.management import Capability
from PySide6.QtWidgets import QMessageBox
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
adapter=SimpleNamespace(capabilities=lambda:{op:Capability(True,'available') for op in ('add','update','remove')})
window=window_for(qtbot,tmp_path,monkeypatch,management_adapter=adapter)
load(window,qtbot); results=[]
def handed_off(*a,**k): raise TaskHandoff(BatchTaskContext('a.lmc'))
if kind=='recovery':
window.restore_backup(); dialog=window.backup_dialog
source=tmp_path/'A.prj'; source.write_text('project'); dialog.source_edit.setText(str(source))
dialog.recoverer=handed_off
dialog.completed.connect(lambda name,result:results.append(result))
dialog.restore_button.click()
else:
window.select_visible_button.click(); window.manage_cbb('remove'); dialog=window.management_dialog
dialog.runner=handed_off
dialog.completed.connect(results.extend)
dialog.execute_button.click()
qtbot.waitUntil(lambda:bool(results))
assert results[0].safe_to_continue is False
def test_real_startup_observer_delivery_after_destroy_is_ignored(qtbot,tmp_path,monkeypatch):
callbacks=[]
monkeypatch.setattr('cbb_refresh_verify.management.unfinished_operations',lambda _:[])
monkeypatch.setattr('cbb_refresh_verify.session_record.discover_sessions',lambda _:[dict(
status='ACTIVE',path='owned-session.json',block='A',phase='NATIVE_CALL',detail='running')])
monkeypatch.setattr('cbb_refresh_verify.session_record.handoff_session',lambda *a,**kw:callbacks.append(kw['progress']))
# This test explicitly destroys the QObject, so pytest-qt must not retain it
# for its normal close-at-teardown fixture.
window=MainWindow(reader=lambda _:LibraryReadResult(()),data_root=tmp_path)
window.show()
qtbot.waitUntil(lambda:bool(callbacks))
window.close(); qtbot.waitUntil(lambda:not window.isVisible())
import shiboken6
shiboken6.delete(window)
callbacks[0]({'library':'a.lmc','status':'RELEASED'})
def test_running_a_emits_real_choice_after_reading_b(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.pcb_open_consent import OpenChoice
entered,continue_a,answered=Event(),Event(),Event(); choices=[]
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.DEFAULT_TIMEOUT_MS',80)
def verify(request,*,version_prompt,**kwargs):
entered.set(); continue_a.wait(5)
choice=OpenChoice(request.block_name,request.lmc_file); choices.append(choice)
version_prompt(choice)
for _ in range(100):
if choice.decision is not None: answered.set(); break
Event().wait(.02)
return VerifyResult('SKIPPED',safe_to_continue=True)
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_verify',verify)
window=window_for(qtbot,tmp_path,monkeypatch,status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
load(window,qtbot); window._run(['A']); qtbot.waitUntil(entered.is_set)
try:
load(window,qtbot,'b.lmc'); message=window.status_label.text()
continue_a.set(); qtbot.waitUntil(answered.is_set)
assert choices[0].decision=='skip' and choices[0].library==Path('a.lmc')
assert window.status_label.text()==message
finally: continue_a.set(); window.pool.waitForDone(6000)
def test_second_management_dialog_cannot_submit_same_active_snapshot(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.management import Capability
from PySide6.QtWidgets import QMessageBox
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
entered,release=Event(),Event(); calls=[]
adapter=SimpleNamespace(capabilities=lambda:{op:Capability(True,'available') for op in ('add','update','remove')})
window=window_for(qtbot,tmp_path,monkeypatch,management_adapter=adapter)
def runner(requests,**kwargs):
calls.append(requests[0].name); entered.set(); release.wait(5); return []
load(window,qtbot); window.select_visible_button.click(); window.manage_cbb('remove')
first=window.management_dialog; first.runner=runner; first.execute_button.click()
qtbot.waitUntil(entered.is_set)
try:
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
window.select_visible_button.click(); window.manage_cbb('remove')
second=window.management_dialog; second.runner=runner; second.execute_button.click()
assert not second.busy
assert '重复' in second.status_label.text()
release.set(); qtbot.waitUntil(lambda:not first.busy)
assert calls==['A']
finally: release.set(); first.pool.waitForDone(6000)
def test_manual_repair_uses_current_diagnostic_database(qtbot,tmp_path,monkeypatch):
import json
evidence=tmp_path/'run'/'result.json'; evidence.parent.mkdir(); evidence.write_text('{}')
diagnostic=evidence.parent/'diagnostics'/'icdb-recovery.json'; diagnostic.parent.mkdir()
database=tmp_path/'actual-project'/'database'
diagnostic.write_text(json.dumps({'database_path':str(database),'scope':'project'}))
calls=[]
def launcher(request,**kwargs):
calls.append(kwargs)
return SimpleNamespace(process=SimpleNamespace(poll=lambda:None),job=evidence,
library=request.lmc_file,block=request.block_name,path_lease=None)
window=window_for(qtbot,tmp_path,monkeypatch,native_backup_launcher=launcher,
verifier=lambda _:VerifyResult('FAIL',safe_to_continue=True,evidence_path=evidence,error_category='ICDB_REPAIR_REQUIRED'),
status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
load(window,qtbot); window._run(['A']); qtbot.waitUntil(lambda:not window.busy)
window.cbb_table.setCurrentCell(0,0); window.native_repair_button.click()
qtbot.waitUntil(lambda:bool(calls))
assert calls[0]['target_database']==str(database)
@pytest.mark.parametrize('maintenance',[False,True])
def test_directory_only_submission_is_not_treated_as_native_registration(qtbot,tmp_path,monkeypatch,maintenance):
from cbb_refresh_verify.management import Catalog
calls=[]
window=window_for(qtbot,tmp_path,monkeypatch,
verifier=lambda req:(calls.append(req.block_name) or VerifyResult('PASS')),
status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
load(window,qtbot)
# The snapshot was already selectable while the native catalog was unknown.
window.catalog_reader=lambda path,evidence:Catalog(path,1,())
window._run(['A'],maintenance=maintenance)
qtbot.waitUntil(lambda:not window.busy and not window._icdb_active())
assert calls == []
def test_missing_all_project_directories_still_allows_native_catalog_reconciliation(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.management import Catalog,CatalogEntry
path=tmp_path/'lib.lmc'; path.write_bytes(b'library metadata')
window=MainWindow(data_root=tmp_path/'data',
catalog_reader=lambda library,evidence:Catalog(library,1,(CatalogEntry('NativeOnly','Logical-Physical'),)),
status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
qtbot.addWidget(window); window.show()
load(window,qtbot,str(path))
qtbot.waitUntil(lambda:'NativeOnly' in window._records_by_name)
assert window._records_by_name['NativeOnly'].catalog_source=='native_only'
assert window._read_counts==(0,1,1)
def test_failed_native_entry_resumes_captured_check_after_view_switch(qtbot,tmp_path,monkeypatch):
entered,release=Event(),Event(); calls=[]
def verify(request):
calls.append(request.block_name)
if len(calls)==1: entered.set(); release.wait(5)
return VerifyResult('CHECKED',safe_to_continue=True)
def failed(*a,**k): raise RuntimeError('entry refused')
window=window_for(qtbot,tmp_path,monkeypatch,reader=lambda _:LibraryReadResult((CbbRecord('A','LP'),CbbRecord('Next','LP'))),
verifier=verify,native_backup_launcher=failed)
load(window,qtbot); window._start_icdb_check(['A','Next']); qtbot.waitUntil(entered.is_set)
task=window.icdb_task
try:
window.cbb_table.setCurrentCell(0,0); window.native_backup_button.click()
assert task.paused
load(window,qtbot,'b.lmc'); message=window.status_label.text()
release.set()
qtbot.waitUntil(lambda:len(calls)==2,timeout=2000)
assert window.status_label.text()==message
finally:
release.set(); task.cancel(); qtbot.waitUntil(lambda:not task.active)
def test_old_release_panel_never_cancels_replacement_check(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
monkeypatch.setattr(ResidualReleaseDialog,'refresh',lambda self:None)
entered=Event(); window=None
def verify(_):
task=window.icdb_task; entered.set(); task.stop.wait(5)
return VerifyResult('CANCELLED',safe_to_continue=True)
window=window_for(qtbot,tmp_path,monkeypatch,verifier=verify)
load(window,qtbot); window._start_icdb_check(['A']); qtbot.waitUntil(entered.is_set)
old=window.icdb_task
window.release_library_button.click(); dialog=window.release_dialog
old.cancel(); qtbot.waitUntil(lambda:not old.active)
entered.clear(); load(window,qtbot,'b.lmc'); window._start_icdb_check(['A'])
qtbot.waitUntil(entered.is_set); newer=window.icdb_task
try:
dialog.before_release.emit()
assert not newer.stop.is_set()
finally:
newer.cancel(); qtbot.waitUntil(lambda:not newer.active)
@pytest.mark.parametrize('switch_view',[True,False])
def test_summary_actions_keep_original_revision_and_resume_configuration(qtbot,tmp_path,monkeypatch,switch_view):
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.DEFAULT_TIMEOUT_MS',10000)
monkeypatch.setattr('cbb_refresh_verify.operation_lifecycle.recheck_failed_release',lambda library,name,result,**kw:result)
requests=[]; release_clicks=[]
def verify(request):
requests.append(request)
return VerifyResult('FAIL' if request.block_name=='A' else 'PASS',safe_to_continue=request.block_name!='A')
window=window_for(qtbot,tmp_path,monkeypatch,reader=lambda _:LibraryReadResult((CbbRecord('A','LP'),CbbRecord('Next','LP'))),
verifier=verify,status_refresher=lambda names,_:{name:'PENDING' for name in names})
monkeypatch.setattr(window,'check_library_release',lambda *a,**k:release_clicks.append(True))
load(window,qtbot); original_timeout=window.timeout_spin.value(); window._run(['A','Next'])
qtbot.waitUntil(lambda:not window.busy)
old_release,old_resume=window._residual_release_action,window._resume_batch_action
window._resume_batch['released']=True; window._update()
if switch_view:
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
old_release.click(); old_resume.click(); qtbot.wait(100)
assert release_clicks==[] and len(requests)==1
else:
window.timeout_spin.setValue(45)
old_resume.click(); qtbot.waitUntil(lambda:not window.busy)
assert len(requests)==2 and requests[-1].block_name=='Next'
assert requests[-1].timeout_seconds==original_timeout
def test_recovery_retry_rejects_old_external_progress_and_choice(qtbot,tmp_path,monkeypatch):
from PySide6.QtWidgets import QMessageBox
from cbb_refresh_verify.pcb_open_consent import OpenChoice
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
callbacks=[]; entered,release=Event(),Event()
def recover(*args,progress,version_prompt,stop):
callbacks.append((progress,version_prompt))
if len(callbacks)==2: entered.set(); release.wait(5)
return VerifyResult('CANCELLED',safe_to_continue=True)
monkeypatch.setattr('cbb_refresh_verify.backup_recovery.recover_from_backup',recover)
window=window_for(qtbot,tmp_path,monkeypatch,status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
load(window,qtbot); window.restore_backup(); dialog=window.backup_dialog
source=tmp_path/'A.prj'; source.write_text('project'); dialog.source_edit.setText(str(source))
dialog.restore_button.click(); qtbot.waitUntil(lambda:not dialog.busy and not window.busy)
try:
dialog.restore_button.click(); qtbot.waitUntil(entered.is_set)
message=dialog.status_label.text()
callbacks[0][0]({'detail':'old external observer'})
choice=OpenChoice('A',Path('a.lmc')); callbacks[0][1](choice)
qtbot.wait(50)
assert dialog.status_label.text()==message
assert choice.decision=='cancel'
finally:
release.set(); qtbot.waitUntil(lambda:not dialog.busy)
+10 -10
View File
@@ -35,7 +35,7 @@ def test_reader_accepts_com_collections_exposing_callable_count():
def test_reader_fast_scans_reusable_blocks_without_com(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
(tmp_path / 'ReusableBlocksLP' / 'B_CBB').mkdir(parents=True)
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir()
from cbb_refresh_verify.library_reader import read_library_fast
@@ -45,7 +45,7 @@ def test_reader_fast_scans_reusable_blocks_without_com(tmp_path):
def test_reader_fast_applies_status_reader(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
(tmp_path / 'ReusableBlocksLP' / 'READY_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import read_library_fast
result = read_library_fast(lmc, status_reader=lambda name: 'READY' if name == 'READY_CBB' else 'PENDING')
@@ -53,7 +53,7 @@ def test_reader_fast_applies_status_reader(tmp_path):
def test_reader_fast_bulk_status_reader_is_called_once(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir(parents=True)
(tmp_path / 'ReusableBlocksLP' / 'B_CBB').mkdir()
calls = []
@@ -68,7 +68,7 @@ def test_reader_fast_bulk_status_reader_is_called_once(tmp_path):
def test_reader_fast_preserves_unavailable_bridge_status(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import read_library_fast
result = read_library_fast(lmc, status_reader=lambda path, names: {'A_CBB': 'UNAVAILABLE'})
@@ -77,7 +77,7 @@ def test_reader_fast_preserves_unavailable_bridge_status(tmp_path):
def test_reader_fast_exposes_status_reader_failure_as_unavailable(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import read_library_fast
result = read_library_fast(lmc, status_reader=lambda path, names: (_ for _ in ()).throw(RuntimeError('bridge down')))
@@ -86,7 +86,7 @@ def test_reader_fast_exposes_status_reader_failure_as_unavailable(tmp_path):
def test_filesystem_status_uses_complete_fresh_cert_artifacts(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
root = tmp_path / 'ReusableBlocksLP'
ready = root / 'READY_CBB' / 'Work'
pending = root / 'PENDING_CBB' / 'Work'
@@ -325,7 +325,7 @@ def test_status_scan_logs_each_cbb_image_id(caplog, tmp_path):
def test_status_scan_without_native_observation_does_not_guess_status(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
root = lmc.parent / 'ReusableBlocksLP'
ready = root / 'READY_CBB' / 'Work'
(ready / 'PCB' / 'Layout').mkdir(parents=True)
@@ -353,7 +353,7 @@ def test_status_scan_without_native_observation_does_not_guess_status(tmp_path):
def test_filesystem_evidence_exposes_multiple_persistent_dimensions(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
work = tmp_path / 'ReusableBlocksLP' / 'A_CBB' / 'Work'
(work / 'PCB' / 'Layout').mkdir(parents=True)
(work / 'A_CBB.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
@@ -375,7 +375,7 @@ def test_filesystem_evidence_exposes_multiple_persistent_dimensions(tmp_path):
def test_filesystem_evidence_preserves_mapped_drive_paths(tmp_path, monkeypatch):
"""Legacy evidence scanning must not resolve a mapped drive back to UNC."""
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
work = tmp_path / 'ReusableBlocksLP' / 'A_CBB' / 'Work'
(work / 'PCB' / 'Layout').mkdir(parents=True)
(work / 'A_CBB.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
@@ -393,7 +393,7 @@ def test_filesystem_evidence_preserves_mapped_drive_paths(tmp_path, monkeypatch)
def test_missing_work_project_is_a_pending_calibration_anchor(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
(tmp_path / 'ReusableBlocksLP' / 'IMPORTED_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import filesystem_evidence_map
evidence = filesystem_evidence_map(lmc, ('IMPORTED_CBB',))['IMPORTED_CBB']
+2 -1
View File
@@ -154,6 +154,7 @@ def test_released_batch_can_resume_only_its_unexecuted_items(qtbot, tmp_path, mo
action = window._resume_batch_action
assert action.isEnabled()
calls = []
original_remaining = (window._batch_requests[1],)
monkeypatch.setattr(window, '_run', lambda names, **kw: calls.append((names, kw)))
action.click()
assert calls == [(['Gamma'], {'maintenance': False})]
assert calls == [(['Gamma'], {'maintenance': False, 'request_snapshot': original_remaining})]
+19 -7
View File
@@ -28,6 +28,8 @@ def test_queued_action_has_visible_release_entry_and_resumes_after_proof(qtbot,
window.show()
library = window.mentor_lmc_path
retain(monkeypatch, library)
from test_review381_queue_release import hold_native_queue
queue_release, queue_worker = hold_native_queue(window)
finished = Event()
window._start(lambda: VerifyResult('PASS'), lambda _: finished.set())
qtbot.waitUntil(lambda: 'BlockedCBB' in window.status_label.text())
@@ -37,6 +39,7 @@ def test_queued_action_has_visible_release_entry_and_resumes_after_proof(qtbot,
window.queue_release_button.click()
assert opened == [{'queued': True}]
sessions._retained_libraries.clear()
queue_release.set(); queue_worker.join(2)
window.native_queue.wake()
qtbot.waitUntil(finished.is_set)
qtbot.waitUntil(lambda: not window.busy)
@@ -70,7 +73,9 @@ def test_release_mapping_cleanup_finishes_before_waiting_ticket_resumes(qtbot, t
retain(monkeypatch, library)
monkeypatch.setattr(library_lock, 'inspect_residual_sessions',
lambda _: dict(library=str(library), sessions=[]))
entered, allow_release = Event(), Event()
def backend_release(*a, **kw):
entered.set(); assert allow_release.wait(5)
sessions._retained_libraries.clear()
return dict(status='RELEASE_CONFIRMED', sessions=[], proof=dict(status='RELEASE_CONFIRMED',
library=str(library), evidence_path='controlled-proof.json'))
@@ -82,15 +87,20 @@ def test_release_mapping_cleanup_finishes_before_waiting_ticket_resumes(qtbot, t
def action():
assert cleaned.is_set(), 'new native operation began before old mapping release completed'
finished.set()
window._start(action, lambda _: None)
qtbot.waitUntil(lambda: window._queue_wait_library is not None)
window._queue_wait_library = str(library)
window.check_library_release(queued=True)
qtbot.waitUntil(lambda: not window.release_dialog.busy)
window.release_dialog.confirm_button.click()
qtbot.waitUntil(finished.is_set)
qtbot.waitUntil(lambda: not window.release_dialog.busy)
qtbot.waitUntil(lambda: not window.busy)
window.release_dialog.close()
qtbot.waitUntil(entered.is_set)
try:
window._start(action, lambda _: None)
allow_release.set()
qtbot.waitUntil(finished.is_set)
qtbot.waitUntil(lambda: not window.release_dialog.busy)
qtbot.waitUntil(lambda: not window.busy)
window.release_dialog.close()
finally:
allow_release.set()
def test_wait_reason_updates_when_active_task_becomes_a_retained_session(qtbot, tmp_path, monkeypatch):
@@ -110,7 +120,6 @@ def test_wait_reason_updates_when_active_task_becomes_a_retained_session(qtbot,
qtbot.waitUntil(lambda: '已排队' in window.status_label.text())
assert window._queue_wait_library is None
sessions._retained_libraries['controlled-session'] = {sessions._library_key(library)}
release.set(); first.join(3)
qtbot.waitUntil(lambda: 'BlockedCBB' in window.status_label.text())
assert not window.queue_release_button.isHidden()
finally:
@@ -132,6 +141,8 @@ def test_management_wait_shows_same_block_and_emits_release_target(qtbot, tmp_pa
qtbot.addWidget(dialog); dialog.show()
targets = []
dialog.release_requested.connect(targets.append)
from test_review381_queue_release import hold_native_queue
queue_release, queue_worker = hold_native_queue(dialog)
dialog.execute_button.click()
qtbot.waitUntil(lambda: 'BlockedCBB' in dialog.status_label.text())
assert dialog.release_wait_button.isVisible()
@@ -139,6 +150,7 @@ def test_management_wait_shows_same_block_and_emits_release_target(qtbot, tmp_pa
assert targets == [library]
dialog.stop.set()
qtbot.waitUntil(lambda: not dialog.busy)
queue_release.set(); queue_worker.join(2)
def test_close_waits_for_independent_release_worker(qtbot, tmp_path, monkeypatch):
+26 -4
View File
@@ -1,5 +1,5 @@
"""Stale and repeated user actions around native queue admission."""
from threading import Event
from threading import Event, Thread
from types import SimpleNamespace
from pathlib import Path
@@ -12,6 +12,18 @@ from test_review326_queue_guidance import retain
from test_ui_filters import load_window
def hold_native_queue(window):
"""A live owner, rather than old retention metadata, keeps admission queued."""
entered, release = Event(), Event()
def action():
entered.set()
assert release.wait(10)
worker = Thread(target=lambda:window.native_queue.run(action))
worker.start()
assert entered.wait(2)
return release, worker
def test_verify_admission_hides_release_entry_before_action_finishes(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
window.show()
@@ -81,6 +93,7 @@ def test_old_waiting_event_is_rechecked_against_current_release_state(qtbot, tmp
def test_other_library_icdb_start_preserves_the_foreground_wait(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
window.show()
queue_release, queue_worker = hold_native_queue(window)
retain(monkeypatch, window.mentor_lmc_path)
window._start(lambda: None, lambda _: None)
try:
@@ -90,6 +103,7 @@ def test_other_library_icdb_start_preserves_the_foreground_wait(qtbot, tmp_path,
assert window.queue_release_button.isVisible()
assert window._queue_wait_library == 'test.lmc'
finally:
queue_release.set(); queue_worker.join(2)
sessions._retained_libraries.clear()
window.native_queue.wake()
qtbot.waitUntil(lambda: not window.busy)
@@ -130,6 +144,7 @@ def test_repeated_click_and_close_reuse_one_panel_without_unlocking_the_task(qtb
from cbb_refresh_verify import library_lock
window = load_window(qtbot, tmp_path, monkeypatch)
window.show()
queue_release, queue_worker = hold_native_queue(window)
retain(monkeypatch, window.mentor_lmc_path)
monkeypatch.setattr(library_lock, 'inspect_residual_sessions',
lambda library: dict(library=str(library), sessions=[]))
@@ -150,6 +165,7 @@ def test_repeated_click_and_close_reuse_one_panel_without_unlocking_the_task(qtb
reopened.close()
assert window.busy
finally:
queue_release.set(); queue_worker.join(2)
sessions._retained_libraries.clear()
window.native_queue.wake()
qtbot.waitUntil(lambda: not window.busy)
@@ -159,6 +175,7 @@ def test_repeat_verify_then_stop_then_delayed_release_click_never_starts_work(qt
calls = []
window = load_window(qtbot, tmp_path, monkeypatch, verifier=lambda request: calls.append(request.block_name))
window.show()
queue_release, queue_worker = hold_native_queue(window)
retain(monkeypatch, window.mentor_lmc_path)
window.search_edit.setText('Beta')
window.verify_all()
@@ -167,15 +184,16 @@ def test_repeat_verify_then_stop_then_delayed_release_click_never_starts_work(qt
for _ in range(5):
qtbot.mouseClick(window.batch_button, Qt.LeftButton)
window.verify_all()
assert len(window.native_queue.pending) == 1
assert len(window.native_queue.pending) == 2
qtbot.mouseClick(window.stop_button, Qt.LeftButton)
qtbot.waitUntil(lambda: not window.busy)
for _ in range(5):
window.check_library_release(queued=True)
assert calls == []
assert not window.native_queue.pending
assert len(window.native_queue.pending) == 1
assert getattr(window, 'release_dialog', None) is None
finally:
queue_release.set(); queue_worker.join(2)
window.stop.set()
sessions._retained_libraries.clear()
window.native_queue.wake()
@@ -186,11 +204,14 @@ def test_repeat_verify_then_stop_then_delayed_release_click_never_starts_work(qt
def test_foreground_completion_and_background_cancel_keep_only_live_waits(qtbot, tmp_path, monkeypatch,
foreground_finishes_first):
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: pytest.fail('A retained library must not start a native check'))
verifier=lambda _: pytest.fail('An intentionally paused check must not execute'))
window.show()
queue_release, queue_worker = hold_native_queue(window)
retain(monkeypatch, window.mentor_lmc_path)
window._run(['Beta'], maintenance=True)
window.icdb_task.pause()
qtbot.waitUntil(lambda: window.queue_release_button.isVisible())
queue_release.set(); queue_worker.join(2)
window.mentor_lmc_path = Path('other.lmc')
window.lmc_edit.setText('other.lmc')
started, finish = Event(), Event()
@@ -215,6 +236,7 @@ def test_foreground_completion_and_background_cancel_keep_only_live_waits(qtbot,
if not foreground_finishes_first:
assert window.busy
finally:
queue_release.set(); queue_worker.join(2)
finish.set()
window.icdb_task.cancel()
sessions._retained_libraries.clear()
+2 -1
View File
@@ -49,7 +49,8 @@ def test_batch_result_is_visible_before_queued_refresh_and_survives_user_actions
other_started.set();other_release.wait(5)
thread=Thread(target=lambda:window.native_queue.run(other));thread.start()
try:
qtbot.waitUntil(lambda:len(window.native_queue.pending)==1)
# The queue retains both the active ticket and its waiting successor.
qtbot.waitUntil(lambda:len(window.native_queue.pending)==2)
release.set();qtbot.waitUntil(other_started.is_set)
qtbot.waitUntil(lambda:getattr(window,'summary',None) is not None,timeout=1500)
assert window.summary.isVisible() and window.busy
+2 -1
View File
@@ -126,7 +126,8 @@ def test_verify_requires_loaded_library_and_invalidates_on_path_change(qtbot):
assert hasattr(window, 'libspec_edit') and hasattr(window, 'dms_edit')
window.lmc_edit.setText('different.lmc')
assert not window.batch_button.isEnabled()
assert window.cbb_table.rowCount() == 0
assert window.cbb_table.rowCount() == 1
assert '失效' in window.library_notice.text()
def test_ui_removes_current_cbb_controls_and_hides_advanced_settings(qtbot):