"""Field #17: data failures finish their own cleanup before the next writer.""" import json import time from dataclasses import replace from pathlib import Path from types import SimpleNamespace import pytest from cbb_refresh_verify import failed_session, verify_runner from cbb_refresh_verify.models import CbbRecord, LibraryReadResult def test_database_load_question_declines_log_view_then_closes_empty_target(tmp_path, monkeypatch): import win32con from test_failed_startup import read_write_fixture job, records, messages, names, _ = read_write_fixture(tmp_path, monkeypatch) names[203] = ('Problem encountered while opening one of the database files. ' 'See PCBLogFile.txt for details. Loading of the job has failed.\r\r' 'Do you wish to view the log file now?') result = failed_session.close_failed_startup(job, 12, timeout_seconds=0) assert result['status'] == 'CLOSED', result assert messages == [(202, win32con.BM_CLICK), (100, win32con.WM_CLOSE)] assert not records @pytest.mark.parametrize('text', [ 'Problem encountered while opening one of the database files. Delete database?', 'Loading of the job has failed. Do you wish to repair it?', ]) def test_unknown_database_question_is_preserved(tmp_path, monkeypatch, text): from test_failed_startup import read_write_fixture job, records, messages, names, _ = read_write_fixture(tmp_path, monkeypatch) names[203] = text result = failed_session.close_failed_startup(job, 12, timeout_seconds=0) assert result['status'] == 'RETAINED' and records and not messages def test_supervisor_acknowledged_failed_open_can_close_empty_shell_with_address(tmp_path, monkeypatch): import win32con from cbb_refresh_verify.dialog_models import WindowSnapshot, ControlSnapshot, DialogPhase from test_failed_startup import startup_fixture job, records, messages = startup_fixture(tmp_path, monkeypatch) address = tmp_path/'database/cdbsvr/sAddress.adr' address.parent.mkdir(parents=True) address.write_text('original address') popup = WindowSnapshot(200,12,'ExpeditionPCB.exe','pcb','#32770','Expedition PCB', DialogPhase.PCB_STARTING, ( ControlSnapshot(201,6,'Button','Yes'), ControlSnapshot(202,7,'Button','No'), ControlSnapshot(203,65535,'Static', 'Problem encountered while opening one of the database files. ' 'See PCBLogFile.txt for details. Loading of the job has failed.\r\r' 'Do you wish to view the log file now?'))) (tmp_path/'dialogs.jsonl').write_text(json.dumps(dict(popup.to_record(), action='acknowledge_fatal', error_code='MENTOR_DATABASE_LOAD_FAILED', accepted_control=[7]))+'\n') result = failed_session.close_failed_startup(job, 12, timeout_seconds=0) assert result['status'] == 'CLOSED', result assert messages == [(100,win32con.WM_CLOSE)] assert not records and address.read_text() == 'original address' @pytest.mark.parametrize('aliased', [False, True]) def test_late_release_is_rechecked_before_later_same_library_item(tmp_path, monkeypatch, aliased): library = tmp_path/'lib.lmc' calls, checks = [], [] failed = verify_runner.VerifyResult('FAIL', stderr='bad database', safe_to_continue=False, evidence_path=tmp_path/'result.json', error_category='MENTOR_DATABASE_LOAD_FAILED') def verify(request): calls.append(request.block_name) return failed if request.block_name == 'Bad' else verify_runner.VerifyResult('PASS') def recheck(library, block, result, **kwargs): checks.append(block) return result if len(checks) == 1 else replace(result, safe_to_continue=True) monkeypatch.setattr('cbb_refresh_verify.operation_lifecycle.recheck_failed_release', recheck) if aliased: monkeypatch.setattr('cbb_refresh_verify.operation_queue.request_library_keys', lambda *args:{'display-path','mapped-path'}) results = verify_runner.run_batch([verify_runner.VerifyRequest(library, n, tmp_path) for n in ('Bad','Good')], verifier=verify) assert calls == ['Bad','Good'] assert [r.status for r in results] == ['FAIL','PASS'] assert results[0].safe_to_continue def test_slow_catalog_status_is_delivered_and_unknown_cannot_start_bulk(qtbot, tmp_path, monkeypatch): from test_issue15_ui_integration import window_for from cbb_refresh_verify.management import Catalog, CatalogEntry from threading import Event entered, release = Event(), Event() def statuses(names, library): entered.set() assert release.wait(15) return {name:'READY' for name in names} window = window_for(qtbot, tmp_path, monkeypatch, reader=lambda _: LibraryReadResult((CbbRecord('A','LP'),), directory_count=1), catalog_reader=lambda p,e:Catalog(p,1,(CatalogEntry('A','Logical-Physical'),)), status_refresher=statuses) window.lmc_edit.setText('a.lmc') window.load_library() qtbot.waitUntil(entered.is_set) try: assert not window.batch_button.isEnabled() assert window.backup_restore_button.isEnabled() assert '待读取 1' in window.counts_label.text() # Actual prior metadata cutoff; native IO is simulated, task/Qt delivery is real. qtbot.wait(10300) release.set() qtbot.waitUntil(lambda:window.ready_names == {'A'}, timeout=3000) assert '原生 1' in window.counts_label.text() finally: release.set() window.pool.waitForDone(5000) def test_successful_worker_does_not_report_retained_save(tmp_path, monkeypatch): from test_verify_worker_stability import exercise_worker job, events, execute = exercise_worker(tmp_path, monkeypatch) assert execute()['status'] == 'PASS' assert not [e for e in events if e.get('stage') == 'save_result_retained'] @pytest.mark.parametrize('fresh', ['UNKNOWN', 'UNAVAILABLE', None]) def test_execution_rechecks_status_without_starting_unknown_target(qtbot, tmp_path, monkeypatch, fresh): from test_issue15_ui_integration import window_for from cbb_refresh_verify.management import Catalog, CatalogEntry calls, reads = [], [] def statuses(names, library): reads.append(tuple(names)) return {'A':'PENDING'} if len(reads) == 1 else ({} if fresh is None else {'A':fresh}) window = window_for(qtbot,tmp_path,monkeypatch, reader=lambda _:LibraryReadResult((CbbRecord('A','LP'),), directory_count=1), catalog_reader=lambda p,e:Catalog(p,1,(CatalogEntry('A','Logical-Physical'),)), status_refresher=statuses, verifier=lambda request:(calls.append(request.block_name) or verify_runner.VerifyResult('PASS'))) window.lmc_edit.setText('a.lmc'); window.load_library() qtbot.waitUntil(lambda:window._read_counts[1] == 1) window._run(['A']) qtbot.waitUntil(lambda:not window.busy) assert calls == [] reports=list((tmp_path/'reports').glob('batch-*.log')) assert reports and 'STATUS_UNCONFIRMED' in reports[0].read_text(encoding='utf-8') @pytest.mark.parametrize('second_ready', [True,False]) def test_saved_closed_pending_commit_gets_only_one_followup(tmp_path, monkeypatch, second_ready): root=tmp_path/'first';root.mkdir() evidence=root/'result.json';evidence.write_text('{"status":"FAIL"}') second=tmp_path/'second';second.mkdir() second_evidence=second/'result.json';second_evidence.write_text('{}') pending=verify_runner.VerifyResult('FAIL',safe_to_continue=True,evidence_path=evidence, library_flag='NOT_GREEN',error_category='MENTOR_VERIFY_NOT_COMMITTED',error_stage='library_flag', bridge_attempts=({'status':'PENDING','source':'IsVerifiedReuseBlock','raw_status':0},), timings_seconds={'total':2.0}, write_outcome=dict(save_state='COMMITTED',close_state='CLOSED',helper_state='EXITED', resource_state='RELEASED',interrupted=False)) calls=[] def serialized(request,**kwargs): calls.append(request.block_name) if len(calls)==1:return pending return (verify_runner.VerifyResult('PASS',library_flag='GREEN',evidence_path=second_evidence,timings_seconds={'total':3.0}) if second_ready else replace(pending,evidence_path=second_evidence,timings_seconds={'total':3.0})) monkeypatch.setattr(verify_runner,'_run_verify_serialized',serialized) result=verify_runner._run_verify_task(verify_runner.VerifyRequest(tmp_path/'missing.lmc','Block',tmp_path)) assert calls == ['Block','Block'] assert result.status == ('PASS' if second_ready else 'FAIL') assert result.timings_seconds['total']==5.0 assert json.loads(evidence.read_text()) == {'status':'FAIL'} link=json.loads((root/'commit-followup.json').read_text()) assert link['status']==('READY' if second_ready else 'UNCONFIRMED') @pytest.mark.parametrize('obstacle', ['unsafe','save_unknown','close_unknown','native_retained', 'helper_running','interrupted','database_failure','unknown_status','diagnostic','auto_repair','cancelled']) def test_incomplete_or_failed_native_operation_never_gets_commit_followup(tmp_path,monkeypatch,obstacle): from threading import Event evidence=tmp_path/'result.json';evidence.write_text('{}') facts=dict(save_state='COMMITTED',close_state='CLOSED',helper_state='EXITED',resource_state='RELEASED',interrupted=False) if obstacle=='save_unknown':facts['save_state']='UNKNOWN' if obstacle=='close_unknown':facts['close_state']='UNKNOWN' if obstacle=='native_retained':facts['resource_state']='RETAINED' if obstacle=='helper_running':facts['helper_state']='RUNNING' if obstacle=='interrupted':facts['interrupted']=True pending=verify_runner.VerifyResult('FAIL',safe_to_continue=obstacle!='unsafe',evidence_path=evidence, library_flag='NOT_GREEN' if obstacle!='unknown_status' else 'UNKNOWN', error_category='MENTOR_DATABASE_LOAD_FAILED' if obstacle=='database_failure' else 'MENTOR_VERIFY_NOT_COMMITTED', error_stage='library_flag',bridge_attempts=({'status':'PENDING','source':'IsVerifiedReuseBlock','raw_status':0},), write_outcome=facts) stop=Event();calls=[] def serialized(*args,**kwargs): calls.append(1) if obstacle=='cancelled':stop.set() return pending monkeypatch.setattr(verify_runner,'_run_verify_serialized',serialized) verify_runner._run_verify_task(verify_runner.VerifyRequest(tmp_path/'missing.lmc','Block',tmp_path, diagnostic_only=obstacle=='diagnostic',auto_repair=obstacle=='auto_repair'),stop=stop) assert calls == [1] assert not (tmp_path/'commit-followup.json').exists() def test_cancel_after_followup_checkpoint_releases_completed_first_lease(tmp_path,monkeypatch): from cbb_refresh_verify.operation_queue import BatchTaskContext, QueueCancelled from cbb_refresh_verify import library_lock import win32con, win32file library=tmp_path/'lib.lmc';library.write_bytes(b'isolated fixture') evidence=tmp_path/'result.json';evidence.write_text('{}') pending=verify_runner.VerifyResult('FAIL',safe_to_continue=True,evidence_path=evidence, library_flag='NOT_GREEN',error_category='MENTOR_VERIFY_NOT_COMMITTED',error_stage='library_flag', write_outcome=dict(save_state='COMMITTED',close_state='CLOSED',helper_state='EXITED',resource_state='RELEASED',interrupted=False)) monkeypatch.setattr(library_lock,'recheck_previous_release',lambda *a,**k:None) monkeypatch.setattr(verify_runner,'_run_verify_serialized',lambda *a,**k:pending) context=BatchTaskContext(str(library)) original=Path.write_text def write(path,*a,**k): result=original(path,*a,**k) if path.name=='commit-followup.json':context.cancel() return result monkeypatch.setattr(Path,'write_text',write) try: with pytest.raises(QueueCancelled): context.run(lambda:verify_runner._run_verify_task( verify_runner.VerifyRequest(library,'Block',tmp_path),stop=context.stop)) lock=library_lock.LibraryLock(library) handle=win32file.CreateFile(str(lock.path),win32con.GENERIC_READ,0,None,win32con.OPEN_EXISTING,0,None) handle.Close() finally: context.close(timeout_seconds=0) with library_lock._guard: owner=library_lock._owners.pop(library_lock.LibraryLock(library).key,None) if owner:owner['handle'].Close()