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

245 lines
12 KiB
Python

import json
from pathlib import Path
import pytest
def target_fixture(tmp_path):
from test_verify_runner import fixture, request
from cbb_refresh_verify.native_repair import select_repair_target
work = fixture(tmp_path)
database = work/'database'
database.mkdir()
(database/'icdb.dat').write_bytes(b'original damaged database')
diagnosis = {'error_code': 'ICDB_REPAIR_REQUIRED', 'machine': 'OLD-PC',
'database_path': str(database), 'session': '2026-10-24 08.22.29-10308', 'scope': 'project'}
return request(tmp_path), diagnosis, select_repair_target(request(tmp_path), diagnosis)
def test_repair_target_matches_actual_database_not_guessed_cbb_name(tmp_path):
request, record, target = target_fixture(tmp_path)
assert target.project.name == 'CBB1.prj'
assert target.database == target.project.parent/'database'
@pytest.mark.parametrize('change', ['foreign', 'shared', 'missing_session'])
def test_repair_target_rejects_unresolved_or_shared_database(tmp_path, change):
from cbb_refresh_verify.native_repair import select_repair_target
request, record, target = target_fixture(tmp_path)
if change == 'foreign': record['database_path'] = str(tmp_path/'foreign/database')
if change == 'shared':
record.update(scope='central_library', database_path=str(tmp_path/'SymbolLibs/__ReusableBlocksSymb'))
if change == 'missing_session': record['session'] = ''
with pytest.raises(ValueError):
select_repair_target(request, record)
def test_repair_backup_contains_database_locks_backups_and_original_files(tmp_path):
from cbb_refresh_verify.native_repair import backup_project
request, record, target = target_fixture(tmp_path)
for relative in ('database/cdbsvr/sAddress.adr', 'ProjectBackup/backups/old.zip',
'PCB/copy.lock', 'Log Files/ProjectBackupLog.txt'):
path = target.project.parent/relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'original '+relative.encode())
destination = tmp_path/'repair-backup'
manifest = backup_project(target, destination)
assert manifest['complete'] is True
assert (destination/'database/icdb.dat').read_bytes() == b'original damaged database'
assert (destination/'database/cdbsvr/sAddress.adr').read_bytes().startswith(b'original')
assert (destination/'ProjectBackup/backups/old.zip').is_file()
assert (destination/'PCB/copy.lock').is_file()
def test_repair_backup_refuses_database_open_by_another_client(tmp_path):
import win32file, win32con
from cbb_refresh_verify.native_repair import backup_project
request, record, target = target_fixture(tmp_path)
handle = win32file.CreateFile(str(target.database/'icdb.dat'), win32con.GENERIC_READ,
win32con.FILE_SHARE_READ, None, win32con.OPEN_EXISTING, 0, None)
try:
with pytest.raises(OSError):
backup_project(target, tmp_path/'backup')
finally:
handle.Close()
assert not (tmp_path/'backup/backup-manifest.json').exists()
def test_repair_backup_rejects_reparse_directory(tmp_path):
import _winapi
from cbb_refresh_verify.native_repair import backup_project
request, record, target = target_fixture(tmp_path)
outside = tmp_path/'outside'
outside.mkdir()
_winapi.CreateJunction(str(outside), str(target.project.parent/'linked'))
with pytest.raises(ValueError):
backup_project(target, tmp_path/'backup')
def test_native_confirmation_requires_exact_target_and_known_repair_prompt():
from cbb_refresh_verify.native_repair_ui import confirmation_allowed
assert confirmation_allowed('iCDB Project Backup - C:\\exact.prj', r'C:\exact.prj',
'The project content will be validated and repaired if necessary.\n'
'A project backup will be created before any action take place.\n'
'You will be able to revert all changes using that backup.')
assert not confirmation_allowed('iCDB Project Backup - C:\\OTHER.prj', r'C:\exact.prj',
'The project content will be validated and repaired if necessary.')
assert not confirmation_allowed('iCDB Project Backup - C:\\exact.prj', r'C:\exact.prj',
'Confirm no other clients are connected. Continue anyway?')
def test_native_diagnostics_finish_alone_does_not_prove_repair_success():
from cbb_refresh_verify.native_repair_ui import repair_completed
assert not repair_completed('Diagnostic: FINISH', 'IC: Closing project', native_backup=False)
assert not repair_completed('ERROR: invalid database\nDiagnostic: FINISH',
'iCDBProjectBackupRepair\nIC: Closing project', native_backup=True)
assert repair_completed('Diagnostic: START\nDiagnostic: FINISH',
'iCDBProjectBackupRepair\nIC: Closing project', native_backup=True)
def test_automatic_repair_retries_only_once_and_preserves_original_failure(tmp_path, monkeypatch):
from dataclasses import replace
from cbb_refresh_verify import verify_runner as runner
from cbb_refresh_verify import native_repair
request, record, target = target_fixture(tmp_path)
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(record))
original = runner.VerifyResult('FAIL', stderr='native lost session',
safe_to_continue=False, error_category='ICDB_REPAIR_REQUIRED', evidence_path=evidence)
calls = []
def verify(req, **kwargs):
calls.append(req)
return original
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {'status':'REPAIRED'})
outcome = runner.run_verify(request)
assert len(calls) == 2
assert outcome.status == 'FAIL'
assert outcome.stderr == 'native lost session'
assert outcome.recovery_attempts[0]['original_error'] == 'native lost session'
def test_automatic_repair_does_not_retry_busy_or_unsupported_target(tmp_path, monkeypatch):
from cbb_refresh_verify import verify_runner as runner
from cbb_refresh_verify import native_repair
request, record, target = target_fixture(tmp_path)
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(record))
calls = []
def verify(req, **kwargs):
calls.append(req)
return runner.VerifyResult('FAIL', stderr='native lost session',
error_category='ICDB_REPAIR_REQUIRED', safe_to_continue=False, evidence_path=evidence)
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw: {'status':'BLOCKED'})
outcome = runner.run_verify(request)
assert len(calls) == 1
assert outcome.safe_to_continue is False
assert outcome.recovery_attempts[0]['status'] == 'BLOCKED'
def test_timeout_never_enters_automatic_repair(tmp_path, monkeypatch):
from cbb_refresh_verify import verify_runner as runner, native_repair
request, record, target = target_fixture(tmp_path)
evidence = tmp_path/'first/result.json'
evidence.parent.mkdir()
(evidence.parent/'diagnostics').mkdir()
(evidence.parent/'diagnostics/icdb-recovery.json').write_text(json.dumps(record))
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **kw:
runner.VerifyResult('TIMEOUT', error_category='ICDB_REPAIR_REQUIRED',
safe_to_continue=False, evidence_path=evidence))
monkeypatch.setattr(native_repair, 'attempt_recovery', lambda *a, **kw:
pytest.fail('A timed-out native owner must not be repaired'))
assert runner.run_verify(request).status == 'TIMEOUT'
def test_retained_importer_blocks_repair_even_without_an_open_database_handle(tmp_path, monkeypatch):
from cbb_refresh_verify import native_repair
request, record, target = target_fixture(tmp_path)
evidence = tmp_path/'original'
evidence.mkdir()
(evidence/'content-check-process.json').write_text(json.dumps({'status':'RETAINED','pid':123}))
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **kw:
pytest.fail('Do not repair between importer transactions'))
outcome = native_repair.attempt_recovery(request, record, evidence)
assert outcome['status'] == 'BLOCKED'
assert 'IMPORTER_RELEASE_UNCONFIRMED' in outcome['detail']
def test_repair_cancellation_during_backup_prevents_native_launch(tmp_path, monkeypatch):
from cbb_refresh_verify import native_repair_ui as ui, native_repair, mentor_adapter
request, record, target = target_fixture(tmp_path)
root = tmp_path/'worker'
root.mkdir()
cancel = root/'cancel.signal'
job = root/'request.json'
job.write_text(json.dumps({'project':str(target.project),'database':str(target.database),
'root':str(root),'cancel_signal':str(cancel),'timeout':1,
'supervisor_pid':123,'desktop':'CbbRepair_test'}))
calls = []
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.start_supervisor_watchdog',
lambda *a, **kw: calls.append('watchdog'))
monkeypatch.setattr(ui, '_current_desktop_name', lambda: 'CbbRepair_test', raising=False)
monkeypatch.setattr(ui, '_repair_command', lambda *_: 32924)
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda *_: [])
def backup(*a):
assert calls == ['watchdog'], 'Watch supervisor before the potentially long backup'
cancel.touch()
calls.append('backup')
monkeypatch.setattr(native_repair, 'backup_project', backup)
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('Repair must not start'))
assert ui.repair_worker_main(job) == 1
outcome = json.loads((root/'repair-result.json').read_text('utf-8'))
assert 'REPAIR_CANCELLED_AFTER_BACKUP' in outcome['detail']
def test_repair_worker_refuses_the_input_desktop_before_backup(tmp_path, monkeypatch):
from cbb_refresh_verify import native_repair_ui as ui, native_repair
request, record, target = target_fixture(tmp_path)
root = tmp_path/'worker'
root.mkdir()
job = root/'request.json'
job.write_text(json.dumps({'project':str(target.project),'database':str(target.database),
'root':str(root),'cancel_signal':str(root/'cancel.signal'),'timeout':1,
'supervisor_pid':123,'desktop':'CbbRepair_test'}))
monkeypatch.setattr(ui, '_current_desktop_name', lambda: 'Default', raising=False)
monkeypatch.setattr(native_repair, 'backup_project', lambda *a: pytest.fail('Input desktop repair forbidden'))
assert ui.repair_worker_main(job) == 1
assert 'REPAIR_PRIVATE_DESKTOP_REQUIRED' in json.loads((root/'repair-result.json').read_text('utf-8'))['detail']
def test_repair_worker_job_binds_supervisor_and_private_desktop(tmp_path, monkeypatch):
from cbb_refresh_verify.native_repair import run_native_repair
request, record, target = target_fixture(tmp_path)
class Worker:
returncode = 0
def __init__(self, command, desktop):
job = json.loads(Path(command[-1]).read_text('utf-8'))
assert job['supervisor_pid'] > 0
assert job['desktop'] == desktop
assert desktop.startswith('CbbRepair_')
(Path(job['root'])/'repair-result.json').write_text('{"status":"BLOCKED"}')
def poll(self): return 0
def bind_cancellation(self, path): pass
def close(self): pass
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
assert run_native_repair(target, tmp_path/'native')['status'] == 'BLOCKED'
def test_backup_detects_a_file_added_during_the_copy(tmp_path, monkeypatch):
from cbb_refresh_verify import native_repair
request, record, target = target_fixture(tmp_path)
original = native_repair.shutil.copy2
def changed(source, destination):
result = original(source, destination)
(target.project.parent/'new-file.txt').write_bytes(b'concurrent writer')
return result
monkeypatch.setattr(native_repair.shutil, 'copy2', changed)
with pytest.raises(OSError, match='REPAIR_BACKUP_CHANGED'):
native_repair.backup_project(target, tmp_path/'backup')