from pathlib import Path from threading import Event, Thread import pytest from cbb_refresh_verify import mentor_adapter as adapter from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult, classify_output, preflight def test_project_rewrite_preserves_non_utf8_bytes_and_exact_backup(tmp_path): pcb = tmp_path / 'Work/PCB/sample.pcb' pcb.parent.mkdir(parents=True) config = pcb.with_name('pcb.prj') original = b'# native ANSI text: \xd6\xd0\xce\xc4\r\nKEY CentralLibrary "S:\\old.lmc"\r\n' config.write_bytes(original) evidence = tmp_path / 'evidence' adapter.ensure_pcb_central_library(pcb, tmp_path / 'new.lmc', evidence_dir=evidence) assert config.read_bytes() == original.replace(b'S:\\old.lmc', b'..\\..\\new.lmc') assert (evidence / 'pcb.prj.before-central-library').read_bytes() == original def test_project_rewrite_is_atomic_on_replace_failure(tmp_path, monkeypatch): pcb = tmp_path / 'Work/PCB/sample.pcb' pcb.parent.mkdir(parents=True) config = pcb.with_name('pcb.prj') original = b'KEY CentralLibrary "S:\\old.lmc"\r\n' config.write_bytes(original) def denied(*a): raise PermissionError('simulated sharing violation') monkeypatch.setattr(adapter.os, 'replace', denied) with pytest.raises(PermissionError): adapter.ensure_pcb_central_library(pcb, tmp_path / 'new.lmc', evidence_dir=tmp_path/'evidence') assert config.read_bytes() == original @pytest.mark.parametrize('code', [1, 2, -1, None]) def test_content_check_success_text_cannot_override_bad_exit(code): assert classify_output(code, 'content checking completed successfully') != 'PASS' def test_preflight_rejects_pcb_junction_outside_current_block(tmp_path): import _winapi library = tmp_path / 'lib.lmc' library.touch() work = tmp_path / 'ReusableBlocksLP/CBB/Work' work.mkdir(parents=True) (work/'CBB.prj').write_text('KEY PCBDesignPath "PCB\\CBB.pcb"\n') outside = tmp_path / 'other-project' (outside/'Layout').mkdir(parents=True) (outside/'CBB.pcb').touch() (outside/'Layout/LayoutDB.lyt').touch() _winapi.CreateJunction(str(outside), str(work/'PCB')) with pytest.raises(ValueError): preflight(VerifyRequest(library, 'CBB', tmp_path/'evidence')) def test_nonnative_preparation_leaves_real_host_channel_available(tmp_path, monkeypatch): from cbb_refresh_verify import verify_runner as runner entered, release = Event(), Event() calls, results = [], [] def operation(request, **kwargs): calls.append(request.block_name) entered.set() if request.block_name == 'first': assert release.wait(5) return VerifyResult('PASS') monkeypatch.setattr(runner, '_run_verify', operation) request = VerifyRequest(tmp_path/'lib.lmc', 'first', tmp_path/'evidence') thread = Thread(target=lambda: results.append(runner.run_verify(request))) thread.start() assert entered.wait(3) try: from cbb_refresh_verify.operation_queue import native_channel with native_channel(): pass assert calls == ['first'] finally: release.set() thread.join(6) assert results[0].status == 'PASS' def test_recovery_retains_temporary_network_mapping(): from test_network_path import FakeWNet from cbb_refresh_verify.network_path import LibraryPathLease backend = FakeWNet() lease = LibraryPathLease.acquire(r'\\server\share\lib\mentor_lib.lmc', backend=backend) lease.retain_for_recovery() lease.close() assert backend.cancelled == [] assert lease.drive in backend.existing def test_verified_green_block_does_not_call_forbidden_forward_annotation(): from cbb_refresh_verify.integration import refresh_integration class AlreadyVerified: ForwardAnnotationStatus = SynchCESStatus = LoadCESStatus = BackAnnotationStatus = 2 IsForwardAnnotationAllowed = IsSynchCESAllowed = IsLoadCESAllowed = IsBackAnnotationAllowed = False def ForwardAnnotate(self): pytest.fail('Mentor explicitly forbids ForwardAnnotate on this verified block') result = refresh_integration(AlreadyVerified(), settle_seconds=0) assert all(value == 2 for value in result.values()) def test_wmi_process_query_rejects_non_allowlisted_names(): with pytest.raises(ValueError): adapter._process_details("ExpeditionPCB.exe' OR Name='other.exe") def test_supervisor_loss_stops_automation_but_preserves_native_like_process(tmp_path): import subprocess import sys import time import win32api, win32con, win32process supervisor = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)']) script = tmp_path/'watchdog-worker.py' ready = tmp_path/'native.pid' script.write_text( 'import sys, subprocess, time\nfrom pathlib import Path\n' 'from cbb_refresh_verify.desktop_worker import start_supervisor_watchdog\n' f'start_supervisor_watchdog({supervisor.pid})\n' 'native = subprocess.Popen([sys.executable,"-c","import time; time.sleep(30)"])\n' f'Path({str(ready)!r}).write_text(str(native.pid))\n' 'time.sleep(30)\n', encoding='utf-8') worker = subprocess.Popen([sys.executable, str(script)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) native_handle = None try: deadline = time.monotonic()+5 while not ready.exists() and worker.poll() is None and time.monotonic()