astrbot_plugin_imagestudio/tests/test_route_registry.py

233 行
11 KiB
Python

from __future__ import annotations
import importlib
import tempfile
import unittest
from pathlib import Path
from adapters.astrbot_adapter import (
dispatch_extension_request,
normalize_extension_path,
register_astrbot_runtime,
resolve_route,
runtime_health,
runtime_registration_manifest,
runtime_route_table,
)
from adapters.webui_adapter import get_web_mount_manifest, resolve_web_asset
from backend.route_registry import ROUTES, assert_unique_routes, route_manifest
from backend.services.web_hosting_service import WebHostingService
from core.identity import RequestContext
class RouteRegistryTests(unittest.TestCase):
def test_route_manifest_is_unique_and_contains_core_endpoints(self):
assert_unique_routes()
routes = route_manifest()
keys = {(route["method"], route["endpoint"]) for route in routes}
self.assertIn(("GET", "ui/bootstrap"), keys)
self.assertIn(("GET", "ui/actions"), keys)
self.assertIn(("POST", "nodes/{node_id}/generate"), keys)
self.assertIn(("POST", "profiles/quick-draft/save"), keys)
self.assertIn(("GET", "security/audit-logs"), keys)
self.assertIn(("POST", "api-discovery/probe-provider"), keys)
self.assertIn(("PUT", "material-categories/{category_id}"), keys)
self.assertIn(("GET", "materials/{material_id}"), keys)
self.assertIn(("DELETE", "profiles/{profile_id}/wardrobe/{wardrobe_item_id}"), keys)
self.assertIn(("DELETE", "profiles/{profile_id}/wardrobe/items/{wardrobe_item_id}"), keys)
self.assertIn(("GET", "integrations/private-companion/token"), keys)
self.assertIn(("POST", "integrations/private-companion/token/rotate"), keys)
self.assertIn(("GET", "integrations/logs"), keys)
self.assertIn(("POST", "workflows/{workflow_id}/start"), keys)
self.assertIn(("POST", "workflows/{workflow_id}/cancel"), keys)
self.assertIn(("POST", "workflows/{workflow_id}/archive"), keys)
self.assertIn(("POST", "workflows/{workflow_id}/execute-character"), keys)
self.assertIn(("GET", "nodes/{node_id}/review"), keys)
self.assertIn(("GET", "nodes/{node_id}/dependency-context"), keys)
self.assertIn(("GET", "workflows/{workflow_id}/review"), keys)
self.assertIn(("GET", "review/policy"), keys)
self.assertIn(("POST", "review/policy/validate"), keys)
self.assertIn(("POST", "review/policy/save"), keys)
self.assertIn(("POST", "prompts/expand"), keys)
self.assertIn(("POST", "images/{image_id}/safe-delete"), keys)
self.assertIn(("POST", "nodes/{node_id}/retry"), keys)
self.assertIn(("POST", "nodes/{node_id}/complete"), keys)
self.assertIn(("POST", "nodes/{node_id}/mark-completed"), keys)
self.assertIn(("POST", "materials/{material_id}/re-recognize"), keys)
self.assertIn(("POST", "assets/import-pack"), keys)
self.assertIn(("POST", "profiles/{profile_id}/archive"), keys)
self.assertIn(("POST", "profiles/{profile_id}/wardrobe/items"), keys)
self.assertIn(("GET", "settings/snapshots"), keys)
self.assertIn(("GET", "settings/snapshots/{snapshot_id}"), keys)
self.assertIn(("POST", "settings/rollback"), keys)
self.assertIn(("POST", "storage/migrate"), keys)
self.assertIn(("GET", "media/index"), keys)
self.assertIn(("GET", "media/orphans"), keys)
self.assertIn(("GET", "events/stream"), keys)
self.assertIn(("GET", "costs/usage"), keys)
self.assertIn(("POST", "costs/guard"), keys)
self.assertEqual(len(routes), len(ROUTES))
def test_webui_adapter_manifest_includes_api_routes(self):
manifest = get_web_mount_manifest()
self.assertIn("standalone_web", manifest)
self.assertTrue(any(route["endpoint"] == "dashboard/summary" for route in manifest["api_routes"]))
def test_webui_adapter_resolves_standalone_assets(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
web = root / "web"
assets = web / "assets"
assets.mkdir(parents=True)
(web / "index.html").write_text("<html></html>", encoding="utf-8")
(assets / "app.js").write_text("console.log('ok')", encoding="utf-8")
service = WebHostingService(plugin_page_dir=root / "plugin", standalone_web_dir=web)
index = resolve_web_asset(
"/api/v1/plugins/extensions/astrbot_plugin_imagestudio/web",
service,
)
script = resolve_web_asset(
"/api/v1/plugins/extensions/astrbot_plugin_imagestudio/web/assets/app.js?cache=1",
service,
)
escaped = resolve_web_asset(
"/api/v1/plugins/extensions/astrbot_plugin_imagestudio/web/../config.yaml",
service,
)
self.assertTrue(index["ok"])
self.assertEqual(index["data"]["relative_path"], "index.html")
self.assertEqual(index["data"]["body_base64"], "PGh0bWw-PC9odG1sPg")
self.assertEqual(index["data"]["cache_control"], "public, max-age=300")
self.assertTrue(script["ok"])
self.assertEqual(script["data"]["content_type"], "text/javascript")
self.assertTrue(script["data"]["body_base64"])
self.assertFalse(escaped["ok"])
self.assertEqual(escaped["error_code"], "FORBIDDEN")
def test_route_handlers_are_importable_callables(self):
for route in ROUTES:
module_name, function_name = route.handler.rsplit(".", 1)
module = importlib.import_module(module_name)
handler = getattr(module, function_name)
self.assertTrue(callable(handler), route.handler)
def test_astrbot_adapter_resolves_extension_routes(self):
self.assertEqual(
normalize_extension_path(
"/api/v1/plugins/extensions/astrbot_plugin_imagestudio/nodes/node_001/review?x=1"
),
"nodes/node_001/review",
)
match = resolve_route("GET", "/api/v1/plugins/extensions/astrbot_plugin_imagestudio/nodes/node_001/review")
self.assertIsNotNone(match)
self.assertEqual(match.endpoint, "nodes/{node_id}/review")
self.assertEqual(match.path_params, {"node_id": "node_001"})
self.assertTrue(callable(match.handler))
table = runtime_route_table()
self.assertTrue(any(route["path"].endswith("/dashboard/summary") for route in table))
def test_runtime_registration_manifest_and_health_are_stable(self):
registration = runtime_registration_manifest()
health = runtime_health()
self.assertEqual(registration["plugin_name"], "astrbot_plugin_imagestudio")
self.assertTrue(registration["api_base"].endswith("astrbot_plugin_imagestudio"))
self.assertTrue(registration["web_mounts"][0]["path"].endswith("/web"))
self.assertTrue(health["ok"])
self.assertEqual(health["route_count"], len(ROUTES))
self.assertEqual(health["importable_handlers"], len(ROUTES))
def test_register_astrbot_runtime_calls_host_registration_methods(self):
class FakeRuntime:
def __init__(self):
self.routes = []
self.mounts = []
def register_extension_route(self, **kwargs):
self.routes.append(kwargs)
def register_web_mount(self, **kwargs):
self.mounts.append(kwargs)
runtime = FakeRuntime()
result = register_astrbot_runtime(runtime)
self.assertTrue(result["registered"])
self.assertEqual(result["routes_registered"], len(ROUTES))
self.assertEqual(result["web_mounts_registered"], 1)
self.assertTrue(callable(runtime.routes[0]["handler"]))
self.assertTrue(callable(runtime.mounts[0]["handler"]))
def test_astrbot_adapter_dispatches_pure_route_handlers(self):
ctx = RequestContext.from_astrbot(username="admin", user_id="user_001", permissions={"can_manage_config"})
response = dispatch_extension_request(
ctx,
"GET",
"/api/v1/plugins/extensions/astrbot_plugin_imagestudio/ui/actions",
)
self.assertTrue(response["ok"])
self.assertTrue(any(item["action_id"] == "open_workbench" for item in response["data"]))
missing = dispatch_extension_request(ctx, "GET", "/api/v1/plugins/extensions/astrbot_plugin_imagestudio/nope")
self.assertFalse(missing["ok"])
self.assertEqual(missing["error_code"], "RESOURCE_NOT_FOUND")
def test_astrbot_adapter_dispatches_payload_query_and_path_params(self):
ctx = RequestContext.from_astrbot(username="admin", user_id="user_001", permissions={"can_manage_config"})
settings_routes = importlib.import_module("backend.routes.settings_routes")
original_validate = settings_routes.validate_settings
original_list_snapshots = settings_routes.list_settings_snapshots
original_get_snapshot = settings_routes.get_settings_snapshot
def fake_validate_settings(ctx: RequestContext, payload: dict) -> dict:
return {"ok": True, "data": {"actor_id": ctx.actor_id, "payload": payload}}
def fake_list_settings_snapshots(ctx: RequestContext, query: dict | None = None) -> dict:
return {"ok": True, "data": {"query": query or {}}}
def fake_get_settings_snapshot(ctx: RequestContext, snapshot_id: str) -> dict:
return {"ok": True, "data": {"snapshot_id": snapshot_id}}
settings_routes.validate_settings = fake_validate_settings
settings_routes.list_settings_snapshots = fake_list_settings_snapshots
settings_routes.get_settings_snapshot = fake_get_settings_snapshot
try:
payload_response = dispatch_extension_request(
ctx,
"POST",
"/api/v1/plugins/extensions/astrbot_plugin_imagestudio/settings/validate",
payload={"config": {"database": {"backend": "sqlite"}}},
)
query_response = dispatch_extension_request(
ctx,
"GET",
"/api/v1/plugins/extensions/astrbot_plugin_imagestudio/settings/snapshots",
query={"limit": "3"},
)
path_response = dispatch_extension_request(
ctx,
"GET",
"/api/v1/plugins/extensions/astrbot_plugin_imagestudio/settings/snapshots/cfgsnap_001",
)
finally:
settings_routes.validate_settings = original_validate
settings_routes.list_settings_snapshots = original_list_snapshots
settings_routes.get_settings_snapshot = original_get_snapshot
self.assertEqual(payload_response["data"]["payload"]["config"]["database"]["backend"], "sqlite")
self.assertEqual(query_response["data"]["query"], {"limit": "3"})
self.assertEqual(path_response["data"]["snapshot_id"], "cfgsnap_001")
if __name__ == "__main__":
unittest.main()