test: align safety contracts and isolate owned native fixtures
This commit is contained in:
1 parent
422d5483bc
commit
c3a6e59420
5 files changed
+93
-8
No files matched your search
@@ -145,6 +145,8 @@ def worker_runtime(tmp_path, monkeypatch, monitor):
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
from dx_productivity.trial_task_center import worker_monitor
|
||||
monkeypatch.setattr(worker_monitor, 'run_monitored_process', monitor)
|
||||
Desktop.created = []
|
||||
Desktop.fail_release = False
|
||||
Cad.created = []
|
||||
return BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=Desktop, cad_factory=Cad)
|
||||
|
||||
|
||||
@@ -246,7 +246,12 @@ def test_real_private_desktop_messagebox_is_handled_without_touching_input_deskt
|
||||
else:
|
||||
assert process.poll() is None
|
||||
assert guard.summary()['blocked']
|
||||
# Explicitly dismiss our disposable sample after proving no automatic click.
|
||||
dialog, = guard.summary()['current_dialogs']
|
||||
guard.manual_action(dialog, dialog['buttons'][0]['hwnd'])
|
||||
assert process.wait(timeout=3) == 0
|
||||
assert desktop.cleanup_record['desktop_confirmation']['released']
|
||||
assert not any(row.get('forced_termination') for row in desktop.cleanup_record['processes'])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('directory', ['tasks/task/quick-run', 'batch-resources/batch/generation-1'])
|
||||
|
||||
@@ -77,6 +77,7 @@ def test_deep_quick_run_prepare_publish_read_archive_keeps_canonical_results(dee
|
||||
def test_deep_native_recovery_keeps_canonical_proof_and_release_logs(deep_root):
|
||||
import hashlib
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
from dx_productivity.trial_task_center.project_discovery import ReleasedProjectReadError
|
||||
from test_batch_runtime import Desktop
|
||||
Desktop.created = []
|
||||
Desktop.fail_release = False
|
||||
@@ -95,8 +96,19 @@ def test_deep_native_recovery_keeps_canonical_proof_and_release_logs(deep_root):
|
||||
'source_hashes': {str(path): hashlib.sha256(internal_path(path).read_bytes()).hexdigest()
|
||||
for path in (project, database)}}
|
||||
internal_path(evidence / 'native-retry-proof.json').write_text(json.dumps(proof), encoding='utf-8')
|
||||
assert owner.recover_native_failure(project, evidence, 'timeout')
|
||||
assert not owner.recover_native_failure(project, evidence, 'second timeout')
|
||||
with pytest.raises(ReleasedProjectReadError) as caught:
|
||||
owner.recover_native_failure(project, evidence, 'timeout')
|
||||
assert caught.value.code == 'quick_run_sheet_discovery'
|
||||
assert owner.desktop is owner.cad is None
|
||||
assert not owner.record['retries']
|
||||
release_record = json.loads(internal_path(evidence / 'project-read-release.json').read_text(encoding='utf-8'))
|
||||
assert release_record['project_path'] == str(project)
|
||||
assert release_record['resource_record'] == str(owner.path)
|
||||
assert release_record['resources_released'] is True
|
||||
assert json.loads(internal_path(evidence / 'native-retry-proof.json').read_text(encoding='utf-8')) == proof
|
||||
assert proof['project_path'] == str(project) and proof['evidence_root'] == str(evidence)
|
||||
assert proof['source_hashes'] == {str(path): hashlib.sha256(internal_path(path).read_bytes()).hexdigest()
|
||||
for path in (project, database)}
|
||||
assert all(desktop.released for desktop in Desktop.created)
|
||||
assert not owner.record.get('release_log_errors')
|
||||
release = owner.path.with_name('resource-release.log')
|
||||
|
||||
@@ -2,6 +2,7 @@ import os
|
||||
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
|
||||
|
||||
from dx_productivity.trial_task_center.logging_setup import append_task_event
|
||||
from PySide6.QtCore import Qt
|
||||
from test_ui_remediation import window
|
||||
|
||||
|
||||
@@ -10,7 +11,8 @@ def test_results_use_executed_readback_and_clear_when_switching_tasks(window, qt
|
||||
for state, ref in [('saved_ok', 'R1'), ('batch_failed', 'R2'), ('no_match', 'R3')]:
|
||||
append_task_event(window.service._logging, level='INFO', task_id=task.task_id,
|
||||
operation='quick_run_executed', message=f'Replacements: {ref} OLD -> ACTUAL Saved, reopened',
|
||||
details={'state': state, 'schematic_name': 'MAIN', 'sheet_number': '1'})
|
||||
details={'state': state, 'schematic_name': 'MAIN', 'sheet_number': '1',
|
||||
'custom_value': 'PLANNED-ONLY', 'copy_part_number_to_value': True})
|
||||
window.open_task(task.task_id)
|
||||
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
|
||||
window._show_task_log()
|
||||
@@ -19,7 +21,14 @@ def test_results_use_executed_readback_and_clear_when_switching_tasks(window, qt
|
||||
assert results.rowCount() == 1
|
||||
assert results.index(0, 1).data() == 'R1'
|
||||
assert results.index(0, 3).data() == 'ACTUAL'
|
||||
assert '已保存并核验' in results.index(0, 4).data()
|
||||
headers = [results.headerData(column, Qt.Orientation.Horizontal)
|
||||
for column in range(results.columnCount())]
|
||||
assert headers == ['图页', '位号', '旧料号', '回读料号', '原 Value', '实际 Value', '核验状态']
|
||||
assert '已保存并核验' in results.index(0, headers.index('核验状态')).data()
|
||||
assert results.index(0, headers.index('原 Value')).data() == '未提供'
|
||||
assert results.index(0, headers.index('实际 Value')).data() == '未提供实际回读'
|
||||
assert all(results.index(0, column).data() != 'PLANNED-ONLY'
|
||||
for column in range(results.columnCount()))
|
||||
other = window.service.create_task('Unexecuted')
|
||||
window.open_task(other.task_id)
|
||||
qtbot.waitUntil(lambda: not window._loading and not window._context_query.busy)
|
||||
|
||||
@@ -36,6 +36,7 @@ def test_unsafe_save_timeout_waits_for_completion_and_recovers_on_progress():
|
||||
|
||||
|
||||
def test_real_slow_save_is_not_killed_by_inactivity(tmp_path, started_worker_watch):
|
||||
from dx_productivity.trial_task_center.stop_control import StopControl
|
||||
script = tmp_path / 'save.py'
|
||||
script.write_text('''import sys,time,pathlib
|
||||
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
|
||||
@@ -45,12 +46,63 @@ time.sleep(1.5)
|
||||
(root/'saved.txt').write_text('saved and independently verified')
|
||||
''', encoding='utf-8')
|
||||
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
|
||||
result = run_monitored_process(command, .3)
|
||||
result = run_monitored_process(command, .3, force_control=StopControl())
|
||||
assert result.returncode == 0
|
||||
assert 'save_and_close' in started_worker_watch
|
||||
assert (tmp_path / 'saved.txt').read_text() == 'saved and independently verified'
|
||||
|
||||
|
||||
def test_noninteractive_unsafe_save_retains_owner_until_natural_exit(tmp_path, monkeypatch, started_worker_watch):
|
||||
import time
|
||||
from uuid import uuid4
|
||||
from dx_productivity.trial_task_center import batch_resources, worker_monitor
|
||||
from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop
|
||||
script = tmp_path / 'save.py'
|
||||
script.write_text('''import sys,time,pathlib
|
||||
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
|
||||
while not (root/f'monitor-{token}.ready').exists():time.sleep(.01)
|
||||
print(f'DX_PROGRESS\\t{token}\\t{job}\\t1\\tsave_and_close\\t0\\t1\\t0',flush=True)
|
||||
while not (root/'allow-exit').exists():time.sleep(.01)
|
||||
(root/'saved.txt').write_text('naturally completed')
|
||||
''', encoding='utf-8')
|
||||
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
|
||||
processes = []
|
||||
with PrivateDesktop('dx-' + uuid4().hex, enabled=True) as desktop:
|
||||
def launch(command, **options):
|
||||
process = desktop.start_process(command, **options)
|
||||
processes.append(process)
|
||||
return process
|
||||
monkeypatch.setattr(worker_monitor._OwnedWorkers, 'stop_workers',
|
||||
lambda *_: pytest.fail('unsafe save must not be killed'))
|
||||
try:
|
||||
with pytest.raises(worker_monitor.WorkerMonitorError, match='owned worker retained'):
|
||||
run_monitored_process(command, .3, process_factory=launch)
|
||||
assert len(processes) == 1 and processes[0].poll() is None
|
||||
assert 'save_and_close' in started_worker_watch
|
||||
retained = next(tmp_path.glob('retained-worker-*.json'))
|
||||
assert json.loads(retained.read_text())['state'] == 'blocked'
|
||||
assert (tmp_path / 'uncertain.flag').exists()
|
||||
assert batch_resources.cleanup_pending_resources(tmp_path)
|
||||
assert processes[0].poll() is None and len(processes) == 1
|
||||
(tmp_path / 'allow-exit').touch()
|
||||
assert processes[0].wait(timeout=5) == 0
|
||||
deadline = time.monotonic() + 5
|
||||
while not processes[0].tree_exited():
|
||||
assert time.monotonic() < deadline
|
||||
time.sleep(.01)
|
||||
assert batch_resources.cleanup_pending_resources(tmp_path) == ()
|
||||
assert json.loads(retained.read_text())['state'] == 'released'
|
||||
assert not processes[0].cleanup_record['forced_termination']
|
||||
assert (tmp_path / 'saved.txt').read_text() == 'naturally completed'
|
||||
assert (tmp_path / 'uncertain.flag').exists() and len(processes) == 1
|
||||
finally:
|
||||
(tmp_path / 'allow-exit').touch()
|
||||
for process in processes:
|
||||
process.wait(timeout=5)
|
||||
worker_monitor.cleanup_retained_workers(tmp_path)
|
||||
assert desktop.cleanup_record['desktop_confirmation']['released']
|
||||
|
||||
|
||||
def test_readonly_native_wait_keeps_bounded_cancellation_without_force_ui(tmp_path, started_worker_watch):
|
||||
script = tmp_path / 'read.py'
|
||||
script.write_text('''import sys,time,pathlib
|
||||
@@ -196,7 +248,7 @@ def test_interruption_targets_active_project_without_invalidating_previous_tasks
|
||||
|
||||
|
||||
@pytest.mark.parametrize('interactive', [False, True])
|
||||
def test_supervisor_only_holds_for_resolution_when_caller_has_force_control(tmp_path, monkeypatch, interactive):
|
||||
def test_supervisor_preserves_caller_interactivity_and_always_owns_stop_control(tmp_path, monkeypatch, interactive):
|
||||
import textwrap
|
||||
from dx_productivity.trial_task_center import batch_supervisor as module
|
||||
from dx_productivity.trial_task_center.stop_control import StopControl
|
||||
@@ -211,7 +263,10 @@ def test_supervisor_only_holds_for_resolution_when_caller_has_force_control(tmp_
|
||||
original=batch_runtime.BatchCadRuntime
|
||||
def runtime(*args,**kwargs):
|
||||
result=original(*args,**kwargs)
|
||||
Path(sys.argv[1]).with_name('interactive-witness.json').write_text(json.dumps(isinstance(result.stop_event,StopControl)))
|
||||
request = json.loads(Path(sys.argv[1]).read_text())
|
||||
Path(sys.argv[1]).with_name('interactive-witness.json').write_text(json.dumps({
|
||||
'request_interactive_stop': request['interactive_stop'],
|
||||
'internal_stop_control': isinstance(result.stop_event,StopControl)}))
|
||||
return result
|
||||
batch_runtime.BatchCadRuntime=runtime
|
||||
batch_worker.run(Path(sys.argv[1]))
|
||||
@@ -222,7 +277,9 @@ def test_supervisor_only_holds_for_resolution_when_caller_has_force_control(tmp_
|
||||
service = TaskCenterService(store, configure_logging(tmp_path))
|
||||
module.run_supervised(service, 'probe', {}, stop_event=StopControl() if interactive else Event())
|
||||
witness = next((tmp_path / 'batch-resources').glob('*/interactive-witness.json'))
|
||||
assert json.loads(witness.read_text()) is interactive
|
||||
observed = json.loads(witness.read_text())
|
||||
assert observed['request_interactive_stop'] is interactive
|
||||
assert observed['internal_stop_control'] is True
|
||||
finally:
|
||||
store.close()
|
||||
|
||||
|
||||
Reference in new issue
Block a user