210 lines
9.6 KiB
Python
210 lines
9.6 KiB
Python
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_serial_guard_covers_preflight_and_content_check(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:
|
|
second = runner.run_verify(VerifyRequest(tmp_path/'lib.lmc', 'second', tmp_path/'evidence'))
|
|
assert second.status == 'BLOCKED'
|
|
assert second.safe_to_continue
|
|
assert second.error_category == 'NATIVE_CHANNEL_BUSY'
|
|
assert calls == ['first']
|
|
finally:
|
|
release.set()
|
|
thread.join(6)
|
|
|
|
|
|
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()<deadline:
|
|
time.sleep(.05)
|
|
assert ready.exists(), 'Supervised automation worker could not start'
|
|
native_handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_TERMINATE,
|
|
False, int(ready.read_text()))
|
|
supervisor.terminate()
|
|
supervisor.wait(5)
|
|
time.sleep(.5)
|
|
assert worker.poll() is None
|
|
assert win32process.GetExitCodeProcess(native_handle) == 259
|
|
finally:
|
|
if supervisor.poll() is None: supervisor.terminate()
|
|
if worker.poll() is None: worker.terminate()
|
|
supervisor.wait(5)
|
|
worker.wait(5)
|
|
if native_handle is not None:
|
|
win32process.TerminateProcess(native_handle, 0)
|
|
native_handle.Close()
|
|
|
|
|
|
@pytest.mark.parametrize('encoding', ['utf-8-sig', 'utf-16-le', 'utf-16-be'])
|
|
def test_project_rewrite_preserves_bom_and_unicode(tmp_path, encoding):
|
|
pcb = tmp_path/'Work/PCB/sample.pcb'
|
|
pcb.parent.mkdir(parents=True)
|
|
bom = {'utf-8-sig': b'', 'utf-16-le': b'\xff\xfe', 'utf-16-be': b'\xfe\xff'}[encoding]
|
|
original = bom + ('KEY CentralLibrary "S:\\old.lmc"\r\n# 中文工程\r\n').encode(encoding)
|
|
config = pcb.with_name('pcb.prj')
|
|
config.write_bytes(original)
|
|
adapter.ensure_pcb_central_library(pcb, tmp_path/'new.lmc', evidence_dir=tmp_path/'evidence')
|
|
expected = bom + ('KEY CentralLibrary "..\\..\\new.lmc"\r\n# 中文工程\r\n').encode(encoding)
|
|
assert config.read_bytes() == expected
|
|
assert (tmp_path/'evidence/pcb.prj.before-central-library').read_bytes() == original
|
|
|
|
|
|
def test_cli_unsafe_batch_preserves_created_drive(tmp_path, monkeypatch):
|
|
from test_network_path import FakeWNet
|
|
from cbb_refresh_verify.network_path import LibraryPathLease
|
|
from cbb_refresh_verify import application
|
|
backend = FakeWNet()
|
|
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
|
|
monkeypatch.setattr(LibraryPathLease, 'acquire', lambda path: lease)
|
|
monkeypatch.setattr('cbb_refresh_verify.network_path.select_library_file', lambda path: tmp_path/'lib.lmc')
|
|
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_batch', lambda requests, **kw: [VerifyResult('FAIL', safe_to_continue=False)])
|
|
code = application.main(['--batch-lmc', r'\\server\share\lib.lmc', '--block', 'CBB', '--data-root', str(tmp_path/'run')])
|
|
assert code == 2
|
|
assert not backend.cancelled
|
|
assert lease.drive in backend.existing
|
|
|
|
|
|
def test_ui_unsafe_batch_preserves_created_drive(qtbot, tmp_path):
|
|
from test_network_path import FakeWNet
|
|
from cbb_refresh_verify.network_path import LibraryPathLease
|
|
from cbb_refresh_verify.ui.main_window import MainWindow
|
|
backend = FakeWNet()
|
|
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
|
|
window = MainWindow(data_root=tmp_path)
|
|
qtbot.addWidget(window)
|
|
window.library_lease = lease
|
|
window._batch_done(([VerifyResult('FAIL', safe_to_continue=False)], tmp_path/'batch.log'))
|
|
window.close()
|
|
assert not backend.cancelled
|
|
assert lease.drive in backend.existing
|
|
|
|
|
|
def test_legacy_library_reader_only_requests_owned_window_close(monkeypatch):
|
|
import win32gui, win32process, win32con
|
|
from types import SimpleNamespace
|
|
posted = []
|
|
monkeypatch.setattr(win32gui, 'GetWindowText', lambda hwnd: 'Library Manager: example.lmc')
|
|
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 23 if hwnd == 10 else 99))
|
|
monkeypatch.setattr(win32gui, 'PostMessage', lambda *args: posted.append(args))
|
|
monkeypatch.setattr(adapter, '_process_details', lambda name: [])
|
|
desktop = SimpleNamespace(EnumDesktopWindows=lambda: [10, 11])
|
|
assert adapter.close_library_reader(23, desktop, timeout_seconds=0)
|
|
assert posted == [(10, win32con.WM_CLOSE, 0, 0)]
|
|
|
|
|
|
def test_legacy_library_reader_retains_unclosed_native_session(monkeypatch):
|
|
from types import SimpleNamespace
|
|
monkeypatch.setattr(adapter, '_process_details', lambda name: [(23, 'LibraryManager.exe', '', 1)])
|
|
assert not adapter.close_library_reader(23, SimpleNamespace(EnumDesktopWindows=lambda: []), timeout_seconds=0)
|