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

192 lines
10 KiB
Python

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'