astrbot_plugin_imagestudio/tests/test_plugin_entrypoint.py

199 行
7.3 KiB
Python

from __future__ import annotations
import asyncio
import tempfile
import unittest
from pathlib import Path
from backend.route_registry import ROUTES
from core.identity import RequestContext
from database.db_helper import Database, DatabaseSettings, SqliteSettings
from database.db_helper import load_database_settings, set_runtime_config_overrides
from main import (
Main,
PLUGIN_NAME,
apply_astrbot_config_overrides,
dispatch_bridge_request,
dispatch_web_request,
get_plugin_manifest,
get_runtime_health,
initialize_runtime_database,
register_bridge_api,
register_plugin,
)
class PluginEntrypointTests(unittest.TestCase):
def test_plugin_manifest_exposes_astrbot_mounts(self):
manifest = get_plugin_manifest()
self.assertEqual(manifest["plugin_name"], PLUGIN_NAME)
self.assertTrue(manifest["api_base"].endswith("astrbot_plugin_imagestudio"))
self.assertTrue(manifest["contract_url"].endswith("/contract"))
self.assertIn("web", manifest)
self.assertTrue(any(route["endpoint"] == "dashboard/summary" for route in manifest["routes"]))
self.assertTrue(manifest["runtime"]["health"]["ok"])
self.assertEqual(manifest["health"]["route_count"], len(ROUTES))
def test_dispatch_web_request_delegates_to_adapter(self):
ctx = RequestContext.from_astrbot(username="admin", user_id="user_001")
response = dispatch_web_request(
ctx,
"GET",
"/api/v1/plugins/extensions/astrbot_plugin_imagestudio/ui/bootstrap",
)
self.assertTrue(response["ok"])
self.assertEqual(response["data"]["plugin_name"], PLUGIN_NAME)
def test_register_plugin_delegates_to_runtime_registration(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_plugin(runtime)
self.assertTrue(result["registered"])
self.assertEqual(len(runtime.routes), len(ROUTES))
self.assertEqual(len(runtime.mounts), 1)
self.assertFalse(result["bridge_api"]["registered"])
self.assertTrue(get_runtime_health()["ok"])
def test_register_bridge_api_registers_astrbot_web_routes(self):
class FakeRuntime:
def __init__(self):
self.web_apis = []
def register_web_api(self, path, handler, methods=None):
self.web_apis.append({"path": path, "handler": handler, "methods": methods or []})
runtime = FakeRuntime()
result = register_bridge_api(runtime)
self.assertTrue(result["registered"])
self.assertGreater(len(runtime.web_apis), len(ROUTES))
self.assertTrue(any(api["path"] == f"/{PLUGIN_NAME}/ui/bootstrap" for api in runtime.web_apis))
bootstrap_api = next(
api
for api in runtime.web_apis
if api["path"] == f"/{PLUGIN_NAME}/ui/bootstrap" and api["methods"] == ["GET"]
)
response = asyncio.run(bootstrap_api["handler"]())
self.assertEqual(response["status"], "ok")
self.assertEqual(response["data"]["plugin_name"], PLUGIN_NAME)
def test_dispatch_bridge_request_accepts_astrbot_plugin_path(self):
class FakeUrl:
path = "/api/plug/astrbot_plugin_imagestudio/ui/bootstrap"
class FakeRequest:
method = "GET"
url = FakeUrl()
query_params = {}
response = asyncio.run(dispatch_bridge_request("", request=FakeRequest()))
self.assertEqual(response["status"], "ok")
self.assertEqual(response["data"]["plugin_name"], PLUGIN_NAME)
def test_initialize_runtime_database_runs_migrations(self):
with tempfile.TemporaryDirectory() as tmp:
db_path = Path(tmp) / "imagestudio.db"
settings = DatabaseSettings(sqlite=SqliteSettings(path=str(db_path)))
result = initialize_runtime_database(settings)
self.assertTrue(result["initialized"])
self.assertEqual(result["backend"], "sqlite")
self.assertGreater(result["seed"]["material_categories"]["total"], 0)
self.assertTrue(db_path.exists())
database = Database(settings)
conn = database.connect()
try:
row = conn.execute(
"""
SELECT parent_id, category_type
FROM material_categories
WHERE category_id = 'cat_imagestudio_accessory_头部'
"""
).fetchone()
finally:
conn.close()
self.assertEqual(row["parent_id"], "cat_imagestudio_配饰")
self.assertEqual(row["category_type"], "accessory_group")
def test_astrbot_config_overrides_default_database_settings(self):
try:
result = apply_astrbot_config_overrides(
{
"database_backend": "postgresql",
"postgresql_enabled": True,
"postgresql_host": "127.0.0.1",
"postgresql_port": "5432",
"postgresql_database": "imagestudio_runtime",
"postgresql_user": "imagestudio",
"enable_private_companion_integration": True,
}
)
settings = load_database_settings()
self.assertTrue(result["applied"])
self.assertIn("database.postgresql.host", result["keys"])
self.assertEqual(settings.selected_backend, "postgresql")
self.assertEqual(settings.postgresql.database, "imagestudio_runtime")
finally:
set_runtime_config_overrides({})
def test_astrbot_main_class_exposes_manifest(self):
plugin = Main(context=object())
manifest = plugin.get_plugin_manifest()
self.assertEqual(manifest["plugin_name"], PLUGIN_NAME)
self.assertTrue(manifest["runtime"]["health"]["ok"])
def test_astrbot_main_initialize_registers_routes_when_supported(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()
plugin = Main(context=runtime)
asyncio.run(plugin.initialize())
self.assertTrue(plugin.registration_result["registered"])
self.assertEqual(len(runtime.routes), len(ROUTES))
self.assertEqual(len(runtime.mounts), 1)
self.assertFalse(plugin.registration_result["bridge_api"]["registered"])
def test_plugin_page_uses_relative_assets(self):
page = Path(__file__).resolve().parents[1] / "pages" / "imagestudio" / "index.html"
html = page.read_text(encoding="utf-8")
self.assertRegex(html, r'src="\.?/assets/')
self.assertRegex(html, r'href="\.?/assets/')
self.assertNotIn('src="/assets/', html)
self.assertNotIn('href="/assets/', html)
if __name__ == "__main__":
unittest.main()