Files
cbb-refresh-verify-795/tests/test_native_backup.py
T

264 lines
13 KiB
Python

"""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()