fix: isolate ICDB checks and recover scoped native sessions

This commit is contained in:
阿白叔 committed 2026-11-05 21:52:38 +08:00
1 parent 1acfbd6374
commit 1bd7589fef
82 files changed
+7770 -1583

No files matched your search

+87
View File
@@ -0,0 +1,87 @@
from threading import Event, Thread
import time
def test_native_queue_is_fifo_and_waiting_cancel_never_runs_action():
from cbb_refresh_verify.operation_queue import NativeQueue, QueueCancelled
queue = NativeQueue()
holding, release, waiting, cancelled = Event(), Event(), Event(), Event()
order = []
first = Thread(target=lambda: queue.run(lambda: (holding.set(), release.wait(3), order.append('first'))))
first.start(); assert holding.wait(1)
def second():
try: queue.run(lambda: order.append('cancelled'), stop=cancelled, waiting=waiting.set)
except QueueCancelled: pass
second_thread = Thread(target=second); second_thread.start(); assert waiting.wait(1)
cancelled.set(); second_thread.join(1); assert not second_thread.is_alive()
third = Thread(target=lambda: queue.run(lambda: order.append('third')))
third.start(); release.set(); first.join(2); third.join(2)
assert order == ['first', 'third']
def test_background_scan_keeps_ui_usable_and_yields_between_projects(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
started, release = Event(), Event()
order = []
def verify(request):
order.append(request.block_name)
if request.block_name == 'Beta':
started.set(); release.wait(3)
return VerifyResult('CHECKED')
window = load_window(qtbot, tmp_path, monkeypatch, verifier=verify)
window._run(['Beta', 'Gamma'], maintenance=True)
try:
qtbot.waitUntil(started.is_set)
assert not window.busy and window.search_edit.isEnabled() and window.load_button.isEnabled()
window.search_edit.setText('Gamma')
assert [r.name for r in window.visible_records()] == ['Gamma']
window._start(lambda: order.append('foreground'), lambda _: None)
qtbot.wait(30)
assert order == ['Beta']
release.set()
qtbot.waitUntil(lambda: not window.icdb_task.active and not window.busy)
assert order == ['Beta', 'foreground', 'Gamma']
assert window.search_edit.text() == 'Gamma'
assert window.icdb_repair_button.isEnabled()
finally:
release.set()
def test_unconfirmed_open_is_amber_and_does_not_claim_icdb_damage(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
window = load_window(qtbot, tmp_path, monkeypatch, verifier=lambda _: VerifyResult('FAIL',
error_category='DATABASE_SAFETY_STOP', stderr='Continue to open read/write?'))
window._run(['Beta'], maintenance=True)
qtbot.waitUntil(lambda: not window.icdb_task.active)
cell = window.cbb_table.item(window._row_by_name['Beta'], 3)
assert '未确认' in cell.text() and 'ICDB 错误' not in cell.text()
assert cell.background().color().name() == '#fff8e1'
def test_completed_old_library_result_does_not_release_new_library(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
from pathlib import Path
window = load_window(qtbot, tmp_path, monkeypatch, verifier=lambda _: VerifyResult('FAIL', safe_to_continue=False))
window._run(['Beta'], maintenance=True)
qtbot.waitUntil(lambda: not window._icdb_active())
summary = window.icdb_summary
window.lmc_edit.setText('other.lmc')
next(button for button in summary.buttons() if '释放' in button.text()).click()
assert getattr(window, 'release_dialog', None) is None
assert '切' in window.status_label.text()
def test_later_management_invalidates_old_recovery_offer(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from test_reimport_recovery import failed_repair
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: failed_repair(tmp_path/'old/result.json', safe=True))
window._run(['Beta'], maintenance=True)
qtbot.waitUntil(lambda: not window._icdb_active())
action = next(b for b in window.icdb_summary.buttons() if '副本' in b.text())
assert action.isEnabled()
window._invalidate_check_targets('test.lmc', ['Beta'])
assert not action.isEnabled() and not window._reimport_offers
+122
View File
@@ -0,0 +1,122 @@
"""Background check and foreground queue interaction regressions."""
from threading import Event
import pytest
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
def background(window, qtbot):
started, release = Event(), Event()
calls=[]
def verify(request):
calls.append(request.block_name)
if request.block_name=='Beta':
started.set()
assert release.wait(5)
return VerifyResult('CHECKED')
window.verifier=verify
window._run(['Beta','Gamma'],maintenance=True)
qtbot.waitUntil(started.is_set)
return release,calls
def finish(window, qtbot, release):
release.set()
window.icdb_task.resume()
qtbot.waitUntil(lambda:not window._icdb_active() and not window.busy)
qtbot.waitUntil(lambda:window.pool.activeThreadCount()==0)
def test_stop_whole_queue_does_not_resume_background_checks(qtbot,tmp_path,monkeypatch):
window=load_window(qtbot,tmp_path,monkeypatch)
release,calls=background(window,qtbot)
try:
window._start(lambda:None,lambda _:None)
qtbot.waitUntil(lambda:bool(window.native_queue.pending))
window.stop_button.click()
release.set()
qtbot.waitUntil(lambda:not window._icdb_active() and not window.busy)
assert calls==['Beta'],f'Cancelled queue still ran: {calls}'
finally:finish(window,qtbot,release)
def test_check_progress_survives_queued_verify(qtbot,tmp_path,monkeypatch):
window=load_window(qtbot,tmp_path,monkeypatch,
status_refresher=lambda names,path:{name:'PENDING' for name in names})
release,calls=background(window,qtbot)
try:
assert not window.icdb_progress.isHidden()
window._run(['Gamma'])
assert not window.icdb_progress.isHidden(),'Queued verify hid the active check progress'
finally:finish(window,qtbot,release)
def test_release_failure_is_not_labelled_as_read_write_prompt(qtbot,tmp_path,monkeypatch):
window=load_window(qtbot,tmp_path,monkeypatch,verifier=lambda request:VerifyResult(
'FAIL',error_category='DATABASE_SAFETY_STOP',safe_to_continue=False,
stderr='PCB_RELEASE_UNCONFIRMED: launcher still running'))
window._run(['Beta'],maintenance=True)
qtbot.waitUntil(lambda:not window._icdb_active())
cell=window.cbb_table.item(window._row_by_name['Beta'],3)
assert '读写确认' not in cell.text(),cell.text()
def test_pending_check_skips_a_target_that_has_become_ready(qtbot,tmp_path,monkeypatch):
window=load_window(qtbot,tmp_path,monkeypatch)
release,calls=background(window,qtbot)
try:
window.icdb_task.pause()
release.set()
qtbot.waitUntil(lambda:len(window.icdb_task.results)==1 and not window.icdb_task.running)
window._apply_refreshed_records((('Gamma',),{'Gamma':'READY'},{},''))
assert 'Gamma' in window.ready_names
window.icdb_task.resume()
qtbot.waitUntil(lambda:not window._icdb_active())
assert calls==['Beta'],f'Already READY target was opened again: {calls}'
finally:finish(window,qtbot,release)
def test_worker_refresh_excludes_ready_before_any_gui_result_callback(qtbot,tmp_path,monkeypatch):
window=load_window(qtbot,tmp_path,monkeypatch,
status_refresher=lambda names,path:{name:'READY' for name in names})
release,calls=background(window,qtbot)
try:
window._start(lambda:window._read_affected_records(('Gamma',)),lambda payload:None)
qtbot.waitUntil(lambda:bool(window.native_queue.pending))
release.set()
qtbot.waitUntil(lambda:not window._icdb_active() and not window.busy)
assert window._records_by_name['Gamma'].status=='UNKNOWN'
assert calls==['Beta']
assert window.icdb_task.results[1].status=='SKIPPED'
assert 'READY' in window.icdb_task.results[1].stderr
finally:finish(window,qtbot,release)
def test_another_library_ready_status_cannot_skip_this_library_target(qtbot,tmp_path,monkeypatch):
window=load_window(qtbot,tmp_path,monkeypatch)
release,calls=background(window,qtbot)
try:
window._publish_check_statuses('other.lmc',{'Gamma':'READY'})
release.set()
qtbot.waitUntil(lambda:not window._icdb_active())
assert calls==['Beta','Gamma']
finally:finish(window,qtbot,release)
@pytest.mark.parametrize('detail,safe,expected',[
('Continue to open the design with read/write access permission?',True,'读写确认'),
('PCB_RELEASE_UNCONFIRMED: launcher still running',False,'释放未确认'),
('ICDB_RELEASE_UNCONFIRMED: database still occupied',False,'释放未确认'),
('PCB_SESSION_ACTIVE: target already open',True,'会话或数据库状态待确认'),
])
def test_safety_stop_label_tracks_actual_reason(qtbot,tmp_path,monkeypatch,detail,safe,expected):
window=load_window(qtbot,tmp_path,monkeypatch,verifier=lambda request:VerifyResult(
'FAIL',error_category='DATABASE_SAFETY_STOP',safe_to_continue=safe,stderr=detail))
window._run(['Beta'],maintenance=True)
qtbot.waitUntil(lambda:not window._icdb_active())
cell=window.cbb_table.item(window._row_by_name['Beta'],3)
assert expected in cell.text()
assert cell.toolTip()==detail
assert cell.background().color().name()=='#fff8e1'
+54
View File
@@ -152,6 +152,60 @@ def test_idle_guard_queries_supported_native_process_names(recovery_files, monke
assert any("Name='viewdraw.exe'" in query for query in queries)
def test_idle_guard_ignores_unrelated_project_and_prefix_sibling(recovery_files, monkeypatch):
from cbb_refresh_verify.backup_recovery import _idle_check
from cbb_refresh_verify import mentor_adapter
request, original, _ = recovery_files
unrelated = original.parent.with_name(original.parent.name+'Old')/'PCB/A.pcb'
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [(123, '', str(unrelated))])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda name:
[(123, 'ExpeditionPCB.exe', f'ExpeditionPCB.exe "{unrelated}" -ReusableCircuit', 0)]
if name == 'ExpeditionPCB.exe' else [])
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
def test_idle_guard_rejects_exact_target_process(recovery_files, monkeypatch):
from cbb_refresh_verify.backup_recovery import _idle_check
from cbb_refresh_verify import mentor_adapter
request, original, _ = recovery_files
target = original.parent/'PCB/A.pcb'
monkeypatch.setattr(mentor_adapter, 'pcb_processes', lambda: [])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda name:
[(123, 'ExpeditionPCB.exe', f'ExpeditionPCB.exe "{target}" -ReusableCircuit', 0)]
if name == 'ExpeditionPCB.exe' else [])
with pytest.raises(ValueError, match='TARGET_NATIVE_OWNER_ACTIVE'):
_idle_check(request.lmc_file, original, target)
def test_prelaunch_recovery_rejection_has_no_unreleased_session(recovery_files):
from cbb_refresh_verify.backup_recovery import recover_from_backup
request, _, source = recovery_files
def reject(*args): raise ValueError('target unavailable before launch')
result = recover_from_backup(request, source, idle_check=reject,
verifier=lambda *a, **k: pytest.fail('prelaunch rejection must not start native'))
assert result.status == 'BLOCKED'
assert result.safe_to_continue
def test_report_write_failure_does_not_lose_prelaunch_release_fact(recovery_files, monkeypatch):
from cbb_refresh_verify.backup_recovery import recover_from_backup
import win32event
from uuid import uuid4
create_mutex = win32event.CreateMutex
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
create_mutex(security, owned, name+'-test-'+uuid4().hex))
request, _, source = recovery_files
original_write = Path.write_text
def write(path, *args, **kwargs):
if path.name == 'recovery-result.json': raise OSError('report disk unavailable')
return original_write(path, *args, **kwargs)
monkeypatch.setattr(Path, 'write_text', write)
def reject(*args): raise ValueError('prelaunch unavailable')
result = recover_from_backup(request, source, idle_check=reject)
assert result.status == 'BLOCKED' and result.safe_to_continue
assert 'report disk unavailable' in result.stderr
def test_copy_refuses_directory_junction_before_copying(tmp_path):
import subprocess
from cbb_refresh_verify.backup_recovery import _copy_verified
+2 -2
View File
@@ -99,7 +99,7 @@ def test_timeout_isolated_and_later_item_continues(tmp_path):
assert records[1].status == "PENDING"
def test_protocol_path_mismatch_stops_repeating_same_global_failure(tmp_path):
def test_protocol_path_mismatch_records_each_queried_item(tmp_path):
class BrokenProtocolBridge:
def __init__(self):
self.requests = []
@@ -116,7 +116,7 @@ def test_protocol_path_mismatch_stops_repeating_same_global_failure(tmp_path):
['A', 'B', 'C'], lmc, tmp_path / 'scan.jsonl'
)
assert bridge.requests == ['A']
assert bridge.requests == ['A', 'B', 'C']
assert [record.status for record in records] == ['MALFORMED'] * 3
+91
View File
@@ -0,0 +1,91 @@
import pytest
def test_constructor_releases_private_desktop_when_process_launch_fails(monkeypatch):
import cbb_refresh_verify.desktop_worker as module
class Handle:
def __init__(self):
self.closed = False
def Close(self):
self.closed = True
def CloseDesktop(self):
self.closed = True
desktop = Handle()
job = Handle()
monkeypatch.setattr(module.win32service, 'CreateDesktop', lambda *args: desktop)
monkeypatch.setattr(module.win32job, 'CreateJobObject', lambda *args: job)
monkeypatch.setattr(module.win32process, 'STARTUPINFO', lambda: type('Startup', (), {})())
monkeypatch.setattr(module.win32process, 'CreateProcess',
lambda *args: (_ for _ in ()).throw(RuntimeError('launch failed')))
with pytest.raises(RuntimeError, match='launch failed') as caught:
module.DesktopWorker(['worker.exe'], 'PrivateDesk')
assert desktop.closed is True
assert job.closed is True
assert caught.value.worker_launch_release == {
'process_created': False, 'safe_to_continue': True, 'worker_exited': True, 'remaining_pids': []}
def test_partial_launch_cleanup_never_claims_native_descendants_released(monkeypatch):
import cbb_refresh_verify.desktop_worker as module
class Handle:
def Close(self): pass
def CloseDesktop(self): pass
class Thread:
def Close(self): raise OSError('thread handle cleanup failed')
monkeypatch.setattr(module.win32service, 'CreateDesktop', lambda *args: Handle())
monkeypatch.setattr(module.win32job, 'CreateJobObject', lambda *args: Handle())
monkeypatch.setattr(module.win32process, 'STARTUPINFO', lambda: type('Startup', (), {})())
monkeypatch.setattr(module.win32process, 'CreateProcess', lambda *args: (Handle(), Thread(), 123, 456))
terminated = []
monkeypatch.setattr(module.win32process, 'TerminateProcess', lambda *args: terminated.append(args))
with pytest.raises(OSError, match='thread handle cleanup failed') as caught:
module.DesktopWorker(['worker.exe'], 'PrivateDesk')
assert caught.value.worker_launch_release == {
'process_created': True, 'safe_to_continue': False, 'worker_exited': False, 'remaining_pids': [123]}
assert len(terminated) == 1
def test_release_probe_allows_measured_owner_helper_startup_time(monkeypatch):
import cbb_refresh_verify.desktop_worker as module
from cbb_refresh_verify import owner_probe
worker = module.DesktopWorker.__new__(module.DesktopWorker)
worker.pid = 123
worker._closed = True
worker._exit_code = 1
def query(names, *, timeout_seconds):
# Real helper measured ~4.75s including interpreter + COM startup.
if timeout_seconds < 5:
raise RuntimeError('OWNER_QUERY_TIMEOUT')
return []
monkeypatch.setattr(owner_probe, 'query_owners', query)
assert worker.automation_release_state() == {'safe_to_continue': True, 'remaining_pids': []}
def test_library_flag_loads_ui_dependencies_before_creating_private_desktop(monkeypatch):
import builtins
import win32service
import cbb_refresh_verify.mentor_adapter as module
created = []
original_import = builtins.__import__
def deny_pywinauto(name, *args, **kwargs):
if name == 'pywinauto' or name.startswith('pywinauto.'):
raise ImportError('pywinauto unavailable')
return original_import(name, *args, **kwargs)
monkeypatch.setattr(builtins, '__import__', deny_pywinauto)
monkeypatch.setattr(win32service, 'CreateDesktop',
lambda *args: created.append(args))
with pytest.raises(ImportError, match='pywinauto unavailable'):
module.read_library_flag('library.lmc', 'Block')
assert created == []
+338
View File
@@ -0,0 +1,338 @@
import importlib
import importlib.util
from pathlib import Path
import pytest
@pytest.fixture
def diagnostic():
assert importlib.util.find_spec('cbb_refresh_verify.diagnostic_open') is not None, 'diagnostic open module is missing'
return importlib.import_module('cbb_refresh_verify.diagnostic_open')
@pytest.fixture
def job(tmp_path):
project = tmp_path / 'IP101GR'
pcb = project / 'PCB/IP101GR.pcb'
pcb.parent.mkdir(parents=True)
pcb.write_bytes(b'pcb')
return {'project': str(project / 'IP101GR.prj'), 'pcb': str(pcb), 'root': str(tmp_path / 'evidence'),
'desktop': 'CbbDiagnosticTest', 'timeout': .03}
def write_logs(job, *, pid=42, foreign=False, success=True):
project = Path(job['project']).parent
logdir = Path(job['pcb']).parent / 'LogFiles'
logdir.mkdir(parents=True, exist_ok=True)
pcb = str(Path(job['pcb'])) if not foreign else str(project.parent / 'other/PCB/IP101GR.pcb')
(logdir / 'PCBAutoSave.txt').write_text('Job Name: ' + pcb + '\n', encoding='utf-8')
(logdir / 'PCBLogFile.txt').write_text('Successfully read the design.\n' if success else 'Loading\n', encoding='utf-8')
database = str(project / 'database') if not foreign else str(project.parent / 'other/database')
logs = project / 'database/cdbsvr/log/current'
logs.mkdir(parents=True, exist_ok=True)
(logs / 'current.txt').write_text(
f'S: Project path [{database}] on file system [NTFS]\n'
f'S: Project file (.prj) path [{project / "IP101GR.prj"}] on file system [NTFS]\n'
f'S: Started up automatically by iCDB Client: ABS:ABS:{pid}\n'
'S: iCDB database loaded\n'
f'SC[455]: Registered sub-client [Expedition PCB_123] with ID [1] for session ID [455] host [Abs] user [ABS] process ID [{pid}]\n',
encoding='utf-8')
def test_old_success_logs_are_not_current_open_evidence(diagnostic, job):
write_logs(job)
baseline = diagnostic.snapshot_diagnostic_logs(job)
assert diagnostic._load_evidence(job, 42, baseline) is None
@pytest.mark.parametrize('pid,foreign,success', [(99, False, True), (42, True, True), (42, False, False)])
def test_foreign_pid_path_or_incomplete_load_cannot_pass(diagnostic, job, pid, foreign, success):
baseline = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job, pid=pid, foreign=foreign, success=success)
assert diagnostic._load_evidence(job, 42, baseline) is None
def test_current_full_path_and_pcb_pid_logs_prove_open_only(diagnostic, job):
baseline = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
evidence = diagnostic._load_evidence(job, 42, baseline)
assert evidence['pcb'] == job['pcb']
assert evidence['pcb_pid'] == 42
def test_old_prefix_in_appended_log_cannot_supply_target_identity(diagnostic, job):
write_logs(job)
baseline = diagnostic.snapshot_diagnostic_logs(job)
for path in Path(job['project']).parent.rglob('*.txt'):
with path.open('a', encoding='utf-8') as output:
output.write('unrelated new record\n')
assert diagnostic._load_evidence(job, 42, baseline) is None
def frame(job, *, title='IP101GR'):
return {'hwnd': 10, 'pid': 42, 'class': 'Afx:123',
'text': f'Expedition PCB - Reusable Block - [{title}]', 'enabled': True,
'children': [{'hwnd': 11, 'class': 'MDIClient', 'text': '', 'parent': 10},
{'hwnd': 12, 'class': 'Afx:document', 'text': title, 'parent': 11}]}
def test_target_title_without_target_mdi_does_not_pass(diagnostic, job):
window = frame(job)
window['children'][1]['text'] = 'another_project'
assert diagnostic._target_frame([window], Path(job['pcb']).stem) is None
class Session:
instances = []
def __init__(self, job, pid, launcher):
self.alive = True
self.closed = False
self.posted = []
self.instances.append(self)
def pcb_alive(self):
return self.alive
def launcher_alive(self):
return self.alive
def post(self, hwnd, message):
self.posted.append((hwnd, message))
self.alive = False
def close(self):
self.closed = True
def test_unknown_prompt_is_preserved_and_never_closed(diagnostic, job, monkeypatch):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job),
{'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': 'Unknown question', 'children': []}])
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
assert Session.instances[-1].posted == []
assert Session.instances[-1].closed
def test_success_posts_one_exact_close_and_reports_only_open_check(diagnostic, job, monkeypatch):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)] if Session.instances[-1].alive else [])
outcome = diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
assert outcome['status'] == 'PASS'
assert outcome['check'] == 'native_open_only'
assert outcome['native_processes_exited'] is True
assert outcome['library_ownership'] == 'NOT_ASSESSED'
assert Session.instances[-1].posted == [(10, 0x10)]
assert Session.instances[-1].closed
def test_transient_startup_window_cannot_abort_before_target_is_loaded(diagnostic, job, monkeypatch):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
calls = []
def windows(pid):
calls.append(True)
if len(calls) == 1:
return [{'hwnd': 20, 'pid': 42, 'class': 'VendorSplash', 'text': '', 'children': []}]
return [frame(job)] if Session.instances[-1].alive else []
monkeypatch.setattr(diagnostic, '_windows', windows)
job['timeout'] = 1
assert diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)['status'] == 'PASS'
assert Session.instances[-1].posted == [(10, 0x10)]
def test_native_caption_variant_uses_proven_target_mdi(diagnostic, job, monkeypatch):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
target = frame(job)
target['text'] = 'Expedition PCB - [IP101GR]'
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [target] if Session.instances[-1].alive else [])
assert diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)['status'] == 'PASS'
def test_cancel_does_not_wait_for_open_timeout(diagnostic, job, monkeypatch):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
cancel = Path(job['root']).parent / 'cancel'
cancel.touch()
job['cancel_signal'] = str(cancel)
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [])
with pytest.raises(RuntimeError, match='VERIFY_CANCELLED'):
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
assert Session.instances[-1].posted == []
assert Session.instances[-1].closed
def test_cancel_after_close_request_still_waits_for_own_launcher_exit(diagnostic, job, monkeypatch):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
cancel = Path(job['root']).parent / 'cancel'
job['cancel_signal'] = str(cancel)
class DelayedLauncher(Session):
polls = 0
def post(self, hwnd, message):
super().post(hwnd, message)
cancel.touch()
def launcher_alive(self):
self.polls += 1
return self.polls < 3
monkeypatch.setattr(diagnostic, '_NativeSession', DelayedLauncher)
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)] if Session.instances[-1].alive else [])
assert diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)['status'] == 'PASS'
assert Session.instances[-1].polls >= 3
@pytest.mark.parametrize('owner,window_class', [(10, 'VendorModal'), (0, 'VendorModal'),
(0, 'Internet Explorer_Hidden')])
def test_unknown_custom_owned_window_blocks_close(diagnostic, job, monkeypatch, owner, window_class):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job),
{'hwnd': 20, 'pid': 42, 'class': window_class, 'text': 'Unclassified prompt',
'owner': owner, 'enabled': True, 'children': []}])
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
assert Session.instances[-1].posted == []
def test_empty_desktop_resets_stale_win32_last_error(diagnostic, monkeypatch):
import win32api
import win32gui
import pywintypes
seen = []
def empty(callback, context):
seen.append(win32api.GetLastError())
raise pywintypes.error(0, 'EnumWindows', 'empty desktop')
monkeypatch.setattr(win32gui, 'EnumWindows', empty)
win32api.SetLastError(170)
assert diagnostic._windows(42) == []
assert seen == [0]
def test_missing_launcher_cannot_claim_verified_native_release(diagnostic, job):
with pytest.raises(RuntimeError, match='DIAGNOSTIC_LAUNCHER_REQUIRED'):
diagnostic._NativeSession(job, 42, None)
def test_buffered_full_pcb_path_must_be_verified_after_normal_close(diagnostic, job, monkeypatch):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
autosave = Path(job['pcb']).parent / 'LogFiles/PCBAutoSave.txt'
autosave.write_text('', encoding='utf-8')
class BufferedSession(Session):
def post(self, hwnd, message):
super().post(hwnd, message)
autosave.write_text('Job Name: ' + job['pcb'] + '\n', encoding='utf-8')
monkeypatch.setattr(diagnostic, '_NativeSession', BufferedSession)
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)] if Session.instances[-1].alive else [])
outcome = diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
assert outcome['status'] == 'PASS'
assert Session.instances[-1].posted == [(10, 0x10)]
def test_large_unrelated_history_does_not_block_current_evidence(diagnostic, job):
logs = Path(job['project']).parent / 'database/cdbsvr/log'
for index in range(270):
directory = logs / f'2000-01-01 00.00.00-{index:05}'
directory.mkdir(parents=True)
(directory / '2000.01.01.txt').write_bytes(b'old unrelated history\n' * 14000)
baseline = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
assert diagnostic._load_evidence(job, 42, baseline) is not None
def test_pcb_logs_follow_actual_pcb_directory(diagnostic, job):
pcb = Path(job['pcb']).parent.parent / 'AlternativePCB/IP101GR.pcb'
pcb.parent.mkdir()
pcb.write_bytes(b'pcb')
job['pcb'] = str(pcb)
baseline = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
assert diagnostic._load_evidence(job, 42, baseline)['pcb'] == str(pcb)
def test_only_exact_owned_save_prompt_gets_no_after_diagnostic_close(diagnostic, job, monkeypatch):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
class SaveSession(Session):
closing = False
def post(self, hwnd, message):
self.posted.append((hwnd, message))
if message == 0x10:
self.closing = True
else:
self.alive = False
closing_scans = []
def windows(pid):
state = Session.instances[-1]
if not state.closing:
return [frame(job)]
closing_scans.append(True)
if len(closing_scans) == 1:
return [{'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': '',
'owner': 10, 'children': []}]
return [{'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB',
'owner': 10, 'children': [
{'hwnd': 30, 'class': 'Static', 'text': 'Do you want to save the reusable block cell?', 'id': -1},
{'hwnd': 31, 'class': 'Button', 'text': '&No', 'id': 7}]}]
monkeypatch.setattr(diagnostic, '_NativeSession', SaveSession)
monkeypatch.setattr(diagnostic, '_windows', windows)
outcome = diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
assert outcome['status'] == 'PASS'
assert Session.instances[-1].posted == [(10, 0x10), (31, 0xF5)]
def test_no_pass_when_normal_close_never_flushes_full_pcb_path(diagnostic, job, monkeypatch):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
(Path(job['pcb']).parent / 'LogFiles/PCBAutoSave.txt').write_bytes(b'')
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)] if Session.instances[-1].alive else [])
with pytest.raises(RuntimeError, match='fresh full PCB path not confirmed after close'):
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
assert Session.instances[-1].posted == [(10, 0x10)]
@pytest.mark.parametrize('filename,accepted', [('IP101GR.pcb', True), ('Foreign.pcb', False)])
def test_standard_save_question_requires_exact_target_filename(diagnostic, job, monkeypatch, filename, accepted):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
class SaveSession(Session):
closing = False
def post(self, hwnd, message):
self.posted.append((hwnd, message))
if message == 0x10:
self.closing = True
else:
self.alive = False
def windows(pid):
if not Session.instances[-1].closing:
return [frame(job)]
return [{'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB', 'owner': 10,
'children': [{'hwnd': 30, 'class': 'Static', 'text': f'Save changes to {filename}?', 'id': -1},
{'hwnd': 31, 'class': 'Button', 'text': '否(&N)', 'id': 7},
{'hwnd': 32, 'class': 'Button', 'text': '是(&Y)', 'id': 6},
{'hwnd': 33, 'class': 'Button', 'text': '取消', 'id': 2}]}]
monkeypatch.setattr(diagnostic, '_NativeSession', SaveSession)
monkeypatch.setattr(diagnostic, '_windows', windows)
if accepted:
assert diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)['status'] == 'PASS'
assert Session.instances[-1].posted == [(10, 0x10), (31, 0xF5)]
else:
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
assert Session.instances[-1].posted == [(10, 0x10)]
def test_recycled_window_from_another_pid_never_receives_close(diagnostic, monkeypatch):
import win32process
session = diagnostic._NativeSession.__new__(diagnostic._NativeSession)
session.pid = 42
session.pcb_alive = lambda: True
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 99))
with pytest.raises(RuntimeError, match='DIAGNOSTIC_STALE_WINDOW'):
session.post(10, 0x10)
+74 -1
View File
@@ -412,6 +412,79 @@ def test_agent_start_failure_releases_listener(tmp_path):
DialogAgentClient.start(FailedWorker(), tmp_path)
def _slow_start_client(tmp_path, monkeypatch, *, delay, stop=None):
import socket
from types import SimpleNamespace
from cbb_refresh_verify import dialog_agent as module
client = DialogAgentClient.prepare(tmp_path, desktop_name='test')
client.listener.close()
elapsed = [0.0]
class Listener:
closed = False
def settimeout(self, timeout): self.timeout = timeout
def accept(self):
if elapsed[0] < delay:
elapsed[0] += self.timeout
if stop is not None and elapsed[0] >= .4: stop.set()
raise socket.timeout()
return SimpleNamespace(setsockopt=lambda *a: None), None
def close(self): self.closed = True
class Channel:
def __init__(self, connection): pass
def receive(self, timeout): return {'token': client.paths.token}
def send(self, *a): pass
def close(self): pass
client.listener = Listener()
monkeypatch.setattr(module, 'JsonChannel', Channel)
monkeypatch.setattr(module.time, 'monotonic', lambda: elapsed[0])
monkeypatch.setattr(DialogAgentClient, 'prepare', classmethod(lambda cls, *a, **k: client))
worker = SimpleNamespace(name='test', start_companion=lambda command: None)
return client, worker, elapsed
def test_frozen_agent_can_initialize_after_the_old_ten_second_deadline(tmp_path, monkeypatch):
client, worker, elapsed = _slow_start_client(tmp_path, monkeypatch, delay=12)
assert DialogAgentClient.start(worker, tmp_path) is client
assert elapsed[0] >= 12 and client.channel is not None
assert client.timeout_seconds == 2 # Normal IPC does not inherit the startup budget.
def test_agent_startup_wait_responds_to_cancel_without_starting_pcb(tmp_path, monkeypatch):
import pytest
from threading import Event
stop = Event()
client, worker, elapsed = _slow_start_client(tmp_path, monkeypatch, delay=100, stop=stop)
with pytest.raises(InterruptedError, match='VERIFY_CANCELLED'):
DialogAgentClient.start(worker, tmp_path, stop=stop)
assert elapsed[0] < 1 and client.listener.closed
def test_agent_startup_still_has_an_absolute_deadline(tmp_path, monkeypatch):
import pytest
client, worker, elapsed = _slow_start_client(tmp_path, monkeypatch, delay=100)
with pytest.raises(TimeoutError):
DialogAgentClient.start(worker, tmp_path)
assert 29 <= elapsed[0] <= 31 and client.listener.closed
def test_cancellation_during_authenticated_handshake_never_releases_startup(tmp_path, monkeypatch):
import pytest
from threading import Event
from cbb_refresh_verify import dialog_agent as module
stop = Event()
client, worker, _ = _slow_start_client(tmp_path, monkeypatch, delay=0)
class Channel:
def __init__(self, connection): pass
def receive(self, timeout):
stop.set()
return {'token': client.paths.token}
def close(self): pass
monkeypatch.setattr(module, 'JsonChannel', Channel)
with pytest.raises(InterruptedError, match='VERIFY_CANCELLED'):
DialogAgentClient.start(worker, tmp_path, stop=stop)
assert client.channel is None and client.listener.closed
def test_memory_channel_timeout_is_bounded_and_partial_packets_survive():
import socket
import pytest
@@ -436,7 +509,7 @@ def test_loopback_connection_rejects_wrong_agent_token(tmp_path):
import socket
import pytest
from cbb_refresh_verify.dialog_agent import JsonChannel, DialogAgentProtocolError
client = DialogAgentClient.prepare(tmp_path, desktop_name='test', timeout_seconds=.3)
client = DialogAgentClient.prepare(tmp_path, desktop_name='test', timeout_seconds=2)
wrong = JsonChannel(socket.create_connection(('127.0.0.1', client.paths.port), timeout=1))
try:
wrong.send({'token': 'not-the-agent'})
+12
View File
@@ -86,6 +86,18 @@ def test_probe_keeps_visible_non_dialog_classes():
assert snapshots[0].process_name == "proc-1010.exe"
def test_pid_scope_excludes_foreign_dialog_before_child_or_uia_read():
gui = FakeGui({10: {'class_name': '#32770', 'text': 'owned'},
20: {'class_name': '#32770', 'text': 'other project'}})
class Uia:
def controls(self, hwnd):
assert hwnd == 10, 'Foreign project was probed'
return ()
probe = make_probe(gui, (20, 10), Uia())
assert [w.hwnd for w in probe.capture(PHASE, pids={1010})] == [10]
assert probe.capture(PHASE, pids=set()) == ()
def test_disappearing_window_is_skipped_without_hiding_other_windows():
gui = FakeGui({
10: {"class_name": "GXWND", "text": "gone"},
+31
View File
@@ -0,0 +1,31 @@
import json
from types import SimpleNamespace
import pytest
@pytest.mark.parametrize('cancel,gate_present', [(False, False), (True, False), (True, True)])
def test_worker_waits_for_cold_agent_but_cancellation_never_opens_pcb(tmp_path, monkeypatch, cancel, gate_present):
from cbb_refresh_verify import mentor_adapter as adapter
import pythoncom
gate, stop = tmp_path/'start.signal', tmp_path/'cancel.signal'
if gate_present: gate.touch()
if cancel: stop.touch()
clock, opened = [0.0], []
def advance(seconds):
clock[0] += seconds
if not cancel and clock[0] >= 20: gate.touch()
monkeypatch.setattr(adapter, 'time', SimpleNamespace(monotonic=lambda: clock[0], sleep=advance,
strftime=lambda *_: 'test'))
monkeypatch.setattr(pythoncom, 'CoInitialize', lambda: None)
monkeypatch.setattr(pythoncom, 'CoUninitialize', lambda: None)
monkeypatch.setattr(adapter, 'execute_job', lambda *args: opened.append(True) or {'status': 'PASS'})
job = tmp_path/'request.json'
job.write_text(json.dumps({'root': str(tmp_path), 'block_name': 'fixture',
'start_gate': str(gate), 'cancel_signal': str(stop)}), encoding='utf-8')
result = adapter.worker_main(job)
assert result == (1 if cancel else 0)
assert opened == ([] if cancel else [True])
if cancel:
outcome = json.loads((tmp_path/'outcome.json').read_text('utf-8'))
assert 'VERIFY_CANCELLED' in outcome['stderr']
+2 -1
View File
@@ -72,7 +72,8 @@ def test_serial_guard_covers_preflight_and_content_check(tmp_path, monkeypatch):
try:
second = runner.run_verify(VerifyRequest(tmp_path/'lib.lmc', 'second', tmp_path/'evidence'))
assert second.status == 'BLOCKED'
assert not second.safe_to_continue
assert second.safe_to_continue
assert second.error_category == 'NATIVE_CHANNEL_BUSY'
assert calls == ['first']
finally:
release.set()
+95 -4
View File
@@ -50,7 +50,7 @@ def test_failed_startup_normally_closes_owned_empty_pcb(tmp_path, monkeypatch, t
@pytest.mark.parametrize('obstacle', ['baseline', 'wrong_path', 'path_prefix', 'desktop', 'address',
'dialog', 'document_title', 'mdi_document', 'disabled', 'no_diagnosis'])
'dialog', 'document_title', 'mdi_document', 'disabled'])
def test_failed_startup_preserves_unconfirmed_or_busy_session(tmp_path, monkeypatch, obstacle):
import win32gui
from cbb_refresh_verify import native_repair_ui
@@ -79,6 +79,97 @@ def test_failed_startup_preserves_unconfirmed_or_busy_session(tmp_path, monkeypa
assert not messages
def test_owned_empty_shell_closes_without_an_icdb_diagnosis(tmp_path, monkeypatch):
job, records, messages = startup_fixture(tmp_path, monkeypatch)
(tmp_path/'diagnostics/icdb-recovery.json').unlink()
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'CLOSED' and not records and len(messages) == 1
def read_write_fixture(tmp_path, monkeypatch):
import win32gui, win32con
from cbb_refresh_verify.post_repair_consent import PROMPT_TEXT
job, records, messages = startup_fixture(tmp_path, monkeypatch)
(tmp_path/'diagnostics/icdb-recovery.json').unlink()
visible = {100, 200}
classes = {100: 'Afx:main', 200: '#32770', 201: 'Button', 202: 'Button', 203: 'Static'}
names = {100: 'Expedition PCB', 200: 'Expedition PCB', 201: 'Yes', 202: 'No', 203: PROMPT_TEXT}
identifiers = {201: 6, 202: 7, 203: 65535}
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(h, arg) for h in tuple(visible)])
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda h, fn, arg:
[fn(c, arg) for c in (201, 202, 203)] if h == 200 else None)
monkeypatch.setattr(win32gui, 'GetClassName', classes.__getitem__)
monkeypatch.setattr(win32gui, 'GetWindowText', names.__getitem__)
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', identifiers.__getitem__)
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda h: h != 100 or 200 not in visible)
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda h: h in visible or h in identifiers)
def post(hwnd, message, *_):
messages.append((hwnd, message))
if hwnd == 202 and message == win32con.BM_CLICK:
visible.remove(200)
elif hwnd == 100 and message == win32con.WM_CLOSE:
records.clear()
monkeypatch.setattr(win32gui, 'PostMessage', post)
return job, records, messages, names, visible
def test_captured_read_write_question_is_declined_and_own_empty_shell_exits(tmp_path, monkeypatch):
import win32con
job, records, messages, _, _ = read_write_fixture(tmp_path, monkeypatch)
# A pre-existing address must not prevent cancelling our own attempted open.
address = tmp_path/'database/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_text('existing foreign or stale address')
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'CLOSED' and result['release']['safe_to_continue']
assert messages == [(202, win32con.BM_CLICK), (100, win32con.WM_CLOSE)]
assert not records and address.read_text() == 'existing foreign or stale address'
assert result['cancelled_prompt'] == 'read_write_access'
@pytest.mark.parametrize('obstacle', ['text', 'foreign_pid', 'baseline', 'wrong_path', 'desktop', 'stuck'])
def test_read_write_cancel_never_accepts_unconfirmed_or_unclosed_prompt(tmp_path, monkeypatch, obstacle):
import win32gui, win32process, win32con
from cbb_refresh_verify import native_repair_ui
job, records, messages, names, _ = read_write_fixture(tmp_path, monkeypatch)
if obstacle == 'text': names[203] += ' Different recovery operation.'
if obstacle == 'foreign_pid':
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda h: (1, 99 if h == 200 else 12))
if obstacle == 'wrong_path': records[0] = (12, records[0][1], 'other.pcb -ReusableCircuit', 11)
if obstacle == 'desktop': monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'Default')
if obstacle == 'stuck':
monkeypatch.setattr(win32gui, 'PostMessage', lambda h, m, *_: messages.append((h, m)))
result = failed_session.close_failed_startup(job, 12,
baseline_pids=(12,) if obstacle == 'baseline' else (), timeout_seconds=0)
assert result['status'] == 'RETAINED' and records
assert messages == ([(202, win32con.BM_CLICK)] if obstacle == 'stuck' else [])
def test_version_choice_is_cancelled_without_selecting_or_confirming_a_version(tmp_path, monkeypatch):
import win32gui, win32con
from test_pcb_version_choice import captured
job, records, messages, _, visible = read_write_fixture(tmp_path, monkeypatch)
snapshot = captured()
children = [c for c in snapshot.controls if c.handle and c.handle != snapshot.hwnd]
mapping = {300+i: c for i, c in enumerate(children)}
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda h, fn, arg:
[fn(c, arg) for c in mapping] if h == 200 else None)
monkeypatch.setattr(win32gui, 'GetClassName', lambda h: mapping[h].class_name if h in mapping else
'#32770' if h == 200 else 'Afx:main')
monkeypatch.setattr(win32gui, 'GetWindowText', lambda h: mapping[h].name if h in mapping else
'Database Restoration' if h == 200 else 'Expedition PCB')
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda h: mapping[h].control_id)
cancel = next(h for h, c in mapping.items() if c.control_id == 2)
def post(h, m, *_):
messages.append((h, m))
if h == cancel: visible.remove(200)
elif h == 100: records.clear()
monkeypatch.setattr(win32gui, 'PostMessage', post)
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'CLOSED' and result['cancelled_prompt'] == 'pcb_version_choice'
assert messages == [(cancel, win32con.BM_CLICK), (100, win32con.WM_CLOSE)]
def test_requested_close_without_exit_is_not_reported_closed(tmp_path, monkeypatch):
import win32gui
job, records, messages = startup_fixture(tmp_path, monkeypatch)
@@ -169,13 +260,13 @@ def test_failed_startup_accepts_current_owned_database_failure_dialog(tmp_path,
@pytest.mark.parametrize('pid,phase', [(99, 'PCB_STARTING'), (12, 'SAVING')])
def test_failed_startup_rejects_unrelated_failure_dialog(tmp_path, monkeypatch, pid, phase):
def test_unrelated_failure_record_is_not_needed_to_close_own_empty_shell(tmp_path, monkeypatch, pid, phase):
job, records, messages = startup_fixture(tmp_path, monkeypatch)
(tmp_path/'diagnostics/icdb-recovery.json').unlink()
(tmp_path/'dialogs.jsonl').write_text(json.dumps({
'pid': pid, 'phase': phase, 'error_code': 'MENTOR_DATABASE_LOAD_FAILED'})+'\n')
assert failed_session.close_failed_startup(job, 12, timeout_seconds=0)['status'] == 'RETAINED'
assert not messages
assert failed_session.close_failed_startup(job, 12, timeout_seconds=0)['status'] == 'CLOSED'
assert len(messages) == 1 and not records
@pytest.mark.parametrize('exits', [True, False])
+159 -194
View File
@@ -1,194 +1,159 @@
"""Batch ICDB inspection never opens PCB or dispatches Repair."""
from dataclasses import replace
import json
import pytest
from test_maintenance_entry import case, no_native_launch
from test_maintenance_diagnosis import inspection
@pytest.mark.parametrize('scenario,status,category,safe', [
('healthy', 'CHECKED', '', True),
('fault', 'FAIL', 'ICDB_REPAIR_REQUIRED', True),
('busy', 'BLOCKED', 'ICDB_DATABASE_IN_USE', True),
('unknown', 'FAIL', 'ICDB_INSPECTION_UNCONFIRMED', True),
('unexpected_repair', 'FAIL', 'ICDB_INSPECTION_UNCONFIRMED', True),
('missing_exit_proof', 'FAIL', 'ICDB_INSPECTION_UNCONFIRMED', False),
('not_launched', 'FAIL', 'ICDB_INSPECTION_UNCONFIRMED', True),
('unreleased', 'FAIL', 'ICDB_INSPECTION_UNCONFIRMED', False),
('cancelled', 'CANCELLED', '', True),
])
def test_batch_check_only_loads_native_inspection(case, monkeypatch, scenario, status, category, safe):
from cbb_refresh_verify import verify_runner as runner, native_repair, maintenance_entry as entry
from test_native_occupancy import output
request, _, address = case
calls = []
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('check opened PCB'))
monkeypatch.setattr(entry, 'assert_native_idle', lambda: pytest.fail('check used host-wide owner gate'))
def native(target, root, **kw):
assert kw['inspection_only'] is True and not kw.get('maintenance_context')
calls.append('inspect')
record = inspection(target, fault=scenario == 'fault')
if scenario == 'busy':
record.update(status='IN_USE', output=output(target.project, target.database, busy=True))
if scenario in ('unknown', 'unreleased'):
record.update(status='UNCONFIRMED', output='No conclusive native response')
if scenario == 'unreleased': record['release']['native_exited'] = False
if scenario == 'cancelled': record.update(status='CANCELLED')
if scenario == 'unexpected_repair': record.update(status='REPAIRED', repair_requested=True)
if scenario == 'missing_exit_proof': return {}
if scenario == 'not_launched': return {'status': 'BLOCKED', 'native_started': False}
return record
monkeypatch.setattr(native_repair, 'run_native_repair', native)
result = runner.run_verify(replace(request, auto_repair=True))
assert calls == ['inspect']
assert (result.status, result.error_category, result.safe_to_continue) == (status, category, safe)
assert result.library_flag == 'UNKNOWN' and result.recovery_attempts == ()
assert address.read_bytes() == b'old server address - preserved'
record = json.loads(result.evidence_path.read_text('utf-8'))
assert record['operation'] == 'icdb_batch_check' and record['automatic_repair'] is False
@pytest.mark.parametrize('case_type', ['no_layout', 'no_pcb', 'no_icdb', 'ambiguous_repair_targets'])
def test_inspection_does_not_require_repair_admission(case, monkeypatch, case_type):
from cbb_refresh_verify import verify_runner as runner, native_repair
request, project, address = case
if case_type == 'no_layout': (project.parent/'PCB/Layout/LayoutDB.lyt').unlink()
if case_type == 'no_pcb': (project.parent/'PCB/IP101GR.pcb').unlink()
if case_type == 'no_icdb': (project.parent/'database/icdb.dat').unlink()
if case_type == 'ambiguous_repair_targets':
address.unlink()
(project.parent/'PCB/pcb.prj').write_text('KEY iCDBDir "database"\n')
db = project.parent/'PCB/database'; db.mkdir(); (db/'icdb.dat').touch()
calls = []
def native(target, *a, **kw):
assert kw['inspection_only'] is True and target.project == project
calls.append('inspect')
return inspection(target)
monkeypatch.setattr(native_repair, 'run_native_repair', native)
result = runner.run_verify(request)
assert calls == ['inspect']
assert result.recovery_attempts == ()
@pytest.mark.parametrize('before_launch', [True, False])
def test_cancellation_never_dispatches_repair_or_reports_a_clean_check(case, monkeypatch, before_launch):
from threading import Event
from cbb_refresh_verify import verify_runner as runner, native_repair
request, _, _ = case
stop = Event(); calls = []
if before_launch: stop.set()
def native(target, *a, **kw):
assert kw['inspection_only'] is True
calls.append('inspect'); stop.set()
return inspection(target)
monkeypatch.setattr(native_repair, 'run_native_repair', native)
result = runner.run_verify(request, stop=stop)
assert result.status == 'CANCELLED' and result.safe_to_continue
assert calls == ([] if before_launch else ['inspect'])
def test_released_icdb_fault_continues_the_check_batch(case, monkeypatch):
from cbb_refresh_verify import verify_runner as runner, native_repair
request, _, _ = case
calls = []
def native(target, root, **kw):
assert kw['inspection_only'] is True
calls.append('inspect')
return inspection(target, fault=len(calls) == 1)
monkeypatch.setattr(native_repair, 'run_native_repair', native)
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **k: pytest.fail('check opened PCB'))
results = runner.run_batch([request, request])
assert calls == ['inspect', 'inspect']
assert [result.status for result in results] == ['FAIL', 'CHECKED']
def test_inspection_ignores_other_pcb_and_skips_exclusive_repair_probe(tmp_path, monkeypatch):
import win32con
from test_native_repair import repair_worker_fixture
from test_native_occupancy import output
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
job.write_text(json.dumps(data), encoding='utf-8')
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter.pcb_processes', lambda: [(999, 'other.pcb', '')])
monkeypatch.setattr('cbb_refresh_verify.native_repair.check_repair_access',
lambda *a: pytest.fail('inspection used exclusive Repair admission'))
monkeypatch.setattr(ui, '_repair_command', lambda *a: pytest.fail('inspection resolved Repair command'))
monkeypatch.setattr(ui, '_native_output', lambda *_: output(data['project'], data['database'], busy=True))
assert ui.repair_worker_main(job) == 0
assert actions == [(100, win32con.WM_CLOSE)]
def test_ui_check_summary_reports_findings_and_never_claims_repair(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
from PySide6.QtWidgets import QMessageBox
requests, prompts = [], []
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda req: (requests.append(req) or VerifyResult('FAIL',
error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。')),
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (prompts.append(a[2]) or QMessageBox.Yes))
window.search_edit.setText('Beta')
window.icdb_repair_button.click(); qtbot.waitUntil(lambda: not window.busy)
assert requests[0].maintenance and not requests[0].auto_repair
assert '批量检查' in window.icdb_repair_button.text()
assert not any('手动备份' in text for text in prompts)
assert window.summary.windowTitle() == 'ICDB 批量检查结果'
assert '发现问题 1' in window.summary.text()
assert '修复并校验通过' not in window.summary.detailedText()
@pytest.mark.parametrize('category,label', [('ICDB_DATABASE_IN_USE', '占用 1'),
('ICDB_INSPECTION_UNCONFIRMED', '无法确认 1')])
def test_busy_or_unknown_inspection_is_not_labelled_as_database_damage(qtbot, tmp_path, monkeypatch, category, label):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: VerifyResult('FAIL', error_category=category, stderr='暂未完成检查。'),
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
window.search_edit.setText('Beta')
window.icdb_repair_button.click(); qtbot.waitUntil(lambda: not window.busy)
assert label in window.summary.text()
assert 'ICDB 问题' not in window.cbb_table.item(window._row_by_name['Beta'], 3).text()
def test_missing_pcb_is_skipped_from_icdb_batch_check_and_restore(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.models import CbbRecord
from cbb_refresh_verify.verify_runner import VerifyResult
calls = []
window = load_window(qtbot, tmp_path, monkeypatch,
records=(CbbRecord('Missing', 'Power', status='PENDING'),),
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('CHECKED')),
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
assert not window.icdb_repair_button.isEnabled()
assert not window.batch_button.isEnabled() and not window.backup_restore_button.isEnabled()
assert calls == []
def test_missing_project_rows_are_excluded_from_icdb_batch_check(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.models import CbbRecord
from cbb_refresh_verify.verify_runner import VerifyResult
window = load_window(qtbot, tmp_path, monkeypatch,
records=(CbbRecord('Missing', 'Power', status='PENDING'),
CbbRecord('Good', 'Power', status='PENDING')),
verifier=lambda req: VerifyResult('CHECKED'),
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
window.skipped_names.add('Missing')
window._update()
assert window._maintenance_names() == ['Good']
def test_check_reports_describe_inspection_without_pcb_verification(case, tmp_path):
from cbb_refresh_verify.verify_runner import write_batch_report, failure_report_path, VerifyResult
request, _, _ = case
report = write_batch_report([request], [VerifyResult('FAIL',
error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。')], tmp_path/'reports')
full = report.read_text('utf-8-sig')
failed = failure_report_path(report).read_text('utf-8-sig')
assert 'ICDB 批量检查' in full and 'Project Integration' not in full
assert 'ICDB 检查异常' in failed and '发现问题: 1' in failed
assert 'ICDB已修复待校验' not in failed
"""Batch ICDB checks open diagnostically without dispatching Repair."""
from dataclasses import replace
import json
import pytest
from test_maintenance_entry import case, no_native_launch
@pytest.mark.parametrize('scenario,status,category,safe', [
('healthy', 'CHECKED', '', True),
('fault', 'FAIL', 'ICDB_REPAIR_REQUIRED', True),
('generic', 'FAIL', 'MENTOR_DATABASE_LOAD_FAILED', True),
('unreleased', 'FAIL', 'MENTOR_DATABASE_LOAD_FAILED', False),
('cancelled', 'CANCELLED', '', True),
])
def test_batch_check_opens_pcb_without_repair(case, monkeypatch, scenario, status, category, safe):
from cbb_refresh_verify import verify_runner as runner, native_repair, maintenance_entry as entry
from test_icdb_open_check import NATIVE_ERROR
request, _, address = case
calls = []
def open_pcb(probe, **kwargs):
assert probe.diagnostic_only and not probe.maintenance and not probe.auto_repair
calls.append('open')
return runner.VerifyResult('PASS' if scenario=='healthy' else 'CANCELLED' if scenario=='cancelled' else 'FAIL',
stderr=NATIVE_ERROR if scenario=='fault' else '' if scenario in ('healthy','cancelled') else 'Failed to open document.',
error_category='' if scenario in ('healthy','cancelled') else 'MENTOR_DATABASE_LOAD_FAILED',
safe_to_continue=scenario!='unreleased')
monkeypatch.setattr(runner,'_run_verify_serialized',open_pcb)
monkeypatch.setattr(native_repair,'run_native_repair',lambda *a,**k:pytest.fail('scan requested Project Backup'))
monkeypatch.setattr(entry,'assert_native_idle',lambda:pytest.fail('scan used host-wide owner gate'))
result=runner.run_verify(replace(request,auto_repair=True))
assert calls==['open']
assert (result.status,result.error_category,result.safe_to_continue)==(status,category,safe)
assert result.library_flag=='UNKNOWN' and result.recovery_attempts==()
assert address.read_bytes()==b'old server address - preserved'
record=json.loads(result.evidence_path.read_text('utf-8'))
assert record['operation']=='icdb_batch_check' and record['automatic_repair'] is False
@pytest.mark.parametrize('before_launch',[True,False])
def test_cancellation_never_dispatches_repair_or_reports_a_clean_check(case,monkeypatch,before_launch):
from threading import Event
from cbb_refresh_verify import verify_runner as runner
request,_,_=case
stop=Event();calls=[]
if before_launch:stop.set()
def open_pcb(probe,**kwargs):
calls.append('open');stop.set()
return runner.VerifyResult('PASS')
monkeypatch.setattr(runner,'_run_verify_serialized',open_pcb)
result=runner.run_verify(request,stop=stop)
assert result.status=='CANCELLED' and result.safe_to_continue
assert calls==([] if before_launch else ['open'])
def test_released_icdb_fault_continues_the_check_batch(case,monkeypatch):
from cbb_refresh_verify import verify_runner as runner
from test_icdb_open_check import NATIVE_ERROR
request,_,_=case
calls=[]
def open_pcb(probe,**kwargs):
calls.append('open')
return runner.VerifyResult('FAIL',stderr=NATIVE_ERROR) if len(calls)==1 else runner.VerifyResult('PASS')
monkeypatch.setattr(runner,'_run_verify_serialized',open_pcb)
results=runner.run_batch([request,request])
assert calls==['open','open']
assert [result.status for result in results]==['FAIL','CHECKED']
def test_inspection_ignores_other_pcb_and_skips_exclusive_repair_probe(tmp_path, monkeypatch):
import win32con
from test_native_repair import repair_worker_fixture
from test_native_occupancy import output
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
job.write_text(json.dumps(data), encoding='utf-8')
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter.pcb_processes', lambda: [(999, 'other.pcb', '')])
monkeypatch.setattr('cbb_refresh_verify.native_repair.check_repair_access',
lambda *a: pytest.fail('inspection used exclusive Repair admission'))
monkeypatch.setattr(ui, '_repair_command', lambda *a: pytest.fail('inspection resolved Repair command'))
monkeypatch.setattr(ui, '_native_output', lambda *_: output(data['project'], data['database'], busy=True))
assert ui.repair_worker_main(job) == 0
assert actions == [(100, win32con.WM_CLOSE)]
def test_ui_check_summary_reports_findings_and_never_claims_repair(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
from PySide6.QtWidgets import QMessageBox
requests, prompts = [], []
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda req: (requests.append(req) or VerifyResult('FAIL',
error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。')),
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (prompts.append(a[2]) or QMessageBox.Yes))
window.search_edit.setText('Beta')
window.icdb_repair_button.click(); qtbot.waitUntil(lambda: not window._icdb_active())
assert requests[0].maintenance and not requests[0].auto_repair
assert '批量检查' in window.icdb_repair_button.text()
assert not any('手动备份' in text for text in prompts)
assert window.summary.windowTitle() == 'ICDB 批量检查结果'
assert '发现问题 1' in window.summary.text()
assert '修复并校验通过' not in window.summary.detailedText()
@pytest.mark.parametrize('category,label', [('ICDB_DATABASE_IN_USE', '占用 1'),
('ICDB_INSPECTION_UNCONFIRMED', '无法确认 1')])
def test_busy_or_unknown_inspection_is_not_labelled_as_database_damage(qtbot, tmp_path, monkeypatch, category, label):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: VerifyResult('FAIL', error_category=category, stderr='暂未完成检查。'),
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
window.search_edit.setText('Beta')
window.icdb_repair_button.click(); qtbot.waitUntil(lambda: not window._icdb_active())
assert label in window.summary.text()
assert 'ICDB 问题' not in window.cbb_table.item(window._row_by_name['Beta'], 3).text()
def test_missing_pcb_is_skipped_from_icdb_batch_check_and_restore(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.models import CbbRecord
from cbb_refresh_verify.verify_runner import VerifyResult
calls = []
window = load_window(qtbot, tmp_path, monkeypatch,
records=(CbbRecord('Missing', 'Power', status='PENDING'),),
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('CHECKED')),
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
assert not window.icdb_repair_button.isEnabled()
assert not window.batch_button.isEnabled() and not window.backup_restore_button.isEnabled()
assert calls == []
def test_missing_project_rows_are_excluded_from_icdb_batch_check(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.models import CbbRecord
from cbb_refresh_verify.verify_runner import VerifyResult
window = load_window(qtbot, tmp_path, monkeypatch,
records=(CbbRecord('Missing', 'Power', status='PENDING'),
CbbRecord('Good', 'Power', status='PENDING')),
verifier=lambda req: VerifyResult('CHECKED'),
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
window.skipped_names.add('Missing')
window._update()
assert window._maintenance_names() == ['Good']
def test_check_reports_describe_inspection_without_pcb_verification(case, tmp_path):
from cbb_refresh_verify.verify_runner import write_batch_report, failure_report_path, VerifyResult
request, _, _ = case
report = write_batch_report([request], [VerifyResult('FAIL',
error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。')], tmp_path/'reports')
full = report.read_text('utf-8-sig')
failed = failure_report_path(report).read_text('utf-8-sig')
assert 'ICDB 批量检查' in full and 'Project Integration' not in full
assert 'PCB 打开检查' in full and 'Project Backup 加载检查' not in full
assert 'ICDB 检查异常' in failed and '发现问题: 1' in failed
assert 'ICDB已修复待校验' not in failed
+133
View File
@@ -0,0 +1,133 @@
"""PCB open errors identify ICDB findings by native content, never by code alone."""
from dataclasses import replace
import json
import pytest
from test_maintenance_entry import case, no_native_launch
NATIVE_ERROR = (
'Database cannot be loaded and the server cannot be started, the project will not be opened. '
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue. "
'(Database [C:\\isolated\\Work\\database\\icdb.dat] in old, unsupported format)')
@pytest.mark.parametrize('message,expected', [
(NATIVE_ERROR, True),
('Unable to open iCDB connection.', True),
('iCDB database check FAILED', True),
('iCDB database check PASSED', False),
('0x8004021E: Failed to open document.', False),
('ICDB_REPAIR_REQUIRED: Failed to open document.', False),
('Cannot open [C:\\icdb\\icdb.dat].', False),
('PCB file was not found. Evidence: C:\\icdb\\result.json', False),
])
def test_error_content_requires_an_icdb_failure_message(message, expected):
from cbb_refresh_verify.icdb_recovery import icdb_error_content
assert bool(icdb_error_content(message)) is expected
def test_unknown_icdb_description_in_an_actual_open_error_is_retained():
from cbb_refresh_verify.icdb_recovery import icdb_error_content
assert icdb_error_content('iCDB connection: E_NEW_NATIVE_CODE', error_message=True)
@pytest.mark.parametrize('mode', ['append', 'rewrite', 'retained', 'unchanged'])
def test_native_error_content_is_from_this_open_attempt(tmp_path, mode):
from cbb_refresh_verify.icdb_recovery import snapshot_log, read_icdb_error
path = tmp_path/'PCBLogFile.txt'
previous = 'old header\n'+NATIVE_ERROR+'\n' if mode in ('retained','unchanged') else 'old header\n'
path.write_text(previous, 'utf-8')
baseline = snapshot_log(path)
if mode == 'append': path.write_text(previous+NATIVE_ERROR, 'utf-8')
elif mode == 'rewrite': path.write_text('new header\n'+NATIVE_ERROR, 'utf-8')
elif mode == 'retained': path.write_text('new header\n'+NATIVE_ERROR+'\nNormal startup', 'utf-8')
assert bool(read_icdb_error(path, baseline)) is (mode in ('append','rewrite'))
@pytest.mark.parametrize('failure,category', [(NATIVE_ERROR,'ICDB_REPAIR_REQUIRED'),
('0x8004021E: Failed to open document.','MENTOR_DATABASE_LOAD_FAILED')])
def test_batch_scan_opens_without_repair_and_classifies_native_content(case, monkeypatch, failure, category):
from cbb_refresh_verify import maintenance_entry as entry, verify_runner as runner, native_repair
request, _, address = case
probes=[]
monkeypatch.setattr(native_repair,'run_native_repair',lambda *a,**k:pytest.fail('scan dispatched Project Backup'))
def diagnose(probe, **kw):
probes.append(probe)
return runner.VerifyResult('FAIL',stderr=failure,error_category='MENTOR_DATABASE_LOAD_FAILED')
monkeypatch.setattr(runner,'run_verify',diagnose)
result=entry.run_icdb_check(replace(request,auto_repair=True))
assert len(probes)==1 and probes[0].diagnostic_only and not probes[0].maintenance
assert not probes[0].auto_repair and not probes[0].native_lm_verify
assert result.status=='FAIL' and result.error_category==category and result.safe_to_continue
assert result.library_flag=='UNKNOWN' and result.recovery_attempts==()
assert address.read_bytes()==b'old server address - preserved'
def test_scan_uses_the_current_open_evidence_even_when_popup_is_generic(case, monkeypatch):
from cbb_refresh_verify import maintenance_entry as entry, verify_runner as runner
request, _, _=case
def diagnose(probe, **kw):
root=probe.evidence_dir/'verify-current'; (root/'diagnostics').mkdir(parents=True)
(root/'diagnostics/icdb-error-content.json').write_text(json.dumps(
{'native_message':NATIVE_ERROR,'source':'PCBLogFile.txt'}),'utf-8')
result=root/'result.json'; result.write_text('{}','utf-8')
return runner.VerifyResult('FAIL',stderr='Problem encountered while opening one of the database files.',
evidence_path=result,error_category='MENTOR_DATABASE_LOAD_FAILED')
monkeypatch.setattr(runner,'run_verify',diagnose)
result=entry.run_icdb_check(request)
assert result.error_category=='ICDB_REPAIR_REQUIRED' and NATIVE_ERROR in result.stderr
def test_scan_does_not_reuse_an_older_operation_error_evidence(case, monkeypatch):
from cbb_refresh_verify import maintenance_entry as entry, verify_runner as runner
request,_,_=case
root=request.evidence_dir/'older-operation';(root/'diagnostics').mkdir(parents=True)
(root/'diagnostics/icdb-error-content.json').write_text(json.dumps({'native_message':NATIVE_ERROR}),'utf-8')
result=root/'result.json';result.write_text('{}','utf-8')
monkeypatch.setattr(runner,'run_verify',lambda *a,**k:runner.VerifyResult('FAIL',
stderr='Failed to open document.',error_category='MENTOR_DATABASE_LOAD_FAILED',evidence_path=result))
scanned=entry.run_icdb_check(request)
assert scanned.error_category=='MENTOR_DATABASE_LOAD_FAILED'
def test_error_capture_retains_the_new_native_corruption_detail(tmp_path):
from cbb_refresh_verify.icdb_recovery import snapshot_log
from cbb_refresh_verify.verify_diagnostics import collect_native_failure_logs
pcb=tmp_path/'PCB/CBB.pcb'; log=pcb.parent/'LogFiles/PCBLogFile.txt'
log.parent.mkdir(parents=True)
evidence=tmp_path/'evidence'; (evidence/'diagnostics').mkdir(parents=True)
baseline=snapshot_log(log)
(evidence/'diagnostics/startup-log-baseline.json').write_text(json.dumps(
{'source':str(log),'baseline':baseline}),'utf-8')
log.write_text(NATIVE_ERROR,'utf-8')
collect_native_failure_logs(pcb,evidence)
record=json.loads((evidence/'diagnostics/icdb-error-content.json').read_text('utf-8'))
assert record['source']==str(log) and record['native_message']==NATIVE_ERROR
@pytest.mark.parametrize('scenario', ['current', 'other_pid', 'old', 'other_database'])
def test_repeated_failure_uses_only_this_pcb_process_icdb_log(tmp_path, scenario):
import os,time
from cbb_refresh_verify.verify_diagnostics import collect_native_client_error
root=tmp_path/'evidence'; (root/'diagnostics').mkdir(parents=True)
logs=tmp_path/'Client/Logs'
pid=123
started=time.time_ns()-1_000_000_000
folder=logs/('2026-11-05 12.00.00-'+str(321 if scenario=='other_pid' else pid))
folder.mkdir(parents=True)
source=folder/'2026.11.05.iCDBManager.txt'
database=tmp_path/'Work/database'
message=f'SingleFile: ERROR: Database [{database}/icdb.dat] in old, unsupported format'
if scenario=='other_database': message=message.replace(str(database),'C:/other/database')
source.write_text(f'PID [{pid}]\n'+message,'utf-8')
if scenario=='old':os.utime(source,ns=(started-1_000_000_000,started-1_000_000_000))
(root/'diagnostics/native-client-context.json').write_text(json.dumps(
{'native_pid':pid,'started_ns':started,'client_log_root':str(logs),'database':str(database)}),'utf-8')
collect_native_client_error(root)
result=root/'diagnostics/icdb-error-content.json'
assert result.exists() is (scenario=='current')
if result.exists():
record=json.loads(result.read_text('utf-8'))
assert record['native_pid']==pid and 'unsupported format' in record['native_message']
+11 -13
View File
@@ -75,11 +75,15 @@ def test_loading_a_different_library_clears_old_management_block(qtbot, tmp_path
def test_targeted_native_idle_ignores_unrelated_native_command(tmp_path, monkeypatch):
from cbb_refresh_verify import maintenance_entry as entry
from cbb_refresh_verify.native_repair import RepairTarget
project = tmp_path/'target.prj'; project.touch()
work = tmp_path/'target/Work'; work.mkdir(parents=True)
library = tmp_path/'library.lmc'; library.touch()
project = work/'target.prj'
project.write_text(f'KEY CentralLibrary "{library}"\n', encoding='utf-8')
other_pcb = tmp_path/'other/Work/PCB/other.pcb'
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names: [
{'pid': 10, 'name': 'ExpeditionPCB.exe', 'command': 'ExpeditionPCB.exe other.pcb'},
{'pid': 10, 'name': 'ExpeditionPCB.exe', 'command': f'ExpeditionPCB.exe "{other_pcb}"'},
])
entry.assert_native_idle(RepairTarget(project, tmp_path/'database'))
entry.assert_native_idle(RepairTarget(project, work/'database'))
def test_maintenance_guard_does_not_scan_other_cbb_projects(case, monkeypatch):
@@ -148,20 +152,14 @@ def test_live_writer_keeps_execution_lock_without_a_permanent_diagnostic_blocker
if owner: owner['handle'].Close()
def test_healthy_native_inspection_with_old_address_does_not_lock_management(case, monkeypatch):
def test_healthy_open_with_old_address_does_not_lock_management(case, monkeypatch):
from cbb_refresh_verify import native_repair, verify_runner as runner, library_lock as locks
from test_native_occupancy import output
request, project, address = case
def inspect(target, *a, **kw):
assert kw['inspection_only']
return {'inspection_only': True, 'repair_requested': False, 'repair_required': False,
'status': 'NOT_IN_USE', 'native_pid': 777, 'native_exit_code': 0,
'project': str(target.project), 'database': str(target.database),
'output': output(target.project, target.database), 'release': {'native_exited': True}}
monkeypatch.setattr(native_repair, 'run_native_repair', inspect)
monkeypatch.setattr(runner, '_run_verify_serialized', lambda *a, **kw: runner.VerifyResult('PASS'))
monkeypatch.setattr(native_repair, 'run_native_repair', lambda *a, **kw: pytest.fail('scan requested Project Backup'))
result = runner.run_verify(request)
assert result.status == 'CHECKED' and result.safe_to_continue and address.exists()
assert not result.stderr and '无需修复' in result.stdout
assert not result.stderr and '未发现 ICDB 错误' in result.stdout
assert not locks.blocker_path(request.lmc_file).exists()
with locks.LibraryLock(request.lmc_file): pass
+19 -1
View File
@@ -134,6 +134,24 @@ def test_release_proof_checks_addresses_and_exclusive_databases(tmp_path, monkey
assert proof['exclusive_files'] == [str(library)]
def test_release_does_not_resolve_every_unrelated_generated_file(tmp_path, monkeypatch):
from pathlib import Path
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.owner_probe as probe
monkeypatch.setattr(probe, 'query_owners', lambda *_: [])
library = tmp_path/'lib.lmc'; library.touch()
outputs = tmp_path/'generated'; outputs.mkdir()
for index in range(100): (outputs/f'{index}.log').touch()
database = tmp_path/'database/icdb.dat'; database.parent.mkdir(); database.touch()
resolve = Path.resolve
def guarded(path, *a, **kw):
assert path.parent != outputs, 'Release resolved unrelated generated content'
return resolve(path, *a, **kw)
monkeypatch.setattr(Path, 'resolve', guarded)
with locks._prove_library_released(library) as proof:
assert set(proof['exclusive_files']) == {str(library), str(database)}
def test_scoped_release_ignores_another_cbb_address(tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.owner_probe as probe
@@ -261,7 +279,7 @@ def test_arbitrary_guard_filename_is_preserved_and_primary(tmp_path, monkeypatch
assert marker.name in manifest['files']
from contextlib import contextmanager
@contextmanager
def proof(*a): yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
def proof(*a, **kw): yield {'native_owners': [], 'addresses': [], 'exclusive_files': [str(library)]}
monkeypatch.setattr(locks, '_prove_library_released', proof)
with pytest.raises(locks.LibraryBusy):
locks.release_retained_library(library, tmp_path/'release')
+1 -1
View File
@@ -280,7 +280,7 @@ def test_takeover_preserves_old_checkpoint_until_every_guard_passes(case, monkey
if change == 'foreign_library': record['library'] = str(library.parent.parent/'foreign/mentor.lmc')
marker.write_text('broken json' if change == 'malformed' else json.dumps(record), encoding='utf-8')
old = marker.read_bytes()
monkeypatch.setattr(locks, '_supervisor_alive', lambda pid: change == 'live_foreign')
monkeypatch.setattr(locks, '_recorded_supervisor_alive', lambda record: change == 'live_foreign')
if change == 'guard_failure':
monkeypatch.setattr(entry, 'assert_native_idle', lambda: (_ for _ in ()).throw(ValueError('guard failed')))
archive = request.evidence_dir/'takeover'
+93
View File
@@ -0,0 +1,93 @@
"""Ownership scoping only: no native process or execution mutex is started."""
import json
from types import SimpleNamespace
import pytest
@pytest.fixture
def scope(tmp_path, monkeypatch):
from cbb_refresh_verify.native_repair import RepairTarget
from cbb_refresh_verify import native_management, native_engineering_identity
library = tmp_path/'a/lib.lmc'
library.parent.mkdir()
library.touch()
other = tmp_path/'b/lib.lmc'
other.parent.mkdir()
other.touch()
project = tmp_path/'work/main.prj'
project.parent.mkdir()
project.write_text(f'KEY CentralLibrary "{library}"\n')
target = RepairTarget(project, project.parent/'database')
monkeypatch.setattr(native_management, '_retained_workers', [])
monkeypatch.setattr(native_engineering_identity, '_retained_exports', [])
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_a, **_k: [])
return target, library, other
@pytest.mark.parametrize('kind', ['management', 'export'])
@pytest.mark.parametrize('ownership', ['same', 'other', 'unknown'])
def test_retained_native_ownership_is_scoped_only_with_proven_library(scope, monkeypatch, kind, ownership):
from cbb_refresh_verify import maintenance_entry as entry
target, library, other = scope
claimed = library if ownership == 'same' else other if ownership == 'other' else None
worker = SimpleNamespace(poll=lambda: None, cbb_library=claimed)
if kind == 'management':
monkeypatch.setattr('cbb_refresh_verify.native_management._retained_workers', [worker])
else:
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._retained_exports',
[(worker, {}, {'library': str(claimed)} if claimed else {})])
if ownership == 'other':
entry.assert_native_idle(target)
else:
with pytest.raises(Exception, match='(OWNER_ACTIVE|exporter)'):
entry.assert_native_idle(target)
@pytest.mark.parametrize('reference', ['missing', 'conflicting', 'invalid', 'empty_extra'])
def test_unproven_library_does_not_exclude_retained_workers(scope, monkeypatch, reference):
from cbb_refresh_verify import maintenance_entry as entry
target, library, other = scope
target.project.write_text('' if reference == 'missing' else
f'KEY CentralLibrary "{library}"\nKEY CentralLibrary "{other}"' if reference == 'conflicting' else
f'KEY CentralLibrary "{library}"\nKEY CentralLibrary ""' if reference == 'empty_extra' else
'KEY CentralLibrary "missing.lmc"')
monkeypatch.setattr('cbb_refresh_verify.native_management._retained_workers',
[SimpleNamespace(poll=lambda: None, cbb_library=other)])
with pytest.raises(ValueError, match='OWNER_ACTIVE'):
entry.assert_native_idle(target)
@pytest.mark.parametrize('source', ['project', 'pcb', 'database', 'lmc', 'shared', 'job', 'unknown', 'other'])
def test_native_commands_include_target_and_shared_library_ownership(scope, monkeypatch, tmp_path, source):
from cbb_refresh_verify import maintenance_entry as entry
target, library, other = scope
job = tmp_path/'request.json'
job.write_text(json.dumps({'library': str(library)}))
command = {
'project': f'ExpeditionPCB.exe "{target.project}"',
'pcb': f'ExpeditionPCB.exe "{target.project.parent / "PCB/board.pcb"}"',
'database': f'iCDBProjectBackup.exe -icdb="{target.database}"',
'lmc': f'LibraryManager.exe "{library}"',
'shared': f'viewdraw.exe -project="{library.parent / "SymbolLibs/database"}"',
'job': f'python.exe --management-worker "{job}"',
'unknown': 'ExpeditionPCB.exe',
'other': f'LibraryManager.exe "{other}"',
}[source]
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_a, **_k:
[{'pid': 987654, 'name': 'python.exe' if source == 'job' else 'ExpeditionPCB.exe',
'command': command}])
if source == 'other':
entry.assert_native_idle(target)
else:
with pytest.raises(ValueError, match='OWNER_ACTIVE'):
entry.assert_native_idle(target)
def test_no_target_keeps_global_retained_owner_guard(scope, monkeypatch):
from cbb_refresh_verify import maintenance_entry as entry
_, _, other = scope
monkeypatch.setattr('cbb_refresh_verify.native_management._retained_workers',
[SimpleNamespace(poll=lambda: None, cbb_library=other)])
with pytest.raises(ValueError, match='OWNER_ACTIVE'):
entry.assert_native_idle()
+55 -23
View File
@@ -31,12 +31,28 @@ def test_diagnostic_worker_closes_without_integration_save_or_config_edit(tmp_pa
def forbidden(*args, **kwargs):
pytest.fail('diagnosis attempted integration/save/config rewrite')
monkeypatch.setattr(adapter, 'ensure_pcb_central_library', forbidden)
monkeypatch.setattr(adapter, 'pcb_log_reports_integration_error', forbidden)
original_read = Path.read_bytes
def read_bytes(path):
if path.name in ('ForwardAnnotation.txt', 'MsgBoxResponse.log', 'PartPkg.log'):
pytest.fail('opening check read unrelated integration history')
return original_read(path)
monkeypatch.setattr(Path, 'read_bytes', read_bytes)
monkeypatch.setattr('cbb_refresh_verify.integration.refresh_integration', forbidden)
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.launch_save_helper', forbidden)
monkeypatch.setattr('cbb_refresh_verify.pcb_bridge.wait_for_target_document', forbidden)
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document', forbidden)
closes = []
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document',
lambda job, **kw: closes.append(job) or {'status': 'CLOSED'})
def check(job, pid, **kw):
assert pid == 2 and kw['launcher_process'].pid == 1
assert job['diagnostic_log_baseline']['started_ns']
closes.append(job)
kw['emit'](stage='diagnostic_wm_close')
return {'status': 'PASS', 'native_processes_exited': True}
monkeypatch.setattr('cbb_refresh_verify.diagnostic_open.check_target_window', check)
result = execute()
from cbb_refresh_verify.verify_runner import VerifyResult
assert VerifyResult(**result).status == 'PASS'
assert result['status'] == 'PASS'
assert len(closes) == 1
assert not any(e['stage'] in ('save_start', 'saved_and_closed') for e in events)
@@ -47,8 +63,13 @@ def test_diagnostic_close_failure_never_returns_healthy(tmp_path, monkeypatch):
job, events, execute = diagnostic_worker(tmp_path, monkeypatch)
job['diagnostic_only'] = True
closes = []
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document',
lambda *a, **kw: closes.append(a) or {'status': 'RETAINED'})
def check(*a, **kw):
closes.append(a)
kw['emit'](stage='diagnostic_wm_close')
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED')
monkeypatch.setattr('cbb_refresh_verify.diagnostic_open.check_target_window', check)
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_startup',
lambda *a, **kw: pytest.fail('must not send another close after WM_CLOSE'))
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
execute()
assert len(closes) == 1
@@ -71,6 +92,8 @@ def diagnostic_worker(tmp_path, monkeypatch):
job, events, execute = exercise_worker(tmp_path, monkeypatch)
(Path(job['pcb']).parent/'pcb.prj').write_text(
'KEY CentralLibrary "' + job['lmc_file'] + '"\n', encoding='utf-8')
monkeypatch.setattr('cbb_refresh_verify.diagnostic_open.check_target_window',
lambda *a, **kw: {'status': 'PASS', 'native_processes_exited': True})
return job, events, execute
@@ -98,19 +121,14 @@ def test_diagnostic_runner_skips_importer_and_ready_verification(tmp_path, monke
assert captured['diagnostic_only'] is True
def test_diagnostic_waits_for_normal_exit_after_close_returns(tmp_path, monkeypatch):
def test_diagnostic_cannot_pass_with_unconfirmed_process_exit(tmp_path, monkeypatch):
from cbb_refresh_verify import mentor_adapter as adapter
job, events, execute = diagnostic_worker(tmp_path, monkeypatch)
job['diagnostic_only'] = True
observations = []
def release(*a, **kw):
observations.append(True)
return {'safe_to_continue': len(observations) > 1}
monkeypatch.setattr(adapter, 'cleanup_verify_processes', release)
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document',
lambda *a, **kw: {'status': 'CLOSED'})
assert execute()['status'] == 'PASS'
assert len(observations) >= 2
monkeypatch.setattr(adapter, 'cleanup_verify_processes',
lambda *a, **kw: {'safe_to_continue': False, 'remaining_pids': [2]})
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
execute()
@pytest.mark.parametrize('when', ['document_ready', 'closing'])
@@ -123,17 +141,31 @@ def test_diagnostic_checks_late_startup_errors_before_declaring_healthy(tmp_path
source.parent.mkdir(exist_ok=True)
source.write_text("The last server session on different server machine lost the connection to the database. "
f"Machine:[fixture] Path:[{Path(job['project']).parent/'database'}] session:[current]", encoding='utf-8')
def document(*a, **kw):
if when == 'document_ready': late_fault()
return None, None, object()
closes = []
def close(*a, **kw):
def check(*a, **kw):
if when == 'document_ready':
late_fault()
raise RuntimeError(kw['error_reader']())
closes.append(True)
if when == 'closing': late_fault()
return {'status': 'CLOSED'}
monkeypatch.setattr('cbb_refresh_verify.pcb_bridge.wait_for_target_document', document)
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document', close)
kw['emit'](stage='diagnostic_wm_close')
late_fault()
return {'status': 'PASS', 'native_processes_exited': True}
monkeypatch.setattr('cbb_refresh_verify.diagnostic_open.check_target_window', check)
monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_startup',
lambda *a, **kw: {'status': 'CLOSED'})
with pytest.raises(RuntimeError, match='ICDB_REPAIR_REQUIRED'):
execute()
assert len(closes) == 1
assert len(closes) == (1 if when == 'closing' else 0)
assert not any(e['stage'] == 'diagnostic_complete' for e in events)
def test_diagnostic_snapshot_is_before_launch(tmp_path, monkeypatch):
from cbb_refresh_verify import mentor_adapter as adapter
job, events, execute = diagnostic_worker(tmp_path, monkeypatch)
job['diagnostic_only'] = True
def launch(*a):
assert job.get('diagnostic_log_baseline', {}).get('started_ns')
from types import SimpleNamespace
return SimpleNamespace(pid=1)
monkeypatch.setattr(adapter, 'launch_pcb_process', launch)
assert execute()['status'] == 'PASS'
+115 -115
View File
@@ -1,115 +1,115 @@
import json
from pathlib import Path
import pytest
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QMessageBox
def test_only_confirmed_maintenance_sets_explicit_flag(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
calls = []
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda req: (calls.append(req) or VerifyResult('FAIL', safe_to_continue=True)),
status_refresher=lambda names, path: {name: 'PENDING' for name in names})
window.search_edit.setText('Beta')
window.verify_all(); qtbot.waitUntil(lambda: not window.busy)
assert calls and calls[-1].maintenance is False
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.No)
window.repair_icdb_all(); assert len(calls) == 1
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
window.repair_icdb_all(); qtbot.waitUntil(lambda: not window.busy)
assert len(calls) == 2 and calls[-1].maintenance is True
@pytest.mark.parametrize('marker_kind', ['valid', 'foreign', 'malformed'])
def test_old_checkpoint_does_not_force_maintenance_or_disable_verify(qtbot, tmp_path, monkeypatch, marker_kind):
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path, _owners, _guard
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.verify_runner import VerifyResult
from cbb_refresh_verify.models import LibraryReadResult, CbbRecord
import cbb_refresh_verify.ui.main_window as ui
library = tmp_path/'library/mentor.lmc'; library.parent.mkdir(); library.touch()
(library.parent/'ReusableBlocksLP/IP101GR').mkdir(parents=True)
with LibraryLock(library, safe_to_release=lambda: False) as lock: pass
with _guard:
owner = _owners.pop(lock.key, None)
if owner: owner['handle'].Close()
marker = blocker_path(library)
if marker_kind == 'malformed': marker.write_text('{}')
if marker_kind == 'foreign':
record = json.loads(marker.read_text()); record['library'] = str(tmp_path/'foreign/mentor.lmc')
marker.write_text(json.dumps(record))
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *a: None)
calls = []
window = MainWindow(reader=lambda *a: LibraryReadResult((CbbRecord('IP101GR', 'Reusable Blocks', status='PENDING'),)),
verifier=lambda req: (calls.append(req) or VerifyResult('BLOCKED', safe_to_continue=False)),
status_refresher=lambda *a: {'IP101GR': 'PENDING'}, data_root=tmp_path/'data')
qtbot.addWidget(window)
window.lmc_edit.setText(str(library)); window.load_library()
qtbot.waitUntil(lambda: not window.busy)
assert window.release_library_button.isEnabled()
assert window.visible_records()[0].name == 'IP101GR'
assert window.visible_records()[0].status == 'PENDING'
assert not window._maintenance_recovery_view
window.select_visible_button.click()
assert window.icdb_repair_button.isEnabled()
assert window.batch_button.isEnabled() and window.selected_batch_button.isEnabled()
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
window.verify_selected(); qtbot.waitUntil(lambda: not window.busy)
assert len(calls) == 1 and calls[0].maintenance is False
assert window.selected_batch_button.isEnabled()
window.repair_icdb_all(); qtbot.waitUntil(lambda: not window.busy)
assert len(calls) == 2 and calls[1].maintenance is True
assert marker.exists()
def test_maintenance_summary_exposes_first_failure_reason(qtbot, tmp_path):
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.verify_runner import VerifyResult
window = MainWindow(data_root=tmp_path)
qtbot.addWidget(window)
window._global_icdb_run = True
detail = 'MAINTENANCE_TARGET_UNCONFIRMED: PCB 引用与当前工程不一致'
window._batch_done(([VerifyResult('BLOCKED', stderr=detail, safe_to_continue=False)], tmp_path/'batch.log'))
assert detail in window.summary.detailedText()
assert detail in window.output.toPlainText()
assert detail not in window.summary.text()
assert str(tmp_path) not in window.summary.text()
assert detail not in window.status_label.text()
assert '无法确认 1' in window.summary.text()
def test_safe_maintenance_reloads_authoritative_catalog_after_worker_finishes(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path, _owners, _guard
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.models import LibraryReadResult, CbbRecord
from cbb_refresh_verify.verify_runner import VerifyResult
import cbb_refresh_verify.ui.main_window as ui
library = tmp_path/'library/mentor.lmc'; library.parent.mkdir(); library.touch()
(library.parent/'ReusableBlocksLP/IP101GR').mkdir(parents=True)
with LibraryLock(library, safe_to_release=lambda: False) as lease: pass
with _guard:
owner = _owners.pop(lease.key, None)
if owner: owner['handle'].Close()
reads = []
def reader(path):
reads.append(path)
return LibraryReadResult((CbbRecord('IP101GR', 'Reusable Blocks', status='PENDING'),))
def verify(req):
assert req.maintenance
blocker_path(library).unlink() # Simulate normal cleanup at the injected boundary.
return VerifyResult('PASS', library_flag='GREEN')
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *a: None)
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
window = MainWindow(reader=reader, verifier=verify, data_root=tmp_path/'data',
status_refresher=lambda *a: {'IP101GR': 'READY'})
qtbot.addWidget(window)
window.lmc_edit.setText(str(library)); window.load_library(); qtbot.waitUntil(lambda: not window.busy)
assert len(reads) == 1
window.search_edit.setText('IP101')
window.repair_icdb_all()
qtbot.waitUntil(lambda: not window.busy)
assert window.visible_records()[0].status == 'READY'
assert not window._maintenance_recovery_view and window.search_edit.text() == 'IP101'
import json
from pathlib import Path
import pytest
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QMessageBox
def test_only_confirmed_maintenance_sets_explicit_flag(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
calls = []
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda req: (calls.append(req) or VerifyResult('FAIL', safe_to_continue=True)),
status_refresher=lambda names, path: {name: 'PENDING' for name in names})
window.search_edit.setText('Beta')
window.verify_all(); qtbot.waitUntil(lambda: not window.busy)
assert calls and calls[-1].maintenance is False
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.No)
window.repair_icdb_all(); assert len(calls) == 1
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
window.repair_icdb_all(); qtbot.waitUntil(lambda: not window._icdb_active())
assert len(calls) == 2 and calls[-1].maintenance is True
@pytest.mark.parametrize('marker_kind', ['valid', 'foreign', 'malformed'])
def test_old_checkpoint_does_not_force_maintenance_or_disable_verify(qtbot, tmp_path, monkeypatch, marker_kind):
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path, _owners, _guard
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.verify_runner import VerifyResult
from cbb_refresh_verify.models import LibraryReadResult, CbbRecord
import cbb_refresh_verify.ui.main_window as ui
library = tmp_path/'library/mentor.lmc'; library.parent.mkdir(); library.touch()
(library.parent/'ReusableBlocksLP/IP101GR').mkdir(parents=True)
with LibraryLock(library, safe_to_release=lambda: False) as lock: pass
with _guard:
owner = _owners.pop(lock.key, None)
if owner: owner['handle'].Close()
marker = blocker_path(library)
if marker_kind == 'malformed': marker.write_text('{}')
if marker_kind == 'foreign':
record = json.loads(marker.read_text()); record['library'] = str(tmp_path/'foreign/mentor.lmc')
marker.write_text(json.dumps(record))
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *a: None)
calls = []
window = MainWindow(reader=lambda *a: LibraryReadResult((CbbRecord('IP101GR', 'Reusable Blocks', status='PENDING'),)),
verifier=lambda req: (calls.append(req) or VerifyResult('BLOCKED', safe_to_continue=False)),
status_refresher=lambda *a: {'IP101GR': 'PENDING'}, data_root=tmp_path/'data')
qtbot.addWidget(window)
window.lmc_edit.setText(str(library)); window.load_library()
qtbot.waitUntil(lambda: not window.busy)
assert window.release_library_button.isEnabled()
assert window.visible_records()[0].name == 'IP101GR'
assert window.visible_records()[0].status == 'PENDING'
assert not window._maintenance_recovery_view
window.select_visible_button.click()
assert window.icdb_repair_button.isEnabled()
assert window.batch_button.isEnabled() and window.selected_batch_button.isEnabled()
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
window.verify_selected(); qtbot.waitUntil(lambda: not window.busy)
assert len(calls) == 1 and calls[0].maintenance is False
assert window.selected_batch_button.isEnabled()
window.repair_icdb_all(); qtbot.waitUntil(lambda: not window._icdb_active())
assert len(calls) == 2 and calls[1].maintenance is True
assert marker.exists()
def test_maintenance_summary_exposes_first_failure_reason(qtbot, tmp_path):
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.verify_runner import VerifyResult
window = MainWindow(data_root=tmp_path)
qtbot.addWidget(window)
window._global_icdb_run = True
detail = 'MAINTENANCE_TARGET_UNCONFIRMED: PCB 引用与当前工程不一致'
window._batch_done(([VerifyResult('BLOCKED', stderr=detail, safe_to_continue=False)], tmp_path/'batch.log'))
assert detail in window.summary.detailedText()
assert detail in window.output.toPlainText()
assert detail not in window.summary.text()
assert str(tmp_path) not in window.summary.text()
assert detail not in window.status_label.text()
assert '无法确认 1' in window.summary.text()
def test_open_check_preserves_verify_state_without_starting_an_extra_catalog_read(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path, _owners, _guard
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.models import LibraryReadResult, CbbRecord
from cbb_refresh_verify.verify_runner import VerifyResult
import cbb_refresh_verify.ui.main_window as ui
library = tmp_path/'library/mentor.lmc'; library.parent.mkdir(); library.touch()
(library.parent/'ReusableBlocksLP/IP101GR').mkdir(parents=True)
with LibraryLock(library, safe_to_release=lambda: False) as lease: pass
with _guard:
owner = _owners.pop(lease.key, None)
if owner: owner['handle'].Close()
reads = []
def reader(path):
reads.append(path)
return LibraryReadResult((CbbRecord('IP101GR', 'Reusable Blocks', status='PENDING'),))
def verify(req):
assert req.maintenance
blocker_path(library).unlink() # Simulate normal cleanup at the injected boundary.
return VerifyResult('CHECKED')
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *a: None)
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
window = MainWindow(reader=reader, verifier=verify, data_root=tmp_path/'data',
status_refresher=lambda *a: pytest.fail('An open check must not start a second native status read'))
qtbot.addWidget(window)
window.lmc_edit.setText(str(library)); window.load_library(); qtbot.waitUntil(lambda: not window.busy)
assert len(reads) == 1
window.search_edit.setText('IP101')
window.repair_icdb_all()
qtbot.waitUntil(lambda: not window._icdb_active())
assert window.visible_records()[0].status == 'PENDING' and len(reads) == 1
assert not window._maintenance_recovery_view and window.search_edit.text() == 'IP101'
+3 -3
View File
@@ -162,7 +162,7 @@ def test_update_failed_readd_keeps_removed_checkpoint_and_baseline(setup):
request, adapter, source = setup
adapter.fail_add = True
result = execute(replace(request, operation='update', source=source), adapter)
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
assert adapter.records == []
history = json.loads(result.evidence_path.read_text(encoding='utf-8'))['history']
assert 'removed' in [x['stage'] for x in history]
@@ -177,7 +177,7 @@ def test_lying_native_output_does_not_report_success(setup, operation):
request = replace(request, operation=operation, source=source,
name='New' if operation == 'add' else 'Block')
result = execute(request, adapter)
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
def test_unreleased_native_owner_prevents_postread_and_verification(setup):
@@ -265,7 +265,7 @@ def test_replaced_source_bytes_fail_identity_even_with_same_name(setup):
return result
adapter.add = wrong_source
result = execute(replace(request, operation='add', name='New', source=source), adapter)
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
def test_update_success_requires_same_identity_and_no_implicit_partition_move(setup):
+4 -2
View File
@@ -107,7 +107,8 @@ def test_native_registered_but_asset_mismatch_retains_recovery(transaction, corr
root, request, state = transaction
state['corrupt'] = corrupt
result = execute(root, request)
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
assert execute(root, request).status == 'BLOCKED'
def test_update_readd_failure_preserves_baseline_and_removed_checkpoint(transaction):
@@ -115,7 +116,8 @@ def test_update_readd_failure_preserves_baseline_and_removed_checkpoint(transact
assert execute(root, request).status == 'UPLOADED'
state['fail_add'] = True
result = execute(root, replace(request, operation='update'))
assert result.status == 'RECOVERY_REQUIRED' and not result.safe_to_continue
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
assert execute(root, replace(request, operation='update')).status == 'BLOCKED'
assert (result.evidence_path.parent/'library-baseline-manifest.json').exists()
assert not (result.evidence_path.parent/'library-before').exists()
assert 'removed' in [entry['stage'] for entry in json.loads(result.evidence_path.read_text())['history']]
+585
View File
@@ -0,0 +1,585 @@
"""Retry boundaries use fake native outcomes and temporary libraries only."""
import json
import os
from pathlib import Path
from types import SimpleNamespace
import pytest
from test_management import setup, execute
from test_management_native_transaction import transaction
@pytest.fixture
def isolated_mutex(monkeypatch):
import win32event
from uuid import uuid4
original = win32event.CreateMutex
suffix = uuid4().hex
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
original(security, owned, name + suffix))
def test_released_catalog_failure_does_not_retain_management_lease(setup, monkeypatch):
from cbb_refresh_verify.native_management import NativeManagementAdapter
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path
request, _, _ = setup
adapter = NativeManagementAdapter(mentor_home=request.library.parent)
monkeypatch.setattr(adapter, 'capabilities', lambda: {'remove': SimpleNamespace(supported=True)})
monkeypatch.setattr(adapter, '_worker', lambda *_: {
'success': False, 'safe_to_continue': True, 'detail': 'catalog read failed after exit'})
result = execute(request, adapter)
assert result.safe_to_continue
assert not blocker_path(request.library).exists()
with LibraryLock(request.library):
pass
@pytest.mark.parametrize('busy', [False, True])
def test_legacy_blocker_is_rechecked_before_management_without_inventing_new_owner(setup, monkeypatch, isolated_mutex, busy):
import cbb_refresh_verify.library_lock as locks
request, adapter, _ = setup
marker = locks.blocker_path(request.library)
legacy = {'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
'lease_id': 'eae80a06f23e4664b00c70b6bf81b01d', 'library': str(request.library),
'status': 'OWNER_RELEASE_UNCONFIRMED', 'pid': 57076, 'time': '2026-11-04T09:43:50.830958+00:00'}
marker.write_text(json.dumps(legacy), encoding='utf-8')
before = marker.read_bytes()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
address = request.library.parent/'database/cdbsvr/sAddress.adr'
if busy:
address.parent.mkdir(parents=True); address.write_bytes(b'actual address')
result = execute(request, adapter)
assert result.safe_to_continue, 'No new native session was started by a blocked release check'
assert result.evidence_path and result.evidence_path.is_file()
if busy:
assert result.status == 'BLOCKED' and adapter.calls == []
assert marker.read_bytes() == before and address.read_bytes() == b'actual address'
assert '地址' in result.detail
else:
assert result.status == 'REMOVED' and adapter.calls == ['remove']
assert result.release_proof['status'] == 'RELEASE_CONFIRMED'
archive = Path(result.release_proof['evidence_path']).with_name('blocker-before-0.json')
assert archive.read_bytes() == before and not marker.exists()
def test_busy_execution_channel_does_not_create_unreleased_management_owner(setup, monkeypatch):
import win32con, win32event
request, adapter, _ = setup
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *_: win32con.WAIT_TIMEOUT)
result = execute(request, adapter)
assert result.status == 'BLOCKED' and result.safe_to_continue and not adapter.calls
assert result.evidence_path.is_file()
def test_management_rechecks_retained_verify_lease_without_checkpoint(setup, monkeypatch, isolated_mutex):
import cbb_refresh_verify.library_lock as locks
from cbb_refresh_verify.residual_sessions import inspect_residual_sessions
request, adapter, _ = setup
with locks.LibraryLock(request.library, checkpoint=False, safe_to_release=lambda: False):
pass
assert not locks.blocker_path(request.library).exists()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
monkeypatch.setattr('cbb_refresh_verify.residual_sessions.query_process_snapshot', lambda: [])
preview = inspect_residual_sessions(request.library)
assert preview['sessions'] == [] and any(r.get('kind') == 'in_memory' for r in preview['previous_records'])
result = execute(request, adapter)
assert result.status == 'REMOVED' and result.release_proof['status'] == 'RELEASE_CONFIRMED'
assert not locks.has_retained_library(request.library)
def test_management_worker_prelaunch_failure_is_safe(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
job = tmp_path/'request.json'
job.write_text(json.dumps({'operation': 'catalog', 'desktop': 'CbbManagement_test',
'library': str(tmp_path/'lib.lmc')}), encoding='utf-8')
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'wrong desktop'))
assert native.management_worker_main(job) == 2
result = json.loads((tmp_path/'result.json').read_text('utf-8'))
assert result['safe_to_continue'] is True
@pytest.mark.parametrize('code,busy', [(5, False), (32, True), (33, True)])
def test_coordination_open_error_preserves_access_failure(tmp_path, monkeypatch, code, busy):
import pywintypes
import win32file
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
def denied(*_):
raise pywintypes.error(code, 'CreateFile', 'test failure')
monkeypatch.setattr(win32file, 'CreateFile', denied)
with pytest.raises((OSError, pywintypes.error)) as error:
with LibraryLock(tmp_path/'lib.lmc'):
pass
assert isinstance(error.value, LibraryBusy) is busy
def test_retained_checkpoint_lease_can_reprobe_exact_release(tmp_path):
import cbb_refresh_verify.library_lock as locks
library = tmp_path/'lib.lmc'; library.touch()
released = False
lease = locks.LibraryLock(library, safe_to_release=lambda: released)
try:
with lease:
pass
with pytest.raises(locks.LibraryBusy):
with locks.LibraryLock(library):
pass
released = True
with locks.LibraryLock(library):
pass
assert not locks.blocker_path(library).exists()
finally:
owner = locks._owners.pop(lease.key, None)
if owner:
owner['handle'].Close()
@pytest.mark.parametrize('failure', ['enumerate', 'cancel'])
def test_owned_mapping_close_retries_after_transient_failure(monkeypatch, failure):
from test_network_path import FakeWNet
from cbb_refresh_verify.network_path import LibraryPathLease, NetworkPathError
backend = FakeWNet()
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
method = 'mappings' if failure == 'enumerate' else 'cancel_mapping'
original = getattr(backend, method)
def broken(*_):
raise OSError('temporary disconnect')
monkeypatch.setattr(backend, method, broken)
with pytest.raises(NetworkPathError):
lease.close()
monkeypatch.setattr(backend, method, original)
lease.close()
assert backend.cancelled == [lease.drive]
def test_batch_mismatch_isolated_to_item(tmp_path):
from cbb_refresh_verify.batch_status import BatchStatusSession
from cbb_refresh_verify.status_bridge import BridgeResponseError, BridgeResult
library = tmp_path/'lib.lmc'; library.touch()
class Bridge:
def __init__(self): self.calls = []; self.restarts = 0
def start(self): pass
def close(self): pass
def restart(self): self.restarts += 1
def query(self, library, name, **kwargs):
self.calls.append(name)
if name == 'Bad': raise BridgeResponseError('CBB mismatch')
return BridgeResult('PENDING', 'test')
bridge = Bridge()
results = BatchStatusSession(bridge).scan(['Bad', 'Good'], library, tmp_path/'scan.jsonl')
assert [result.status for result in results] == ['MALFORMED', 'PENDING']
assert bridge.calls == ['Bad', 'Good'] and bridge.restarts == 1
def test_batch_cache_binds_exact_library_identity(tmp_path):
from cbb_refresh_verify.batch_status import fingerprint_library
first = tmp_path/'a/lib.lmc'; first.parent.mkdir(); first.write_bytes(b'same')
second = tmp_path/'b/lib.lmc'; second.parent.mkdir(); second.write_bytes(b'same')
stat = first.stat(); os.utime(second, ns=(stat.st_atime_ns, stat.st_mtime_ns))
assert fingerprint_library(first).sha256 != fingerprint_library(second).sha256
def test_timed_out_management_worker_releases_only_after_its_result(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
state = {'exit': None}
worker = SimpleNamespace(poll=lambda: state['exit'], close=lambda: None)
adapter = native.NativeManagementAdapter(mentor_home=tmp_path, worker_factory=lambda *_: worker)
library = tmp_path/'lib.lmc'; library.touch()
evidence = tmp_path/'run'; evidence.mkdir()
result = adapter._launch_worker({'library': str(library), 'operation': 'catalog',
'desktop': 'CbbManagement_test', 'timeout_seconds': 0}, evidence)
try:
assert result['safe_to_continue'] is False
assert adapter.release_confirmed(library) is False
state['exit'] = 2
assert adapter.release_confirmed(library) is False
(evidence/'result.json').write_text(json.dumps({'success': False, 'safe_to_continue': True}))
assert adapter.release_confirmed(tmp_path/'other.lmc') is False
assert adapter.release_confirmed(library) is True
assert worker not in native._retained_workers
finally:
if worker in native._retained_workers:
native._retained_workers.remove(worker)
def test_existing_library_manager_refusal_preserves_prelaunch_release(tmp_path, monkeypatch):
import cbb_refresh_verify.native_management as native
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'CbbManagement_test'))
monkeypatch.setattr('cbb_refresh_verify.mentor_adapter._process_details', lambda *_: [(123, 'other')])
with pytest.raises(RuntimeError) as error:
native._catalog_native({'operation': 'catalog', 'desktop': 'CbbManagement_test'}, tmp_path)
assert error.value.safe_to_continue is True
@pytest.mark.parametrize('stage,expected', [('catalog_before', 'REMOVED'), ('native_remove', 'BLOCKED')])
def test_prewrite_failure_evidence_does_not_permanently_prevent_retry(setup, stage, expected):
request, adapter, _ = setup
checkpoint = request.evidence_dir/'interrupted/checkpoint.json'
checkpoint.parent.mkdir(parents=True)
checkpoint.write_text(json.dumps({'library': str(request.library), 'stage': 'complete',
'status': 'BLOCKED', 'safe_to_continue': False, 'history': [{'stage': stage}]}), encoding='utf-8')
result = execute(request, adapter)
assert result.status == expected
def test_scoped_release_includes_shared_database_addresses(tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
library = tmp_path/'lib.lmc'; library.touch()
address = tmp_path/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True); address.write_bytes(b'preserve shared native address')
with pytest.raises(locks.LibraryBusy):
with locks._prove_library_released(library, block_name='Target'):
pass
assert address.read_bytes() == b'preserve shared native address'
def test_valid_relocated_pending_checkpoint_does_not_block_snapshot(tmp_path):
import cbb_refresh_verify.library_lock as locks
library = tmp_path/'copy/lib.lmc'; library.parent.mkdir(); library.touch()
pending = locks.blocker_path(library).with_suffix('.pending')
pending.write_text(json.dumps({'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
'library': str(tmp_path/'source/lib.lmc'), 'pid': os.getpid(),
'status': 'OPERATION_IN_PROGRESS', 'lease_id': 'a'*32, 'time': '2026-11-05'}))
assert not locks.has_blocker(library)
@pytest.mark.parametrize('content', ['{torn json', '{"unrecognized":"metadata"}'])
def test_unknown_checkpoint_release_archives_only_after_full_fresh_proof(tmp_path, monkeypatch, content):
import cbb_refresh_verify.library_lock as locks
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: [])
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
marker = locks.blocker_path(library); marker.write_text(content)
result = locks.release_retained_library(library, tmp_path/'evidence', block_name='Target')
assert result['status'] == 'RELEASE_CONFIRMED'
assert Path(result['evidence_path']).with_name('blocker-before-0.json').read_text() == content
assert not marker.exists()
assert library.with_name('.lib.cbb-upload.lock').exists()
def test_unknown_checkpoint_cannot_use_selected_target_to_ignore_other_owners(tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: [])
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
marker = locks.blocker_path(library); marker.write_bytes(b'{torn checkpoint')
address = library.parent/'ReusableBlocksLP/Other/Work/database/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True); address.write_bytes(b'preserve owner record')
with pytest.raises(locks.LibraryBusy):
locks.release_retained_library(library, tmp_path/'evidence', block_name='Target')
assert marker.read_bytes() == b'{torn checkpoint'
assert address.read_bytes() == b'preserve owner record'
def test_status_cache_does_not_reuse_a_different_block_type(tmp_path):
from cbb_refresh_verify.batch_status import BatchStatusSession
from cbb_refresh_verify.status_bridge import BridgeResult
library = tmp_path/'lib.lmc'; library.touch()
calls = []
class Bridge:
def query(self, library, name, **kwargs):
calls.append(kwargs['block_type'])
return BridgeResult('READY', 'test')
session = BatchStatusSession(Bridge())
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='RULP')
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='Other')
assert calls == ['RULP', 'Other']
@pytest.mark.parametrize('case,relevant', [('other', False), ('prefix', False),
('target', True), ('shared', True), ('worker_target', True), ('worker_other', False)])
def test_release_owner_scope_uses_exact_paths_and_bound_worker_request(tmp_path, monkeypatch, case, relevant):
import cbb_refresh_verify.library_lock as locks
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
target = library.parent/'ReusableBlocksLP/Target/Work'
locations = {'other': tmp_path/'other/Other.prj', 'prefix': target.with_name('WorkOld')/'Other.prj',
'target': target/'Target.prj', 'shared': library.parent/'SymbolLibs/shared/database'}
if case.startswith('worker_'):
job = tmp_path/'worker.json'
job.write_text(json.dumps({'library': str(library if case == 'worker_target' else tmp_path/'other/lib.lmc')}))
name, command = 'python.exe', f'python.exe --management-worker "{job}"'
else:
name, command = 'ExpeditionPCB.exe', f'ExpeditionPCB.exe -project="{locations[case]}"'
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [
{'pid': 123456, 'name': name, 'command': command, 'parent': 0}])
if relevant:
with pytest.raises(locks.LibraryBusy):
with locks._prove_library_released(library, block_name='Target'):
pass
else:
with locks._prove_library_released(library, block_name='Target'):
pass
def test_release_ignores_retained_management_worker_for_other_library(tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.native_management as native
library = tmp_path/'lib.lmc'; library.touch()
other = SimpleNamespace(poll=lambda: None, cbb_library=str(tmp_path/'other.lmc'))
monkeypatch.setattr(native, '_retained_workers', [other])
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
with locks._prove_library_released(library):
pass
def test_retained_mapping_can_close_after_exact_release_proof():
from test_network_path import FakeWNet
from cbb_refresh_verify.network_path import LibraryPathLease
backend = FakeWNet()
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
lease.retain_for_recovery()
lease.close()
assert backend.cancelled == []
assert not lease.release_after_recovery({'status': 'RELEASE_CONFIRMED', 'library': r'\\other\share\lib.lmc'})
assert lease.release_after_recovery({'status': 'RELEASE_CONFIRMED', 'library': r'\\server\share\lib.lmc'})
lease.close()
assert backend.cancelled == [lease.drive]
def test_target_mapping_query_ignores_unrelated_enumeration_failure():
from test_network_path import FakeWNet
from cbb_refresh_verify.network_path import ensure_mapped_drive_visible
class Backend(FakeWNet):
def mapping(self, drive):
assert drive == 'S:'
return r'\\server\share'
def mappings(self):
raise OSError('unrelated drive enumeration failed')
result = ensure_mapped_drive_visible('S:', r'\\server\share', backend=Backend())
assert result['created'] is False
def test_windows_mapping_enumeration_reserves_unavailable_drive():
from cbb_refresh_verify.network_path import WindowsWNetBackend
backend = WindowsWNetBackend.__new__(WindowsWNetBackend)
def connection(drive, buffer, size):
if drive == 'D:': return 5
if drive == 'Y:':
buffer.value = r'\\server\share'
return 0
return 2250
backend._mpr = SimpleNamespace(WNetGetConnectionW=connection)
backend._kernel32 = SimpleNamespace(GetLogicalDrives=lambda: 0)
assert backend.mappings() == {'Y:': r'\\server\share'}
assert 'D:' in backend.used_drives()
def test_postnative_idle_failure_preserves_known_release(setup, isolated_mutex):
from cbb_refresh_verify.management import run_management
from cbb_refresh_verify.library_lock import LibraryLock
request, adapter, _ = setup
checks = []
def idle(*_):
checks.append(1)
if len(checks) == 3:
raise OSError('passive owner query unavailable after native exit')
result = run_management(request, adapter=adapter, idle_check=idle)
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
with LibraryLock(request.library):
pass
def test_final_report_failure_does_not_discard_release_result(setup, monkeypatch, isolated_mutex):
import cbb_refresh_verify.management as management
request, adapter, _ = setup
original = management._write_json
def write(path, record):
if record.get('stage') == 'complete':
raise OSError('evidence volume unavailable')
return original(path, record)
monkeypatch.setattr(management, '_write_json', write)
result = execute(request, adapter)
assert result.status == 'REMOVED' and result.safe_to_continue
assert 'evidence volume unavailable' in result.detail
def test_legacy_checkpoint_cannot_clear_other_target_owner(tmp_path, monkeypatch, isolated_mutex):
import cbb_refresh_verify.library_lock as locks
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
marker = locks.blocker_path(library)
locks._persist_blocker(library, lease_id='b'*32)
original = marker.read_bytes()
address = library.parent/'ReusableBlocksLP/Other/Work/database/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True); address.write_bytes(b'keep actual owner address')
with pytest.raises(locks.LibraryBusy):
locks.release_retained_library(library, tmp_path/'evidence', block_name='Target')
assert marker.read_bytes() == original
assert address.read_bytes() == b'keep actual owner address'
def test_release_proof_recovers_old_mapping_lease_and_transfers_shared_drive():
import cbb_refresh_verify.network_path as network
from test_network_path import FakeWNet
backend = FakeWNet()
old = network.LibraryPathLease.acquire(r'\\server\share\A\lib.lmc', backend=backend)
current = network.LibraryPathLease.acquire(r'\\server\share\B\lib.lmc', backend=backend)
old.retain_for_recovery(); old.close()
proof = {'status': 'RELEASE_CONFIRMED', 'library': r'\\server\share\A\lib.lmc'}
assert network.release_retained_path_leases(proof, current_lease=current) == 1
assert backend.cancelled == [] and current.created
current.close()
assert backend.cancelled == [current.drive]
def test_clean_failed_mutation_keeps_recovery_requirement_and_released_owner(setup, isolated_mutex):
from dataclasses import replace
from cbb_refresh_verify.management import run_management
request, adapter, source = setup
adapter.fail_add = True
failed = execute(replace(request, operation='update', source=source, auto_verify=False), adapter)
assert failed.status == 'RECOVERY_REQUIRED' and failed.safe_to_continue
adapter.fail_add = False
same = execute(replace(request, operation='add', source=source, auto_verify=False), adapter)
assert same.status == 'BLOCKED'
other = execute(replace(request, operation='add', name='Independent', source=source, auto_verify=False), adapter)
assert other.status == 'UPLOADED' and other.safe_to_continue
@pytest.mark.parametrize('history', [None, [], [{'stage': 'native_remove'}, {'stage': 'prepare_identity'}]])
def test_prewrite_stage_alone_does_not_override_unknown_or_mutated_history(history):
from cbb_refresh_verify.management import _may_have_mutated
record = {'stage': 'prepare_identity', 'history': history, 'status': 'RUNNING'}
assert _may_have_mutated(record)
def test_library_checkpoint_binds_supervisor_creation_identity(tmp_path):
import cbb_refresh_verify.library_lock as locks
library = tmp_path/'lib.lmc'; library.touch()
locks._persist_blocker(library, lease_id='c'*32)
record = json.loads(locks.blocker_path(library).read_text())
assert record.get('supervisor_created')
assert locks._recorded_supervisor_alive(record) is True
assert locks._recorded_supervisor_alive({**record, 'supervisor_created': 'other process'}) is False
legacy = {key: value for key, value in record.items() if key not in ('machine', 'supervisor_created')}
assert locks._recorded_supervisor_alive(legacy) is None
@pytest.mark.parametrize('proof,safe', [
({'safe_to_continue': True, 'process_created': False, 'worker_exited': True, 'remaining_pids': []}, True),
({'safe_to_continue': True, 'process_created': True, 'worker_exited': True, 'remaining_pids': []}, False),
({'safe_to_continue': True, 'process_created': False, 'worker_exited': False, 'remaining_pids': []}, False),
(None, False)])
def test_management_worker_launch_exception_uses_explicit_release_protocol(tmp_path, proof, safe):
from cbb_refresh_verify.native_management import NativeManagementAdapter
error = OSError('private desktop creation failed')
error.worker_launch_release = proof
def fail(*_): raise error
adapter = NativeManagementAdapter(mentor_home=tmp_path, worker_factory=fail)
with pytest.raises(OSError) as caught:
adapter._launch_worker({'library': str(tmp_path/'lib.lmc'), 'operation': 'catalog',
'desktop': 'CbbManagement_test', 'timeout_seconds': 1}, tmp_path)
assert getattr(caught.value, 'safe_to_continue', None) is safe
def test_native_add_passive_postcheck_failure_preserves_release(transaction, monkeypatch, isolated_mutex):
from test_management_native_transaction import execute as execute_transaction
root, request, state = transaction
def unavailable(*_): raise OSError('passive target check unavailable')
monkeypatch.setattr('cbb_refresh_verify.backup_recovery._idle_check', unavailable)
result = execute_transaction(root, request)
assert result.status == 'RECOVERY_REQUIRED' and result.safe_to_continue
@pytest.mark.parametrize('case,safe', [('exit_output_error', True), ('popen_missing', True),
('popen_denied', True), ('popen_unknown', False), ('timeout', False)])
def test_remove_worker_preserves_exit_and_known_creation_rejection(tmp_path, monkeypatch, case, safe):
import cbb_refresh_verify.native_management as native
job = tmp_path/'request.json'
job.write_text(json.dumps({'operation': 'remove', 'desktop': 'CbbManagement_test',
'mentor_home': str(tmp_path), 'library': str(tmp_path/'lib.lmc'), 'name': 'Block',
'partition': 'Logical-Physical', 'timeout_seconds': 1}), encoding='utf-8')
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'CbbManagement_test'))
monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities', lambda _: {
'remove': SimpleNamespace(supported=True)})
observed = {'waited': False}
def wait(timeout):
if case == 'timeout':
raise native.subprocess.TimeoutExpired('fake CleanWGLib', timeout)
observed['waited'] = True
return 0
def popen(*args, **kwargs):
failures = {'popen_missing': FileNotFoundError('native binary disappeared'),
'popen_denied': PermissionError('native creation denied'),
'popen_unknown': OSError('unconfirmed process creation')}
if case in failures:
raise failures[case]
return SimpleNamespace(pid=123456, wait=wait)
monkeypatch.setattr(native.subprocess, 'Popen', popen)
original_read = Path.read_bytes
def read(path):
if path.name == 'native-output.txt' and case == 'exit_output_error':
assert observed['waited']
raise OSError('native output storage unavailable after exit')
return original_read(path)
monkeypatch.setattr(Path, 'read_bytes', read)
assert native.management_worker_main(job) == 2
result = json.loads((tmp_path/'result.json').read_text('utf-8'))
assert result['safe_to_continue'] is safe
if case == 'exit_output_error':
assert result['exit_code'] == 0 and 'storage unavailable' in result['detail']
def test_add_source_missing_central_library_fails_before_capture_without_retaining(setup, monkeypatch, isolated_mutex):
from dataclasses import replace
import cbb_refresh_verify.native_management as native
from cbb_refresh_verify.management import Catalog
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path
request, _, source = setup
adapter = native.NativeManagementAdapter(mentor_home=source.parent)
monkeypatch.setattr(adapter, 'capabilities', lambda: {'add': SimpleNamespace(supported=True)})
monkeypatch.setattr(adapter, 'catalog', lambda library, evidence: Catalog(library, 1, ()))
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity.capture_identity',
lambda *_a, **_kw: pytest.fail('incomplete source reached native capture'))
result = execute(replace(request, operation='add', name='New', source=source, auto_verify=False), adapter)
assert result.status == 'UPLOAD_FAILED' and result.safe_to_continue
assert 'CentralLibrary' in result.detail
assert not blocker_path(request.library).exists()
with LibraryLock(request.library):
pass
def test_prepared_transaction_storage_failure_preserves_capture_release(transaction, monkeypatch, isolated_mutex):
from test_management_native_transaction import execute as execute_transaction
root, request, _ = transaction
def unavailable(*_a, **_kw): raise OSError('prepared transaction storage unavailable')
monkeypatch.setattr('cbb_refresh_verify.management_transaction.prepare_transaction', unavailable)
result = execute_transaction(root, request)
assert result.status == 'UPLOAD_FAILED' and result.safe_to_continue
assert 'prepared transaction storage unavailable' in result.detail
@pytest.mark.parametrize('flag,relevant', [('-icdb', False), ('-icdb=', False),
('-ICDB', True), ('-icdb=', True)])
def test_release_owner_scope_parses_actual_edif_database_argument(tmp_path, flag, relevant):
from cbb_refresh_verify.library_lock import _owner_matches_scope
library = tmp_path/'Target/lib.lmc'
database = library.parent/'Work/database'
selected = database if relevant else tmp_path/'Other project/database'
argument = flag + ('' if flag.endswith('=') else ' ') + f'"{selected}"'
item = {'command': f'edifExporter.exe -schematic {argument} -isnap DxD'}
assert _owner_matches_scope(item, library, (database,)) is relevant
def test_release_owner_scope_does_not_match_edif_database_prefix(tmp_path):
from cbb_refresh_verify.library_lock import _owner_matches_scope
database = tmp_path/'Target/database'
item = {'command': f'edifExporter.exe -schematic -icdb "{database}_old" -isnap DxD'}
assert _owner_matches_scope(item, tmp_path/'Target/lib.lmc', (database,)) is False
def test_same_target_recovery_gate_preserves_release_and_batch_continues(setup, isolated_mutex):
from dataclasses import replace
from cbb_refresh_verify.management import run_management_batch
request, adapter, source = setup
adapter.fail_add = True
failed = execute(replace(request, operation='update', source=source, auto_verify=False), adapter)
assert failed.status == 'RECOVERY_REQUIRED' and failed.safe_to_continue
adapter.fail_add = False
results = run_management_batch([
replace(request, operation='add', source=source, auto_verify=False),
replace(request, operation='add', name='Independent', source=source, auto_verify=False)],
adapter=adapter, idle_check=lambda *_: None)
assert [result.status for result in results] == ['BLOCKED', 'UPLOADED']
assert all(result.safe_to_continue for result in results)
+41 -3
View File
@@ -80,6 +80,37 @@ def test_restart_shows_unfinished_without_starting_worker(qtbot, tmp_path):
assert 'Block' in window.output.toPlainText()
def test_previous_unsafe_result_allows_retry_and_requires_matching_release_proof(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.management import Capability, ManagementResult
adapter = SimpleNamespace(capabilities=lambda: {op: Capability(True, 'available')
for op in ('add', 'update', 'remove')})
window = load_window(qtbot, tmp_path, monkeypatch, management_adapter=adapter)
library = Path(window.mentor_lmc_path or window.loaded_path)
from cbb_refresh_verify.network_path import LibraryPathLease
current = LibraryPathLease(library, library)
current.retain_for_recovery()
window.library_lease = current
window._management_unsafe = True
window._management_unsafe_library = library
window.select_visible_button.click()
assert window.remove_button.isEnabled(), 'A historical flag must not disable the fresh release check'
window.remove_button.click()
requests = window.management_dialog.requests()
assert requests and all(r.check_previous_release for r in requests)
result = ManagementResult('remove', library, 'Beta', 'Logical-Physical', None,
False, 'complete', 'BLOCKED', True, 'prelaunch failure')
window._management_completed([result])
assert window._management_library_unsafe(library), 'An input failure does not prove the previous session released'
assert current._retained_for_recovery
proof = {'status': 'RELEASE_CONFIRMED', 'library': str(library), 'evidence_path': 'proof.json'}
window._management_completed([replace(result, release_proof=proof)])
qtbot.waitUntil(lambda: window._mapping_busy == 0)
assert not window._management_library_unsafe(library)
assert not current._retained_for_recovery
window.management_dialog.reject()
def test_historical_record_does_not_prevent_catalog_load_and_offers_checked_release(qtbot, tmp_path, monkeypatch):
import pytest
import cbb_refresh_verify.library_lock as locks
@@ -95,9 +126,16 @@ def test_historical_record_does_not_prevent_catalog_load_and_offers_checked_rele
assert window.release_library_button.isEnabled()
assert locks.blocker_path(library).read_text() == '{}'
calls = []
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
monkeypatch.setattr(locks, 'release_retained_library', lambda *a:
(calls.append(a) or {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'proof.json'}))
monkeypatch.setattr(locks, 'inspect_residual_sessions', lambda *a:
{'library': str(library), 'sessions': []})
monkeypatch.setattr(locks, 'release_residual_sessions', lambda *a, **kw:
(calls.append(a) or {'status': 'RELEASE_CONFIRMED', 'sessions': [], 'proof':
{'status': 'RELEASE_CONFIRMED', 'library': str(library), 'evidence_path': 'proof.json'}}))
window.release_library_button.click()
qtbot.waitUntil(lambda: not window.release_dialog.busy)
assert not calls
window.release_dialog.confirm_button.click()
qtbot.waitUntil(lambda: not window.release_dialog.busy)
window.release_dialog.close()
qtbot.waitUntil(lambda: not window.busy)
assert len(calls) == 1 and 'proof.json' in window.output.toPlainText()
+2 -1
View File
@@ -46,7 +46,8 @@ def test_add_timeout_publishes_cancellation_without_killing_native_owner(tmp_pat
def poll(self): return None
def close(self): pytest.fail('live worker must not be killed')
adapter=native.NativeManagementAdapter(worker_factory=Running)
result=adapter._launch_worker({'operation':'add','desktop':'CbbManagement_test','timeout_seconds':0},tmp_path)
result=adapter._launch_worker({'operation':'add','desktop':'CbbManagement_test','timeout_seconds':0,
'library':str(tmp_path/'library.lmc')},tmp_path)
assert not result['safe_to_continue'] and (tmp_path/'cancel-native-add.signal').exists()
assert len(native._retained_workers)==1
+2 -1
View File
@@ -163,6 +163,7 @@ def test_closing_app_keeps_manual_native_window_and_mapping(qtbot, tmp_path, mon
window.library_lease = lease
window._native_backup_session = session
window.show(); window.close()
qtbot.waitUntil(lambda: not window.isVisible())
assert retained == [True] and session.process.poll() is None
@@ -214,7 +215,7 @@ def test_confirmed_native_close_transfers_mapping_to_current_library(qtbot, tmp_
assert window._native_backup_session is None
assert backend.cancelled == [] and current.created
window.close()
assert backend.cancelled == [current.drive]
qtbot.waitUntil(lambda: backend.cancelled == [current.drive])
def test_native_mapping_ownership_transfers_to_new_library_on_same_share():
+235
View File
@@ -200,6 +200,241 @@ def test_export_timeout_retains_process_without_kill(project, tmp_path, monkeypa
assert (root/'ascii-process.json').is_file()
def test_export_does_not_adopt_unrelated_existing_native_owner(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
source, _ = project
root = tmp_path/'exports'; root.mkdir()
unrelated = {'pid': 888888, 'parent': 0, 'name': 'iCDBNetServer.exe',
'executable': 'native', 'command': 'iCDBNetServer.exe C:\\other\\database'}
monkeypatch.setattr(identity, '_process_snapshot', lambda: [unrelated])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
monkeypatch.setattr(identity, 'validate_export_output', lambda *_: None)
started = []
class Finished:
pid = 987654
returncode = 0
def __init__(self, command, **kwargs): started.append(command)
def poll(self): return 0
monkeypatch.setattr(identity.subprocess, 'Popen', Finished)
result = identity._run_exports(source, root, tmp_path, 1)
assert result['success'] and result['safe_to_continue']
assert len(started) == 3
def test_export_spawn_failure_does_not_manufacture_native_ownership(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
source, _ = project
root = tmp_path/'exports'; root.mkdir()
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
def fail(*a, **k): raise FileNotFoundError('missing exporter')
monkeypatch.setattr(identity.subprocess, 'Popen', fail)
result = identity._run_exports(source, root, tmp_path, 1)
assert not result['success'] and result['safe_to_continue']
assert 'missing exporter' in result['detail']
def test_unconfirmed_export_constructor_failure_retains_ownership(project, tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
source, _ = project
root = tmp_path/'exports'; root.mkdir()
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
def fail(*a, **k): raise RuntimeError('uncertain partially-created process')
monkeypatch.setattr(identity.subprocess, 'Popen', fail)
result = identity._run_exports(source, root, tmp_path, 1)
assert not result['success'] and not result['safe_to_continue']
@pytest.mark.parametrize('summary', ['native-outcome.json', 'identity.json'])
def test_export_summary_write_failure_preserves_confirmed_release(project, tmp_path, monkeypatch, summary):
import cbb_refresh_verify.native_engineering_identity as identity
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path
import win32event
from uuid import uuid4
create_mutex = win32event.CreateMutex
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
create_mutex(security, owned, name+'-test-'+uuid4().hex))
source, library = project
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
def exports(clone, root, *_):
(root/'export-launch.json').write_text('{"started": false}')
return {'success': False, 'safe_to_continue': True, 'detail': 'export rejected before start'}
monkeypatch.setattr(identity, '_run_exports', exports)
original_write = identity._write_json
def write(path, record):
if path.name == summary: raise OSError('summary unavailable')
return original_write(path, record)
monkeypatch.setattr(identity, '_write_json', write)
with LibraryLock(library):
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
owner_library=library, mentor_home=tmp_path)
assert result.identity is None and result.safe_to_continue
assert 'summary unavailable' in result.detail
assert not blocker_path(library).exists()
def test_export_snapshot_uses_bounded_read_only_helper(monkeypatch):
from cbb_refresh_verify import native_engineering_identity as identity, owner_probe
rows = [{'pid': 42, 'parent': 10, 'name': 'unknown-child.exe'}]
calls = []
def query(**kwargs):
calls.append(kwargs)
return rows
monkeypatch.setattr(owner_probe, 'query_process_snapshot', query)
assert identity._process_snapshot() == rows
assert calls == [{'timeout_seconds': 10}]
@pytest.mark.parametrize('after_launch', [False, True])
def test_export_snapshot_timeout_preserves_launch_extent(project, tmp_path, monkeypatch, after_launch):
from cbb_refresh_verify import native_engineering_identity as identity
source, _ = project
root = tmp_path/'exports'; root.mkdir()
calls = []
def snapshot():
calls.append('snapshot')
if after_launch and len(calls) == 1: return []
raise RuntimeError('OWNER_QUERY_TIMEOUT: WMI timed out')
monkeypatch.setattr(identity, '_process_snapshot', snapshot)
monkeypatch.setattr(identity, '_database_released', lambda _: True)
monkeypatch.setattr(identity, '_retained_exports', [])
launched = []
class Running:
pid = 987654
def __init__(self, *a, **k): launched.append(self)
def poll(self): return None
monkeypatch.setattr(identity.subprocess, 'Popen', Running)
result = identity._run_exports(source, root, tmp_path, 1)
assert not result['success']
assert result['safe_to_continue'] is (not after_launch)
assert result['native_started'] is after_launch
assert 'OWNER_QUERY_TIMEOUT' in result['detail']
assert bool(launched) is after_launch
assert bool(identity._retained_exports) is after_launch
def test_prelaunch_snapshot_timeout_releases_only_own_unstarted_guard(project, tmp_path, monkeypatch):
from cbb_refresh_verify import native_engineering_identity as identity
from cbb_refresh_verify.library_lock import LibraryLock, blocker_path
import win32event
from uuid import uuid4
source, library = project
create_mutex = win32event.CreateMutex
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
create_mutex(security, owned, name+'-test-'+uuid4().hex))
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
calls = []
def snapshot():
calls.append('query')
raise RuntimeError('OWNER_QUERY_TIMEOUT: process tree unavailable')
monkeypatch.setattr(identity, '_process_snapshot', snapshot)
with LibraryLock(library):
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
owner_library=library, mentor_home=tmp_path)
assert result.identity is None and result.safe_to_continue
assert 'OWNER_QUERY_TIMEOUT' in result.detail
assert calls == ['query']
assert not blocker_path(library).exists()
@pytest.mark.parametrize('failure', ['source', 'lease', 'scope', 'exporters', 'directory', 'mutex'])
def test_capture_prevalidation_failure_explicitly_reports_no_native_session(project, tmp_path, monkeypatch, failure):
from cbb_refresh_verify import native_engineering_identity as identity, library_lock
import win32event
source, library = project
root = tmp_path/'analysis'
def reject(*args, **kwargs): raise OSError(f'prevalidation {failure} unavailable')
monkeypatch.setattr(library_lock, 'owned_snapshot', lambda _: b'owned lease')
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
monkeypatch.setattr(identity, '_run_exports', lambda *a, **k: pytest.fail('native export must not start'))
if failure == 'source': monkeypatch.setattr(identity, 'source_project', reject)
if failure == 'lease': monkeypatch.setattr(library_lock, 'owned_snapshot', lambda _: None)
if failure == 'scope': root = source.parent/'analysis'
if failure == 'exporters': monkeypatch.setattr(identity, 'check_exporters', reject)
if failure == 'directory':
mkdir = Path.mkdir
def create(path, *args, **kwargs):
if path == root: return reject()
return mkdir(path, *args, **kwargs)
monkeypatch.setattr(Path, 'mkdir', create)
if failure == 'mutex': monkeypatch.setattr(win32event, 'CreateMutex', reject)
result = identity.capture_identity(source, root, expected_library=library,
owner_library=library, mentor_home=tmp_path)
assert result.identity is None and result.safe_to_continue
assert result.detail
@pytest.mark.parametrize('failure', ['initial_launch_record', 'final_process_record'])
def test_export_record_io_preserves_known_launch_extent(project, tmp_path, monkeypatch, failure):
from cbb_refresh_verify import native_engineering_identity as identity, library_lock
import win32event
from uuid import uuid4
source, library = project
create_mutex = win32event.CreateMutex
monkeypatch.setattr(win32event, 'CreateMutex', lambda security, owned, name:
create_mutex(security, owned, name+'-test-'+uuid4().hex))
monkeypatch.setattr(identity, 'check_exporters', lambda _: None)
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
monkeypatch.setattr(library_lock, '_supervisor_alive', lambda _: False)
launched = []
class Finished:
pid = 987654
returncode = 0
def __init__(self, *args, **kwargs): launched.append(self)
def poll(self): return 0
monkeypatch.setattr(identity.subprocess, 'Popen', Finished)
def content_failure(*args): raise ValueError('native export content rejected')
monkeypatch.setattr(identity, 'validate_export_output', content_failure)
write = identity._write_json
process_writes = []
def fail(path, record):
if path.name == 'export-launch.json' and failure == 'initial_launch_record':
raise OSError('launch metadata unavailable')
if path.name == 'ascii-process.json':
process_writes.append(record.copy())
if failure == 'final_process_record' and len(process_writes) == 2:
raise OSError('final process metadata unavailable')
return write(path, record)
monkeypatch.setattr(identity, '_write_json', fail)
with library_lock.LibraryLock(library):
result = identity.capture_identity(source, tmp_path/'analysis', expected_library=library,
owner_library=library, mentor_home=tmp_path)
assert result.identity is None and result.safe_to_continue
assert 'metadata unavailable' in result.detail
assert bool(launched) is (failure == 'final_process_record')
assert not library_lock.blocker_path(library).exists()
with library_lock.LibraryLock(library): pass
def test_successful_export_keeps_release_when_final_diagnostic_write_fails(project, tmp_path, monkeypatch):
from cbb_refresh_verify import native_engineering_identity as identity
source, _ = project
root = tmp_path/'exports'; root.mkdir()
monkeypatch.setattr(identity, '_process_snapshot', lambda: [])
monkeypatch.setattr(identity, '_database_released', lambda _: True)
monkeypatch.setattr(identity, 'validate_export_output', lambda *_: None)
class Finished:
pid = 987654
returncode = 0
def __init__(self, *args, **kwargs): pass
def poll(self): return 0
monkeypatch.setattr(identity.subprocess, 'Popen', Finished)
write = identity._write_json
counts = {}
def fail(path, record):
if path.name.endswith('-process.json'):
counts[path] = counts.get(path, 0)+1
if counts[path] == 2: raise OSError('final metadata unavailable')
return write(path, record)
monkeypatch.setattr(identity, '_write_json', fail)
result = identity._run_exports(source, root, tmp_path, 1)
assert result['success'] and result['safe_to_continue']
assert 'final metadata unavailable' in result['detail']
def edif_report(timestamp=b'2026 11 3 11 40 56'):
return (b'(edif DxD (edifVersion 2 0 0) (status (written (timestamp '+timestamp+b')'
b' (program "DxDesigner Edif Exporter"))) (library Board1 (cell Top'
+80
View File
@@ -116,3 +116,83 @@ def test_successful_export_clears_only_its_bound_guard_after_fresh_copy_proof(tm
finish_export_analysis(library, token)
assert 'export_analysis' not in json.loads(marker.read_text())
assert not marker.exists()
def test_unrelated_same_name_server_does_not_prevent_copy_release(export_case, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
from cbb_refresh_verify.native_export_guard import prove_export_copies_released
library, root, *_ = export_case
monkeypatch.setattr(identity, '_process_snapshot', lambda: [
{'pid': 777777, 'name': 'iCDBNetServer.exe', 'parent': 0, 'executable': 'native',
'command': 'iCDBNetServer.exe C:\\other\\database'}])
with prove_export_copies_released(library) as copies:
assert copies == [str(root/'project')]
def test_retained_export_registry_is_scoped_to_its_library(tmp_path, monkeypatch):
import cbb_refresh_verify.native_engineering_identity as identity
from cbb_refresh_verify.native_export_guard import assert_retained_exports_idle
from cbb_refresh_verify.library_lock import LibraryBusy
library_a, library_b = tmp_path/'a.lmc', tmp_path/'b.lmc'
monkeypatch.setattr(identity, '_retained_exports', [
(SimpleNamespace(poll=lambda: None), {}, {'library': str(library_a.resolve())})])
assert_retained_exports_idle(library_b)
with pytest.raises(LibraryBusy): assert_retained_exports_idle(library_a)
@pytest.mark.parametrize('created,blocked', [('new-process', False), ('original-process', True)])
def test_recorded_export_pid_reuse_requires_matching_creation_identity(export_case, monkeypatch, created, blocked):
import cbb_refresh_verify.native_engineering_identity as identity
import cbb_refresh_verify.library_lock as locks
from cbb_refresh_verify.native_export_guard import prove_export_copies_released
library, root, *_ = export_case
path = root/'ascii-process.json'
record = json.loads(path.read_text('utf-8'))
record['process_identities'] = [{'pid': 123456, 'created': 'original-process', 'executable': 'native'}]
path.write_text(json.dumps(record), encoding='utf-8')
monkeypatch.setattr(locks, '_supervisor_alive', lambda _: True)
monkeypatch.setattr(identity, '_process_snapshot', lambda: [
{'pid': 123456, 'name': 'unrelated.exe', 'parent': 0,
'executable': 'native', 'created': created, 'command': ''}])
if blocked:
with pytest.raises(locks.LibraryBusy):
with prove_export_copies_released(library): pass
else:
with prove_export_copies_released(library): pass
@pytest.mark.parametrize('active', [False, True])
def test_unknown_checkpoint_requires_explicit_full_proof_and_no_native_export_owner(tmp_path, monkeypatch, active):
import cbb_refresh_verify.native_engineering_identity as identity
import cbb_refresh_verify.library_lock as locks
from cbb_refresh_verify.native_export_guard import prove_export_copies_released
library = tmp_path/'lib.lmc'; library.touch()
locks.blocker_path(library).write_text('{torn metadata')
monkeypatch.setattr(identity, '_retained_exports', [])
monkeypatch.setattr(identity, '_process_snapshot', lambda: [
{'pid': 12345, 'name': 'iCDBNetServer.exe', 'parent': 0}] if active else [])
with pytest.raises(locks.LibraryBusy):
with prove_export_copies_released(library): pass
if active:
with pytest.raises(locks.LibraryBusy):
with prove_export_copies_released(library, allow_unknown_checkpoint=True): pass
else:
with prove_export_copies_released(library, allow_unknown_checkpoint=True) as copies:
assert copies == []
assert locks.blocker_path(library).read_text() == '{torn metadata'
@pytest.mark.parametrize('no_start_proven', [False, True])
def test_missing_pid_requires_bound_no_start_evidence(export_case, no_start_proven):
from cbb_refresh_verify.native_export_guard import prove_export_copies_released
from cbb_refresh_verify.library_lock import LibraryBusy
library, root, *_ = export_case
record = {'success': False, 'safe_to_continue': True}
if no_start_proven: record['native_started'] = False
(root/'ascii-process.json').write_text(json.dumps(record), encoding='utf-8')
(root/'export-launch.json').write_text(json.dumps({'started': not no_start_proven}), encoding='utf-8')
if no_start_proven:
with prove_export_copies_released(library): pass
else:
with pytest.raises(LibraryBusy):
with prove_export_copies_released(library): pass
+191 -191
View File
@@ -1,191 +1,191 @@
import json
from pathlib import Path
import pytest
def output(project, database, *, fault=False, busy=False):
text = f'Loading project file [{project}].\nChecking if project is in use.\n'
if fault:
text += (f'Project database [{database}] is inconsistent. It has been manually copied while the iCDB Server was running. '
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue.\n")
return text + ('Project is in use.\n' if busy else
"Project is not in use. Full iCDB Project Backup's functionality is available.\nBackup information loaded correctly.\n")
@pytest.mark.parametrize('fault,busy,status,repair', [
(False, False, 'NOT_IN_USE', False), (True, False, 'NOT_IN_USE', True),
(True, True, 'IN_USE', False), (False, True, 'IN_USE', False)])
def test_native_ownership_and_repair_need_are_separate(tmp_path, fault, busy, status, repair):
from cbb_refresh_verify.native_occupancy import classify_inspection
project, database = tmp_path/'A.prj', tmp_path/'database'
result = classify_inspection(project, database, output(project, database, fault=fault, busy=busy))
assert result['status'] == status
assert result['repair_required'] is repair
@pytest.mark.parametrize('case', ['progress', 'wrong_project', 'wrong_database', 'stale_verdict', 'generic_repair'])
def test_incomplete_or_foreign_output_cannot_authorize_repair(tmp_path, case):
from cbb_refresh_verify.native_occupancy import classify_inspection
project, database = tmp_path/'A.prj', tmp_path/'database'
text = output(project, database, fault=True)
if case == 'progress': text = f'Loading project file [{project}].\nChecking if project is in use.'
if case == 'wrong_project': text = output(tmp_path/'Other.prj', database, fault=True)
if case == 'wrong_database': text = output(project, tmp_path/'other', fault=True)
if case == 'stale_verdict': text += 'Checking if project is in use.\n'
if case == 'generic_repair': text = output(project, database) + 'Please try to repair the project!'
assert classify_inspection(project, database, text)['repair_required'] is False
@pytest.mark.parametrize('fault,busy', [(False, False), (True, False), (False, True)])
def test_inspection_mode_only_observes_and_closes_its_tool(tmp_path, monkeypatch, fault, busy):
import win32con
from test_native_repair import repair_worker_fixture
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
job.write_text(json.dumps(data), encoding='utf-8')
monkeypatch.setattr(ui, '_repair_command', lambda *a: pytest.fail('inspection resolved Repair command'))
monkeypatch.setattr(ui, '_native_output', lambda *_: output(data['project'], data['database'], fault=fault, busy=busy))
assert ui.repair_worker_main(job) == 0
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['status'] == ('IN_USE' if busy else 'NOT_IN_USE')
assert result['release']['native_exited'] is True
assert result['repair_required'] is (fault and not busy)
assert actions == [(100, win32con.WM_CLOSE)]
def test_generic_project_backup_shell_is_accepted_as_the_single_target_window(tmp_path, monkeypatch):
import json
from test_native_repair import repair_worker_fixture
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
job.write_text(json.dumps(data), encoding='utf-8')
monkeypatch.setattr(ui, '_native_output', lambda windows: (
f'Loading project file [{data["project"]}].\nChecking if project is in use.\n'
"Project is not in use. Full iCDB Project Backup's functionality is available.\n"
'Backup information loaded correctly.'))
assert ui.repair_worker_main(job) == 0
def test_only_check_never_counts_as_repair_success():
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
from cbb_refresh_verify.verify_runner import VerifyResult
counts = maintenance_counts([VerifyResult('CHECKED', safe_to_continue=True)])
assert counts['passed'] == counts['repaired'] == 0
assert counts['checked_without_repair'] == 1
def test_cancelled_probe_returns_within_grace_without_killing_native(tmp_path, monkeypatch):
from threading import Event
from types import SimpleNamespace
from cbb_refresh_verify import native_repair as native
from cbb_refresh_verify.native_repair import RepairTarget
stop = Event(); ticks = [0.0]; actions = []
def sleep(seconds):
ticks[0] += seconds
stop.set()
monkeypatch.setattr(native, 'time', SimpleNamespace(monotonic=lambda: ticks[0], sleep=sleep))
class Worker:
pid = 123
def __init__(self, *a): pass
def bind_cancellation(self, p): pass
def poll(self): return None
def request_stop(self): actions.append('cancel')
def close(self): actions.append('close_handles')
def kill(self): pytest.fail('native owner must not be killed')
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
result = native.run_native_repair(RepairTarget(tmp_path/'A.prj', tmp_path/'database'),
tmp_path/'evidence', timeout_seconds=600, inspection_only=True, stop=stop)
assert ticks[0] < 6
assert result['status'] == 'CANCELLED_UNRELEASED'
assert result['release']['safe_to_continue'] is False
assert actions[-1] == 'close_handles'
def test_ui_keeps_processing_events_and_passes_cancel_to_native_task(qtbot, tmp_path, monkeypatch):
from threading import Event
from PySide6.QtCore import QTimer
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
entered = Event(); cancelled = Event(); ticks = []
def verify(req, *, stop, **kw):
entered.set()
if stop.wait(3): cancelled.set()
return VerifyResult('CANCELLED')
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_verify', verify)
window = load_window(qtbot, tmp_path, monkeypatch,
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
window.search_edit.setText('Beta')
timer = QTimer(window); timer.setInterval(10); timer.timeout.connect(lambda: ticks.append(True)); timer.start()
window.repair_icdb_all()
qtbot.waitUntil(entered.is_set)
qtbot.waitUntil(lambda: len(ticks) >= 3)
assert window.busy and window.stop_button.isEnabled()
window.stop_button.click()
qtbot.waitUntil(lambda: not window.busy)
assert cancelled.is_set()
@pytest.mark.parametrize('extra', ['foreign_session', 'extra_error'])
def test_foreign_or_additional_fault_is_never_a_clean_inspection(tmp_path, extra):
from cbb_refresh_verify.native_occupancy import classify_inspection
project, database = tmp_path/'A.prj', tmp_path/'database'
text = output(project, database, fault=extra == 'extra_error')
if extra == 'foreign_session':
text += ('The last server session on different server machine lost the connection to the database. '
'Machine:[SERVER] Path:[C:/Other/Work/database] session:[old]')
else:
text += 'ERROR: shared symbol database unavailable'
assert classify_inspection(project, database, text)['status'] == 'UNCONFIRMED'
def test_unconfirmed_inspection_closes_known_main_at_timeout(tmp_path, monkeypatch):
import win32con
from test_native_repair import repair_worker_fixture
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
job.write_text(json.dumps(data), encoding='utf-8')
monkeypatch.setattr(ui, '_native_output', lambda *_: 'Unrecognized response')
assert ui.repair_worker_main(job) == 1
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['status'] == 'UNCONFIRMED'
assert result['release']['native_exited'] is True
assert actions == [(100, win32con.WM_CLOSE)]
def test_directory_scan_honors_cancel_between_entries(tmp_path):
from cbb_refresh_verify.scoped_manifest import scan_tree
for i in range(10): (tmp_path/f'{i}.dat').touch()
calls = []
def cancel():
calls.append(True)
if len(calls) == 3: raise RuntimeError('CANCELLED')
with pytest.raises(RuntimeError, match='CANCELLED'):
scan_tree(tmp_path, check=cancel)
assert len(calls) == 3
def test_cancel_during_final_guard_cannot_launch_native_tool(tmp_path, monkeypatch):
from contextlib import contextmanager
from test_native_repair import repair_worker_fixture
from cbb_refresh_verify.native_repair import RepairTarget
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
data = json.loads(job.read_text('utf-8'))
data['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
job.write_text(json.dumps(data), encoding='utf-8')
calls = []
@contextmanager
def guard(*a, **kw):
calls.append(True)
yield {'target': RepairTarget(Path(data['project']), Path(data['database']))}
Path(data['cancel_signal']).touch()
monkeypatch.setattr('cbb_refresh_verify.maintenance_entry.maintenance_target_guard', guard)
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('late native launch'))
assert ui.repair_worker_main(job) == 1
assert len(calls) == 1 and not actions
def test_verified_cbb_refusal_is_not_hidden_by_secondary_release_failure():
from cbb_refresh_verify.verify_runner import classify_failure_category
detail = ('BackAnnotate: Back Annotation is not allowed on verified (or once verified) Reusable Blocks.'
'\nPCB_RELEASE_UNCONFIRMED: not released')
assert classify_failure_category(detail) == 'CBB_REIMPORT_REQUIRED'
import json
from pathlib import Path
import pytest
def output(project, database, *, fault=False, busy=False):
text = f'Loading project file [{project}].\nChecking if project is in use.\n'
if fault:
text += (f'Project database [{database}] is inconsistent. It has been manually copied while the iCDB Server was running. '
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue.\n")
return text + ('Project is in use.\n' if busy else
"Project is not in use. Full iCDB Project Backup's functionality is available.\nBackup information loaded correctly.\n")
@pytest.mark.parametrize('fault,busy,status,repair', [
(False, False, 'NOT_IN_USE', False), (True, False, 'NOT_IN_USE', True),
(True, True, 'IN_USE', False), (False, True, 'IN_USE', False)])
def test_native_ownership_and_repair_need_are_separate(tmp_path, fault, busy, status, repair):
from cbb_refresh_verify.native_occupancy import classify_inspection
project, database = tmp_path/'A.prj', tmp_path/'database'
result = classify_inspection(project, database, output(project, database, fault=fault, busy=busy))
assert result['status'] == status
assert result['repair_required'] is repair
@pytest.mark.parametrize('case', ['progress', 'wrong_project', 'wrong_database', 'stale_verdict', 'generic_repair'])
def test_incomplete_or_foreign_output_cannot_authorize_repair(tmp_path, case):
from cbb_refresh_verify.native_occupancy import classify_inspection
project, database = tmp_path/'A.prj', tmp_path/'database'
text = output(project, database, fault=True)
if case == 'progress': text = f'Loading project file [{project}].\nChecking if project is in use.'
if case == 'wrong_project': text = output(tmp_path/'Other.prj', database, fault=True)
if case == 'wrong_database': text = output(project, tmp_path/'other', fault=True)
if case == 'stale_verdict': text += 'Checking if project is in use.\n'
if case == 'generic_repair': text = output(project, database) + 'Please try to repair the project!'
assert classify_inspection(project, database, text)['repair_required'] is False
@pytest.mark.parametrize('fault,busy', [(False, False), (True, False), (False, True)])
def test_inspection_mode_only_observes_and_closes_its_tool(tmp_path, monkeypatch, fault, busy):
import win32con
from test_native_repair import repair_worker_fixture
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
job.write_text(json.dumps(data), encoding='utf-8')
monkeypatch.setattr(ui, '_repair_command', lambda *a: pytest.fail('inspection resolved Repair command'))
monkeypatch.setattr(ui, '_native_output', lambda *_: output(data['project'], data['database'], fault=fault, busy=busy))
assert ui.repair_worker_main(job) == 0
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['status'] == ('IN_USE' if busy else 'NOT_IN_USE')
assert result['release']['native_exited'] is True
assert result['repair_required'] is (fault and not busy)
assert actions == [(100, win32con.WM_CLOSE)]
def test_generic_project_backup_shell_is_accepted_as_the_single_target_window(tmp_path, monkeypatch):
import json
from test_native_repair import repair_worker_fixture
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
job.write_text(json.dumps(data), encoding='utf-8')
monkeypatch.setattr(ui, '_native_output', lambda windows: (
f'Loading project file [{data["project"]}].\nChecking if project is in use.\n'
"Project is not in use. Full iCDB Project Backup's functionality is available.\n"
'Backup information loaded correctly.'))
assert ui.repair_worker_main(job) == 0
def test_only_check_never_counts_as_repair_success():
from cbb_refresh_verify.icdb_maintenance import maintenance_counts
from cbb_refresh_verify.verify_runner import VerifyResult
counts = maintenance_counts([VerifyResult('CHECKED', safe_to_continue=True)])
assert counts['passed'] == counts['repaired'] == 0
assert counts['checked_without_repair'] == 1
def test_cancelled_probe_returns_within_grace_without_killing_native(tmp_path, monkeypatch):
from threading import Event
from types import SimpleNamespace
from cbb_refresh_verify import native_repair as native
from cbb_refresh_verify.native_repair import RepairTarget
stop = Event(); ticks = [0.0]; actions = []
def sleep(seconds):
ticks[0] += seconds
stop.set()
monkeypatch.setattr(native, 'time', SimpleNamespace(monotonic=lambda: ticks[0], sleep=sleep))
class Worker:
pid = 123
def __init__(self, *a): pass
def bind_cancellation(self, p): pass
def poll(self): return None
def request_stop(self): actions.append('cancel')
def close(self): actions.append('close_handles')
def kill(self): pytest.fail('native owner must not be killed')
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
result = native.run_native_repair(RepairTarget(tmp_path/'A.prj', tmp_path/'database'),
tmp_path/'evidence', timeout_seconds=600, inspection_only=True, stop=stop)
assert ticks[0] < 6
assert result['status'] == 'CANCELLED_UNRELEASED'
assert result['release']['safe_to_continue'] is False
assert actions[-1] == 'close_handles'
def test_ui_keeps_processing_events_and_passes_cancel_to_native_task(qtbot, tmp_path, monkeypatch):
from threading import Event
from PySide6.QtCore import QTimer
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
entered = Event(); cancelled = Event(); ticks = []
def verify(req, *, stop, **kw):
entered.set()
if stop.wait(3): cancelled.set()
return VerifyResult('CANCELLED')
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_verify', verify)
window = load_window(qtbot, tmp_path, monkeypatch,
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
window.search_edit.setText('Beta')
timer = QTimer(window); timer.setInterval(10); timer.timeout.connect(lambda: ticks.append(True)); timer.start()
window.repair_icdb_all()
qtbot.waitUntil(entered.is_set)
qtbot.waitUntil(lambda: len(ticks) >= 3)
assert not window.busy and window._icdb_active() and window.stop_button.isEnabled()
window.stop_button.click()
qtbot.waitUntil(lambda: not window._icdb_active())
assert cancelled.is_set()
@pytest.mark.parametrize('extra', ['foreign_session', 'extra_error'])
def test_foreign_or_additional_fault_is_never_a_clean_inspection(tmp_path, extra):
from cbb_refresh_verify.native_occupancy import classify_inspection
project, database = tmp_path/'A.prj', tmp_path/'database'
text = output(project, database, fault=extra == 'extra_error')
if extra == 'foreign_session':
text += ('The last server session on different server machine lost the connection to the database. '
'Machine:[SERVER] Path:[C:/Other/Work/database] session:[old]')
else:
text += 'ERROR: shared symbol database unavailable'
assert classify_inspection(project, database, text)['status'] == 'UNCONFIRMED'
def test_unconfirmed_inspection_closes_known_main_at_timeout(tmp_path, monkeypatch):
import win32con
from test_native_repair import repair_worker_fixture
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
data = json.loads(job.read_text('utf-8')); data['inspection_only'] = True
job.write_text(json.dumps(data), encoding='utf-8')
monkeypatch.setattr(ui, '_native_output', lambda *_: 'Unrecognized response')
assert ui.repair_worker_main(job) == 1
result = json.loads((root/'repair-result.json').read_text('utf-8'))
assert result['status'] == 'UNCONFIRMED'
assert result['release']['native_exited'] is True
assert actions == [(100, win32con.WM_CLOSE)]
def test_directory_scan_honors_cancel_between_entries(tmp_path):
from cbb_refresh_verify.scoped_manifest import scan_tree
for i in range(10): (tmp_path/f'{i}.dat').touch()
calls = []
def cancel():
calls.append(True)
if len(calls) == 3: raise RuntimeError('CANCELLED')
with pytest.raises(RuntimeError, match='CANCELLED'):
scan_tree(tmp_path, check=cancel)
assert len(calls) == 3
def test_cancel_during_final_guard_cannot_launch_native_tool(tmp_path, monkeypatch):
from contextlib import contextmanager
from test_native_repair import repair_worker_fixture
from cbb_refresh_verify.native_repair import RepairTarget
ui, root, job, actions = repair_worker_fixture(tmp_path, monkeypatch, 'active')
data = json.loads(job.read_text('utf-8'))
data['maintenance_context'] = {'library': str(tmp_path/'lib.lmc'), 'block': 'CBB1'}
job.write_text(json.dumps(data), encoding='utf-8')
calls = []
@contextmanager
def guard(*a, **kw):
calls.append(True)
yield {'target': RepairTarget(Path(data['project']), Path(data['database']))}
Path(data['cancel_signal']).touch()
monkeypatch.setattr('cbb_refresh_verify.maintenance_entry.maintenance_target_guard', guard)
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('late native launch'))
assert ui.repair_worker_main(job) == 1
assert len(calls) == 1 and not actions
def test_verified_cbb_refusal_is_not_hidden_by_secondary_release_failure():
from cbb_refresh_verify.verify_runner import classify_failure_category
detail = ('BackAnnotate: Back Annotation is not allowed on verified (or once verified) Reusable Blocks.'
'\nPCB_RELEASE_UNCONFIRMED: not released')
assert classify_failure_category(detail) == 'CBB_REIMPORT_REQUIRED'
+1 -1
View File
@@ -446,7 +446,7 @@ def test_repair_without_application_backup_still_rejects_busy_database(tmp_path,
try:
monkeypatch.setattr(ui.subprocess, 'Popen', lambda *a, **kw: pytest.fail('busy database launched'))
assert ui.repair_worker_main(job) == 1
assert 'REPAIR_DATABASE_IN_USE' in json.loads((root/'repair-result.json').read_text())['detail']
assert 'REPAIR_DATABASE_IN_USE' in json.loads((root/'repair-result.json').read_text(encoding='utf-8'))['detail']
finally:
handle.Close()
+65
View File
@@ -0,0 +1,65 @@
from cbb_refresh_verify import network_path as network
from test_network_path import FakeWNet
def test_releasing_a_keeps_shared_mapping_until_retained_b_releases(monkeypatch):
monkeypatch.setattr(network, '_retained_path_leases', {})
backend = FakeWNet()
original_a = network.LibraryPathLease.acquire(r'\\server\share\A\lib.lmc', backend=backend)
b = network.LibraryPathLease.acquire(r'\\server\share\B\lib.lmc', backend=backend)
original_a.retain_for_recovery(); b.retain_for_recovery()
current_a = network.LibraryPathLease.acquire(r'\\server\share\A\lib.lmc', backend=backend)
network.release_retained_path_leases(
{'status': 'RELEASE_CONFIRMED', 'library': str(original_a.mentor_path)}, current_lease=current_a)
current_a.close()
assert backend.cancelled == [] and b._retained_for_recovery and b.created
network.release_retained_path_leases({'status': 'RELEASE_CONFIRMED', 'library': str(b.mentor_path)})
assert backend.cancelled == [original_a.drive]
def test_unbound_directory_cannot_accept_an_arbitrary_sibling_library_proof(monkeypatch):
monkeypatch.setattr(network, '_retained_path_leases', {})
lease = network.LibraryPathLease.acquire(r'\\server\share\Folder', backend=FakeWNet())
lease.retain_for_recovery()
proof = {'status': 'RELEASE_CONFIRMED', 'library': r'\\server\share\Folder\other.lmc'}
assert not lease.release_after_recovery(proof)
# The library reader binds the selected LMC before retaining a loaded lease.
lease.mentor_path = lease.mentor_path/'chosen.lmc'
assert not lease.release_after_recovery(proof)
proof['library'] = r'\\server\share\Folder\chosen.lmc'
assert lease.release_after_recovery(proof)
def test_closing_scanner_lease_preserves_an_unpublished_live_reader_lease():
backend = FakeWNet()
scanner = network.LibraryPathLease.acquire(r'\\server\share\A\lib.lmc', backend=backend)
reader = network.LibraryPathLease.acquire(r'\\server\share\B\lib.lmc', backend=backend)
scanner.close()
assert not backend.cancelled and reader.created
reader.close()
assert backend.cancelled == [scanner.drive]
def test_acquire_and_close_do_not_race_before_new_reader_is_registered():
from threading import Event, Thread
entered, release = Event(), Event()
class Backend(FakeWNet):
block = False
def mappings(self):
snapshot = super().mappings()
if self.block:
entered.set(); assert release.wait(3)
return snapshot
backend = Backend()
scanner = network.LibraryPathLease.acquire(r'\\server\share\A\lib.lmc', backend=backend)
backend.block = True
leases = []
reader = Thread(target=lambda: leases.append(network.LibraryPathLease.acquire(
r'\\server\share\B\lib.lmc', backend=backend)))
closer = Thread(target=scanner.close)
reader.start(); assert entered.wait(1)
closer.start(); release.set()
reader.join(2); closer.join(2)
assert leases and not backend.cancelled and leases[0].created
leases[0].close()
assert backend.cancelled == [scanner.drive]
+69
View File
@@ -21,3 +21,72 @@ def test_malformed_wmi_response_is_not_empty_owner_list(monkeypatch):
monkeypatch.setattr(subprocess, 'run', run)
with pytest.raises(RuntimeError, match='OWNER_QUERY_UNCONFIRMED'):
query_owners(['ExpeditionPCB.exe'])
def test_full_snapshot_timeout_is_bounded_and_not_idle(monkeypatch):
from cbb_refresh_verify.owner_probe import query_process_snapshot
import json
from pathlib import Path
def hang(command, **kw):
assert json.loads(Path(command[-1]).read_text('utf-8')) == {'snapshot_version': 1}
assert 0 < kw['timeout'] <= .5
raise subprocess.TimeoutExpired(command, kw['timeout'])
monkeypatch.setattr(subprocess, 'run', hang)
with pytest.raises(RuntimeError, match='OWNER_QUERY_TIMEOUT'):
query_process_snapshot(timeout_seconds=.5)
def test_full_snapshot_keeps_unknown_processes_and_creation_identity(monkeypatch):
from cbb_refresh_verify.owner_probe import query_process_snapshot
import json
from pathlib import Path
rows = [{'pid': 0, 'parent': 0, 'name': 'System Idle Process',
'command': '', 'executable': '', 'created': ''},
{'pid': 999, 'parent': 100, 'name': 'unlisted-child.exe',
'command': 'unlisted-child.exe', 'executable': 'C:/native/unlisted-child.exe',
'created': '20261105123456.000000+480'}]
def run(command, **kw):
Path(command[-1]).with_name('result.json').write_text(json.dumps({
'snapshot_version': 1, 'owners': rows}), encoding='utf-8')
return subprocess.CompletedProcess(command, 0)
monkeypatch.setattr(subprocess, 'run', run)
assert query_process_snapshot() == rows
@pytest.mark.parametrize('change', ['version', 'created', 'duplicate', 'pid'])
def test_full_snapshot_rejects_incomplete_response(monkeypatch, change):
from cbb_refresh_verify.owner_probe import query_process_snapshot
import json
from pathlib import Path
row = {'pid': 10, 'parent': 1, 'name': 'child.exe', 'command': '',
'executable': '', 'created': ''}
record = {'snapshot_version': 1, 'owners': [row]}
if change == 'version': record['snapshot_version'] = 2
if change == 'created': del row['created']
if change == 'duplicate': record['owners'].append(dict(row))
if change == 'pid': row['pid'] = -1
def run(command, **kw):
Path(command[-1]).with_name('result.json').write_text(json.dumps(record), encoding='utf-8')
return subprocess.CompletedProcess(command, 0)
monkeypatch.setattr(subprocess, 'run', run)
with pytest.raises(RuntimeError, match='OWNER_QUERY_UNCONFIRMED'):
query_process_snapshot()
def test_full_snapshot_helper_does_not_filter_unknown_descendants(tmp_path, monkeypatch):
from cbb_refresh_verify.owner_probe import owner_probe_main
import win32com.client
from types import SimpleNamespace
import json
queries = []
def query(sql):
queries.append(sql)
return [SimpleNamespace(ProcessId=42, ParentProcessId=12, Name='custom-native-child.exe',
CommandLine='custom-native-child.exe', ExecutablePath='C:/custom-native-child.exe',
CreationDate='creation-time')]
monkeypatch.setattr(win32com.client, 'GetObject', lambda _: SimpleNamespace(ExecQuery=query))
job = tmp_path/'request.json'; job.write_text('{"snapshot_version": 1}')
assert owner_probe_main(job) == 0
assert len(queries) == 1 and 'WHERE' not in queries[0]
row = json.loads(job.with_name('result.json').read_text('utf-8'))['owners'][0]
assert row['name'] == 'custom-native-child.exe' and row['created'] == 'creation-time'
+242 -242
View File
@@ -1,242 +1,242 @@
from dataclasses import replace
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QMessageBox
from cbb_refresh_verify.management import Capability, ManagementRequest, ManagementResult
from cbb_refresh_verify.verify_runner import VerifyResult
def failed_repair(path, *, safe=False):
return VerifyResult('FAIL', error_category='CBB_REIMPORT_REQUIRED',
stderr='Back Annotation is not allowed on verified (or once verified) Reusable Blocks.',
evidence_path=path, safe_to_continue=safe,
recovery_attempts=({'native_status': 'REPAIRED', 'status': 'REPAIR_VALIDATION_FAILED',
'validation_passed': False},))
def recovery_window(qtbot, tmp_path, monkeypatch, result=None):
from test_ui_filters import load_window
adapter = SimpleNamespace(capabilities=lambda: {op: Capability(True, 'available')
for op in ('add', 'update', 'remove')})
result = result or failed_repair(tmp_path/'maintenance/result.json')
window = load_window(qtbot, tmp_path, monkeypatch, management_adapter=adapter,
verifier=lambda _: result, status_refresher=lambda names, path: {n: 'PENDING' for n in names})
window.search_edit.setText('Beta')
window.repair_icdb_all()
qtbot.waitUntil(lambda: not window.busy)
return window, result
def test_failed_repair_offers_copy_import_bound_to_failed_target(qtbot, tmp_path, monkeypatch):
window, failed = recovery_window(qtbot, tmp_path, monkeypatch)
assert '副本' in window.summary.text()
action = next(b for b in window.summary.buttons() if '副本' in b.text())
window.search_edit.setText('Alpha')
window.select_visible_button.click()
action.click()
dialog = window.management_dialog
requests = dialog.requests()
assert len(requests) == 1 and requests[0].name == 'Beta'
assert requests[0].partition == 'Power' and requests[0].operation == 'update'
assert requests[0].source is None and requests[0].auto_verify
assert '修复未完成' in dialog.status_label.text()
assert '手动备份' in dialog.status_label.text()
assert str(failed.evidence_path) in dialog.output.toPlainText()
dialog.reject()
assert failed.status == 'FAIL'
assert window.reimport_button.isEnabled()
def test_declining_reimport_confirmation_does_not_check_release_or_write(qtbot, tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
window, _ = recovery_window(qtbot, tmp_path, monkeypatch)
window.summary.close()
window.reimport_button.click()
dialog = window.management_dialog
source = tmp_path/'copy/test.prj'; source.parent.mkdir(); source.touch()
dialog.add_sources([source])
monkeypatch.setattr(locks, 'release_retained_library', lambda *a: pytest.fail('unconfirmed release'))
confirmations = []
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **kw:
confirmations.append(a[2]) or QMessageBox.No)
dialog.execute_button.click()
assert not dialog.busy and not dialog.executed
assert 'Beta' in confirmations[0] and str(source) in confirmations[0]
assert '副本' in confirmations[0] and '先移除' in confirmations[0]
dialog.reject()
@pytest.mark.parametrize('result', [VerifyResult('CHECKED'), VerifyResult('PASS', library_flag='GREEN'),
VerifyResult('BLOCKED', error_category='ICDB_DATABASE_IN_USE', safe_to_continue=False),
VerifyResult('FAIL', stderr='unknown error')])
def test_no_reimport_offer_for_unconfirmed_diagnosis_or_success(qtbot, tmp_path, monkeypatch, result):
window, _ = recovery_window(qtbot, tmp_path, monkeypatch, result)
assert not window.reimport_button.isVisible()
assert not any('副本' in b.text() for b in window.summary.buttons())
def test_changing_library_invalidates_old_reimport_offer(qtbot, tmp_path, monkeypatch):
window, _ = recovery_window(qtbot, tmp_path, monkeypatch)
old_action = next(b for b in window.summary.buttons() if '副本' in b.text())
window.lmc_edit.setText('another.lmc')
old_action.click()
assert not getattr(window, 'management_dialog', None)
assert not window.reimport_button.isVisible()
def request(tmp_path):
library = tmp_path/'lib/mentor.lmc'; library.parent.mkdir(); library.touch()
source = tmp_path/'copy/Block.prj'; source.parent.mkdir(); source.touch()
return ManagementRequest('update', library, 'Block', source=source, evidence_dir=tmp_path/'management')
def test_release_failure_preserves_failure_and_never_dispatches_management(tmp_path, monkeypatch):
from cbb_refresh_verify.reimport_recovery import run_reimport_recovery
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.management as management
req = request(tmp_path)
monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block'))
def denied(*a): raise locks.LibraryBusy('PCB still active: 123')
monkeypatch.setattr(locks, 'release_retained_library', denied)
monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: pytest.fail('unsafe write'))
results = run_reimport_recovery([req], previous_evidence={'Block': tmp_path/'old/result.json'},
evidence_dir=tmp_path/'reimport')
assert results[0].status == 'BLOCKED' and not results[0].safe_to_continue
assert '123' in results[0].detail
import json
record = json.loads(results[0].evidence_path.read_text('utf-8'))
assert record['previous_evidence']['Block'] == str(tmp_path/'old/result.json')
assert record['stage'] == 'release_failed'
def test_cancel_during_release_prevents_import(tmp_path, monkeypatch):
from cbb_refresh_verify.reimport_recovery import run_reimport_recovery
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.management as management
req = request(tmp_path); stop = Event()
monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block'))
def release(*a):
stop.set()
return {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'}
monkeypatch.setattr(locks, 'release_retained_library', release)
monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: pytest.fail('cancelled write'))
results = run_reimport_recovery([req], previous_evidence={'Block': 'old.json'},
evidence_dir=tmp_path/'reimport', stop=stop)
assert results == []
@pytest.mark.parametrize('uploaded_status', ['UPLOADED', 'UPLOADED_VERIFY_FAILED', 'UPLOADED_VERIFIED'])
def test_copy_recovery_keeps_native_management_outcome_and_original_evidence(tmp_path, monkeypatch, uploaded_status):
from cbb_refresh_verify.reimport_recovery import run_reimport_recovery
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.management as management
import json
req = request(tmp_path)
old = tmp_path/'old.json'; old.write_text('{"status":"FAIL"}', encoding='utf-8')
before = old.read_bytes()
monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block'))
monkeypatch.setattr(locks, 'release_retained_library', lambda *a:
{'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'})
expected = ManagementResult('update', req.library, req.name, req.partition, req.source,
True, 'complete', uploaded_status, True)
monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: [expected])
results = run_reimport_recovery([req], previous_evidence={'Block': str(old)},
evidence_dir=tmp_path/'reimport')
assert results == [expected] and old.read_bytes() == before
record = json.loads(next((tmp_path/'reimport').glob('*/recovery.json')).read_text('utf-8'))
assert record['original_repair_succeeded'] is False
assert record['results'][0]['status'] == uploaded_status and record['version_review_required']
def test_incomplete_copy_never_releases_or_removes_target(tmp_path, monkeypatch):
from cbb_refresh_verify.reimport_recovery import run_reimport_recovery
import cbb_refresh_verify.library_lock as locks
req = request(tmp_path) # Empty PRJ is deliberately incomplete.
monkeypatch.setattr(locks, 'release_retained_library', lambda *a: pytest.fail('incomplete source'))
results = run_reimport_recovery([req], previous_evidence={'Block': 'old.json'},
evidence_dir=tmp_path/'reimport')
assert results[0].status == 'BLOCKED' and results[0].stage == 'preflight'
def test_recovery_uses_background_release_then_existing_management(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.management as management
req = request(tmp_path); entered, finish = Event(), Event(); calls = []
monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block'))
def release(*a):
entered.set(); assert finish.wait(5)
calls.append('release')
return {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'}
monkeypatch.setattr(locks, 'release_retained_library', release)
def run(items, **kw):
calls.append('management')
return [ManagementResult('update', req.library, req.name, req.partition, req.source,
True, 'complete', 'UPLOADED_VERIFIED', True)]
monkeypatch.setattr(management, 'run_management_batch', run)
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **kw: QMessageBox.Yes)
dialog = ManagementDialog([req], recovery_from={'Block': 'old.json'})
qtbot.addWidget(dialog)
ticks = []
timer = QTimer(); timer.setInterval(10); timer.timeout.connect(lambda: ticks.append(1)); timer.start()
try:
dialog.execute_button.click()
qtbot.waitUntil(entered.is_set)
qtbot.waitUntil(lambda: len(ticks) >= 3)
assert calls == [] and dialog.busy
finally:
finish.set()
qtbot.waitUntil(lambda: not dialog.busy)
timer.stop()
assert calls == ['release', 'management']
assert '版本待核对' in dialog.status_label.text()
def test_recovery_dialog_keeps_internal_details_in_optional_log(qtbot, tmp_path):
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
req = request(tmp_path)
dialog = ManagementDialog([req], recovery_from={'Block': 'old-result.json'})
qtbot.addWidget(dialog); dialog.show()
assert dialog.output.isHidden()
assert not any(word in dialog.status_label.text() for word in ('原生', '证据', '检查点', '记录保留'))
detail = 'OWNER_QUERY_TIMEOUT: diagnostic internals'
result = ManagementResult('update', req.library, req.name, req.partition, req.source,
True, 'release_check', 'BLOCKED', False, detail, tmp_path/'recovery.json')
dialog._result([result])
assert detail not in dialog.status_label.text()
assert '日志' in dialog.status_label.text()
dialog.logs_button.click()
assert dialog.output.isVisible() and detail in dialog.output.toPlainText()
def test_main_stop_during_recovery_release_cancels_import(qtbot, tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.management as management
window, _ = recovery_window(qtbot, tmp_path, monkeypatch)
window.summary.close(); window.reimport_button.click()
dialog = window.management_dialog
source = tmp_path/'copy/source.prj'; source.parent.mkdir(); source.touch()
dialog.add_sources([source])
monkeypatch.setattr(management, 'source_project', lambda *a: (source, source, 'Beta'))
entered, finish = Event(), Event()
def release(*args):
entered.set(); assert finish.wait(5)
return {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'}
monkeypatch.setattr(locks, 'release_retained_library', release)
dispatched = []
monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: dispatched.append(a) or [])
dialog.execute_button.click()
try:
qtbot.waitUntil(entered.is_set)
window.stop_button.click()
assert dialog.stop.is_set()
finally:
finish.set(); qtbot.waitUntil(lambda: not dialog.busy)
dialog.reject()
assert dispatched == []
from dataclasses import replace
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
from PySide6.QtCore import QTimer
from PySide6.QtWidgets import QMessageBox
from cbb_refresh_verify.management import Capability, ManagementRequest, ManagementResult
from cbb_refresh_verify.verify_runner import VerifyResult
def failed_repair(path, *, safe=False):
return VerifyResult('FAIL', error_category='CBB_REIMPORT_REQUIRED',
stderr='Back Annotation is not allowed on verified (or once verified) Reusable Blocks.',
evidence_path=path, safe_to_continue=safe,
recovery_attempts=({'native_status': 'REPAIRED', 'status': 'REPAIR_VALIDATION_FAILED',
'validation_passed': False},))
def recovery_window(qtbot, tmp_path, monkeypatch, result=None):
from test_ui_filters import load_window
adapter = SimpleNamespace(capabilities=lambda: {op: Capability(True, 'available')
for op in ('add', 'update', 'remove')})
result = result or failed_repair(tmp_path/'maintenance/result.json')
window = load_window(qtbot, tmp_path, monkeypatch, management_adapter=adapter,
verifier=lambda _: result, status_refresher=lambda names, path: {n: 'PENDING' for n in names})
window.search_edit.setText('Beta')
window.repair_icdb_all()
qtbot.waitUntil(lambda: not window._icdb_active())
return window, result
def test_failed_repair_offers_copy_import_bound_to_failed_target(qtbot, tmp_path, monkeypatch):
window, failed = recovery_window(qtbot, tmp_path, monkeypatch)
assert '副本' in window.summary.text()
action = next(b for b in window.summary.buttons() if '副本' in b.text())
window.search_edit.setText('Alpha')
window.select_visible_button.click()
action.click()
dialog = window.management_dialog
requests = dialog.requests()
assert len(requests) == 1 and requests[0].name == 'Beta'
assert requests[0].partition == 'Power' and requests[0].operation == 'update'
assert requests[0].source is None and requests[0].auto_verify
assert '修复未完成' in dialog.status_label.text()
assert '手动备份' in dialog.status_label.text()
assert str(failed.evidence_path) in dialog.output.toPlainText()
dialog.reject()
assert failed.status == 'FAIL'
assert window.reimport_button.isEnabled()
def test_declining_reimport_confirmation_does_not_check_release_or_write(qtbot, tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
window, _ = recovery_window(qtbot, tmp_path, monkeypatch)
window.summary.close()
window.reimport_button.click()
dialog = window.management_dialog
source = tmp_path/'copy/test.prj'; source.parent.mkdir(); source.touch()
dialog.add_sources([source])
monkeypatch.setattr(locks, 'release_retained_library', lambda *a: pytest.fail('unconfirmed release'))
confirmations = []
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **kw:
confirmations.append(a[2]) or QMessageBox.No)
dialog.execute_button.click()
assert not dialog.busy and not dialog.executed
assert 'Beta' in confirmations[0] and str(source) in confirmations[0]
assert '副本' in confirmations[0] and '先移除' in confirmations[0]
dialog.reject()
@pytest.mark.parametrize('result', [VerifyResult('CHECKED'), VerifyResult('PASS', library_flag='GREEN'),
VerifyResult('BLOCKED', error_category='ICDB_DATABASE_IN_USE', safe_to_continue=False),
VerifyResult('FAIL', stderr='unknown error')])
def test_no_reimport_offer_for_unconfirmed_diagnosis_or_success(qtbot, tmp_path, monkeypatch, result):
window, _ = recovery_window(qtbot, tmp_path, monkeypatch, result)
assert not window.reimport_button.isVisible()
assert not any('副本' in b.text() for b in window.summary.buttons())
def test_changing_library_invalidates_old_reimport_offer(qtbot, tmp_path, monkeypatch):
window, _ = recovery_window(qtbot, tmp_path, monkeypatch)
old_action = next(b for b in window.summary.buttons() if '副本' in b.text())
window.lmc_edit.setText('another.lmc')
old_action.click()
assert not getattr(window, 'management_dialog', None)
assert not window.reimport_button.isVisible()
def request(tmp_path):
library = tmp_path/'lib/mentor.lmc'; library.parent.mkdir(); library.touch()
source = tmp_path/'copy/Block.prj'; source.parent.mkdir(); source.touch()
return ManagementRequest('update', library, 'Block', source=source, evidence_dir=tmp_path/'management')
def test_release_failure_preserves_failure_and_never_dispatches_management(tmp_path, monkeypatch):
from cbb_refresh_verify.reimport_recovery import run_reimport_recovery
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.management as management
req = request(tmp_path)
monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block'))
def denied(*a): raise locks.LibraryBusy('PCB still active: 123')
monkeypatch.setattr(locks, 'release_retained_library', denied)
monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: pytest.fail('unsafe write'))
results = run_reimport_recovery([req], previous_evidence={'Block': tmp_path/'old/result.json'},
evidence_dir=tmp_path/'reimport')
assert results[0].status == 'BLOCKED' and not results[0].safe_to_continue
assert '123' in results[0].detail
import json
record = json.loads(results[0].evidence_path.read_text('utf-8'))
assert record['previous_evidence']['Block'] == str(tmp_path/'old/result.json')
assert record['stage'] == 'release_failed'
def test_cancel_during_release_prevents_import(tmp_path, monkeypatch):
from cbb_refresh_verify.reimport_recovery import run_reimport_recovery
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.management as management
req = request(tmp_path); stop = Event()
monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block'))
def release(*a):
stop.set()
return {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'}
monkeypatch.setattr(locks, 'release_retained_library', release)
monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: pytest.fail('cancelled write'))
results = run_reimport_recovery([req], previous_evidence={'Block': 'old.json'},
evidence_dir=tmp_path/'reimport', stop=stop)
assert results == []
@pytest.mark.parametrize('uploaded_status', ['UPLOADED', 'UPLOADED_VERIFY_FAILED', 'UPLOADED_VERIFIED'])
def test_copy_recovery_keeps_native_management_outcome_and_original_evidence(tmp_path, monkeypatch, uploaded_status):
from cbb_refresh_verify.reimport_recovery import run_reimport_recovery
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.management as management
import json
req = request(tmp_path)
old = tmp_path/'old.json'; old.write_text('{"status":"FAIL"}', encoding='utf-8')
before = old.read_bytes()
monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block'))
monkeypatch.setattr(locks, 'release_retained_library', lambda *a:
{'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'})
expected = ManagementResult('update', req.library, req.name, req.partition, req.source,
True, 'complete', uploaded_status, True)
monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: [expected])
results = run_reimport_recovery([req], previous_evidence={'Block': str(old)},
evidence_dir=tmp_path/'reimport')
assert results == [expected] and old.read_bytes() == before
record = json.loads(next((tmp_path/'reimport').glob('*/recovery.json')).read_text('utf-8'))
assert record['original_repair_succeeded'] is False
assert record['results'][0]['status'] == uploaded_status and record['version_review_required']
def test_incomplete_copy_never_releases_or_removes_target(tmp_path, monkeypatch):
from cbb_refresh_verify.reimport_recovery import run_reimport_recovery
import cbb_refresh_verify.library_lock as locks
req = request(tmp_path) # Empty PRJ is deliberately incomplete.
monkeypatch.setattr(locks, 'release_retained_library', lambda *a: pytest.fail('incomplete source'))
results = run_reimport_recovery([req], previous_evidence={'Block': 'old.json'},
evidence_dir=tmp_path/'reimport')
assert results[0].status == 'BLOCKED' and results[0].stage == 'preflight'
def test_recovery_uses_background_release_then_existing_management(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.management as management
req = request(tmp_path); entered, finish = Event(), Event(); calls = []
monkeypatch.setattr(management, 'source_project', lambda *a: (req.source, req.source, 'Block'))
def release(*a):
entered.set(); assert finish.wait(5)
calls.append('release')
return {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'}
monkeypatch.setattr(locks, 'release_retained_library', release)
def run(items, **kw):
calls.append('management')
return [ManagementResult('update', req.library, req.name, req.partition, req.source,
True, 'complete', 'UPLOADED_VERIFIED', True)]
monkeypatch.setattr(management, 'run_management_batch', run)
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **kw: QMessageBox.Yes)
dialog = ManagementDialog([req], recovery_from={'Block': 'old.json'})
qtbot.addWidget(dialog)
ticks = []
timer = QTimer(); timer.setInterval(10); timer.timeout.connect(lambda: ticks.append(1)); timer.start()
try:
dialog.execute_button.click()
qtbot.waitUntil(entered.is_set)
qtbot.waitUntil(lambda: len(ticks) >= 3)
assert calls == [] and dialog.busy
finally:
finish.set()
qtbot.waitUntil(lambda: not dialog.busy)
timer.stop()
assert calls == ['release', 'management']
assert '版本待核对' in dialog.status_label.text()
def test_recovery_dialog_keeps_internal_details_in_optional_log(qtbot, tmp_path):
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
req = request(tmp_path)
dialog = ManagementDialog([req], recovery_from={'Block': 'old-result.json'})
qtbot.addWidget(dialog); dialog.show()
assert dialog.output.isHidden()
assert not any(word in dialog.status_label.text() for word in ('原生', '证据', '检查点', '记录保留'))
detail = 'OWNER_QUERY_TIMEOUT: diagnostic internals'
result = ManagementResult('update', req.library, req.name, req.partition, req.source,
True, 'release_check', 'BLOCKED', False, detail, tmp_path/'recovery.json')
dialog._result([result])
assert detail not in dialog.status_label.text()
assert '日志' in dialog.status_label.text()
dialog.logs_button.click()
assert dialog.output.isVisible() and detail in dialog.output.toPlainText()
def test_main_stop_during_recovery_release_cancels_import(qtbot, tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.management as management
window, _ = recovery_window(qtbot, tmp_path, monkeypatch)
window.summary.close(); window.reimport_button.click()
dialog = window.management_dialog
source = tmp_path/'copy/source.prj'; source.parent.mkdir(); source.touch()
dialog.add_sources([source])
monkeypatch.setattr(management, 'source_project', lambda *a: (source, source, 'Beta'))
entered, finish = Event(), Event()
def release(*args):
entered.set(); assert finish.wait(5)
return {'status': 'RELEASE_CONFIRMED', 'evidence_path': 'release.json'}
monkeypatch.setattr(locks, 'release_retained_library', release)
dispatched = []
monkeypatch.setattr(management, 'run_management_batch', lambda *a, **kw: dispatched.append(a) or [])
dialog.execute_button.click()
try:
qtbot.waitUntil(entered.is_set)
window.stop_button.click()
assert dialog.stop.is_set()
finally:
finish.set(); qtbot.waitUntil(lambda: not dialog.busy)
dialog.reject()
assert dispatched == []
+130
View File
@@ -0,0 +1,130 @@
from pathlib import Path
from PySide6.QtCore import Qt
def test_preview_lists_residuals_and_does_not_close_before_confirmation(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
plan = {'library': str(tmp_path/'lib.lmc'), 'sessions': [
{'project': 'A', 'name': 'iCDBProjectBackup.exe', 'pid': 10, 'detail': '可正常关闭'}]}
monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda *_: plan)
calls = []
monkeypatch.setattr(library_lock, 'release_residual_sessions', lambda *a, **k: calls.append(a))
dialog = ResidualReleaseDialog(tmp_path/'lib.lmc', tmp_path/'evidence')
qtbot.addWidget(dialog); dialog.show()
qtbot.waitUntil(lambda: not dialog.busy)
assert dialog.table.item(0, 0).text() == 'A'
assert dialog.table.item(0, 2).text() == '10'
assert not calls
dialog.close()
assert not calls
def test_empty_process_list_explains_historical_records_without_claiming_activity(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda *_: {
'library': str(tmp_path/'lib.lmc'), 'sessions': [], 'previous_records': [
{'path': 'old-record.json', 'time': '2026-11-04T09:43:50+00:00', 'pid': 57076}]})
dialog = ResidualReleaseDialog(tmp_path/'lib.lmc', tmp_path/'evidence')
qtbot.addWidget(dialog)
qtbot.waitUntil(lambda: not dialog.busy)
assert '未发现活跃会话' in dialog.message.text()
assert '历史操作记录' in dialog.message.text() and '2026-11-04' in dialog.message.text()
assert dialog.confirm_button.isEnabled() and not dialog.force_button.isEnabled()
dialog.close()
def test_confirm_releases_full_plan_and_only_emits_actual_library_proof(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
plan = {'library': str(tmp_path/'lib.lmc'), 'sessions': [
{'project': name, 'name': 'iCDBProjectBackup.exe', 'pid': pid, 'detail': '可正常关闭'}
for name, pid in [('A', 10), ('B', 20)]]}
monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda *_: plan)
proof = {'status': 'RELEASE_CONFIRMED', 'library': plan['library'], 'evidence_path': 'proof.json'}
calls = []
def release(actual, *a, **kw):
calls.append(actual)
return {'status': 'RELEASE_CONFIRMED', 'proof': proof, 'sessions': [
{**row, 'release_status': 'RELEASED', 'detail': '已正常退出'} for row in actual['sessions']]}
monkeypatch.setattr(library_lock, 'release_residual_sessions', release)
dialog = ResidualReleaseDialog(tmp_path/'lib.lmc', tmp_path/'evidence')
qtbot.addWidget(dialog); dialog.show()
released = []
dialog.released.connect(released.append)
qtbot.waitUntil(lambda: not dialog.busy)
qtbot.mouseClick(dialog.confirm_button, Qt.LeftButton)
qtbot.waitUntil(lambda: not dialog.busy)
assert calls == [plan] and released == [proof]
assert '已释放 2' in dialog.message.text()
assert not dialog.confirm_button.isEnabled()
def test_main_window_opens_confirmation_list_and_returns_to_idle_when_closed(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify import library_lock
monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda library, **kw:
{'library': str(library), 'sessions': []})
window = load_window(qtbot, tmp_path, monkeypatch)
window.check_library_release()
dialog = getattr(window, 'release_dialog', None)
assert dialog is not None, 'Release entry must preview sessions before cleanup'
qtbot.waitUntil(lambda: not dialog.busy)
assert window.busy and dialog.confirm_button.isEnabled()
dialog.close()
qtbot.waitUntil(lambda: not window.busy)
def test_force_close_is_explicit_and_cancel_does_not_release(qtbot, tmp_path, monkeypatch):
from PySide6.QtWidgets import QMessageBox
from cbb_refresh_verify import library_lock
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
plan = {'library': str(tmp_path/'lib.lmc'), 'sessions': [
{'project': 'A', 'name': 'ExpeditionPCB.exe', 'pid': 10, 'detail': '窗口无响应'}]}
monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda *_: plan)
calls = []
def release(actual, *a, **kw):
calls.append(kw['force'])
return {'status': 'PARTIAL', 'sessions': [{**plan['sessions'][0], 'release_status': 'WAITING'}]}
monkeypatch.setattr(library_lock, 'release_residual_sessions', release)
dialog = ResidualReleaseDialog(tmp_path/'lib.lmc', tmp_path/'evidence')
qtbot.addWidget(dialog)
qtbot.waitUntil(lambda: not dialog.busy)
monkeypatch.setattr(QMessageBox, 'warning', lambda *a: QMessageBox.Cancel)
dialog.force_button.click()
assert not calls
monkeypatch.setattr(QMessageBox, 'warning', lambda *a: QMessageBox.Yes)
dialog.force_button.click()
qtbot.waitUntil(lambda: not dialog.busy)
assert calls == [True]
def test_released_batch_can_resume_only_its_unexecuted_items(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: VerifyResult('FAIL', stderr='release unconfirmed', safe_to_continue=False))
window._run(['Beta', 'Gamma'])
qtbot.waitUntil(lambda: not window.busy)
action = getattr(window, '_resume_batch_action', None)
assert action is not None and not action.isEnabled()
library = Path(window.mentor_lmc_path or window.loaded_path)
from cbb_refresh_verify import library_lock
monkeypatch.setattr(library_lock, 'inspect_residual_sessions', lambda *_:
{'library': str(library), 'sessions': []})
monkeypatch.setattr(library_lock, 'release_residual_sessions', lambda *a, **kw:
{'status': 'RELEASE_CONFIRMED', 'sessions': [], 'proof': {'status': 'RELEASE_CONFIRMED',
'library': str(library), 'evidence_path': str(tmp_path/'proof.json')}})
window._residual_release_action.click()
qtbot.waitUntil(lambda: not window.release_dialog.busy)
window.release_dialog.confirm_button.click()
qtbot.waitUntil(lambda: not window.release_dialog.busy)
window.release_dialog.close()
qtbot.waitUntil(lambda: not window.busy)
assert window.summary.isVisible()
assert action.isEnabled()
calls = []
monkeypatch.setattr(window, '_run', lambda names, **kw: calls.append((names, kw)))
action.click()
assert calls == [(['Gamma'], {'maintenance': False})]
+229
View File
@@ -0,0 +1,229 @@
from pathlib import Path
from types import SimpleNamespace
import pytest
def api():
from cbb_refresh_verify import library_lock
inspect = getattr(library_lock, 'inspect_residual_sessions', None)
release = getattr(library_lock, 'release_residual_sessions', None)
assert callable(inspect) and callable(release), 'Missing confirmed residual-session release workflow'
return inspect, release
def row(pid, project, *, name='iCDBProjectBackup.exe'):
return {'pid': pid, 'name': name, 'parent': 1, 'created': f'created-{pid}',
'executable': 'C:/Mentor/'+name, 'command': f'{name} -p "{project}"'}
def test_preview_limits_to_selected_projects_and_keeps_process_identity(tmp_path, monkeypatch):
inspect, _ = api()
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'lib.lmc'; library.touch()
a = library.parent/'ReusableBlocksLP/A/Work/A.prj'
b = library.parent/'ReusableBlocksLP/B/Work/B.prj'
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [row(10, a), row(20, b)])
monkeypatch.setattr(sessions, '_process_identity', lambda r: {'created_handle': r['created'], 'image': r['executable']})
monkeypatch.setattr(sessions, '_process_windows', lambda pids: {p: [] for p in pids})
result = inspect(library, block_names=('A',))
assert [r['pid'] for r in result['sessions']] == [10]
assert result['sessions'][0]['created'] == 'created-10'
def test_unknown_scope_is_visible_but_never_closed_even_with_force(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'lib.lmc'; library.touch()
process = row(10, ''); process['command'] = 'LibraryManager.exe'
process['name'] = 'LibraryManager.exe'
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
monkeypatch.setattr(sessions, '_process_identity', lambda r: {'created_handle': 'old', 'image': r['executable']})
plan = sessions.inspect_residual_sessions(library)
assert plan['sessions'] and plan['sessions'][0]['scope_confirmed'] is False
monkeypatch.setattr(sessions, '_request_close', lambda *a, **kw: pytest.fail('closed unknown scope'))
monkeypatch.setattr(sessions, '_force_close', lambda *a, **kw: pytest.fail('ended unknown scope'))
for force in (False, True):
result = sessions.release_residual_sessions(plan, tmp_path.parent/'release-evidence'/tmp_path.name, force=force)
assert result['status'] == 'PARTIAL'
# A request file becoming readable must not expand the user's consent list.
monkeypatch.setattr('cbb_refresh_verify.library_lock._owner_matches_scope', lambda *a: True)
result = sessions.release_residual_sessions(plan, tmp_path.parent/'release-evidence'/tmp_path.name, force=True)
assert result['status'] == 'PARTIAL'
@pytest.mark.parametrize('name,title,children,expected', [
('iCDBProjectBackup.exe', 'iCDB Project Backup - test', [], True),
('ExpeditionPCB.exe', 'Expedition PCB - Reusable Block', [], True),
('ExpeditionPCB.exe', 'Design.pcb - Expedition PCB', [], True),
('iCDBProjectBackup.exe', 'iCDB Project Backup - test', [{'class': 'msctls_progress32', 'text': ''}], False),
])
def test_only_idle_supported_native_windows_are_offered_for_close(name, title, children, expected):
api()
from cbb_refresh_verify.residual_sessions import close_target
windows = [{'hwnd': 100, 'class': 'Afx:main', 'title': title, 'enabled': True,
'children': children, 'documents': [], 'output': 'Backup information loaded correctly.'}]
target, reason = close_target(name, windows)
assert bool(target) is expected
if not expected: assert reason
def test_confirmation_rechecks_pid_reuse_and_never_posts_to_replacement(tmp_path, monkeypatch):
inspect, release = api()
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'lib.lmc'; library.touch()
process = row(10, tmp_path/'ReusableBlocksLP/A/Work/A.prj')
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process.copy()])
monkeypatch.setattr(sessions, '_process_identity', lambda r: {'created_handle': 'old', 'image': r['executable']})
monkeypatch.setattr(sessions, '_process_windows', lambda _: {10: []})
plan = inspect(library)
process['created'] = 'replacement'
monkeypatch.setattr(sessions, '_request_close', lambda *_: pytest.fail('closed replacement PID'))
monkeypatch.setattr(sessions, '_finish_library_release', lambda *_: {'status': 'RELEASE_CONFIRMED'})
result = release(plan, tmp_path.parent/'release-evidence'/tmp_path.name)
assert result['sessions'][0]['release_status'] == 'IDENTITY_CHANGED'
assert result['status'] == 'PARTIAL'
def test_close_requests_cover_whole_preview_and_failures_remain_per_item(tmp_path, monkeypatch):
inspect, release = api()
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'lib.lmc'; library.touch()
rows = [row(p, tmp_path/f'ReusableBlocksLP/{p}/Work/{p}.prj') for p in (10, 20)]
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: rows)
monkeypatch.setattr(sessions, '_process_identity', lambda r: {'created_handle': r['created'], 'image': r['executable']})
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
calls = []
monkeypatch.setattr(sessions, '_request_close', lambda r, *_, **kw: calls.append(r['pid']) or
{'release_status': 'RELEASED' if r['pid'] == 10 else 'WAITING', 'detail': 'native window pending'})
monkeypatch.setattr(sessions, '_finish_library_release', lambda *_: pytest.fail('partial release cleared library marker'))
result = release(inspect(library), tmp_path.parent/'release-evidence'/tmp_path.name)
assert calls == [10, 20]
assert result['status'] == 'PARTIAL'
assert [r['release_status'] for r in result['sessions']] == ['RELEASED', 'WAITING']
def test_no_remaining_processes_rechecks_and_clears_old_metadata(tmp_path, monkeypatch):
inspect, release = api()
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'lib.lmc'; library.touch()
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [])
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
proof = {'status': 'RELEASE_CONFIRMED', 'library': str(library), 'evidence_path': 'proof.json'}
monkeypatch.setattr(sessions, '_finish_library_release', lambda *_: proof)
result = release(inspect(library), tmp_path.parent/'release-evidence'/tmp_path.name)
assert result['status'] == 'RELEASE_CONFIRMED' and result['proof'] == proof
def test_empty_session_scan_still_exposes_historical_operation_record(tmp_path, monkeypatch):
import json
from cbb_refresh_verify import residual_sessions as sessions
from cbb_refresh_verify.library_lock import blocker_path
library = tmp_path/'lib.lmc'; library.touch()
marker = blocker_path(library)
marker.write_text(json.dumps({'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
'library': str(library), 'lease_id': 'a'*32, 'pid': 57076,
'status': 'OWNER_RELEASE_UNCONFIRMED', 'time': '2026-11-04T09:43:50+00:00'}))
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [])
result = sessions.inspect_residual_sessions(library)
assert result['sessions'] == []
assert result['previous_records'][0]['path'] == str(marker)
assert result['previous_records'][0]['time'].startswith('2026-11-04')
assert marker.exists()
@pytest.mark.parametrize('output', [None, 'Repairing project\nRepair backup created successfully.',
'Repairing project\nBackup information loaded correctly.\nRestoring project'])
def test_backup_intermediate_success_does_not_allow_cooperative_close(output):
from cbb_refresh_verify.residual_sessions import close_target
window = {'hwnd': 10, 'class': 'Afx:main', 'title': 'iCDB Project Backup - test',
'children': [], 'enabled': True, 'output': output}
assert close_target('iCDBProjectBackup.exe', [window])[0] is None
def test_force_requires_separate_explicit_argument_and_rechecks_identity(tmp_path, monkeypatch):
from cbb_refresh_verify import residual_sessions as sessions
library = tmp_path/'lib.lmc'; library.touch()
process = row(10, tmp_path/'ReusableBlocksLP/A/Work/A.prj')
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process.copy()])
monkeypatch.setattr(sessions, '_process_identity', lambda r: {'created_handle': 'old', 'image': r['executable']})
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
monkeypatch.setattr(sessions, '_request_close', lambda *a, **k: {'release_status': 'WAITING', 'detail': 'hung'})
forced = []
monkeypatch.setattr(sessions, '_force_close', lambda r, **kw: forced.append(r['pid']) or
{'release_status': 'WAITING', 'detail': 'exiting'})
plan = sessions.inspect_residual_sessions(library)
evidence = tmp_path.parent/'release-evidence'/tmp_path.name
sessions.release_residual_sessions(plan, evidence)
assert not forced
sessions.release_residual_sessions(plan, evidence, force=True)
assert forced == [10]
process['created'] = 'reused'
sessions.release_residual_sessions(plan, evidence, force=True)
assert forced == [10]
def test_current_process_handle_identity_uses_real_windows_api():
import os
from cbb_refresh_verify.residual_sessions import _process_identity
identity = _process_identity({'pid': os.getpid()})
assert identity['created_handle'] and Path(identity['image']).is_file()
def test_force_checks_exact_handle_before_ending_owned_test_helper():
import subprocess
import sys
from cbb_refresh_verify.residual_sessions import _process_identity, _force_close
child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'],
creationflags=subprocess.CREATE_NO_WINDOW)
try:
process = {'pid': child.pid, **_process_identity({'pid': child.pid})}
changed = {**process, 'created_handle': 'different process'}
assert _force_close(changed)['release_status'] == 'IDENTITY_CHANGED'
assert child.poll() is None
assert _force_close(process)['release_status'] == 'RELEASED'
assert child.wait(3) == 1
finally:
if child.poll() is None:
child.terminate(); child.wait(3) # This test's sleep-only helper.
def test_partial_desktop_enumeration_never_offers_normal_close(monkeypatch):
import win32gui, win32service
from cbb_refresh_verify.residual_sessions import _process_windows, close_target
def failed(*_): raise OSError('desktop disappeared')
monkeypatch.setattr(win32gui, 'EnumWindows', failed)
monkeypatch.setattr(win32service, 'GetProcessWindowStation', lambda: SimpleNamespace(EnumDesktops=lambda: []))
windows = _process_windows({10})[10]
assert any(w['class'] == 'UNCONFIRMED' for w in windows)
windows.append({'hwnd': 100, 'class': 'Afx:main', 'title': 'Design - Expedition PCB',
'children': [], 'enabled': True})
assert close_target('ExpeditionPCB.exe', windows)[0] is None
@pytest.mark.parametrize('choice', [6, 7, 2])
def test_save_answers_require_current_exact_prompt_and_process(monkeypatch, choice):
import win32con, win32gui, win32process
from contextlib import nullcontext
from cbb_refresh_verify import residual_sessions as sessions
process = row(10, 'C:/Lib/ReusableBlocksLP/A/Work/A.prj')
process.update(created_handle='creation', image='pcb.exe')
dialog = {'hwnd': 100, 'class': '#32770', 'title': 'Expedition PCB', 'children': [
{'class': 'Static', 'text': 'Save changes to the modified design?'},
*[{'class': 'Button', 'text': text, 'enabled': True, 'id': code, 'hwnd': code}
for code, text in ((6, 'Yes'), (7, 'No'), (2, 'Cancel'))]]}
windows = [dialog]
process['prompt'] = sessions._save_question(windows)
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
monkeypatch.setattr(sessions, '_process_handle', lambda _: nullcontext(123))
monkeypatch.setattr(sessions, '_handle_identity', lambda _: {'created_handle': 'creation', 'image': 'pcb.exe'})
monkeypatch.setattr(sessions, '_process_windows', lambda _: {10: windows})
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (1, 10))
clicked = []
monkeypatch.setattr(win32gui, 'PostMessage', lambda *a: clicked.append(a))
sessions._answer_save_question(process, choice)
assert clicked == [(choice, win32con.BM_CLICK, 0, 0)]
dialog['children'][0]['text'] = 'Save changes to another modified design?'
with pytest.raises(ValueError, match='提示已变化'):
sessions._answer_save_question(process, choice)
assert len(clicked) == 1
+11
View File
@@ -12,6 +12,17 @@ def test_phase_duration_uses_worker_monotonic_time_not_delayed_poll_time():
assert timer.snapshot()[0]['pcb_startup'] == 132.0
def test_opening_check_ends_startup_and_close_without_starting_integration():
timer = RunTimings(clock=lambda: 50.0)
timer.record({'stage': 'pcb_launch', 'monotonic_seconds': 10})
timer.record({'stage': 'diagnostic_native_loaded_candidate', 'monotonic_seconds': 30})
timer.record({'stage': 'diagnostic_complete', 'monotonic_seconds': 38})
values, unfinished = timer.snapshot()
assert values['pcb_startup'] == 20
assert values['diagnostic_close'] == 8
assert 'integration' not in values and not unfinished
def test_action_and_save_subtimings_accumulate_real_durations():
timer = RunTimings(clock=lambda: 1000.0)
timer.record({'stage': 'integration_action_complete', 'action': 'ForwardAnnotate',
+3 -2
View File
@@ -112,7 +112,8 @@ def _without_authorized_checkpoint_cleanup(text):
"""Exempt exact protocol-checkpoint callsites, never the whole module."""
tree = ast.parse(text)
parents = {child: parent for parent in ast.walk(tree) for child in ast.iter_child_nodes(parent)}
allowed = {('LibraryLock', '_exit_owned'): 'marker', ('release_retained_library',): 'checkpoint'}
allowed = {('LibraryLock', '_exit_owned'): 'marker', ('LibraryLock', '__enter__'): 'marker',
('release_retained_library',): 'checkpoint'}
used, spans = set(), []
for call in ast.walk(tree):
if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)
@@ -126,7 +127,7 @@ def _without_authorized_checkpoint_cleanup(text):
scope = tuple(scope)
if scope in used or allowed.get(scope) != call.func.value.id:
continue
expected = ([] if scope == ('release_retained_library',) else [('missing_ok', True)])
expected = ([('missing_ok', True)] if scope == ('LibraryLock', '_exit_owned') else [])
keywords = [(k.arg, k.value.value if isinstance(k.value, ast.Constant) else None) for k in call.keywords]
if keywords == expected and call.lineno == call.end_lineno:
spans.append((call.lineno - 1, call.col_offset, call.end_col_offset))
+46
View File
@@ -0,0 +1,46 @@
"""Foreign PCB windows must not become this scan's evidence or cleanup targets."""
from dataclasses import replace
import os
from pathlib import Path
import pytest
@pytest.mark.parametrize('suffix,flag', [('.backup', '-ReusableCircuit'), ('', '-ReusableCircuitOther')])
def test_reusable_pcb_binding_requires_exact_path_and_switch(tmp_path, suffix, flag):
from cbb_refresh_verify.mentor_adapter import is_reusable_circuit_pcb
pcb = tmp_path/'Board.pcb'
assert not is_reusable_circuit_pcb('C:/Mentor/ExpeditionPCB.exe',
f'ExpeditionPCB.exe "{pcb}{suffix}" {flag}', pcb)
def test_agent_roundtrip_applies_pid_scope_and_rejects_window_changed_to_foreign_owner(tmp_path):
from test_dialog_agent import running_protocol, snapshot, FakeExecutor
from cbb_refresh_verify.dialog_models import DialogPhase, stable_fingerprint
class Probe:
value = snapshot()
scopes = []
def capture(self, phase, *, pids=None):
self.scopes.append(pids)
return (self.value,) if self.value.pid in pids else ()
def matches_identity(self, expected):
return self.value.pid == expected.pid
probe, executor = Probe(), FakeExecutor()
client, _, thread = running_protocol(tmp_path, probe, executor)
try:
assert client.observe(DialogPhase.PCB_STARTING, pids={99}) == ()
owned = client.observe(DialogPhase.PCB_STARTING, pids={20})[0]
probe.value = replace(probe.value, pid=99)
result = client.perform(hwnd=owned.hwnd, fingerprint=stable_fingerprint(owned),
action={'action': 'confirm', 'channels': ['win32_button_click']}, phase=DialogPhase.PCB_STARTING)
assert result.error_code == 'STALE_DIALOG' and not executor.calls
finally:
client.close(); thread.join(2)
def test_process_watch_polls_bound_handles_without_wmi(monkeypatch):
from cbb_refresh_verify import owner_probe
from cbb_refresh_verify.pcb_bridge import ProcessWatch
monkeypatch.setattr(owner_probe, 'query_owners', lambda *a, **kw: pytest.fail('Polled WMI during COM attach'))
with ProcessWatch({os.getpid()}) as watch:
assert all(watch.alive() for _ in range(20))
+12 -12
View File
@@ -47,7 +47,7 @@ def test_global_icdb_action_confirms_and_excludes_ready_rows(qtbot, tmp_path, mo
assert calls == []
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
window.icdb_repair_button.click()
qtbot.waitUntil(lambda: not window.busy)
qtbot.waitUntil(lambda: not window._icdb_active())
assert calls == ['PENDING']
def test_global_icdb_action_disabled_without_library_or_while_busy(qtbot):
@@ -72,11 +72,11 @@ def test_global_icdb_failure_preserves_untargeted_ready_and_stops_queue(qtbot, t
qtbot.waitUntil(lambda: not window.busy)
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
window.icdb_repair_button.click()
qtbot.waitUntil(lambda: not window.busy)
qtbot.waitUntil(lambda: not window._icdb_active())
assert calls == ['B']
assert 'A' in window.ready_names
assert window.cbb_table.item(1, 2).text() == '未知 / 需确认'
assert window.cbb_table.item(2, 3).text().startswith('SKIPPED')
assert window.cbb_table.item(2, 3).text() == '未检查'
def test_global_icdb_progress_and_check_summary(qtbot, tmp_path, monkeypatch):
from PySide6.QtWidgets import QMessageBox
@@ -92,7 +92,7 @@ def test_global_icdb_progress_and_check_summary(qtbot, tmp_path, monkeypatch):
window.lmc_edit.setText('lib.lmc'); window.load_library()
qtbot.waitUntil(lambda: not window.busy)
window.icdb_repair_button.click()
qtbot.waitUntil(lambda: not window.busy)
qtbot.waitUntil(lambda: not window._icdb_active())
assert 'lib.lmc' in confirmations[0]
assert '非 READY' in confirmations[0]
assert window.icdb_progress.value() == 1
@@ -284,7 +284,7 @@ def test_unc_library_uses_mentor_path_for_read_and_verify_and_releases_on_close(
assert calls == [lease.mentor_path]
assert window._request('CBB1').lmc_file == lease.mentor_path
window.close()
assert lease.closed
qtbot.waitUntil(lambda: lease.closed)
def test_advanced_options_are_copied_to_verify_request(qtbot, tmp_path):
@@ -353,12 +353,12 @@ def test_ui_default_timeout_matches_request_and_labels_inactivity(qtbot):
assert window.timeout_spin.value() == 600
assert window.timeout_spin.value() == VerifyRequest(Path('lib.lmc'), 'CBB1', Path('data')).timeout_seconds
assert '无进展' in window.timeout_spin.suffix()
def test_batch_summary_exposes_failures_only_report(qtbot, tmp_path):
window = MainWindow(reader=fake_reader, data_root=tmp_path)
qtbot.addWidget(window)
report=tmp_path/'reports/batch-20260929-test.log'
window._batch_done(([VerifyResult('FAIL',stderr='Mentor error')],report))
def test_batch_summary_exposes_failures_only_report(qtbot, tmp_path):
window = MainWindow(reader=fake_reader, data_root=tmp_path)
qtbot.addWidget(window)
report=tmp_path/'reports/batch-20260929-test.log'
window._batch_done(([VerifyResult('FAIL',stderr='Mentor error')],report))
assert '仅失败日志' in window.summary.detailedText()
assert str(report.with_name('failures-20260929-test.log')) in window.summary.detailedText()
+308
View File
@@ -0,0 +1,308 @@
"""No native applications or shared execution mutex are used by these regressions."""
import json
from dataclasses import replace
from pathlib import Path
from types import SimpleNamespace
import pytest
from cbb_refresh_verify import verify_runner as runner
from cbb_refresh_verify.status_bridge import BridgeResult
from test_verify_runner import fixture, request, PORTS_OK
@pytest.fixture
def isolated_verify(tmp_path, monkeypatch):
import win32event
fixture(tmp_path)
monkeypatch.setattr(win32event, 'CreateMutex', lambda *_: SimpleNamespace(Close=lambda: None))
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *_: 0)
monkeypatch.setattr(win32event, 'ReleaseMutex', lambda *_: None)
monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k:
{'safe_to_continue': True, 'remaining_pids': []})
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *_: None)
monkeypatch.setattr(runner, 'read_library_flag_if_available',
lambda *_: BridgeResult('READY', 'IsVerifiedReuseBlock', 1))
return request(tmp_path)
def test_invalid_proof_is_safe_before_worker_launch(isolated_verify, monkeypatch):
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker',
lambda *_: pytest.fail('invalid proof launched a worker'))
req = replace(isolated_verify, post_repair_proof=object())
results = runner.run_batch([req, req], verifier=lambda r: runner.run_verify(r, port_check=PORTS_OK))
assert [r.status for r in results] == ['BLOCKED', 'BLOCKED']
assert all(r.safe_to_continue for r in results)
@pytest.mark.parametrize('failure', ['directory', 'runtime', 'request', 'worker_log'])
def test_prelaunch_disk_failure_does_not_stop_independent_items(isolated_verify, monkeypatch, failure):
class FinishedWorker:
desktop = None
returncode = 0
def __init__(self, command, *_a, **_k):
Path(command[-1]).with_name('outcome.json').write_text('{"status":"PASS"}')
def poll(self): return 0
def close(self): pass
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', FinishedWorker)
mkdir, write, open_file = Path.mkdir, Path.write_text, Path.open
def make(path, *a, **k):
if failure == 'directory' and path.name.startswith('verify-'):
raise OSError('evidence volume unavailable')
return mkdir(path, *a, **k)
def save(path, *a, **k):
if path.name == {'runtime': 'runtime.json', 'request': 'request.json'}.get(failure):
raise OSError('evidence volume unavailable')
return write(path, *a, **k)
def opening(path, *a, **k):
if failure == 'worker_log' and path.name == 'worker.log':
raise OSError('evidence volume unavailable')
return open_file(path, *a, **k)
monkeypatch.setattr(Path, 'mkdir', make)
monkeypatch.setattr(Path, 'write_text', save)
monkeypatch.setattr(Path, 'open', opening)
from cbb_refresh_verify import library_lock as locks
try:
results = runner.run_batch([isolated_verify, isolated_verify],
verifier=lambda r: runner.run_verify(r, port_check=PORTS_OK))
assert all(r.safe_to_continue for r in results)
assert [r.status for r in results] == (['PASS', 'PASS'] if failure == 'runtime' else ['FAIL', 'FAIL'])
assert locks.LibraryLock(isolated_verify.lmc_file).key not in locks._owners
finally:
owner = locks._owners.pop(locks.LibraryLock(isolated_verify.lmc_file).key, None)
if owner: owner['handle'].Close()
def test_coordination_permission_failure_does_not_manufacture_native_owner(isolated_verify, monkeypatch):
from cbb_refresh_verify.library_lock import LibraryLock
def denied(_): raise PermissionError('coordination directory is read-only')
monkeypatch.setattr(LibraryLock, '__enter__', denied)
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker',
lambda *_: pytest.fail('permission failure launched native work'))
results = runner.run_batch([isolated_verify, isolated_verify],
verifier=lambda r: runner.run_verify(r, port_check=PORTS_OK))
assert [r.status for r in results] == ['FAIL', 'FAIL']
assert all(r.safe_to_continue and r.error_category == 'LIBRARY_ACCESS_FAILED' for r in results)
@pytest.mark.parametrize('launch_state', ['never_created', 'unknown', 'partially_created'])
def test_constructor_release_evidence_controls_batch_continuation(isolated_verify, monkeypatch, launch_state):
proven_rollback = launch_state == 'never_created'
launches = []
def fail_launch(*_a, **_k):
launches.append(True)
error = RuntimeError('worker launch failed')
if launch_state != 'unknown':
error.worker_launch_release = {'safe_to_continue': True, 'worker_exited': True,
'remaining_pids': [], 'process_created': not proven_rollback}
raise error
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', fail_launch)
from cbb_refresh_verify import library_lock as locks
try:
results = runner.run_batch([isolated_verify, isolated_verify],
verifier=lambda r: runner.run_verify(r, port_check=PORTS_OK))
assert len(launches) == (2 if proven_rollback else 1)
assert results[0].safe_to_continue is proven_rollback
if proven_rollback:
proof = json.loads(results[0].evidence_path.with_name('session-release.json').read_text('utf-8'))
assert proof['worker_exited'] and proof['safe_to_continue']
assert locks.LibraryLock(isolated_verify.lmc_file).key not in locks._owners
finally:
with locks._guard:
owner = locks._owners.pop(locks.LibraryLock(isolated_verify.lmc_file).key, None)
if owner:
owner['handle'].Close()
@pytest.mark.parametrize('filename', ['result.json', 'performance.json', 'bridge-status.json'])
def test_optional_evidence_write_failure_preserves_released_result(isolated_verify, monkeypatch, filename):
class FinishedWorker:
desktop = None
returncode = 0
def __init__(self, command, *_a, **_k):
Path(command[-1]).with_name('outcome.json').write_text('{"status":"PASS"}')
def poll(self): return 0
def close(self): pass
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', FinishedWorker)
original = Path.write_text
def write(path, *a, **k):
if path.name == filename:
raise OSError('report disk unavailable')
return original(path, *a, **k)
monkeypatch.setattr(Path, 'write_text', write)
results = runner.run_batch([isolated_verify, isolated_verify],
verifier=lambda r: runner.run_verify(r, port_check=PORTS_OK))
assert [r.status for r in results] == ['PASS', 'PASS']
assert all(r.safe_to_continue for r in results)
def test_progress_failure_does_not_stop_safe_batch(isolated_verify):
def failed_progress(*_):
raise RuntimeError('view was closed')
results = runner.run_batch([isolated_verify, isolated_verify],
verifier=lambda _: runner.VerifyResult('FAIL', safe_to_continue=True), progress=failed_progress)
assert len(results) == 2 and all(r.safe_to_continue for r in results)
def test_performance_progress_failure_preserves_release(isolated_verify, monkeypatch):
root = isolated_verify.evidence_dir
root.mkdir()
result = runner.VerifyResult('FAIL', safe_to_continue=True, evidence_path=root/'result.json')
monkeypatch.setattr(runner, '_run_verify', lambda *a, **k: result)
def progress(event):
if event['stage'] == 'performance':
raise RuntimeError('view was closed')
actual = runner._run_verify_serialized(isolated_verify, progress=progress)
assert actual.safe_to_continue and actual.status == 'FAIL'
def test_performance_logger_failure_preserves_release(isolated_verify, monkeypatch):
def unavailable_log(*_a, **_k):
raise OSError('log destination unavailable')
req = replace(isolated_verify, logging_context=SimpleNamespace(logger=SimpleNamespace(info=unavailable_log)))
monkeypatch.setattr(runner, '_run_verify', lambda *a, **k: runner.VerifyResult('FAIL', safe_to_continue=True))
result = runner._run_verify_serialized(req)
assert result.safe_to_continue and result.status == 'FAIL'
def test_management_unsafe_survives_switching_back_to_library(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.management import Capability
adapter = SimpleNamespace(capabilities=lambda: {op: Capability(True, 'available')
for op in ('add', 'update', 'remove')})
window = load_window(qtbot, tmp_path, monkeypatch, management_adapter=adapter)
window.path_lease_factory = lambda path: SimpleNamespace(mentor_path=path, close=lambda: None,
retain_for_recovery=lambda: None)
library_a = tmp_path/'a.lmc'
library_b = tmp_path/'b.lmc'
window._management_unsafe = True
window._management_unsafe_library = library_a
for library, blocked in [(library_b, False), (library_a, True)]:
window.lmc_edit.setText(str(library))
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
assert window._management_library_unsafe(library) is blocked
assert not window._management_block_reason('add')
assert window.batch_button.isEnabled()
@pytest.mark.parametrize('released', [True, False])
def test_batch_report_failure_preserves_ui_outcomes(qtbot, tmp_path, monkeypatch, released):
from test_ui_filters import load_window
import cbb_refresh_verify.ui.main_window as ui
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: runner.VerifyResult('FAIL', stderr='item failed', safe_to_continue=released),
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
retained = []
window.library_lease.retain_for_recovery = lambda: retained.append(True)
monkeypatch.setattr(ui, 'write_batch_report', lambda *_: (_ for _ in ()).throw(OSError('report unavailable')))
window._run(['Beta', 'Gamma'])
qtbot.waitUntil(lambda: not window.busy)
assert bool(retained) is not released
assert 'report unavailable' in window.output.toPlainText()
assert 'item failed' in window.output.toPlainText()
assert window.batch_button.isEnabled()
def test_release_check_clears_only_its_own_management_library(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.management import Capability
adapter = SimpleNamespace(capabilities=lambda: {op: Capability(True, 'available')
for op in ('add', 'update', 'remove')})
window = load_window(qtbot, tmp_path, monkeypatch, management_adapter=adapter)
window.path_lease_factory = lambda path: SimpleNamespace(mentor_path=path, close=lambda: None,
retain_for_recovery=lambda: None)
library_a, library_b = tmp_path/'a.lmc', tmp_path/'b.lmc'
for library in (library_a, library_b):
window._management_unsafe = True
window._management_unsafe_library = library
window._update()
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library',
lambda *_: {'status': 'RELEASE_CONFIRMED', 'library': str(library_a),
'evidence_path': str(tmp_path/'release.json')})
window.lmc_edit.setText(str(library_a))
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
window._complete_library_release(library_a, {'status': 'RELEASE_CONFIRMED',
'library': str(library_a), 'evidence_path': str(tmp_path/'release.json')})
qtbot.waitUntil(lambda: not window.busy)
assert not window._management_block_reason('add')
window.lmc_edit.setText(str(library_b))
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
assert window._management_library_unsafe(library_b)
assert not window._management_block_reason('add')
@pytest.mark.parametrize('alias', ['absolute', 'mapped'])
def test_native_backup_session_matches_library_alias_without_network_resolution(qtbot, tmp_path, monkeypatch, alias):
from test_ui_filters import load_window
window = load_window(qtbot, tmp_path, monkeypatch)
if alias == 'absolute':
current = Path.cwd()/'test.lmc'
session_library = Path('test.lmc')
session_lease = None
else:
current = Path('T:/folder/lib.lmc')
session_library = Path('S:/folder/lib.lmc')
window.library_lease = SimpleNamespace(mentor_path=current, display_path=current,
drive='T:', remote_root=r'\\server\share', close=lambda: None)
session_lease = SimpleNamespace(mentor_path=session_library, display_path=session_library,
drive='S:', remote_root=r'\\server\share')
window.mentor_lmc_path = current
window._native_backup_session = SimpleNamespace(library=session_library, path_lease=session_lease)
try:
with monkeypatch.context() as context:
context.setattr(Path, 'resolve', lambda *_a, **_k: pytest.fail('UI touched network resolution'))
assert window._native_backup_same_library()
finally:
window._native_backup_session = None
@pytest.mark.parametrize('proof_kind', ['valid', 'foreign', 'invalid', 'lease_error'])
def test_release_check_restores_current_mapping_only_after_matching_proof(qtbot, tmp_path, monkeypatch, proof_kind):
from test_ui_filters import load_window
from cbb_refresh_verify import network_path
window = load_window(qtbot, tmp_path, monkeypatch)
library = Path('test.lmc').absolute()
current = network_path.LibraryPathLease(library, library)
current.retain_for_recovery()
window.library_lease = current
window.mentor_lmc_path = library
window._management_unsafe = True
window._management_unsafe_library = library
session = SimpleNamespace(library=library, path_lease=current, process=SimpleNamespace(poll=lambda: 0))
window._native_backup_session = session
proof = {'status': 'UNCONFIRMED' if proof_kind == 'invalid' else 'RELEASE_CONFIRMED',
'library': str(tmp_path/'foreign.lmc') if proof_kind == 'foreign' else str(library),
'evidence_path': str(tmp_path/'release.json')}
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library', lambda *_: proof)
if proof_kind == 'lease_error':
def failed_release(*_a, **_k):
raise network_path.NetworkPathError('mapping release failed')
monkeypatch.setattr(network_path, 'release_retained_path_leases', failed_release)
try:
window._complete_library_release(library, proof)
qtbot.waitUntil(lambda: window._mapping_busy == 0)
qtbot.waitUntil(lambda: window._lease_pending == 0)
assert current._retained_for_recovery is (proof_kind != 'valid')
assert not current._closed
assert window._management_unsafe is (proof_kind != 'valid')
assert (window._native_backup_session is session) is (proof_kind != 'valid')
finally:
window._native_backup_session = None
network_path._retained_path_leases.pop(id(current), None)
def test_opening_evidence_failure_does_not_retain_library(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
window = load_window(qtbot, tmp_path, monkeypatch)
retained = []
window.library_lease.retain_for_recovery = lambda: retained.append(True)
window.recovery_path = tmp_path
def cannot_open(*_):
raise OSError('file viewer unavailable')
monkeypatch.setattr('os.startfile', cannot_open)
window.recover()
assert not retained
assert 'file viewer unavailable' in window.output.toPlainText()
+291 -291
View File
@@ -1,291 +1,291 @@
"""Local catalog scope and authoritative status refresh regression tests."""
import json
import time
from threading import Event
from pathlib import Path
from types import SimpleNamespace
import pytest
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QMessageBox
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.verify_runner import VerifyResult
MIXED = (
CbbRecord('Alpha', 'Power', status='READY'),
CbbRecord('Beta', 'Power', status='PENDING'),
CbbRecord('Gamma', 'Analog', status='UNKNOWN'),
CbbRecord('Delta', 'Analog', status='ERROR'),
CbbRecord('Missing', 'Power', status='READY'),
)
def load_window(qtbot, tmp_path, monkeypatch, records=MIXED, **kwargs):
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
import cbb_refresh_verify.ui.main_window as ui
monkeypatch.setattr(ui, 'preflight_skip_reason',
lambda _, name: 'missing project' if name == 'Missing' else None)
lease = SimpleNamespace(mentor_path=Path('test.lmc'), close=lambda: None,
retain_for_recovery=lambda: None)
window = MainWindow(reader=lambda _: LibraryReadResult(records), data_root=tmp_path,
path_lease_factory=lambda _: lease, **kwargs)
qtbot.addWidget(window)
window.lmc_edit.setText('test.lmc')
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
return window
def names(records):
return [record.name for record in records]
def test_search_and_filters_use_cached_catalog_and_count_visible_states(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
window.reader = lambda _: pytest.fail('filter reread Mentor')
assert window.visible_counts() == {'visible': 5, 'ready': 2, 'error': 3}
expected = {
'ready': ['Alpha', 'Missing'], 'non_ready': ['Beta', 'Gamma', 'Delta'],
'pending': ['Beta'], 'errors': ['Gamma', 'Delta'], 'missing': ['Missing'],
}
for mode, wanted in expected.items():
window.status_filter.setCurrentIndex(window.status_filter.findData(mode))
assert names(window.visible_records()) == wanted
window.status_filter.setCurrentIndex(window.status_filter.findData('all'))
window.search_edit.setText(' ANALOG ')
assert names(window.visible_records()) == ['Gamma', 'Delta']
assert window.visible_counts() == {'visible': 2, 'ready': 0, 'error': 2}
window.search_edit.setText('aLpH')
assert names(window.visible_records()) == ['Alpha']
assert '1' in window.counts_label.text()
def test_management_selection_includes_ready_and_missing_but_hiding_clears_checks(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
window.select_visible_button.click()
assert names(window.selected_records()) == ['Alpha', 'Beta', 'Gamma', 'Delta', 'Missing']
assert window.selected_records()[0].logical_type == 'LP'
window.search_edit.setText('power')
assert names(window.selected_records()) == ['Alpha', 'Beta', 'Missing']
window.search_edit.clear()
assert names(window.selected_records()) == ['Alpha', 'Beta', 'Missing']
window.clear_selection_button.click()
assert window.selected_records() == ()
def test_verify_all_and_selected_only_target_visible_non_ready_with_projects(qtbot, tmp_path, monkeypatch):
calls = []
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')),
status_refresher=lambda names, _: {name: 'READY' for name in names})
window.search_edit.setText('power')
window.select_visible_button.click()
window.verify_selected()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['Beta']
window.search_edit.setText('analog')
window.verify_all()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['Beta', 'Gamma', 'Delta']
def test_maintenance_confirmation_progress_and_report_use_visible_checked_subset(qtbot, tmp_path, monkeypatch):
calls, confirmations, refreshes = [], [], []
def refresh(targets, _):
refreshes.append(tuple(targets))
return {name: 'PENDING' for name in targets}
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')),
status_refresher=refresh)
window.search_edit.setText('analog')
window.cbb_table.item(3, 0).setCheckState(Qt.Checked)
monkeypatch.setattr(QMessageBox, 'question', lambda *args, **_: (
confirmations.append(args[2]) or QMessageBox.Yes))
window.repair_icdb_all()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['Delta']
assert refreshes == [('Delta',)]
assert '1' in confirmations[0] and '非 READY' in confirmations[0]
assert window.icdb_progress.maximum() == 1 and window.icdb_progress.value() == 1
report = json.loads(next((tmp_path/'reports').glob('icdb-*.json')).read_text(encoding='utf-8'))
assert report['includes_ready'] is False
assert report['target_names'] == ['Delta']
assert report['preflight_skipped'] == []
assert report['counts']['total'] == 1
assert window.search_edit.text() == 'analog'
assert window.cbb_table.item(3, 3).text() == 'PASS'
assert names(window.visible_records()) == ['Gamma', 'Delta']
assert window.visible_records()[1].status == 'PENDING'
def test_maintenance_defaults_to_visible_eligible_and_ready_only_checks_do_not_fallback(qtbot, tmp_path, monkeypatch):
calls = []
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')),
status_refresher=lambda targets, _: {name: 'PENDING' for name in targets})
monkeypatch.setattr(QMessageBox, 'question', lambda *_, **__: QMessageBox.Yes)
window.cbb_table.item(0, 0).setCheckState(Qt.Checked)
window.repair_icdb_all()
assert not window.busy and calls == []
window.clear_selection_button.click()
window.search_edit.setText('power')
window.repair_icdb_all()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['Beta']
def test_recovery_defaults_to_visible_checked_non_ready_and_skips_ready(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
window.search_edit.setText('power')
window.restore_backup()
assert [window.backup_dialog.block_combo.itemText(i)
for i in range(window.backup_dialog.block_combo.count())] == ['Beta']
window.backup_dialog.reject()
window.search_edit.clear()
window.cbb_table.item(3, 0).setCheckState(Qt.Checked)
window.restore_backup()
assert window.backup_dialog.block_combo.currentText() == 'Delta'
assert window.backup_dialog.block_combo.count() == 1
window.backup_dialog.reject()
def test_action_pass_does_not_promote_pending_without_authoritative_ready(qtbot, tmp_path, monkeypatch):
entered = []
window = load_window(qtbot, tmp_path, monkeypatch,
status_refresher=lambda targets, _: (entered.extend(targets) or {'Beta': 'READY'}))
window.status_filter.setCurrentIndex(window.status_filter.findData('pending'))
window.cbb_table.item(1, 0).setCheckState(Qt.Checked)
window._progress({'block': 'Beta', 'stage': 'PASS'})
assert names(window.visible_records()) == ['Beta']
assert window.visible_records()[0].status == 'PENDING'
window.refresh_affected_records(['Beta'])
qtbot.waitUntil(lambda: not window.busy)
assert entered == ['Beta']
assert window.visible_records() == ()
assert window.selected_records() == ()
assert window.status_filter.currentData() == 'pending'
window.status_filter.setCurrentIndex(window.status_filter.findData('ready'))
assert names(window.visible_records()) == ['Alpha', 'Beta', 'Missing']
assert window.cbb_table.item(1, 3).text() == 'PASS'
def test_refresh_failure_demotes_affected_without_losing_other_statuses(qtbot, tmp_path, monkeypatch):
def fail(*_):
raise OSError('bridge unavailable')
window = load_window(qtbot, tmp_path, monkeypatch, status_refresher=fail)
window.refresh_affected_records(['Alpha'])
qtbot.waitUntil(lambda: not window.busy)
assert window.visible_records()[0].status == 'UNKNOWN'
assert window.visible_records()[1].status == 'PENDING'
assert 'Alpha' not in window.ready_names
assert 'bridge unavailable' in window.output.toPlainText()
def test_unsafe_result_defers_native_refresh_and_retains_action_evidence(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: VerifyResult('FAIL', stderr='owner release unconfirmed',
safe_to_continue=False, evidence_path=tmp_path/'evidence.json'),
status_refresher=lambda *_: pytest.fail('unsafe owner was reopened'))
window.search_edit.setText('beta')
window.verify_all()
qtbot.waitUntil(lambda: not window.busy)
assert window.visible_records()[0].status == 'UNKNOWN'
assert window.cbb_table.item(1, 3).text() == 'FAIL: owner release unconfirmed'
assert str(tmp_path/'evidence.json') in window.output.toPlainText()
assert '暂缓原生状态复核' in window.cbb_table.item(1, 2).toolTip()
def test_refresh_callback_uses_only_known_affected_records_and_preserves_logical_type(qtbot, tmp_path, monkeypatch):
observed, callbacks = [], []
def refresh(targets, path):
observed.append((targets, path))
return {'X': 'READY'}
window = load_window(qtbot, tmp_path, monkeypatch,
records=(CbbRecord('X', 'Display label', logical_type='RULP', status='PENDING'),),
status_refresher=refresh)
assert window.refresh_affected_records(['unknown']) is False
assert window.refresh_affected_records(['X', 'X', 'unknown'], callbacks.append) is True
assert window.refresh_affected_records(['X']) is False
qtbot.waitUntil(lambda: not window.busy)
assert observed == [(('X',), Path('test.lmc'))]
assert callbacks == [(CbbRecord('X', 'Display label', logical_type='RULP', status='READY'),)]
def test_backup_completion_refreshes_status_without_dialog_close_unlocking_pending_refresh(qtbot, tmp_path, monkeypatch):
entered, release = Event(), Event()
def refresh(targets, _):
entered.set()
release.wait(3)
return {name: 'PENDING' for name in targets}
window = load_window(qtbot, tmp_path, monkeypatch, status_refresher=refresh)
window.search_edit.setText('beta')
window.restore_backup()
window.backup_dialog.started.emit('Beta')
window.backup_dialog.completed.emit('Beta', VerifyResult('PASS'))
try:
qtbot.waitUntil(entered.is_set)
window.backup_dialog.reject()
assert window.busy
finally:
release.set()
qtbot.waitUntil(lambda: not window.busy)
assert window.visible_records()[0].status == 'PENDING'
assert window.cbb_table.item(1, 3).text() == 'PASS'
def test_missing_project_keeps_explicit_authoritative_status(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
assert 'Ready' in window.cbb_table.item(4, 2).text()
assert '缺少工程' in window.cbb_table.item(4, 2).text()
def test_open_backup_dialog_cannot_restore_target_that_became_ready(qtbot, tmp_path, monkeypatch):
calls = []
window = load_window(qtbot, tmp_path, monkeypatch,
status_refresher=lambda targets, _: {name: 'READY' for name in targets})
window.search_edit.setText('beta')
window.restore_backup()
dialog = window.backup_dialog
source = tmp_path/'Beta.prj'
source.touch()
dialog.source_edit.setText(str(source))
dialog.recoverer = lambda *_, **__: (calls.append('restore') or VerifyResult('PASS'))
window.refresh_affected_records(['Beta'])
qtbot.waitUntil(lambda: not window.busy)
dialog.restore_button.click()
qtbot.waitUntil(lambda: not dialog.busy)
assert calls == []
assert '非 READY' in dialog.status_label.text()
dialog.reject()
@pytest.mark.parametrize('status', ['UNKNOWN', 'UNAVAILABLE', 'ERROR', 'TIMEOUT', 'MALFORMED', 'CRASHED',
'UNRECOGNIZED'])
def test_unconfirmed_statuses_are_non_ready_and_error_filter_candidates(qtbot, tmp_path, monkeypatch, status):
window = load_window(qtbot, tmp_path, monkeypatch, records=(CbbRecord('X', 'LP', status=status),))
window.status_filter.setCurrentIndex(window.status_filter.findData('non_ready'))
assert names(window.visible_records()) == ['X']
window.status_filter.setCurrentIndex(window.status_filter.findData('errors'))
assert names(window.visible_records()) == ['X']
@pytest.mark.parametrize('size', [381, 3000])
def test_large_catalog_local_filter_and_selection_remain_responsive(qtbot, tmp_path, monkeypatch, size):
records = tuple(CbbRecord(f'CBB{i:04}', 'Power' if i % 2 else 'Analog',
status='READY' if i % 3 == 0 else 'PENDING') for i in range(size))
start = time.perf_counter()
window = load_window(qtbot, tmp_path, monkeypatch, records=records)
loaded = time.perf_counter() - start
window.reader = lambda _: pytest.fail('local actions reread Mentor')
start = time.perf_counter()
window.search_edit.setText('power')
window.select_visible_button.click()
window.status_filter.setCurrentIndex(window.status_filter.findData('pending'))
window.clear_selection_button.click()
elapsed = time.perf_counter() - start
print(f'catalog rows={size} load={loaded:.3f}s local_actions={elapsed:.3f}s')
assert elapsed < 2.0
assert window.selected_records() == ()
"""Local catalog scope and authoritative status refresh regression tests."""
import json
import time
from threading import Event
from pathlib import Path
from types import SimpleNamespace
import pytest
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QMessageBox
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.verify_runner import VerifyResult
MIXED = (
CbbRecord('Alpha', 'Power', status='READY'),
CbbRecord('Beta', 'Power', status='PENDING'),
CbbRecord('Gamma', 'Analog', status='UNKNOWN'),
CbbRecord('Delta', 'Analog', status='ERROR'),
CbbRecord('Missing', 'Power', status='READY'),
)
def load_window(qtbot, tmp_path, monkeypatch, records=MIXED, **kwargs):
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
import cbb_refresh_verify.ui.main_window as ui
monkeypatch.setattr(ui, 'preflight_skip_reason',
lambda _, name: 'missing project' if name == 'Missing' else None)
lease = SimpleNamespace(mentor_path=Path('test.lmc'), close=lambda: None,
retain_for_recovery=lambda: None)
window = MainWindow(reader=lambda _: LibraryReadResult(records), data_root=tmp_path,
path_lease_factory=lambda _: lease, **kwargs)
qtbot.addWidget(window)
window.lmc_edit.setText('test.lmc')
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
return window
def names(records):
return [record.name for record in records]
def test_search_and_filters_use_cached_catalog_and_count_visible_states(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
window.reader = lambda _: pytest.fail('filter reread Mentor')
assert window.visible_counts() == {'visible': 5, 'ready': 2, 'error': 3}
expected = {
'ready': ['Alpha', 'Missing'], 'non_ready': ['Beta', 'Gamma', 'Delta'],
'pending': ['Beta'], 'errors': ['Gamma', 'Delta'], 'missing': ['Missing'],
}
for mode, wanted in expected.items():
window.status_filter.setCurrentIndex(window.status_filter.findData(mode))
assert names(window.visible_records()) == wanted
window.status_filter.setCurrentIndex(window.status_filter.findData('all'))
window.search_edit.setText(' ANALOG ')
assert names(window.visible_records()) == ['Gamma', 'Delta']
assert window.visible_counts() == {'visible': 2, 'ready': 0, 'error': 2}
window.search_edit.setText('aLpH')
assert names(window.visible_records()) == ['Alpha']
assert '1' in window.counts_label.text()
def test_management_selection_includes_ready_and_missing_but_hiding_clears_checks(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
window.select_visible_button.click()
assert names(window.selected_records()) == ['Alpha', 'Beta', 'Gamma', 'Delta', 'Missing']
assert window.selected_records()[0].logical_type == 'LP'
window.search_edit.setText('power')
assert names(window.selected_records()) == ['Alpha', 'Beta', 'Missing']
window.search_edit.clear()
assert names(window.selected_records()) == ['Alpha', 'Beta', 'Missing']
window.clear_selection_button.click()
assert window.selected_records() == ()
def test_verify_all_and_selected_only_target_visible_non_ready_with_projects(qtbot, tmp_path, monkeypatch):
calls = []
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')),
status_refresher=lambda names, _: {name: 'READY' for name in names})
window.search_edit.setText('power')
window.select_visible_button.click()
window.verify_selected()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['Beta']
window.search_edit.setText('analog')
window.verify_all()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['Beta', 'Gamma', 'Delta']
def test_maintenance_confirmation_progress_and_report_use_visible_checked_subset(qtbot, tmp_path, monkeypatch):
calls, confirmations, refreshes = [], [], []
def refresh(targets, _):
refreshes.append(tuple(targets))
return {name: 'PENDING' for name in targets}
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('CHECKED')),
status_refresher=refresh)
window.search_edit.setText('analog')
window.cbb_table.item(3, 0).setCheckState(Qt.Checked)
monkeypatch.setattr(QMessageBox, 'question', lambda *args, **_: (
confirmations.append(args[2]) or QMessageBox.Yes))
window.repair_icdb_all()
qtbot.waitUntil(lambda: not window._icdb_active())
assert calls == ['Delta']
assert refreshes == []
assert '1' in confirmations[0] and '非 READY' in confirmations[0]
assert window.icdb_progress.maximum() == 1 and window.icdb_progress.value() == 1
report = json.loads(next((tmp_path/'reports').glob('icdb-*.json')).read_text(encoding='utf-8'))
assert report['includes_ready'] is False
assert report['target_names'] == ['Delta']
assert report['preflight_skipped'] == []
assert report['counts']['total'] == 1
assert window.search_edit.text() == 'analog'
assert window.cbb_table.item(3, 3).text() == '未发现 ICDB 错误'
assert names(window.visible_records()) == ['Gamma', 'Delta']
assert window.visible_records()[1].status == 'ERROR'
def test_maintenance_defaults_to_visible_eligible_and_ready_only_checks_do_not_fallback(qtbot, tmp_path, monkeypatch):
calls = []
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda req: (calls.append(req.block_name) or VerifyResult('PASS')),
status_refresher=lambda targets, _: {name: 'PENDING' for name in targets})
monkeypatch.setattr(QMessageBox, 'question', lambda *_, **__: QMessageBox.Yes)
window.cbb_table.item(0, 0).setCheckState(Qt.Checked)
window.repair_icdb_all()
assert not window.busy and calls == []
window.clear_selection_button.click()
window.search_edit.setText('power')
window.repair_icdb_all()
qtbot.waitUntil(lambda: not window._icdb_active())
assert calls == ['Beta']
def test_recovery_defaults_to_visible_checked_non_ready_and_skips_ready(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
window.search_edit.setText('power')
window.restore_backup()
assert [window.backup_dialog.block_combo.itemText(i)
for i in range(window.backup_dialog.block_combo.count())] == ['Beta']
window.backup_dialog.reject()
window.search_edit.clear()
window.cbb_table.item(3, 0).setCheckState(Qt.Checked)
window.restore_backup()
assert window.backup_dialog.block_combo.currentText() == 'Delta'
assert window.backup_dialog.block_combo.count() == 1
window.backup_dialog.reject()
def test_action_pass_does_not_promote_pending_without_authoritative_ready(qtbot, tmp_path, monkeypatch):
entered = []
window = load_window(qtbot, tmp_path, monkeypatch,
status_refresher=lambda targets, _: (entered.extend(targets) or {'Beta': 'READY'}))
window.status_filter.setCurrentIndex(window.status_filter.findData('pending'))
window.cbb_table.item(1, 0).setCheckState(Qt.Checked)
window._progress({'block': 'Beta', 'stage': 'PASS'})
assert names(window.visible_records()) == ['Beta']
assert window.visible_records()[0].status == 'PENDING'
window.refresh_affected_records(['Beta'])
qtbot.waitUntil(lambda: not window.busy)
assert entered == ['Beta']
assert window.visible_records() == ()
assert window.selected_records() == ()
assert window.status_filter.currentData() == 'pending'
window.status_filter.setCurrentIndex(window.status_filter.findData('ready'))
assert names(window.visible_records()) == ['Alpha', 'Beta', 'Missing']
assert window.cbb_table.item(1, 3).text() == 'PASS'
def test_refresh_failure_demotes_affected_without_losing_other_statuses(qtbot, tmp_path, monkeypatch):
def fail(*_):
raise OSError('bridge unavailable')
window = load_window(qtbot, tmp_path, monkeypatch, status_refresher=fail)
window.refresh_affected_records(['Alpha'])
qtbot.waitUntil(lambda: not window.busy)
assert window.visible_records()[0].status == 'UNKNOWN'
assert window.visible_records()[1].status == 'PENDING'
assert 'Alpha' not in window.ready_names
assert 'bridge unavailable' in window.output.toPlainText()
def test_unsafe_result_defers_native_refresh_and_retains_action_evidence(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: VerifyResult('FAIL', stderr='owner release unconfirmed',
safe_to_continue=False, evidence_path=tmp_path/'evidence.json'),
status_refresher=lambda *_: pytest.fail('unsafe owner was reopened'))
window.search_edit.setText('beta')
window.verify_all()
qtbot.waitUntil(lambda: not window.busy)
assert window.visible_records()[0].status == 'UNKNOWN'
assert window.cbb_table.item(1, 3).text() == 'FAIL: owner release unconfirmed'
assert str(tmp_path/'evidence.json') in window.output.toPlainText()
assert '暂缓原生状态复核' in window.cbb_table.item(1, 2).toolTip()
def test_refresh_callback_uses_only_known_affected_records_and_preserves_logical_type(qtbot, tmp_path, monkeypatch):
observed, callbacks = [], []
def refresh(targets, path):
observed.append((targets, path))
return {'X': 'READY'}
window = load_window(qtbot, tmp_path, monkeypatch,
records=(CbbRecord('X', 'Display label', logical_type='RULP', status='PENDING'),),
status_refresher=refresh)
assert window.refresh_affected_records(['unknown']) is False
assert window.refresh_affected_records(['X', 'X', 'unknown'], callbacks.append) is True
assert window.refresh_affected_records(['X']) is False
qtbot.waitUntil(lambda: not window.busy)
assert observed == [(('X',), Path('test.lmc'))]
assert callbacks == [(CbbRecord('X', 'Display label', logical_type='RULP', status='READY'),)]
def test_backup_completion_refreshes_status_without_dialog_close_unlocking_pending_refresh(qtbot, tmp_path, monkeypatch):
entered, release = Event(), Event()
def refresh(targets, _):
entered.set()
release.wait(3)
return {name: 'PENDING' for name in targets}
window = load_window(qtbot, tmp_path, monkeypatch, status_refresher=refresh)
window.search_edit.setText('beta')
window.restore_backup()
window.backup_dialog.started.emit('Beta')
window.backup_dialog.completed.emit('Beta', VerifyResult('PASS'))
try:
qtbot.waitUntil(entered.is_set)
window.backup_dialog.reject()
assert window.busy
finally:
release.set()
qtbot.waitUntil(lambda: not window.busy)
assert window.visible_records()[0].status == 'PENDING'
assert window.cbb_table.item(1, 3).text() == 'PASS'
def test_missing_project_keeps_explicit_authoritative_status(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
assert 'Ready' in window.cbb_table.item(4, 2).text()
assert '缺少工程' in window.cbb_table.item(4, 2).text()
def test_open_backup_dialog_cannot_restore_target_that_became_ready(qtbot, tmp_path, monkeypatch):
calls = []
window = load_window(qtbot, tmp_path, monkeypatch,
status_refresher=lambda targets, _: {name: 'READY' for name in targets})
window.search_edit.setText('beta')
window.restore_backup()
dialog = window.backup_dialog
source = tmp_path/'Beta.prj'
source.touch()
dialog.source_edit.setText(str(source))
dialog.recoverer = lambda *_, **__: (calls.append('restore') or VerifyResult('PASS'))
window.refresh_affected_records(['Beta'])
qtbot.waitUntil(lambda: not window.busy)
dialog.restore_button.click()
qtbot.waitUntil(lambda: not dialog.busy)
assert calls == []
assert '非 READY' in dialog.status_label.text()
dialog.reject()
@pytest.mark.parametrize('status', ['UNKNOWN', 'UNAVAILABLE', 'ERROR', 'TIMEOUT', 'MALFORMED', 'CRASHED',
'UNRECOGNIZED'])
def test_unconfirmed_statuses_are_non_ready_and_error_filter_candidates(qtbot, tmp_path, monkeypatch, status):
window = load_window(qtbot, tmp_path, monkeypatch, records=(CbbRecord('X', 'LP', status=status),))
window.status_filter.setCurrentIndex(window.status_filter.findData('non_ready'))
assert names(window.visible_records()) == ['X']
window.status_filter.setCurrentIndex(window.status_filter.findData('errors'))
assert names(window.visible_records()) == ['X']
@pytest.mark.parametrize('size', [381, 3000])
def test_large_catalog_local_filter_and_selection_remain_responsive(qtbot, tmp_path, monkeypatch, size):
records = tuple(CbbRecord(f'CBB{i:04}', 'Power' if i % 2 else 'Analog',
status='READY' if i % 3 == 0 else 'PENDING') for i in range(size))
start = time.perf_counter()
window = load_window(qtbot, tmp_path, monkeypatch, records=records)
loaded = time.perf_counter() - start
window.reader = lambda _: pytest.fail('local actions reread Mentor')
start = time.perf_counter()
window.search_edit.setText('power')
window.select_visible_button.click()
window.status_filter.setCurrentIndex(window.status_filter.findData('pending'))
window.clear_selection_button.click()
elapsed = time.perf_counter() - start
print(f'catalog rows={size} load={loaded:.3f}s local_actions={elapsed:.3f}s')
assert elapsed < 2.0
assert window.selected_records() == ()
+166
View File
@@ -0,0 +1,166 @@
"""Lease calls may wait on WNet; the Qt event loop must never wait for them."""
from pathlib import Path
from threading import Event, get_ident
from types import SimpleNamespace
from PySide6.QtCore import QTimer
from test_ui_filters import load_window
def slow_lease(main_thread):
entered, release, closed = Event(), Event(), Event()
calls = []
def retain():
assert get_ident() != main_thread, 'retain blocked the Qt thread'
calls.append('retain')
entered.set()
assert release.wait(3)
def close():
assert get_ident() != main_thread, 'close blocked the Qt thread'
calls.append('close')
closed.set()
lease = SimpleNamespace(mentor_path=Path('test.lmc'), retain_for_recovery=retain, close=close)
return lease, entered, release, closed, calls
def test_unsafe_background_retains_before_a_later_cross_library_close(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.verify_runner import VerifyResult
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: VerifyResult('FAIL', safe_to_continue=False))
lease, entered, release, closed, calls = slow_lease(get_ident())
window.library_lease = lease
try:
window._run(['Beta'], maintenance=True)
qtbot.waitUntil(entered.is_set)
ticks = []
QTimer.singleShot(0, lambda: ticks.append(True))
window.lmc_edit.setText('other.lmc')
qtbot.waitUntil(lambda: bool(ticks))
assert window.search_edit.isEnabled() and not closed.is_set()
release.set()
qtbot.waitUntil(closed.is_set)
assert calls == ['retain', 'close']
finally:
release.set()
qtbot.waitUntil(lambda: window.pool.activeThreadCount() == 0)
def test_management_dialog_finish_waits_for_mapping_cleanup_without_freezing_filters(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.management import ManagementResult
window = load_window(qtbot, tmp_path, monkeypatch)
library = Path(window.mentor_lmc_path)
window._management_operation_library = library
window._management_unsafe = True
window._management_unsafe_library = library
window.busy = True
entered, release = Event(), Event()
main_thread = get_ident()
def restore(*args, **kwargs):
assert get_ident() != main_thread, 'mapping release blocked the Qt thread'
entered.set()
assert release.wait(3)
monkeypatch.setattr('cbb_refresh_verify.network_path.release_retained_path_leases', restore)
proof = {'status': 'RELEASE_CONFIRMED', 'library': str(library)}
result = ManagementResult('remove', library, 'Beta', 'Logical-Physical', None, False,
'complete', 'BLOCKED', True, release_proof=proof)
try:
window._management_completed([result])
window._management_closed()
qtbot.waitUntil(entered.is_set)
assert window.busy and window.search_edit.isEnabled() and window.status_filter.isEnabled()
assert window._management_library_unsafe(library)
release.set()
qtbot.waitUntil(lambda: not window.busy)
assert not window._management_library_unsafe(library)
finally:
release.set()
qtbot.waitUntil(lambda: window.pool.activeThreadCount() == 0)
def test_release_dialog_finish_cannot_clear_busy_before_mapping_cleanup(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
library = Path(window.mentor_lmc_path)
entered, release = Event(), Event()
main_thread = get_ident()
def restore(*args, **kwargs):
assert get_ident() != main_thread, 'mapping release blocked the Qt thread'
entered.set()
assert release.wait(3)
monkeypatch.setattr('cbb_refresh_verify.network_path.release_retained_path_leases', restore)
window.busy = True
try:
window._complete_library_release(library, {'status': 'RELEASE_CONFIRMED',
'library': str(library), 'evidence_path': 'proof.json'})
window._release_dialog_finished(0)
qtbot.waitUntil(entered.is_set)
assert window.busy and window.search_edit.isEnabled()
release.set()
qtbot.waitUntil(lambda: not window.busy)
finally:
release.set()
qtbot.waitUntil(lambda: window.pool.activeThreadCount() == 0)
def test_window_close_waits_asynchronously_for_retain_and_all_pool_work(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
lease, entered, release, closed, calls = slow_lease(get_ident())
window.library_lease = SimpleNamespace(mentor_path=Path('other.lmc'), close=lease.close)
window._native_backup_session = SimpleNamespace(path_lease=lease, library=Path('test.lmc'))
window.show()
try:
window.close()
qtbot.waitUntil(entered.is_set)
ticks = []
QTimer.singleShot(0, lambda: ticks.append(True))
qtbot.waitUntil(lambda: bool(ticks))
assert window.isVisible() and not closed.is_set()
release.set()
qtbot.waitUntil(lambda: not window.isVisible())
assert calls == ['retain', 'close']
assert window.pool.activeThreadCount() == 0
finally:
release.set()
qtbot.waitUntil(lambda: window.pool.activeThreadCount() == 0)
window._native_backup_session = None
def test_duplicate_dialog_finish_schedules_only_one_catalog_reload(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.management import ManagementResult
window = load_window(qtbot, tmp_path, monkeypatch)
library = Path(window.mentor_lmc_path)
window._management_operation_library = library
window.busy = True
entered, release = Event(), Event()
reloads = []
monkeypatch.setattr(window, 'load_library', lambda: reloads.append(True))
def restore(*args, **kwargs):
entered.set()
assert release.wait(3)
monkeypatch.setattr('cbb_refresh_verify.network_path.release_retained_path_leases', restore)
result = ManagementResult('remove', library, 'Beta', 'Logical-Physical', None, False,
'complete', 'REMOVED', True, release_proof={'status': 'RELEASE_CONFIRMED', 'library': str(library)})
try:
window._management_completed([result])
window._management_closed(); window._management_closed()
qtbot.waitUntil(entered.is_set)
release.set()
qtbot.waitUntil(lambda: not window.busy)
qtbot.waitUntil(lambda: bool(reloads))
assert reloads == [True]
finally:
release.set()
qtbot.waitUntil(lambda: window.pool.activeThreadCount() == 0)
def test_window_close_tolerates_fake_and_deleted_dialog_pools(qtbot, tmp_path, monkeypatch):
from PySide6.QtCore import QThreadPool
from shiboken6 import delete
window = load_window(qtbot, tmp_path, monkeypatch)
deleted_pool = QThreadPool()
delete(deleted_pool)
window.release_dialog = SimpleNamespace()
window.management_dialog = SimpleNamespace(pool=deleted_pool)
window.show()
window.close()
qtbot.waitUntil(lambda: not window.isVisible())