sh2/d2ypp2/tests/test_control_plane_services.py
eric 9888f1daad Harden YouTube unmanned live stack and hide advanced console panels.
Fix Pro config SSOT, event FSM, FFmpeg error tiers, relay heartbeat, and ingest auth while keeping relay snapshot, quality guard, and event hub hidden in the UI.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-23 06:31:31 -05:00

458 lines
21 KiB
Python

from __future__ import annotations
import unittest
import asyncio
import tempfile
from pathlib import Path
from unittest.mock import AsyncMock, patch
import yaml
from src.control_plane import (
SERVICE_SPECS,
_normalize_shellcrash_yaml,
deployment_report,
network_iface_stats,
neko_instance_action,
stack_summary,
)
class ControlPlaneServiceTests(unittest.TestCase):
def test_service_registry_includes_required_modules(self) -> None:
ids = {spec.service_id for spec in SERVICE_SPECS}
self.assertTrue(
{
"mitmproxy",
"vscode_server",
"uptime_kuma",
"pulseaudio",
"kmscube",
"openclaw",
"homeassistant",
"frigate",
"wol",
"ntfy",
"coturn",
}.issubset(ids)
)
def test_stack_summary_exposes_new_quick_links(self) -> None:
env = {"HOSTNAME_ALIAS": "live", "NEKO_ACCESS_MODE": "remote", "NEKO_WIREGUARD_HOST": "10.88.0.2"}
with patch("src.control_plane.load_stack_env", return_value=env):
with patch("src.control_plane.local_ips", return_value=["192.168.2.20"]):
summary = stack_summary()
links = summary["quick_links"]
for key in (
"mitmproxy",
"vscode_server",
"uptime_kuma",
"pulseaudio_tcp",
"openclaw",
"studio",
"youtube_events",
"homeassistant",
"frigate",
"wol",
"ntfy",
"coturn_turn",
"coturn_turns",
"neko_browser",
"neko_browser_1",
"neko_browser_2",
"neko_browser_mdns_1",
"neko_browser_lan_1",
"neko_browser_wireguard_1",
):
self.assertIn(key, links)
neko_instances = summary["neko_instances"]
self.assertEqual([item["id"] for item in neko_instances], [1, 2])
self.assertEqual(links["neko_browser"], links["neko_browser_1"])
self.assertEqual(links["neko_browser"], "http://10.88.0.2:9200")
self.assertEqual(links["neko_browser_wireguard_1"], "http://10.88.0.2:9200")
self.assertEqual(links["neko_browser_mdns_1"], "http://live.local:9200")
self.assertEqual(links["homeassistant"], "http://live.local:8123")
self.assertEqual(links["frigate"], "http://live.local:5001")
self.assertEqual(links["ntfy"], "http://live.local:8089")
self.assertEqual(links["coturn_turn"], "turn:live.local:3478?transport=udp")
self.assertEqual(links["coturn_turns"], "turns:live.local:5349?transport=tcp")
self.assertTrue(links["wol"].endswith("/?view=studio"))
self.assertTrue(links["youtube_events"].endswith("/youtube-events"))
def test_stack_summary_keeps_neko_on_lan_until_remote_mode_selected(self) -> None:
env = {"HOSTNAME_ALIAS": "live", "NEKO_WIREGUARD_HOST": "10.88.0.2"}
with patch("src.control_plane.load_stack_env", return_value=env):
with patch("src.control_plane.local_ips", return_value=["192.168.2.20"]):
summary = stack_summary()
links = summary["quick_links"]
self.assertNotIn("neko_browser_wireguard_1", links)
self.assertEqual(links["neko_browser"], "http://live.local:9200")
self.assertEqual(links["neko_browser_lan_1"], "http://192.168.2.20:9200")
def test_stack_summary_exposes_pro_neko_links_when_configured(self) -> None:
with patch("src.control_plane.load_stack_env", return_value={"HOSTNAME_ALIAS": "live", "NEKO_INSTANCE_COUNT": "4"}):
summary = stack_summary()
links = summary["quick_links"]
self.assertIn("neko_browser_3", links)
self.assertIn("neko_browser_4", links)
self.assertEqual([item["id"] for item in summary["neko_instances"]], [1, 2, 3, 4])
def test_neko_instance_status_reports_single_container_state(self) -> None:
runner = AsyncMock(
side_effect=[
(0, "running"),
(0, "0.0.0.0:9201\n[::]:9201"),
(0, "running"),
(0, "0.0.0.0:9201\n[::]:9201"),
]
)
with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}):
with patch("src.control_plane.shutil.which", return_value="/usr/bin/docker"):
with patch("src.control_plane._run_command", runner):
result = asyncio.run(neko_instance_action(2, "status"))
self.assertEqual(result["container"], "live-neko-2")
self.assertTrue(result["exists"])
self.assertTrue(result["running"])
self.assertTrue(result["ready"])
self.assertTrue(result["port_published"])
self.assertEqual(result["http_port"], 9201)
self.assertEqual(result["status"], "running")
self.assertIn("Neko 2", result["message"])
self.assertEqual(runner.await_count, 4)
def test_neko_instance_delete_removes_container_but_preserves_profile(self) -> None:
runner = AsyncMock(
side_effect=[
(0, "running"),
(0, "0.0.0.0:9201"),
(0, "live-neko-2"),
(0, "message=Neko WebRTC config reapplied (1 browser instances)"),
(1, "Error: No such object: live-neko-2"),
]
)
with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}):
with patch("src.control_plane.shutil.which", return_value="/usr/bin/docker"):
with patch("src.control_plane.SERVICE_CTL") as service_ctl:
service_ctl.is_file.return_value = True
with patch("src.control_plane.write_stack_env_value") as write_env:
with patch("src.control_plane._run_command", runner):
result = asyncio.run(neko_instance_action(2, "delete"))
write_env.assert_called_once_with("NEKO_INSTANCE_COUNT", "1")
self.assertEqual(result["container"], "live-neko-2")
self.assertEqual(result["configured_count"], 1)
self.assertFalse(result["exists"])
self.assertFalse(result["running"])
self.assertTrue(result["profile_preserved"])
self.assertIn("配置数据已保留", result["message"])
def test_neko_instance_delete_rejects_non_last_instance(self) -> None:
runner = AsyncMock(
side_effect=[
(0, "running"),
(0, "0.0.0.0:9200"),
]
)
with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "3"}):
with patch("src.control_plane.shutil.which", return_value="/usr/bin/docker"):
with patch("src.control_plane._run_command", runner):
with self.assertRaisesRegex(ValueError, "最后一个"):
asyncio.run(neko_instance_action(1, "delete"))
def test_neko_instance_start_rebuilds_missing_container(self) -> None:
runner = AsyncMock(
side_effect=[
(1, "Error: No such object: live-neko-1"),
(0, "message=Neko stack started"),
(0, "running"),
(0, "0.0.0.0:9200"),
]
)
with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}):
with patch("src.control_plane.shutil.which", return_value="/usr/bin/docker"):
with patch("src.control_plane.SERVICE_CTL") as service_ctl:
service_ctl.is_file.return_value = True
with patch("src.control_plane._run_command", runner):
result = asyncio.run(neko_instance_action(1, "start"))
self.assertEqual(result["container"], "live-neko-1")
self.assertTrue(result["exists"])
self.assertTrue(result["running"])
self.assertTrue(result["ready"])
self.assertIn("重建", result["message"])
def test_neko_instance_start_reconfigures_existing_stopped_container(self) -> None:
runner = AsyncMock(
side_effect=[
(0, "exited"),
(0, "0.0.0.0:9200"),
(0, "message=Neko WebRTC config reapplied"),
(0, "running"),
(0, "0.0.0.0:9200"),
]
)
with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}):
with patch("src.control_plane.shutil.which", return_value="/usr/bin/docker"):
with patch("src.control_plane._run_command", runner):
result = asyncio.run(neko_instance_action(1, "start"))
self.assertEqual(result["container"], "live-neko-1")
self.assertTrue(result["running"])
self.assertTrue(result["ready"])
self.assertIn("reconfigured", result["message"])
reconfigure_cmd = runner.await_args_list[2].args[0]
self.assertEqual(reconfigure_cmd[-2:], ["neko", "reconfigure"])
self.assertNotEqual(reconfigure_cmd[:2], ["docker", "start"])
def test_neko_instance_start_reconfigures_running_container_without_published_port(self) -> None:
runner = AsyncMock(
side_effect=[
(0, "running"),
(0, ""),
(0, "message=Neko WebRTC config reapplied"),
(0, "running"),
(0, "0.0.0.0:9201"),
]
)
with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}):
with patch("src.control_plane.shutil.which", return_value="/usr/bin/docker"):
with patch("src.control_plane._run_command", runner):
result = asyncio.run(neko_instance_action(2, "start"))
self.assertEqual(result["container"], "live-neko-2")
self.assertTrue(result["running"])
self.assertTrue(result["ready"])
self.assertTrue(result["port_published"])
self.assertIn("reconfigured", result["message"])
reconfigure_cmd = runner.await_args_list[2].args[0]
self.assertEqual(reconfigure_cmd[-2:], ["neko", "reconfigure"])
def test_neko_instance_restart_reconfigures_existing_container(self) -> None:
runner = AsyncMock(
side_effect=[
(0, "running"),
(0, "0.0.0.0:9200"),
(0, "message=Neko WebRTC config reapplied"),
(0, "running"),
(0, "0.0.0.0:9200"),
]
)
with patch("src.control_plane.load_stack_env", return_value={"NEKO_INSTANCE_COUNT": "2"}):
with patch("src.control_plane.shutil.which", return_value="/usr/bin/docker"):
with patch("src.control_plane._run_command", runner):
result = asyncio.run(neko_instance_action(1, "restart"))
self.assertEqual(result["container"], "live-neko-1")
self.assertTrue(result["running"])
self.assertTrue(result["ready"])
self.assertIn("reconfigured", result["message"])
reconfigure_cmd = runner.await_args_list[2].args[0]
self.assertEqual(reconfigure_cmd[-2:], ["neko", "reconfigure"])
self.assertNotEqual(reconfigure_cmd[:2], ["docker", "restart"])
def test_network_stats_expose_realtime_and_total_bandwidth_fields(self) -> None:
stats = network_iface_stats()
for key in ("interfaces", "total_rx_bytes", "total_tx_bytes", "total_rx_bps", "total_tx_bps"):
self.assertIn(key, stats)
for iface in stats["interfaces"]:
self.assertIn("rx_bps", iface)
self.assertIn("tx_bps", iface)
self.assertIn("sample_interval_seconds", iface)
def test_shellcrash_manual_config_without_default_node_is_still_applicable(self) -> None:
content = """
proxies:
- name: manual-node
type: http
server: 127.0.0.1
port: 8080
proxy-groups:
- name: PROXY
type: select
proxies:
- manual-node
rules:
- MATCH,PROXY
"""
normalized, meta = _normalize_shellcrash_yaml(content, "missing-default-node")
data = yaml.safe_load(normalized)
self.assertFalse(meta["target_node_found"])
self.assertIn("Target proxy node not found", meta["warning"])
self.assertEqual(data["proxy-groups"][0]["proxies"], ["manual-node"])
self.assertTrue(data["allow-lan"])
self.assertEqual(data["mixed-port"], 7890)
self.assertEqual(data["external-controller"], "0.0.0.0:9999")
self.assertEqual(data["external-ui"], "ui")
self.assertEqual(data["rules"][0], "DOMAIN,live.local,DIRECT")
self.assertIn("DOMAIN-SUFFIX,local,DIRECT", data["rules"])
self.assertIn("IP-CIDR,192.168.0.0/16,DIRECT,no-resolve", data["rules"])
self.assertEqual(data["rules"][-1], "MATCH,PROXY")
def test_shellcrash_normalize_adds_neko_dedicated_listener(self) -> None:
content = """
proxies:
- name: proxycheap
type: socks5
server: 23.188.208.5
port: 12441
- name: 5d723acc-singbox_tuic3
type: tuic
server: vpn.nomadro.live
port: 11090
proxy-groups:
- name: dialer
type: select
proxies:
- 5d723acc-singbox_tuic3
- name: 🚀 节点选择
type: select
proxies:
- proxycheap
- 5d723acc-singbox_tuic3
rules:
- MATCH,🚀 节点选择
"""
normalized, meta = _normalize_shellcrash_yaml(content, "5d723acc-singbox_tuic3")
data = yaml.safe_load(normalized)
listeners = data.get("listeners") or []
self.assertTrue(meta["neko_listener"]["listener_applied"])
self.assertEqual(meta["neko_listener"]["port"], 7894)
self.assertEqual(meta["neko_listener"]["node"], "proxycheap")
self.assertEqual(len(listeners), 1)
self.assertEqual(listeners[0]["name"], "neko-mixed")
self.assertEqual(listeners[0]["port"], 7894)
self.assertEqual(listeners[0]["proxy"], "proxycheap")
self.assertEqual(listeners[0]["listen"], "0.0.0.0")
def test_shellcrash_service_controller_syncs_runtime_config_before_start(self) -> None:
script = Path("scripts/linux/service_ctl.sh").read_text(encoding="utf-8")
common = Path("scripts/linux/lib/common.sh").read_text(encoding="utf-8")
self.assertIn("shellcrash_sync_runtime_config()", script)
self.assertIn("shellcrash_prepare_runtime()", script)
self.assertIn('install -m 0644 "$src" "$dst"', script)
self.assertIn('local dst="/tmp/ShellCrash/config.yaml"', script)
self.assertIn("ShellCrash config.yaml is missing; save/apply a YAML profile first", script)
self.assertIn('shellcrash_sync_runtime_config "$SHELLCRASH_DIR/yamls/config.yaml"', script)
self.assertIn("ShellCrash CrashCore is missing; check DNS/network and rerun apply", script)
self.assertIn("shellcrash_systemd_start()", script)
self.assertIn("systemctl start shellcrash.service", script)
self.assertIn("systemctl disable shellcrash.service", script)
self.assertIn("shellcrash_should_autostart_on_direct_fail()", script)
self.assertIn("systemctl enable --now shellcrash.service", script)
self.assertIn("SHELLCRASH_AUTOSTART_ON_DIRECT_FAIL", script)
self.assertIn("SHELLCRASH_AUTO_START_ON_WEB_PANEL", script)
self.assertIn("shellcrash_systemd_restart", script)
self.assertIn("system_direct_global_ready()", common)
self.assertIn("shellcrash_should_autostart_on_direct_fail()", common)
self.assertIn("SHELLCRASH_AUTOSTART", common)
self.assertIn("SHELLCRASH_DOCKER_CIDR", common)
self.assertIn("ENABLE_NEKO_BROWSER_PROXY", common)
self.assertIn("NEKO_SHELLCRASH_PROXY_PORT", common)
self.assertIn("SHELLCRASH_NEKO_PROXY_NODE", common)
self.assertIn("service_homeassistant_start()", script)
self.assertIn("service_frigate_start()", script)
self.assertIn("service_frigate_auto()", script)
self.assertIn("service_wol_wake()", script)
self.assertIn("service_wol_stop()", script)
self.assertIn("service_ntfy_start()", script)
self.assertIn("service_ntfy_stop()", script)
self.assertIn("service_coturn_start()", script)
self.assertIn("coturn_secret_ready()", script)
self.assertIn("HOMEASSISTANT_AUTOSTART", common)
self.assertIn("prepare_coturn()", common)
self.assertIn("configure_host_dns()", common)
self.assertIn("configure_sudoers", common)
self.assertIn("User=root", common)
self.assertIn("Group=root", common)
self.assertNotIn("CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_RAW", common)
self.assertIn("ensure_project_full_access()", common)
self.assertIn("prepare_homeassistant()", common)
self.assertIn("prepare_frigate()", common)
self.assertIn("prepare_ntfy()", common)
self.assertIn("install_frigate_usb_watch_service()", common)
def test_deployment_report_marks_live_local_ready_when_checks_pass(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
base_dir = Path(tmp)
console_index = base_dir / "web-console" / "out" / "index.html"
console_index.parent.mkdir(parents=True, exist_ok=True)
console_index.write_text("ok", encoding="utf-8")
stack_env = base_dir / "config" / "system-stack.env"
stack_env.parent.mkdir(parents=True, exist_ok=True)
stack_env.write_text("PORT=8001\nENABLE_LIVE_EDGE_PROXY=1\nENABLE_MDNS=1\n", encoding="utf-8")
def probe(url: str, timeout: float = 2.5) -> dict[str, object]:
return {
"reachable": True,
"http_code": 200,
"latency_ms": 3.1,
"error": "",
}
with patch("src.control_plane.BASE_DIR", base_dir):
with patch("src.control_plane.STACK_ENV", stack_env):
with patch("src.control_plane.load_stack_env", return_value={
"PORT": "8001",
"ENABLE_LIVE_EDGE_PROXY": "1",
"ENABLE_MDNS": "1",
}):
with patch("src.control_plane.stack_summary", return_value={
"hostname": "live",
"mdns_host": "live.local",
"ips": ["192.168.1.10"],
}):
with patch("src.control_plane._probe_http_get", side_effect=probe):
with patch("src.control_plane._resolve_host_ipv4s", return_value=["192.168.1.10"]):
report = deployment_report()
self.assertTrue(report["ready"])
ids = {item["id"] for item in report["checks"]}
self.assertIn("api_loopback", ids)
self.assertIn("edge_loopback", ids)
self.assertIn("mdns_edge", ids)
self.assertEqual(report["urls"]["mdns_root"], "http://live.local/")
def test_deployment_report_explains_edge_and_mdns_failures(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
base_dir = Path(tmp)
console_index = base_dir / "web-console" / "out" / "index.html"
console_index.parent.mkdir(parents=True, exist_ok=True)
console_index.write_text("ok", encoding="utf-8")
stack_env = base_dir / "config" / "system-stack.env"
stack_env.parent.mkdir(parents=True, exist_ok=True)
stack_env.write_text("PORT=8001\nENABLE_LIVE_EDGE_PROXY=1\nENABLE_MDNS=1\n", encoding="utf-8")
def probe(url: str, timeout: float = 2.5) -> dict[str, object]:
if "127.0.0.1:8001/health" in url:
return {"reachable": True, "http_code": 200, "latency_ms": 2.0, "error": ""}
return {"reachable": False, "http_code": 0, "latency_ms": 2.0, "error": "connection refused"}
with patch("src.control_plane.BASE_DIR", base_dir):
with patch("src.control_plane.STACK_ENV", stack_env):
with patch("src.control_plane.load_stack_env", return_value={
"PORT": "8001",
"ENABLE_LIVE_EDGE_PROXY": "1",
"ENABLE_MDNS": "1",
}):
with patch("src.control_plane.stack_summary", return_value={
"hostname": "live",
"mdns_host": "live.local",
"ips": ["192.168.1.10"],
}):
with patch("src.control_plane._probe_http_get", side_effect=probe):
with patch("src.control_plane._resolve_host_ipv4s", return_value=[]):
report = deployment_report()
self.assertFalse(report["ready"])
joined = "\n".join(report["hints"])
self.assertIn("live.local does not resolve locally", joined)
self.assertIn("reverse proxy is unhealthy", joined)
if __name__ == "__main__":
unittest.main()