Files
cbb-refresh-verify-795/tests/test_pr16_review_cleanup.py

113 lines
4.7 KiB
Python

"""PR 16: handoff must preserve control flow, resource cleanup and cancellation."""
import json
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
def test_verify_handoff_skips_duplicate_native_cleanup_and_keeps_result(tmp_path, monkeypatch):
from cbb_refresh_verify import operation_queue, verify_runner
from test_cancelled_session_handoff import worker_fixture
handoff = operation_queue.hold_native_handoff
state, _, run = worker_fixture(tmp_path, monkeypatch)
monkeypatch.setattr(operation_queue, 'hold_native_handoff', handoff)
late_cleanup = []
monkeypatch.setattr(verify_runner, '_cleanup_session_processes',
lambda *a, **kw: late_cleanup.append(True) or {'safe_to_continue': False})
completed = Event()
original = verify_runner._run_verify_task
def execute(*args, **kwargs):
try:
return original(*args, **kwargs)
finally:
completed.set()
monkeypatch.setattr(verify_runner, '_run_verify_task', execute)
result = run(True)
assert completed.wait(3)
assert result.status == 'CANCELLED' and not result.safe_to_continue
assert state['observers'] and not state['closed']
assert not late_cleanup, 'The registered observer owns native cleanup after handoff'
saved = json.loads(state['path'].with_name('result.json').read_text(encoding='utf-8'))
assert saved['status'] == 'CANCELLED' and saved['safe_to_continue'] is False
@pytest.mark.parametrize('registration_error', [False, True])
def test_repair_handoff_always_closes_local_worker_resources(tmp_path, monkeypatch, registration_error):
from cbb_refresh_verify import desktop_worker, native_repair, session_record
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff
events = []
class Worker:
pid = 700
session_record_path = tmp_path/'session.json'
def __init__(self, *args): pass
def bind_cancellation(self, path): pass
def bind_session(self, job): pass
def poll(self): return None
def request_stop(self): events.append('stop')
def close(self): events.append('close')
monkeypatch.setattr(desktop_worker, 'DesktopWorker', Worker)
ticks = iter((0, 100))
monkeypatch.setattr(native_repair, 'time', SimpleNamespace(monotonic=lambda: next(ticks)))
def observe(*args, **kwargs):
events.append('observe')
if registration_error:
raise OSError('observer registration failed')
monkeypatch.setattr(session_record, 'handoff_session', observe)
context = BatchTaskContext(str(tmp_path/'library.lmc'))
completed = Event()
def execute():
try:
return native_repair._supervise_repair([], 'CbbRepair_test', tmp_path/'cancel',
tmp_path, 1, None, None, {'start_gate': str(tmp_path/'start')})
finally:
completed.set()
with pytest.raises(OSError if registration_error else TaskHandoff):
context.run(execute)
assert completed.wait(3)
assert events == ['stop', 'observe', 'close']
def test_icdb_fallback_stop_cancels_the_active_task_context(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.verify_runner import VerifyResult
from test_ui_filters import load_window
entered, release = Event(), Event()
def verify(request):
entered.set()
assert release.wait(3)
return VerifyResult('CANCELLED')
window = load_window(qtbot, tmp_path, monkeypatch, verifier=verify)
window._start_icdb_check(['Beta'])
try:
qtbot.waitUntil(entered.is_set)
window.stop.set()
assert window.icdb_task.stop.is_set(), 'Fallback Stop must cancel the running ICDB task'
finally:
window.icdb_task.cancel()
release.set()
qtbot.waitUntil(lambda: not window.icdb_task.active)
@pytest.mark.parametrize('mode', ['versions', 'repair'])
@pytest.mark.parametrize('config', [
'KEY iCDBDir "C:\\outside\\database"\n',
'KEY iCDBDir "database"\nKEY iCDBDir "other"\n',
])
def test_ambiguous_or_absolute_database_stops_before_native_launch(tmp_path, monkeypatch, mode, config):
from cbb_refresh_verify import native_backup
from test_native_backup import project_fixture
request, project = project_fixture(tmp_path)
project.write_text(config, encoding='utf-8')
monkeypatch.setattr(native_backup, 'native_backup_executable',
lambda *_: pytest.fail('Invalid database binding reached native preparation'))
with pytest.raises(ValueError, match='NATIVE_TARGET_UNCONFIRMED'):
native_backup.launch_native_backup(request, mode=mode)
assert not request.evidence_dir.exists()