feat: import Sea vHost single-server testing release

This commit is contained in:
canglan committed 2026-10-30 08:39:10 +08:00
commit 248badd33e
441 files changed
+63221

No files matched your search

+223
View File
@@ -0,0 +1,223 @@
"""Installer safety/flow tests; no system commands or host provisioning."""
import contextlib
import importlib.util
import io
import json
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch, Mock
spec = importlib.util.spec_from_file_location('install_wizard', Path(__file__).with_name('install-wizard.py'))
wizard = importlib.util.module_from_spec(spec)
spec.loader.exec_module(wizard)
class Answers:
def __init__(self, answers=(), confirmations=()):
self.answers = iter(answers)
self.confirmations = iter(confirmations)
def ask(self, label, default=''):
return next(self.answers)
def confirm(self, label, default=True):
return next(self.confirmations)
def secret(self, label):
return next(self.answers)
def paired():
return {'identity': {'nodeId': 2, 'caPem': 'CA', 'certificate': 'CERT', 'privateKey': 'PRIVATE', 'clientSpki': 'PIN'},
'tenantRoot': '/www/wwwroot/seavHost/vHost', 'address': ':9443',
'brokerSocket': '/run/sea-vhost-panel/broker.sock', 'agentSocket': '/run/sea-vhost/agent.sock'}
class WizardTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
for name in ('CONFIG', 'NODE_CONFIG', 'PANEL_CREDENTIALS', 'PANEL_REGISTRY', 'ENVIRONMENT'):
p = patch.object(wizard, name, self.root / name)
p.start()
self.addCleanup(p.stop)
self.output = io.StringIO()
p = contextlib.redirect_stdout(self.output)
p.__enter__()
self.addCleanup(p.__exit__, None, None, None)
def test_role_conversion_rejected_before_install(self):
for role, values in [('node', {'SEA_CONTROLLER_ONLY': 'true'}), ('controller', {'SEA_NODE_STATELESS': 'true'}),
('combined', {'SEA_CONTROLLER_ONLY': 'true'}), ('controller', {'SEA_ADDR': '127.0.0.1:8080'})]:
with self.subTest(role=role, values=values), self.assertRaises(wizard.InstallError):
wizard.check_role(role, values)
wizard.CONFIG.write_text('{}')
with self.assertRaises(wizard.InstallError):
wizard.check_role('node', {})
def test_existing_roles_allowed(self):
for role, values in [('combined', {'SEA_ADDR': '127.0.0.1:8080'}),
('controller', {'SEA_CONTROLLER_ONLY': 'true'}), ('node', {'SEA_NODE_STATELESS': 'true'})]:
wizard.check_role(role, values)
def test_panel_address_is_loopback_origin_only(self):
for value in ('https://evil.example:8888', 'https://localhost:8888/path', 'http://u:p@127.0.0.1:8888',
'https://127.0.0.1:99999', 'http://127.0.0.1:8888/?redirect=evil', 'file:///etc/passwd'):
with self.subTest(value=value), self.assertRaises(wizard.InstallError):
wizard.panel_url(value)
self.assertEqual(wizard.panel_url('https://127.0.0.1:7812/'), 'https://127.0.0.1:7812')
self.assertEqual(wizard.panel_url('http://[::1]:8888'), 'http://[::1]:8888')
def test_node_pair_identity_and_path(self):
self.assertEqual(wizard.validate_pair(paired()), (2, '/www/wwwroot/seavHost/vHost'))
for update in ({'tenantRoot': '/etc'}, {'tenantRoot': '/www/wwwroot/a/../b'}, {'address': ':22'},
{'address': 'localhost:9443'}, {'agentSocket': '/tmp/agent.sock'}, {'identity': {'nodeId': 1}}):
with self.subTest(update=update), self.assertRaises(wizard.InstallError):
wizard.validate_pair({**paired(), **update})
def test_missing_build_rejected_before_prompts(self):
with patch.object(wizard, 'SOURCE', self.root):
with self.assertRaisesRegex(wizard.InstallError, '安装包不完整'):
wizard.check_build('node')
def test_private_write_never_overwrites(self):
file = self.root / 'credentials.json'
wizard.private_json(file, {'api_key': 'secret'})
with self.assertRaises(FileExistsError):
wizard.private_json(file, {'api_key': 'changed'})
self.assertEqual(json.loads(file.read_text())['api_key'], 'secret')
if os.name == 'posix':
self.assertEqual(file.stat().st_mode & 0o777, 0o600)
def test_secret_prompt_and_credentials_not_printed(self):
key = 'sensitive-test-key-never-print'
with patch.object(wizard, 'detect_panel_url', return_value='https://127.0.0.1:7812'):
creds = wizard.credentials(Answers(['https://127.0.0.1:7812', key], [True]))
self.assertEqual(creds['api_key'], key)
self.assertTrue(creds['tls_insecure'])
self.assertNotIn(key, self.output.getvalue())
def test_node_flow_stages_credentials_and_cleans_even_on_failure(self):
# Real files, mocked privileged subprocess only. Assert no key in argv.
config = self.root / 'pair.json'
config.write_text(json.dumps(paired()))
creds = {'version': 1, 'url': 'https://127.0.0.1:7812', 'api_key': 'NEVER-PRINT-OR-ARGV', 'tls_insecure': True}
real_directory = tempfile.TemporaryDirectory
staged = []
def temporary_directory(**kwargs):
return real_directory(prefix=kwargs['prefix'], dir=self.root)
def command(args, **kwargs):
stage_pair, stage_creds = Path(args[-2]), Path(args[-1])
self.assertEqual(json.loads(stage_pair.read_text()), paired())
self.assertEqual(json.loads(stage_creds.read_text()), creds)
self.assertNotIn(creds['api_key'], ' '.join(str(a) for a in args))
staged.extend([stage_pair, stage_creds])
raise subprocess.CalledProcessError(2, args)
with patch.object(Path, 'is_dir', return_value=True), patch.object(Path, 'is_file', return_value=True), \
patch.object(wizard, 'credentials', return_value=creds), \
patch.object(wizard.os, 'fchmod', create=True), \
patch.object(wizard.tempfile, 'TemporaryDirectory', side_effect=temporary_directory), \
patch.object(wizard, 'run', side_effect=command), self.assertRaises(subprocess.CalledProcessError):
wizard.install_node(Answers([str(config)], [True]))
self.assertEqual(len(staged), 2)
self.assertTrue(all(not p.exists() for p in staged))
self.assertNotIn(creds['api_key'], self.output.getvalue())
def test_controller_uses_legacy_noninteractive_then_starts_services(self):
with patch.object(wizard, 'nginx_plan', return_value=None), patch.object(wizard, 'run') as command, \
patch.object(wizard, 'wait_services') as ready, patch.object(wizard, 'wait_api') as api_ready, patch.object(wizard, 'environment', return_value={'SEA_SETUP_TOKEN': 'install-token'}):
self.assertTrue(wizard.install_controller(Answers(confirmations=[True]), 'controller', {}))
self.assertEqual(command.call_args_list[0].args[0][-1], '--non-interactive')
self.assertEqual(command.call_args_list[2].args[0], ['systemctl', 'restart', 'sea-vhost-api'])
ready.assert_called_once_with(['sea-vhost-api'])
api_ready.assert_called_once_with({})
self.assertIn('install-token', self.output.getvalue())
def test_cancel_leaves_system_untouched(self):
with patch.object(wizard, 'nginx_plan', return_value=None), patch.object(wizard, 'run') as command:
self.assertFalse(wizard.install_controller(Answers(confirmations=[False]), 'controller', {}))
command.assert_not_called()
def test_cancel_node_upgrade_preserves_installed_config_permissions(self):
wizard.NODE_CONFIG.write_text(json.dumps(paired()))
with patch.object(Path, 'is_dir', return_value=True), patch.object(Path, 'is_file', return_value=True), \
patch.object(wizard, 'credentials', return_value={'url': 'https://127.0.0.1:7812'}), \
patch.object(wizard.os, 'fchmod', create=True) as chmod, patch.object(wizard, 'run') as command:
self.assertFalse(wizard.install_node(Answers([str(wizard.NODE_CONFIG)], [False])))
chmod.assert_not_called()
command.assert_not_called()
self.assertEqual(json.loads(wizard.NODE_CONFIG.read_text()), paired())
def test_nginx_failed_check_restores_existing_config(self):
file = self.root / 'console.conf'
file.write_bytes(b'previous')
plan = {'existing': False, 'target': file, 'text': 'replacement', 'nginx': '/test/nginx', 'reload': ['nginx', '-s', 'reload']}
with patch.object(wizard.os, 'fchmod', create=True), patch.object(wizard, 'run', side_effect=subprocess.CalledProcessError(1, ['nginx'])), \
patch.object(wizard.subprocess, 'run'):
with self.assertRaises(wizard.InstallError):
wizard.apply_nginx(plan)
self.assertEqual(file.read_bytes(), b'previous')
self.assertEqual(len(list(self.root.glob('console.conf.*.bak'))), 1)
def test_nginx_failed_reload_removes_new_config(self):
file = self.root / 'console.conf'
plan = {'existing': False, 'target': file, 'text': 'replacement', 'nginx': '/test/nginx', 'reload': ['nginx', '-s', 'reload']}
with patch.object(wizard.os, 'fchmod', create=True), \
patch.object(wizard, 'run', side_effect=[Mock(), subprocess.CalledProcessError(1, ['nginx'])]), \
patch.object(wizard.subprocess, 'run'):
with self.assertRaises(wizard.InstallError):
wizard.apply_nginx(plan)
self.assertFalse(file.exists())
def test_nginx_successful_atomic_write(self):
file = self.root / 'console.conf'
plan = {'existing': False, 'target': file, 'text': 'new config', 'nginx': '/test/nginx', 'reload': ['nginx', '-s', 'reload']}
with patch.object(wizard.os, 'fchmod', create=True), patch.object(wizard, 'run') as command:
wizard.apply_nginx(plan)
self.assertEqual(command.call_count, 2)
self.assertEqual(file.read_text(), 'new config')
self.assertFalse(list(self.root.glob('.sea-vhost-*')))
def test_runtime_readiness_failure_is_actionable(self):
with patch.object(wizard.subprocess, 'run', return_value=Mock(returncode=1)), patch.object(wizard.time, 'sleep'):
with self.assertRaisesRegex(wizard.InstallError, 'journalctl'):
wizard.wait_services(['sea-vhost-node'], attempts=2)
def test_runtime_readiness_requires_stable_active_service(self):
with patch.object(wizard.subprocess, 'run', side_effect=[Mock(returncode=0), Mock(returncode=1), Mock(returncode=0), Mock(returncode=0)]) as command, \
patch.object(wizard.time, 'sleep'):
wizard.wait_services(['sea-vhost-node'], attempts=4)
self.assertEqual(command.call_count, 4)
def test_api_readiness_does_not_accept_only_active_systemd(self):
with patch.object(wizard.time, 'monotonic', side_effect=[0, 1]):
with self.assertRaisesRegex(wizard.InstallError, 'API 健康检查未通过'):
wizard.wait_api({}, timeout=0)
def test_api_readiness_retries_connection_refused(self):
opener = Mock()
response = Mock(status=200)
response.read.return_value = b'{"status":"setup_required"}'
context = Mock()
context.__enter__ = Mock(return_value=response)
context.__exit__ = Mock(return_value=False)
opener.open.side_effect = [ConnectionRefusedError(), context]
with patch.object(wizard.urllib.request, 'build_opener', return_value=opener), patch.object(wizard.time, 'sleep'):
wizard.wait_api({})
self.assertEqual(opener.open.call_count, 2)
def test_domain_injection_rejected(self):
for value in ('example.com; root /etc;', 'a b.example.com', '*.example.com', 'https://example.com', 'a..example.com'):
self.assertFalse(wizard.valid_domain(value))
self.assertTrue(wizard.valid_domain('host.ser888.cn'))
if __name__ == '__main__':
unittest.main()