fix: harden PCB and iCDB verification lifecycle for beta release

This commit is contained in:
阿白叔 committed 2026-10-26 15:32:01 +08:00
1 parent 11a2b2e46e
commit a11eb3c766
33 files changed
+1226 -267

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$root = Split-Path $PSScriptRoot -Parent
Import-Module (Join-Path $root 'CBBRefresh.Core.psm1') -Force
$scratch = Join-Path $root ('build\content-check-exit-' + [guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $scratch | Out-Null
$exe = Join-Path $scratch 'ReuseBlockImporter.exe'
Add-Type -TypeDefinition @'
using System;
public class FakeImporter {
public static int Main(string[] args) {
Console.WriteLine("content checking completed successfully");
return 7;
}
}
'@ -OutputAssembly $exe -OutputType ConsoleApplication
$library = Join-Path $scratch 'test.lmc'
[IO.File]::WriteAllText($library, '')
$result = Invoke-CbbReuseBlockContentCheck -LmcFile $library -BlockName 'CBB' -LibSpec 'test' -DmsLoginConfig 'test' -MentorBin $scratch
if ($result.result -ne 'fail' -or $result.exitCode -ne 7) {
throw 'A nonzero native exit must not pass, even when stdout claims success.'
}
Write-Output 'Content-check exit-code regression passed (no Mentor data opened).'
+111
View File
@@ -0,0 +1,111 @@
"""Fault injection at native boundaries; real Windows supervisor-loss check."""
import json
from pathlib import Path
from types import SimpleNamespace
import pytest
from cbb_refresh_verify import mentor_adapter as adapter
from test_verify_worker_stability import exercise_worker
FULL_SAVE = 'LICENSE_OK\nSAVE_OK\nIS_SAVED\nPOST_SAVE_SYNCHRONIZED\nCLOSE_OK\nQUIT_OK\n'
@pytest.mark.parametrize('stage,log,exit_code', [
('startup', '', 0),
('integration', '', 0),
('save', '', 1),
('save', 'LICENSE_OK\nSAVE_START\n', 1),
('save', FULL_SAVE, 7),
('save', FULL_SAVE.replace('CLOSE_OK\n', ''), 0),
('save', FULL_SAVE.replace('IS_SAVED\n', ''), 0),
])
def test_native_disconnect_or_interrupted_save_never_completes(tmp_path, monkeypatch, stage, log, exit_code):
job, _, _ = exercise_worker(tmp_path, monkeypatch,
integration_error='RPC_E_DISCONNECTED: PCB closed during integration' if stage == 'integration' else None)
if stage == 'startup':
from cbb_refresh_verify.pcb_bridge import PcbBridgeError
def disconnected(*a, **k):
raise PcbBridgeError('PCB_EXITED_BEFORE_COM', 'PCB exited before COM was ready')
monkeypatch.setattr('cbb_refresh_verify.pcb_bridge.wait_for_target_document', disconnected)
if stage == 'save':
def interrupted_helper(command, **kwargs):
kwargs['stdout'].write(log)
kwargs['stdout'].flush()
return SimpleNamespace(pid=3, poll=lambda: exit_code, returncode=exit_code)
monkeypatch.setattr(adapter.subprocess, 'Popen', interrupted_helper)
root = Path(job['root'])
request = root/'request.json'
request.write_text(json.dumps(job), encoding='utf-8')
assert adapter.worker_main(request) == 1
result = json.loads((root/'outcome.json').read_text(encoding='utf-8'))
assert result['status'] == 'FAIL'
assert result['safe_to_continue'] is False
events = [json.loads(line) for line in (root/'events.jsonl').read_text(encoding='utf-8').splitlines()]
assert not any(event['stage'] in ('complete', 'saved_and_closed') for event in events)
if stage != 'save':
assert not (root/'save.log').exists()
@pytest.mark.parametrize('outcome', [None, {'status': 'PASS'}])
def test_crashed_worker_cannot_pass_even_with_pass_file(tmp_path, monkeypatch, outcome):
from test_verify_runner import fixture, request
from cbb_refresh_verify.verify_runner import run_verify
fixture(tmp_path)
class CrashedWorker:
desktop = None
returncode = 7
def __init__(self, command, *_args, **_kwargs):
if outcome:
Path(command[-1]).with_name('outcome.json').write_text(json.dumps(outcome))
def poll(self): return 7
def close(self): pass
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', CrashedWorker)
monkeypatch.setattr('cbb_refresh_verify.verify_runner._cleanup_session_processes',
lambda *a, **k: {'safe_to_continue': True, 'remaining_pids': []})
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *a: None)
def must_not_query(*a):
pytest.fail('A crashed writer must not become PASS via a pre-existing READY flag')
result = run_verify(request(tmp_path), port_check=lambda: (True, ''), flag_reader=must_not_query)
assert result.status == 'FAIL'
assert result.safe_to_continue is False
def test_supervisor_crash_stops_registered_save_helper_but_not_native(tmp_path):
import subprocess, sys, time
import win32api, win32con, win32process, win32event
supervisor = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])
ready = tmp_path/'processes.json'
script = tmp_path/'worker.py'
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})\n'
'native = subprocess.Popen([sys.executable,"-c","import time; time.sleep(30)"])\n'
'helper = launch_save_helper([sys.executable,"-c","import time; time.sleep(30)"])\n'
f'Path({str(ready)!r}).write_text(json.dumps([native.pid,helper.pid]))\n'
'time.sleep(30)\n', encoding='utf-8')
worker = subprocess.Popen([sys.executable, str(script)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
handles = []
try:
deadline = time.monotonic()+6
while not ready.exists() and worker.poll() is None and time.monotonic()<deadline:
time.sleep(.05)
assert ready.exists()
for pid in json.loads(ready.read_text()):
handles.append(win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION |
win32con.PROCESS_TERMINATE | win32con.SYNCHRONIZE, False, pid))
supervisor.terminate()
supervisor.wait(5)
assert worker.wait(8) == 75
assert win32event.WaitForSingleObject(handles[1], 3000) == win32con.WAIT_OBJECT_0
assert win32process.GetExitCodeProcess(handles[0]) == 259
finally:
for process in (supervisor, worker):
if process.poll() is None: process.terminate()
process.wait(5)
for handle in handles:
if win32process.GetExitCodeProcess(handle) == 259:
win32process.TerminateProcess(handle, 0)
handle.Close()
+3 -3
View File
@@ -78,7 +78,7 @@ def test_license_selector_is_allowed_after_com_attach_wait():
assert decision.error_code == ""
def test_open_lock_confirmation_is_allowed_during_pcb_starting():
def test_open_lock_confirmation_blocks_during_pcb_starting():
rules = load_rules(ASSETS / "dialog_rules.v1.json")
snapshot = prompt(
"Continue to open the design with read/write access permission?",
@@ -87,8 +87,8 @@ def test_open_lock_confirmation_is_allowed_during_pcb_starting():
decision = decide(snapshot, rules)
assert decision.rule_id == "open-lock-confirm"
assert decision.error_code == ""
assert not decision.action
assert decision.error_code == "DATABASE_RECOVERY_REQUIRED"
def test_forward_annotation_confirmation_is_accepted_during_document_attach():
+10 -10
View File
@@ -345,14 +345,14 @@ def test_phase_aware_unknown_window_fails_without_action():
def test_phase_aware_action_is_pending_until_window_disappears():
restore = evidence_window(
'Database Restoration - Load the last user saved database',
phase=DialogPhase.DATABASE_RECOVERY,
'Do you want to save the reusable block cell',
phase=DialogPhase.SAVE,
)
backend = PhaseBackend([[restore], []])
supervisor = DialogSupervisor(backend, rules=RULES, retry_seconds=60)
first = supervisor.poll(DialogPhase.DATABASE_RECOVERY)
second = supervisor.poll(DialogPhase.DATABASE_RECOVERY)
first = supervisor.poll(DialogPhase.SAVE)
second = supervisor.poll(DialogPhase.SAVE)
assert first.action_sent and not first.resolved
assert second.resolved
@@ -361,19 +361,19 @@ def test_phase_aware_action_is_pending_until_window_disappears():
def test_phase_aware_changed_content_is_not_window_gone():
first = evidence_window(
'Database Restoration - Load the last user saved database',
phase=DialogPhase.DATABASE_RECOVERY,
'Do you want to save the reusable block cell',
phase=DialogPhase.SAVE,
)
changed = evidence_window(
'Database Restoration - Load the last user saved database - selected',
phase=DialogPhase.DATABASE_RECOVERY,
'Do you want to save the reusable block cell - selected',
phase=DialogPhase.SAVE,
selected=True,
)
backend = PhaseBackend([[first], [changed]])
supervisor = DialogSupervisor(backend, rules=RULES, retry_seconds=60)
first_result = supervisor.poll(DialogPhase.DATABASE_RECOVERY)
second_result = supervisor.poll(DialogPhase.DATABASE_RECOVERY)
first_result = supervisor.poll(DialogPhase.SAVE)
second_result = supervisor.poll(DialogPhase.SAVE)
assert first_result.action_sent and not first_result.resolved
assert not second_result.resolved
+207
View File
@@ -0,0 +1,207 @@
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 not second.safe_to_continue
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)
assert worker.wait(8) == 75
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: [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)
+6 -6
View File
@@ -17,7 +17,7 @@ def test_parse_icdb_server_address_extracts_port_and_hosts(tmp_path):
}
def test_stale_icdb_address_is_moved_to_evidence(tmp_path, monkeypatch):
def test_unreachable_icdb_address_is_preserved(tmp_path, monkeypatch):
from cbb_refresh_verify import mentor_adapter
database = tmp_path / "database"
@@ -33,12 +33,12 @@ def test_stale_icdb_address_is_moved_to_evidence(tmp_path, monkeypatch):
emit=lambda **event: events.append(event),
)
assert result["status"] == "STALE_MOVED"
assert not address.exists()
assert result["status"] == "UNREACHABLE"
assert address.exists()
moved = list((tmp_path / "evidence" / "diagnostics" / "cdbsvr").glob("sAddress.adr.stale-*"))
assert len(moved) == 1
assert moved[0].read_text(encoding="ascii") == "guid\n127.0.0.1\n10062\n1094\n"
assert events[-1]["stage"] == "icdb_address_stale"
assert len(moved) == 0
assert address.read_text(encoding="ascii") == "guid\n127.0.0.1\n10062\n1094\n"
assert events[-1]["stage"] == "icdb_address_check"
def test_live_icdb_address_is_left_in_place(tmp_path, monkeypatch):
+236
View File
@@ -0,0 +1,236 @@
"""Regression cases for the PCB/iCDB emergency shutdown defects.
Native Mentor boundaries are replaced; no production library is opened.
"""
from pathlib import Path
from types import SimpleNamespace
import pytest
from cbb_refresh_verify import mentor_adapter as adapter
from cbb_refresh_verify.verify_runner import VerifyResult, run_batch
from test_verify_worker_stability import exercise_worker
from test_dialog_rules import prompt, ASSETS
from cbb_refresh_verify.dialog_rules import decide, load_rules
def test_network_timeout_cannot_remove_database_advertisement(tmp_path, monkeypatch):
address = tmp_path / 'database/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
original = b'guid\n192.168.1.10\n10062\n1094\n'
address.write_bytes(original)
monkeypatch.setattr(adapter, 'probe_icdb_server', lambda *a: (False, 'timeout'))
result = adapter.prepare_icdb_address(tmp_path / 'database', tmp_path / 'evidence')
assert address.exists(), 'A timeout is not proof the database owner is dead'
assert address.read_bytes() == original
assert result['status'] == 'UNREACHABLE'
@pytest.mark.parametrize('state', ['LIVE', 'UNREACHABLE', 'INVALID'])
def test_existing_database_owner_blocks_before_pcb_launch(tmp_path, monkeypatch, state):
job, events, execute = exercise_worker(tmp_path, monkeypatch)
monkeypatch.setattr(adapter, 'prepare_icdb_address', lambda *a, **k: {'status': state})
with pytest.raises(RuntimeError, match='ICDB_SESSION_UNCONFIRMED'):
execute()
assert not any(e['stage'] == 'pcb_launch' for e in events)
@pytest.mark.parametrize('text', [
'Continue to open the design with read/write access permission?',
'Confirm that no other users have the design open',
'Database restoration: last user saved database',
])
def test_database_recovery_requires_manual_review_without_click(text):
decision = decide(prompt(text), load_rules(ASSETS / 'dialog_rules.v1.json'))
assert decision.error_code == 'DATABASE_RECOVERY_REQUIRED'
assert not decision.action
def test_unsafe_result_stops_batch_even_when_reported_pass():
calls = []
def verify(item):
calls.append(item)
return VerifyResult('PASS', safe_to_continue=False)
results = run_batch(['A', 'B'], verifier=verify)
assert calls == ['A']
assert results[1].status == 'SKIPPED'
def test_cleanup_does_not_force_terminate_native_database_owner(monkeypatch):
killed = []
monkeypatch.setattr(adapter, '_terminate_pid', lambda pid, **k: killed.append(pid))
monkeypatch.setattr(adapter, '_process_details', lambda name:
[(22, 'ExpeditionPCB.exe', 'pcb', 11)] if name == 'ExpeditionPCB.exe' else [])
events = []
result = adapter.cleanup_verify_processes(None, 22, 11, emit=lambda **e: events.append(e))
assert killed == []
assert result['safe_to_continue'] is False
assert result['remaining_pids'] == [22]
assert any(e['stage'] == 'process_retained' for e in events)
def test_cleanup_enumeration_failure_cannot_confirm_release(monkeypatch):
def fail(name):
raise OSError('access denied')
monkeypatch.setattr(adapter, '_process_details', fail)
result = adapter.cleanup_verify_processes(None, 22)
assert result['safe_to_continue'] is False
def test_python_com_references_are_released_before_save_helper(tmp_path, monkeypatch):
import weakref
job, events, execute = exercise_worker(tmp_path, monkeypatch)
references = []
class ComObject:
pass
def attach(*a, **k):
objects = tuple(ComObject() for _ in range(3))
references.extend(weakref.ref(obj) for obj in objects)
return objects
monkeypatch.setattr('cbb_refresh_verify.pcb_bridge.wait_for_target_document', attach)
original = adapter.subprocess.Popen
def helper(*a, **k):
assert all(ref() is None for ref in references), 'Python still owns PCB COM references'
return original(*a, **k)
monkeypatch.setattr(adapter.subprocess, 'Popen', helper)
assert execute()['status'] == 'PASS'
def test_desktop_abort_does_not_kill_native_process_tree(monkeypatch):
from cbb_refresh_verify import desktop_worker as desktop
worker = desktop.DesktopWorker.__new__(desktop.DesktopWorker)
worker.job_bound = True
worker.job = object()
worker.handle = object()
worker.pid = 101
worker.companions = []
terminated = []
job_kills = []
monkeypatch.setattr(desktop.win32job, 'TerminateJobObject', lambda *a: job_kills.append(a))
monkeypatch.setattr(desktop.win32process, 'TerminateProcess', lambda h, code: terminated.append(h))
monkeypatch.setattr(adapter, '_process_details', lambda name: [])
worker.kill()
assert job_kills == [], 'Terminating the job interrupts PCB and cdbsvr writes'
assert worker.handle in terminated
def test_saved_pcb_with_retained_icdb_address_cannot_pass(tmp_path, monkeypatch):
job, events, execute = exercise_worker(tmp_path, monkeypatch)
original = adapter.subprocess.Popen
def helper(*a, **k):
address = Path(job['project']).parent / 'database/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_text('still owned', encoding='ascii')
return original(*a, **k)
monkeypatch.setattr(adapter.subprocess, 'Popen', helper)
with pytest.raises(RuntimeError, match='ICDB_RELEASE_UNCONFIRMED'):
execute()
assert not any(e['stage'] == 'complete' for e in events)
def test_retained_pcb_after_close_cannot_pass_or_be_killed(tmp_path, monkeypatch):
from itertools import count
job, events, execute = exercise_worker(tmp_path, monkeypatch)
calls = count()
monkeypatch.setattr(adapter, 'pcb_processes', lambda:
() if next(calls) == 0 else ((2, 'ExpeditionPCB.exe', 'pcb'),))
clock = count(step=40)
monkeypatch.setattr(adapter.time, 'monotonic', lambda: next(clock))
with pytest.raises(RuntimeError, match='PCB_RELEASE_UNCONFIRMED'):
execute()
assert not any(e['stage'] == 'complete' for e in events)
def test_library_manager_close_does_not_force_kill_database_owner():
from cbb_refresh_verify.library_manager_verify import LibraryVerifySession
killed = []
def wait(**kw):
import subprocess
raise subprocess.TimeoutExpired('LibraryManager', 5)
process = SimpleNamespace(poll=lambda: None, wait=wait,
terminate=lambda: killed.append('terminate'),
kill=lambda: killed.append('kill'))
session = LibraryVerifySession(SimpleNamespace(close=lambda: None), process, 1, Path('lib.lmc'), 'CBB')
session.close()
assert killed == []
def test_supervisor_rejects_pass_when_native_release_is_unconfirmed(tmp_path, monkeypatch):
import json
from test_verify_runner import fixture, request, PORTS_OK
from cbb_refresh_verify.verify_runner import run_verify
fixture(tmp_path)
class Worker:
desktop = None
returncode = 0
def __init__(self, command, *_a, **_k):
root = Path(command[-1]).parent
(root / 'outcome.json').write_text('{"status":"PASS"}', encoding='utf-8')
(root / 'backup/CBB').mkdir(parents=True)
(root / 'backup/CBB/original.bin').write_bytes(b'original')
def poll(self): return 0
def close(self): pass
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
monkeypatch.setattr('cbb_refresh_verify.verify_runner._cleanup_session_processes',
lambda *a, **k: {'safe_to_continue': False, 'remaining_pids': [42]})
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *a: None)
bridge_calls = []
result = run_verify(request(tmp_path), port_check=PORTS_OK,
flag_reader=lambda *a: bridge_calls.append(a))
assert result.status == 'FAIL'
assert not result.safe_to_continue
assert bridge_calls == []
root = result.evidence_path.parent
assert (root / 'backup/CBB/original.bin').read_bytes() == b'original'
recovery = json.loads((root / 'recovery-required.json').read_text(encoding='utf-8'))
assert recovery['release']['remaining_pids'] == [42]
assert recovery['desktop'].startswith('CbbVerify_')
def test_existing_pcb_session_blocks_before_mutating_project(tmp_path, monkeypatch):
job, events, execute = exercise_worker(tmp_path, monkeypatch)
monkeypatch.setattr(adapter, 'pcb_processes', lambda: ((20, 'ExpeditionPCB.exe', 'user design'),))
with pytest.raises(RuntimeError, match='PCB_SESSION_ACTIVE'):
execute()
assert not events
def test_real_windows_job_abort_preserves_native_like_child(tmp_path):
"""Exercise real Win32 job/handle semantics using harmless Python processes."""
import sys
import time
import uuid
import win32api
import win32con
import win32process
from cbb_refresh_verify.desktop_worker import DesktopWorker
script = tmp_path / 'parent.py'
pid_path = tmp_path / 'child.pid'
script.write_text(
'import subprocess, sys, time\nfrom pathlib import Path\n'
'child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])\n'
f'Path({str(pid_path)!r}).write_text(str(child.pid))\n'
'time.sleep(30)\n', encoding='utf-8')
worker = DesktopWorker([sys.executable, str(script)], 'CbbSafetyTest_' + uuid.uuid4().hex[:8])
child_handle = None
closed = False
try:
deadline = time.monotonic() + 10
while not pid_path.exists() and time.monotonic() < deadline:
time.sleep(.05)
assert pid_path.exists(), 'Harmless child process failed to start'
child_handle = win32api.OpenProcess(
win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_TERMINATE, False,
int(pid_path.read_text()))
worker.kill()
worker.wait()
worker.close()
closed = True
assert win32process.GetExitCodeProcess(child_handle) == 259
finally:
if not closed:
worker.kill()
worker.close()
if child_handle is not None:
win32process.TerminateProcess(child_handle, 0)
child_handle.Close()
+13 -9
View File
@@ -32,13 +32,13 @@ class FakeProjectIntegration:
return True
def test_database_restoration_dialog_selects_last_saved_database():
def test_database_restoration_dialog_requires_manual_recovery():
action = choose_dialog_action(
'Database Restoration',
['Restore Database', 'Load the last user saved database dated 2026/9/3 19:32.',
'Load the autosave database dated 2026/9/3 19:32.', 'OK', 'Cancel'],
)
assert action == 'restore_last_saved'
assert action is None
def test_library_manager_fresh_pid_filter_rejects_stale_sessions():
@@ -77,14 +77,16 @@ def test_interactive_verify_focuses_library_manager_before_real_right_click():
assert calls == ['focus', 'select', ('click', 'right')]
def test_cleanup_verify_processes_terminates_worker_parent_and_lm(monkeypatch):
def test_cleanup_verify_processes_confirms_absent_worker_parent_and_lm(monkeypatch):
from cbb_refresh_verify import mentor_adapter
terminated = []
monkeypatch.setattr(mentor_adapter, '_terminate_pid',
lambda pid, **_kwargs: terminated.append(int(pid)))
cleanup_verify_processes(101, 202, 303, emit=lambda **event: None)
assert terminated == [202, 303, 101]
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _name: ())
result = cleanup_verify_processes(101, 202, 303, emit=lambda **event: None)
assert terminated == []
assert result['safe_to_continue']
def test_cleanup_verify_processes_discovers_unbound_target_pcb_processes(monkeypatch):
@@ -106,7 +108,7 @@ def test_cleanup_verify_processes_discovers_unbound_target_pcb_processes(monkeyp
monkeypatch.setattr(mentor_adapter, '_terminate_pid',
lambda pid, **_kwargs: terminated.append(int(pid)))
mentor_adapter.cleanup_verify_processes(
result = mentor_adapter.cleanup_verify_processes(
101,
None,
None,
@@ -115,7 +117,9 @@ def test_cleanup_verify_processes_discovers_unbound_target_pcb_processes(monkeyp
emit=lambda **event: None,
)
assert terminated == [202, 303, 204, 101]
assert terminated == []
assert result['remaining_pids'] == [202, 204, 303]
assert not result['safe_to_continue']
def test_verify_cleanup_is_present_on_all_exit_paths():
@@ -279,11 +283,11 @@ def test_refresh_integration_never_accepts_initial_green_when_refresh_fails(fail
assert 'SynchCES' not in pi.actions
def test_refresh_integration_attempts_disabled_green_action_once():
def test_refresh_integration_skips_native_disabled_green_action():
pi = GreenProjectIntegration()
pi.IsForwardAnnotationAllowed = False
refresh_integration(pi, settle_seconds=0)
assert pi.actions == ['ForwardAnnotate']
assert pi.actions == []
def test_refresh_integration_never_counts_rejected_green_action_as_completed():
+2 -2
View File
@@ -89,7 +89,7 @@ def test_dialog_handling_only_posts_button_clicks():
text = (SOURCE_ROOT/'mentor_adapter.py').read_text(encoding='utf-8')
assert 'BM_CLICK' in text
# The only posted messages are the documented dialog button clicks.
assert text.count('PostMessage') == 1
assert 'win32con.WM_CLOSE' in text
def test_desktop_worker_close_kills_unbound_worker_tree():
@@ -108,5 +108,5 @@ def test_verification_never_deletes_or_moves_library_files():
assert 'shutil.rmtree(backup)' in adapter
# The only library-side mutation is quarantining the volatile, unreachable
# cdbsvr address advertisement; stable CBB content remains untouched.
assert adapter.count('shutil.move') == 1
assert 'shutil.move' not in adapter
assert "sAddress.adr" in adapter
+11 -11
View File
@@ -212,12 +212,12 @@ def test_preflight_uses_project_pcb_reference_not_block_name(tmp_path):
assert preflight(request(tmp_path)) == (work/'CBB1.prj', work/'PCB'/'actual.pcb')
def test_preflight_preserves_mapped_drive_without_resolve(tmp_path, monkeypatch):
def test_preflight_uses_canonical_paths_for_safety_but_preserves_mentor_path(tmp_path, monkeypatch):
work = fixture(tmp_path)
monkeypatch.setattr(
Path,
'resolve',
lambda self: pytest.fail(f'preflight must preserve mapped drive: {self}'),
lambda self: Path(str(self).replace(str(tmp_path), str(tmp_path/'canonical-share'))),
)
assert preflight(request(tmp_path)) == (work/'CBB1.prj', work/'PCB'/'actual.pcb')
@@ -458,18 +458,18 @@ def test_batch_continues_past_item_failure_and_logs_all_items(tmp_path):
assert [r.status for r in results] == ['BLOCKED','FAIL','PASS']
def test_batch_does_not_stop_for_timeout_failure(tmp_path):
def test_batch_stops_for_unsafe_timeout_failure(tmp_path):
calls = []
outcomes = [VerifyResult('TIMEOUT', stderr='PCB remains open', safe_to_continue=False), VerifyResult('PASS')]
def verify(req):
calls.append(req.block_name)
return outcomes.pop(0)
results = run_batch([request(tmp_path, n) for n in ['A','B']], verifier=verify)
assert calls == ['A','B']
assert [r.status for r in results] == ['TIMEOUT','PASS']
assert calls == ['A']
assert [r.status for r in results] == ['TIMEOUT','SKIPPED']
def test_batch_continues_when_verifier_raises(tmp_path):
def test_batch_stops_when_verifier_raises(tmp_path):
calls = []
def verify(req):
@@ -479,10 +479,10 @@ def test_batch_continues_when_verifier_raises(tmp_path):
return VerifyResult('PASS')
results = run_batch([request(tmp_path, n) for n in ['A', 'B']], verifier=verify)
assert calls == ['A', 'B']
assert calls == ['A']
assert results[0].status == 'FAIL'
assert 'unexpected worker error' in results[0].stderr
assert results[1].status == 'PASS'
assert results[1].status == 'SKIPPED'
def test_batch_cancel_between_items(tmp_path):
@@ -499,7 +499,7 @@ def test_parallelism_rejected_for_shared_library(tmp_path):
run_batch([], max_workers=2)
def test_timeout_terminates_worker_job_before_next_item(tmp_path, monkeypatch):
def test_timeout_stops_automation_and_blocks_next_item(tmp_path, monkeypatch):
"""A timed-out item must not leave a Mentor process holding the library."""
fixture(tmp_path)
killed = []
@@ -521,7 +521,7 @@ def test_timeout_terminates_worker_job_before_next_item(tmp_path, monkeypatch):
assert result.status == 'TIMEOUT'
assert killed == [True]
assert result.safe_to_continue
assert not result.safe_to_continue
def test_fatal_dialog_terminates_current_worker_and_cannot_become_pass(tmp_path, monkeypatch):
@@ -1013,7 +1013,7 @@ def test_saved_closed_without_cert_uses_bridge_and_never_reexecutes_verify(
def close(self): ordering.append('worker_close')
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker',FinishedWorker)
monkeypatch.setattr('cbb_refresh_verify.verify_runner._cleanup_session_processes',
lambda *a,**kw: ordering.append('cleanup'))
lambda *a,**kw: (ordering.append('cleanup') or {'safe_to_continue': True}))
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout',
lambda *_: ordering.append('failure_logs'))
waits=[]
+1 -1
View File
@@ -26,7 +26,7 @@ def exercise_worker(tmp_path, monkeypatch, *, integration_error=None):
monkeypatch.setattr(adapter, 'launch_pcb_process', lambda *a: SimpleNamespace(pid=1))
monkeypatch.setattr(adapter, '_process_details', lambda _: ())
monkeypatch.setattr(adapter, 'select_reusable_circuit_worker', lambda *a, **kw: (2,'pcb','command',1))
monkeypatch.setattr(adapter, 'cleanup_verify_processes', lambda *a, **kw: None)
monkeypatch.setattr(adapter, 'cleanup_verify_processes', lambda *a, **kw: {'safe_to_continue': True, 'remaining_pids': []})
monkeypatch.setattr('cbb_refresh_verify.pcb_bridge.wait_for_target_document',
lambda *a, **kw: (None, None, object()))
def integration(*args, **kwargs):