251 lines
11 KiB
Python
251 lines
11 KiB
Python
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
|
|
from cbb_refresh_verify import native_management as native
|
|
from cbb_refresh_verify.batch_status import BatchStatusSession
|
|
from cbb_refresh_verify.status_bridge import BridgeResult
|
|
|
|
|
|
def test_status_scan_delivers_progress_after_each_record(tmp_path):
|
|
snapshots = []
|
|
bridge = SimpleNamespace(query=lambda *args, **kwargs: BridgeResult("READY", "test"))
|
|
lmc = tmp_path / 'library.lmc'
|
|
lmc.write_bytes(b'library')
|
|
checkpoint = tmp_path / 'pending.jsonl'
|
|
|
|
def progress(completed, total):
|
|
snapshots.append((completed, total, len(checkpoint.read_text('utf-8').splitlines())))
|
|
|
|
results = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint, progress=progress)
|
|
assert [record.status for record in results] == ['READY', 'READY']
|
|
assert snapshots == [(1, 2, 1), (2, 2, 2)]
|
|
|
|
|
|
@pytest.mark.parametrize('include_identity', [False, True])
|
|
def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatch, include_identity):
|
|
import win32com.client
|
|
from cbb_refresh_verify import mentor_adapter
|
|
|
|
lmc = tmp_path / 'lib.lmc'
|
|
lmc.touch()
|
|
project = tmp_path / 'ReusableBlocksLP/A/Work/A.prj'
|
|
project.parent.mkdir(parents=True)
|
|
project.touch()
|
|
hashed = []
|
|
monkeypatch.setattr(native, 'engineering_identity', lambda p: hashed.append(p) or {'identity': True})
|
|
|
|
partition = SimpleNamespace(Count=1,
|
|
Item=lambda _: SimpleNamespace(Name='A', PartitionName='Logical-Physical'))
|
|
library = SimpleNamespace(FullName=str(lmc), FlowType=1, Close=lambda: None,
|
|
Partitions=lambda _: SimpleNamespace(Count=1, Item=lambda _: partition))
|
|
app = SimpleNamespace(OpenLibrary=lambda _: library, Quit=lambda: None)
|
|
exe = tmp_path / 'lm/win32/bin/LibraryManager.exe'
|
|
no_owners = iter([[], [(123, str(exe), '', 0)]])
|
|
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: next(no_owners))
|
|
monkeypatch.setattr(native, '_current_desktop',
|
|
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
|
|
monkeypatch.setattr(win32com.client, 'DispatchEx', lambda _: app)
|
|
result = native._catalog_com({'operation': 'catalog', 'worker_role': 'catalog_readonly',
|
|
'include_engineering_identity': include_identity, 'library': str(lmc),
|
|
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path), 'supervisor_pid': __import__('os').getpid()}, tmp_path)
|
|
assert result['success']
|
|
assert hashed == ([project] if include_identity else [])
|
|
|
|
|
|
@pytest.mark.parametrize('scope', ['foreign', 'same', 'shared', 'unknown', 'switched', 'occupied'])
|
|
def test_catalog_distinguishes_foreign_and_conflicting_manager(tmp_path, monkeypatch, scope):
|
|
target = tmp_path/'target'/'lib.lmc'
|
|
outside = tmp_path/'outside'/'lib.lmc'
|
|
for lmc in (target, outside):
|
|
lmc.parent.mkdir()
|
|
lmc.touch()
|
|
if scope == 'shared':
|
|
from cbb_refresh_verify.icdb_ownership import shared_symbol_database
|
|
first = shared_symbol_database(target)/'icdb.dat'
|
|
second = shared_symbol_database(outside)/'icdb.dat'
|
|
first.parent.mkdir(parents=True)
|
|
second.parent.mkdir(parents=True)
|
|
first.touch()
|
|
second.hardlink_to(first)
|
|
lk = target if scope == 'same' else outside
|
|
actual = None if scope == 'unknown' else target if scope == 'switched' else lk
|
|
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: actual, raising=False)
|
|
owners = [(123, 'LibraryManager.exe', '' if scope == 'unknown' else f'LibraryManager.exe "{lk}"', 0)]
|
|
if scope == 'occupied':
|
|
def held(library):
|
|
raise OSError('shared database handle is occupied')
|
|
monkeypatch.setattr(native, '_probe_catalog_files', held)
|
|
if scope == 'foreign':
|
|
native._check_catalog_owners(target, owners)
|
|
else:
|
|
with pytest.raises(RuntimeError, match='LIBRARY_MANAGER_BUSY.*123'):
|
|
native._check_catalog_owners(target, owners)
|
|
|
|
|
|
def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path, monkeypatch):
|
|
import win32com.client
|
|
from cbb_refresh_verify import mentor_adapter
|
|
|
|
target = tmp_path/'target'/'lib.lmc'
|
|
other = tmp_path/'other'/'lib.lmc'
|
|
for lmc in (target, other):
|
|
lmc.parent.mkdir()
|
|
lmc.touch()
|
|
exe = tmp_path/'lm/win32/bin/LibraryManager.exe'
|
|
exe.parent.mkdir(parents=True)
|
|
exe.write_bytes(b'library manager')
|
|
monkeypatch.setitem(native._BINARY_PROOF, 'lm/win32/bin/LibraryManager.exe', native.hash_file(exe))
|
|
before = [(123, 'LibraryManager.exe', f'LibraryManager.exe "{other}"', 0)]
|
|
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: before)
|
|
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: other, raising=False)
|
|
monkeypatch.setattr(native, '_current_desktop',
|
|
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
|
|
|
|
class Foreign:
|
|
def __setattr__(self, key, value):
|
|
pytest.fail(f'changed foreign LM property {key}')
|
|
def OpenLibrary(self, *_):
|
|
pytest.fail('opened target from a foreign LM')
|
|
def Quit(self):
|
|
pytest.fail('quit foreign LM')
|
|
|
|
monkeypatch.setattr(win32com.client, 'DispatchEx', lambda _: Foreign())
|
|
result = native._catalog_com({'operation': 'catalog', 'worker_role': 'catalog_readonly',
|
|
'include_engineering_identity': False, 'library': str(target),
|
|
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path), 'supervisor_pid': __import__('os').getpid()}, tmp_path)
|
|
assert not result['success']
|
|
assert result['native_pids'] == []
|
|
assert result['no_new_manager'] is True
|
|
assert 'LIBRARY_MANAGER_BUSY' in result['detail']
|
|
|
|
|
|
|
|
def test_catalog_progress_and_pending_preview_are_visible(qtbot, tmp_path, monkeypatch):
|
|
from threading import Event
|
|
from cbb_refresh_verify.management import Catalog, CatalogEntry
|
|
from cbb_refresh_verify.ui import main_window as ui
|
|
from test_issue15_ui_integration import load
|
|
|
|
checked, finish = Event(), Event()
|
|
library = tmp_path/'lib.lmc'
|
|
library.write_bytes(b'test catalog')
|
|
for name in ('A', 'B'):
|
|
(tmp_path/'ReusableBlocksLP'/name).mkdir(parents=True)
|
|
|
|
def status(names, path, checkpoint=None, *, progress=None):
|
|
if progress is not None:
|
|
progress(1, len(names))
|
|
checked.set()
|
|
assert finish.wait(5)
|
|
checkpoint.parent.mkdir(parents=True, exist_ok=True)
|
|
checkpoint.write_text('complete', encoding='utf-8')
|
|
return {name: 'READY' for name in names}
|
|
|
|
monkeypatch.setattr(ui, 'authoritative_status_map', status)
|
|
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *_: None)
|
|
window = ui.MainWindow(data_root=tmp_path/'data', catalog_reader=lambda path, _: Catalog(
|
|
path, 1, tuple(CatalogEntry(name, 'Logical-Physical') for name in ('A', 'B'))))
|
|
qtbot.addWidget(window)
|
|
window.show()
|
|
try:
|
|
load(window, qtbot, str(library))
|
|
qtbot.waitUntil(checked.is_set)
|
|
qtbot.waitUntil(lambda: '已核对 1/2' in window.status_label.text(), timeout=1000)
|
|
assert window.ready_names == set()
|
|
assert not window.icdb_repair_button.isEnabled()
|
|
assert not window.backup_restore_button.isEnabled()
|
|
assert not (tmp_path/'data'/'status-refresh.jsonl').exists()
|
|
finish.set()
|
|
qtbot.waitUntil(lambda: window.ready_names == {'A', 'B'})
|
|
finally:
|
|
finish.set()
|
|
window.pool.waitForDone(6000)
|
|
|
|
|
|
def test_timed_out_catalog_can_refresh_already_registered_status_only(qtbot, tmp_path, monkeypatch):
|
|
from cbb_refresh_verify.management import Catalog, CatalogEntry
|
|
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
|
|
from cbb_refresh_verify.ui import main_window as ui
|
|
from test_issue15_ui_integration import load, window_for
|
|
|
|
calls = []
|
|
still_active = []
|
|
|
|
def catalog(library, _):
|
|
calls.append(library)
|
|
if len(calls) > 1:
|
|
raise native.NativeOperationError('LIBRARY_MANAGER_BUSY: PID 123', safe_to_continue=True,
|
|
blocking_manager_pids=(123,))
|
|
return Catalog(library, 1, (CatalogEntry('A', 'Logical-Physical'),))
|
|
|
|
monkeypatch.setattr(ui, 'CATALOG_MANAGER_WAIT_SECONDS', 0, raising=False)
|
|
window = window_for(qtbot, tmp_path, monkeypatch,
|
|
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'), CbbRecord('Ghost', 'LP')), directory_count=2),
|
|
catalog_reader=catalog, status_refresher=lambda names, _: (
|
|
still_active.append(tuple(names)) or {name: ('READY' if len(calls) == 1 else 'PENDING') for name in names}))
|
|
try:
|
|
load(window, qtbot)
|
|
qtbot.waitUntil(lambda: window.ready_names == {'A'})
|
|
window.load_button.click()
|
|
qtbot.waitUntil(lambda: window.load_button.text() == '重试读取')
|
|
assert window.ready_names == {'A'}
|
|
assert not window.batch_button.isEnabled()
|
|
window.catalog_status_button.click()
|
|
qtbot.waitUntil(lambda: window._records_by_name['A'].status == 'PENDING')
|
|
assert window._records_by_name['Ghost'].status == 'UNKNOWN'
|
|
assert not window.batch_button.isEnabled()
|
|
assert len(calls) == 2 and still_active == [('A',), ('A',)]
|
|
assert window.loaded_path is None
|
|
finally:
|
|
window.pool.waitForDone(6000)
|
|
|
|
|
|
def test_catalog_switch_retains_complete_snapshot_and_ignores_duplicate_reads(qtbot, tmp_path, monkeypatch):
|
|
from threading import Event
|
|
from cbb_refresh_verify.management import Catalog, CatalogEntry
|
|
from cbb_refresh_verify.ui import main_window as ui
|
|
from test_issue15_ui_integration import load
|
|
|
|
paths = {name: tmp_path/name/'lib.lmc' for name in ('A', 'B')}
|
|
for name, library in paths.items():
|
|
(library.parent/'ReusableBlocksLP'/name).mkdir(parents=True)
|
|
library.write_bytes(b'catalog')
|
|
reading, allow_return = Event(), Event()
|
|
calls = []
|
|
|
|
def catalog(path, _):
|
|
calls.append(path.parent.name)
|
|
if path == paths['B']:
|
|
reading.set()
|
|
assert allow_return.wait(5)
|
|
return Catalog(path, 1, (CatalogEntry(path.parent.name, 'Logical-Physical'),))
|
|
|
|
def statuses(names, path, checkpoint=None, *, progress=None):
|
|
checkpoint.parent.mkdir(parents=True, exist_ok=True)
|
|
checkpoint.write_text(path.parent.name, encoding='utf-8')
|
|
return {name: 'READY' for name in names}
|
|
|
|
monkeypatch.setattr(ui, 'authoritative_status_map', statuses)
|
|
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *_: None)
|
|
window = ui.MainWindow(data_root=tmp_path/'data', catalog_reader=catalog)
|
|
qtbot.addWidget(window)
|
|
window.show()
|
|
try:
|
|
load(window, qtbot, str(paths['A']))
|
|
qtbot.waitUntil(lambda: window.ready_names == {'A'})
|
|
load(window, qtbot, str(paths['B']))
|
|
qtbot.waitUntil(reading.is_set)
|
|
window.load_button.click()
|
|
assert window.ready_names == {'A'}
|
|
assert str(paths['A']) in window.library_notice.text()
|
|
assert not window.batch_button.isEnabled()
|
|
allow_return.set()
|
|
qtbot.waitUntil(lambda: window.ready_names == {'B'})
|
|
assert calls == ['A', 'B']
|
|
assert (tmp_path/'data/status-refresh.jsonl').read_text('utf-8') == 'B'
|
|
finally:
|
|
allow_return.set()
|
|
window.pool.waitForDone(6000)
|