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

596 lines
30 KiB
Python

"""Retry boundaries use fake native outcomes and temporary libraries only."""
import json
import os
from pathlib import Path
from types import SimpleNamespace
import pytest
from test_management import setup, execute
from test_management_native_transaction import transaction
@pytest.fixture
def isolated_mutex(monkeypatch):
import win32event
from uuid import uuid4
original = win32event.CreateMutex
suffix = uuid4().hex
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
original(security, owned, name + suffix))
def test_released_catalog_failure_does_not_retain_management_lease(setup, monkeypatch):
from cbb_refresh_verify.native_management import NativeManagementAdapter
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path
request, _, _ = setup
adapter = NativeManagementAdapter(mentor_home=request.library.parent)
monkeypatch.setattr(adapter, 'capabilities', lambda: {'remove': SimpleNamespace(supported=True)})
monkeypatch.setattr(adapter, '_worker', lambda *_: {
'success': False, 'safe_to_continue': True, 'detail': 'catalog read failed after exit'})
result = execute(request, adapter)
assert result.safe_to_continue
assert not blocker_path(request.library).exists()
with LibraryLock(request.library):
pass
@pytest.mark.parametrize('busy', [False, True])
def test_legacy_blocker_is_rechecked_before_management_without_inventing_new_owner(setup, monkeypatch, isolated_mutex, busy):
import cbb_refresh_verify.library_lock as locks
request, adapter, _ = setup
marker = locks.blocker_path(request.library)
legacy = {'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
'lease_id': 'eae80a06f23e4664b00c70b6bf81b01d', 'library': str(request.library),
'status': 'OWNER_RELEASE_UNCONFIRMED', 'pid': 57076, 'time': '2026-11-04T09:43:50.830958+00:00'}
marker.write_text(json.dumps(legacy), encoding='utf-8')
before = marker.read_bytes()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
address = request.library.parent/'database/cdbsvr/sAddress.adr'
if busy:
address.parent.mkdir(parents=True); address.write_bytes(b'actual address')
result = execute(request, adapter)
assert result.safe_to_continue, 'No new native session was started by a blocked release check'
assert result.evidence_path and result.evidence_path.is_file()
if busy:
assert result.status == 'BLOCKED' and adapter.calls == []
assert marker.read_bytes() == before and address.read_bytes() == b'actual address'
assert '地址' in result.detail
else:
assert result.status == 'REMOVED' and adapter.calls == ['remove']
assert result.release_proof['status'] == 'RELEASE_CONFIRMED'
archive = Path(result.release_proof['evidence_path']).with_name('blocker-before-0.json')
assert archive.read_bytes() == before and not marker.exists()
def test_busy_execution_channel_does_not_create_unreleased_management_owner(setup, monkeypatch):
import win32con, win32event
request, adapter, _ = setup
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *_: win32con.WAIT_TIMEOUT)
result = execute(request, adapter)
assert result.status == 'BLOCKED' and result.safe_to_continue and not adapter.calls
assert result.evidence_path.is_file()
def test_management_rechecks_retained_verify_lease_without_checkpoint(setup, monkeypatch, isolated_mutex):
import cbb_refresh_verify.library_lock as locks
from cbb_refresh_verify.residual_sessions import inspect_residual_sessions
request, adapter, _ = setup
with locks.LibraryLock(request.library, checkpoint=False, safe_to_release=lambda: False):
pass
assert not locks.blocker_path(request.library).exists()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
monkeypatch.setattr('cbb_refresh_verify.residual_sessions.query_process_snapshot', lambda: [])
preview = inspect_residual_sessions(request.library)
assert preview['sessions'] == [] and any(r.get('kind') == 'in_memory' for r in preview['previous_records'])
result = execute(request, adapter)
assert result.status == 'REMOVED' and result.release_proof['status'] == 'RELEASE_CONFIRMED'
assert not locks.has_retained_library(request.library)
def test_management_worker_prelaunch_failure_is_safe(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
job = tmp_path/'request.json'
job.write_text(json.dumps({'operation': 'catalog', 'desktop': 'CbbManagement_test',
'library': str(tmp_path/'lib.lmc')}), encoding='utf-8')
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'wrong desktop'))
assert native.management_worker_main(job) == 2
result = json.loads((tmp_path/'result.json').read_text('utf-8'))
assert result['safe_to_continue'] is True
@pytest.mark.parametrize('code,busy', [(5, False), (32, True), (33, True)])
def test_coordination_open_error_preserves_access_failure(tmp_path, monkeypatch, code, busy):
import pywintypes
import win32file
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
def denied(*_):
raise pywintypes.error(code, 'CreateFile', 'test failure')
monkeypatch.setattr(win32file, 'CreateFile', denied)
with pytest.raises((OSError, pywintypes.error)) as error:
with LibraryLock(tmp_path/'lib.lmc'):
pass
assert isinstance(error.value, LibraryBusy) is busy
def test_retained_checkpoint_lease_can_reprobe_exact_release(tmp_path):
import cbb_refresh_verify.library_lock as locks
library = tmp_path/'lib.lmc'; library.touch()
released = False
lease = locks.LibraryLock(library, safe_to_release=lambda: released)
try:
with lease:
pass
with pytest.raises(locks.LibraryBusy):
with locks.LibraryLock(library):
pass
released = True
with locks.LibraryLock(library):
pass
assert not locks.blocker_path(library).exists()
finally:
owner = locks._owners.pop(lease.key, None)
if owner:
owner['handle'].Close()
@pytest.mark.parametrize('failure', ['enumerate', 'cancel'])
def test_owned_mapping_close_retries_after_transient_failure(monkeypatch, failure):
from test_network_path import FakeWNet
from cbb_refresh_verify.network_path import LibraryPathLease, NetworkPathError
backend = FakeWNet()
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
method = 'mappings' if failure == 'enumerate' else 'cancel_mapping'
original = getattr(backend, method)
def broken(*_):
raise OSError('temporary disconnect')
monkeypatch.setattr(backend, method, broken)
with pytest.raises(NetworkPathError):
lease.close()
monkeypatch.setattr(backend, method, original)
lease.close()
assert backend.cancelled == [lease.drive]
def test_batch_mismatch_isolated_to_item(tmp_path):
from cbb_refresh_verify.batch_status import BatchStatusSession
from cbb_refresh_verify.status_bridge import BridgeResponseError, BridgeResult
library = tmp_path/'lib.lmc'; library.touch()
class Bridge:
def __init__(self): self.calls = []; self.restarts = 0
def start(self): pass
def close(self): pass
def restart(self): self.restarts += 1
def query(self, library, name, **kwargs):
self.calls.append(name)
if name == 'Bad': raise BridgeResponseError('CBB mismatch')
return BridgeResult('PENDING', 'test')
bridge = Bridge()
results = BatchStatusSession(bridge).scan(['Bad', 'Good'], library, tmp_path/'scan.jsonl')
assert [result.status for result in results] == ['MALFORMED', 'PENDING']
assert bridge.calls == ['Bad', 'Good'] and bridge.restarts == 1
def test_batch_cache_binds_exact_library_identity(tmp_path):
from cbb_refresh_verify.batch_status import fingerprint_library
first = tmp_path/'a/lib.lmc'; first.parent.mkdir(); first.write_bytes(b'same')
second = tmp_path/'b/lib.lmc'; second.parent.mkdir(); second.write_bytes(b'same')
stat = first.stat(); os.utime(second, ns=(stat.st_atime_ns, stat.st_mtime_ns))
assert fingerprint_library(first).sha256 != fingerprint_library(second).sha256
def test_timed_out_management_worker_requires_independent_release_proof(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
state = {'exit': None}
proven = {'released': False}
def release(*a, **kw):
if not proven['released']:
raise OSError('native resources still owned')
return {'status': 'RELEASE_CONFIRMED', 'library': str(library)}
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library', release)
worker = SimpleNamespace(poll=lambda: state['exit'], close=lambda: None)
adapter = native.NativeManagementAdapter(mentor_home=tmp_path, worker_factory=lambda *_: worker)
library = tmp_path/'lib.lmc'; library.touch()
evidence = tmp_path/'run'; evidence.mkdir()
result = adapter._launch_worker({'library': str(library), 'operation': 'catalog',
'desktop': 'CbbManagement_test', 'timeout_seconds': 0}, evidence)
try:
assert result['safe_to_continue'] is False
assert adapter.release_confirmed(library) is False
state['exit'] = 2
assert adapter.release_confirmed(library) is False
(evidence/'result.json').write_text(json.dumps({'success': False, 'safe_to_continue': True}))
assert adapter.release_confirmed(tmp_path/'other.lmc') is False
assert adapter.release_confirmed(library) is False
proven['released'] = True
assert adapter.release_confirmed(library) is True
assert worker not in native._retained_workers
finally:
if worker in native._retained_workers:
native._retained_workers.remove(worker)
def test_existing_library_manager_refusal_preserves_prelaunch_release(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'CbbManagement_test'))
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter._process_details', lambda *_: [(123, 'other')])
with pytest.raises(RuntimeError) as error:
native._catalog_native({'operation': 'catalog', 'desktop': 'CbbManagement_test'}, tmp_path)
assert error.value.safe_to_continue is True
@pytest.mark.parametrize('stage,expected', [('catalog_before', 'REMOVED'), ('native_remove', 'BLOCKED')])
def test_prewrite_failure_evidence_does_not_permanently_prevent_retry(setup, stage, expected):
request, adapter, _ = setup
checkpoint = request.evidence_dir/'interrupted/checkpoint.json'
checkpoint.parent.mkdir(parents=True)
checkpoint.write_text(json.dumps({'library': str(request.library), 'stage': 'complete',
'status': 'BLOCKED', 'safe_to_continue': False, 'history': [{'stage': stage}]}), encoding='utf-8')
result = execute(request, adapter)
assert result.status == expected
def test_scoped_release_includes_shared_database_addresses(tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
library = tmp_path/'lib.lmc'; library.touch()
address = tmp_path/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True); address.write_bytes(b'preserve shared native address')
with pytest.raises(locks.LibraryBusy):
with locks._prove_library_released(library, block_name='Target'):
pass
assert address.read_bytes() == b'preserve shared native address'
def test_valid_relocated_pending_checkpoint_does_not_block_snapshot(tmp_path):
import cbb_refresh_verify.library_lock as locks
library = tmp_path/'copy/lib.lmc'; library.parent.mkdir(); library.touch()
pending = locks.blocker_path(library).with_suffix('.pending')
pending.write_text(json.dumps({'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
'library': str(tmp_path/'source/lib.lmc'), 'pid': os.getpid(),
'status': 'OPERATION_IN_PROGRESS', 'lease_id': 'a'*32, 'time': '2026-11-05'}))
assert not locks.has_blocker(library)
@pytest.mark.parametrize('content', ['{torn json', '{"unrecognized":"metadata"}'])
def test_unknown_checkpoint_release_archives_only_after_full_fresh_proof(tmp_path, monkeypatch, content):
import cbb_refresh_verify.library_lock as locks
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: [])
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
marker = locks.blocker_path(library); marker.write_text(content)
result = locks.release_retained_library(library, tmp_path/'evidence', block_name='Target')
assert result['status'] == 'RELEASE_CONFIRMED'
assert Path(result['evidence_path']).with_name('blocker-before-0.json').read_text() == content
assert not marker.exists()
assert library.with_name('.lib.cbb-upload.lock').exists()
def test_unknown_checkpoint_cannot_use_selected_target_to_ignore_other_owners(tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: [])
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
marker = locks.blocker_path(library); marker.write_bytes(b'{torn checkpoint')
address = library.parent/'ReusableBlocksLP/Other/Work/database/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True); address.write_bytes(b'preserve owner record')
with pytest.raises(locks.LibraryBusy):
locks.release_retained_library(library, tmp_path/'evidence', block_name='Target')
assert marker.read_bytes() == b'{torn checkpoint'
assert address.read_bytes() == b'preserve owner record'
def test_status_cache_does_not_reuse_a_different_block_type(tmp_path):
from cbb_refresh_verify.batch_status import BatchStatusSession
from cbb_refresh_verify.status_bridge import BridgeResult
library = tmp_path/'lib.lmc'; library.touch()
calls = []
class Bridge:
def query(self, library, name, **kwargs):
calls.append(kwargs['block_type'])
return BridgeResult('READY', 'test')
session = BatchStatusSession(Bridge())
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='RULP')
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='Other', resume=True)
assert calls == ['RULP', 'Other']
@pytest.mark.parametrize('case,relevant', [('other', False), ('prefix', False),
('target', True), ('shared', True), ('worker_target', True), ('worker_other', False)])
def test_release_owner_scope_uses_exact_paths_and_bound_worker_request(tmp_path, monkeypatch, case, relevant):
import cbb_refresh_verify.library_lock as locks
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
target = library.parent/'ReusableBlocksLP/Target/Work'
locations = {'other': tmp_path/'other/Other.prj', 'prefix': target.with_name('WorkOld')/'Other.prj',
'target': target/'Target.prj', 'shared': library.parent/'SymbolLibs/shared/database'}
if case.startswith('worker_'):
job = tmp_path/'worker.json'
job.write_text(json.dumps({'library': str(library if case == 'worker_target' else tmp_path/'other/lib.lmc')}))
name, command = 'python.exe', f'python.exe --management-worker "{job}"'
else:
name, command = 'ExpeditionPCB.exe', f'ExpeditionPCB.exe -project="{locations[case]}"'
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [
{'pid': 123456, 'name': name, 'command': command, 'parent': 0}])
if relevant:
with pytest.raises(locks.LibraryBusy):
with locks._prove_library_released(library, block_name='Target'):
pass
else:
with locks._prove_library_released(library, block_name='Target'):
pass
def test_release_ignores_retained_management_worker_for_other_library(tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.native_management as native
library = tmp_path/'lib.lmc'; library.touch()
other = SimpleNamespace(poll=lambda: None, cbb_library=str(tmp_path/'other.lmc'))
monkeypatch.setattr(native, '_retained_workers', [other])
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
with locks._prove_library_released(library):
pass
def test_retained_mapping_can_close_after_exact_release_proof():
from test_network_path import FakeWNet
from cbb_refresh_verify.network_path import LibraryPathLease
backend = FakeWNet()
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
lease.retain_for_recovery()
lease.close()
assert backend.cancelled == []
assert not lease.release_after_recovery({'status': 'RELEASE_CONFIRMED', 'library': r'\\other\share\lib.lmc'})
assert lease.release_after_recovery({'status': 'RELEASE_CONFIRMED', 'library': r'\\server\share\lib.lmc'})
lease.close()
assert backend.cancelled == [lease.drive]
def test_target_mapping_query_ignores_unrelated_enumeration_failure():
from test_network_path import FakeWNet
from cbb_refresh_verify.network_path import ensure_mapped_drive_visible
class Backend(FakeWNet):
def mapping(self, drive):
assert drive == 'S:'
return r'\\server\share'
def mappings(self):
raise OSError('unrelated drive enumeration failed')
result = ensure_mapped_drive_visible('S:', r'\\server\share', backend=Backend())
assert result['created'] is False
def test_windows_mapping_enumeration_reserves_unavailable_drive():
from cbb_refresh_verify.network_path import WindowsWNetBackend
backend = WindowsWNetBackend.__new__(WindowsWNetBackend)
def connection(drive, buffer, size):
if drive == 'D:': return 5
if drive == 'Y:':
buffer.value = r'\\server\share'
return 0
return 2250
backend._mpr = SimpleNamespace(WNetGetConnectionW=connection)
backend._kernel32 = SimpleNamespace(GetLogicalDrives=lambda: 0)
assert backend.mappings() == {'Y:': r'\\server\share'}
assert 'D:' in backend.used_drives()
def test_postnative_idle_failure_preserves_known_release(setup, isolated_mutex):
from cbb_refresh_verify.management import run_management
from cbb_refresh_verify.library_lock import LibraryLock
request, adapter, _ = setup
checks = []
def idle(*_):
checks.append(1)
if len(checks) == 3:
raise OSError('passive owner query unavailable after native exit')
result = run_management(request, adapter=adapter, idle_check=idle)
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
with LibraryLock(request.library):
pass
def test_final_report_failure_does_not_discard_release_result(setup, monkeypatch, isolated_mutex):
import cbb_refresh_verify.management as management
request, adapter, _ = setup
original = management._write_json
def write(path, record):
if record.get('stage') == 'complete':
raise OSError('evidence volume unavailable')
return original(path, record)
monkeypatch.setattr(management, '_write_json', write)
result = execute(request, adapter)
assert result.status == 'REMOVED' and result.safe_to_continue
assert 'evidence volume unavailable' in result.detail
def test_legacy_checkpoint_cannot_clear_other_target_owner(tmp_path, monkeypatch, isolated_mutex):
import cbb_refresh_verify.library_lock as locks
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
marker = locks.blocker_path(library)
locks._persist_blocker(library, lease_id='b'*32)
original = marker.read_bytes()
address = library.parent/'ReusableBlocksLP/Other/Work/database/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True); address.write_bytes(b'keep actual owner address')
with pytest.raises(locks.LibraryBusy):
locks.release_retained_library(library, tmp_path/'evidence', block_name='Target')
assert marker.read_bytes() == original
assert address.read_bytes() == b'keep actual owner address'
def test_release_proof_recovers_old_mapping_lease_and_transfers_shared_drive():
import cbb_refresh_verify.network_path as network
from test_network_path import FakeWNet
backend = FakeWNet()
old = network.LibraryPathLease.acquire(r'\\server\share\A\lib.lmc', backend=backend)
current = network.LibraryPathLease.acquire(r'\\server\share\B\lib.lmc', backend=backend)
old.retain_for_recovery(); old.close()
proof = {'status': 'RELEASE_CONFIRMED', 'library': r'\\server\share\A\lib.lmc'}
assert network.release_retained_path_leases(proof, current_lease=current) == 1
assert backend.cancelled == [] and current.created
current.close()
assert backend.cancelled == [current.drive]
def test_clean_failed_mutation_keeps_recovery_requirement_and_released_owner(setup, isolated_mutex):
from dataclasses import replace
from cbb_refresh_verify.management import run_management
request, adapter, source = setup
adapter.fail_add = True
failed = execute(replace(request, operation='update', source=source, auto_verify=False), adapter)
assert failed.status == 'RECOVERY_REQUIRED' and failed.safe_to_continue
adapter.fail_add = False
same = execute(replace(request, operation='add', source=source, auto_verify=False), adapter)
assert same.status == 'BLOCKED'
other = execute(replace(request, operation='add', name='Independent', source=source, auto_verify=False), adapter)
assert other.status == 'UPLOADED' and other.safe_to_continue
@pytest.mark.parametrize('history', [None, [], [{'stage': 'native_remove'}, {'stage': 'prepare_identity'}]])
def test_prewrite_stage_alone_does_not_override_unknown_or_mutated_history(history):
from cbb_refresh_verify.management import _may_have_mutated
record = {'stage': 'prepare_identity', 'history': history, 'status': 'RUNNING'}
assert _may_have_mutated(record)
def test_library_checkpoint_binds_supervisor_creation_identity(tmp_path):
import cbb_refresh_verify.library_lock as locks
library = tmp_path/'lib.lmc'; library.touch()
locks._persist_blocker(library, lease_id='c'*32)
record = json.loads(locks.blocker_path(library).read_text())
assert record.get('supervisor_created')
assert locks._recorded_supervisor_alive(record) is True
assert locks._recorded_supervisor_alive({**record, 'supervisor_created': 'other process'}) is False
legacy = {key: value for key, value in record.items() if key not in ('machine', 'supervisor_created')}
assert locks._recorded_supervisor_alive(legacy) is None
@pytest.mark.parametrize('proof,safe', [
({'safe_to_continue': True, 'process_created': False, 'worker_exited': True, 'remaining_pids': []}, True),
({'safe_to_continue': True, 'process_created': True, 'worker_exited': True, 'remaining_pids': []}, False),
({'safe_to_continue': True, 'process_created': False, 'worker_exited': False, 'remaining_pids': []}, False),
(None, False)])
def test_management_worker_launch_exception_uses_explicit_release_protocol(tmp_path, proof, safe):
from cbb_refresh_verify.native_management import NativeManagementAdapter
error = OSError('private desktop creation failed')
error.worker_launch_release = proof
def fail(*_): raise error
adapter = NativeManagementAdapter(mentor_home=tmp_path, worker_factory=fail)
with pytest.raises(OSError) as caught:
adapter._launch_worker({'library': str(tmp_path/'lib.lmc'), 'operation': 'catalog',
'desktop': 'CbbManagement_test', 'timeout_seconds': 1}, tmp_path)
assert getattr(caught.value, 'safe_to_continue', None) is safe
def test_native_add_passive_postcheck_failure_preserves_release(transaction, monkeypatch, isolated_mutex):
from test_management_native_transaction import execute as execute_transaction
root, request, state = transaction
def unavailable(*_): raise OSError('passive target check unavailable')
monkeypatch.setattr('cbb_refresh_verify.backup_recovery._idle_check', unavailable)
result = execute_transaction(root, request)
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
@pytest.mark.parametrize('case,safe', [('exit_output_error', True), ('popen_missing', True),
('popen_denied', True), ('popen_unknown', False), ('timeout', True)])
def test_remove_worker_preserves_exit_and_known_creation_rejection(tmp_path, monkeypatch, case, safe):
import cbb_refresh_verify.native_management as native
job = tmp_path/'request.json'
job.write_text(json.dumps({'operation': 'remove', 'desktop': 'CbbManagement_test',
'mentor_home': str(tmp_path), 'library': str(tmp_path/'lib.lmc'), 'name': 'Block',
'partition': 'Logical-Physical', 'timeout_seconds': 1,
'supervisor_pid': __import__('os').getpid()}), encoding='utf-8')
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'CbbManagement_test'))
monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities', lambda _: {
'remove': SimpleNamespace(supported=True)})
observed = {'waited': False}
def wait(timeout):
if case == 'timeout' and not observed.get('timed_out'):
observed['timed_out'] = True
raise native.subprocess.TimeoutExpired('fake CleanWGLib', timeout)
observed['waited'] = True
return 0
def popen(*args, **kwargs):
failures = {'popen_missing': FileNotFoundError('native binary disappeared'),
'popen_denied': PermissionError('native creation denied'),
'popen_unknown': OSError('unconfirmed process creation')}
if case in failures:
raise failures[case]
return SimpleNamespace(pid=123456, wait=wait)
monkeypatch.setattr(native.subprocess, 'Popen', popen)
original_read = Path.read_bytes
def read(path):
if path.name == 'native-output.txt' and case == 'exit_output_error':
assert observed['waited']
raise OSError('native output storage unavailable after exit')
return original_read(path)
monkeypatch.setattr(Path, 'read_bytes', read)
assert native.management_worker_main(job) == 2
result = json.loads((tmp_path/'result.json').read_text('utf-8'))
assert result['safe_to_continue'] is safe
if case == 'exit_output_error':
assert result['exit_code'] == 0 and 'storage unavailable' in result['detail']
def test_add_source_missing_central_library_fails_before_capture_without_retaining(setup, monkeypatch, isolated_mutex):
from dataclasses import replace
import cbb_refresh_verify.native_management as native
from cbb_refresh_verify.management import Catalog
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path
request, _, source = setup
adapter = native.NativeManagementAdapter(mentor_home=source.parent)
monkeypatch.setattr(adapter, 'capabilities', lambda: {'add': SimpleNamespace(supported=True)})
monkeypatch.setattr(adapter, 'catalog', lambda library, evidence: Catalog(library, 1, ()))
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity.capture_identity',
lambda *_a, **_kw: pytest.fail('incomplete source reached native capture'))
result = execute(replace(request, operation='add', name='New', source=source, auto_verify=False), adapter)
assert result.status == 'UPLOAD_FAILED' and result.safe_to_continue
assert 'CentralLibrary' in result.detail
assert not blocker_path(request.library).exists()
with LibraryLock(request.library):
pass
def test_prepared_transaction_storage_failure_preserves_capture_release(transaction, monkeypatch, isolated_mutex):
from test_management_native_transaction import execute as execute_transaction
root, request, _ = transaction
def unavailable(*_a, **_kw): raise OSError('prepared transaction storage unavailable')
monkeypatch.setattr('cbb_refresh_verify.management_transaction.prepare_transaction', unavailable)
result = execute_transaction(root, request)
assert result.status == 'UPLOAD_FAILED' and result.safe_to_continue
assert 'prepared transaction storage unavailable' in result.detail
@pytest.mark.parametrize('flag,relevant', [('-icdb', False), ('-icdb=', False),
('-ICDB', True), ('-icdb=', True)])
def test_release_owner_scope_parses_actual_edif_database_argument(tmp_path, flag, relevant):
from cbb_refresh_verify.library_lock import _owner_matches_scope
library = tmp_path/'Target/lib.lmc'
database = library.parent/'Work/database'
selected = database if relevant else tmp_path/'Other project/database'
argument = flag + ('' if flag.endswith('=') else ' ') + f'"{selected}"'
item = {'command': f'edifExporter.exe -schematic {argument} -isnap DxD'}
assert _owner_matches_scope(item, library, (database,)) is relevant
def test_release_owner_scope_does_not_match_edif_database_prefix(tmp_path):
from cbb_refresh_verify.library_lock import _owner_matches_scope
database = tmp_path/'Target/database'
item = {'command': f'edifExporter.exe -schematic -icdb "{database}_old" -isnap DxD'}
assert _owner_matches_scope(item, tmp_path/'Target/lib.lmc', (database,)) is False
def test_same_target_recovery_gate_preserves_release_and_batch_continues(setup, isolated_mutex):
from dataclasses import replace
from cbb_refresh_verify.management import run_management_batch
request, adapter, source = setup
adapter.fail_add = True
failed = execute(replace(request, operation='update', source=source, auto_verify=False), adapter)
assert failed.status == 'RECOVERY_REQUIRED' and failed.safe_to_continue
adapter.fail_add = False
results = run_management_batch([
replace(request, operation='add', source=source, auto_verify=False),
replace(request, operation='add', name='Independent', source=source, auto_verify=False)],
adapter=adapter, idle_check=lambda *_: None)
assert [result.status for result in results] == ['BLOCKED', 'UPLOADED']
assert all(result.safe_to_continue for result in results)