feat: open native project history and backup interface

This commit is contained in:
阿白叔 committed 2026-11-04 22:12:24 +08:00
1 parent 00db1cf5f2
commit 4ebe098ef0
6 files changed
+560 -6

No files matched your search

@@ -0,0 +1,31 @@
# 原生版本历史、备份与回退入口
## 用户操作
在“ICDB 维护”页勾选一个非 READY CBB,点击“版本历史与备份…”。应用将所选工程的唯一 PRJ 传给已安装的 `iCDBProjectBackup.exe -p`,打开可见的原生窗口。当前 Layout 数据缺失但 PRJ 仍在时也可以进入。
版本列表、备份详情、操作日志和 Restore backup 由原生窗口提供。选择版本、手动保存/自动保存分支以及恢复确认均由用户操作;应用不代点 Restore、Repair、删除或清理菜单。用户已报告手工回退能够走通,本轮接入该原生入口,不把手工成功当作自动 Repair 验收通过。
原生窗口正常关闭后重新读取受影响 CBB 的权威状态。窗口关闭仅记为 `CLOSED`,始终记录 `restore_confirmed=false`,不自动执行校验,不伪造 PASS/READY。需要验证恢复后的工程时,单独使用“检验”页。
## 会话与独立操作
- 可见原生窗口由独立辅助进程启动和监督;Qt 线程不等待原生会话,清单搜索、筛选、横向页面和库切换保持可用。
- 使用 Windows Job 跟踪本次原生进程及后代,根进程退出但后代仍在时继续等待。Job 不设置 kill-on-close;关闭本应用不强制关闭原生窗口。
- 实际会话持有现有中心库协调锁,同库写入等待该会话关闭;其他库不因这个窗口禁用。没有新增历史 ICDB 失败标记作为普通校验前置条件。
- 状态或结果文件写入失败不结束原生监督。辅助进程退出后,只有返回身份一致且 `safe_to_continue=true` 才清除应用内会话和路径租约;缺失、损坏或释放未确认时保留同库冲突,可通过已有“检查占用…”取得新的释放证明。
- 切换到同一共享上的其他库时,旧会话结束会把临时盘符所有权交给当前租约,避免断开当前路径。关闭应用时为仍打开的原生窗口保留所需盘符。
## 本机验证
证据目录:`diagnostics/native-backup-ui-20261104/`(本地诊断目录,不包含原库发布副本)。
源码实际按钮验证使用自有隔离库 `C:/Temp/CbbTabsRelease20261104/library/mentor_lib.lmc` 的 `1GPHY_8212`,由测试夹具提供 PENDING 清单状态,确认原生 Output 加载同一 PRJ、报告工程未使用、完成备份目录加载,再向该原生空闲窗口发送正常关闭。未点击 Restore/Repair,也未操作原库。详见 `source-acceptance.json`。
冻结候选包读取真实权威清单时,`1GPHY_8212` 为 READY,其维护入口按规则禁用。随后选择同一隔离库中实际 PENDING 的 `IP101GR`,验证真实 Qt 按钮、原生备份列表加载、正常关闭和应用状态刷新;最终仍为“待校验”,应用正常退出。原生 Output 明确报告该隔离副本的数据库不一致,本轮只验证入口,不点击 Repair/Restore,也不将此报错当作自动修复已通过。记录在 `frozen-acceptance.json`。
相关功能回归 88 项通过;最终全量回归 **1260 passed**,188.94 秒,退出码 0,1 条既有 pywinauto STA 警告。冻结的 13 个关键 Python 模块及两个 VBS 与源码一致,冻结启动/退出冒烟、Unicode/UNC 协议和包内 x86 运行库加载通过。全量回归、冻结模块一致性和启动冒烟结果分别保存在 `pytest-final.log`、`frozen-result.json`;最终构建记录随包保存到 `BUILD.json`。一次按系统 GBK 模式运行的全量测试因既有测试未指定 UTF-8 读取原生日志而失败,保留 `pytest-locale-failure.log`,最终回归使用 `python -X utf8 -m pytest -q`。
## 验收边界
本轮覆盖“应用入口 → 原生备份列表加载 → 用户可操作窗口 → 正常关闭 → 状态刷新”。不自动回退数据,不以本轮打开/关闭试验代替恢复后的保存关闭与 READY 验收。现场失联故障的完整自动修复、Win10 干净系统和跨机共享库并发仍未验收;ICDB 自动修复研究按用户要求暂停。工单和 WIP PR 保持开放。
+4
View File
@@ -51,6 +51,7 @@ def main(argv: Sequence[str] | None = None) -> int:
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)
@@ -64,6 +65,9 @@ def main(argv: Sequence[str] | None = None) -> int:
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)
+155
View File
@@ -0,0 +1,155 @@
"""Open the official backup UI; version selection and writes stay native."""
from dataclasses import dataclass
import json
from pathlib import Path
import stat
import subprocess
import sys
import time
from uuid import uuid4
def native_backup_executable(mentor_bin=''):
from .mentor_paths import discover_sdd_home
home = discover_sdd_home(mentor_bin)
executable = home/'iCDB/win32/bin/iCDBProjectBackup.exe' if home else None
if executable is None or not executable.is_file():
raise ValueError('未找到 iCDB Project Backup,请检查 Mentor 安装位置。')
return executable
def native_backup_project(library, block):
from .verify_runner import INVALID_NAME_CHARS
library = Path(library).absolute()
if not block or block in ('.', '..') or any(c in block for c in INVALID_NAME_CHARS):
raise ValueError('CBB 名称非法。')
if not library.is_file():
raise ValueError('中心库文件不存在。')
work = library.parent/'ReusableBlocksLP'/block/'Work'
expected = library.parent.resolve()/'ReusableBlocksLP'/block/'Work'
if work.resolve() != expected:
raise ValueError('工程路径通过链接指向其他位置。')
projects = list(work.glob('*.prj'))
if len(projects) != 1 or not projects[0].is_file():
raise ValueError('无法唯一确定所选 CBB 的工程 PRJ。')
project = projects[0]
if (project.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT
or not project.resolve().is_relative_to(expected)):
raise ValueError('工程文件通过链接指向其他位置。')
return project
@dataclass
class NativeBackupSession:
process: object
job: Path
library: Path
block: str
path_lease: object = None
def launch_native_backup(request):
project = native_backup_project(request.lmc_file, request.block_name)
native_backup_executable(request.mentor_bin)
root = Path(request.evidence_dir).resolve()/('native-backup-'+uuid4().hex[:12])
library_root = Path(request.lmc_file).resolve().parent
if root.is_relative_to(library_root) or library_root.is_relative_to(root):
raise ValueError('运行记录目录需位于中心库之外。')
root.mkdir(parents=True)
job = root/'request.json'
job.write_text(json.dumps({'library': str(request.lmc_file), 'block': request.block_name,
'project': str(project), 'mentor_bin': request.mentor_bin}, ensure_ascii=False), 'utf-8')
command = ([sys.executable] if getattr(sys, 'frozen', False) else
[sys.executable, '-m', 'cbb_refresh_verify'])+['--native-backup-worker', str(job)]
process = subprocess.Popen(command, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
return NativeBackupSession(process, job, Path(request.lmc_file), request.block_name)
class _NativeBackupProcess:
"""Track this visible tool and its descendants without killing on close."""
def __init__(self, command, cwd):
import win32con, win32job, win32process
self.job = win32job.CreateJobObject(None, '')
startup = win32process.STARTUPINFO()
try:
self.handle, thread, self.pid, _ = win32process.CreateProcess(
command[0], subprocess.list2cmdline(command), None, None, False,
win32con.CREATE_SUSPENDED, None, str(cwd), startup)
except Exception:
self.job.Close()
raise
try:
win32job.AssignProcessToJobObject(self.job, self.handle)
win32process.ResumeThread(thread)
except Exception:
# No native code has run while suspended; there can be no DB write.
win32process.TerminateProcess(self.handle, 1)
self.handle.Close(); self.job.Close()
raise
finally:
thread.Close()
def poll(self):
import win32process
code = win32process.GetExitCodeProcess(self.handle)
return None if code == 259 else code
def session_pids(self):
import win32job
return win32job.QueryInformationJobObject(self.job, win32job.JobObjectBasicProcessIdList)
def close(self):
self.handle.Close(); self.job.Close()
def native_backup_worker_main(job, *, process_factory=None):
from .library_lock import LibraryLock
from .management import _write_json
job = Path(job)
result = {'status': 'FAILED', 'safe_to_continue': True, 'restore_confirmed': False}
native = None
def write_evidence(name, value):
try:
_write_json(job.with_name(name), value)
except Exception as error:
# Evidence storage must never end supervision of a live transaction.
result['evidence_error'] = str(error)
try:
record = json.loads(job.read_text('utf-8'))
library, block = Path(record['library']), record['block']
result.update(library=str(library), block=block)
project = native_backup_project(library, block)
if project != Path(record['project']):
raise ValueError('工程身份已变化,未打开原生工具。')
executable = native_backup_executable(record.get('mentor_bin', ''))
released = True
with LibraryLock(library, checkpoint=False, safe_to_release=lambda: released):
native = (process_factory or _NativeBackupProcess)([str(executable), '-p', str(project)], project.parent)
released = False
result.update(status='OPEN', native_pid=native.pid, project=str(project), safe_to_continue=False)
write_evidence('state.json', result)
waiting = False
while True:
try:
pids, exit_code = native.session_pids(), native.poll()
except Exception as error:
write_evidence('state.json', {**result,
'status': 'RELEASE_UNCONFIRMED', 'detail': str(error)})
time.sleep(.5)
continue # Keep the lease while the live session cannot be observed.
if not pids and exit_code is not None:
break
if exit_code is not None and not waiting:
waiting = True
write_evidence('state.json', {**result, 'status': 'WAITING_RELEASE'})
time.sleep(.25)
released = True
result.update(status='CLOSED', native_exit_code=exit_code, safe_to_continue=True)
return 0 if result['native_exit_code'] == 0 else 1
except Exception as error:
result.update(status='FAILED', detail=str(error), safe_to_continue=native is None)
return 1
finally:
write_evidence('result.json', result)
if native is not None:
native.close() # No kill-on-close: never interrupt a native transaction.
+8
View File
@@ -229,6 +229,14 @@ class LibraryPathLease:
"""Keep the Mentor drive available to a retained native session."""
self._retained_for_recovery = True
def transfer_ownership(self, other) -> None:
"""Keep a shared mapping alive for the currently loaded library."""
if (isinstance(other, LibraryPathLease) and not other._closed
and self.created and self.drive.upper() == other.drive.upper()
and self.remote_root and _same_remote(self.remote_root, other.remote_root)):
other.created, other._backend = True, self._backend
self.created = False
def close(self) -> None:
if self._closed:
return
+110 -6
View File
@@ -5,7 +5,7 @@ import time
from collections import Counter
from dataclasses import replace
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt, QTimer
from PySide6.QtGui import QColor, QIcon
from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout,
QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton,
@@ -49,7 +49,7 @@ def application_icon_path():
class MainWindow(QWidget):
def __init__(self, reader=None, verifier=None, logging_context=None, data_root=None,
authoritative_status=True, path_lease_factory=None, status_refresher=None,
management_adapter=None):
management_adapter=None, native_backup_launcher=None):
super().__init__()
self.setWindowTitle('CBB 刷新校验')
icon_path = application_icon_path()
@@ -72,6 +72,11 @@ class MainWindow(QWidget):
self._batch_requests = ()
self._batch_records = {}
self._reimport_summary_action = None
self.native_backup_launcher = native_backup_launcher
self._native_backup_session = None
self.native_backup_timer = QTimer(self)
self.native_backup_timer.setInterval(400)
self.native_backup_timer.timeout.connect(self._poll_native_backup)
if reader is not None:
self.reader = reader
elif authoritative_status and os.environ.get('CBB_STATUS_BRIDGE_MODE', 'authoritative').casefold() != 'legacy':
@@ -215,6 +220,10 @@ class MainWindow(QWidget):
maintenance = QWidget()
maintenance_layout = QVBoxLayout(maintenance)
maintenance_layout.setContentsMargins(0, 0, 0, 0)
self.native_backup_button = QPushButton('版本历史与备份…')
self.native_backup_button.setToolTip('勾选一个非 READY CBB,打开原生备份列表并选择回退版本。')
self.native_backup_button.clicked.connect(self.open_native_backup)
maintenance_layout.addWidget(self.native_backup_button)
maintenance_row = QHBoxLayout()
maintenance_row.addWidget(self.icdb_repair_button)
maintenance_row.addWidget(self.backup_restore_button)
@@ -278,6 +287,8 @@ class MainWindow(QWidget):
def _release_library_lease(self):
lease, self.library_lease = self.library_lease, None
if self._native_backup_session is not None and self._native_backup_session.path_lease is lease:
return # The visible native session still needs this mapping.
if lease is None:
return
try:
@@ -290,6 +301,10 @@ class MainWindow(QWidget):
# The refresh flow needs only the library and a CBB; LibSpec/DMS config
# are optional and only enable the extra contents check.
ready = not self.busy and self.loaded_path == self.lmc_edit.text() and self.cbb_table.rowCount() > 0
selected = self.selected_records()
self.native_backup_button.setEnabled(ready and self._native_backup_session is None
and len(selected) == 1 and selected[0].status != 'READY')
ready = ready and not self._native_backup_same_library()
self.batch_button.setEnabled(ready and bool(self._eligible_names()))
self.selected_batch_button.setEnabled(ready and bool(self._eligible_names(checked_only=True)))
self.icdb_repair_button.setEnabled(ready and bool(self._maintenance_names()))
@@ -347,6 +362,9 @@ class MainWindow(QWidget):
library = select_library_file(library)
def completed(result):
self._management_unsafe = False
session = self._native_backup_session
if session is not None and session.library == library and session.process.poll() is not None:
self._release_native_backup_session(session)
message = f'原生会话释放检查通过。请审查未完成任务后重新读取中心库。\n{result["evidence_path"]}'
self.status_label.setText(message); self.output.append(message)
self._start(lambda: release_retained_library(library, self.data_root/'release-checks'), completed)
@@ -354,6 +372,8 @@ class MainWindow(QWidget):
def _management_block_reason(self, operation):
if self.busy:
return '当前任务尚未结束,请等待后再执行库管理操作。'
if self._native_backup_same_library():
return '该库的版本与备份窗口仍在使用,关闭后可执行写入操作。'
if self._management_unsafe:
return '上次管理操作的会话尚未安全释放,请先查看异常证据并执行释放检查。'
capability = self.management_capabilities[operation]
@@ -655,7 +675,7 @@ class MainWindow(QWidget):
def _confirm_verify(self, names):
from .backup_notice import MANUAL_BACKUP_NOTICE
if self.busy or not self.loaded_path or not names:
if self.busy or not self.loaded_path or self._native_backup_same_library() or not names:
return
if QMessageBox.question(self, '确认批量校验',
f'{MANUAL_BACKUP_NOTICE}\n\n目标库:{self.loaded_path}\n'
@@ -677,8 +697,84 @@ class MainWindow(QWidget):
if answer == QMessageBox.Yes:
self._run(names, maintenance=True)
def _native_backup_same_library(self):
session = self._native_backup_session
return session is not None and Path(self.mentor_lmc_path or self.lmc_edit.text()) == session.library
def open_native_backup(self):
if self.busy or not self.loaded_path or self._native_backup_session is not None:
return
selected = self.selected_records()
if len(selected) != 1 or selected[0].status == 'READY':
self.status_label.setText('请勾选一个非 READY CBB。')
return
from cbb_refresh_verify.native_backup import launch_native_backup
request = self._request(selected[0].name)
launcher = self.native_backup_launcher or launch_native_backup
self._global_icdb_run = False
self._reimport_offers = ()
self.status_label.setText(f'正在打开 {request.block_name} 的版本与备份…')
def opened(session):
session.path_lease = self.library_lease
self._native_backup_session = session
self.native_backup_timer.start()
self.status_label.setText(f'正在打开 {session.block} 的原生备份窗口,请在其中选择版本。')
self.output.append(f'{session.block} · 原生版本与备份\n{session.job}')
self.busy = True; self._update()
self.worker = ServiceWorker(lambda: launcher(request))
self.worker.signals.succeeded.connect(opened)
self.worker.signals.failed.connect(lambda error: self.status_label.setText(f'无法打开版本与备份:{error}'))
self.worker.signals.finished.connect(self._finished)
self.pool.start(self.worker)
def _release_native_backup_session(self, session):
self._native_backup_session = None
if session.path_lease is not None and session.path_lease is not self.library_lease:
transfer = getattr(session.path_lease, 'transfer_ownership', None)
if transfer is not None:
transfer(self.library_lease)
session.path_lease.close()
def _poll_native_backup(self):
session = self._native_backup_session
if session is None or self.busy or session.process.poll() is None:
return
self.native_backup_timer.stop()
same_library = Path(self.mentor_lmc_path or self.lmc_edit.text()) == session.library
def read_result():
import json
result = json.loads(session.job.with_name('result.json').read_text('utf-8'))
if Path(result['library']) != session.library or result['block'] != session.block:
raise ValueError('原生会话返回的工程身份不一致。')
refresh = (self._read_affected_records((session.block,))
if result.get('safe_to_continue') is True and same_library else None)
return result, refresh
def completed(payload):
result, refresh = payload
if result.get('safe_to_continue') is not True:
unconfirmed(result.get('detail', '未取得会话释放结果。'))
return
self._release_native_backup_session(session)
if refresh is not None:
self._apply_refreshed_records(refresh)
message = ('原生备份窗口已关闭。需要时可单独运行校验。' if result.get('status') == 'CLOSED'
else '原生备份操作未结束:' + result.get('detail', '请检查原生窗口。'))
self.status_label.setText(message)
self.output.append(f'{session.block} · {message}\n{session.job.with_name("result.json")}')
if same_library and session.block in self._row_by_name:
self.cbb_table.item(self._row_by_name[session.block], 3).setText(message)
def unconfirmed(error):
self.status_label.setText('原生窗口退出尚未确认,请关闭窗口后检查释放。')
self.output.append(f'{session.block} · 退出尚未确认:{error}\n{session.job}')
self.busy = True; self._update()
self.worker = ServiceWorker(read_result)
self.worker.signals.succeeded.connect(completed)
self.worker.signals.failed.connect(unconfirmed)
self.worker.signals.finished.connect(self._finished)
self.pool.start(self.worker)
def restore_backup(self):
if self.busy or not self.loaded_path:
if self.busy or not self.loaded_path or self._native_backup_same_library():
return
from .backup_recovery_dialog import BackupRecoveryDialog
names = self._eligible_names(checked_only=bool(self.selected_records()))
@@ -697,7 +793,7 @@ class MainWindow(QWidget):
def _backup_request(self, name):
# A still-open dialog must recheck a target after an earlier recovery
# or an authoritative refresh changed its eligibility.
if self.busy or name not in self._eligible_names(checked_only=bool(self.selected_records())):
if self.busy or self._native_backup_same_library() or name not in self._eligible_names(checked_only=bool(self.selected_records())):
raise ValueError('目标需为当前可见、可用的非 READY CBB;请重新选择。')
return self._request(name)
@@ -737,6 +833,9 @@ class MainWindow(QWidget):
def _run(self, names, *, maintenance=False):
if self.busy or not self.loaded_path: return
if self._native_backup_same_library():
self.status_label.setText('请先关闭该库的版本与备份窗口。')
return
eligible = set(self._maintenance_names() if maintenance else self._eligible_names())
names = [name for name in names if name in eligible]
if not names:
@@ -853,7 +952,7 @@ class MainWindow(QWidget):
(UNKNOWN on read failure). It runs before the worker's finished signal.
Search, filter, original logical_type and action-result cells are retained.
"""
if self.busy or not self.loaded_path:
if self.busy or not self.loaded_path or self._native_backup_same_library():
return False
targets = tuple(dict.fromkeys(name for name in names if name in self._records_by_name))
if not targets:
@@ -1034,5 +1133,10 @@ class MainWindow(QWidget):
if self.busy:
self.request_stop(); event.ignore()
else:
if self._native_backup_session is not None:
self.native_backup_timer.stop()
lease = self._native_backup_session.path_lease
if lease is not None:
lease.retain_for_recovery()
self._release_library_lease()
event.accept()
+252
View File
@@ -0,0 +1,252 @@
"""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()
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()
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()
assert 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()