import json import os from pathlib import Path import subprocess import sys import time import pytest from cbb_refresh_verify import verify_runner as runner def test_content_timeout_preserves_importer_and_native_like_child(tmp_path): import win32api, win32con, win32process script = tmp_path/'importer.py' pids = tmp_path/'pids.json' script.write_text( 'import subprocess,sys,time,os,json\nfrom pathlib import Path\n' 'child=subprocess.Popen([sys.executable,"-c","import time;time.sleep(30)"],' 'stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)\n' f'Path({str(pids)!r}).write_text(json.dumps([os.getpid(),child.pid]))\n' 'time.sleep(30)\n', encoding='utf-8') handles = [] try: result = runner._run_process([sys.executable, str(script)], 2, tmp_path) assert result[3] is True assert pids.is_file() for pid in json.loads(pids.read_text()): try: handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_TERMINATE, False, pid) except Exception: pytest.fail(f'Timeout terminated database-related process {pid}') handles.append(handle) assert win32process.GetExitCodeProcess(handle) == 259 finally: for handle in handles: win32process.TerminateProcess(handle, 0) handle.Close() def test_content_timeout_stops_remaining_batch(tmp_path, monkeypatch): from test_verify_runner import fixture, request fixture(tmp_path) monkeypatch.setattr(runner, 'resolve_importer', lambda *_: Path('ReuseBlockImporter.exe')) calls = [] def timeout(*args): calls.append(args) return None, '', 'content check still running', True req = request(tmp_path, libspec='EE', dms_login_config='login') results = runner.run_batch([req, req], verifier=lambda item: runner.run_verify(item, process_runner=timeout, port_check=lambda: pytest.fail('PCB must not start'))) assert len(calls) == 1 assert results[0].status == 'TIMEOUT' assert results[0].safe_to_continue is False assert results[1].status == 'SKIPPED' @pytest.mark.parametrize('identity,close_ok,other_document,expected_code', [ (True, True, False, 0), (False, True, False, 2), (True, False, False, 4), (True, True, True, 5)]) def test_failed_document_close_uses_native_discard_and_rejects_wrong_identity( tmp_path, identity, close_ok, other_document, expected_code): source = Path('src/cbb_refresh_verify/close_failed_block.vbs').read_text('utf-8') classes = r''' Dim nativeClosed nativeClosed = False Class FakePi Public ProjectFile Private Sub Class_Initialize ProjectFile = PROJECT_VALUE End Sub End Class Class FakeDoc Public Name Private Sub Class_Initialize Name = "CBB.pcb" End Sub Public Property Get ProjectIntegration Set ProjectIntegration = New FakePi End Property Public Function Validate(value) Validate = 17 End Function Public Function Close(saveChanges) If saveChanges Then WScript.Quit 90 WScript.Echo "NATIVE_DISCARD_CLOSE" nativeClosed = CLOSE_RETURN Close = CLOSE_RETURN End Function End Class Class FakeApp Public Property Get ActiveDocument If nativeClosed And Not OTHER_DOCUMENT Then Set ActiveDocument = Nothing Else Set ActiveDocument = New FakeDoc End If End Property Public Sub Quit() WScript.Echo "NATIVE_QUIT" End Sub End Class Class FakeLic Public Function GetToken(value) GetToken = value End Function End Class '''.replace('PROJECT_VALUE', 'WScript.Arguments(0)' if identity else '"OTHER.prj"') classes = classes.replace('CLOSE_RETURN', str(close_ok)) classes = classes.replace('OTHER_DOCUMENT', str(other_document)) source = source.replace('Option Explicit', 'Option Explicit\n'+classes) source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp') source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic') harness = tmp_path/'close.vbs' harness.write_text(source, encoding='ascii') outcome = subprocess.run([str(Path(os.environ['WINDIR'])/'SysWOW64/cscript.exe'), '//nologo', str(harness), 'expected.prj', 'CBB.pcb'], capture_output=True, text=True, timeout=10) assert outcome.returncode == expected_code, outcome.stderr assert ('NATIVE_DISCARD_CLOSE' in outcome.stdout) is identity assert ('NATIVE_QUIT' in outcome.stdout) is (identity and close_ok and not other_document) def test_cancel_after_native_save_returns_stops_later_native_operations(tmp_path): source = Path('src/cbb_refresh_verify/save_verified_block.vbs').read_text('utf-8') classes = r''' Class FakePi Public ProjectFile, ForwardAnnotationStatus, SynchCESStatus, LoadCESStatus, BackAnnotationStatus Private Sub Class_Initialize ProjectFile = WScript.Arguments(0) ForwardAnnotationStatus = 2 SynchCESStatus = 2 LoadCESStatus = 2 BackAnnotationStatus = 2 End Sub End Class Class FakeDoc Public Name Private Sub Class_Initialize Name = "CBB.pcb" End Sub Public Property Get ProjectIntegration Set ProjectIntegration = New FakePi End Property Public Function Validate(token) Validate = 17 End Function Public Function Save() Dim fso, flag Set fso = CreateObject("Scripting.FileSystemObject") Set flag = fso.CreateTextFile(WScript.Arguments(2), True) flag.Close WScript.Sleep 120 WScript.Echo "NATIVE_SAVE_RETURNED" Save = True End Function Public Function IsSaved() IsSaved = True End Function Public Function Close(saveChanges) Close = True End Function End Class Class FakeApp Public Property Get ActiveDocument Set ActiveDocument = New FakeDoc End Property Public Sub Quit() End Sub End Class Class FakeLic Public Function GetToken(value) GetToken = value End Function End Class ''' source = source.replace('Option Explicit', 'Option Explicit\n'+classes) source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp') source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic') harness = tmp_path/'save-cancel.vbs' harness.write_text(source, encoding='ascii') outcome = subprocess.run([str(Path(os.environ['WINDIR'])/'SysWOW64/cscript.exe'), '//nologo', str(harness), 'expected.prj', 'CBB.pcb', str(tmp_path/'cancel.signal')], capture_output=True, text=True, timeout=10) assert 'NATIVE_SAVE_RETURNED' in outcome.stdout assert outcome.returncode == 9, outcome.stderr assert 'VERIFY_CANCELLED' in outcome.stdout assert 'CLOSE_OK' not in outcome.stdout def test_worker_attempts_normal_close_after_idle_integration_failure(tmp_path, monkeypatch): from test_verify_worker_stability import exercise_worker from cbb_refresh_verify import mentor_adapter as adapter job, events, execute = exercise_worker(tmp_path, monkeypatch, integration_error='packaging rejected') closes = [] monkeypatch.setattr('cbb_refresh_verify.failed_session.close_failed_document', lambda value, **kwargs: closes.append(value) or {'status': 'CLOSED'}) with pytest.raises(RuntimeError, match='packaging rejected'): execute() assert closes == [job] assert not any(event['stage'] == 'save_start' for event in events) def test_stop_cancels_then_stops_automation_client_after_deadline(tmp_path): calls = [] class BusyWorker: def request_stop(self): calls.append('cancel') def wait(self, timeout): raise TimeoutError('native Save still running') def kill(self): calls.append('kill') runner._stop_worker(BusyWorker(), timeout=0) assert calls == ['cancel', 'kill'] def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path): from cbb_refresh_verify.status_bridge import StatusBridgeServer script = tmp_path/'reader.py' marker = tmp_path/'released.txt' script.write_text('import sys,time\nfrom pathlib import Path\n' 'for line in sys.stdin: pass\n' 'time.sleep(.1)\n' f'Path({str(marker)!r}).write_text("native handles released")\n', encoding='utf-8') server = StatusBridgeServer(script) server.start() time.sleep(.2) server.close() assert marker.is_file() def test_shared_address_does_not_block_actual_content_check(tmp_path, monkeypatch): from test_verify_runner import fixture, request fixture(tmp_path) address = tmp_path/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr' address.parent.mkdir(parents=True) address.write_bytes(b'unknown native owner') req = request(tmp_path, libspec='EE', dms_login_config='login') calls = [] outcome = runner.run_verify(req, process_runner=lambda *args: (calls.append(args) or (1, 'ERROR: shared database unavailable', '', False))) assert calls and outcome.status == 'FAIL' and outcome.safe_to_continue assert 'shared database unavailable' in outcome.stderr assert address.read_bytes() == b'unknown native owner' def test_shared_address_is_diagnostic_after_successful_native_execution(tmp_path, monkeypatch): from test_verify_worker_stability import exercise_worker from cbb_refresh_verify import mentor_adapter as adapter job, events, execute = exercise_worker(tmp_path, monkeypatch) original = adapter.subprocess.Popen def helper(*args, **kwargs): address = Path(job['lmc_file']).parent/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr' address.parent.mkdir(parents=True) address.write_bytes(b'shared owner retained') return original(*args, **kwargs) monkeypatch.setattr(adapter.subprocess, 'Popen', helper) assert execute()['status'] == 'PASS' assert any(event['stage'] == 'icdb_address_remaining' for event in events) def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path): import win32api, win32con, win32process supervisor = subprocess.Popen([sys.executable, '-c', 'import time;time.sleep(30)']) script, ready, cancel = tmp_path/'worker.py', tmp_path/'ready.json', tmp_path/'cancel.signal' script.write_text('import subprocess,sys,time,json\nfrom pathlib import Path\n' 'from cbb_refresh_verify.desktop_worker import start_supervisor_watchdog,launch_save_helper\n' f'start_supervisor_watchdog({supervisor.pid},cancel_path={str(cancel)!r})\n' 'helper=launch_save_helper([sys.executable,"-c","import time;time.sleep(30)"])\n' f'Path({str(ready)!r}).write_text(json.dumps(helper.pid))\n' 'time.sleep(30)\n', encoding='utf-8') worker = subprocess.Popen([sys.executable, str(script)]) handle = None try: deadline = time.monotonic()+5 while not ready.exists() and time.monotonic()