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