Files
dxdesigner-part-replacement/tests/v1_1/test_isolated_cad.py
T

149 lines
6.8 KiB
Python

import io
import json
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import isolated_cad as runtime
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
def fake_desktop(monkeypatch, tmp_path, *, abort=None, quit_code=0, cad_exit_code=0):
events = []
cad = SimpleNamespace(pid=123, returncode=None)
cad.poll = lambda: cad.returncode
cad.wait = lambda timeout: cad.returncode
class Desktop:
def __init__(self, name, **kwargs):
self.name = name
def __enter__(self):
events.append('create')
return self
def start_process(self, command, **kwargs):
events.append(command[0])
if command[0] == 'cad.exe':
return cad
action, path, pid = command
if action == 'probe':
Path(path).write_text(json.dumps({'desktop': self.name, 'pid': pid,
'guid': '{owned}', 'token': kwargs['env']['DXPART_SESSION_TOKEN']}))
if abort is not None:
abort.set()
else:
cad.returncode = cad_exit_code
return SimpleNamespace(poll=lambda: None if abort is not None else 0,
wait=lambda timeout: quit_code, close=lambda: events.append('close-helper'),
stderr=io.BytesIO(b'project still open'))
def close(self):
events.append(('release', (tmp_path / 'uncertain.flag').exists()))
cad.returncode = 1 if cad.returncode is None else cad.returncode
monkeypatch.setattr(runtime, 'PrivateDesktop', Desktop)
monkeypatch.setattr(runtime, '_designer_executable', lambda: 'cad.exe')
monkeypatch.setattr(runtime, '_helper_command', lambda action, path, pid: (action, str(path), pid))
return events, cad
def test_success_quits_owned_cad_before_releasing_desktop(monkeypatch, tmp_path):
events, cad = fake_desktop(monkeypatch, tmp_path)
with runtime.IsolatedCadSession(tmp_path):
assert cad.poll() is None
assert events.index('quit') < events.index(('release', False))
record = json.loads((tmp_path / 'private-desktop.json').read_text())
assert record['state'] == 'released' and record['clean']
def test_repeated_session_preserves_prior_release_evidence(monkeypatch, tmp_path):
fake_desktop(monkeypatch, tmp_path)
with runtime.IsolatedCadSession(tmp_path) as first:
first_token = first.token
fake_desktop(monkeypatch, tmp_path)
with runtime.IsolatedCadSession(tmp_path):
pass
records = [json.loads(path.read_text()) for path in (tmp_path / 'private-desktop-sessions').glob('*.json')]
assert len(records) == 2 and first_token in {row['token'] for row in records}
assert all(row['state'] == 'released' and row['clean'] for row in records)
def test_hidden_private_action_dispatches_without_opening_gui(monkeypatch, tmp_path):
from dx_productivity.trial_task_center import application
def forbidden(*args, **kwargs):
pytest.fail('private CAD helper must not initialize the GUI')
monkeypatch.setattr(application, 'QApplication', forbidden)
calls = []
monkeypatch.setattr(runtime, 'native_action', lambda *args: calls.append(args) or 0)
path = tmp_path / 'evidence.json'
assert application.main(['--private-cad-action', 'probe', '--private-cad-evidence', str(path),
'--private-cad-pid', '123']) == 0
assert calls == [('probe', path, 123)]
assert application.main(['--private-cad-action', 'probe']) == 2
def test_startup_cancellation_releases_without_waiting_for_com_timeout(monkeypatch, tmp_path):
abort = Event()
events, _ = fake_desktop(monkeypatch, tmp_path, abort=abort)
with pytest.raises(WorkerMonitorError, match='cancelled'):
with runtime.IsolatedCadSession(tmp_path, abort_event=abort):
pytest.fail('cancelled startup entered replacement body')
assert 'quit' not in events
assert ('release', False) in events
def test_startup_cleanup_failure_keeps_uncertain_lock(monkeypatch, tmp_path):
abort = Event()
fake_desktop(monkeypatch, tmp_path, abort=abort)
session = runtime.IsolatedCadSession(tmp_path, abort_event=abort)
def failure():
raise OSError('owned process did not exit')
session.desktop.close = failure
with pytest.raises(WorkerMonitorError, match='cleanup requires reconciliation'):
session.__enter__()
assert (tmp_path / 'uncertain.flag').exists()
def test_released_startup_failure_returns_retryable_pre_mutation_code(monkeypatch, tmp_path):
class FailedStartup:
def __init__(self, *args, **kwargs):
pass
def __enter__(self):
raise runtime.PrivateCadStartupError('startup cancelled before project launch')
def __exit__(self, *args):
pytest.fail('failed enter must not enter execution')
monkeypatch.setattr(runtime, 'IsolatedCadSession', FailedStartup)
result = runtime.run_isolated_process(('cscript.exe', '//nologo', 'helper.vbs', str(tmp_path)), 1)
assert result.returncode == 2
assert 'before project launch' in result.stderr
assert not (tmp_path / 'uncertain.flag').exists()
@pytest.mark.parametrize('failure', ['quit', 'cad_exit', 'unexpected_exit'])
def test_uncertain_cleanup_is_durable_before_forced_owned_release(monkeypatch, tmp_path, failure):
events, cad = fake_desktop(monkeypatch, tmp_path,
quit_code=1 if failure == 'quit' else 0,
cad_exit_code=7 if failure == 'cad_exit' else 0)
with pytest.raises(WorkerMonitorError, match='reconciliation'):
with runtime.IsolatedCadSession(tmp_path):
if failure == 'unexpected_exit':
cad.returncode = 9
assert ('release', True) in events
assert not json.loads((tmp_path / 'private-desktop.json').read_text())['clean']
def test_single_step_backup_precedes_discovery_and_failure_blocks_discovery(monkeypatch, tmp_path):
from dx_productivity.trial_task_center import single_step
events = []
preparer = SimpleNamespace(data_root=tmp_path,
progress=lambda *args, **kwargs: SimpleNamespace(queue_complete=False, next_project_path=tmp_path / 'one.prj'),
ensure_batch_handoff=lambda *args, **kwargs: events.append('discover'))
monkeypatch.setattr(single_step, 'create_schematic_backup', lambda *args: events.append('backup'))
single_step.prepare_private_single_step(preparer, 'task', (), (), False)
assert events == ['backup', 'discover']
def failed_backup(*args):
raise OSError('backup failed')
monkeypatch.setattr(single_step, 'create_schematic_backup', failed_backup)
events.clear()
with pytest.raises(OSError, match='backup failed'):
single_step.prepare_private_single_step(preparer, 'task', (), (), False)
assert not events