Files

208 lines
10 KiB
Python

"""Real filesystem/subprocess probes using fake CLIs, never a model or design."""
import asyncio
import importlib
import json
import os
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import AsyncMock, patch
from codex_pcb import preflight
class ProductionPreflight(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name).resolve()
self.workspace = self.root / 'data/tasks/test/workspace'
self.bin = self.root / 'bin'
self.bin.mkdir()
reference = self.root / 'data/resources/references/_index.md'
reference.parent.mkdir(parents=True)
reference.write_text('API index')
jar = self.root / 'router.jar'
jar.touch()
self.settings = patch.multiple(preflight, ROOT=self.root / 'data',
CODEX_HOME=self.root / 'codex-home', CODEX_BIN=str(self.bin / 'codex'),
EDA_BIN=str(self.bin / 'eda'), BLENDER_BIN=str(self.bin / 'blender'),
FREEROUTING_JAR=jar)
self.settings.start()
self.addCleanup(self.settings.stop)
self.environment = patch.dict(os.environ, {
'HOME': str(self.root / 'home'), 'PATH': os.defpath,
'OPENAI_API_KEY': 'must-not-reach-eda-or-probe',
'DEEPSEEK_API_KEY_FILE': '/must-not-reach-child',
}, clear=True)
self.environment.start()
self.addCleanup(self.environment.stop)
self.program('codex', '''import os,sys,json
from pathlib import Path
assert 'OPENAI_API_KEY' not in os.environ
assert 'DEEPSEEK_API_KEY_FILE' not in os.environ
assert sys.argv[1] == 'sandbox'
assert '-C' not in sys.argv # Requires a named profile in the pinned CLI.
assert 'sandbox_mode="workspace-write"' in sys.argv
assert 'sandbox_workspace_write.exclude_slash_tmp=true' in sys.argv
assert Path(os.environ['TMPDIR']).is_relative_to(Path.cwd())
if os.environ.get('FAIL_SANDBOX'):
print('bwrap: Creating new namespace failed: Operation not permitted',file=sys.stderr)
sys.exit(1)
if not os.environ.get('NO_SANDBOX_WRITE'):
Path(sys.argv[-1]).write_text('pcb-preflight')
''')
self.env_calls = self.root / 'eda-calls.jsonl'
os.environ['TEST_EDA_CALLS'] = str(self.env_calls)
self.program('eda', '''import os,sys,json
from pathlib import Path
assert 'OPENAI_API_KEY' not in os.environ
assert 'DEEPSEEK_API_KEY_FILE' not in os.environ
assert sys.argv[-1] == '--no-sandbox'
args=sys.argv[1:-1]
with Path(os.environ['TEST_EDA_CALLS']).open('a') as stream:stream.write(json.dumps(args)+'\\n')
if os.environ.get('FAIL_EDA'):
print('Permission denied: /opt/lceda-pro/lceda-pro',file=sys.stderr)
sys.exit(126)
if args == ['--help']:print('EasyEDA CLI help')
elif args == ['open','--headless','true']:print(json.dumps({'ok':True,'value':{'sessionId':'diagnostic-only'}}))
elif args[:1] == ['invoke']:
assert args[args.index('--session')+1] == 'diagnostic-only'
code=sys.stdin.read()
assert 'getEditorCurrentVersion' in code and 'createProject' not in code
if os.environ.get('FAIL_BRIDGE'):
print(json.dumps({'ok':False,'error':{'code':'BRIDGE_NOT_READY','message':'command-space-missing'}}))
sys.exit(1)
print(json.dumps({'ok':True,'value':{'client':True,'version':'test-editor'}}))
elif args == ['session','close','--session','diagnostic-only','--destroy']:
if os.environ.get('FAIL_CLOSE'):
print(json.dumps({'ok':False,'error':{'code':'CLOSE_FAILED'}}));sys.exit(1)
print(json.dumps({'ok':True,'value':None}))
else:raise AssertionError(args)
''')
self.program('blender', 'pass\n')
def program(self, name, body):
path = self.bin / name
path.write_text(f'#!{sys.executable}\n' + body)
path.chmod(0o755)
async def test_success_checks_real_writes_and_does_not_call_model_or_leave_probe_files(self):
report = await preflight.check_runtime(self.workspace)
self.assertTrue(report['ok'], report)
checks = {item['name']: item for item in report['checks']}
self.assertTrue(checks['codex_sandbox']['ok'])
self.assertTrue(checks['eda_launch']['ok'])
self.assertTrue(checks['eda_bridge']['ok'])
calls = [json.loads(line) for line in self.env_calls.read_text().splitlines()]
self.assertEqual(calls[-1], ['session', 'close', '--session', 'diagnostic-only', '--destroy'])
self.assertFalse(list(self.root.rglob('.pcb-*-check-*')))
self.assertEqual((self.root / 'codex-home').stat().st_mode & 0o777, 0o700)
self.assertNotIn('must-not-reach', json.dumps(report))
async def test_independent_eda_and_namespace_failures_both_reported(self):
os.environ.update(FAIL_SANDBOX='1', FAIL_EDA='1')
report = await preflight.check_runtime(self.workspace)
self.assertFalse(report['ok'])
failed = {item['name']: item['message'] for item in report['checks'] if not item['ok']}
self.assertIn('bwrap', failed['codex_sandbox'])
self.assertIn('Permission denied', failed['eda_launch'])
self.assertNotIn('must-not-reach', json.dumps(report))
async def test_eda_keeps_host_temp_directory_for_persistent_ipc(self):
host_tmp = str(self.root / 'host-tmp')
os.environ.update(TMPDIR=host_tmp, TMP=host_tmp, TEMP=host_tmp)
with patch.object(preflight, 'eda_cli', wraps=preflight.eda_cli) as cli:
report = await preflight.check_runtime(self.workspace)
self.assertTrue(report['ok'], report)
self.assertEqual(cli.await_count, 3)
for call in cli.await_args_list:
for name in ('TMPDIR', 'TMP', 'TEMP'):
self.assertEqual(call.kwargs['environment'][name], host_tmp)
async def test_native_only_workflow_does_not_require_external_router(self):
with patch.object(preflight, 'FREEROUTING_JAR', self.root / 'missing-router.jar'):
report = await preflight.check_runtime(self.workspace)
self.assertTrue(report['ok'], report)
self.assertNotIn('freerouting', [item['name'] for item in report['checks']])
async def test_nonexecutable_eda_is_detected_without_launch(self):
(self.bin / 'eda').chmod(0o644)
report = await preflight.check_runtime(self.workspace)
self.assertFalse(report['ok'])
failed = [item for item in report['checks'] if not item['ok']]
self.assertEqual([item['name'] for item in failed], ['eda_binary'])
self.assertIn('执行权限', failed[0]['message'])
async def test_help_success_does_not_hide_bridge_failure_and_owned_session_is_closed(self):
os.environ['FAIL_BRIDGE'] = '1'
report = await preflight.check_runtime(self.workspace)
checks = {item['name']: item for item in report['checks']}
self.assertTrue(checks['eda_launch']['ok'])
self.assertFalse(report['ok'])
self.assertIn('BRIDGE_NOT_READY', checks['eda_bridge']['message'])
calls = [json.loads(line) for line in self.env_calls.read_text().splitlines()]
self.assertEqual(calls[-1], ['session', 'close', '--session', 'diagnostic-only', '--destroy'])
async def test_cleanup_failure_is_not_reported_as_ready(self):
os.environ['FAIL_CLOSE'] = '1'
report = await preflight.check_runtime(self.workspace)
self.assertFalse(report['ok'])
self.assertIn('eda_cleanup', [item['name'] for item in report['checks'] if not item['ok']])
async def test_exit_zero_without_actual_sandbox_write_is_rejected(self):
os.environ['NO_SANDBOX_WRITE'] = '1'
report = await preflight.check_runtime(self.workspace)
failed = [item['name'] for item in report['checks'] if not item['ok']]
self.assertEqual(failed, ['codex_sandbox'])
async def test_unwritable_workspace_is_reported_as_failure(self):
blocker = self.root / 'not-a-directory'
blocker.touch()
report = await preflight.check_runtime(blocker / 'workspace')
self.assertFalse(report['ok'])
self.assertFalse(next(item for item in report['checks'] if item['name'] == 'workspace_write')['ok'])
async def test_probe_timeout_is_a_failure(self):
with patch.object(preflight, 'command', side_effect=asyncio.TimeoutError):
report = await preflight.check_runtime(self.workspace)
self.assertFalse(report['ok'])
self.assertFalse(next(item for item in report['checks'] if item['name'] == 'codex_sandbox')['ok'])
async def test_production_does_not_start_model_after_failed_preflight(self):
app = importlib.import_module('codex_pcb.app')
self.workspace.mkdir(parents=True)
task = {'id': 'preflight-test', 'state': 'running', 'busy': True, 'approval': {}}
report = {'ok': False, 'checks': [{'name': 'codex_sandbox', 'ok': False, 'message': 'bwrap namespace blocked'}]}
entries = []
with patch.object(app, 'frozen'), patch.object(app, 'save'), \
patch.object(app, 'workspace', return_value=self.workspace), \
patch.object(app, 'event', side_effect=lambda t, name, data: entries.append((name, data))), \
patch.object(app, 'check_runtime', AsyncMock(return_value=report)), \
patch.object(app, 'run_turn', AsyncMock()) as turn:
await app.work(task, 'Approved design', True)
turn.assert_not_awaited()
self.assertEqual(task['state'], 'failed')
self.assertFalse(task['busy'])
self.assertIn('bwrap namespace blocked', task['error'])
self.assertEqual(json.loads((self.workspace / 'evidence/runtime-check.json').read_text()), report)
self.assertIn(('runtime.checked', report), entries)
async def test_source_freeze_is_checked_before_production_probes(self):
app = importlib.import_module('codex_pcb.app')
task = {'id': 'frozen-test', 'state': 'running', 'busy': True}
with patch.object(app, 'frozen', side_effect=RuntimeError('Backend source changed after approval')), \
patch.object(app, 'save'), patch.object(app, 'event'), \
patch.object(app, 'check_runtime', AsyncMock()) as check, \
patch.object(app, 'run_turn', AsyncMock()) as turn:
await app.work(task, 'Approved design', True)
check.assert_not_awaited()
turn.assert_not_awaited()
self.assertIn('source changed', task['error'])
self.assertFalse(task['busy'])
if __name__ == '__main__':
unittest.main()