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

130 lines
5.7 KiB
Python

#!/usr/bin/env python3
"""Behavior checks for opt-in native service control; never contact a real host."""
import importlib.util
from pathlib import Path
import tempfile
import unittest
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', 'strata-next-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:] == ['--', 'strata-next-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, 'strata-next.service', runner=host)
for bad in ['sshd.service', 'strata-next.service;id', '../strata-next.service', 'strata-next@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', 'strata-next.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', 'strata-next.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', 'strata-next-test.service', runner=host), 'fixture log\n')
self.assertEqual(host.calls[-1][1], ['journalctl', '--user', '--unit=strata-next-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)
if __name__ == '__main__':
unittest.main()