fix: preserve mapped native paths and retain probe ownership guards

This commit is contained in:
阿白叔 committed 2026-11-02 21:48:40 +08:00
1 parent dd1fcea7e2
commit 46c3e72364
7 files changed
+365 -36

No files matched your search

+49
View File
@@ -252,3 +252,52 @@ def test_verify_exception_after_upload_retains_coordination_lock(setup):
with pytest.raises(LibraryBusy):
with LibraryLock(request.library):
pass
@pytest.mark.parametrize('nested', [True, False])
def test_library_inside_source_tree_rejected_before_catalog_or_guard(setup, nested):
request, adapter, source = setup
library = source.parent/('nested/lib.lmc' if nested else 'lib.lmc')
library.parent.mkdir(exist_ok=True)
library.write_bytes(b'library')
adapter.catalog = lambda *a: pytest.fail('overlapping library reached native catalog')
result = execute(replace(request, operation='add', name='New', source=source, library=library), adapter)
assert result.status == 'BLOCKED' and not adapter.calls
assert not library.with_name('.lib.cbb-upload.lock').exists()
assert not request.evidence_dir.exists()
def test_mapped_library_spelling_and_context_survive_engine_verify_boundary(setup, monkeypatch):
import shutil
from cbb_refresh_verify.verify_runner import VerifyResult
request, adapter, source = setup
alias_root = request.library.parent
canonical_root = alias_root.with_name('canonical-library')
shutil.copytree(alias_root, canonical_root)
original_resolve = Path.resolve
def resolve(path, *a, **k):
if path.is_relative_to(alias_root):
return original_resolve(canonical_root/path.relative_to(alias_root), *a, **k)
return original_resolve(path, *a, **k)
monkeypatch.setattr(Path, 'resolve', resolve)
catalogs, verified = [], []
catalog = adapter.catalog
adapter.catalog = lambda library, evidence: (catalogs.append(library) or catalog(library, evidence))
def verifier(req, **k):
verified.append(req)
return VerifyResult('PASS', library_flag='GREEN')
request = replace(request, operation='add', name='New', source=source,
mapped_drive='S:', mapped_remote_root=r'\\server\share')
result = execute(request, adapter, verifier=verifier)
assert result.status == 'UPLOADED_VERIFIED'
assert catalogs == [request.library, request.library]
assert verified[0].lmc_file == request.library
assert verified[0].mapped_drive == 'S:' and verified[0].mapped_remote_root == r'\\server\share'
def test_source_inside_target_library_rejected_before_catalog(setup):
request, adapter, _ = setup
source = request.library.parent/'ReusableBlocksLP/Block/Work/Block.prj'
adapter.catalog = lambda *a: pytest.fail('overlapping source reached native catalog')
result = execute(replace(request, operation='add', name='New', source=source), adapter)
assert result.status == 'BLOCKED' and not request.evidence_dir.exists()
+189
View File
@@ -0,0 +1,189 @@
"""Exercise actual guards/snapshots; only the native worker transport is fake."""
from dataclasses import asdict
import json
from pathlib import Path
import pytest
@pytest.fixture(autouse=True)
def prohibit_native_launch(monkeypatch):
"""Backstop independent of the boundary under development: no live apps."""
import subprocess, win32process, win32com.client
import cbb_refresh_verify.desktop_worker as desktop
def forbidden(*a, **k):
raise AssertionError('Native/process launch is forbidden in probe-guard tests')
monkeypatch.setattr(desktop, 'DesktopWorker', forbidden)
monkeypatch.setattr(win32process, 'CreateProcess', forbidden)
monkeypatch.setattr(subprocess, 'Popen', forbidden)
monkeypatch.setattr(win32com.client, 'Dispatch', forbidden)
monkeypatch.setattr(win32com.client, 'DispatchEx', forbidden)
@pytest.fixture
def probe_files(tmp_path):
def source(root, data):
(root/'database').mkdir(parents=True)
(root/'database/icdb.dat').write_bytes(data)
(root/'PCB/Layout').mkdir(parents=True)
(root/'PCB/Layout/LayoutDB.lyt').write_bytes(data)
(root/'PCB/pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n')
(root/'PCB/Block.pcb').write_text('KEY ProjectFile "../Block.prj"\n')
project = root/'Block.prj'
project.write_text('KEY RootBlock "Block"\nKEY iCDBDir "database"\nKEY PCBDesignPath "PCB/Block.pcb"\n')
return project
original = source(tmp_path/'original', b'original')
replacement = source(tmp_path/'replacement', b'replacement')
root = tmp_path/'probe'
yield original, replacement, root
# Only file fakes ran; close this test's deliberately retained OS handle.
import cbb_refresh_verify.library_lock as locks
library = root/'native-add/fixture/mentor_lib.lmc'
with locks._guard:
owner = locks._owners.pop(locks._key(library.with_name('.mentor_lib.cbb-upload.lock')), None)
if owner:
owner['handle'].Close()
@pytest.mark.parametrize('fault', ['create_unsafe', 'first_catalog_exception', 'remove_unsafe',
'remove_exception', 'after_remove_exception', 'readd_unsafe', 'readd_exception', 'final_catalog_exception'])
def test_isolated_probe_retains_guard_on_uncertain_native_lifecycle(probe_files, monkeypatch, fault):
import cbb_refresh_verify.native_management as native
import cbb_refresh_verify.library_lock as locks
from cbb_refresh_verify.management import Capability, CatalogEntry, engineering_identity
original, replacement, root = probe_files
records = []
monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities', lambda self:
{'remove': Capability(True, 'file transport fixture')})
def launch(self, job, evidence):
nonlocal records
evidence = Path(evidence)
operation = job['operation']
library = Path(job['library'])
if operation == 'probe_create_add':
# Directory creation belongs to the real supervising adapter.
assert native.prepare_probe_library(job, evidence) == library
library.write_bytes(b'native-created fixture')
(root/'probe-owner.json').write_text(json.dumps({'library': str(library), 'token': job['probe_token']}))
records = [CatalogEntry(job['name'], 'Logical-Physical', engineering_identity(job['source']))]
if fault == 'create_unsafe':
return {'success': False, 'safe_to_continue': False, 'detail': 'creation owner retained'}
elif operation == 'remove':
if fault == 'remove_exception':
raise TimeoutError('native removal transport disconnected')
if fault == 'remove_unsafe':
return {'success': False, 'safe_to_continue': False, 'detail': 'removal owner retained'}
records = []
elif operation == 'probe_readd':
if fault == 'readd_exception':
raise TimeoutError('native readd transport disconnected')
if fault == 'readd_unsafe':
return {'success': False, 'safe_to_continue': False, 'detail': 'readd owner retained'}
records = [CatalogEntry(job['name'], 'Logical-Physical', engineering_identity(job['source']))]
elif operation == 'catalog':
stage_fault = {'reopen': 'first_catalog_exception', 'after-remove': 'after_remove_exception',
'reopen-update': 'final_catalog_exception'}.get(evidence.name)
if stage_fault == fault:
raise TimeoutError('catalog owner release unknown')
return {'success': True, 'safe_to_continue': True, 'library': str(library), 'flow': 1,
'entries': [asdict(entry) for entry in records], 'detail': 'file fixture result'}
class Worker:
def __init__(self, command, desktop):
request = Path(command[-1])
job = json.loads(request.read_text(encoding='utf-8'))
result = launch(None, job, request.parent)
(request.parent/'result.json').write_text(json.dumps(result), encoding='utf-8')
def poll(self): return 0
def close(self): pass
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
try:
native.run_isolated_probe(original, root, 'Block', replacement_source=replacement)
except TimeoutError:
pass
library = root/'native-add/fixture/mentor_lib.lmc'
assert locks.has_blocker(library)
with pytest.raises(locks.LibraryBusy):
with locks.LibraryLock(library): pass
assert (root/'probe-result.json').is_file()
from contextlib import contextmanager
@contextmanager
def denied(*a):
raise locks.LibraryBusy('fresh proof still sees a native owner')
yield
monkeypatch.setattr(locks, '_prove_library_released', denied)
with pytest.raises(locks.LibraryBusy):
locks.release_retained_library(library, root/'release-checks')
assert locks.has_blocker(library)
@contextmanager
def released(*a):
yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
monkeypatch.setattr(locks, '_prove_library_released', released)
assert locks.release_retained_library(library, root/'release-checks')['status'] == 'RELEASE_CONFIRMED'
with locks.LibraryLock(library): pass
def test_mapping_context_is_serialized_and_restored_before_catalog(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
import cbb_refresh_verify.network_path as network
captured = []
class Worker:
def __init__(self, command, desktop):
request = Path(command[-1])
job = json.loads(request.read_text(encoding='utf-8'))
captured.append(job)
(request.parent/'result.json').write_text(json.dumps({'success': True, 'safe_to_continue': True,
'library': job['library'], 'flow': 1, 'entries': []}), encoding='utf-8')
def poll(self): return 0
def close(self): pass
adapter = native.NativeManagementAdapter(worker_factory=Worker)
adapter.bind_library_mapping('S:', r'\\server\share')
library = Path('S:/library/mentor.lmc')
adapter.catalog(library, tmp_path/'catalog')
assert captured[0]['library'] == str(library)
assert captured[0]['mapped_drive'] == 'S:'
order = []
monkeypatch.setattr(native, '_current_desktop', lambda: (None, captured[0]['desktop']))
monkeypatch.setattr(network, 'ensure_mapped_drive_visible', lambda drive, remote:
order.append(('mapping', drive, remote)))
monkeypatch.setattr(native, '_catalog_native', lambda job, root:
(order.append(('catalog', job['library'])) or {'success': True, 'safe_to_continue': True}))
assert native.management_worker_main(tmp_path/'catalog/request.json') == 0
assert order == [('mapping', 'S:', r'\\server\share'), ('catalog', str(library))]
def test_removal_cli_keeps_mapped_drive_spelling(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
from cbb_refresh_verify.management import Capability
job = {'operation': 'remove', 'library': 'S:\\library\\mentor.lmc', 'name': 'Block',
'partition': 'Logical-Physical', 'desktop': 'CbbManagement_fixture',
'mentor_home': str(tmp_path), 'timeout_seconds': 10}
request = tmp_path/'request.json'; request.write_text(json.dumps(job), encoding='utf-8')
monkeypatch.setattr(native, '_current_desktop', lambda: (None, job['desktop']))
monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities', lambda self: {'remove': Capability(True, 'fake transport')})
commands = []
class Process:
pid = 1234
def __init__(self, command, *, stdout, **kwargs):
commands.append(command)
stdout.write(b"# Note: Removed REUSE_BLOCK 'Block' from partition 'Logical-Physical'.\n")
stdout.flush()
def wait(self, **kwargs): return 0
monkeypatch.setattr(native.subprocess, 'Popen', Process)
assert native.management_worker_main(request) == 0
assert commands[0][1] == job['library']
def test_staged_project_alignment_keeps_selected_mapped_drive(tmp_path, monkeypatch):
from cbb_refresh_verify.backup_recovery import _align_library
project = tmp_path/'Block.prj'
project.write_text('KEY CentralLibrary "old.lmc"\n', encoding='utf-8')
pcb = tmp_path/'PCB/Block.pcb'; pcb.parent.mkdir(); pcb.touch()
pcb_project = pcb.parent/'pcb.prj'
pcb_project.write_text('KEY CentralLibrary "old.lmc"\n', encoding='utf-8')
library = Path('S:/library/mentor.lmc')
original_resolve = Path.resolve
monkeypatch.setattr(Path, 'resolve', lambda path, *a, **k:
Path(r'\\server\share\library\mentor.lmc') if path == library else original_resolve(path, *a, **k))
_align_library(project, pcb, library)
for path in (project, pcb_project):
assert 'KEY CentralLibrary "S:\\library\\mentor.lmc"' in path.read_text(encoding='utf-8')
+18 -5
View File
@@ -78,25 +78,38 @@ def test_probe_cannot_use_existing_fixture_or_mutate_source(tmp_path):
def test_probe_requires_owned_new_native_library_path(tmp_path):
import os
from cbb_refresh_verify.native_management import prepare_probe_library
from cbb_refresh_verify.library_lock import LibraryLock
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)
owned.parent.mkdir()
job = {'library': str(owned), 'probe_token': 'test-token', 'supervisor_pid': os.getpid()}
(root/'probe-prepared.json').write_text(json.dumps({'library': str(owned), 'token': 'test-token',
'supervisor_pid': os.getpid()}), encoding='utf-8')
with LibraryLock(owned):
assert prepare_probe_library(job, root) == owned
owned.write_bytes(b'first creation')
with pytest.raises(ValueError):
prepare_probe_library(job, root)
@pytest.mark.parametrize('records', [[], [('Actual', 'Logical-Physical')]])
def test_native_catalog_only_uses_com_records_and_checks_exact_process(tmp_path, monkeypatch, records):
@pytest.mark.parametrize('mapped', [False, True])
def test_native_catalog_only_uses_com_records_and_checks_exact_process(tmp_path, monkeypatch, records, mapped):
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()
if mapped:
original_resolve = Path.resolve
def resolve(path, *a, **k):
return tmp_path/'canonical/lib.lmc' if path == library_path else original_resolve(path, *a, **k)
monkeypatch.setattr(Path, 'resolve', resolve)
(tmp_path/'ReusableBlocksLP/Ghost').mkdir(parents=True)
class Collection:
def __init__(self, items): self.items = items; self.Count = len(items)