fix: preserve native calls on stop and keep status reads observational

This commit is contained in:
阿白叔 committed 2026-11-06 15:42:33 +08:00
1 parent 97a3de20c9
commit 8d3eab1164
19 files changed
+631 -290

No files matched your search

+4 -3
View File
@@ -72,7 +72,7 @@ def test_crashed_worker_cannot_pass_even_with_pass_file(tmp_path, monkeypatch, o
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):
def test_supervisor_crash_preserves_registered_save_caller_and_native(tmp_path):
import subprocess, sys, time
import win32api, win32con, win32process, win32event
supervisor = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])
@@ -98,8 +98,9 @@ def test_supervisor_crash_stops_registered_save_helper_but_not_native(tmp_path):
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
time.sleep(.5)
assert worker.poll() is None
assert win32event.WaitForSingleObject(handles[1], 0) == win32con.WAIT_TIMEOUT
assert win32process.GetExitCodeProcess(handles[0]) == 259
finally:
for process in (supervisor, worker):
+8 -5
View File
@@ -66,8 +66,8 @@ def test_stop_worker_escalates_only_after_cooperative_deadline():
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']
assert runner._stop_worker(Worker(), timeout=.1) is False
assert calls == ['cancel', 'wait']
def test_cancel_reaches_current_supervised_worker(tmp_path, monkeypatch):
@@ -223,7 +223,7 @@ def test_save_and_failure_close_clients_are_both_tracked(script, monkeypatch):
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):
def test_watchdog_with_cancel_signal_retains_callers_after_supervisor_exit(tmp_path):
import subprocess, sys, time
import win32api, win32con, win32process
supervisor = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)'])
@@ -246,9 +246,12 @@ def test_watchdog_with_cancel_signal_stops_clients_after_supervisor_exit(tmp_pat
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()
deadline = time.monotonic()+3
while not cancel.is_file() and time.monotonic()<deadline:
time.sleep(.02)
assert worker.poll() is None and cancel.is_file()
assert win32process.GetExitCodeProcess(handles[0]) == 259
assert win32process.GetExitCodeProcess(handles[1]) != 259
assert win32process.GetExitCodeProcess(handles[1]) == 259
finally:
for p in (supervisor, worker):
if p.poll() is None: p.terminate()
+6 -5
View File
@@ -111,10 +111,12 @@ def test_reader_does_not_create_desktop_before_preparation_finishes(monkeypatch,
@pytest.mark.parametrize('reader', ['read_library_flag', 'read_library_tree_image_map'])
def test_reader_closes_desktop_when_process_launch_fails(monkeypatch, tmp_path, reader):
def test_reader_never_creates_a_desktop_or_process(monkeypatch, tmp_path, reader):
import win32service
import win32process
import cbb_refresh_verify.mentor_adapter as module
from pywinauto import Desktop
monkeypatch.setattr(Desktop, 'windows', lambda *_: [])
closed = []
@@ -133,11 +135,10 @@ def test_reader_closes_desktop_when_process_launch_fails(monkeypatch, tmp_path,
if reader == 'read_library_flag':
flag, detail = module.read_library_flag(tmp_path / 'library.lmc', 'Block')
assert flag == module.FLAG_UNKNOWN
assert 'launch failed' in detail
assert 'Library Manager' in detail
else:
with pytest.raises(RuntimeError, match='launch failed'):
module.read_library_tree_image_map(tmp_path / 'library.lmc', ['Block'])
assert closed == ['desktop']
assert module.read_library_tree_image_map(tmp_path / 'library.lmc', ['Block']) == {'Block': None}
assert closed == []
def test_constructor_releases_private_desktop_when_process_launch_fails(monkeypatch):
+3 -2
View File
@@ -133,7 +133,8 @@ def test_supervisor_loss_stops_automation_but_preserves_native_like_process(tmp_
False, int(ready.read_text()))
supervisor.terminate()
supervisor.wait(5)
assert worker.wait(8) == 75
time.sleep(.5)
assert worker.poll() is None
assert win32process.GetExitCodeProcess(native_handle) == 259
finally:
if supervisor.poll() is None: supervisor.terminate()
@@ -167,7 +168,7 @@ def test_cli_unsafe_batch_preserves_created_drive(tmp_path, monkeypatch):
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)])
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
+14 -9
View File
@@ -120,7 +120,7 @@ End Class
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):
def test_cancel_after_native_save_returns_keeps_save_fact_and_normal_close(tmp_path):
source = Path('src/cbb_refresh_verify/save_verified_block.vbs').read_text('utf-8')
classes = r'''
Class FakePi
@@ -182,9 +182,10 @@ End Class
'//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
assert 'SAVE_OK' in outcome.stdout
assert 'CLOSE_OK' in outcome.stdout
assert 'SAVE_REJECTED' not in outcome.stdout
assert outcome.returncode == 10, outcome.stderr # FakeApp retains another document.
def test_worker_attempts_normal_close_after_idle_integration_failure(tmp_path, monkeypatch):
@@ -200,14 +201,16 @@ 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_cancels_then_stops_automation_client_after_deadline(tmp_path):
def test_stop_cancels_without_killing_pending_native_call(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 stop_automation_clients(self): calls.append('stop-helper')
def poll(self): return None
assert runner._stop_worker(BusyWorker(), timeout=0) is False
assert calls == ['cancel']
def test_status_server_close_allows_eof_cleanup_before_termination(tmp_path):
@@ -255,13 +258,14 @@ def test_shared_address_is_diagnostic_after_successful_native_execution(tmp_path
assert any(event['stage'] == 'icdb_address_remaining' for event in events)
def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path):
@pytest.mark.parametrize('stop_clients', [False, True])
def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path, stop_clients):
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'
f'start_supervisor_watchdog({supervisor.pid},cancel_path={str(cancel)!r},stop_clients={stop_clients!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')
@@ -280,6 +284,7 @@ def test_cooperative_supervisor_loss_keeps_pending_save_helper_alive(tmp_path):
while not cancel.exists() and time.monotonic()<deadline:
time.sleep(.05)
assert cancel.exists()
time.sleep(5.2 if stop_clients else .1)
assert worker.poll() is None
assert win32process.GetExitCodeProcess(handle) == 259
finally:
+2 -2
View File
@@ -323,7 +323,7 @@ def test_status_scan_logs_each_cbb_image_id(caplog, tmp_path):
assert 'name=B image_id=28' in caplog.text
def test_status_scan_keeps_only_missing_cert_or_project_items_pending(tmp_path):
def test_status_scan_without_native_observation_does_not_guess_status(tmp_path):
lmc = tmp_path / 'center.lmc'
lmc.touch()
root = lmc.parent / 'ReusableBlocksLP'
@@ -348,7 +348,7 @@ def test_status_scan_keeps_only_missing_cert_or_project_items_pending(tmp_path):
('READY_CBB', 'IP101GR', 'MISSING_CBB'),
tree_image_reader=lambda _library, _names: {},
)
assert result == {'READY_CBB': 'READY', 'IP101GR': 'PENDING', 'MISSING_CBB': 'PENDING'}
assert result == {'READY_CBB': 'UNKNOWN', 'IP101GR': 'UNKNOWN', 'MISSING_CBB': 'UNKNOWN'}
def test_filesystem_evidence_exposes_multiple_persistent_dimensions(tmp_path):
+78
View File
@@ -0,0 +1,78 @@
from dataclasses import replace
import json
import threading
import pytest
from cbb_refresh_verify import verify_runner as runner
from test_verify_runner import fixture, request
def test_default_batch_verifier_receives_current_stop(monkeypatch, tmp_path):
stop = threading.Event()
received = []
def verify(req, **kw):
received.append(kw.get('stop'))
return runner.VerifyResult('FAIL')
monkeypatch.setattr(runner, 'run_verify', verify)
runner.run_batch([request(tmp_path)], stop=stop)
assert received == [stop]
def test_stopped_helper_save_fact_survives_supervisor_finally(tmp_path, monkeypatch):
fixture(tmp_path)
stop = threading.Event()
class SavingWorker:
desktop = None
pid = None
returncode = None
def __init__(self, command, *_a, **_kw):
self.root = __import__('pathlib').Path(command[-1]).parent
(self.root/'save.log').write_text('SAVE_START\nSAVE_OK\nCLOSE_START\n')
stop.set()
def poll(self): return None
def request_stop(self): pass
def wait(self, timeout): raise TimeoutError('Close pending')
def kill(self): pytest.fail('Stop/finally interrupted native Close')
def stop_automation_clients(self): pytest.fail('Save caller was killed')
def close(self): pass
def automation_release_state(self):
return {'safe_to_continue': False, 'remaining_pids': [42]}
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', SavingWorker)
monkeypatch.setattr(runner, '_cleanup_session_processes',
lambda *a, **kw: {'safe_to_continue': False, 'remaining_pids': []})
result = runner.run_verify(request(tmp_path), stop=stop, port_check=lambda: (True, ''))
assert result.status == 'CANCELLED'
assert result.safe_to_continue is False
assert result.write_outcome['save_state'] == 'COMMITTED'
assert result.write_outcome['close_state'] == 'UNKNOWN'
assert result.write_outcome['helper_state'] == 'RUNNING'
def test_unreleased_library_does_not_cancel_an_independent_library(tmp_path):
first = request(tmp_path)
second = replace(first, lmc_file=tmp_path/'other.lmc')
calls = []
def verify(req):
calls.append(req.lmc_file)
return runner.VerifyResult('TIMEOUT', safe_to_continue=req == second)
stop = threading.Event()
results = runner.run_batch([first, second, first], stop=stop, verifier=verify)
assert calls == [first.lmc_file, second.lmc_file]
assert [r.status for r in results] == ['TIMEOUT', 'TIMEOUT', 'SKIPPED']
assert not stop.is_set()
def test_contradictory_helper_result_cannot_be_promoted_by_core_success_markers(tmp_path, monkeypatch):
from types import SimpleNamespace
from test_verify_worker_stability import exercise_worker
from cbb_refresh_verify import mentor_adapter
job, events, execute = exercise_worker(tmp_path, monkeypatch)
def helper(command, **kw):
kw['stdout'].write('LICENSE_OK\nSAVE_OK\nSAVE_REJECTED\nIS_SAVED\nPOST_SAVE_SYNCHRONIZED\nCLOSE_OK\nQUIT_OK\n')
kw['stdout'].flush()
return SimpleNamespace(pid=3, poll=lambda: 0, returncode=0)
monkeypatch.setattr(mentor_adapter.subprocess, 'Popen', helper)
with pytest.raises(RuntimeError, match='保存/关闭未完成'):
execute()
assert not any(event['stage'] == 'complete' for event in events)
+41
View File
@@ -0,0 +1,41 @@
from pathlib import Path
from types import SimpleNamespace
import pytest
from cbb_refresh_verify import mentor_adapter as adapter
from cbb_refresh_verify.library_reader import scan_open_library_status
@pytest.mark.parametrize('prompt', ['', 'Repair database', 'Overwrite existing library',
'Save changes?', 'Unknown license warning'])
def test_compat_readers_neither_launch_nor_answer_native_prompts(monkeypatch, tmp_path, prompt):
import win32process, win32service, win32gui
from pywinauto import Desktop
def forbidden(*a, **kw):
pytest.fail('status observation attempted a native action')
monkeypatch.setattr(win32process, 'CreateProcess', forbidden)
monkeypatch.setattr(win32service, 'CreateDesktop', forbidden)
monkeypatch.setattr(win32gui, 'PostMessage', forbidden)
monkeypatch.setattr(adapter, 'handle_known_dialogs', forbidden)
monkeypatch.setattr(adapter, 'close_library_reader', forbidden)
library = tmp_path/'lib.lmc'
target = SimpleNamespace(window_text=lambda: f'Library Manager: {library}',
is_enabled=lambda: not bool(prompt), descendants=lambda: [], handle=0)
monkeypatch.setattr(Desktop, 'windows', lambda *_: [target] if prompt else [])
assert adapter.read_library_flag(library, 'A')[0] == adapter.FLAG_UNKNOWN
assert adapter.read_library_tree_image_map(library, ['A']) == {'A': None}
assert scan_open_library_status(library, ['A']) == {'A': 'UNKNOWN'}
def test_wrong_library_window_is_not_a_status_source(monkeypatch, tmp_path):
from pywinauto import Desktop
import win32process, win32service
monkeypatch.setattr(win32process, 'CreateProcess', lambda *a, **kw: pytest.fail('implicit launch'))
monkeypatch.setattr(win32service, 'CreateDesktop', lambda *a, **kw: pytest.fail('implicit desktop'))
def forbidden():
pytest.fail('read another library tree')
window = SimpleNamespace(window_text=lambda: 'Library Manager: C:/Other/lib.lmc',
descendants=forbidden)
monkeypatch.setattr(Desktop, 'windows', lambda *_: [window])
assert adapter.read_library_tree_image_map(tmp_path/'lib.lmc', ['A']) == {'A': None}
+3 -3
View File
@@ -113,7 +113,7 @@ def _without_authorized_checkpoint_cleanup(text):
tree = ast.parse(text)
parents = {child: parent for parent in ast.walk(tree) for child in ast.iter_child_nodes(parent)}
allowed = {('LibraryLock', '_exit_owned'): 'marker', ('LibraryLock', '__enter__'): 'marker',
('release_retained_library',): 'checkpoint'}
('release_retained_library',): 'checkpoint', ('write_session_record',): 'pending'}
used, spans = set(), []
for call in ast.walk(tree):
if not (isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)
@@ -127,7 +127,7 @@ def _without_authorized_checkpoint_cleanup(text):
scope = tuple(scope)
if scope in used or allowed.get(scope) != call.func.value.id:
continue
expected = ([('missing_ok', True)] if scope == ('LibraryLock', '_exit_owned') else [])
expected = ([('missing_ok', True)] if scope in (('LibraryLock', '_exit_owned'), ('write_session_record',)) else [])
keywords = [(k.arg, k.value.value if isinstance(k.value, ast.Constant) else None) for k in call.keywords]
if keywords == expected and call.lineno == call.end_lineno:
spans.append((call.lineno - 1, call.col_offset, call.end_col_offset))
@@ -143,7 +143,7 @@ def _without_authorized_checkpoint_cleanup(text):
def test_verification_never_deletes_or_moves_library_files():
for path in production_sources():
text = path.read_text(encoding='utf-8')
if path == SOURCE_ROOT/'library_lock.py':
if path.name in ('library_lock.py', 'session_record.py'):
# Approved runtime JSON lifecycle only. Actual sidecar/engineering
# protection is also exercised against real files below.
text = _without_authorized_checkpoint_cleanup(text)
+55
View File
@@ -0,0 +1,55 @@
import json
import subprocess
import sys
import time
import pytest
from cbb_refresh_verify.desktop_worker import launch_save_helper
def test_helper_gate_only_opens_after_exact_identity_is_durable(tmp_path):
gate, journal, called = tmp_path/'gate', tmp_path/'worker-state.json', tmp_path/'called.json'
script = tmp_path/'helper.py'
script.write_text('import json,time\nfrom pathlib import Path\n'
f'gate=Path({str(gate)!r})\n'
'while not gate.exists(): time.sleep(.02)\n'
f'Path({str(called)!r}).write_text(Path({str(journal)!r}).read_text())\n')
helper = None
try:
helper = launch_save_helper([sys.executable, str(script)], start_gate=gate,
identity_path=journal, operation_id='test-gate')
helper.wait(5)
record = json.loads(called.read_text())
assert record['operation_id'] == 'test-gate'
identity = record['processes'][0]
assert identity['pid'] == helper.pid
assert identity['created_handle'] and identity['owner_sid']
assert identity['image'].casefold() == sys.executable.casefold()
finally:
if helper is not None and helper.poll() is None:
helper.terminate()
helper.wait(5)
def test_identity_storage_failure_does_not_allow_native_call(tmp_path, monkeypatch):
from cbb_refresh_verify import desktop_worker
gate = tmp_path/'gate'
script = tmp_path/'helper.py'
script.write_text('import time;time.sleep(.5)')
created = []
real_popen = subprocess.Popen
def popen(*a, **kw):
process = real_popen(*a, **kw)
created.append(process)
return process
monkeypatch.setattr(desktop_worker.subprocess, 'Popen', popen)
def fail(*a, **kw):
raise OSError('journal unavailable')
monkeypatch.setattr('cbb_refresh_verify.session_record.write_session_record', fail)
with pytest.raises(OSError, match='journal unavailable'):
launch_save_helper([sys.executable, str(script)], start_gate=gate,
identity_path=tmp_path/'worker-state.json', operation_id='test')
assert not gate.exists()
for process in created:
process.wait(5)
+116
View File
@@ -85,3 +85,119 @@ End Class
assert completed.returncode == 4, completed.stderr
assert 'SAVE_OK' not in parsed['markers']
assert 'CLOSE_OK' not in parsed['markers']
def run_helper(tmp_path, *, save_body='Save = True', close_body='Close = True',
is_saved='True', gated=False, cancelled=False):
source = Path('src/cbb_refresh_verify/save_verified_block.vbs').read_text('utf-8')
classes = '''
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()
WScript.Echo "TEST_SAVE_CALLED"
SAVE_BODY
End Function
Public Function IsSaved()
IsSaved = IS_SAVED_VALUE
End Function
Public Function Close(saveChanges)
CLOSE_BODY
closedDoc = True
End Function
End Class
Class FakeApp
Public Property Get ActiveDocument
If closedDoc 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
Public Function GetToken(value)
GetToken = value
End Function
End Class
'''.replace('SAVE_BODY', save_body).replace('CLOSE_BODY', close_body).replace('IS_SAVED_VALUE', is_saved)
source = source.replace('Option Explicit', 'Option Explicit\nDim closedDoc\n' + classes)
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
harness = tmp_path/'facts.vbs'
harness.write_text(source, encoding='ascii')
cancel = tmp_path/'cancel.signal'
if cancelled:
cancel.touch()
args = [str(Path(os.environ['WINDIR'])/'SysWOW64/cscript.exe'), '//nologo',
str(harness), 'expected.prj', 'CBB.pcb', str(cancel)]
if gated:
args.append(str(tmp_path/'start.signal'))
return subprocess.run(args, capture_output=True, text=True, timeout=35)
@pytest.mark.parametrize('body,marker', [('Close = False', 'CLOSE_FAILED'),
('Err.Raise 5, "FakeDoc", "close failed"', 'CLOSE_FAILED')])
def test_close_failure_keeps_successful_save_fact(tmp_path, body, marker):
result = run_helper(tmp_path, close_body=body)
assert 'SAVE_OK' in result.stdout
assert marker in result.stdout
assert 'CLOSE_OK' not in result.stdout
assert result.returncode != 0
def test_save_exception_has_unknown_result_marker(tmp_path):
result = run_helper(tmp_path, save_body='Err.Raise 5, "FakeDoc", "save failed"')
assert 'SAVE_RESULT_UNKNOWN|5|' in result.stdout
assert 'CLOSE_START' not in result.stdout
assert result.returncode != 0
def test_saved_document_postcheck_failure_does_not_discard_save_fact(tmp_path):
result = run_helper(tmp_path, is_saved='False')
assert 'SAVE_OK' in result.stdout
assert 'POST_SAVE_FAILED' in result.stdout
assert 'CLOSE_START' not in result.stdout
def test_cancellation_in_save_allows_identity_checked_saved_close(tmp_path):
result = run_helper(tmp_path, save_body='''
Dim fso, flag
Set fso = CreateObject("Scripting.FileSystemObject")
Set flag = fso.CreateTextFile(WScript.Arguments(2), True)
flag.Close
Save = True
''')
assert 'SAVE_OK' in result.stdout
assert 'CLOSE_OK' in result.stdout
assert 'QUIT_OK' in result.stdout
assert result.returncode == 0, result.stderr
def test_unopened_gate_cancellation_exits_before_com(tmp_path):
result = run_helper(tmp_path, gated=True, cancelled=True)
assert 'CANCELLED_BEFORE_SAVE' in result.stdout
assert 'TEST_SAVE_CALLED' not in result.stdout
assert 'VALIDATE_START' not in result.stdout
assert result.returncode == 9
+6 -7
View File
@@ -499,8 +499,7 @@ def test_parallelism_rejected_for_shared_library(tmp_path):
run_batch([], max_workers=2)
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."""
def test_timeout_without_release_evidence_preserves_native_caller(tmp_path, monkeypatch):
fixture(tmp_path)
killed = []
@@ -520,11 +519,11 @@ def test_timeout_stops_automation_and_allows_retry_when_no_native_owner_remains(
port_check=PORTS_OK)
assert result.status == 'TIMEOUT'
assert killed == [True]
assert result.safe_to_continue
assert killed == []
assert result.safe_to_continue is False
def test_fatal_dialog_terminates_current_worker_and_cannot_become_pass(tmp_path, monkeypatch):
def test_fatal_dialog_preserves_current_worker_and_cannot_become_pass(tmp_path, monkeypatch):
fixture(tmp_path)
killed = []
@@ -557,7 +556,7 @@ def test_fatal_dialog_terminates_current_worker_and_cannot_become_pass(tmp_path,
assert result.status == 'FAIL'
assert result.stderr.startswith('SAVE_REUSABLE_BLOCK_FAILED')
assert killed == [True]
assert killed == []
def test_worker_events_advance_dialog_phase():
@@ -631,7 +630,7 @@ def test_unknown_dialog_writes_snapshot_before_current_item_fails(tmp_path, monk
assert '"error_code": "UNKNOWN_DIALOG"' in dialog_records
assert 'Unknown recovery prompt' in dialog_records
assert (evidence/'process_tree.json').is_file()
assert killed == [True]
assert killed == []
def test_library_flag_is_reported_verbatim_and_never_fabricated(tmp_path, monkeypatch):