fix: bind UI jobs and recovery actions to captured scope

This commit is contained in:
阿白叔 committed 2026-11-16 22:11:17 +08:00
1 parent 601dd7b6b2
commit cd7a5e0ca1
20 files changed
+1570 -297

No files matched your search

+1 -1
View File
@@ -130,7 +130,7 @@ def test_main_logs_and_evidence_buttons_open_the_correct_paths(controls, qtbot):
w.recovery_path = evidence
w.recovery_button.setEnabled(True)
press(qtbot, w.recovery_button)
assert controls.opened == [w.data_root, evidence]
assert controls.opened == [w.data_root/'logs', evidence]
@pytest.mark.parametrize('attribute', ['selected_batch_button', 'batch_button', 'icdb_repair_button'])
+3 -2
View File
@@ -69,9 +69,10 @@ def test_completed_old_library_result_does_not_release_new_library(qtbot, tmp_pa
qtbot.waitUntil(lambda: not window._icdb_active())
summary = window.icdb_summary
window.lmc_edit.setText('other.lmc')
message = window.status_label.text()
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()
assert window.status_label.text() == message
def test_later_management_invalidates_old_recovery_offer(qtbot, tmp_path, monkeypatch):
@@ -109,4 +110,4 @@ def test_check_release_action_tracks_busy_and_retained_queue(qtbot, tmp_path, mo
assert opened == [{'queued': True}]
window.busy = False
window._update()
assert action.isEnabled()
assert not action.isEnabled(), 'A dismissed one-shot result cannot be reactivated'
+38
View File
@@ -0,0 +1,38 @@
from threading import Event
import pytest
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff, native_phase
def test_metadata_can_refresh_while_abandoned_native_scope_stays_protected():
entered, release = Event(), Event()
old = BatchTaskContext('a.lmc')
def stalled():
entered.set(); release.wait(3)
try:
with pytest.raises(TaskHandoff): old.run(stalled, timeout_seconds=.01)
assert entered.is_set()
new = BatchTaskContext('a.lmc')
assert new.run(lambda: 'metadata', metadata_only=True) == 'metadata'
with pytest.raises(TaskHandoff): new.run(lambda: 'native')
finally:
release.set(); old.close(timeout_seconds=1)
def test_metadata_cannot_escalate_into_native_phase():
context = BatchTaskContext('a.lmc')
def escalate():
with native_phase():
pytest.fail('metadata admitted native action')
with pytest.raises(RuntimeError, match='metadata'):
context.run(escalate, metadata_only=True)
def test_abandoned_metadata_does_not_block_next_native_admission():
release = Event()
old = BatchTaskContext('a.lmc')
try:
with pytest.raises(TaskHandoff):
old.run(lambda: release.wait(3), timeout_seconds=.01, metadata_only=True)
assert BatchTaskContext('a.lmc').run(lambda: 'admitted') == 'admitted'
finally:
release.set(); old.close(timeout_seconds=1)
+8 -1
View File
@@ -241,7 +241,14 @@ def test_common_admission_refusal_publishes_bound_receipt_and_ui_can_reopen(qtbo
session.process.poll = lambda: 1
launched = []
window = load_window(qtbot, tmp_path, monkeypatch,
native_backup_launcher=lambda req: (launched.append(req) or session))
native_backup_launcher=lambda req: (launched.append(req) or session),
status_refresher=lambda names, _: {name:'UNKNOWN' for name in names})
# Deliver the receipt to its actual library view; a foreign view must not
# receive an old session's status label after Task 4's callback isolation.
window.path_lease_factory = lambda path: SimpleNamespace(mentor_path=path, display_path=path,
drive='', remote_root='', close=lambda:None, retain_for_recovery=lambda:None)
window.lmc_edit.setText(str(session.library)); window.load_library()
qtbot.waitUntil(lambda:not window.busy)
session.block = 'Beta'; record['block'] = 'Beta'
session.job.with_name('result.json').write_text(json.dumps(record), encoding='utf-8')
window._native_backup_session = session
+651
View File
@@ -0,0 +1,651 @@
"""Task-bound UI delivery and filesystem/native catalog separation."""
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
from PySide6.QtCore import Qt
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
def window_for(qtbot, tmp_path, monkeypatch, *, reader=None, **kwargs):
monkeypatch.setattr('cbb_refresh_verify.ui.main_window.preflight_skip_reason', lambda *_: None)
def lease(path):
return SimpleNamespace(mentor_path=path, display_path=path, drive='', remote_root='',
close=lambda: None, retain_for_recovery=lambda: None)
window = MainWindow(reader=reader or (lambda _: LibraryReadResult((CbbRecord('A', 'LP'),))),
path_lease_factory=lease, data_root=tmp_path, **kwargs)
qtbot.addWidget(window)
window.show()
return window
def load(window, qtbot, path='a.lmc'):
window.lmc_edit.setText(path)
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
def test_first_read_can_cancel_and_keeps_navigation_live(qtbot, tmp_path, monkeypatch):
entered, release = Event(), Event()
def reader(_):
entered.set(); release.wait(5)
return LibraryReadResult((CbbRecord('Late', 'LP'),))
window = window_for(qtbot, tmp_path, monkeypatch, reader=reader)
window.lmc_edit.setText('a.lmc'); window.load_library()
qtbot.waitUntil(entered.is_set)
try:
assert window.stop_button.isEnabled()
assert window.lmc_edit.isEnabled() and window.load_button.isEnabled()
window.stop_button.click()
qtbot.waitUntil(lambda: not window.busy, timeout=2000)
assert window.loaded_path is None
finally:
release.set(); window.pool.waitForDone(6000)
def test_failed_read_preserves_stale_table_without_write_eligibility(qtbot, tmp_path, monkeypatch):
window = window_for(qtbot, tmp_path, monkeypatch)
load(window, qtbot)
window.reader = lambda _: LibraryReadResult((), 'INPUT_EMPTY: 空文件')
load(window, qtbot, 'bad.lmc')
assert window.cbb_table.rowCount() == 1
assert window.loaded_path is None
assert not window.batch_button.isEnabled()
assert '失效' in window.library_notice.text()
def test_successful_path_is_local_and_only_prefilled(qtbot, tmp_path, monkeypatch):
window = window_for(qtbot, tmp_path, monkeypatch)
load(window, qtbot, 'remember.lmc')
calls = []
other = window_for(qtbot, tmp_path, monkeypatch, reader=lambda p: calls.append(p))
assert other.lmc_edit.text() == 'remember.lmc'
assert not calls and other.loaded_path is None
isolated = window_for(qtbot, tmp_path/'other', monkeypatch)
assert isolated.lmc_edit.text() == ''
def test_result_nonmodal_and_safe_cancel_evidence_and_logs(qtbot, tmp_path, monkeypatch):
window = window_for(qtbot, tmp_path, monkeypatch)
load(window, qtbot)
evidence = tmp_path/'evidence'/'result.json'
evidence.parent.mkdir(); evidence.write_text('{}')
window._batch_done(([VerifyResult('CANCELLED', safe_to_continue=True, evidence_path=evidence)], None))
assert window.summary.windowModality() == Qt.NonModal
assert window.recovery_button.isEnabled()
opened = []
monkeypatch.setattr('os.startfile', opened.append)
window.open_logs()
assert Path(opened[-1]) == tmp_path/'logs'
def test_read_does_not_wait_forever_on_old_retained_cache(qtbot, tmp_path, monkeypatch):
calls = []
monkeypatch.setattr('cbb_refresh_verify.session_record.library_available', lambda _: False)
monkeypatch.setattr('cbb_refresh_verify.session_record.library_wait_reason', lambda _: 'old retained')
window = window_for(qtbot, tmp_path, monkeypatch, reader=lambda p: (
calls.append(p) or LibraryReadResult((CbbRecord('A', 'LP'),))))
window.lmc_edit.setText('a.lmc'); window.load_library()
try:
qtbot.waitUntil(lambda: bool(calls), timeout=1500)
finally:
window.request_stop(); window.pool.waitForDone(3000)
@pytest.mark.parametrize('filename,content,category', [
('wrong.txt', b'library', 'INPUT_SUFFIX'), ('empty.lmc', b'', 'INPUT_EMPTY')])
def test_fast_read_rejects_invalid_input(tmp_path, filename, content, category):
from cbb_refresh_verify.library_reader import read_library_fast
path = tmp_path/filename; path.write_bytes(content)
(tmp_path/'ReusableBlocksLP').mkdir()
result = read_library_fast(path)
assert result.error and category in result.error
def test_fast_read_distinguishes_unknown_native_count(tmp_path):
from cbb_refresh_verify.library_reader import read_library_fast
path = tmp_path/'lib.lmc'; path.write_bytes(b'not-a-native-validation')
(tmp_path/'ReusableBlocksLP'/'Orphan').mkdir(parents=True)
result = read_library_fast(path)
assert result.directory_count == 1 and result.native_count is None
assert result.records[0].catalog_source == 'directory'
assert result.records[0].status == 'UNKNOWN'
def test_late_read_a_b_a_cannot_replace_newer_snapshot(qtbot, tmp_path, monkeypatch):
entered, release = Event(), Event()
count = 0
def reader(path):
nonlocal count
count += 1
if count == 1:
entered.set(); release.wait(5)
return LibraryReadResult((CbbRecord('Old', 'LP'),))
return LibraryReadResult((CbbRecord('New', 'LP'),))
window = window_for(qtbot, tmp_path, monkeypatch, reader=reader)
window.lmc_edit.setText('a.lmc'); window.load_library()
qtbot.waitUntil(entered.is_set)
try:
window.lmc_edit.setText('b.lmc'); window.lmc_edit.setText('a.lmc')
window.load_library()
qtbot.waitUntil(lambda: window.loaded_path == 'a.lmc', timeout=2000)
release.set(); qtbot.wait(100)
assert tuple(window._records_by_name) == ('New',)
finally:
release.set(); window.pool.waitForDone(6000)
def test_batch_result_cannot_modify_reloaded_library_and_current_cancel_displays(qtbot, tmp_path, monkeypatch):
entered, release = Event(), Event()
def verify(_):
entered.set(); release.wait(5)
return VerifyResult('CANCELLED', stderr='old A cancelled')
window = window_for(qtbot, tmp_path, monkeypatch, verifier=verify,
status_refresher=lambda names, _: {name:'PENDING' for name in names})
load(window, qtbot)
try:
window._run(['A']); qtbot.waitUntil(entered.is_set)
load(window, qtbot, 'b.lmc'); load(window, qtbot, 'a.lmc')
release.set(); qtbot.wait(200)
assert 'old A cancelled' not in window.status_label.text()
assert window.cbb_table.item(0,3).text() == '未检查'
window._run(['A']); qtbot.waitUntil(lambda:not window.busy)
assert '取消' in window.output.toPlainText() or 'CANCELLED' in window.output.toPlainText()
finally:
release.set(); window.pool.waitForDone(6000)
def test_catalog_union_keeps_registration_source_and_counts(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.management import Catalog, CatalogEntry
entered, release = Event(), Event()
def catalog(path, evidence):
entered.set(); release.wait(5)
return Catalog(path,1,(CatalogEntry('A','Logical-Physical'),CatalogEntry('NativeOnly','Logical-Physical')))
window = window_for(qtbot,tmp_path,monkeypatch, reader=lambda _:LibraryReadResult(
(CbbRecord('A','LP',catalog_source='directory'), CbbRecord('Orphan','LP',catalog_source='directory')),
directory_count=2), catalog_reader=catalog, status_refresher=lambda names,_:{name:'READY' for name in names})
try:
load(window,qtbot)
qtbot.waitUntil(entered.is_set)
assert '未知' in window.counts_label.text()
assert window.batch_button.isEnabled()
release.set()
qtbot.waitUntil(lambda:'NativeOnly' in window._records_by_name)
assert window._records_by_name['Orphan'].catalog_source == 'directory_only'
assert window._records_by_name['NativeOnly'].catalog_source == 'native_only'
assert window._records_by_name['A'].status_source == 'authoritative'
assert '原生 2' in window.counts_label.text()
finally:
release.set(); window.pool.waitForDone(6000)
def test_execution_rechecks_ready_when_directory_snapshot_was_unknown(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.management import Catalog, CatalogEntry
calls=[]
window=window_for(qtbot,tmp_path,monkeypatch, verifier=lambda r:(calls.append(r.block_name) or VerifyResult('PASS')),
catalog_reader=lambda p,e:Catalog(p,1,(CatalogEntry('A','Logical-Physical'),)),
status_refresher=lambda names,_:{name:'READY' for name in names})
load(window,qtbot)
window._run(['A'])
qtbot.waitUntil(lambda:not window.busy)
assert calls == []
def test_active_a_choice_defaults_after_switch_to_b(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.pcb_open_consent import OpenChoice
from cbb_refresh_verify.ui import timed_prompt
monkeypatch.setattr(timed_prompt,'DEFAULT_TIMEOUT_MS',80)
window=window_for(qtbot,tmp_path,monkeypatch)
load(window,qtbot)
job=window._new_job('verify',targets=('A',))
load(window,qtbot,'b.lmc')
choice=OpenChoice('A',Path('a.lmc'))
window._emit_job(job,'version_choice',choice)
qtbot.waitUntil(lambda:choice.decision is not None)
assert choice.decision == 'skip'
window._finish_job(job)
@pytest.mark.parametrize('mode',['versions','repair'])
def test_native_session_outlives_launcher_and_cleans_up_after_a_b_a(qtbot,tmp_path,monkeypatch,mode):
import json
exited=Event(); calls=[]
job_file=tmp_path/'native'/'job.json'; job_file.parent.mkdir(); job_file.write_text('{}')
def launcher(request, **options):
calls.append(options.get('mode','versions'))
return SimpleNamespace(process=SimpleNamespace(poll=lambda:0 if exited.is_set() else None),
job=job_file,library=request.lmc_file,block=request.block_name,path_lease=None,operation_id='native-1')
window=window_for(qtbot,tmp_path,monkeypatch,native_backup_launcher=launcher,
status_refresher=lambda names,_:{name:'PENDING' for name in names})
load(window,qtbot); window.cbb_table.setCurrentCell(0,0)
button=window.native_backup_button if mode=='versions' else window.native_repair_button
button.click(); qtbot.waitUntil(lambda:window._native_backup_session is not None)
qtbot.waitUntil(lambda:not window.busy)
assert calls == [mode]
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
message=window.status_label.text()
job_file.with_name('result.json').write_text(json.dumps(dict(operation_id='native-1',
library='a.lmc',block='A',safe_to_continue=True,status='CLOSED')))
exited.set(); window._poll_native_backup()
qtbot.waitUntil(lambda:window._native_backup_session is None)
assert window.status_label.text() == message
window.cbb_table.setCurrentCell(0,0)
assert window.native_backup_button.isEnabled()
def test_close_during_first_read_finishes_and_late_emit_is_harmless(qtbot,tmp_path,monkeypatch):
entered, release=Event(),Event()
def reader(_):
entered.set(); release.wait(5)
return LibraryReadResult((CbbRecord('Late','LP'),))
window=window_for(qtbot,tmp_path,monkeypatch,reader=reader)
window.lmc_edit.setText('a.lmc'); window.load_library(); qtbot.waitUntil(entered.is_set)
job=window._current_job
try:
window.close()
qtbot.waitUntil(lambda:not window.isVisible(),timeout=2000)
window._emit_job(job,'event',{'stage':'late'})
finally: release.set()
def test_input_lock_directory_and_permissions_are_classified(tmp_path,monkeypatch):
from cbb_refresh_verify.library_reader import read_library_fast
path=tmp_path/'lib.lmc'; path.write_bytes(b'library')
(tmp_path/'ReusableBlocksLP').mkdir(); path.with_suffix('.lock').mkdir()
assert 'INPUT_LOCK_DIRECTORY' in read_library_fast(path).error
original=Path.open
def denied(self,*a,**k):
if self == path: raise PermissionError('denied')
return original(self,*a,**k)
monkeypatch.setattr(Path,'open',denied)
assert 'INPUT_PERMISSION' in read_library_fast(path).error
def test_management_completion_after_switch_preserves_current_table(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.management import Capability, ManagementResult
from PySide6.QtWidgets import QMessageBox
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
entered,release=Event(),Event()
adapter=SimpleNamespace(capabilities=lambda:{op:Capability(True,'available') for op in ('add','update','remove')})
window=window_for(qtbot,tmp_path,monkeypatch,management_adapter=adapter)
load(window,qtbot); window.select_visible_button.click(); window.manage_cbb('remove')
dialog=window.management_dialog
def runner(requests,**kwargs):
entered.set(); release.wait(5)
r=requests[0]
return [ManagementResult('remove',r.library,r.name,r.partition,None,False,'complete','REMOVED',True,'old remove')]
dialog.runner=runner
try:
dialog.execute_button.click(); qtbot.waitUntil(entered.is_set)
assert dialog.windowModality()==Qt.NonModal
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
message=window.status_label.text()
release.set(); qtbot.waitUntil(lambda:not dialog.busy)
dialog.close(); qtbot.wait(100)
assert window.status_label.text()==message
assert window.cbb_table.item(0,3).text()=='未检查'
finally: release.set(); dialog.pool.waitForDone(6000)
def test_recovery_dialog_binds_original_library_and_is_nonmodal(qtbot,tmp_path,monkeypatch):
from PySide6.QtWidgets import QMessageBox
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
entered,release=Event(),Event(); calls=[]
window=window_for(qtbot,tmp_path,monkeypatch)
load(window,qtbot); window.restore_backup(); dialog=window.backup_dialog
source=tmp_path/'A.prj'; source.write_text('project')
dialog.source_edit.setText(str(source))
def recover(request,source,**kwargs):
calls.append(request.lmc_file); entered.set(); release.wait(5)
return VerifyResult('FAIL',stderr='old recovery',safe_to_continue=True)
dialog.recoverer=recover
try:
assert dialog.windowModality()==Qt.NonModal
load(window,qtbot,'b.lmc')
dialog.restore_button.click(); qtbot.waitUntil(entered.is_set)
message=window.status_label.text()
release.set(); qtbot.waitUntil(lambda:not dialog.busy)
assert calls == [Path('a.lmc')]
assert window.status_label.text()==message
finally: release.set(); dialog.pool.waitForDone(6000)
def test_icdb_does_not_wait_on_stale_retained_and_late_result_is_scoped(qtbot,tmp_path,monkeypatch):
entered,release=Event(),Event()
monkeypatch.setattr('cbb_refresh_verify.session_record.library_available',lambda _:False)
monkeypatch.setattr('cbb_refresh_verify.session_record.library_wait_reason',lambda _:'historical')
def verify(_):
entered.set(); release.wait(5)
return VerifyResult('CHECKED',safe_to_continue=True)
window=window_for(qtbot,tmp_path,monkeypatch,verifier=verify)
load(window,qtbot); window._start_icdb_check(['A'])
try:
qtbot.waitUntil(entered.is_set,timeout=1500)
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
message=window.status_label.text()
release.set(); qtbot.waitUntil(lambda:not window._icdb_active())
assert window.status_label.text()==message
assert window.cbb_table.item(0,3).text()=='未检查'
finally:
release.set(); window._stop_icdb_check(); window.icdb_task.pool.waitForDone(6000)
def test_default_reentrant_tick_commits_one_choice(qtbot,monkeypatch):
from PySide6.QtWidgets import QMessageBox
from cbb_refresh_verify.ui.timed_prompt import arm_default
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.DEFAULT_TIMEOUT_MS',50)
box=QMessageBox(); qtbot.addWidget(box); box.setStandardButtons(QMessageBox.Yes|QMessageBox.No)
choices=[]
def clicked(button):
choices.append(button)
if len(choices)==1: countdown.tick()
box.buttonClicked.connect(clicked)
countdown=arm_default(box,box.button(QMessageBox.Yes))
box.show(); qtbot.wait(120)
assert len(choices) == 1
def test_release_dialog_is_available_during_task_and_stale_receipt_keeps_view(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
monkeypatch.setattr(ResidualReleaseDialog,'refresh',lambda self:None)
released=[]
monkeypatch.setattr('cbb_refresh_verify.network_path.release_retained_path_leases',lambda proof,**kw:released.append(proof))
window=window_for(qtbot,tmp_path,monkeypatch)
load(window,qtbot); window.busy=True; window._update()
window.release_library_button.click()
dialog=window.release_dialog
assert dialog.isVisible() and dialog.windowModality()==Qt.NonModal
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc'); message=window.status_label.text()
dialog.released.emit(dict(status='RELEASE_CONFIRMED',library='a.lmc',evidence_path='proof.json'))
qtbot.waitUntil(lambda:bool(released))
dialog.close(); qtbot.wait(100)
assert window.status_label.text()==message
@pytest.mark.parametrize('kind',['read','lease'])
def test_source_process_exits_after_stalled_bookkeeping(tmp_path,kind):
import subprocess,sys,os,time
script=tmp_path/'close_app.py'
script.write_text('''from threading import Event
from pathlib import Path
import sys
from PySide6.QtWidgets import QApplication
from PySide6.QtCore import QTimer
from cbb_refresh_verify.ui.main_window import MainWindow
app=QApplication([])
MainWindow._show_unfinished_management=lambda self:None
block=Event()
w=MainWindow(reader=lambda _:block.wait(90),data_root=Path(sys.argv[2]))
w.show()
if sys.argv[1]=='read':
w.lmc_edit.setText('stalled.lmc'); w.load_library()
else: w._lease_action(lambda:block.wait(90))
QTimer.singleShot(150,w.close)
app.exec()
print('APP_RETURNED',flush=True)
''',encoding='utf-8')
env=dict(os.environ,QT_QPA_PLATFORM='offscreen')
started=__import__('time').monotonic()
process=subprocess.Popen([sys.executable,'-X','utf8',str(script),kind,str(tmp_path/'data')],
stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,encoding='utf-8',env=env)
try:
stdout,stderr=process.communicate(timeout=8)
assert process.returncode==0,stderr
assert 'APP_RETURNED' in stdout
assert time.monotonic()-started < 8
finally:
if process.poll() is None:
process.kill(); process.communicate()
def test_old_library_mapping_cleanup_does_not_keep_new_library_busy(qtbot,tmp_path,monkeypatch):
entered,release=Event(),Event(); calls=[]
window=window_for(qtbot,tmp_path,monkeypatch,verifier=lambda r:(calls.append(r.lmc_file) or VerifyResult('PASS')),
status_refresher=lambda names,_:{name:'PENDING' for name in names})
load(window,qtbot)
def cleanup(): entered.set(); release.wait(5)
window._lease_action(cleanup,hold_busy=True)
qtbot.waitUntil(entered.is_set)
try:
window.lmc_edit.setText('b.lmc'); window.load_library()
qtbot.waitUntil(lambda:window.loaded_path=='b.lmc' and not window.busy,timeout=1000)
window._run(['A'])
qtbot.waitUntil(lambda:bool(calls),timeout=1000)
assert calls == [Path('b.lmc')]
finally:
release.set(); qtbot.waitUntil(lambda:window._lease_pending==0)
@pytest.mark.parametrize('kind',['recovery','management'])
def test_dialog_handoff_is_not_claimed_as_safe_cancellation(qtbot,tmp_path,monkeypatch,kind):
from cbb_refresh_verify.operation_queue import TaskHandoff,BatchTaskContext
from cbb_refresh_verify.management import Capability
from PySide6.QtWidgets import QMessageBox
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
adapter=SimpleNamespace(capabilities=lambda:{op:Capability(True,'available') for op in ('add','update','remove')})
window=window_for(qtbot,tmp_path,monkeypatch,management_adapter=adapter)
load(window,qtbot); results=[]
def handed_off(*a,**k): raise TaskHandoff(BatchTaskContext('a.lmc'))
if kind=='recovery':
window.restore_backup(); dialog=window.backup_dialog
source=tmp_path/'A.prj'; source.write_text('project'); dialog.source_edit.setText(str(source))
dialog.recoverer=handed_off
dialog.completed.connect(lambda name,result:results.append(result))
dialog.restore_button.click()
else:
window.select_visible_button.click(); window.manage_cbb('remove'); dialog=window.management_dialog
dialog.runner=handed_off
dialog.completed.connect(results.extend)
dialog.execute_button.click()
qtbot.waitUntil(lambda:bool(results))
assert results[0].safe_to_continue is False
def test_real_startup_observer_delivery_after_destroy_is_ignored(qtbot,tmp_path,monkeypatch):
callbacks=[]
monkeypatch.setattr('cbb_refresh_verify.management.unfinished_operations',lambda _:[])
monkeypatch.setattr('cbb_refresh_verify.session_record.discover_sessions',lambda _:[dict(
status='ACTIVE',path='owned-session.json',block='A',phase='NATIVE_CALL',detail='running')])
monkeypatch.setattr('cbb_refresh_verify.session_record.handoff_session',lambda *a,**kw:callbacks.append(kw['progress']))
# This test explicitly destroys the QObject, so pytest-qt must not retain it
# for its normal close-at-teardown fixture.
window=MainWindow(reader=lambda _:LibraryReadResult(()),data_root=tmp_path)
window.show()
qtbot.waitUntil(lambda:bool(callbacks))
window.close(); qtbot.waitUntil(lambda:not window.isVisible())
import shiboken6
shiboken6.delete(window)
callbacks[0]({'library':'a.lmc','status':'RELEASED'})
def test_running_a_emits_real_choice_after_reading_b(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.pcb_open_consent import OpenChoice
entered,continue_a,answered=Event(),Event(),Event(); choices=[]
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.DEFAULT_TIMEOUT_MS',80)
def verify(request,*,version_prompt,**kwargs):
entered.set(); continue_a.wait(5)
choice=OpenChoice(request.block_name,request.lmc_file); choices.append(choice)
version_prompt(choice)
for _ in range(100):
if choice.decision is not None: answered.set(); break
Event().wait(.02)
return VerifyResult('SKIPPED',safe_to_continue=True)
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_verify',verify)
window=window_for(qtbot,tmp_path,monkeypatch,status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
load(window,qtbot); window._run(['A']); qtbot.waitUntil(entered.is_set)
try:
load(window,qtbot,'b.lmc'); message=window.status_label.text()
continue_a.set(); qtbot.waitUntil(answered.is_set)
assert choices[0].decision=='skip' and choices[0].library==Path('a.lmc')
assert window.status_label.text()==message
finally: continue_a.set(); window.pool.waitForDone(6000)
def test_second_management_dialog_cannot_submit_same_active_snapshot(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.management import Capability
from PySide6.QtWidgets import QMessageBox
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
entered,release=Event(),Event(); calls=[]
adapter=SimpleNamespace(capabilities=lambda:{op:Capability(True,'available') for op in ('add','update','remove')})
window=window_for(qtbot,tmp_path,monkeypatch,management_adapter=adapter)
def runner(requests,**kwargs):
calls.append(requests[0].name); entered.set(); release.wait(5); return []
load(window,qtbot); window.select_visible_button.click(); window.manage_cbb('remove')
first=window.management_dialog; first.runner=runner; first.execute_button.click()
qtbot.waitUntil(entered.is_set)
try:
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
window.select_visible_button.click(); window.manage_cbb('remove')
second=window.management_dialog; second.runner=runner; second.execute_button.click()
assert not second.busy
assert '重复' in second.status_label.text()
release.set(); qtbot.waitUntil(lambda:not first.busy)
assert calls==['A']
finally: release.set(); first.pool.waitForDone(6000)
def test_manual_repair_uses_current_diagnostic_database(qtbot,tmp_path,monkeypatch):
import json
evidence=tmp_path/'run'/'result.json'; evidence.parent.mkdir(); evidence.write_text('{}')
diagnostic=evidence.parent/'diagnostics'/'icdb-recovery.json'; diagnostic.parent.mkdir()
database=tmp_path/'actual-project'/'database'
diagnostic.write_text(json.dumps({'database_path':str(database),'scope':'project'}))
calls=[]
def launcher(request,**kwargs):
calls.append(kwargs)
return SimpleNamespace(process=SimpleNamespace(poll=lambda:None),job=evidence,
library=request.lmc_file,block=request.block_name,path_lease=None)
window=window_for(qtbot,tmp_path,monkeypatch,native_backup_launcher=launcher,
verifier=lambda _:VerifyResult('FAIL',safe_to_continue=True,evidence_path=evidence,error_category='ICDB_REPAIR_REQUIRED'),
status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
load(window,qtbot); window._run(['A']); qtbot.waitUntil(lambda:not window.busy)
window.cbb_table.setCurrentCell(0,0); window.native_repair_button.click()
qtbot.waitUntil(lambda:bool(calls))
assert calls[0]['target_database']==str(database)
@pytest.mark.parametrize('maintenance',[False,True])
def test_directory_only_submission_is_not_treated_as_native_registration(qtbot,tmp_path,monkeypatch,maintenance):
from cbb_refresh_verify.management import Catalog
calls=[]
window=window_for(qtbot,tmp_path,monkeypatch,
verifier=lambda req:(calls.append(req.block_name) or VerifyResult('PASS')),
status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
load(window,qtbot)
# The snapshot was already selectable while the native catalog was unknown.
window.catalog_reader=lambda path,evidence:Catalog(path,1,())
window._run(['A'],maintenance=maintenance)
qtbot.waitUntil(lambda:not window.busy and not window._icdb_active())
assert calls == []
def test_missing_all_project_directories_still_allows_native_catalog_reconciliation(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.management import Catalog,CatalogEntry
path=tmp_path/'lib.lmc'; path.write_bytes(b'library metadata')
window=MainWindow(data_root=tmp_path/'data',
catalog_reader=lambda library,evidence:Catalog(library,1,(CatalogEntry('NativeOnly','Logical-Physical'),)),
status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
qtbot.addWidget(window); window.show()
load(window,qtbot,str(path))
qtbot.waitUntil(lambda:'NativeOnly' in window._records_by_name)
assert window._records_by_name['NativeOnly'].catalog_source=='native_only'
assert window._read_counts==(0,1,1)
def test_failed_native_entry_resumes_captured_check_after_view_switch(qtbot,tmp_path,monkeypatch):
entered,release=Event(),Event(); calls=[]
def verify(request):
calls.append(request.block_name)
if len(calls)==1: entered.set(); release.wait(5)
return VerifyResult('CHECKED',safe_to_continue=True)
def failed(*a,**k): raise RuntimeError('entry refused')
window=window_for(qtbot,tmp_path,monkeypatch,reader=lambda _:LibraryReadResult((CbbRecord('A','LP'),CbbRecord('Next','LP'))),
verifier=verify,native_backup_launcher=failed)
load(window,qtbot); window._start_icdb_check(['A','Next']); qtbot.waitUntil(entered.is_set)
task=window.icdb_task
try:
window.cbb_table.setCurrentCell(0,0); window.native_backup_button.click()
assert task.paused
load(window,qtbot,'b.lmc'); message=window.status_label.text()
release.set()
qtbot.waitUntil(lambda:len(calls)==2,timeout=2000)
assert window.status_label.text()==message
finally:
release.set(); task.cancel(); qtbot.waitUntil(lambda:not task.active)
def test_old_release_panel_never_cancels_replacement_check(qtbot,tmp_path,monkeypatch):
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
monkeypatch.setattr(ResidualReleaseDialog,'refresh',lambda self:None)
entered=Event(); window=None
def verify(_):
task=window.icdb_task; entered.set(); task.stop.wait(5)
return VerifyResult('CANCELLED',safe_to_continue=True)
window=window_for(qtbot,tmp_path,monkeypatch,verifier=verify)
load(window,qtbot); window._start_icdb_check(['A']); qtbot.waitUntil(entered.is_set)
old=window.icdb_task
window.release_library_button.click(); dialog=window.release_dialog
old.cancel(); qtbot.waitUntil(lambda:not old.active)
entered.clear(); load(window,qtbot,'b.lmc'); window._start_icdb_check(['A'])
qtbot.waitUntil(entered.is_set); newer=window.icdb_task
try:
dialog.before_release.emit()
assert not newer.stop.is_set()
finally:
newer.cancel(); qtbot.waitUntil(lambda:not newer.active)
@pytest.mark.parametrize('switch_view',[True,False])
def test_summary_actions_keep_original_revision_and_resume_configuration(qtbot,tmp_path,monkeypatch,switch_view):
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.DEFAULT_TIMEOUT_MS',10000)
monkeypatch.setattr('cbb_refresh_verify.operation_lifecycle.recheck_failed_release',lambda library,name,result,**kw:result)
requests=[]; release_clicks=[]
def verify(request):
requests.append(request)
return VerifyResult('FAIL' if request.block_name=='A' else 'PASS',safe_to_continue=request.block_name!='A')
window=window_for(qtbot,tmp_path,monkeypatch,reader=lambda _:LibraryReadResult((CbbRecord('A','LP'),CbbRecord('Next','LP'))),
verifier=verify,status_refresher=lambda names,_:{name:'PENDING' for name in names})
monkeypatch.setattr(window,'check_library_release',lambda *a,**k:release_clicks.append(True))
load(window,qtbot); original_timeout=window.timeout_spin.value(); window._run(['A','Next'])
qtbot.waitUntil(lambda:not window.busy)
old_release,old_resume=window._residual_release_action,window._resume_batch_action
window._resume_batch['released']=True; window._update()
if switch_view:
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
old_release.click(); old_resume.click(); qtbot.wait(100)
assert release_clicks==[] and len(requests)==1
else:
window.timeout_spin.setValue(45)
old_resume.click(); qtbot.waitUntil(lambda:not window.busy)
assert len(requests)==2 and requests[-1].block_name=='Next'
assert requests[-1].timeout_seconds==original_timeout
def test_recovery_retry_rejects_old_external_progress_and_choice(qtbot,tmp_path,monkeypatch):
from PySide6.QtWidgets import QMessageBox
from cbb_refresh_verify.pcb_open_consent import OpenChoice
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
callbacks=[]; entered,release=Event(),Event()
def recover(*args,progress,version_prompt,stop):
callbacks.append((progress,version_prompt))
if len(callbacks)==2: entered.set(); release.wait(5)
return VerifyResult('CANCELLED',safe_to_continue=True)
monkeypatch.setattr('cbb_refresh_verify.backup_recovery.recover_from_backup',recover)
window=window_for(qtbot,tmp_path,monkeypatch,status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
load(window,qtbot); window.restore_backup(); dialog=window.backup_dialog
source=tmp_path/'A.prj'; source.write_text('project'); dialog.source_edit.setText(str(source))
dialog.restore_button.click(); qtbot.waitUntil(lambda:not dialog.busy and not window.busy)
try:
dialog.restore_button.click(); qtbot.waitUntil(entered.is_set)
message=dialog.status_label.text()
callbacks[0][0]({'detail':'old external observer'})
choice=OpenChoice('A',Path('a.lmc')); callbacks[0][1](choice)
qtbot.wait(50)
assert dialog.status_label.text()==message
assert choice.decision=='cancel'
finally:
release.set(); qtbot.waitUntil(lambda:not dialog.busy)
+10 -10
View File
@@ -35,7 +35,7 @@ def test_reader_accepts_com_collections_exposing_callable_count():
def test_reader_fast_scans_reusable_blocks_without_com(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
(tmp_path / 'ReusableBlocksLP' / 'B_CBB').mkdir(parents=True)
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir()
from cbb_refresh_verify.library_reader import read_library_fast
@@ -45,7 +45,7 @@ def test_reader_fast_scans_reusable_blocks_without_com(tmp_path):
def test_reader_fast_applies_status_reader(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
(tmp_path / 'ReusableBlocksLP' / 'READY_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import read_library_fast
result = read_library_fast(lmc, status_reader=lambda name: 'READY' if name == 'READY_CBB' else 'PENDING')
@@ -53,7 +53,7 @@ def test_reader_fast_applies_status_reader(tmp_path):
def test_reader_fast_bulk_status_reader_is_called_once(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir(parents=True)
(tmp_path / 'ReusableBlocksLP' / 'B_CBB').mkdir()
calls = []
@@ -68,7 +68,7 @@ def test_reader_fast_bulk_status_reader_is_called_once(tmp_path):
def test_reader_fast_preserves_unavailable_bridge_status(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import read_library_fast
result = read_library_fast(lmc, status_reader=lambda path, names: {'A_CBB': 'UNAVAILABLE'})
@@ -77,7 +77,7 @@ def test_reader_fast_preserves_unavailable_bridge_status(tmp_path):
def test_reader_fast_exposes_status_reader_failure_as_unavailable(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
(tmp_path / 'ReusableBlocksLP' / 'A_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import read_library_fast
result = read_library_fast(lmc, status_reader=lambda path, names: (_ for _ in ()).throw(RuntimeError('bridge down')))
@@ -86,7 +86,7 @@ def test_reader_fast_exposes_status_reader_failure_as_unavailable(tmp_path):
def test_filesystem_status_uses_complete_fresh_cert_artifacts(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
root = tmp_path / 'ReusableBlocksLP'
ready = root / 'READY_CBB' / 'Work'
pending = root / 'PENDING_CBB' / 'Work'
@@ -325,7 +325,7 @@ def test_status_scan_logs_each_cbb_image_id(caplog, tmp_path):
def test_status_scan_without_native_observation_does_not_guess_status(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
root = lmc.parent / 'ReusableBlocksLP'
ready = root / 'READY_CBB' / 'Work'
(ready / 'PCB' / 'Layout').mkdir(parents=True)
@@ -353,7 +353,7 @@ def test_status_scan_without_native_observation_does_not_guess_status(tmp_path):
def test_filesystem_evidence_exposes_multiple_persistent_dimensions(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
work = tmp_path / 'ReusableBlocksLP' / 'A_CBB' / 'Work'
(work / 'PCB' / 'Layout').mkdir(parents=True)
(work / 'A_CBB.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
@@ -375,7 +375,7 @@ def test_filesystem_evidence_exposes_multiple_persistent_dimensions(tmp_path):
def test_filesystem_evidence_preserves_mapped_drive_paths(tmp_path, monkeypatch):
"""Legacy evidence scanning must not resolve a mapped drive back to UNC."""
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
work = tmp_path / 'ReusableBlocksLP' / 'A_CBB' / 'Work'
(work / 'PCB' / 'Layout').mkdir(parents=True)
(work / 'A_CBB.prj').write_text('KEY PCBDesignPath "PCB\\actual.pcb"', encoding='utf-8')
@@ -393,7 +393,7 @@ def test_filesystem_evidence_preserves_mapped_drive_paths(tmp_path, monkeypatch)
def test_missing_work_project_is_a_pending_calibration_anchor(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
lmc.write_bytes(b'fixture metadata; native format is not checked')
(tmp_path / 'ReusableBlocksLP' / 'IMPORTED_CBB').mkdir(parents=True)
from cbb_refresh_verify.library_reader import filesystem_evidence_map
evidence = filesystem_evidence_map(lmc, ('IMPORTED_CBB',))['IMPORTED_CBB']
+2 -1
View File
@@ -154,6 +154,7 @@ def test_released_batch_can_resume_only_its_unexecuted_items(qtbot, tmp_path, mo
action = window._resume_batch_action
assert action.isEnabled()
calls = []
original_remaining = (window._batch_requests[1],)
monkeypatch.setattr(window, '_run', lambda names, **kw: calls.append((names, kw)))
action.click()
assert calls == [(['Gamma'], {'maintenance': False})]
assert calls == [(['Gamma'], {'maintenance': False, 'request_snapshot': original_remaining})]
+19 -7
View File
@@ -28,6 +28,8 @@ def test_queued_action_has_visible_release_entry_and_resumes_after_proof(qtbot,
window.show()
library = window.mentor_lmc_path
retain(monkeypatch, library)
from test_review381_queue_release import hold_native_queue
queue_release, queue_worker = hold_native_queue(window)
finished = Event()
window._start(lambda: VerifyResult('PASS'), lambda _: finished.set())
qtbot.waitUntil(lambda: 'BlockedCBB' in window.status_label.text())
@@ -37,6 +39,7 @@ def test_queued_action_has_visible_release_entry_and_resumes_after_proof(qtbot,
window.queue_release_button.click()
assert opened == [{'queued': True}]
sessions._retained_libraries.clear()
queue_release.set(); queue_worker.join(2)
window.native_queue.wake()
qtbot.waitUntil(finished.is_set)
qtbot.waitUntil(lambda: not window.busy)
@@ -70,7 +73,9 @@ def test_release_mapping_cleanup_finishes_before_waiting_ticket_resumes(qtbot, t
retain(monkeypatch, library)
monkeypatch.setattr(library_lock, 'inspect_residual_sessions',
lambda _: dict(library=str(library), sessions=[]))
entered, allow_release = Event(), Event()
def backend_release(*a, **kw):
entered.set(); assert allow_release.wait(5)
sessions._retained_libraries.clear()
return dict(status='RELEASE_CONFIRMED', sessions=[], proof=dict(status='RELEASE_CONFIRMED',
library=str(library), evidence_path='controlled-proof.json'))
@@ -82,15 +87,20 @@ def test_release_mapping_cleanup_finishes_before_waiting_ticket_resumes(qtbot, t
def action():
assert cleaned.is_set(), 'new native operation began before old mapping release completed'
finished.set()
window._start(action, lambda _: None)
qtbot.waitUntil(lambda: window._queue_wait_library is not None)
window._queue_wait_library = str(library)
window.check_library_release(queued=True)
qtbot.waitUntil(lambda: not window.release_dialog.busy)
window.release_dialog.confirm_button.click()
qtbot.waitUntil(finished.is_set)
qtbot.waitUntil(lambda: not window.release_dialog.busy)
qtbot.waitUntil(lambda: not window.busy)
window.release_dialog.close()
qtbot.waitUntil(entered.is_set)
try:
window._start(action, lambda _: None)
allow_release.set()
qtbot.waitUntil(finished.is_set)
qtbot.waitUntil(lambda: not window.release_dialog.busy)
qtbot.waitUntil(lambda: not window.busy)
window.release_dialog.close()
finally:
allow_release.set()
def test_wait_reason_updates_when_active_task_becomes_a_retained_session(qtbot, tmp_path, monkeypatch):
@@ -110,7 +120,6 @@ def test_wait_reason_updates_when_active_task_becomes_a_retained_session(qtbot,
qtbot.waitUntil(lambda: '已排队' in window.status_label.text())
assert window._queue_wait_library is None
sessions._retained_libraries['controlled-session'] = {sessions._library_key(library)}
release.set(); first.join(3)
qtbot.waitUntil(lambda: 'BlockedCBB' in window.status_label.text())
assert not window.queue_release_button.isHidden()
finally:
@@ -132,6 +141,8 @@ def test_management_wait_shows_same_block_and_emits_release_target(qtbot, tmp_pa
qtbot.addWidget(dialog); dialog.show()
targets = []
dialog.release_requested.connect(targets.append)
from test_review381_queue_release import hold_native_queue
queue_release, queue_worker = hold_native_queue(dialog)
dialog.execute_button.click()
qtbot.waitUntil(lambda: 'BlockedCBB' in dialog.status_label.text())
assert dialog.release_wait_button.isVisible()
@@ -139,6 +150,7 @@ def test_management_wait_shows_same_block_and_emits_release_target(qtbot, tmp_pa
assert targets == [library]
dialog.stop.set()
qtbot.waitUntil(lambda: not dialog.busy)
queue_release.set(); queue_worker.join(2)
def test_close_waits_for_independent_release_worker(qtbot, tmp_path, monkeypatch):
+26 -4
View File
@@ -1,5 +1,5 @@
"""Stale and repeated user actions around native queue admission."""
from threading import Event
from threading import Event, Thread
from types import SimpleNamespace
from pathlib import Path
@@ -12,6 +12,18 @@ from test_review326_queue_guidance import retain
from test_ui_filters import load_window
def hold_native_queue(window):
"""A live owner, rather than old retention metadata, keeps admission queued."""
entered, release = Event(), Event()
def action():
entered.set()
assert release.wait(10)
worker = Thread(target=lambda:window.native_queue.run(action))
worker.start()
assert entered.wait(2)
return release, worker
def test_verify_admission_hides_release_entry_before_action_finishes(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
window.show()
@@ -81,6 +93,7 @@ def test_old_waiting_event_is_rechecked_against_current_release_state(qtbot, tmp
def test_other_library_icdb_start_preserves_the_foreground_wait(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch)
window.show()
queue_release, queue_worker = hold_native_queue(window)
retain(monkeypatch, window.mentor_lmc_path)
window._start(lambda: None, lambda _: None)
try:
@@ -90,6 +103,7 @@ def test_other_library_icdb_start_preserves_the_foreground_wait(qtbot, tmp_path,
assert window.queue_release_button.isVisible()
assert window._queue_wait_library == 'test.lmc'
finally:
queue_release.set(); queue_worker.join(2)
sessions._retained_libraries.clear()
window.native_queue.wake()
qtbot.waitUntil(lambda: not window.busy)
@@ -130,6 +144,7 @@ def test_repeated_click_and_close_reuse_one_panel_without_unlocking_the_task(qtb
from cbb_refresh_verify import library_lock
window = load_window(qtbot, tmp_path, monkeypatch)
window.show()
queue_release, queue_worker = hold_native_queue(window)
retain(monkeypatch, window.mentor_lmc_path)
monkeypatch.setattr(library_lock, 'inspect_residual_sessions',
lambda library: dict(library=str(library), sessions=[]))
@@ -150,6 +165,7 @@ def test_repeated_click_and_close_reuse_one_panel_without_unlocking_the_task(qtb
reopened.close()
assert window.busy
finally:
queue_release.set(); queue_worker.join(2)
sessions._retained_libraries.clear()
window.native_queue.wake()
qtbot.waitUntil(lambda: not window.busy)
@@ -159,6 +175,7 @@ def test_repeat_verify_then_stop_then_delayed_release_click_never_starts_work(qt
calls = []
window = load_window(qtbot, tmp_path, monkeypatch, verifier=lambda request: calls.append(request.block_name))
window.show()
queue_release, queue_worker = hold_native_queue(window)
retain(monkeypatch, window.mentor_lmc_path)
window.search_edit.setText('Beta')
window.verify_all()
@@ -167,15 +184,16 @@ def test_repeat_verify_then_stop_then_delayed_release_click_never_starts_work(qt
for _ in range(5):
qtbot.mouseClick(window.batch_button, Qt.LeftButton)
window.verify_all()
assert len(window.native_queue.pending) == 1
assert len(window.native_queue.pending) == 2
qtbot.mouseClick(window.stop_button, Qt.LeftButton)
qtbot.waitUntil(lambda: not window.busy)
for _ in range(5):
window.check_library_release(queued=True)
assert calls == []
assert not window.native_queue.pending
assert len(window.native_queue.pending) == 1
assert getattr(window, 'release_dialog', None) is None
finally:
queue_release.set(); queue_worker.join(2)
window.stop.set()
sessions._retained_libraries.clear()
window.native_queue.wake()
@@ -186,11 +204,14 @@ def test_repeat_verify_then_stop_then_delayed_release_click_never_starts_work(qt
def test_foreground_completion_and_background_cancel_keep_only_live_waits(qtbot, tmp_path, monkeypatch,
foreground_finishes_first):
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: pytest.fail('A retained library must not start a native check'))
verifier=lambda _: pytest.fail('An intentionally paused check must not execute'))
window.show()
queue_release, queue_worker = hold_native_queue(window)
retain(monkeypatch, window.mentor_lmc_path)
window._run(['Beta'], maintenance=True)
window.icdb_task.pause()
qtbot.waitUntil(lambda: window.queue_release_button.isVisible())
queue_release.set(); queue_worker.join(2)
window.mentor_lmc_path = Path('other.lmc')
window.lmc_edit.setText('other.lmc')
started, finish = Event(), Event()
@@ -215,6 +236,7 @@ def test_foreground_completion_and_background_cancel_keep_only_live_waits(qtbot,
if not foreground_finishes_first:
assert window.busy
finally:
queue_release.set(); queue_worker.join(2)
finish.set()
window.icdb_task.cancel()
sessions._retained_libraries.clear()
+2 -1
View File
@@ -49,7 +49,8 @@ def test_batch_result_is_visible_before_queued_refresh_and_survives_user_actions
other_started.set();other_release.wait(5)
thread=Thread(target=lambda:window.native_queue.run(other));thread.start()
try:
qtbot.waitUntil(lambda:len(window.native_queue.pending)==1)
# The queue retains both the active ticket and its waiting successor.
qtbot.waitUntil(lambda:len(window.native_queue.pending)==2)
release.set();qtbot.waitUntil(other_started.is_set)
qtbot.waitUntil(lambda:getattr(window,'summary',None) is not None,timeout=1500)
assert window.summary.isVisible() and window.busy
+2 -1
View File
@@ -126,7 +126,8 @@ def test_verify_requires_loaded_library_and_invalidates_on_path_change(qtbot):
assert hasattr(window, 'libspec_edit') and hasattr(window, 'dms_edit')
window.lmc_edit.setText('different.lmc')
assert not window.batch_button.isEnabled()
assert window.cbb_table.rowCount() == 0
assert window.cbb_table.rowCount() == 1
assert '失效' in window.library_notice.text()
def test_ui_removes_current_cbb_controls_and_hides_advanced_settings(qtbot):