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

278 lines
15 KiB
Python

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
def test_add_route_readiness_is_separate_from_conservative_capability_gate(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.route_capabilities()['add'].supported
assert not adapter.capabilities()['add'].supported
assert '身份' in adapter.capabilities()['add'].reason
def test_native_add_passes_existing_library_and_staged_source_to_worker(tmp_path, monkeypatch):
from cbb_refresh_verify.management import ManagementRequest
import cbb_refresh_verify.native_management as native
source = tmp_path/'source.prj'; source.write_bytes(b'source')
library = tmp_path/'library.lmc'; library.write_bytes(b'library')
seen = {}
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
monkeypatch.setattr(adapter, 'route_capabilities', lambda: {
'add': native.Capability(True, 'route ready')})
monkeypatch.setattr(native, 'engineering_identity', lambda path: {'source': str(path)})
def worker(job, evidence):
seen.update(job=job, evidence=evidence)
return {'success': True, 'safe_to_continue': True, 'identity_matches': True,
'detail': 'native add accepted'}
monkeypatch.setattr(adapter, '_worker', worker)
request = ManagementRequest('add', library, 'Block', source=source,
mapped_drive='S:', mapped_remote_root=r'\\server\share', timeout_seconds=23)
result = adapter.add(request, tmp_path/'evidence')
assert result.success and result.safe_to_continue and result.identity_matches is True
assert seen['job'] == {
'operation': 'add', 'library': str(library), 'source': str(source),
'name': 'Block', 'partition': 'Logical-Physical', 'top_level_block': '',
'mapped_drive': 'S:', 'mapped_remote_root': r'\\server\share',
'timeout_seconds': 23, 'source_identity': {'source': str(source)},
}
def test_native_add_identity_mismatch_is_native_success_with_evidence(tmp_path, monkeypatch):
from cbb_refresh_verify.management import ManagementRequest
import cbb_refresh_verify.native_management as native
source = tmp_path/'source.prj'; source.write_bytes(b'source')
library = tmp_path/'library.lmc'; library.write_bytes(b'library')
adapter = native.NativeManagementAdapter(mentor_home=tmp_path)
monkeypatch.setattr(adapter, 'route_capabilities', lambda: {
'add': native.Capability(True, 'route ready')})
monkeypatch.setattr(native, 'engineering_identity', lambda path: {'source': str(path)})
monkeypatch.setattr(adapter, '_worker', lambda job, evidence: {
'success': True, 'safe_to_continue': True, 'identity_matches': False,
'detail': 'engineering identity readback mismatch',
})
original = source.read_bytes()
result = adapter.add(ManagementRequest('add', library, 'Block', source=source), tmp_path/'evidence')
assert result.success and result.identity_matches is False
assert 'identity' in result.detail
assert result.evidence_path == tmp_path/'evidence'
assert source.read_bytes() == original
@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):
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'
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')]])
@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)
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
@pytest.mark.parametrize('registered', [True, False])
def test_shared_add_reopens_exact_catalog_and_reports_identity_mismatch(tmp_path, monkeypatch, registered):
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()
events = []
class Collection:
def __init__(self, items): self.items = items; self.Count = len(items)
def Item(self, index): return self.items[index - 1]
class Library:
FullName = str(library_path)
FlowType = 1
def Partitions(self, kind):
events.append('catalog')
return Collection([Collection([SimpleNamespace(Name='Block', PartitionName='Logical-Physical')]
if registered else [])])
def Close(self): events.append('close')
state = {'running': False}
class App:
def OpenLibrary(self, path):
assert path == str(library_path)
events.append('open')
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, '_probe_add_dialog', lambda *a, **k: events.append('add'))
result = native._catalog_com({'operation': 'add', 'library': str(library_path),
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path),
'name': 'Block', 'partition': 'Logical-Physical', 'source_identity': {'expected': 'bytes'}}, tmp_path)
assert events == ['open', 'add', 'close', 'open', 'catalog', 'close']
assert result['success'] is registered
assert result['identity_matches'] is False
assert ('engineering identity' if registered else 'exact name and partition') in result['detail']