fix: preserve catalog state and verify PCB write access
This commit is contained in:
1 parent
3efeaed656
commit
86837155ea
11 files changed
+651
-92
No files matched your search
@@ -371,3 +371,56 @@ def test_only_exact_empty_zero_area_childless_ie_infrastructure_is_benign(tmp_pa
|
||||
entry = result['benign_auxiliary_windows'][0]
|
||||
assert entry['class'] == 'Internet Explorer_Hidden' and entry['rect'] == [0, 0, 0, 0]
|
||||
assert entry['children'] == []
|
||||
|
||||
@pytest.mark.parametrize('receipt', ['matching', 'late', 'different_operation', 'different_identity'])
|
||||
def test_supervisor_no_lets_own_empty_pcb_close_with_address_remaining(tmp_path, monkeypatch, receipt):
|
||||
import win32con
|
||||
|
||||
job, records, messages, _, visible = read_write_fixture(tmp_path, monkeypatch)
|
||||
job['operation_id'] = 'verify-owned'
|
||||
address = tmp_path/'database/cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True)
|
||||
address.write_text('existing address')
|
||||
snapshot = failed_session._startup_snapshot(200, 12).to_record()
|
||||
from cbb_refresh_verify import residual_sessions
|
||||
monkeypatch.setattr(residual_sessions, '_force_ownership', lambda *_: {
|
||||
'owner_sid': 'S-1-5-21-test', 'session_id': 1})
|
||||
owner = {'pid': 12, 'owner_sid': 'S-1-5-21-test', 'session_id': 1,
|
||||
'image': records[0][1], 'created_handle': 'reused' if receipt == 'different_identity' else 'original'}
|
||||
(tmp_path/'pcb-open-user-choice.json').write_text(json.dumps(dict(
|
||||
operation_id='another-operation' if receipt == 'different_operation' else job['operation_id'],
|
||||
desktop=job['desktop'], project=job['project'], pcb=job['pcb'],
|
||||
library=job['lmc_file'], choice='skip', snapshot=snapshot, owner={'target': owner})))
|
||||
visible.remove(200)
|
||||
|
||||
def record_acknowledgement():
|
||||
(tmp_path/'dialogs.jsonl').write_text(json.dumps(dict(
|
||||
snapshot, action='user_confirmed_pcb_open', error_code='PCB_OPEN_SKIPPED',
|
||||
accepted_control=[7]))+'\n')
|
||||
|
||||
if receipt == 'late':
|
||||
from types import SimpleNamespace
|
||||
elapsed = 0.0
|
||||
|
||||
def advance(seconds):
|
||||
nonlocal elapsed
|
||||
elapsed += seconds
|
||||
if elapsed < 0.3:
|
||||
record_acknowledgement()
|
||||
|
||||
monkeypatch.setattr(failed_session, 'time',
|
||||
SimpleNamespace(monotonic=lambda: elapsed, sleep=advance))
|
||||
else:
|
||||
record_acknowledgement()
|
||||
result = failed_session.close_failed_startup(
|
||||
job, 12, timeout_seconds=0 if receipt == 'different_operation' else 1)
|
||||
|
||||
if receipt in {'different_operation', 'different_identity'}:
|
||||
assert result['status'] == 'RETAINED' and records and not messages
|
||||
return
|
||||
assert result['status'] == 'CLOSED'
|
||||
assert result['cancelled_prompt'] == 'read_write_access'
|
||||
assert result['release']['addresses'] == [str(address)]
|
||||
assert result['release']['resource_release_confirmed'] is False
|
||||
assert messages == [(100, win32con.WM_CLOSE)]
|
||||
assert not records and address.is_file()
|
||||
@@ -649,3 +649,102 @@ def test_recovery_retry_rejects_old_external_progress_and_choice(qtbot,tmp_path,
|
||||
assert choice.decision=='cancel'
|
||||
finally:
|
||||
release.set(); qtbot.waitUntil(lambda:not dialog.busy)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cancel', [True, False])
|
||||
def test_uncommitted_catalog_refresh_preserves_last_full_result(qtbot, tmp_path, monkeypatch, cancel):
|
||||
from cbb_refresh_verify.management import Catalog, CatalogEntry
|
||||
from cbb_refresh_verify.ui import main_window as ui
|
||||
|
||||
reading, release = Event(), Event()
|
||||
calls = []
|
||||
snapshot = tmp_path/'status-refresh.jsonl'
|
||||
|
||||
def read_status(names, path, checkpoint_path=None):
|
||||
calls.append(names)
|
||||
if checkpoint_path is not None:
|
||||
checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
checkpoint_path.write_text('full scan' if len(calls) == 1 else 'partial scan', encoding='utf-8')
|
||||
if len(calls) == 2:
|
||||
reading.set()
|
||||
release.wait(5)
|
||||
return {name: 'READY' for name in names}
|
||||
|
||||
monkeypatch.setattr(ui, 'authoritative_status_map', read_status)
|
||||
window = window_for(qtbot, tmp_path, monkeypatch,
|
||||
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'),), directory_count=1),
|
||||
catalog_reader=lambda path, _: Catalog(path, 1, (CatalogEntry('A', 'Logical-Physical'),)))
|
||||
try:
|
||||
load(window, qtbot)
|
||||
qtbot.waitUntil(lambda: window.ready_names == {'A'})
|
||||
reports = []
|
||||
monkeypatch.setattr(window, '_publish_check_statuses',
|
||||
lambda library, statuses, lease: reports.append(dict(statuses)))
|
||||
original_replace = Path.replace
|
||||
|
||||
def replace_file(path, target):
|
||||
if target == snapshot:
|
||||
raise PermissionError('snapshot is held')
|
||||
return original_replace(path, target)
|
||||
|
||||
if not cancel:
|
||||
monkeypatch.setattr(Path, 'replace', replace_file)
|
||||
window.load_button.click()
|
||||
qtbot.waitUntil(reading.is_set)
|
||||
assert window.ready_names == {'A'}
|
||||
assert not window.batch_button.isEnabled()
|
||||
assert snapshot.read_text(encoding='utf-8') == 'full scan'
|
||||
if cancel:
|
||||
window.stop_button.click()
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda: not any(job.kind == 'catalog' for job in window._jobs.values()))
|
||||
assert ('已取消读取' if cancel else 'snapshot is held') in window.status_label.text()
|
||||
assert reports == []
|
||||
assert window.ready_names == {'A'}
|
||||
assert snapshot.read_text(encoding='utf-8') == 'full scan'
|
||||
window.status_refresher(('A',), Path('a.lmc'))
|
||||
assert snapshot.read_text(encoding='utf-8') == 'full scan'
|
||||
finally:
|
||||
release.set()
|
||||
window.pool.waitForDone(6000)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cancelled', [False, True])
|
||||
def test_external_catalog_owner_wait_retries_once_or_cancels(qtbot, tmp_path, monkeypatch, cancelled):
|
||||
from cbb_refresh_verify.management import Catalog, CatalogEntry
|
||||
from cbb_refresh_verify.native_management import NativeOperationError
|
||||
|
||||
probing, released = Event(), Event()
|
||||
calls = []
|
||||
|
||||
def read_catalog(path, evidence):
|
||||
calls.append(evidence)
|
||||
if len(calls) == 1:
|
||||
raise NativeOperationError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行。', safe_to_continue=True)
|
||||
return Catalog(path, 1, (CatalogEntry('A', 'Logical-Physical'),))
|
||||
|
||||
def owners(*args, **kwargs):
|
||||
probing.set()
|
||||
return [] if released.is_set() else [{'pid': 123}]
|
||||
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', owners)
|
||||
window = window_for(qtbot, tmp_path, monkeypatch,
|
||||
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'),), directory_count=1),
|
||||
catalog_reader=read_catalog, status_refresher=lambda names, _: {name: 'READY' for name in names})
|
||||
try:
|
||||
load(window, qtbot)
|
||||
qtbot.waitUntil(probing.is_set)
|
||||
assert not window.native_queue.active
|
||||
if cancelled:
|
||||
window.stop_button.click()
|
||||
released.set()
|
||||
qtbot.waitUntil(lambda: not any(job.kind == 'catalog' for job in window._jobs.values()), timeout=4000)
|
||||
assert len(calls) == (1 if cancelled else 2)
|
||||
if cancelled:
|
||||
assert '已取消读取' in window.status_label.text()
|
||||
else:
|
||||
assert calls[0] != calls[1]
|
||||
assert window.ready_names == {'A'}
|
||||
finally:
|
||||
released.set()
|
||||
window.pool.waitForDone(6000)
|
||||
@@ -238,3 +238,43 @@ def test_catalog_native_wait_outlives_metadata_deadline(tmp_path, transport, mon
|
||||
(evidence/'finish').touch()
|
||||
finisher.join(6)
|
||||
context.close(timeout_seconds=6)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('switch', [False, True])
|
||||
def test_stop_reaches_active_catalog_adapter(qtbot, tmp_path, monkeypatch, transport, switch):
|
||||
from types import SimpleNamespace
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
Transport, workers = transport
|
||||
original = Transport.__init__
|
||||
|
||||
def hold_until_signalled(self, command, *args, **kwargs):
|
||||
Path(command[-1]).with_name('hold-handler').touch()
|
||||
original(self, command, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(Transport, '__init__', hold_until_signalled)
|
||||
library = tmp_path/'library.lmc'
|
||||
library.write_bytes(b'isolated')
|
||||
adapter = NativeManagementAdapter(worker_factory=Transport)
|
||||
window = window_for(qtbot, tmp_path/'ui', monkeypatch, catalog_reader=adapter.catalog)
|
||||
mapping_calls = []
|
||||
window.path_lease_factory = lambda path: SimpleNamespace(mentor_path=path, display_path=path,
|
||||
drive='', remote_root='', close=lambda: mapping_calls.append('close'),
|
||||
retain_for_recovery=lambda: mapping_calls.append('retain'))
|
||||
load(window, qtbot, str(library))
|
||||
qtbot.waitUntil(lambda: bool(workers) and workers[0].path.with_name('handler-entered').exists())
|
||||
worker = workers[0]
|
||||
try:
|
||||
if switch:
|
||||
window.lmc_edit.setText(str(tmp_path/'different.lmc'))
|
||||
else:
|
||||
window.stop_button.click()
|
||||
qtbot.waitUntil(lambda: worker.path.with_name('cancel-management.signal').exists(), timeout=3000)
|
||||
qtbot.waitUntil(lambda: bool(mapping_calls), timeout=3000)
|
||||
assert mapping_calls[0] == 'retain'
|
||||
if not switch:
|
||||
qtbot.waitUntil(lambda: '已取消读取中心库' in window.status_label.text(), timeout=3000)
|
||||
assert not window.native_queue.active
|
||||
assert worker.poll() is None
|
||||
finally:
|
||||
worker.path.with_name('finish').touch()
|
||||
qtbot.waitUntil(lambda: worker.poll() is not None, timeout=5000)
|
||||
@@ -112,3 +112,152 @@ def test_readwrite_choice_rejects_replaced_native_button(tmp_path,monkeypatch):
|
||||
changed=replace(original,controls=tuple(replace(c,handle=c.handle+1) if c.control_id==6 else c
|
||||
for c in original.controls))
|
||||
assert controller.handle(changed,(changed,),**kwargs).error_code=='DATABASE_RECOVERY_REQUIRED'
|
||||
|
||||
@pytest.mark.parametrize('origin', ['user', 'timeout_default'])
|
||||
@pytest.mark.parametrize('guard_error, control, code', [
|
||||
(None, 6, ''),
|
||||
(OSError('共享数据库被占用:SymbolLibs/icdb.dat'), 7, 'PCB_OPEN_SKIPPED'),
|
||||
(TimeoutError('原生检查超时'), 7, 'PCB_OPEN_SKIPPED'),
|
||||
])
|
||||
def test_normal_readwrite_uses_same_resource_check(tmp_path, monkeypatch, origin, guard_error, control, code):
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
from cbb_refresh_verify import pcb_open_consent as consent
|
||||
|
||||
monkeypatch.setattr(consent, 'validate_owner', lambda *_: {'target': 'owned'})
|
||||
events = []
|
||||
|
||||
@contextmanager
|
||||
def guard(*_, require_complete_proof=False):
|
||||
assert require_complete_proof
|
||||
events.append('probe')
|
||||
if guard_error is not None:
|
||||
raise guard_error
|
||||
yield
|
||||
events.append('released_probe_handles')
|
||||
|
||||
monkeypatch.setattr(consent, 'resource_guard', guard)
|
||||
controller = consent.OpenController(dict(root=str(tmp_path), block_name='A', lmc_file='lib.lmc',
|
||||
project='A.prj', pcb='A.pcb', desktop='CbbVerify_test'), auto_confirm=True)
|
||||
shown = []
|
||||
|
||||
def perform(_, action, phase):
|
||||
clicked = action['target']['control_id']
|
||||
events.append(clicked)
|
||||
return SimpleNamespace(accepted_controls=(clicked,), error_code='', detail='', channel='win32_button_click')
|
||||
|
||||
kwargs = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append, perform=perform)
|
||||
controller.handle(snapshot(), (snapshot(),), **kwargs)
|
||||
assert not events
|
||||
shown[0].choose('continue', origin=origin)
|
||||
result = controller.handle(snapshot(), (snapshot(),), **kwargs)
|
||||
assert result.error_code == code
|
||||
assert events == (['probe', 'released_probe_handles', control] if guard_error is None else ['probe', control])
|
||||
if guard_error is not None:
|
||||
assert str(guard_error) in result.detail
|
||||
record = json.loads((tmp_path/'pcb-open-user-choice.json').read_text(encoding='utf-8'))
|
||||
assert record['decision_origin'] == origin
|
||||
assert record['choice'] == ('continue' if control == 6 else 'skip')
|
||||
controller.handle(snapshot(), (snapshot(),), **kwargs)
|
||||
assert events.count(control) == 1
|
||||
|
||||
|
||||
def test_unattended_ordinary_dialog_defaults_to_checking_resources(qtbot):
|
||||
from cbb_refresh_verify.pcb_open_consent import OpenChoice
|
||||
from cbb_refresh_verify.ui.pcb_open_dialog import PcbOpenDialog
|
||||
|
||||
choice = OpenChoice('A', 'lib.lmc', auto_confirm=True)
|
||||
dialog = PcbOpenDialog(choice)
|
||||
qtbot.addWidget(dialog)
|
||||
assert dialog.defaultButton() is dialog.continue_button
|
||||
dialog.skip_button.click()
|
||||
assert choice.decision == 'skip'
|
||||
assert choice.decision_origin == 'user'
|
||||
|
||||
def test_unattended_readwrite_checks_actual_shared_database_handle(tmp_path, monkeypatch):
|
||||
import win32con
|
||||
import win32file
|
||||
from cbb_refresh_verify import pcb_open_consent as consent
|
||||
from cbb_refresh_verify import owner_probe
|
||||
|
||||
library = tmp_path/'lib.lmc'
|
||||
work = tmp_path/'ReusableBlocksLP/A/Work'
|
||||
project, pcb = work/'A.prj', work/'PCB/A.pcb'
|
||||
shared = tmp_path/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
|
||||
for path in (library, work/'database/icdb.dat', pcb.parent/'Layout/LayoutDB.lyt', shared):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_bytes(b'fixture')
|
||||
project.write_text('KEY PCBDesignPath "PCB/A.pcb"\nKEY iCDBDir "database"\n')
|
||||
pcb.write_text('KEY ProjectFile "../A.prj"\n')
|
||||
owner = {'target': 'bound'}
|
||||
monkeypatch.setattr(consent, 'validate_owner', lambda *_: owner)
|
||||
monkeypatch.setattr(owner_probe, 'query_process_snapshot', lambda: [])
|
||||
|
||||
def run(attempt, expected_control):
|
||||
evidence = tmp_path/attempt
|
||||
evidence.mkdir()
|
||||
controller = consent.OpenController(dict(root=str(evidence), block_name='A', lmc_file=str(library),
|
||||
project=str(project), pcb=str(pcb), desktop='CbbVerify_test'), auto_confirm=True)
|
||||
shown, actions = [], []
|
||||
|
||||
def perform(_, action, phase):
|
||||
actions.append(action['target']['control_id'])
|
||||
if expected_control == 6:
|
||||
handle = win32file.CreateFile(str(shared), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, 0, None)
|
||||
handle.Close()
|
||||
return SimpleNamespace(error_code='', accepted_controls=tuple(actions), detail='', channel='win32_button_click')
|
||||
|
||||
options = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append, perform=perform)
|
||||
controller.handle(snapshot(), (snapshot(),), **options)
|
||||
shown[0].choose('continue', origin='timeout_default')
|
||||
result = controller.handle(snapshot(), (snapshot(),), **options)
|
||||
assert actions == [expected_control], result.detail
|
||||
return result, evidence
|
||||
|
||||
held = win32file.CreateFile(str(shared), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, 0, None)
|
||||
try:
|
||||
skipped, evidence = run('occupied', 7)
|
||||
assert skipped.error_code == 'PCB_OPEN_SKIPPED'
|
||||
assert str(shared) in skipped.detail
|
||||
assert not (evidence/'pcb-open-resource-proof.json').exists()
|
||||
finally:
|
||||
held.Close()
|
||||
resumed, evidence = run('released', 6)
|
||||
assert not resumed.error_code
|
||||
assert (evidence/'pcb-open-resource-proof.json').is_file()
|
||||
|
||||
project.write_text('KEY PCBDesignPath "PCB/A.pcb"\nKEY iCDBDir "../../../outside"\n')
|
||||
unbound, _ = run('wrong-project-database', 7)
|
||||
assert 'iCDBDir' in unbound.detail
|
||||
|
||||
def test_stop_during_receipt_never_sends_native_yes(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import management
|
||||
from cbb_refresh_verify import pcb_open_consent as consent
|
||||
from cbb_refresh_verify.operation_queue import QueueCancelled
|
||||
|
||||
stopped = False
|
||||
original = management._write_json
|
||||
|
||||
def write_choice(path, value):
|
||||
nonlocal stopped
|
||||
original(path, value)
|
||||
stopped = True
|
||||
|
||||
def check_active():
|
||||
if stopped:
|
||||
raise QueueCancelled('cancelled')
|
||||
|
||||
monkeypatch.setattr(management, '_write_json', write_choice)
|
||||
monkeypatch.setattr('cbb_refresh_verify.operation_queue.check_active', check_active)
|
||||
monkeypatch.setattr(consent, 'validate_owner', lambda *_: {'target': 'bound'})
|
||||
monkeypatch.setattr(consent, 'resource_guard', lambda *_, **__: nullcontext())
|
||||
controller = consent.OpenController(dict(root=str(tmp_path), block_name='A', lmc_file='lib.lmc',
|
||||
project='A.prj', pcb='A.pcb', desktop='CbbVerify_test'), auto_confirm=True)
|
||||
shown = []
|
||||
options = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append,
|
||||
perform=lambda *_: pytest.fail('sent during cancellation'))
|
||||
controller.handle(snapshot(), (snapshot(),), **options)
|
||||
shown[0].choose('continue')
|
||||
assert controller.handle(snapshot(), (snapshot(),), **options).error_code == 'USER_CANCELLED'
|
||||
Reference in new issue
Block a user