Files
leleka/scripts/test-native-service.py

235 lines
11 KiB
Python

#!/usr/bin/env python3
"""Behavior checks for opt-in native service control; never contact a real host."""
import importlib.util
import contextlib
import io
import json
import os
from pathlib import Path
import shlex
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
import qwen_native_service as client
spec = importlib.util.spec_from_file_location('installer', Path(__file__).with_name('install-qwen-native-service.py'))
installer = importlib.util.module_from_spec(spec)
spec.loader.exec_module(installer)
class FakeHost:
def __init__(self):
self.active = False
self.calls = []
self.loaded = True
def __call__(self, host, command):
self.calls.append((host, command))
if command[0] == 'journalctl':
return 'fixture log\n'
action = command[2]
if action == 'show':
return ('LoadState=' + ('loaded' if self.loaded else 'not-found') + '\n'
'ActiveState=' + ('active' if self.active else 'inactive') + '\n'
'SubState=' + ('running' if self.active else 'dead') + '\n'
'MainPID=' + ('123' if self.active else '0') + '\nResult=success\n'
'Environment=must-not-be-returned\n')
if action in {'start', 'stop'}:
self.active = action == 'start'
return ''
raise AssertionError(command)
class ControlTests(unittest.TestCase):
def test_idempotent_start_stop_and_readiness_is_not_inferred(self):
host = FakeHost()
def call(action):
return client.control(action, 'rnr5090', 'leleka-api-test.service', runner=host)
self.assertFalse(call('status')['changed'])
self.assertTrue(call('start')['changed'])
again = call('start')
self.assertFalse(again['changed'])
self.assertEqual(again['model_readiness'], 'not_checked')
self.assertFalse(again['connection_changed'])
self.assertNotIn('Environment', again['process'])
self.assertTrue(call('stop')['changed'])
self.assertFalse(call('stop')['changed'])
mutations = [args for _, args in host.calls if args[2] in {'start', 'stop'}]
self.assertEqual([args[2] for args in mutations], ['start', 'stop'])
self.assertTrue(all(args[-2:] == ['--', 'leleka-api-test.service'] for args in mutations))
def test_rejected_selectors_never_reach_ssh(self):
host = FakeHost()
for bad in ['-oProxyCommand=x', 'host;id', 'host\nother', 'user@host', 'host name']:
with self.assertRaises(ValueError):
client.control('start', bad, 'leleka-api.service', runner=host)
for bad in ['sshd.service', 'leleka-api.service;id', '../leleka-api.service', 'leleka-api@a.service']:
with self.assertRaises(ValueError):
client.control('stop', 'rnr5090', bad, runner=host)
self.assertEqual(host.calls, [])
def test_missing_service_is_not_created_or_started(self):
host = FakeHost()
host.loaded = False
with self.assertRaisesRegex(RuntimeError, 'provision'):
client.control('start', 'rnr5090', 'leleka-api.service', runner=host)
self.assertEqual(len(host.calls), 1)
self.assertEqual(host.calls[0][1][2], 'show')
def test_invalid_status_fails_closed(self):
with self.assertRaisesRegex(RuntimeError, 'invalid'):
client.control('start', 'rnr5090', 'leleka-api.service',
runner=lambda *_: 'LoadState=loaded\nActiveState=active\nMainPID=oops')
def test_logs_are_scoped_and_bounded(self):
host = FakeHost()
self.assertEqual(client.control('logs', 'rnr5090', 'leleka-api-test.service', runner=host), 'fixture log\n')
self.assertEqual(host.calls[-1][1], ['journalctl', '--user', '--unit=leleka-api-test.service',
'--lines=100', '--no-pager', '--output=short-iso'])
class InstallerTests(unittest.TestCase):
SOURCE = '''import argparse, sys
HOST = 'fixture'
def ctl_main():
parser = argparse.ArgumentParser()
sub = parser.add_subparsers(dest='command', required=True)
sub.add_parser('status')
# Strata Next native Responses integration v1
'''
def test_install_reinstall_backup_and_no_profile_write(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
launcher = root / 'qwen_local.py'
launcher.write_text(self.SOURCE)
connection = root / 'connection.json'
connection.write_text('{"untouched":true}')
installer.install(launcher)
first = launcher.read_bytes()
installer.install(launcher)
self.assertEqual(launcher.read_bytes(), first)
self.assertEqual(connection.read_text(), '{"untouched":true}')
backups = list(root.glob('qwen_local.py.before-native-service-*'))
self.assertEqual(len(backups), 1)
self.assertEqual(backups[0].read_text(), self.SOURCE)
self.assertTrue((root / 'qwen_native_service.py').is_file())
def test_changed_launcher_or_unrelated_helper_is_preserved(self):
with self.assertRaises(RuntimeError):
installer.patched(self.SOURCE.replace('def ctl_main():', 'def different():'))
with self.assertRaises(RuntimeError):
installer.patched('unrelated launcher')
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
launcher = root / 'qwen_local.py'
launcher.write_text(self.SOURCE)
(root / 'qwen_native_service.py').write_text('unrelated helper')
with self.assertRaises(RuntimeError):
installer.install(launcher)
self.assertEqual(launcher.read_text(), self.SOURCE)
class PreflightTests(unittest.TestCase):
REPORT = {'schema_version': 1, 'configuration_valid': True, 'platform': 'linux',
'bind': '127.0.0.1:18082', 'model': 'fixture', 'authentication_enabled': True,
'engine': 'external', 'tokenizer_validated': True,
'inference_configured': True, 'readiness_checked': False}
def test_cli_dispatch_and_incompatible_flags(self):
with patch.object(client, 'check_config', return_value={'fixture': True}) as check:
with contextlib.redirect_stdout(io.StringIO()) as output:
client.main(['check-config', '--binary', '/b', '--config', '/c', '--working-dir', '/d'])
self.assertEqual(json.loads(output.getvalue()), {'fixture': True})
check.assert_called_once_with('rnr5090', '/b', '/c', '/d')
for args in [['check-config'], ['status', '--binary', '/b'],
['check-config', '--binary', '/b', '--config', '/c', '--working-dir', '/d', '--unit', 'leleka-api.service']]:
with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
client.main(args)
def test_report_is_filtered_and_does_not_claim_readiness(self):
calls = []
def runner(host, arguments):
calls.append((host, arguments))
return json.dumps({**self.REPORT, 'secret': 'do-not-echo'})
report = client.check_config('rnr5090', '/srv/bin', '/srv/config', '/srv/work', runner=runner)
self.assertEqual(report['configuration'], self.REPORT)
self.assertFalse(report['connection_changed'])
self.assertEqual(report['model_readiness'], 'not_checked')
self.assertEqual(len(calls), 1)
self.assertNotIn('systemctl', calls[0][1])
def test_invalid_selectors_are_rejected_before_transport(self):
def forbidden(*args):
self.fail('invalid selector reached SSH')
for path in ['relative', '/srv/line\nbreak', '/srv/zero\0byte', '/srv/\x7f']:
with self.assertRaises(ValueError):
client.check_config('rnr5090', path, '/c', '/d', runner=forbidden)
with self.assertRaises(ValueError):
client.check_config('-oBad', '/b', '/c', '/d', runner=forbidden)
def test_remote_shell_preserves_paths_and_does_not_expand_them(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
working = root / "work space ' $HOME `false`"
working.mkdir()
binary = working / 'candidate " $(touch INJECTED)'
config = working / 'config "; touch INJECTED; "'
config.write_text('fixture')
output = json.dumps(self.REPORT)
binary.write_text(f'#!{sys.executable}\nimport os,sys\n'
f'assert os.path.samefile(os.getcwd(), {str(working)!r})\n'
f'assert sys.argv[1:] == ["check-config", "--config", {str(config)!r}]\n'
f'print({output!r})\n')
binary.chmod(0o700)
def runner(host, arguments):
return subprocess.check_output(['sh', '-c', shlex.join(arguments)], text=True, timeout=5)
client.check_config('fixture', str(binary), str(config), str(working), runner=runner)
self.assertFalse((working / 'INJECTED').exists())
def test_bad_responses_and_failures_never_echo_remote_text(self):
secret = 'remote-private-marker'
bad = [secret, secret * 7000, '[]', '{}',
json.dumps({**self.REPORT, 'readiness_checked': True}),
json.dumps({**self.REPORT, 'inference_configured': False}),
json.dumps({**self.REPORT, 'schema_version': True}),
json.dumps({**self.REPORT, 'bind': secret}),
json.dumps({**self.REPORT, 'model': secret + '\n'})]
for response in bad:
with self.assertRaises(RuntimeError) as raised:
client.check_config('fixture', '/b', '/c', '/d', runner=lambda *_: response)
self.assertNotIn(secret, str(raised.exception))
def fail(*_):
raise RuntimeError(secret)
with self.assertRaises(RuntimeError) as raised:
client.check_config('fixture', '/b', '/c', '/d', runner=fail)
self.assertNotIn(secret, str(raised.exception))
def test_ssh_transport_caps_output_and_suppresses_stderr(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / 'ssh'
def script(body):
path.write_text(f'#!{sys.executable}\nimport sys\n' + body)
path.chmod(0o700)
with patch.dict(os.environ, {'PATH': directory}):
script('print("ok")\n')
self.assertEqual(client.ssh_check('fixture', ['true']), 'ok\n')
for body in ['print("x" * 70000)\n',
'print("secret-transport-marker", file=sys.stderr)\nsys.exit(1)\n',
'sys.stdout.buffer.write(bytes([255]))\n']:
script(body)
with self.assertRaises(RuntimeError) as raised:
client.ssh_check('fixture', ['true'])
self.assertNotIn('secret-transport-marker', str(raised.exception))
script('print("ok")\n')
with patch.object(client.time, 'monotonic', side_effect=[0, 31]):
with self.assertRaises(RuntimeError):
client.ssh_check('fixture', ['true'])
if __name__ == '__main__':
unittest.main()