652 lines
32 KiB
Python
652 lines
32 KiB
Python
"""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 not 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)
|