Compare commits

..
Author SHA1 Message Date
阿白叔 e8a1714d95 fix: clarify backend status freshness and scoped copy evidence 2026-11-09 13:50:04 +08:00
42 changed files with 1084 additions and 4833 deletions

No files matched your search

@@ -9,3 +9,12 @@ Dependency rationale: library release imports native engineering identity and re
Rollback: before dependents are merged, revert this commit. After merging dependents, revert in reverse order or use the previous candidate package after closing the current app. Code rollback does not undo a native transaction; use a consistent manual backup or explicitly selected native history on an isolated copy.
Validation: full Python suite 1,376 passed (one existing pywinauto COM-threading warning); compileall and git diff --check passed. Native field recovery, Windows 10 and cross-machine shared-library acceptance remain pending.
Review comment 344 follow-up (2026-11-09):
- Production status scans continue to query fresh bridge results. The low-level session now also defaults to fresh scans; explicit checkpoint reuse is documented as a controlled read-only option with no production resume promise.
- `library-changes.json` declares `rule_version`, the selected `scope`, excluded directory categories and suffixes, positional runtime rules, runtime filenames/prefixes, and recognized coordination checkpoints. Names, suffixes, prefixes and native database locations come from the same constants used by semantic classification. These are differences in participating engineering files; excluded content is not proven unchanged, and unrelated CBB content is not checked.
- Removed the tests-only `pcb_bridge.execution_outcome` helper. Production release safety continues to come from observed release state and remaining clients.
- Unlocked primary snapshots hash the copy stream, then independently hash the final source and destination. Source reads decrease from three to two. Rejected the suggestion to remove/threshold the final source hash: size and mtime cannot detect same-size, same-timestamp source edits. Locked LMC/icdb streams and owned lock snapshots retain their existing behavior; no source-rehash skip flag is added.
Validation for this follow-up: 287 targeted cases passed through the isolated mutex/PYTHONPATH wrapper (`test_batch_status`, `test_batch_status_faults`, `test_review_backend_followup`, `test_scoped_manifest`, `test_pcb_bridge`, `test_management_retry_blockers`, `test_backup_recovery`, `test_library_lock`, `test_management`). AST parsing, `git diff --check`, and original newline-style checks passed. No real Mentor, COM automation, shared library or process control was exercised; no full-suite run was requested.
@@ -1,9 +0,0 @@
# 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
@@ -1,7 +0,0 @@
# 评论 275/283:结果口径接入
管理进度显示历史占用复核;结果分别呈现已确认的原生动作、变更清单完整性和历史会话释放事实。单项 RECOVERY_REQUIRED 但 safe_to_continue=True 时,不再声称整个队列停止;记录失败不伪装成原生上传/移除失败。
独立操作回归更新为实际历史记录归档流程:先证明当前占用已释放、保留归档字节,再进行普通验证;不自动 Repair,失败后不遗留新的占用锁。
本阶段相关 UI/独立操作/后端回归 29 passed。后端完整回归与最终集成回归另见验证记录。没有执行真实 Mentor 写操作;回退按依赖逆序,不代表恢复原生事务。
@@ -1,5 +1,7 @@
# CBB Batch Status Bridge Implementation Plan
Current behavior (2026-11-09): production status scans always query the bridge fresh and overwrite checkpoint evidence. `BatchStatusSession.scan` defaults to `resume=False`; `resume=True` remains an explicit low-level option for controlled read-only scans, not an exposed production resume feature. Its lightweight fingerprint cannot detect every native payload/database write, so saved READY/PENDING rows must not authorize production actions.
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Read 180 to 3000 CBB Verify states through one resilient x86 Mentor bridge session with checkpoint recovery and authoritative `READY/PENDING` results.
@@ -1,5 +1,7 @@
# CBB 批量状态桥设计
Current behavior (2026-11-09): production status scans always query the bridge fresh and overwrite checkpoint evidence. `BatchStatusSession.scan` defaults to `resume=False`; `resume=True` remains an explicit low-level option for controlled read-only scans, not an exposed production resume feature. Its lightweight fingerprint cannot detect every native payload/database write, so saved READY/PENDING rows must not authorize production actions.
## 目标
支持对 180 到 3000 个 CBB 进行 Mentor authoritative Verify 状态读取,要求单条失败隔离、过程可恢复、结果可审计,并避免现有“一条 CBB 启动一个桥进程”的启动开销。
+148 -151
View File
@@ -1,151 +1,148 @@
from __future__ import annotations
import argparse, os, sys
from pathlib import Path
from typing import Sequence
from .runtime_logging import configure
def configure_qt_application(app):
"""Apply a predictable light palette across machines and Qt themes."""
from PySide6.QtGui import QColor, QPalette
app.setStyle('Fusion')
palette = app.palette()
colors = {
QPalette.ColorRole.Window: '#f5f6f8',
QPalette.ColorRole.WindowText: '#202124',
QPalette.ColorRole.Base: '#ffffff',
QPalette.ColorRole.AlternateBase: '#eef1f5',
QPalette.ColorRole.Text: '#202124',
QPalette.ColorRole.Button: '#eef1f5',
QPalette.ColorRole.ButtonText: '#202124',
QPalette.ColorRole.Highlight: '#2f6fed',
QPalette.ColorRole.HighlightedText: '#ffffff',
QPalette.ColorRole.ToolTipBase: '#ffffff',
QPalette.ColorRole.ToolTipText: '#202124',
QPalette.ColorRole.PlaceholderText: '#6b7280',
}
for role, color in colors.items():
palette.setColor(role, QColor(color))
for role in (QPalette.ColorRole.WindowText, QPalette.ColorRole.Text, QPalette.ColorRole.ButtonText):
palette.setColor(QPalette.ColorGroup.Disabled, role, QColor('#858b94'))
app.setPalette(palette)
app.setStyleSheet(
'QWidget { color: #202124; }'
'QTableWidget, QLineEdit, QTextEdit, QSpinBox { '
'background: #ffffff; color: #202124; selection-color: #202124; }'
'QHeaderView::section { background: #e9edf2; color: #202124; }'
'QPushButton, QToolButton { color: #202124; }'
'QPushButton:disabled, QToolButton:disabled { color: #858b94; background: #e3e6eb; }'
)
return app
def resolve_data_root(cli_value: Path | None) -> Path:
if cli_value is not None: return cli_value.expanduser().resolve()
if getattr(sys, "frozen", False): return Path(sys.executable).resolve().parent / "data"
local = os.environ.get("LOCALAPPDATA")
return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve()
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--owner-probe', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--native-backup-worker', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--management-worker', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS)
parser.add_argument('--libspec', default='', help=argparse.SUPPRESS)
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
args = parser.parse_args(list(argv) if argv is not None else None)
if args.owner_probe:
from .owner_probe import owner_probe_main
return owner_probe_main(args.owner_probe)
if args.native_backup_worker:
from .native_backup import native_backup_worker_main
return native_backup_worker_main(args.native_backup_worker)
if args.management_worker:
from .native_management import management_worker_main
return management_worker_main(args.management_worker)
if args.repair_worker:
from .native_repair_ui import repair_worker_main
return repair_worker_main(args.repair_worker)
if args.collect_failure_logs:
from .verify_diagnostics import failure_logs_main
return failure_logs_main(args.collect_failure_logs)
if args.dialog_agent:
from .dialog_agent import dialog_agent_main
return dialog_agent_main(args.dialog_agent)
if args.verify_worker:
from .mentor_adapter import worker_main
import contextlib
with args.verify_worker.with_name('worker.log').open('a', encoding='utf-8') as log:
with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
return worker_main(args.verify_worker)
context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start")
try:
if args.batch_lmc:
from .verify_runner import (VerifyRequest, native_lm_verify_enabled,
run_batch, write_batch_report, failure_report_path)
from .library_reader import read_library_fast
from .batch_status import authoritative_status_map
from .network_path import LibraryPathLease, select_library_file
with LibraryPathLease.acquire(args.batch_lmc) as lease:
mentor_path = select_library_file(lease.mentor_path)
logger.info(
'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s',
lease.display_path, mentor_path, lease.drive or '-',
lease.remote_root or '-', lease.created)
names = list(args.block)
if not names:
library = read_library_fast(
mentor_path,
status_reader=lambda path, names: authoritative_status_map(
names, path, context.root/'status-scan.jsonl'),
)
if library.error: raise RuntimeError(library.error)
names = [record.name for record in library.records if record.status != 'READY']
if not names: raise RuntimeError('中心库未读取到需要校验的 CBB')
requests = [VerifyRequest(mentor_path, name, context.root/'evidence',
libspec=args.libspec, dms_login_config=args.dms_login_config,
mentor_bin=args.mentor_bin, logging_context=context,
mapped_drive=lease.drive,
mapped_remote_root=lease.remote_root,
native_lm_verify=native_lm_verify_enabled())
for name in names]
try:
results = run_batch(requests)
except Exception:
lease.retain_for_recovery()
raise
if any(not result.safe_to_continue for result in results):
lease.retain_for_recovery()
report = write_batch_report(requests, results, context.root/'reports')
logger.info('batch_report path=%s', report)
logger.info('failure_report path=%s', failure_report_path(report))
code = 0 if all(result.status == 'PASS' for result in results) else 2
logger.info('application_clean_shutdown exit_code=%s', code)
return code
from .ui.main_window import MainWindow, application_icon_path
if args.smoke_test:
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
from PySide6.QtWidgets import QApplication
app = QApplication.instance() or QApplication([sys.executable])
configure_qt_application(app)
window = MainWindow(logging_context=context); window.show()
icon_path = application_icon_path()
if icon_path.is_file():
from PySide6.QtGui import QIcon
app.setWindowIcon(QIcon(str(icon_path)))
if args.smoke_test:
from PySide6.QtCore import QTimer
logger.info('gui_smoke_window_created title=%s', window.windowTitle())
QTimer.singleShot(250, app.quit)
code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code
except Exception: logger.exception("application_startup_failure"); return 1
finally:
for handler in logger.handlers: handler.flush()
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()
+10 -3
View File
@@ -107,7 +107,7 @@ def fingerprint_library(lmc: Path) -> LmcFingerprint:
# Metadata alone is not a safe checkpoint key: on network shares and on
# file systems with coarse timestamp resolution, two different LMC
# contents can have the same size and mtime. Include the actual file
# digest so a changed central library can never reuse an old status row.
# digest to invalidate changed LMC bytes; payload edits remain outside this key.
content_sha256 = _sha256_file(path)
combined = hashlib.sha256()
combined.update(str(path).casefold().encode('utf-8', errors='surrogatepass'))
@@ -186,7 +186,12 @@ def _now() -> str:
class BatchStatusSession:
"""Supervised serial bridge session with checkpoint recovery."""
"""Supervised serial bridge session; fresh status queries by default.
Checkpoints record scan evidence. Explicit ``resume=True`` is a low-level
opt-in for controlled read-only scans, not a production freshness proof:
the lightweight fingerprint does not cover native payload/database edits.
"""
def __init__(self, bridge: StatusBridgeClient, *, timeout_seconds: float = 10.0,
rotate_every: int = 500) -> None:
@@ -196,7 +201,7 @@ class BatchStatusSession:
self.restart_count = 0
def scan(self, names: Iterable[str], lmc_file: Path, checkpoint_path: Path,
*, block_type: str = "RULP", resume: bool = True) -> list[BatchStatusRecord]:
*, block_type: str = "RULP", resume: bool = False) -> list[BatchStatusRecord]:
fingerprint = fingerprint_library(Path(lmc_file))
if resume:
checkpoint = BatchCheckpoint.load(checkpoint_path)
@@ -291,6 +296,8 @@ def authoritative_status_map(names: Iterable[str], lmc_file: Path, checkpoint_pa
timeout_seconds: float = 10.0) -> dict[str, str]:
"""Return only bridge-backed statuses for an optional UI integration.
Production always queries fresh statuses, including after native writes;
saved READY/PENDING rows are never reused here.
A missing bridge is represented as ``UNAVAILABLE``/``UNKNOWN`` by callers;
it is never promoted to ``READY``.
"""
+2 -1
View File
@@ -8,7 +8,7 @@ from uuid import uuid4
from .library_lock import LibraryLock, LibraryBusy
from .scoped_manifest import (ManifestScope, build_manifest, build_exclusive_library_manifest,
copy_verified, hash_file, scan_tree)
comparison_rules, copy_verified, hash_file, scan_tree)
@dataclass(frozen=True)
@@ -212,6 +212,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
nonlocal change_report
if mutated and original is not None and change_report is None:
change_report = {'status': 'UNCONFIRMED', 'scope': original['scope'],
**comparison_rules(scope),
'unrelated_cbb_content_checked': False,
'detail': '原生会话尚未释放,未读取写后内容'}
if safe:
-15
View File
@@ -160,18 +160,3 @@ def wait_for_target_document(job, app_provider, *, process_alive, emit=lambda **
last_observation = observation
sleep(.25)
raise PcbBridgeError('PCB_EXITED_BEFORE_COM', 'PCB 在 COM 文档就绪前退出')
def execution_outcome(*, save_complete: bool, pcb_exited: bool,
fatal_error: str = '') -> dict[str, object]:
if fatal_error:
code, _, detail = str(fatal_error).partition(':')
return {'status': 'FAIL', 'error_code': code.strip() or 'FATAL_DIALOG',
'stderr': detail.strip() or str(fatal_error), 'safe_to_continue': True}
if not save_complete:
return {'status': 'FAIL', 'error_code': 'SAVE_NOT_CONFIRMED',
'stderr': '保存/关闭未完成', 'safe_to_continue': True}
if not pcb_exited:
return {'status': 'FAIL', 'error_code': 'PCB_EXIT_NOT_CONFIRMED',
'stderr': '保存后未确认 PCB 退出', 'safe_to_continue': True}
return {'status': 'PASS', 'stdout': 'Project Integration 已同步;保存、关闭和 PCB 退出均已确认。'}
+59 -11
View File
@@ -15,6 +15,15 @@ import stat
MANIFEST_VERSION = 1
MANIFEST_RULE_VERSION = 1
_ROOT_RUNTIME_PREFIX = 'work.before-restore-'
_ROOT_RUNTIME_PATH = ('projectbackup', 'backups')
_NATIVE_RUNTIME_DIRECTORIES = ('log', 'dbcheck', 'dbrestore')
_NATIVE_SERVER_DIRECTORY = 'cdbsvr'
_PROJECT_PCB_DIRECTORY = 'pcb'
_PROJECT_DATABASE_PREFIXES = (('database',), (_PROJECT_PCB_DIRECTORY, 'database'))
_NONPRIMARY_FILENAMES = ('saddress.adr',)
_NONPRIMARY_FILENAME_PREFIXES = ('~$',)
_NONPRIMARY_DIRECTORIES = frozenset({
'log', 'logs', 'temp', 'tmp', '__pycache__', 'backup', 'backups',
'output', 'outputs', 'report', 'reports', 'gerber', 'gerbers', 'odb++',
@@ -29,22 +38,21 @@ def _root_runtime(directories):
"""Known runtime/history children of a library or project workspace root."""
return bool(directories and (
directories[0] in _NONPRIMARY_DIRECTORIES
or directories[0].startswith('work.before-restore-')
or directories[:2] == ('projectbackup', 'backups')))
or directories[0].startswith(_ROOT_RUNTIME_PREFIX)
or directories[:len(_ROOT_RUNTIME_PATH)] == _ROOT_RUNTIME_PATH))
def _native_runtime(directories, database_prefix):
runtime_prefix = database_prefix + ('cdbsvr',)
runtime_prefix = database_prefix + (_NATIVE_SERVER_DIRECTORY,)
return (directories[:len(runtime_prefix)] == runtime_prefix
and len(directories) > len(runtime_prefix)
and directories[len(runtime_prefix)] in ('log', 'dbcheck', 'dbrestore'))
and directories[len(runtime_prefix)] in _NATIVE_RUNTIME_DIRECTORIES)
def _project_runtime(directories):
return (_root_runtime(directories)
or (directories[:1] == ('pcb',) and _root_runtime(directories[1:]))
or _native_runtime(directories, ('database',))
or _native_runtime(directories, ('pcb', 'database')))
or (directories[:1] == (_PROJECT_PCB_DIRECTORY,) and _root_runtime(directories[1:]))
or any(_native_runtime(directories, prefix) for prefix in _PROJECT_DATABASE_PREFIXES))
@dataclass(frozen=True)
@@ -85,7 +93,8 @@ class ManifestScope:
"""
directories = parts if directory else parts[:-1]
if not directory and (Path(parts[-1]).suffix in _NONPRIMARY_SUFFIXES
or parts[-1] == 'saddress.adr' or parts[-1].startswith('~$')):
or parts[-1] in _NONPRIMARY_FILENAMES
or parts[-1].startswith(_NONPRIMARY_FILENAME_PREFIXES)):
return True
if self.kind == 'project':
return _project_runtime(directories)
@@ -123,6 +132,36 @@ class ManifestScope:
return 'shared_dependency'
def comparison_rules(scope):
"""Describe semantic exclusions using the classifier's rule constants."""
project_positions = ['project root or its PCB child']
project_native = ' or '.join('/'.join(prefix + (_NATIVE_SERVER_DIRECTORY,))
for prefix in _PROJECT_DATABASE_PREFIXES)
native_positions = [project_native + ' under project root']
if scope.kind == 'library':
project_positions = ['library root', 'selected CBB Work/Cert root or its PCB child']
native_positions = [
project_native + ' under selected CBB Work/Cert',
'SymbolLibs/<partition>/' + _NATIVE_SERVER_DIRECTORY,
'<shared dependency>/' + _NATIVE_SERVER_DIRECTORY,
]
return {
'rule_version': MANIFEST_RULE_VERSION,
'excluded_categories': sorted(_NONPRIMARY_DIRECTORIES),
'excluded_suffixes': sorted(_NONPRIMARY_SUFFIXES),
'runtime_exclusions': {
'directory_name_positions': project_positions,
'directory_prefixes': [_ROOT_RUNTIME_PREFIX],
'relative_directories': ['/'.join(_ROOT_RUNTIME_PATH)],
'native_directory_names': sorted(_NATIVE_RUNTIME_DIRECTORIES),
'native_directory_positions': native_positions,
'file_names': list(_NONPRIMARY_FILENAMES),
'file_name_prefixes': list(_NONPRIMARY_FILENAME_PREFIXES),
'coordination_checkpoints': 'recognized CBB coordination checkpoints',
},
}
def hash_file(path):
digest = hashlib.sha256()
with Path(path).open('rb') as stream:
@@ -271,7 +310,10 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
Native icdb.dat/LMC files are held with exclusive read handles for the copy.
Their expected SHA256 comes from the source read stream, independently of
hashing destination bytes. Failures retain the partial destination evidence.
hashing destination bytes. Unlocked primary files are also hashed while
streaming the copy, then rehashed at source to detect even same-size/mtime
edits. Every primary destination is independently hashed. Failures retain
the partial destination evidence.
Progress receives one dict with stage, hashed_files/bytes and copied_files.
"""
import win32con
@@ -329,9 +371,15 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
shutil.copystat(path, copied)
if stream_hash is not None:
digest = stream_hash.hexdigest()
elif label is not None:
stream_hash = hashlib.sha256()
with path.open('rb') as incoming, copied.open('wb') as outgoing:
for data in iter(lambda: incoming.read(1024 * 1024), b''):
stream_hash.update(data)
outgoing.write(data)
shutil.copystat(path, copied)
digest = stream_hash.hexdigest()
else:
if label is not None:
digest = hash_function(path)
shutil.copy2(path, copied)
before, after = entries[path], path.stat()
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
@@ -1,5 +0,0 @@
"""Shared wording for user-managed backups before write operations."""
MANUAL_BACKUP_NOTICE = (
'应用不会自动备份。请先手动备份中心库及相关工程,并确认备份可用于恢复。'
)
@@ -1,13 +1,11 @@
"""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, QMessageBox)
QHBoxLayout, QLabel, QLineEdit, QPushButton)
from .workers import ServiceWorker
from .backup_notice import MANUAL_BACKUP_NOTICE
class RecoverySignals(QObject):
@@ -24,8 +22,6 @@ 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)
@@ -41,10 +37,7 @@ class BackupRecoveryDialog(QDialog):
self.restore_button.clicked.connect(self._restore)
self.close_button = QPushButton('关闭')
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.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 所选备份先在隔离库中验证;安装时旧 Work 仅改名保留。')
self.status_label = QLabel('使用所选备份版本恢复同名 CBB。先在库副本中验证,原工程与完整库副本会保留;需要额外磁盘空间。')
self.status_label.setWordWrap(True)
layout = QFormLayout(self)
layout.addRow('目标 CBB', self.block_combo)
@@ -56,7 +49,6 @@ 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)
@@ -85,30 +77,12 @@ 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)
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 = ServiceWorker(lambda: recoverer(
request, source, progress=self.signals.progress.emit))
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)
@@ -121,8 +95,6 @@ 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))
@@ -143,7 +115,6 @@ class BackupRecoveryDialog(QDialog):
def _finished(self):
self.busy = False
self.cancel_queue_button.setEnabled(False)
self._set_enabled(True)
def reject(self):
@@ -1,115 +0,0 @@
"""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
@@ -1,250 +0,0 @@
"""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)
@@ -1,31 +0,0 @@
"""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
@@ -1,75 +0,0 @@
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
@@ -1,122 +0,0 @@
"""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'
+7 -15
View File
@@ -2,13 +2,6 @@ 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):
@@ -58,12 +51,11 @@ def test_backup_dialog_keeps_ui_responsive_and_cannot_close_during_restore(qtbot
assert dialog.close_button.isEnabled()
def test_main_window_opens_non_ready_dialog_and_failure_retains_ready_untargeted(qtbot, tmp_path):
def test_main_window_opens_simple_dialog_and_failure_clears_ready(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,
status_refresher=lambda names, _: {name: 'UNKNOWN' for name in names})
CbbRecord('A', 'LP', status='READY'), CbbRecord('B', 'LP'))), data_root=tmp_path)
qtbot.addWidget(window)
window.lmc_edit.setText('lib.lmc'); window.load_library()
qtbot.waitUntil(lambda: not window.busy)
@@ -71,12 +63,12 @@ def test_main_window_opens_non_ready_dialog_and_failure_retains_ready_untargeted
window.backup_restore_button.click()
dialog = window.backup_dialog
assert dialog.isVisible()
assert dialog.block_combo.currentText() == 'B'
dialog.started.emit('B')
assert dialog.block_combo.currentText() == 'A'
dialog.started.emit('A')
assert window.busy
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() == '未知 / 需确认'
assert 'A' not in window.ready_names
dialog.completed.emit('A', VerifyResult('FAIL', stderr='损坏'))
assert window.cbb_table.item(0, 2).text() == '未知 / 需确认'
dialog.reject()
qtbot.waitUntil(lambda: not window.busy)
+21 -2
View File
@@ -84,11 +84,30 @@ def test_scan_reuses_checkpoint_and_queries_only_missing(tmp_path):
encoding="utf-8",
)
bridge = FakeBridge()
records = BatchStatusSession(bridge).scan(["A", "B"], lmc, checkpoint)
records = BatchStatusSession(bridge).scan(["A", "B"], lmc, checkpoint, resume=True)
assert bridge.requests == ["B"]
assert {record.block_name for record in records} == {"A", "B"}
def test_default_scan_refreshes_cached_ready_after_payload_change(tmp_path):
lmc = tmp_path/'library.lmc'; lmc.write_bytes(b'library')
checkpoint = tmp_path/'scan.jsonl'
BatchStatusSession(FakeBridge()).scan(['A'], lmc, checkpoint)
# The lightweight fingerprint cannot prove payload status is unchanged.
fingerprint = fingerprint_library(lmc)
(tmp_path/'payload.pcb').write_bytes(b'native edit without LMC change')
assert fingerprint_library(lmc) == fingerprint
class PendingBridge(FakeBridge):
def query(self, *args, **kwargs):
self.requests.append(args[1])
return BridgeResult('PENDING', 'fake')
bridge = PendingBridge()
records = BatchStatusSession(bridge).scan(['A'], lmc, checkpoint)
assert [record.status for record in records] == ['PENDING']
assert bridge.requests == ['A']
assert len(checkpoint.read_text('utf-8').splitlines()) == 1
def test_timeout_isolated_and_later_item_continues(tmp_path):
lmc = tmp_path / "mentor_lib.lmc"
lmc.write_bytes(b"library")
@@ -180,7 +199,7 @@ def test_retry_rechecks_failed_scan_without_library_changes(tmp_path):
first = BatchStatusSession(FakeBridge(timeout_name='A')).scan(['A', 'B'], lmc, checkpoint)
assert first[0].status == 'TIMEOUT'
bridge = FakeBridge()
second = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint)
second = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint, resume=True)
assert bridge.requests == ['A']
assert second[0].status == 'READY'
+1 -1
View File
@@ -82,5 +82,5 @@ def test_fingerprint_change_does_not_reuse_checkpoint(tmp_path):
from cbb_refresh_verify.status_bridge import BridgeResult
return BridgeResult("PENDING", "fake")
bridge = Bridge()
BatchStatusSession(bridge).scan(["A"], lmc, checkpoint)
BatchStatusSession(bridge).scan(["A"], lmc, checkpoint, resume=True)
assert bridge.requests == ["A"]
-13
View File
@@ -174,19 +174,6 @@ 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
@@ -1,159 +0,0 @@
"""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
@@ -1,187 +0,0 @@
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
@@ -1,171 +0,0 @@
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
@@ -1,75 +0,0 @@
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'
+1 -1
View File
@@ -269,7 +269,7 @@ def test_status_cache_does_not_reuse_a_different_block_type(tmp_path):
return BridgeResult('READY', 'test')
session = BatchStatusSession(Bridge())
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='RULP')
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='Other')
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='Other', resume=True)
assert calls == ['RULP', 'Other']
-113
View File
@@ -1,113 +0,0 @@
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
@@ -1,51 +0,0 @@
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
@@ -1,263 +0,0 @@
"""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()
+169 -191
View File
@@ -1,191 +1,169 @@
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'
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'
-43
View File
@@ -1,43 +0,0 @@
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()
-18
View File
@@ -2,7 +2,6 @@ import pytest
from cbb_refresh_verify.pcb_bridge import (
PcbBridgeError,
execution_outcome,
require_document_identity,
wait_for_target_document,
)
@@ -74,23 +73,6 @@ def test_bridge_stops_if_pcb_exits_before_com_is_ready(tmp_path):
assert raised.value.error_code == 'PCB_EXITED_BEFORE_COM'
def test_fatal_dialog_overrides_successful_save_markers():
result = execution_outcome(
save_complete=True,
pcb_exited=True,
fatal_error='SAVE_REUSABLE_BLOCK_FAILED: Error saving the Reusable Block',
)
assert result['status'] == 'FAIL'
assert result['error_code'] == 'SAVE_REUSABLE_BLOCK_FAILED'
def test_success_requires_save_and_pcb_exit():
assert execution_outcome(save_complete=True, pcb_exited=True)['status'] == 'PASS'
assert execution_outcome(save_complete=False, pcb_exited=True)['status'] == 'FAIL'
assert execution_outcome(save_complete=True, pcb_exited=False)['status'] == 'FAIL'
def test_connected_com_without_document_remains_startup_and_checks_native_failure(tmp_path):
errors = iter(('', 'ICDB_REPAIR_REQUIRED: original lost session'))
events = []
-132
View File
@@ -1,132 +0,0 @@
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
@@ -1,242 +0,0 @@
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 == []
+14
View File
@@ -87,6 +87,20 @@ def test_management_records_scoped_changes_without_hashing_unrelated_cbb(setup,
assert 'SymbolLibs/shared/icdb.dat' in report['modified']
assert 'ReusableBlocksLP/Block/Work/Block.prj' in report['modified']
assert result.change_report == report
assert report['rule_version'] == 1
assert report['scope'] == {'kind': 'library', 'block_name': 'Block',
'library_name': request.library.name}
from cbb_refresh_verify import scoped_manifest as manifests
assert report['excluded_categories'] == sorted(manifests._NONPRIMARY_DIRECTORIES)
assert report['excluded_suffixes'] == sorted(manifests._NONPRIMARY_SUFFIXES)
runtime = report['runtime_exclusions']
assert runtime['native_directory_names'] == ['dbcheck', 'dbrestore', 'log']
assert runtime['file_names'] == ['saddress.adr']
assert runtime['file_name_prefixes'] == ['~$']
assert runtime['relative_directories'] == ['projectbackup/backups']
assert runtime['directory_prefixes'] == ['work.before-restore-']
assert 'selected CBB Work/Cert root or its PCB child' in runtime['directory_name_positions']
assert 'SymbolLibs/<partition>/cdbsvr' in runtime['native_directory_positions']
def test_failed_mutation_still_records_changes_and_release_fact(setup):
@@ -1,31 +0,0 @@
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()
+31 -6
View File
@@ -118,17 +118,42 @@ def test_corrupted_destination_bytes_are_rejected_and_evidence_is_preserved(tmp_
assert (destination/relative).exists()
def test_unlocked_primary_copy_reads_source_twice_and_target_once(tmp_path, monkeypatch):
from collections import Counter
source, destination = tmp_path/'source', tmp_path/'destination'
primary = put(source, 'A.prj', b'engineering' * 100000)
reads = Counter()
original_open = Path.open
def opened(path, mode='r', *args, **kwargs):
if mode == 'rb':
reads[path] += 1
return original_open(path, mode, *args, **kwargs)
monkeypatch.setattr(Path, 'open', opened)
hashes = Counter()
original_hash = recovery._hash
def hashed(path):
hashes[path] += 1
return original_hash(path)
monkeypatch.setattr(recovery, '_hash', hashed)
manifest = recovery._copy_verified(source, destination)
assert hashes[primary] == 1 # Only the final source rehash is a separate pass.
assert hashes[destination/'A.prj'] == 1
assert reads[primary] == 2 # Copy/hash stream, then final source content proof.
assert reads[destination/'A.prj'] == 1
assert manifest['files']['A.prj']['sha256'] == hashlib.sha256(primary.read_bytes()).hexdigest()
def test_source_byte_changes_with_preserved_metadata_are_rejected(tmp_path, monkeypatch):
source, destination = tmp_path/'source', tmp_path/'destination'
primary = put(source, 'A.prj')
real_copy = shutil.copy2
real_copy = shutil.copystat
def copy_then_change_source(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
metadata = primary.stat()
primary.write_bytes(b'X' * metadata.st_size)
os.utime(primary, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_change_source)
monkeypatch.setattr(shutil, 'copystat', copy_then_change_source)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
assert (destination/'A.prj').read_bytes() == b'engineering'
@@ -140,7 +165,7 @@ def test_complete_tree_metadata_must_stay_stable_during_copy(tmp_path, monkeypat
put(source, 'A.prj')
runtime = put(source, 'logs/session.log')
destination = tmp_path/'destination'
real_copy = shutil.copy2
real_copy = shutil.copystat
def copy_then_mutate(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
if Path(src).name == 'A.prj':
@@ -151,7 +176,7 @@ def test_complete_tree_metadata_must_stay_stable_during_copy(tmp_path, monkeypat
else:
put(source, 'logs/added.log')
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_mutate)
monkeypatch.setattr(shutil, 'copystat', copy_then_mutate)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
assert destination.exists()
@@ -277,7 +302,7 @@ def test_colliding_engineering_names_cannot_bypass_primary_copy_byte_checks(tmp_
scope = ManifestScope.library(block, 'target.lmc')
source, destination = tmp_path/'source', tmp_path/'destination'
put(source, relative)
real_copy = shutil.copy2
real_copy = shutil.copystat
def copy_then_corrupt(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
corrupt = Path(src) if side == 'source' else Path(dst)
@@ -285,7 +310,7 @@ def test_colliding_engineering_names_cannot_bypass_primary_copy_byte_checks(tmp_
corrupt.write_bytes(b'X' * metadata.st_size)
os.utime(corrupt, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_corrupt)
monkeypatch.setattr(shutil, 'copystat', copy_then_corrupt)
with pytest.raises(OSError):
recovery._copy_verified(source, destination, scope=scope)
assert (destination/relative).exists()
+32 -45
View File
@@ -1,5 +1,4 @@
import os
import pytest
from pathlib import Path
os.environ.setdefault('QT_QPA_PLATFORM','offscreen')
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
@@ -22,17 +21,7 @@ def test_application_palette_keeps_table_text_readable(qtbot):
def fake_reader(_): return LibraryReadResult((CbbRecord('CBB1','Reusable Blocks'),))
@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):
def test_global_icdb_action_confirms_and_includes_ready_rows(qtbot, tmp_path, monkeypatch):
from PySide6.QtWidgets import QMessageBox
calls = []
window = MainWindow(reader=lambda _: LibraryReadResult((
@@ -47,8 +36,8 @@ def test_global_icdb_action_confirms_and_excludes_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._icdb_active())
assert calls == ['PENDING']
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['READY', 'PENDING']
def test_global_icdb_action_disabled_without_library_or_while_busy(qtbot):
window = MainWindow(reader=fake_reader)
@@ -60,11 +49,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_preserves_untargeted_ready_and_stops_queue(qtbot, tmp_path, monkeypatch):
def test_global_icdb_failure_clears_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('C', 'LP'))),
CbbRecord('A', 'LP', status='READY'), CbbRecord('B', '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)
@@ -72,13 +61,13 @@ def test_global_icdb_failure_preserves_untargeted_ready_and_stops_queue(qtbot, t
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._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() == '未检查'
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')
def test_global_icdb_progress_and_check_summary(qtbot, tmp_path, monkeypatch):
def test_global_icdb_progress_and_repair_summary(qtbot, tmp_path, monkeypatch):
from PySide6.QtWidgets import QMessageBox
confirmations = []
def confirm(*args, **kwargs):
@@ -92,14 +81,13 @@ def test_global_icdb_progress_and_check_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._icdb_active())
qtbot.waitUntil(lambda: not window.busy)
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 '恢复备份待复核' not in window.status_label.text()
assert window.summary.windowTitle() == 'ICDB 批量检查结果'
assert '恢复备份待复核 1' in window.status_label.text()
assert window.summary.windowTitle() == '全库 ICDB 检查与修复结果'
reports = list((tmp_path/'reports').glob('icdb-*.json'))
assert len(reports) == 1
@@ -114,7 +102,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 '缺少工程' in window.cbb_table.item(0, 2).text()
assert window.cbb_table.item(0, 2).text().startswith('跳过')
def test_verify_requires_loaded_library_and_invalidates_on_path_change(qtbot):
window=MainWindow(reader=fake_reader, verifier=lambda _: VerifyResult('PASS')); qtbot.addWidget(window)
@@ -168,8 +156,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 '缺少工程' in window.cbb_table.item(0, 2).text()
assert window.cbb_table.item(0, 0).flags() & Qt.ItemIsUserCheckable
assert window.cbb_table.item(0, 2).text().startswith('跳过:')
assert not (window.cbb_table.item(0, 0).flags() & Qt.ItemIsUserCheckable)
window.verify_all()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['VALID_CBB']
@@ -230,7 +218,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_allow_management_selection_but_cannot_be_verified(qtbot, tmp_path):
def test_ready_rows_show_status_and_cannot_be_selected_or_verified(qtbot, tmp_path):
def reader(_):
return LibraryReadResult((CbbRecord('READY_CBB', 'LP', status='READY'), CbbRecord('PENDING_CBB', 'LP', status='PENDING')))
calls = []
@@ -241,16 +229,15 @@ def test_ready_rows_allow_management_selection_but_cannot_be_verified(qtbot, tmp
qtbot.waitUntil(lambda: window.batch_button.isEnabled())
assert window.cbb_table.columnCount() == 4
assert window.cbb_table.item(0, 2).text() == '绿色 / Ready'
assert window.cbb_table.item(0, 0).flags() & Qt.ItemIsUserCheckable
assert not (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' in window._selected_names()
assert not window.selected_batch_button.isEnabled()
assert 'READY_CBB' not in window._selected_names()
window.verify_all()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['PENDING_CBB']
assert window.cbb_table.item(1, 0).checkState() == Qt.Unchecked
assert window.cbb_table.item(1, 0).flags() & Qt.ItemIsUserCheckable
assert not (window.cbb_table.item(1, 0).flags() & Qt.ItemIsUserCheckable)
assert window.cbb_table.item(1, 0).background().color().name().lower() == '#e8f5e9'
@@ -284,7 +271,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()
qtbot.waitUntil(lambda: lease.closed)
assert lease.closed
def test_advanced_options_are_copied_to_verify_request(qtbot, tmp_path):
@@ -353,12 +340,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.detailedText()
assert str(report.with_name('failures-20260929-test.log')) in window.summary.detailedText()
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()
-247
View File
@@ -1,247 +0,0 @@
"""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
@@ -1,291 +0,0 @@
"""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
@@ -1,133 +0,0 @@
"""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)