import pytest from cbb_refresh_verify.pcb_bridge import ( PcbBridgeError, execution_outcome, require_document_identity, wait_for_target_document, ) class ProjectIntegration: def __init__(self, project): self.ProjectFile = str(project) class Document: def __init__(self, name, project): self.Name = name self.ProjectIntegration = ProjectIntegration(project) class Application: def __init__(self, document): self.ActiveDocument = document def job(tmp_path): return { 'project': str(tmp_path / 'Work' / 'CBB.prj'), 'pcb': str(tmp_path / 'Work' / 'PCB' / 'CBB.pcb'), } def test_bridge_rejects_wrong_document_before_actions(tmp_path): current = Document('OTHER.pcb', tmp_path / 'Work' / 'OTHER.prj') with pytest.raises(PcbBridgeError, match='身份不符') as raised: require_document_identity(current, job(tmp_path)) assert raised.value.error_code == 'PCB_IDENTITY_MISMATCH' def test_bridge_attaches_through_com_without_window_title_gate(tmp_path): expected = Document('CBB.pcb', tmp_path / 'Work' / 'CBB.prj') attempts = iter((RuntimeError('not ready'), Application(expected))) events = [] def provider(): value = next(attempts) if isinstance(value, Exception): raise value return value app, document, integration = wait_for_target_document( job(tmp_path), provider, process_alive=lambda: True, emit=lambda **event: events.append(event), sleep=lambda _seconds: None, ) assert app.ActiveDocument is document assert integration.ProjectFile.endswith('CBB.prj') assert not any(event['stage'] == 'com_wait' for event in events) assert events[-1]['stage'] == 'identity_verified' def test_bridge_stops_if_pcb_exits_before_com_is_ready(tmp_path): alive = iter((True, False)) with pytest.raises(PcbBridgeError) as raised: wait_for_target_document( job(tmp_path), lambda: (_ for _ in ()).throw(RuntimeError('not ready')), process_alive=lambda: next(alive), sleep=lambda _seconds: None, ) assert raised.value.error_code == 'PCB_EXITED_BEFORE_COM' def test_fatal_dialog_overrides_successful_save_markers(): result = execution_outcome( save_complete=True, pcb_exited=True, fatal_error='SAVE_REUSABLE_BLOCK_FAILED: Error saving the Reusable Block', ) assert result['status'] == 'FAIL' assert result['error_code'] == 'SAVE_REUSABLE_BLOCK_FAILED' def test_success_requires_save_and_pcb_exit(): assert execution_outcome(save_complete=True, pcb_exited=True)['status'] == 'PASS' assert execution_outcome(save_complete=False, pcb_exited=True)['status'] == 'FAIL' assert execution_outcome(save_complete=True, pcb_exited=False)['status'] == 'FAIL'