fix: continue released verify batches and bound automation shutdown

This commit is contained in:
阿白叔 committed 2026-11-04 20:51:35 +08:00
1 parent 477a5a46e3
commit 00db1cf5f2
23 files changed
+550 -115

No files matched your search

+1 -1
View File
@@ -69,7 +69,7 @@ def test_crashed_worker_cannot_pass_even_with_pass_file(tmp_path, monkeypatch, o
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
assert result.safe_to_continue is True # Proven release permits another item; crash stays FAIL.
def test_supervisor_crash_stops_registered_save_helper_but_not_native(tmp_path):
+4
View File
@@ -144,6 +144,10 @@ def test_idle_guard_queries_supported_native_process_names(recovery_files, monke
queries.append(query)
return []
monkeypatch.setattr(win32com.client, 'GetObject', lambda _: EmptyProcesses())
from cbb_refresh_verify import owner_probe
import subprocess
monkeypatch.setattr(owner_probe.subprocess, 'run', lambda command, **kw:
subprocess.CompletedProcess(command, owner_probe.owner_probe_main(command[-1])))
_idle_check(request.lmc_file, original, original.parent/'PCB/A.pcb')
assert any("Name='viewdraw.exe'" in query for query in queries)
+243
View File
@@ -0,0 +1,243 @@
"""Only live clients stop a batch; native writes are replaced by fixtures."""
import json
from pathlib import Path
from threading import Event
import pytest
from cbb_refresh_verify import verify_runner as runner
from test_verify_runner import fixture, request, PORTS_OK
@pytest.mark.parametrize('status,detail', [('FAIL', 'UNKNOWN_DIALOG: native prompt'),
('TIMEOUT', 'native operation timed out')])
@pytest.mark.parametrize('released', [True, False])
def test_batch_continuation_follows_actual_release(tmp_path, monkeypatch, status, detail, released):
fixture(tmp_path)
launches = []
class Worker:
desktop = None
returncode = 1
def __init__(self, command, *_a, **_k):
launches.append(command)
Path(command[-1]).with_name('outcome.json').write_text(json.dumps({
'status': status, 'stderr': detail, 'safe_to_continue': False}))
def poll(self): return 1
def close(self): pass
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k:
{'safe_to_continue': released, 'remaining_pids': [] if released else [123]})
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *_: None)
req = request(tmp_path)
try:
results = runner.run_batch([req, req], verifier=lambda r: runner.run_verify(r, port_check=PORTS_OK))
assert results[0].status == status and results[0].safe_to_continue is released
assert len(launches) == (2 if released else 1)
assert results[1].status == (status if released else 'SKIPPED')
finally:
from cbb_refresh_verify import library_lock as locks
with locks._guard:
owner = locks._owners.pop(locks.LibraryLock(req.lmc_file).key, None)
if owner: owner['handle'].Close()
def test_stop_worker_escalates_only_after_cooperative_deadline():
calls = []
class Worker:
stopped = False
def request_stop(self): calls.append('cancel')
def wait(self, timeout=5):
calls.append('wait')
if not self.stopped: raise TimeoutError()
def kill(self): calls.append('client_stop'); self.stopped = True
def poll(self): return 1 if self.stopped else None
assert runner._stop_worker(Worker(), timeout=.1) is True
assert calls == ['cancel', 'wait', 'client_stop', 'wait']
def test_cancel_reaches_current_supervised_worker(tmp_path, monkeypatch):
fixture(tmp_path)
stop = Event()
cancelled = []
class Worker:
desktop = None
returncode = None
def __init__(self, command, *_a, **_k):
self.job = json.loads(Path(command[-1]).read_text('utf-8'))
stop.set()
def bind_cancellation(self, path): self.cancel = Path(path)
def request_stop(self):
self.cancel.touch(); cancelled.append(self.cancel)
self.returncode = 1
def wait(self, **_k): return 1
def poll(self): return self.returncode
def close(self): pass
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k: {'safe_to_continue': True})
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *_: None)
result = runner.run_verify(request(tmp_path), stop=stop, port_check=PORTS_OK)
assert result.status == 'CANCELLED' and result.safe_to_continue
assert len(cancelled) == 1 and cancelled[0].is_file()
@pytest.mark.parametrize('text,expected', [
('content checking completed successfully! 0 errors, 0 warnings', 'PASS'),
('content checking completed successfully! 10 errors', 'FAIL'),
('content checking completed successfully! error: missing symbol', 'FAIL'),
('content checking completed successfully! 0 errors\nERROR: cannot connect', 'FAIL'),
])
def test_zero_error_count_does_not_block_content_check(text, expected):
assert runner.classify_output(0, text) == expected
@pytest.mark.parametrize('codec', ['utf-16', 'utf-8-sig', 'mbcs'])
def test_preflight_reads_native_project_encodings(tmp_path, codec):
work = fixture(tmp_path)
(work/'CBB1.prj').write_bytes(('# 中文工程\nKEY PCBDesignPath "PCB\\actual.pcb"\n').encode(codec))
project, pcb = runner.preflight(request(tmp_path))
assert pcb == work/'PCB/actual.pcb'
def test_unrelated_pcb_does_not_block_target_before_launch(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)
monkeypatch.setattr(adapter, 'pcb_processes', lambda: ((999, 'ExpeditionPCB.exe', '"ExpeditionPCB.exe" "C:\\other\\board.pcb"'),))
assert execute()['status'] == 'PASS'
assert any(e['stage'] == 'pcb_launch' for e in events)
def test_sampling_ports_only_warn_by_default(tmp_path, monkeypatch):
fixture(tmp_path)
launches, warnings = [], []
class Worker:
desktop = None
returncode = 0
def __init__(self, command, *_a, **_k):
launches.append(command)
Path(command[-1]).with_name('outcome.json').write_text('{"status":"PASS"}')
def poll(self): return 0
def close(self): pass
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k: {'safe_to_continue': True})
result = runner.run_verify(request(tmp_path), port_check=lambda: (False, 'sample unavailable'),
flag_reader=lambda *_: __import__('cbb_refresh_verify.status_bridge', fromlist=['BridgeResult']).BridgeResult('READY', 'IsVerifiedReuseBlock', 1),
progress=warnings.append)
assert launches and result.status == 'PASS'
assert any(e['stage'] == 'port_warning' for e in warnings)
def test_cleanup_includes_late_native_descendant_without_pcb_argument(monkeypatch):
from cbb_refresh_verify import mentor_adapter as adapter
rows = [(10, 'ExpeditionPCB.exe', '', 1), (11, 'ExpeditionPCB.exe', '', 10),
(99, 'ExpeditionPCB.exe', '', 77)]
monkeypatch.setattr(adapter, '_process_details', lambda name: rows if name == 'ExpeditionPCB.exe' else [])
result = adapter.cleanup_verify_processes(None, None, 10, baseline_pids={99})
assert not result['safe_to_continue'] and result['remaining_pids'] == [10, 11]
def test_save_client_without_worker_still_prevents_continuation(tmp_path, monkeypatch):
fixture(tmp_path)
class Worker:
desktop = None
returncode = 1
def __init__(self, command, *_a, **_k):
Path(command[-1]).with_name('outcome.json').write_text('{"status":"FAIL"}')
def poll(self): return 1
def close(self): pass
def automation_release_state(self): return {'safe_to_continue': False, 'remaining_pids': [333]}
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', Worker)
monkeypatch.setattr(runner, '_cleanup_session_processes', lambda *a, **k: {'safe_to_continue': True})
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', lambda *_: None)
req = request(tmp_path)
try:
result = runner.run_verify(req, port_check=PORTS_OK)
assert not result.safe_to_continue
proof = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8'))
assert proof['worker_exited'] is True
assert proof['automation_release']['remaining_pids'] == [333]
assert proof['remaining_pids'] == [333]
finally:
from cbb_refresh_verify import library_lock as locks
with locks._guard:
owner = locks._owners.pop(locks.LibraryLock(req.lmc_file).key, None)
if owner: owner['handle'].Close()
def test_closed_desktop_worker_keeps_exit_status_without_using_closed_handle(monkeypatch):
from types import SimpleNamespace
from cbb_refresh_verify import desktop_worker as desktop
worker = desktop.DesktopWorker.__new__(desktop.DesktopWorker)
handle = SimpleNamespace(closed=False)
def close(): handle.closed = True
handle.Close = close
worker.handle = handle
worker.job = SimpleNamespace(Close=lambda: None)
worker.desktop = None; worker.companions = []; worker.companion_pids = []
def code(h):
assert not h.closed, 'Read from a closed Win32 process handle'
return 1
monkeypatch.setattr(desktop.win32process, 'GetExitCodeProcess', code)
worker.close()
assert worker.poll() == 1
worker.close() # Idempotent cleanup.
def test_native_process_queries_use_bounded_shared_helper(monkeypatch):
from cbb_refresh_verify import mentor_adapter as adapter
calls = []
def query(names):
calls.append(names)
return [{'pid': 12, 'executable': 'ExpeditionPCB.exe', 'command': 'native', 'parent': 11}]
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', query)
assert adapter._process_details('ExpeditionPCB.exe') == [(12, 'ExpeditionPCB.exe', 'native', 11)]
assert calls == [('ExpeditionPCB.exe',)]
@pytest.mark.parametrize('script', ['save_verified_block.vbs', 'close_failed_block.vbs'])
def test_save_and_failure_close_clients_are_both_tracked(script, monkeypatch):
from cbb_refresh_verify import desktop_worker as desktop
worker = desktop.DesktopWorker.__new__(desktop.DesktopWorker)
worker.pid = 11; worker._closed = True; worker._exit_code = 1
command = f'cscript.exe //nologo "{Path(desktop.__file__).with_name(script)}" "C:\\fixture\\design.prj"'
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_a, **_k: [
{'pid': 22, 'parent': 11, 'command': command},
{'pid': 33, 'parent': 99, 'command': command},
{'pid': 44, 'parent': 11, 'command': 'cscript.exe unrelated.vbs'}])
proof = worker.automation_release_state()
assert proof['safe_to_continue'] is False and proof['remaining_pids'] == [22]
def test_watchdog_with_cancel_signal_stops_clients_after_supervisor_exit(tmp_path):
import subprocess, sys, time
import win32api, win32con, win32process
supervisor = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])
script = tmp_path/'watchdog.py'; ready = tmp_path/'ready.json'; cancel = tmp_path/'cancel.signal'
script.write_text(
'import sys, subprocess, 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}, stop_clients=True)\n'
'native = subprocess.Popen([sys.executable,"-c","import time; time.sleep(30)"])\n'
'client = launch_save_helper([sys.executable,"-c","import time; time.sleep(30)"])\n'
f'Path({str(ready)!r}).write_text(json.dumps([native.pid,client.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()+10
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, False, pid))
supervisor.terminate(); supervisor.wait(5)
assert worker.wait(10) == 75 and cancel.is_file()
assert win32process.GetExitCodeProcess(handles[0]) == 259
assert win32process.GetExitCodeProcess(handles[1]) != 259
finally:
for p in (supervisor, worker):
if p.poll() is None: p.terminate()
p.wait(5)
for h in handles:
if win32process.GetExitCodeProcess(h) == 259: win32process.TerminateProcess(h, 0)
h.Close()
+23
View File
@@ -172,3 +172,26 @@ def test_authoritative_status_map_never_reuses_previous_scan_status(tmp_path, mo
assert first == {'A': 'PENDING'}
assert second == {'A': 'READY'}
assert calls == ['A', 'A']
def test_retry_rechecks_failed_scan_without_library_changes(tmp_path):
lmc = tmp_path/'library.lmc'; lmc.write_bytes(b'library')
checkpoint = tmp_path/'scan.jsonl'
first = BatchStatusSession(FakeBridge(timeout_name='A')).scan(['A', 'B'], lmc, checkpoint)
assert first[0].status == 'TIMEOUT'
bridge = FakeBridge()
second = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint)
assert bridge.requests == ['A']
assert second[0].status == 'READY'
def test_missing_x86_runtime_does_not_restart_for_every_cbb(tmp_path):
class BrokenBridge(FakeBridge):
def query(self, library, name, **kwargs):
self.requests.append(name)
raise BridgeResponseError('状态桥进程失败: -1073741515')
lmc = tmp_path/'library.lmc'; lmc.write_bytes(b'library')
bridge = BrokenBridge()
result = BatchStatusSession(bridge).scan(['A', 'B', 'C'], lmc, tmp_path/'scan.jsonl')
assert bridge.requests == ['A']
assert [row.status for row in result] == ['UNAVAILABLE'] * 3
+11 -11
View File
@@ -200,14 +200,14 @@ def test_worker_attempts_normal_close_after_idle_integration_failure(tmp_path, m
assert not any(event['stage'] == 'save_start' for event in events)
def test_stop_requests_cooperative_cancel_without_terminating_busy_client(tmp_path):
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']
assert calls == ['cancel', 'kill']
def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path):
@@ -225,21 +225,22 @@ def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path):
assert marker.is_file()
def test_shared_symbol_database_owner_blocks_content_check_and_pcb(tmp_path, monkeypatch):
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')
outcome = runner.run_verify(req, process_runner=lambda *args: pytest.fail('must not launch importer'))
assert outcome.status == 'BLOCKED'
assert outcome.safe_to_continue is False
assert '__ReusableBlocksSymb' in outcome.stderr
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_symbol_database_must_be_released_before_pass(tmp_path, monkeypatch):
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)
@@ -250,9 +251,8 @@ def test_shared_symbol_database_must_be_released_before_pass(tmp_path, monkeypat
address.write_bytes(b'shared owner retained')
return original(*args, **kwargs)
monkeypatch.setattr(adapter.subprocess, 'Popen', helper)
with pytest.raises(RuntimeError, match='ICDB_RELEASE_UNCONFIRMED'):
execute()
assert not any(event['stage'] == 'complete' for event in events)
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):
+1 -1
View File
@@ -303,7 +303,7 @@ def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, mon
monkeypatch.setattr('cbb_refresh_verify.verify_diagnostics.capture_failure_logs_with_timeout', failure_logs_main)
result = runner.run_verify(request(tmp_path), port_check=lambda: (True, ''))
assert result.error_category == 'ICDB_REPAIR_REQUIRED'
assert result.safe_to_continue is False
assert result.safe_to_continue is True
assert 'opening failed' in result.stderr
assert '200091-CBB' in result.stderr
assert '__ReusableBlocksSymb' in result.stderr
+8 -9
View File
@@ -27,12 +27,11 @@ def test_network_timeout_cannot_remove_database_advertisement(tmp_path, monkeypa
@pytest.mark.parametrize('state', ['LIVE', 'UNREACHABLE', 'INVALID'])
def test_existing_database_owner_blocks_before_pcb_launch(tmp_path, monkeypatch, state):
def test_address_probe_result_is_not_a_substitute_for_native_verify(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)
assert execute()['status'] == 'PASS'
assert any(e['stage'] == 'pcb_launch' for e in events)
@pytest.mark.parametrize('text', [
@@ -114,7 +113,7 @@ def test_desktop_abort_does_not_kill_native_process_tree(monkeypatch):
assert worker.handle in terminated
def test_saved_pcb_with_retained_icdb_address_cannot_pass(tmp_path, monkeypatch):
def test_saved_pcb_with_address_records_remains_an_execution_result_for_bridge_validation(tmp_path, monkeypatch):
job, events, execute = exercise_worker(tmp_path, monkeypatch)
original = adapter.subprocess.Popen
def helper(*a, **k):
@@ -123,9 +122,8 @@ def test_saved_pcb_with_retained_icdb_address_cannot_pass(tmp_path, monkeypatch)
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)
assert execute()['status'] == 'PASS'
assert any(e['stage'] == 'icdb_address_remaining' for e in events)
def test_retained_pcb_after_close_cannot_pass_or_be_killed(tmp_path, monkeypatch):
@@ -189,7 +187,8 @@ def test_supervisor_rejects_pass_when_native_release_is_unconfirmed(tmp_path, mo
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'),))
monkeypatch.setattr(adapter, 'pcb_processes', lambda:
((20, 'ExpeditionPCB.exe', f'ExpeditionPCB.exe "{job["pcb"]}"'),))
with pytest.raises(RuntimeError, match='PCB_SESSION_ACTIVE'):
execute()
assert not events
+2 -2
View File
@@ -71,8 +71,8 @@ def test_repair_finishes_without_calling_verify(case, monkeypatch):
assert result.recovery_attempts[0]['validation_passed'] is False
@pytest.mark.parametrize('stage,expected_safe', [('PCB_STARTING', True), ('back_annotation', False)])
def test_only_released_startup_failure_can_continue_from_icdb_diagnosis(tmp_path, monkeypatch, stage, expected_safe):
@pytest.mark.parametrize('stage,expected_safe', [('PCB_STARTING', True), ('back_annotation', True)])
def test_released_failure_can_continue_from_icdb_diagnosis(tmp_path, monkeypatch, stage, expected_safe):
import json
from cbb_refresh_verify import verify_runner as runner
library = tmp_path/'library.lmc'; library.touch()
+5 -4
View File
@@ -27,7 +27,7 @@ def test_native_inspection_holds_lock_without_opening_pcb(case, monkeypatch, old
result = runner.run_verify(request)
assert result.status == 'CHECKED' and result.recovery_attempts == ()
assert result.library_flag == 'UNKNOWN'
assert result.safe_to_continue is (not old_address)
assert result.safe_to_continue is True
@pytest.mark.parametrize('fault', ['missing', 'generic', 'assertion', 'wrong_database', 'stale_verdict', 'not_exited'])
@@ -50,7 +50,7 @@ def test_unconfirmed_native_inspection_never_repairs(case, monkeypatch, fault):
assert result.status == 'BLOCKED' and not result.recovery_attempts
def test_native_fault_repairs_once_then_full_verification_with_old_address(case, monkeypatch):
def test_native_fault_repairs_once_without_running_separate_verification(case, monkeypatch):
from cbb_refresh_verify import verify_runner as runner, native_repair
from test_native_repair import complete_native_success
request, project, address = case
@@ -71,5 +71,6 @@ def test_native_fault_repairs_once_then_full_verification_with_old_address(case,
monkeypatch.setattr(native_repair, 'repair_release_state', lambda req, target, result: result['release'])
monkeypatch.setattr(runner, '_run_verify_serialized', verify)
result = runner.run_verify(request)
assert calls == ['inspect', 'repair', 'verify']
assert result.status == 'PASS' and len(result.recovery_attempts) == 1
assert calls == ['inspect', 'repair']
assert result.status == 'REPAIRED' and len(result.recovery_attempts) == 1
assert result.library_flag == 'UNKNOWN' and not result.recovery_attempts[0]['validation_passed']
+5 -4
View File
@@ -80,19 +80,20 @@ def test_restart_shows_unfinished_without_starting_worker(qtbot, tmp_path):
assert 'Block' in window.output.toPlainText()
def test_persistent_owner_blocker_prevents_native_load_and_offers_checked_release(qtbot, tmp_path, monkeypatch):
def test_historical_record_does_not_prevent_catalog_load_and_offers_checked_release(qtbot, tmp_path, monkeypatch):
import pytest
import cbb_refresh_verify.library_lock as locks
from cbb_refresh_verify.ui.main_window import MainWindow
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
locks.blocker_path(library).write_text('{}', encoding='utf-8')
window = MainWindow(reader=lambda _: pytest.fail('unconfirmed owner reopened'), data_root=tmp_path/'data')
reads = []
window = MainWindow(reader=lambda path: (reads.append(path) or LibraryReadResult(())), data_root=tmp_path/'data')
qtbot.addWidget(window)
window.lmc_edit.setText(str(library)); window.load_library()
qtbot.waitUntil(lambda: not window.busy)
assert window.loaded_path is None
assert window.loaded_path == str(library) and reads
assert window.release_library_button.isEnabled()
assert '释放检查' in window.status_label.text()
assert locks.blocker_path(library).read_text() == '{}'
calls = []
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
monkeypatch.setattr(locks, 'release_retained_library', lambda *a:
+6 -2
View File
@@ -849,18 +849,22 @@ def test_repair_release_uses_real_process_query_contract(tmp_path, monkeypatch,
queried = []
names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'iCDBProjectBackup.exe',
'ReuseBlockImporter.exe', 'cscript.exe')
queries = {"SELECT ProcessId, ParentProcessId, ExecutablePath, CommandLine "
queries = {"SELECT ProcessId,Name,CommandLine,ExecutablePath,ParentProcessId "
f"FROM Win32_Process WHERE Name='{name}'": name for name in names}
def query(wql):
name = queries[wql]
queried.append(name)
return ([SimpleNamespace(ProcessId='456', ParentProcessId='1',
return ([SimpleNamespace(ProcessId='456', ParentProcessId='1', Name=name,
ExecutablePath=f'C:\\Mentor\\{name}', CommandLine=f'{name} target')]
if name == owner else [])
def service(moniker):
assert moniker == 'winmgmts:'
return SimpleNamespace(ExecQuery=query)
monkeypatch.setattr(win32com.client, 'GetObject', service)
from cbb_refresh_verify import owner_probe
import subprocess
monkeypatch.setattr(owner_probe.subprocess, 'run', lambda command, **kw:
subprocess.CompletedProcess(command, owner_probe.owner_probe_main(command[-1])))
# Keep pcb_processes, _processes, _process_details and release validation real.
state = repair_release_state(request, target, complete_native_success(target))
assert 'error' not in state
+14 -4
View File
@@ -8,7 +8,8 @@ from cbb_refresh_verify.runtime_timing import parse_save_progress
@pytest.mark.parametrize('save_ok', [True, False])
def test_packaged_vbs_measures_real_save_call_and_preserves_failure_gate(tmp_path, save_ok):
@pytest.mark.parametrize('other_document', [True, False])
def test_packaged_vbs_measures_real_save_call_and_preserves_failure_gate(tmp_path, save_ok, other_document):
# Execute the real helper in its target 32-bit host. Only external COM
# object creation is replaced; Save/Validate/Close order and timers are real.
script = Path(__file__).parents[1] / 'src/cbb_refresh_verify/save_verified_block.vbs'
@@ -39,14 +40,20 @@ Class FakeDoc
IsSaved = True
End Function
Public Function Close(saveChanges)
closedDoc = True
Close = True
End Function
End Class
Class FakeApp
Public Property Get ActiveDocument
Set ActiveDocument = New FakeDoc
If closedDoc And Not OTHER_DOCUMENT Then
Set ActiveDocument = Nothing
Else
Set ActiveDocument = New FakeDoc
End If
End Property
Public Sub Quit()
WScript.Echo "TEST_QUIT"
End Sub
End Class
Class FakeLic
@@ -55,7 +62,8 @@ Class FakeLic
End Function
End Class
'''
source = source.replace('Option Explicit', 'Option Explicit\n' + classes.replace('SAVE_RETURN', str(save_ok)))
source = source.replace('Option Explicit', 'Option Explicit\nDim closedDoc\n'
+ classes.replace('SAVE_RETURN', str(save_ok)).replace('OTHER_DOCUMENT', str(other_document)))
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
harness = tmp_path/'save_harness.vbs'
@@ -66,11 +74,13 @@ End Class
parsed = parse_save_progress(completed.stdout)
assert parsed['timings_seconds']['save'] >= .08
if save_ok:
assert completed.returncode == 0, completed.stderr
assert completed.returncode == (10 if other_document else 0), completed.stderr
assert 'SAVE_OK' in parsed['markers']
assert 'CLOSE_OK' in parsed['markers']
assert parsed['timings_seconds']['post_save_check'] >= 0
assert parsed['timings_seconds']['close'] >= 0
assert ('TEST_QUIT' in completed.stdout) is (not other_document)
assert ('APP_RETAINED_OTHER_DOCUMENT' in completed.stdout) is other_document
else:
assert completed.returncode == 4, completed.stderr
assert 'SAVE_OK' not in parsed['markers']
+10 -10
View File
@@ -499,7 +499,7 @@ def test_parallelism_rejected_for_shared_library(tmp_path):
run_batch([], max_workers=2)
def test_timeout_stops_automation_and_blocks_next_item(tmp_path, monkeypatch):
def test_timeout_stops_automation_and_allows_retry_when_no_native_owner_remains(tmp_path, monkeypatch):
"""A timed-out item must not leave a Mentor process holding the library."""
fixture(tmp_path)
killed = []
@@ -508,9 +508,9 @@ def test_timeout_stops_automation_and_blocks_next_item(tmp_path, monkeypatch):
def __init__(self, command, name):
self.name = name
self.desktop = None
def poll(self): return None
def poll(self): return self.returncode
returncode = None
def kill(self): killed.append(True)
def kill(self): killed.append(True); self.returncode = 1
def wait(self, timeout=5): return 0
def close(self): pass
@@ -521,7 +521,7 @@ def test_timeout_stops_automation_and_blocks_next_item(tmp_path, monkeypatch):
assert result.status == 'TIMEOUT'
assert killed == [True]
assert not result.safe_to_continue
assert result.safe_to_continue
def test_fatal_dialog_terminates_current_worker_and_cannot_become_pass(tmp_path, monkeypatch):
@@ -532,8 +532,8 @@ def test_fatal_dialog_terminates_current_worker_and_cannot_become_pass(tmp_path,
desktop = object()
returncode = None
def __init__(self, command, name): pass
def poll(self): return None
def kill(self): killed.append(True)
def poll(self): return self.returncode
def kill(self): killed.append(True); self.returncode = 1
def wait(self, timeout=5): return 1
def close(self): pass
@@ -598,8 +598,8 @@ def test_unknown_dialog_writes_snapshot_before_current_item_fails(tmp_path, monk
companion_pids = [701]
returncode = None
def __init__(self, command, name): self.name = name
def poll(self): return None
def kill(self): killed.append(True)
def poll(self): return self.returncode
def kill(self): killed.append(True); self.returncode = 1
def wait(self, timeout=5): return 1
def close(self): pass
@@ -747,7 +747,7 @@ def test_reserved_design_server_ports_block_the_item_fast(tmp_path):
assert result.evidence_path.is_file()
def test_reserved_design_server_ports_block_by_default_before_worker(tmp_path, monkeypatch):
def test_reserved_design_server_ports_block_only_in_explicit_strict_mode(tmp_path, monkeypatch):
fixture(tmp_path)
class FakeWorker:
def __init__(self, command, name):
@@ -757,7 +757,7 @@ def test_reserved_design_server_ports_block_by_default_before_worker(tmp_path, m
def close(self): pass
import cbb_refresh_verify.desktop_worker as desktop_worker
monkeypatch.setattr(desktop_worker, 'DesktopWorker', FakeWorker)
result = run_verify(request(tmp_path), port_check=lambda: (False, '端口区间被系统保留'),
result = run_verify(request(tmp_path, strict_port_check=True), port_check=lambda: (False, '端口区间被系统保留'),
progress=lambda event: None)
assert result.status == 'BLOCKED'
assert '保留' in result.stderr