#!/usr/bin/env python3 """Native controller behavior checks; no GPU or user endpoint is contacted.""" import contextlib import importlib.util import io import json import os from http.server import BaseHTTPRequestHandler, HTTPServer from pathlib import Path import tempfile import threading import unittest from unittest.mock import patch import qwen_native_api as client def load(name): spec = importlib.util.spec_from_file_location(name, Path(__file__).with_name(name + '.py')) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module installer = load('install-qwen-native-api') service_installer = load('install-qwen-native-service') TARGET = {'backend': 'strata-native', 'url': 'http://127.0.0.1:18084'} def state(draining=False, jobs=0): return dict(draining=draining, drained=draining and jobs == 0, requests_in_flight=0, generation_jobs=jobs, worker='ready') class ControlTests(unittest.TestCase): def test_identity_precedes_mutation_and_ready_false_allows_resume(self): calls = [] def transport(url, method, path, token): calls.append((method, path)) return {'service': 'strata-control', 'ready': False} if path == '/status' else state() result = client.control('resume', TARGET, None, transport=transport) self.assertFalse(result['connection_changed']) self.assertEqual(calls, [('GET', '/status'), ('POST', '/admin/resume')]) calls.clear() def wrong(*args): calls.append(args[2]) return {'service': 'other', 'ready': True} with self.assertRaisesRegex(RuntimeError, 'not a native'): client.control('drain', TARGET, None, transport=wrong) self.assertEqual(calls, ['/status']) def test_invalid_target_and_wait_never_send_or_read_key(self): def unexpected(*args, **kwargs): self.fail('Invalid input reached I/O') for url in ['https://127.0.0.1', 'http://remote', 'http://user@localhost', 'http://127.0.0.1/path', 'http://localhost?q=x', 'http://127.0.0.1:0', 'http://127.0.0.1:65536', 'http://localhost\n']: with self.subTest(url=url), self.assertRaises(ValueError): client.control('drain', dict(TARGET, url=url, key_file='private'), unexpected, transport=unexpected) for wait in [-1, float('nan'), float('inf'), 3601]: with self.assertRaises(ValueError): client.control('drain', TARGET, unexpected, wait=wait, transport=unexpected) with self.assertRaises(ValueError): client.control('metrics', TARGET, unexpected, wait=1, transport=unexpected) with self.assertRaises(ValueError): client.control('drain', dict(TARGET, backend='strata'), unexpected, transport=unexpected) self.assertEqual(client.endpoint('http://localhost:99'), ('127.0.0.1', 99)) self.assertEqual(client.endpoint('http://[::1]:99'), ('::1', 99)) def test_wait_completion_timeout_and_concurrent_resume(self): for ending in ['complete', 'timeout', 'resume']: with self.subTest(ending=ending): calls = [] now = [0] def sleep(seconds): now[0] += seconds def transport(url, method, path, token, **kwargs): calls.append((method, path)) if path == '/status': return {'service': 'strata-control', 'ready': True} if path == '/admin/drain' or ending == 'timeout': return state(True, 1) return state(ending == 'complete') def run(): return client.control('drain', TARGET, None, wait=1, transport=transport, sleep=sleep, clock=lambda: now[0]) if ending == 'complete': self.assertTrue(run()['runtime']['drained']) else: with self.assertRaisesRegex(RuntimeError, 'timed out' if ending == 'timeout' else 'resumed concurrently'): run() self.assertEqual([path for method, path in calls if method == 'POST'], ['/admin/drain']) def test_rejects_inconsistent_lifecycle_and_metrics(self): for invalid in [dict(state(), drained=True), dict(state(True), generation_jobs=1), dict(state(True), worker='starting'), dict(state(), generation_jobs=True)]: with self.assertRaises(RuntimeError): client.lifecycle(invalid) with self.assertRaisesRegex(RuntimeError, 'metrics'): client.control('metrics', TARGET, None, transport=lambda u, m, p, t: {'service': 'strata-control', 'ready': True} if p == '/status' else {'schema_version': 2}) def test_cli_auth_is_not_inherited_for_url_overrides(self): def unexpected(*args): self.fail('Connection or key should not be read') for argv in [['status', '--url', TARGET['url']], ['status', '--no-auth'], ['drain', '--key-file', 'private']]: with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): client.main(argv, connection=unexpected, read_key=unexpected) with patch.object(client, 'control', return_value={}) as control, contextlib.redirect_stdout(io.StringIO()): client.main(['status', '--url', TARGET['url'], '--no-auth'], connection=unexpected, read_key=unexpected) self.assertIsNone(control.call_args.args[1]['key_file']) client.main(['metrics'], connection=lambda: dict(TARGET, key_file='selected'), read_key=unexpected) self.assertEqual(control.call_args.args[1]['key_file'], 'selected') class HttpTests(unittest.TestCase): def test_direct_auth_bounded_json_no_redirect_or_secret_echo(self): token = 'fixture-private-' + 'x' * 32 reply = [200, 'application/json', b'{"ok":true}'] seen = [] class Handler(BaseHTTPRequestHandler): def do_GET(self): seen.append((self.path, self.headers.get('Authorization'))) self.send_response(reply[0]) self.send_header('Content-Type', reply[1]) self.send_header('Content-Length', str(len(reply[2]))) self.send_header('Location', '/redirect-must-not-be-followed') self.end_headers() self.wfile.write(reply[2]) def log_message(self, *_): pass server = HTTPServer(('127.0.0.1', 0), Handler) thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() url = f'http://127.0.0.1:{server.server_port}' try: with patch.dict(os.environ, {'http_proxy': 'http://127.0.0.1:1', 'HTTP_PROXY': 'http://127.0.0.1:1'}): self.assertEqual(client.request(url, 'GET', '/status', token), {'ok': True}) self.assertEqual(seen, [('/status', 'Bearer ' + token)]) for response in [(302, 'application/json', b'{}'), (401, 'application/json', token.encode()), (200, 'text/plain', b'{}'), (200, 'application/json', b'x' * (client.LIMIT + 1)), (200, 'application/json', b'{"x":NaN}'), (200, 'application/json', b'[]'), (200, 'application/json', json.dumps({'echo': token}).encode()), (200, 'application/json', ('{"echo":"' + ''.join(f'\\u{ord(c):04x}' for c in token) + '"}').encode())]: reply[:] = response count = len(seen) with self.assertRaises(RuntimeError) as error: client.request(url, 'GET', '/status', token) self.assertNotIn(token, str(error.exception)) self.assertEqual(len(seen), count + 1) finally: server.shutdown() server.server_close() thread.join() class InstallerTests(unittest.TestCase): SOURCE = '''import argparse, sys HOST = 'fixture' def connection(): return {} def native_key(target): return '' def ctl_main(): parser = argparse.ArgumentParser() sub = parser.add_subparsers(dest='command', required=True) sub.add_parser('status') # Strata Next native Responses integration v1 # Strata Next native bearer file integration v1 ''' def test_install_coexists_both_orders_is_idempotent_and_preserves_connection(self): for order in [(installer, service_installer), (service_installer, installer)]: with tempfile.TemporaryDirectory() as directory, contextlib.redirect_stdout(io.StringIO()): root = Path(directory) launcher = root / 'qwen_local.py' launcher.write_text(self.SOURCE) connection = root / 'connection.json' connection.write_text('{"unchanged":true}') for item in order: item.install(launcher) first = launcher.read_bytes() installer.install(launcher) service_installer.install(launcher) self.assertEqual(launcher.read_bytes(), first) self.assertEqual(connection.read_text(), '{"unchanged":true}') self.assertEqual(len(list(root.glob('*.before-native-api-*'))), 1) self.assertEqual((root / 'qwen_native_api.py').stat().st_mode & 0o777, 0o600) self.assertEqual(first.count(b"sys.argv[1] == 'native-api'"), 1) self.assertEqual(first.count(b"sys.argv[1] == 'native-service'"), 1) def test_unrelated_helper_and_missing_anchor_are_preserved(self): with self.assertRaises(RuntimeError): installer.patched(self.SOURCE.replace('def ctl_main():', 'def other():')) with tempfile.TemporaryDirectory() as directory: root = Path(directory) launcher = root / 'qwen_local.py' launcher.write_text(self.SOURCE) (root / 'qwen_native_api.py').write_text('unrelated') with self.assertRaises(RuntimeError): installer.install(launcher) self.assertEqual(launcher.read_text(), self.SOURCE) if __name__ == '__main__': unittest.main()