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

242 lines
11 KiB
Python

import io
import json
import os
from pathlib import Path
from threading import Event
from threading import Timer
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
@pytest.mark.skipif(os.name != 'nt', reason='Windows junction path handling')
def test_private_evidence_uses_canonical_root_behind_a_legacy_alias(tmp_path):
from dx_productivity.trial_task_center.legacy_paths import _AliasPool
root = tmp_path / ('nested-' + 'x' * 90) / ('nested-' + 'y' * 90)
root.mkdir(parents=True)
pool = _AliasPool()
try:
alias = pool.alias(root.resolve())
session = runtime.IsolatedCadSession(alias)
session._record(state='starting')
assert session.root == root.resolve()
assert (root / 'private-desktop-sessions' / (session.token + '.json')).is_file()
finally:
assert not pool.close()
@pytest.mark.skipif(os.name != 'nt', reason='Windows state-file sharing semantics')
def test_private_record_survives_a_reader_temporarily_denying_replacement(tmp_path):
import win32con
import win32file
session = runtime.IsolatedCadSession(tmp_path)
session._record(state='starting')
held = win32file.CreateFile(str(tmp_path / 'private-desktop.json'), win32con.GENERIC_READ,
win32con.FILE_SHARE_READ, None, win32con.OPEN_EXISTING, 0, None)
reader_done = Timer(0.1, held.Close)
reader_done.start()
try:
session._record(state='released', clean=True)
finally:
reader_done.join()
current = json.loads((tmp_path / 'private-desktop.json').read_text())
archived = json.loads((tmp_path / 'private-desktop-sessions' / (session.token + '.json')).read_text())
assert current == archived and current['state'] == 'released' and current['clean']
@pytest.mark.skipif(os.name != 'nt', reason='Windows state-file sharing semantics')
def test_private_record_reports_persistent_denial_and_keeps_previous_record(tmp_path):
import win32con
import win32file
session = runtime.IsolatedCadSession(tmp_path)
session._record(state='starting')
held = win32file.CreateFile(str(tmp_path / 'private-desktop.json'), win32con.GENERIC_READ,
win32con.FILE_SHARE_READ, None, win32con.OPEN_EXISTING, 0, None)
try:
with pytest.raises(PermissionError):
session._record(state='released', clean=True)
assert json.loads((tmp_path / 'private-desktop.json').read_text())['state'] == 'starting'
finally:
held.Close()
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']
@pytest.mark.parametrize('ready_after', [90, None])
def test_slow_startup_is_bounded_and_cleanup_remains_owned(monkeypatch, tmp_path, ready_after):
events, _ = fake_desktop(monkeypatch, tmp_path)
clock = [0.0]
monkeypatch.setattr(runtime.time, 'monotonic', lambda: clock[0])
monkeypatch.setattr(runtime.time, 'sleep', lambda seconds: clock.__setitem__(0, clock[0] + seconds))
original = runtime.PrivateDesktop.start_process
def start(self, command, **kwargs):
process = original(self, command, **kwargs)
if command[0] == 'probe':
process.poll = lambda: 0 if ready_after is not None and clock[0] >= ready_after else None
return process
monkeypatch.setattr(runtime.PrivateDesktop, 'start_process', start)
if ready_after is None:
with pytest.raises(runtime.PrivateCadStartupError, match='bootstrap timed out'):
with runtime.IsolatedCadSession(tmp_path):
pytest.fail('unresponsive startup entered project work')
assert 119 <= clock[0] <= 121
assert ('release', False) in events
else:
with runtime.IsolatedCadSession(tmp_path):
assert clock[0] >= ready_after
assert ('release', False) in events
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_private_helper_works_when_application_is_the_executable_entry_script(monkeypatch, tmp_path):
import runpy
import sys
from dx_productivity.trial_task_center import application
calls = []
monkeypatch.setattr(runtime, 'native_action', lambda *args: calls.append(args) or 0)
evidence = tmp_path / 'binding.json'
monkeypatch.setattr(sys, 'argv', [application.__file__, '--private-cad-action', 'probe',
'--private-cad-evidence', str(evidence), '--private-cad-pid', '123'])
with pytest.raises(SystemExit) as result:
runpy.run_path(application.__file__, run_name='__main__')
assert result.value.code == 0
assert calls == [('probe', evidence, 123)]
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