feat: add guarded native CBB management and recovery coordination
This commit is contained in:
1 parent
3415e010ff
commit
797a79c30e
17 files changed
+2423
-15
No files matched your search
@@ -0,0 +1,209 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import pytest
|
||||
import win32con
|
||||
import win32file
|
||||
|
||||
|
||||
def test_library_lock_excludes_other_thread_and_uploader_but_reenters(tmp_path):
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
|
||||
library = tmp_path/'test.lmc'
|
||||
library.write_bytes(b'fixture')
|
||||
with LibraryLock(library) as lock:
|
||||
assert lock.path.name == '.test.cbb-upload.lock'
|
||||
with LibraryLock(library):
|
||||
assert lock.snapshot_bytes()
|
||||
with pytest.raises(Exception):
|
||||
win32file.CreateFile(str(lock.path), win32con.GENERIC_READ | win32con.GENERIC_WRITE,
|
||||
0, None, win32con.OPEN_ALWAYS, 0, None)
|
||||
def competing():
|
||||
with pytest.raises(LibraryBusy):
|
||||
with LibraryLock(library):
|
||||
pass
|
||||
with ThreadPoolExecutor(1) as pool:
|
||||
pool.submit(competing).result()
|
||||
assert lock.path.exists()
|
||||
with LibraryLock(library):
|
||||
pass
|
||||
|
||||
|
||||
def test_complete_copy_reads_owned_lock_without_reopening(tmp_path):
|
||||
from cbb_refresh_verify.library_lock import LibraryLock
|
||||
from cbb_refresh_verify.scoped_manifest import copy_verified
|
||||
source = tmp_path/'library'
|
||||
source.mkdir()
|
||||
library = source/'test.lmc'
|
||||
library.write_bytes(b'fixture')
|
||||
with LibraryLock(library) as lock:
|
||||
expected = lock.snapshot_bytes()
|
||||
copy_verified(source, tmp_path/'snapshot')
|
||||
assert (tmp_path/'snapshot'/lock.path.name).read_bytes() == expected
|
||||
|
||||
|
||||
def test_external_lock_never_gets_snapshot_exception(tmp_path):
|
||||
from cbb_refresh_verify.scoped_manifest import copy_verified
|
||||
source = tmp_path/'library'
|
||||
source.mkdir()
|
||||
path = source/'.test.cbb-upload.lock'
|
||||
path.write_bytes(b'external')
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ | win32con.GENERIC_WRITE,
|
||||
0, None, win32con.OPEN_EXISTING, 0, None)
|
||||
try:
|
||||
with pytest.raises(OSError):
|
||||
copy_verified(source, tmp_path/'snapshot')
|
||||
finally:
|
||||
handle.Close()
|
||||
|
||||
|
||||
def test_verification_refuses_uploader_exclusive_lock_before_native_work(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.verify_runner as runner
|
||||
library = tmp_path/'lib.lmc'
|
||||
library.touch()
|
||||
lock = tmp_path/'.lib.cbb-upload.lock'
|
||||
handle = win32file.CreateFile(str(lock), win32con.GENERIC_READ | win32con.GENERIC_WRITE,
|
||||
0, None, win32con.OPEN_ALWAYS, 0, None)
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('native work bypassed lock'))
|
||||
try:
|
||||
result = runner.run_verify(runner.VerifyRequest(library, 'Block', tmp_path/'out'))
|
||||
assert result.status == 'BLOCKED' and not result.safe_to_continue
|
||||
finally:
|
||||
handle.Close()
|
||||
|
||||
|
||||
def test_unsafe_verify_retains_lease_and_persistent_blocker(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.verify_runner as runner
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k:
|
||||
runner.VerifyResult('FAIL', safe_to_continue=False))
|
||||
result = runner.run_verify(runner.VerifyRequest(library, 'Block', tmp_path/'out'))
|
||||
assert not result.safe_to_continue
|
||||
assert locks.blocker_path(library).is_file()
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks.LibraryLock(library): pass
|
||||
# Simulate OS handle loss on process exit; persistent marker still blocks.
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(str((tmp_path/'.lib.cbb-upload.lock').resolve()).casefold(), None)
|
||||
if owner: owner['handle'].Close()
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks.LibraryLock(library): pass
|
||||
|
||||
|
||||
def test_explicit_release_requires_fresh_proof_and_never_deletes_sidecar(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
with locks.LibraryLock(library, safe_to_release=lambda: False) as lease:
|
||||
pass
|
||||
try:
|
||||
def denied(*a):
|
||||
raise ValueError('native owner remains')
|
||||
monkeypatch.setattr(locks, '_prove_library_released', denied)
|
||||
with pytest.raises(ValueError, match='native owner'):
|
||||
locks.release_retained_library(library, tmp_path/'release')
|
||||
assert locks.blocker_path(library).is_file()
|
||||
from contextlib import contextmanager
|
||||
@contextmanager
|
||||
def proof(*a):
|
||||
yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
|
||||
monkeypatch.setattr(locks, '_prove_library_released', proof)
|
||||
result = locks.release_retained_library(library, tmp_path/'release')
|
||||
assert result['status'] == 'RELEASE_CONFIRMED'
|
||||
assert lease.path.is_file() and not locks.blocker_path(library).exists()
|
||||
with locks.LibraryLock(library): pass
|
||||
finally:
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(str(lease.path.resolve()).casefold(), None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
def test_release_proof_checks_addresses_and_exclusive_databases(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
import win32com.client
|
||||
from types import SimpleNamespace
|
||||
monkeypatch.setattr(win32com.client, 'GetObject', lambda *_: SimpleNamespace(ExecQuery=lambda *_: []))
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
address = tmp_path/'database/cdbsvr/sAddress.adr'; address.parent.mkdir(parents=True)
|
||||
address.touch()
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks._prove_library_released(library): pass
|
||||
address.unlink() # Test-created empty marker, never a native address file.
|
||||
handle = win32file.CreateFile(str(library), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, 0, None)
|
||||
try:
|
||||
with pytest.raises(Exception):
|
||||
with locks._prove_library_released(library): pass
|
||||
finally:
|
||||
handle.Close()
|
||||
with locks._prove_library_released(library) as proof:
|
||||
assert proof['exclusive_files'] == [str(library)]
|
||||
|
||||
|
||||
def test_public_verify_initializes_com_in_its_operation_thread(tmp_path, monkeypatch):
|
||||
import ctypes
|
||||
import cbb_refresh_verify.verify_runner as runner
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
def serialized(*a, **k):
|
||||
apartment, qualifier = ctypes.c_int(), ctypes.c_int()
|
||||
ole32 = ctypes.WinDLL('ole32')
|
||||
ole32.CoGetApartmentType.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)]
|
||||
initialized = ole32.CoGetApartmentType(ctypes.byref(apartment), ctypes.byref(qualifier)) == 0
|
||||
return runner.VerifyResult('PASS' if initialized else 'FAIL', stderr='COM apartment check')
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', serialized)
|
||||
with ThreadPoolExecutor(1) as pool:
|
||||
result = pool.submit(runner.run_verify, runner.VerifyRequest(library, 'Block', tmp_path/'out')).result()
|
||||
assert result.status == 'PASS'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mode,expected', [(0, 1), (2, 0)])
|
||||
def test_public_verify_preserves_existing_apartment(tmp_path, monkeypatch, mode, expected):
|
||||
import ctypes, pythoncom
|
||||
import cbb_refresh_verify.verify_runner as runner
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: runner.VerifyResult('PASS'))
|
||||
def existing_mta():
|
||||
pythoncom.CoInitializeEx(mode)
|
||||
try:
|
||||
runner.run_verify(runner.VerifyRequest(library, 'Block', tmp_path/'out'))
|
||||
apartment, qualifier = ctypes.c_int(), ctypes.c_int()
|
||||
ole32 = ctypes.WinDLL('ole32')
|
||||
ole32.CoGetApartmentType.argtypes = [ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int)]
|
||||
result = ole32.CoGetApartmentType(ctypes.byref(apartment), ctypes.byref(qualifier))
|
||||
return result, apartment.value
|
||||
finally:
|
||||
pythoncom.CoUninitialize()
|
||||
with ThreadPoolExecutor(1) as pool:
|
||||
assert pool.submit(existing_mta).result() == (0, expected)
|
||||
|
||||
|
||||
def test_nested_snapshot_retains_runtime_checkpoint_bytes_without_semantic_conflicts(tmp_path):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
from cbb_refresh_verify.scoped_manifest import copy_verified, build_manifest, ManifestScope
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.write_bytes(b'library')
|
||||
scope = ManifestScope.library('Block', library.name)
|
||||
with locks.LibraryLock(library) as lease:
|
||||
before = copy_verified(library.parent, tmp_path/'snapshot', scope=scope)
|
||||
marker = locks.blocker_path(library)
|
||||
assert (tmp_path/'snapshot'/marker.name).read_bytes() == marker.read_bytes()
|
||||
with locks.LibraryLock(library):
|
||||
owner = locks._owners[lease.key]
|
||||
locks._persist_blocker(library, lease_id=owner['lease_id'])
|
||||
assert build_manifest(library.parent, scope=scope) == before
|
||||
assert not marker.exists() and lease.path.exists()
|
||||
|
||||
|
||||
def test_arbitrary_guard_filename_is_preserved_and_primary(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
from cbb_refresh_verify.scoped_manifest import build_manifest, ManifestScope
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
marker = locks.blocker_path(library); marker.write_bytes(b'{not a guard record')
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks.LibraryLock(library): pass
|
||||
manifest = build_manifest(library.parent, scope=ManifestScope.library('Block', library.name))
|
||||
assert marker.name in manifest['files']
|
||||
from contextlib import contextmanager
|
||||
@contextmanager
|
||||
def proof(*a): yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
|
||||
monkeypatch.setattr(locks, '_prove_library_released', proof)
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
locks.release_retained_library(library, tmp_path/'release')
|
||||
assert marker.read_bytes() == b'{not a guard record'
|
||||
@@ -0,0 +1,254 @@
|
||||
"""Operation safety tests use a file-only native boundary; never launch Mentor."""
|
||||
from dataclasses import replace
|
||||
import json
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def project(root, name='Source', marker=b'original'):
|
||||
root.mkdir(parents=True)
|
||||
(root/'database').mkdir()
|
||||
(root/'database/icdb.dat').write_bytes(marker)
|
||||
(root/'PCB/Layout').mkdir(parents=True)
|
||||
(root/'PCB/Layout/LayoutDB.lyt').write_bytes(marker)
|
||||
(root/'PCB/pcb.prj').write_text('KEY iCDBDir "../database"\n', encoding='utf-8')
|
||||
(root/'PCB/main.pcb').write_text(f'KEY ProjectFile "../{name}.prj"\n', encoding='utf-8')
|
||||
path = root/f'{name}.prj'
|
||||
path.write_text('KEY RootBlock "Top"\nKEY PCBDesignPath "PCB/main.pcb"\n'
|
||||
'KEY iCDBDir "database"\n', encoding='utf-8')
|
||||
return path
|
||||
|
||||
|
||||
class FileAdapter:
|
||||
def __init__(self):
|
||||
self.records = []
|
||||
self.calls = []
|
||||
self.fail_add = False
|
||||
self.lie = False
|
||||
self.released = True
|
||||
|
||||
def capabilities(self):
|
||||
from cbb_refresh_verify.management import Capability
|
||||
return {op: Capability(True, 'test boundary') for op in ('add', 'update', 'remove')}
|
||||
|
||||
def catalog(self, library, evidence):
|
||||
from cbb_refresh_verify.management import Catalog
|
||||
return Catalog(library, 1, tuple(self.records), safe_to_continue=self.released)
|
||||
|
||||
def remove(self, request, evidence):
|
||||
from cbb_refresh_verify.management import NativeOutcome
|
||||
self.calls.append('remove')
|
||||
if not self.lie:
|
||||
self.records = [r for r in self.records if r.name != request.name]
|
||||
return NativeOutcome(True, self.released, 'native removal accepted')
|
||||
|
||||
def add(self, request, evidence):
|
||||
from cbb_refresh_verify.management import NativeOutcome, CatalogEntry, engineering_identity
|
||||
self.calls.append(('add', request.source))
|
||||
if self.fail_add:
|
||||
return NativeOutcome(False, self.released, 'native add failed')
|
||||
if not self.lie:
|
||||
self.records.append(CatalogEntry(request.name, request.partition,
|
||||
engineering_identity(request.source)))
|
||||
return NativeOutcome(True, self.released, 'native add accepted')
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup(tmp_path):
|
||||
from cbb_refresh_verify.management import ManagementRequest, CatalogEntry
|
||||
library = tmp_path/'library/mentor.lmc'
|
||||
library.parent.mkdir()
|
||||
library.write_bytes(b'library')
|
||||
old = project(library.parent/'ReusableBlocksLP/Block/Work', 'Block')
|
||||
source = project(tmp_path/'source')
|
||||
adapter = FileAdapter()
|
||||
adapter.records = [CatalogEntry('Block', 'Logical-Physical')]
|
||||
request = ManagementRequest('remove', library, 'Block', evidence_dir=tmp_path/'evidence')
|
||||
yield request, adapter, source
|
||||
# FileAdapter never launches native owners. Release only this test's
|
||||
# intentionally retained lease so pytest can remove its temporary tree.
|
||||
from cbb_refresh_verify.library_lock import _guard, _owners
|
||||
key = str(library.with_name('.mentor.cbb-upload.lock').resolve()).casefold()
|
||||
with _guard:
|
||||
owner = _owners.pop(key, None)
|
||||
if owner:
|
||||
owner['handle'].Close()
|
||||
|
||||
|
||||
def execute(request, adapter, **kwargs):
|
||||
from cbb_refresh_verify.management import run_management
|
||||
return run_management(request, adapter=adapter, idle_check=lambda *_: None, **kwargs)
|
||||
|
||||
|
||||
def test_remove_backup_and_strict_absence(setup):
|
||||
request, adapter, _ = setup
|
||||
result = execute(request, adapter)
|
||||
assert result.status == 'REMOVED' and result.safe_to_continue
|
||||
assert (result.evidence_path.parent/'library-before/mentor.lmc').read_bytes() == b'library'
|
||||
assert (result.evidence_path.parent/'library-before/ReusableBlocksLP/Block/Work/Block.prj').is_file()
|
||||
record = json.loads(result.evidence_path.read_text(encoding='utf-8'))
|
||||
assert record['operation'] == 'remove' and record['partition'] == 'Logical-Physical'
|
||||
assert record['stage'] == 'complete'
|
||||
|
||||
|
||||
def test_add_conflict_cannot_overwrite(setup):
|
||||
request, adapter, source = setup
|
||||
result = execute(replace(request, operation='add', source=source), adapter)
|
||||
assert result.status == 'UPLOAD_FAILED' and adapter.calls == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('verify_status,flag,expected', [('PASS', 'GREEN', 'UPLOADED_VERIFIED'),
|
||||
('FAIL', 'RED', 'UPLOADED_VERIFY_FAILED'), ('PASS', 'UNKNOWN', 'UPLOADED_VERIFY_FAILED')])
|
||||
def test_add_stages_source_and_requires_authoritative_verify(setup, verify_status, flag, expected):
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
request, adapter, source = setup
|
||||
original = source.read_bytes()
|
||||
def verifier(req, **_):
|
||||
assert adapter.released
|
||||
return VerifyResult(verify_status, library_flag=flag)
|
||||
result = execute(replace(request, operation='add', name='New', source=source), adapter,
|
||||
verifier=verifier)
|
||||
assert result.status == expected and source.read_bytes() == original
|
||||
assert adapter.calls[0][1] != source
|
||||
assert adapter.calls[0][1].is_relative_to(result.evidence_path.parent)
|
||||
|
||||
|
||||
def test_add_no_auto_verify_and_reimport_after_remove(setup):
|
||||
request, adapter, source = setup
|
||||
assert execute(request, adapter).status == 'REMOVED'
|
||||
result = execute(replace(request, operation='add', source=source, auto_verify=False), adapter,
|
||||
verifier=lambda *_: pytest.fail('auto verify disabled'))
|
||||
assert result.status == 'UPLOADED'
|
||||
|
||||
|
||||
def test_update_failed_readd_keeps_removed_checkpoint_and_recovery_snapshot(setup):
|
||||
request, adapter, source = setup
|
||||
adapter.fail_add = True
|
||||
result = execute(replace(request, operation='update', source=source), adapter)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
|
||||
assert adapter.records == []
|
||||
history = json.loads(result.evidence_path.read_text(encoding='utf-8'))['history']
|
||||
assert 'removed' in [x['stage'] for x in history]
|
||||
assert (result.evidence_path.parent/'library-before/mentor.lmc').is_file()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('operation', ['remove', 'add'])
|
||||
def test_lying_native_output_does_not_report_success(setup, operation):
|
||||
request, adapter, source = setup
|
||||
adapter.lie = True
|
||||
request = replace(request, operation=operation, source=source,
|
||||
name='New' if operation == 'add' else 'Block')
|
||||
result = execute(request, adapter)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
|
||||
|
||||
|
||||
def test_unreleased_native_owner_prevents_postread_and_verification(setup):
|
||||
request, adapter, _ = setup
|
||||
original = adapter.remove
|
||||
def unreleased(*args):
|
||||
adapter.released = False
|
||||
return original(*args)
|
||||
adapter.remove = unreleased
|
||||
reads = []
|
||||
catalog = adapter.catalog
|
||||
adapter.catalog = lambda *a: (reads.append(1) or catalog(*a))
|
||||
result = execute(request, adapter, verifier=lambda *_: pytest.fail('unsafe verify'))
|
||||
assert not result.safe_to_continue and len(reads) == 1
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
|
||||
with pytest.raises(LibraryBusy):
|
||||
with LibraryLock(request.library):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name', ['../escape', 'A\tB', 'A\nB', 'A/B', 'NUL', 'a.', ''])
|
||||
def test_invalid_native_identity_rejected_before_writes(setup, name):
|
||||
request, adapter, _ = setup
|
||||
result = execute(replace(request, name=name), adapter)
|
||||
assert result.status == 'BLOCKED' and adapter.calls == []
|
||||
|
||||
|
||||
def test_evidence_inside_target_rejected(setup):
|
||||
request, adapter, _ = setup
|
||||
result = execute(replace(request, evidence_dir=request.library.parent/'evidence'), adapter)
|
||||
assert result.status == 'BLOCKED' and not (request.library.parent/'evidence').exists()
|
||||
|
||||
|
||||
def test_cancel_and_restart_never_replay(setup):
|
||||
from cbb_refresh_verify.management import run_management_batch, unfinished_operations
|
||||
request, adapter, _ = setup
|
||||
stop = Event(); stop.set()
|
||||
assert run_management_batch([request], stop=stop, adapter=adapter) == []
|
||||
checkpoint = request.evidence_dir/'interrupted/checkpoint.json'
|
||||
checkpoint.parent.mkdir(parents=True)
|
||||
checkpoint.write_text('{"stage":"native_remove", "status":"RUNNING"}', encoding='utf-8')
|
||||
found = unfinished_operations(request.evidence_dir)
|
||||
assert len(found) == 1 and found[0]['evidence_path'] == str(checkpoint)
|
||||
assert adapter.calls == []
|
||||
|
||||
|
||||
def test_capability_gate_enforced_below_ui(setup):
|
||||
from cbb_refresh_verify.management import Capability
|
||||
request, adapter, source = setup
|
||||
adapter.capabilities = lambda: {'add': Capability(False, 'isolated add not validated')}
|
||||
result = execute(replace(request, operation='add', name='New', source=source), adapter)
|
||||
assert result.status == 'UNSUPPORTED' and 'isolated' in result.detail
|
||||
assert adapter.calls == []
|
||||
|
||||
|
||||
def test_timeout_stops_batch_and_persists_ambiguous_native_stage(setup):
|
||||
from cbb_refresh_verify.management import run_management_batch
|
||||
request, adapter, _ = setup
|
||||
def timeout(*_):
|
||||
raise TimeoutError('network timeout')
|
||||
adapter.remove = timeout
|
||||
results = run_management_batch([request, replace(request, name='Other')], adapter=adapter,
|
||||
idle_check=lambda *_: None)
|
||||
assert len(results) == 1 and not results[0].safe_to_continue
|
||||
assert results[0].status == 'RECOVERY_REQUIRED'
|
||||
|
||||
|
||||
def test_catalog_timeout_is_not_safe_to_continue(setup):
|
||||
request, adapter, _ = setup
|
||||
def timeout(*_):
|
||||
raise TimeoutError('catalog owner still running')
|
||||
adapter.catalog = timeout
|
||||
result = execute(request, adapter)
|
||||
assert not result.safe_to_continue and adapter.calls == []
|
||||
|
||||
|
||||
def test_replaced_source_bytes_fail_identity_even_with_same_name(setup):
|
||||
request, adapter, source = setup
|
||||
real_add = adapter.add
|
||||
def wrong_source(*args):
|
||||
from cbb_refresh_verify.management import CatalogEntry
|
||||
result = real_add(*args)
|
||||
entry = adapter.records[-1]
|
||||
adapter.records[-1] = CatalogEntry(entry.name, entry.partition, {'wrong': 'project'})
|
||||
return result
|
||||
adapter.add = wrong_source
|
||||
result = execute(replace(request, operation='add', name='New', source=source), adapter)
|
||||
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
|
||||
|
||||
|
||||
def test_update_success_requires_same_identity_and_no_implicit_partition_move(setup):
|
||||
request, adapter, source = setup
|
||||
result = execute(replace(request, operation='update', source=source, partition='Other'), adapter)
|
||||
assert result.status == 'BLOCKED' and not adapter.calls
|
||||
result = execute(replace(request, operation='update', source=source, auto_verify=False), adapter)
|
||||
assert result.status == 'UPLOADED'
|
||||
assert adapter.calls[0] == 'remove' and adapter.calls[1][0] == 'add'
|
||||
|
||||
|
||||
def test_verify_exception_after_upload_retains_coordination_lock(setup):
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
|
||||
request, adapter, source = setup
|
||||
def broken_verifier(*a, **k):
|
||||
raise OSError('verification worker disconnected')
|
||||
result = execute(replace(request, operation='add', name='New', source=source), adapter,
|
||||
verifier=broken_verifier)
|
||||
assert result.status == 'UPLOADED_VERIFY_FAILED' and not result.safe_to_continue
|
||||
with pytest.raises(LibraryBusy):
|
||||
with LibraryLock(request.library):
|
||||
pass
|
||||
@@ -0,0 +1,99 @@
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
|
||||
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
|
||||
|
||||
|
||||
def test_management_can_select_ready_and_capability_disabled_explanation(qtbot, tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.management import Capability
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
caps = {name: Capability(name == 'remove', name + ' not validated') for name in ('add', 'update', 'remove')}
|
||||
window = MainWindow(reader=lambda _: LibraryReadResult((CbbRecord('Ready', 'Logical-Physical', status='READY'),)),
|
||||
data_root=tmp_path, management_adapter=SimpleNamespace(capabilities=lambda: caps))
|
||||
qtbot.addWidget(window)
|
||||
window.lmc_edit.setText('library.lmc'); window.load_library()
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
window.select_visible_button.click()
|
||||
assert window.remove_button.isEnabled()
|
||||
assert not window.add_button.isEnabled() and not window.update_button.isEnabled()
|
||||
assert 'not validated' in window.management_capability_label.text()
|
||||
assert not window.selected_batch_button.isEnabled()
|
||||
window.remove_button.click()
|
||||
assert window.management_dialog.requests()[0].name == 'Ready'
|
||||
assert window.management_dialog.requests()[0].partition == 'Logical-Physical'
|
||||
window.management_dialog.reject()
|
||||
|
||||
|
||||
def test_management_dialog_preview_confirmation_and_result_status(qtbot, tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.management import ManagementRequest, ManagementResult
|
||||
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
|
||||
requests = [ManagementRequest('remove', tmp_path/'lib.lmc', 'Block', evidence_dir=tmp_path/'out')]
|
||||
calls, confirmations = [], []
|
||||
def runner(items, **_):
|
||||
calls.extend(items)
|
||||
return [ManagementResult('remove', items[0].library, 'Block', 'Logical-Physical', None,
|
||||
False, 'complete', 'REMOVED', True, 'removed', tmp_path/'checkpoint.json')]
|
||||
dialog = ManagementDialog(requests, runner=runner)
|
||||
qtbot.addWidget(dialog)
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (confirmations.append(a[2]) or QMessageBox.No))
|
||||
dialog.execute_button.click()
|
||||
assert not calls and 'Block' in confirmations[0] and '完整' in confirmations[0]
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
|
||||
dialog.execute_button.click()
|
||||
qtbot.waitUntil(lambda: not dialog.busy)
|
||||
assert len(calls) == 1 and '已移除' in dialog.status_label.text()
|
||||
assert str(tmp_path/'checkpoint.json') in dialog.output.toPlainText()
|
||||
assert not dialog.execute_button.isEnabled()
|
||||
|
||||
|
||||
def test_add_dialog_default_auto_verify_and_source_identity_rows(qtbot, tmp_path):
|
||||
from cbb_refresh_verify.management import ManagementRequest
|
||||
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
|
||||
dialog = ManagementDialog([ManagementRequest('add', tmp_path/'lib.lmc', '', evidence_dir=tmp_path/'out')])
|
||||
qtbot.addWidget(dialog)
|
||||
dialog.add_sources([tmp_path/'One.prj', tmp_path/'Two.prj'])
|
||||
requests = dialog.requests()
|
||||
assert [r.name for r in requests] == ['One', 'Two']
|
||||
assert all(r.auto_verify and r.source.suffix == '.prj' for r in requests)
|
||||
dialog.auto_verify.setChecked(False)
|
||||
assert not any(r.auto_verify for r in dialog.requests())
|
||||
|
||||
|
||||
def test_restart_shows_unfinished_without_starting_worker(qtbot, tmp_path):
|
||||
import json
|
||||
from cbb_refresh_verify.management import Capability
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
checkpoint = tmp_path/'management/interrupted/checkpoint.json'
|
||||
checkpoint.parent.mkdir(parents=True)
|
||||
checkpoint.write_text(json.dumps({'status': 'RUNNING', 'stage': 'native_remove', 'name': 'Block'}), encoding='utf-8')
|
||||
adapter = SimpleNamespace(capabilities=lambda: {n: Capability(False, 'disabled') for n in ('add', 'update', 'remove')})
|
||||
window = MainWindow(data_root=tmp_path, management_adapter=adapter)
|
||||
qtbot.addWidget(window)
|
||||
assert '未完成' in window.unfinished_label.text() and not window.busy
|
||||
assert 'Block' in window.output.toPlainText()
|
||||
|
||||
|
||||
def test_persistent_owner_blocker_prevents_native_load_and_offers_checked_release(qtbot, tmp_path, monkeypatch):
|
||||
import pytest
|
||||
import cbb_refresh_verify.library_lock as locks
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
|
||||
locks.blocker_path(library).write_text('{}', encoding='utf-8')
|
||||
window = MainWindow(reader=lambda _: pytest.fail('unconfirmed owner reopened'), data_root=tmp_path/'data')
|
||||
qtbot.addWidget(window)
|
||||
window.lmc_edit.setText(str(library)); window.load_library()
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
assert window.loaded_path is None
|
||||
assert window.release_library_button.isEnabled()
|
||||
assert '释放检查' in window.status_label.text()
|
||||
calls = []
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
|
||||
monkeypatch.setattr(locks, 'release_retained_library', lambda *a:
|
||||
(calls.append(a) or {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'proof.json'}))
|
||||
window.release_library_button.click()
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
assert len(calls) == 1 and 'proof.json' in window.output.toPlainText()
|
||||
@@ -0,0 +1,165 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def test_installed_binary_mismatch_disables_removal(tmp_path):
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
adapter = NativeManagementAdapter(mentor_home=tmp_path)
|
||||
caps = adapter.capabilities()
|
||||
assert not caps['remove'].supported and 'CleanWGLib' in caps['remove'].reason
|
||||
assert not caps['add'].supported and not caps['update'].supported
|
||||
|
||||
|
||||
@pytest.mark.parametrize('name', ['A\tB', 'A\nB', '../A', '中文'])
|
||||
def test_delete_record_rejects_ambiguous_encoding_or_injection(name):
|
||||
from cbb_refresh_verify.native_management import removal_input
|
||||
with pytest.raises(ValueError):
|
||||
removal_input(name, 'Logical-Physical')
|
||||
|
||||
|
||||
def test_delete_record_is_exact_shipped_tcl_contract():
|
||||
from cbb_refresh_verify.native_management import removal_input, removal_output_ok
|
||||
assert removal_input('Block', 'Logical-Physical') == b'REUSE_BLOCK\tLogical-Physical\tBlock\n'
|
||||
assert not removal_output_ok(0, '', 'Block', 'Logical-Physical')
|
||||
assert not removal_output_ok(0, "# Warning: Unable to remove REUSE_BLOCK 'Block' from partition 'Logical-Physical'.", 'Block', 'Logical-Physical')
|
||||
assert removal_output_ok(0, "# Note: Removed REUSE_BLOCK 'Block' from partition 'Logical-Physical'.", 'Block', 'Logical-Physical')
|
||||
|
||||
|
||||
def test_upgrade_dialog_is_refused_and_only_cancel_is_allowed():
|
||||
from cbb_refresh_verify.native_management import catalog_dialog_action
|
||||
assert catalog_dialog_action('Library Manager', 'This Central Library must be updated before it can be opened in Library Manager. Select OK to continue.') == 'cancel'
|
||||
assert catalog_dialog_action('Select flow type', '') == 'cancel'
|
||||
assert catalog_dialog_action('Library Manager', 'Would you like to save?') == 'observe'
|
||||
|
||||
|
||||
def test_catalog_never_falls_back_to_folder_list(tmp_path):
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
library = tmp_path/'lib.lmc'; library.touch()
|
||||
(tmp_path/'ReusableBlocksLP/Ghost').mkdir(parents=True)
|
||||
adapter = NativeManagementAdapter()
|
||||
adapter._worker = lambda *_: {'success': False, 'safe_to_continue': True, 'detail': 'upgrade refused'}
|
||||
with pytest.raises(RuntimeError, match='upgrade refused'):
|
||||
adapter.catalog(library, tmp_path/'evidence')
|
||||
|
||||
|
||||
def test_private_worker_timeout_retains_native_and_never_kills(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
monkeypatch.setattr(native, '_retained_workers', [])
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
class Running:
|
||||
def __init__(self, *a): pass
|
||||
def poll(self): return None
|
||||
def close(self): pytest.fail('closing live DesktopWorker kills automation')
|
||||
def kill(self): pytest.fail('must preserve native owner')
|
||||
adapter = NativeManagementAdapter(worker_factory=Running, timeout_seconds=0)
|
||||
result = adapter._worker({'operation': 'catalog', 'library': str(tmp_path/'lib.lmc')}, tmp_path/'out')
|
||||
assert result['safe_to_continue'] is False
|
||||
assert 'TIMEOUT' in result['detail']
|
||||
|
||||
|
||||
def test_hidden_worker_and_probe_dispatch_before_qt(monkeypatch, tmp_path):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
from cbb_refresh_verify.application import main
|
||||
seen = []
|
||||
monkeypatch.setattr(native, 'management_worker_main', lambda p: (seen.append(p) or 17))
|
||||
assert main(['--management-worker', str(tmp_path/'job.json')]) == 17
|
||||
assert seen == [tmp_path/'job.json']
|
||||
|
||||
|
||||
def test_probe_cannot_use_existing_fixture_or_mutate_source(tmp_path):
|
||||
from cbb_refresh_verify.native_management import run_isolated_probe
|
||||
existing = tmp_path/'existing'
|
||||
existing.mkdir()
|
||||
with pytest.raises(ValueError, match='new|新'):
|
||||
run_isolated_probe(tmp_path/'source.prj', existing, 'Block')
|
||||
|
||||
|
||||
def test_probe_requires_owned_new_native_library_path(tmp_path):
|
||||
from cbb_refresh_verify.native_management import prepare_probe_library
|
||||
outside = tmp_path/'production.lmc'; outside.write_bytes(b'unchanged')
|
||||
root = tmp_path/'worker'; root.mkdir()
|
||||
with pytest.raises(ValueError):
|
||||
prepare_probe_library({'library': str(outside)}, root)
|
||||
assert outside.read_bytes() == b'unchanged'
|
||||
owned = root/'fixture/mentor_lib.lmc'
|
||||
assert prepare_probe_library({'library': str(owned)}, root) == owned
|
||||
owned.write_bytes(b'first creation')
|
||||
with pytest.raises(ValueError):
|
||||
prepare_probe_library({'library': str(owned)}, root)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('records', [[], [('Actual', 'Logical-Physical')]])
|
||||
def test_native_catalog_only_uses_com_records_and_checks_exact_process(tmp_path, monkeypatch, records):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
import cbb_refresh_verify.mentor_adapter as mentor
|
||||
import win32com.client
|
||||
library_path = tmp_path/'lib.lmc'; library_path.touch()
|
||||
(tmp_path/'ReusableBlocksLP/Ghost').mkdir(parents=True)
|
||||
class Collection:
|
||||
def __init__(self, items): self.items = items; self.Count = len(items)
|
||||
def Item(self, index): return self.items[index - 1]
|
||||
items = Collection([SimpleNamespace(Name=name, PartitionName=partition) for name, partition in records])
|
||||
class Library:
|
||||
FullName = str(library_path)
|
||||
FlowType = 1
|
||||
def Partitions(self, kind):
|
||||
assert kind == 7
|
||||
return Collection([items])
|
||||
def Close(self): pass
|
||||
state = {'running': False}
|
||||
class App:
|
||||
def OpenLibrary(self, path):
|
||||
assert path == str(library_path)
|
||||
return Library()
|
||||
def Quit(self): state['running'] = False
|
||||
def dispatch(_): state['running'] = True; return App()
|
||||
monkeypatch.setattr(win32com.client, 'DispatchEx', dispatch)
|
||||
monkeypatch.setattr(native, '_current_desktop', lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
|
||||
monkeypatch.setattr(mentor, '_process_details', lambda _: [(123, str(tmp_path/'lm/win32/bin/LibraryManager.exe'), '', 0)] if state['running'] else [])
|
||||
monkeypatch.setattr(native, '_wait_native_exit', lambda _: not state['running'])
|
||||
result = native._catalog_native({'operation': 'catalog', 'library': str(library_path),
|
||||
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path)}, tmp_path)
|
||||
assert result['success'] and result['safe_to_continue']
|
||||
assert [(entry['name'], entry['partition']) for entry in result['entries']] == records
|
||||
assert result['flow'] == 1
|
||||
|
||||
|
||||
def test_production_caps_require_all_validated_binary_hashes(tmp_path, monkeypatch):
|
||||
import hashlib
|
||||
import cbb_refresh_verify.native_management as native
|
||||
proof = {'lm/win32/bin/CleanWGLib.exe': hashlib.sha256(b'verified').hexdigest()}
|
||||
monkeypatch.setattr(native, '_BINARY_PROOF', proof)
|
||||
path = tmp_path/next(iter(proof)); path.parent.mkdir(parents=True); path.write_bytes(b'verified')
|
||||
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
|
||||
assert adapter.capabilities()['remove'].supported
|
||||
assert not adapter.capabilities()['add'].supported
|
||||
path.write_bytes(b'different')
|
||||
assert not adapter.capabilities()['remove'].supported
|
||||
|
||||
|
||||
def test_probe_readd_requires_creation_token_and_fixed_owned_library(tmp_path):
|
||||
from cbb_refresh_verify.native_management import validate_probe_readd
|
||||
root = tmp_path/'native-readd'; root.mkdir()
|
||||
library = tmp_path/'native-add/fixture/mentor_lib.lmc'
|
||||
library.parent.mkdir(parents=True); library.touch()
|
||||
job = {'library': str(library), 'probe_token': 'owned-token'}
|
||||
with pytest.raises(ValueError):
|
||||
validate_probe_readd(job, root)
|
||||
(tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'other'}), encoding='utf-8')
|
||||
with pytest.raises(ValueError):
|
||||
validate_probe_readd(job, root)
|
||||
(tmp_path/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': 'owned-token'}), encoding='utf-8')
|
||||
assert validate_probe_readd(job, root) == library
|
||||
outside = tmp_path/'production.lmc'; outside.touch()
|
||||
with pytest.raises(ValueError):
|
||||
validate_probe_readd({**job, 'library': str(outside)}, root)
|
||||
|
||||
|
||||
def test_com_failure_without_owner_identity_cannot_claim_release(tmp_path, monkeypatch):
|
||||
import cbb_refresh_verify.native_management as native
|
||||
monkeypatch.setattr(native, '_catalog_com', lambda *a: {'success': False,
|
||||
'safe_to_continue': False, 'native_pids': [], 'detail': 'COM startup ambiguous'})
|
||||
assert native._catalog_native({}, tmp_path)['safe_to_continue'] is False
|
||||
Reference in new issue
Block a user