mirror of
https://github.com/jxxghp/MoviePilot.git
synced 2026-11-30 16:05:05 +08:00
Merge pull request #6666 from Aqr-K/feat/plugin-instance-target-enablement
feat(plugin): 插件实例默认调用目标与启停,未指定实例时不再兜底取第一个
This commit is contained in:
@@ -225,6 +225,10 @@ def configure_plugin_system_services():
|
||||
)
|
||||
from app.runtime.extensions.plugin.system import get_plugin_system
|
||||
from app.runtime.extensions.service import ServiceConfigHelper
|
||||
from app.startup.initializers.plugins import (
|
||||
_clear_plugin_default_target,
|
||||
_set_plugin_default_target,
|
||||
)
|
||||
|
||||
configure_service_directory(
|
||||
configs=ServiceConfigHelper.get_configs,
|
||||
@@ -256,6 +260,8 @@ def configure_plugin_system_services():
|
||||
plugin_manager_module.get_runtime_setting('DEV')
|
||||
),
|
||||
logger=plugin_manager_module.logger,
|
||||
set_default_target=_set_plugin_default_target,
|
||||
clear_default_target=_clear_plugin_default_target,
|
||||
),
|
||||
tool_build_max_attempts=PluginManager.AGENT_TOOLS_BUILD_MAX_ATTEMPTS,
|
||||
)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"app/application/messaging/site.py:SiteInteractionHandler": 579,
|
||||
"app/application/messaging/skill.py:SkillInteractionHandler": 1101,
|
||||
"app/application/messaging/subscribe.py:SubscribeInteractionHandler": 694,
|
||||
"app/application/plugin/install.py:PluginInstallCommand": 739,
|
||||
"app/application/plugin/install.py:PluginInstallCommand": 743,
|
||||
"app/application/rss.py:RssHelper": 531,
|
||||
"app/application/security/url.py:SecurityUtils": 771,
|
||||
"app/application/torrent/download.py:TorrentHelper": 738,
|
||||
@@ -58,7 +58,7 @@
|
||||
"app/application/messaging/skill.py:SkillInteractionHandler._handle_text_interaction": 296,
|
||||
"app/application/messaging/subscribe.py:SubscribeInteractionHandler._handle_text_interaction": 205,
|
||||
"app/application/network.py:NetworkTestService._build_rules": 206,
|
||||
"app/application/plugin/install.py:PluginInstallCommand.__execute_locked": 277,
|
||||
"app/application/plugin/install.py:PluginInstallCommand.__execute_locked": 279,
|
||||
"app/application/rss.py:RssHelper._parse_impl": 213,
|
||||
"app/application/security/cookie.py:CookieHelper._get_site_cookie_ua_impl": 241,
|
||||
"app/application/security/cookie.py:CookieHelper._get_site_cookie_ua_impl.__page_handler": 214,
|
||||
|
||||
@@ -1077,8 +1077,8 @@
|
||||
"runtime_only": true
|
||||
}
|
||||
},
|
||||
"edge_count": 8614,
|
||||
"edge_sha256": "70b80d471a4080e365c0fd45dd87ca2768aac360b406f58e645ab68805d587b0",
|
||||
"edge_count": 8630,
|
||||
"edge_sha256": "498714193dc86bf3580b72f889a8f9ce874cd5185e1bdaaf951d83c523d98b65",
|
||||
"edges": [
|
||||
"app -> app.foundation",
|
||||
"app -> app.foundation.environment",
|
||||
@@ -2718,6 +2718,18 @@
|
||||
"app.api.endpoints.pluginloglevel -> app.schemas",
|
||||
"app.api.endpoints.pluginloglevel -> app.schemas.plugin",
|
||||
"app.api.endpoints.pluginloglevel -> app.schemas.response",
|
||||
"app.api.endpoints.plugintarget -> app.api",
|
||||
"app.api.endpoints.plugintarget -> app.api.dependencies",
|
||||
"app.api.endpoints.plugintarget -> app.api.dependencies.auth",
|
||||
"app.api.endpoints.plugintarget -> app.api.principal",
|
||||
"app.api.endpoints.plugintarget -> app.api.response",
|
||||
"app.api.endpoints.plugintarget -> app.application",
|
||||
"app.api.endpoints.plugintarget -> app.application.plugin",
|
||||
"app.api.endpoints.plugintarget -> app.application.plugin.runtime",
|
||||
"app.api.endpoints.plugintarget -> app.schemas",
|
||||
"app.api.endpoints.plugintarget -> app.schemas.exception",
|
||||
"app.api.endpoints.plugintarget -> app.schemas.plugin",
|
||||
"app.api.endpoints.plugintarget -> app.schemas.response",
|
||||
"app.api.endpoints.recommend -> app.adapters",
|
||||
"app.api.endpoints.recommend -> app.adapters.web",
|
||||
"app.api.endpoints.recommend -> app.adapters.web.security",
|
||||
@@ -3124,6 +3136,7 @@
|
||||
"app.api.routers -> app.api.endpoints.openai",
|
||||
"app.api.routers -> app.api.endpoints.plugin",
|
||||
"app.api.routers -> app.api.endpoints.pluginloglevel",
|
||||
"app.api.routers -> app.api.endpoints.plugintarget",
|
||||
"app.api.routers -> app.api.endpoints.recommend",
|
||||
"app.api.routers -> app.api.endpoints.rule",
|
||||
"app.api.routers -> app.api.endpoints.search",
|
||||
@@ -8336,6 +8349,7 @@
|
||||
"app.runtime.extensions.plugin.runtime -> app.runtime.extensions.plugin.storage",
|
||||
"app.runtime.extensions.plugin.runtime -> app.runtime.extensions.plugin.sync",
|
||||
"app.runtime.extensions.plugin.runtime -> app.runtime.extensions.plugin.system",
|
||||
"app.runtime.extensions.plugin.runtime -> app.runtime.extensions.plugin.target",
|
||||
"app.runtime.extensions.plugin.runtime -> app.runtime.extensions.plugin.tools",
|
||||
"app.runtime.extensions.plugin.runtime -> app.schemas",
|
||||
"app.runtime.extensions.plugin.runtime -> app.schemas.types",
|
||||
@@ -8352,6 +8366,8 @@
|
||||
"app.runtime.extensions.plugin.sync -> app.runtime.extensions.plugin.system",
|
||||
"app.runtime.extensions.plugin.sync -> app.schemas",
|
||||
"app.runtime.extensions.plugin.sync -> app.schemas.plugin",
|
||||
"app.runtime.extensions.plugin.target -> app.schemas",
|
||||
"app.runtime.extensions.plugin.target -> app.schemas.plugin",
|
||||
"app.runtime.extensions.plugin.tools -> app.runtime",
|
||||
"app.runtime.extensions.plugin.tools -> app.runtime.extensions",
|
||||
"app.runtime.extensions.plugin.tools -> app.runtime.extensions.plugin",
|
||||
@@ -9695,7 +9711,7 @@
|
||||
"app.workflow.actions.transfer_file -> app.workflow",
|
||||
"app.workflow.actions.transfer_file -> app.workflow.actions"
|
||||
],
|
||||
"module_count": 1014,
|
||||
"module_count": 1016,
|
||||
"modules": [
|
||||
"app",
|
||||
"app.adapters",
|
||||
@@ -9884,6 +9900,7 @@
|
||||
"app.api.endpoints.plugin",
|
||||
"app.api.endpoints.pluginfolder",
|
||||
"app.api.endpoints.pluginloglevel",
|
||||
"app.api.endpoints.plugintarget",
|
||||
"app.api.endpoints.recommend",
|
||||
"app.api.endpoints.rule",
|
||||
"app.api.endpoints.search",
|
||||
@@ -10547,6 +10564,7 @@
|
||||
"app.runtime.extensions.plugin.storage",
|
||||
"app.runtime.extensions.plugin.sync",
|
||||
"app.runtime.extensions.plugin.system",
|
||||
"app.runtime.extensions.plugin.target",
|
||||
"app.runtime.extensions.plugin.tools",
|
||||
"app.runtime.extensions.resource",
|
||||
"app.runtime.extensions.service",
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"repeat": 3,
|
||||
"targets": {
|
||||
"app.startup.lifecycle": {
|
||||
"loaded_app_module_count": 550,
|
||||
"loaded_app_module_count": 551,
|
||||
"max_ms": 1293.338,
|
||||
"median_ms": 1156.239,
|
||||
"min_ms": 1102.806,
|
||||
@@ -17,7 +17,7 @@
|
||||
]
|
||||
},
|
||||
"app.factory": {
|
||||
"loaded_app_module_count": 562,
|
||||
"loaded_app_module_count": 563,
|
||||
"max_ms": 1127.911,
|
||||
"median_ms": 1122.382,
|
||||
"min_ms": 1119.221,
|
||||
@@ -28,7 +28,7 @@
|
||||
]
|
||||
},
|
||||
"app.main": {
|
||||
"loaded_app_module_count": 564,
|
||||
"loaded_app_module_count": 565,
|
||||
"max_ms": 1188.652,
|
||||
"median_ms": 1183.509,
|
||||
"min_ms": 1174.522,
|
||||
|
||||
@@ -34,8 +34,8 @@ def test_api_operation_registry_matches_migration_batches() -> None:
|
||||
assert len(API_PARITY_OPERATION_SPECS) == 15
|
||||
assert len(API_MUSIC_OPERATION_SPECS) == 10
|
||||
assert len(API_SYSTEM_OPERATION_SPECS) == 7
|
||||
assert len(API_EXTENDED_OPERATION_SPECS) == 139
|
||||
assert len(API_OPERATION_SPECS) == 224
|
||||
assert len(API_EXTENDED_OPERATION_SPECS) == 142
|
||||
assert len(API_OPERATION_SPECS) == 227
|
||||
assert {spec.operation_id for spec in API_OPERATION_SPECS} == set(API_OPERATION_ROUTES)
|
||||
assert {
|
||||
"download.list",
|
||||
|
||||
@@ -155,7 +155,7 @@ async def test_bundled_moviepilot_api_skill_loads_complete_contract() -> None:
|
||||
assert payload["content_limit_bytes"] == MAX_SKILL_CONTENT_BYTES
|
||||
assert payload["truncated"] is False
|
||||
assert payload["truncation_message"] is None
|
||||
assert len(payload["skill"]["allowed_api_operations"]) == 224
|
||||
assert len(payload["skill"]["allowed_api_operations"]) == 227
|
||||
assert "## API Category Index" in payload["content"]
|
||||
assert "### `workflow.update`" not in payload["content"]
|
||||
assert "api/workflow.md" in payload["supporting_files"]
|
||||
|
||||
@@ -35,6 +35,7 @@ def _facade(**overrides):
|
||||
plugin_attr=lambda _plugin_id, _attr: None,
|
||||
plugin_instance=lambda _plugin_id: None,
|
||||
plugin_instances=lambda: {},
|
||||
host_instances=lambda: {},
|
||||
runtime_status=lambda _plugin_id: None,
|
||||
log=SimpleNamespace(error=lambda *_args: None, info=lambda *_args: None),
|
||||
)
|
||||
@@ -80,6 +81,7 @@ async def test_async_online_normalizes_market_configuration(monkeypatch) -> None
|
||||
plugin_attr=lambda _plugin_id, _attr: None,
|
||||
plugin_instance=lambda _plugin_id: None,
|
||||
plugin_instances=lambda: {},
|
||||
host_instances=lambda: {},
|
||||
runtime_status=lambda _plugin_id: None,
|
||||
log=SimpleNamespace(info=lambda *_args: None),
|
||||
)
|
||||
@@ -120,6 +122,7 @@ def test_installed_catalog_keeps_plugins_that_are_not_loaded():
|
||||
plugin_attr=lambda _plugin_id, _attr: None,
|
||||
plugin_instance=lambda _plugin_id: None,
|
||||
plugin_instances=lambda: {},
|
||||
host_instances=lambda: {},
|
||||
runtime_status=statuses.get,
|
||||
log=SimpleNamespace(error=lambda *_args: None, info=lambda *_args: None),
|
||||
)
|
||||
@@ -162,6 +165,7 @@ def test_local_repository_failure_does_not_break_catalog_projection():
|
||||
plugin_attr=lambda _plugin_id, _attr: None,
|
||||
plugin_instance=lambda _plugin_id: None,
|
||||
plugin_instances=lambda: {},
|
||||
host_instances=lambda: {},
|
||||
runtime_status=lambda _plugin_id: None,
|
||||
log=SimpleNamespace(
|
||||
error=lambda *_args: None,
|
||||
|
||||
@@ -97,7 +97,7 @@ def _build_lifecycle(**overrides: Any) -> PluginLifecycle:
|
||||
classes={},
|
||||
running={},
|
||||
load_plugins=lambda _plugin_id, _installed, _check: [],
|
||||
installed_plugins=lambda: [],
|
||||
loadable_plugins=lambda: [],
|
||||
plugin_config=lambda _plugin_id: {},
|
||||
auth_checker=lambda _plugin: True,
|
||||
clear_modules=lambda _plugin_id: None,
|
||||
@@ -141,7 +141,7 @@ def test_start_ensures_the_database_after_init_plugin():
|
||||
plugin_cls = _make_plugin_class("DemoPlugin", calls=calls)
|
||||
lifecycle = _build_lifecycle(
|
||||
load_plugins=lambda *_a, **_kw: [plugin_cls],
|
||||
installed_plugins=lambda: ["DemoPlugin"],
|
||||
loadable_plugins=lambda: ["DemoPlugin"],
|
||||
database=lambda: _recording_database(calls),
|
||||
)
|
||||
|
||||
@@ -157,7 +157,7 @@ def test_start_passes_the_declared_models_and_migration_directory():
|
||||
plugin_cls = _make_plugin_class("DemoPlugin", models=(ModelA,), migrations="m")
|
||||
lifecycle = _build_lifecycle(
|
||||
load_plugins=lambda *_a, **_kw: [plugin_cls],
|
||||
installed_plugins=lambda: ["DemoPlugin"],
|
||||
loadable_plugins=lambda: ["DemoPlugin"],
|
||||
database=lambda: _recording_database(calls),
|
||||
)
|
||||
|
||||
@@ -173,7 +173,7 @@ def test_start_reports_empty_declarations_for_plugins_without_a_database():
|
||||
plugin_cls = _make_plugin_class("DemoPlugin", declare_hooks=False)
|
||||
lifecycle = _build_lifecycle(
|
||||
load_plugins=lambda *_a, **_kw: [plugin_cls],
|
||||
installed_plugins=lambda: ["DemoPlugin"],
|
||||
loadable_plugins=lambda: ["DemoPlugin"],
|
||||
database=lambda: _recording_database(calls),
|
||||
)
|
||||
|
||||
@@ -193,7 +193,7 @@ def test_plugin_failing_to_ensure_is_not_registered_as_running():
|
||||
|
||||
lifecycle = _build_lifecycle(
|
||||
load_plugins=lambda *_a, **_kw: [plugin_cls],
|
||||
installed_plugins=lambda: ["DemoPlugin"],
|
||||
loadable_plugins=lambda: ["DemoPlugin"],
|
||||
database=lambda: PluginDatabase(ensure=_raise_ensure),
|
||||
)
|
||||
|
||||
@@ -209,7 +209,7 @@ def test_stop_releases_the_database_and_never_destroys_it():
|
||||
plugin_cls = _make_plugin_class("DemoPlugin")
|
||||
lifecycle = _build_lifecycle(
|
||||
load_plugins=lambda *_a, **_kw: [plugin_cls],
|
||||
installed_plugins=lambda: ["DemoPlugin"],
|
||||
loadable_plugins=lambda: ["DemoPlugin"],
|
||||
database=lambda: _recording_database(calls),
|
||||
)
|
||||
lifecycle.start("DemoPlugin")
|
||||
@@ -227,7 +227,7 @@ def test_stop_without_plugin_id_releases_every_running_plugin():
|
||||
plugin_b = _make_plugin_class("PluginB")
|
||||
lifecycle = _build_lifecycle(
|
||||
load_plugins=lambda *_a, **_kw: [plugin_a, plugin_b],
|
||||
installed_plugins=lambda: ["PluginA", "PluginB"],
|
||||
loadable_plugins=lambda: ["PluginA", "PluginB"],
|
||||
database=lambda: _recording_database(calls),
|
||||
)
|
||||
lifecycle.start()
|
||||
@@ -244,7 +244,7 @@ def test_reload_releases_then_ensures_again():
|
||||
plugin_cls = _make_plugin_class("DemoPlugin")
|
||||
lifecycle = _build_lifecycle(
|
||||
load_plugins=lambda *_a, **_kw: [plugin_cls],
|
||||
installed_plugins=lambda: ["DemoPlugin"],
|
||||
loadable_plugins=lambda: ["DemoPlugin"],
|
||||
database=lambda: _recording_database(calls),
|
||||
)
|
||||
lifecycle.start("DemoPlugin")
|
||||
@@ -267,7 +267,7 @@ def test_release_failure_does_not_block_unloading():
|
||||
|
||||
lifecycle = _build_lifecycle(
|
||||
load_plugins=lambda *_a, **_kw: [plugin_cls],
|
||||
installed_plugins=lambda: ["DemoPlugin"],
|
||||
loadable_plugins=lambda: ["DemoPlugin"],
|
||||
database=lambda: PluginDatabase(release=_raise_release),
|
||||
)
|
||||
lifecycle.start("DemoPlugin")
|
||||
@@ -405,7 +405,7 @@ def test_start_releases_the_database_of_a_plugin_that_failed_to_load():
|
||||
|
||||
lifecycle = _build_lifecycle(
|
||||
load_plugins=lambda *_a, **_kw: [plugin_cls],
|
||||
installed_plugins=lambda: ["DemoPlugin"],
|
||||
loadable_plugins=lambda: ["DemoPlugin"],
|
||||
database=lambda: PluginDatabase(
|
||||
ensure=_raise_ensure,
|
||||
release=lambda plugin_id: calls.append(("release", plugin_id)),
|
||||
@@ -429,7 +429,7 @@ def test_stop_all_releases_plugins_that_never_reached_the_running_registry():
|
||||
|
||||
lifecycle = _build_lifecycle(
|
||||
load_plugins=lambda *_a, **_kw: [plugin_cls],
|
||||
installed_plugins=lambda: ["DemoPlugin"],
|
||||
loadable_plugins=lambda: ["DemoPlugin"],
|
||||
database=lambda: PluginDatabase(
|
||||
ensure=_raise_ensure,
|
||||
release=lambda plugin_id: calls.append(("release", plugin_id)),
|
||||
@@ -451,7 +451,7 @@ def test_stopping_an_already_stopped_plugin_stays_idempotent():
|
||||
plugin_cls = _make_plugin_class("DemoPlugin")
|
||||
lifecycle = _build_lifecycle(
|
||||
load_plugins=lambda *_a, **_kw: [plugin_cls],
|
||||
installed_plugins=lambda: ["DemoPlugin"],
|
||||
loadable_plugins=lambda: ["DemoPlugin"],
|
||||
database=lambda: _recording_database(calls),
|
||||
)
|
||||
lifecycle.start("DemoPlugin")
|
||||
|
||||
415
tests/test_plugin_default_target.py
Normal file
415
tests/test_plugin_default_target.py
Normal file
@@ -0,0 +1,415 @@
|
||||
"""插件默认调用目标裁决与置位/清除测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.runtime.extensions.plugin.target import PluginDefaultTargetControl
|
||||
from app.schemas.plugin import PluginInstance
|
||||
|
||||
|
||||
class _Harness:
|
||||
"""组装 PluginDefaultTargetControl 依赖并记录调用轨迹的测试脚手架。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
host_instance: PluginInstance | None = None,
|
||||
clones: list[PluginInstance] | None = None,
|
||||
plugin_exists: bool = True,
|
||||
running_ids: set[str] | None = None,
|
||||
set_result: bool = True,
|
||||
) -> None:
|
||||
self.host_instance = host_instance
|
||||
self.clones = list(clones or [])
|
||||
self.plugin_exists_flag = plugin_exists
|
||||
self.running_ids = set(running_ids or set())
|
||||
self.saved_hosts: list[PluginInstance] = []
|
||||
self.set_calls: list[tuple[str, str]] = []
|
||||
self.clear_calls: list[str] = []
|
||||
self._set_result = set_result
|
||||
|
||||
def _get_instance(self, instance_id: str) -> PluginInstance | None:
|
||||
for clone in self.clones:
|
||||
if clone.instance_id == instance_id:
|
||||
return clone
|
||||
return None
|
||||
|
||||
def _instances_for_source(self, source_plugin_id: str) -> list[PluginInstance]:
|
||||
return [clone for clone in self.clones if clone.source_plugin_id == source_plugin_id]
|
||||
|
||||
def _get_host_instance(self, plugin_id: str) -> PluginInstance | None:
|
||||
if self.host_instance is not None and self.host_instance.instance_id == plugin_id:
|
||||
return self.host_instance
|
||||
return None
|
||||
|
||||
def _save_host_instance(self, instance: PluginInstance) -> None:
|
||||
self.saved_hosts.append(instance)
|
||||
self.host_instance = instance
|
||||
|
||||
def _running(self) -> dict[str, object]:
|
||||
return {instance_id: object() for instance_id in self.running_ids}
|
||||
|
||||
def _set_default_target(self, plugin_id: str, instance_id: str) -> bool:
|
||||
self.set_calls.append((plugin_id, instance_id))
|
||||
return self._set_result
|
||||
|
||||
def _clear_default_target(self, plugin_id: str) -> None:
|
||||
self.clear_calls.append(plugin_id)
|
||||
|
||||
def build(self) -> PluginDefaultTargetControl:
|
||||
"""构造挂接本脚手架全部端口的裁决与置位控制器。"""
|
||||
return PluginDefaultTargetControl(
|
||||
plugin_exists=lambda _plugin_id: self.plugin_exists_flag,
|
||||
get_instance=self._get_instance,
|
||||
instances_for_source=self._instances_for_source,
|
||||
get_host_instance=self._get_host_instance,
|
||||
save_host_instance=self._save_host_instance,
|
||||
running=self._running,
|
||||
set_default_target=self._set_default_target,
|
||||
clear_default_target=self._clear_default_target,
|
||||
)
|
||||
|
||||
|
||||
def _clone(instance_id: str, source_plugin_id: str, *, default: bool = False) -> PluginInstance:
|
||||
"""构造一个分身实例描述。"""
|
||||
return PluginInstance(
|
||||
instance_id=instance_id,
|
||||
source_plugin_id=source_plugin_id,
|
||||
is_default_target=default,
|
||||
)
|
||||
|
||||
|
||||
def _host(plugin_id: str, *, default: bool = False) -> PluginInstance:
|
||||
"""构造一个本体实例描述。"""
|
||||
return PluginInstance(
|
||||
instance_id=plugin_id,
|
||||
source_plugin_id=plugin_id,
|
||||
is_default_target=default,
|
||||
)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# resolve():单实例场景与显式实例直通
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_resolve_never_picks_the_first_instance_and_fails_deterministically():
|
||||
"""有分身却未设默认目标时,重复调用必须次次报同一个错,绝不挑出任何实例。
|
||||
|
||||
这是本特性最核心的一条语义:随机挑或按登记顺序取第一个都会让同一次调用在
|
||||
不同时刻落到不同实例,用户既无法复现、也无从知道刚才是哪个实例执行的。
|
||||
因此这里既断言「不返回任何候选」,也断言多次调用的失败完全一致——一个会
|
||||
「取第一个」的实现只会在第一次调用时暴露,之后看起来同样稳定。
|
||||
"""
|
||||
harness = _Harness(
|
||||
host_instance=_host("PluginA"),
|
||||
clones=[
|
||||
_clone("PluginAx2", "PluginA"),
|
||||
_clone("PluginAx3", "PluginA"),
|
||||
],
|
||||
running_ids={"PluginA", "PluginAx2", "PluginAx3"},
|
||||
)
|
||||
control = harness.build()
|
||||
|
||||
messages = []
|
||||
for _ in range(5):
|
||||
with pytest.raises(LookupError) as excinfo:
|
||||
control.resolve("PluginA")
|
||||
messages.append(str(excinfo.value))
|
||||
|
||||
# 五次调用报出完全相同的错误,说明裁决不含任何随机或顺序依赖的挑选
|
||||
assert len(set(messages)) == 1
|
||||
assert "未设置默认实例" in messages[0]
|
||||
# 没有任何一次调用把候选当成结果返回:三个候选都只出现在「可选实例」清单里
|
||||
assert harness.set_calls == []
|
||||
assert harness.clear_calls == []
|
||||
|
||||
|
||||
def test_resolve_returns_plugin_id_when_no_clones_exist():
|
||||
"""只有本体、没有任何分身时直接返回插件 ID,不要求设置默认目标。"""
|
||||
harness = _Harness(host_instance=_host("PluginA"), running_ids={"PluginA"})
|
||||
|
||||
assert harness.build().resolve("PluginA") == "PluginA"
|
||||
|
||||
|
||||
def test_resolve_returns_argument_unchanged_when_it_is_already_a_clone_id():
|
||||
"""传入的标识本身就是某个分身的实例 ID 时原样返回,该分身没有自己的下级分身。"""
|
||||
harness = _Harness(
|
||||
host_instance=_host("PluginA"),
|
||||
clones=[_clone("PluginAx2", "PluginA")],
|
||||
running_ids={"PluginAx2"},
|
||||
)
|
||||
|
||||
assert harness.build().resolve("PluginAx2") == "PluginAx2"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# resolve():有分身时的默认目标裁决
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_resolve_uses_enabled_default_target_among_clones():
|
||||
"""已有分身且默认目标已启用时,未指定实例的调用落到该默认目标。"""
|
||||
harness = _Harness(
|
||||
host_instance=_host("PluginA"),
|
||||
clones=[
|
||||
_clone("PluginAx2", "PluginA", default=True),
|
||||
_clone("PluginAx3", "PluginA"),
|
||||
],
|
||||
running_ids={"PluginAx2", "PluginAx3"},
|
||||
)
|
||||
|
||||
assert harness.build().resolve("PluginA") == "PluginAx2"
|
||||
|
||||
|
||||
def test_resolve_host_itself_can_be_default_target():
|
||||
"""本体同样可以被选为默认调用目标,与分身地位相同。"""
|
||||
harness = _Harness(
|
||||
host_instance=_host("PluginA", default=True),
|
||||
clones=[_clone("PluginAx2", "PluginA")],
|
||||
running_ids={"PluginA", "PluginAx2"},
|
||||
)
|
||||
|
||||
assert harness.build().resolve("PluginA") == "PluginA"
|
||||
|
||||
|
||||
def test_resolve_raises_when_no_default_target_set():
|
||||
"""已有分身但未设置默认目标时报错,且不得回退到任何一个候选。"""
|
||||
harness = _Harness(
|
||||
host_instance=_host("PluginA"),
|
||||
clones=[_clone("PluginAx2", "PluginA"), _clone("PluginAx3", "PluginA")],
|
||||
running_ids={"PluginA", "PluginAx2", "PluginAx3"},
|
||||
)
|
||||
|
||||
with pytest.raises(LookupError) as excinfo:
|
||||
harness.build().resolve("PluginA")
|
||||
|
||||
message = str(excinfo.value)
|
||||
assert "PluginA" in message
|
||||
assert "未设置默认实例" in message
|
||||
assert "PluginA(已启用)" in message
|
||||
assert "PluginAx2(已启用)" in message
|
||||
assert "PluginAx3(已启用)" in message
|
||||
|
||||
|
||||
def test_resolve_raises_when_default_target_disabled_and_does_not_fall_back():
|
||||
"""默认目标已停用时必须报错,不得静默改走另一个正在运行的实例。"""
|
||||
harness = _Harness(
|
||||
host_instance=_host("PluginA"),
|
||||
clones=[
|
||||
_clone("PluginAx2", "PluginA", default=True),
|
||||
_clone("PluginAx3", "PluginA"),
|
||||
],
|
||||
running_ids={"PluginAx3"},
|
||||
)
|
||||
|
||||
with pytest.raises(LookupError) as excinfo:
|
||||
harness.build().resolve("PluginA")
|
||||
|
||||
message = str(excinfo.value)
|
||||
assert "默认实例 PluginAx2 已停用" in message
|
||||
assert "PluginAx3(已启用)" in message
|
||||
|
||||
|
||||
def test_resolve_candidate_description_orders_alphabetically():
|
||||
"""候选实例描述按实例 ID 升序排列,报错文案稳定可预期。"""
|
||||
harness = _Harness(
|
||||
host_instance=_host("PluginZ"),
|
||||
clones=[_clone("PluginZb", "PluginZ"), _clone("PluginZa", "PluginZ")],
|
||||
running_ids=set(),
|
||||
)
|
||||
|
||||
with pytest.raises(LookupError) as excinfo:
|
||||
harness.build().resolve("PluginZ")
|
||||
|
||||
assert str(excinfo.value).endswith(
|
||||
"可选实例:PluginZ(已停用)、PluginZa(已停用)、PluginZb(已停用)"
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_treats_never_persisted_host_as_a_candidate():
|
||||
"""本体从未被显式绑定过任何设置时,仍以默认视图参与候选而不是被略去。"""
|
||||
harness = _Harness(
|
||||
host_instance=None,
|
||||
clones=[_clone("PluginAx2", "PluginA")],
|
||||
running_ids={"PluginA"},
|
||||
)
|
||||
|
||||
with pytest.raises(LookupError) as excinfo:
|
||||
harness.build().resolve("PluginA")
|
||||
|
||||
assert "PluginA(已启用)" in str(excinfo.value)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# set_target()
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_set_target_upserts_never_persisted_host_before_setting():
|
||||
"""本体从未落盘过时,设为默认目标前先落盘一条默认视图记录。"""
|
||||
harness = _Harness(host_instance=None)
|
||||
|
||||
result = harness.build().set_target("PluginA", "PluginA")
|
||||
|
||||
assert result is True
|
||||
assert len(harness.saved_hosts) == 1
|
||||
assert harness.saved_hosts[0].instance_id == "PluginA"
|
||||
assert harness.set_calls == [("PluginA", "PluginA")]
|
||||
|
||||
|
||||
def test_set_target_does_not_resave_already_persisted_host():
|
||||
"""本体已经落盘过时不重复保存,只转发置位调用。"""
|
||||
harness = _Harness(host_instance=_host("PluginA"))
|
||||
|
||||
harness.build().set_target("PluginA", "PluginA")
|
||||
|
||||
assert harness.saved_hosts == []
|
||||
assert harness.set_calls == [("PluginA", "PluginA")]
|
||||
|
||||
|
||||
def test_set_target_delegates_clone_to_atomic_callable():
|
||||
"""目标是已归属该插件的分身时,直接转发给原子置位端口。"""
|
||||
harness = _Harness(
|
||||
host_instance=_host("PluginA"),
|
||||
clones=[_clone("PluginAx2", "PluginA")],
|
||||
)
|
||||
|
||||
result = harness.build().set_target("PluginA", "PluginAx2")
|
||||
|
||||
assert result is True
|
||||
assert harness.set_calls == [("PluginA", "PluginAx2")]
|
||||
|
||||
|
||||
def test_set_target_rejects_instance_not_belonging_to_plugin():
|
||||
"""目标实例不存在或归属另一个插件时拒绝,且不下发到原子置位端口。"""
|
||||
harness = _Harness(
|
||||
host_instance=_host("PluginA"),
|
||||
clones=[_clone("PluginBx2", "PluginB")],
|
||||
)
|
||||
|
||||
result = harness.build().set_target("PluginA", "PluginBx2")
|
||||
|
||||
assert result is False
|
||||
assert harness.set_calls == []
|
||||
|
||||
|
||||
def test_set_target_propagates_atomic_callable_failure():
|
||||
"""原子置位端口报告目标不存在时如实透传,不伪装成功。"""
|
||||
harness = _Harness(
|
||||
host_instance=_host("PluginA"),
|
||||
clones=[_clone("PluginAx2", "PluginA")],
|
||||
set_result=False,
|
||||
)
|
||||
|
||||
assert harness.build().set_target("PluginA", "PluginAx2") is False
|
||||
|
||||
|
||||
def test_set_target_raises_when_plugin_missing():
|
||||
"""插件本身不存在时拒绝设置默认目标。"""
|
||||
harness = _Harness(plugin_exists=False)
|
||||
|
||||
with pytest.raises(LookupError):
|
||||
harness.build().set_target("Missing", "Missing")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# clear_target()
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_clear_target_clears_when_matching_current_default():
|
||||
"""请求清除的实例正是当前默认目标时才真正清除。"""
|
||||
harness = _Harness(
|
||||
host_instance=_host("PluginA"),
|
||||
clones=[_clone("PluginAx2", "PluginA", default=True)],
|
||||
)
|
||||
|
||||
harness.build().clear_target("PluginA", "PluginAx2")
|
||||
|
||||
assert harness.clear_calls == ["PluginA"]
|
||||
|
||||
|
||||
def test_clear_target_is_noop_when_nothing_is_set():
|
||||
"""插件当前没有任何默认目标置位时按空操作处理。"""
|
||||
harness = _Harness(
|
||||
host_instance=_host("PluginA"),
|
||||
clones=[_clone("PluginAx2", "PluginA")],
|
||||
)
|
||||
|
||||
harness.build().clear_target("PluginA", "PluginAx2")
|
||||
|
||||
assert harness.clear_calls == []
|
||||
|
||||
|
||||
def test_clear_target_does_not_touch_a_different_current_default():
|
||||
"""请求清除的实例并非当前默认目标时,不得误清另一个实例的置位。"""
|
||||
harness = _Harness(
|
||||
host_instance=_host("PluginA"),
|
||||
clones=[
|
||||
_clone("PluginAx2", "PluginA", default=True),
|
||||
_clone("PluginAx3", "PluginA"),
|
||||
],
|
||||
)
|
||||
|
||||
harness.build().clear_target("PluginA", "PluginAx3")
|
||||
|
||||
assert harness.clear_calls == []
|
||||
|
||||
|
||||
def test_clear_target_raises_when_plugin_missing():
|
||||
"""插件本身不存在时拒绝清除默认目标。"""
|
||||
harness = _Harness(plugin_exists=False)
|
||||
|
||||
with pytest.raises(LookupError):
|
||||
harness.build().clear_target("Missing", "Missing")
|
||||
|
||||
|
||||
def test_resolve_treats_a_loaded_but_disabled_default_target_as_unavailable():
|
||||
"""默认目标已加载但被用户停用时按「已停用」处理,要求显式指定实例。
|
||||
|
||||
界面上关掉启用开关只会重新 init_plugin,实例仍留在运行表里;只看运行表会把
|
||||
停用实例当成可用目标选中,调用随后以「插件不存在」收场。
|
||||
"""
|
||||
|
||||
class _Disabled:
|
||||
"""模拟已加载但启用开关被关掉的实例。"""
|
||||
|
||||
@staticmethod
|
||||
def get_state() -> bool:
|
||||
"""返回停用状态。"""
|
||||
return False
|
||||
|
||||
harness = _Harness(
|
||||
host_instance=_host("PluginA"),
|
||||
clones=[_clone("PluginAx2", "PluginA", default=True)],
|
||||
running_ids={"PluginAx2"},
|
||||
)
|
||||
harness._running = lambda: {"PluginAx2": _Disabled()}
|
||||
|
||||
with pytest.raises(LookupError) as excinfo:
|
||||
harness.build().resolve("PluginA")
|
||||
|
||||
assert "已停用" in str(excinfo.value)
|
||||
|
||||
|
||||
def test_set_target_rejects_clone_own_id_as_plugin_id():
|
||||
"""用分身自身实例 ID 当源插件 ID 置位必须拒绝,否则会把该行改写成本体记录。"""
|
||||
harness = _Harness(clones=[_clone("PluginAx2", "PluginA")])
|
||||
|
||||
with pytest.raises(LookupError):
|
||||
harness.build().set_target("PluginAx2", "PluginAx2")
|
||||
|
||||
assert harness.saved_hosts == []
|
||||
assert harness.set_calls == []
|
||||
|
||||
|
||||
def test_clear_target_rejects_clone_own_id_as_plugin_id():
|
||||
"""清除置位同样拒绝分身自身实例 ID,避免落到本体分支。"""
|
||||
harness = _Harness(clones=[_clone("PluginAx2", "PluginA")])
|
||||
|
||||
with pytest.raises(LookupError):
|
||||
harness.build().clear_target("PluginAx2", "PluginAx2")
|
||||
|
||||
assert harness.clear_calls == []
|
||||
@@ -302,6 +302,7 @@ def _command(
|
||||
command = PluginInstallCommand(
|
||||
persistence=persistence,
|
||||
installed_plugins_reader=lambda: installed or [],
|
||||
loadable_marker=lambda _plugin_id: calls.append("mark_loadable"),
|
||||
plugin_ids_provider=lambda: plugin_ids or [],
|
||||
packages=packages,
|
||||
install_reporter=reporter or default_reporter,
|
||||
@@ -413,6 +414,8 @@ async def test_success_commits_journal_before_report_and_cleans_package_snapshot
|
||||
"package",
|
||||
"receipt",
|
||||
"journal_target",
|
||||
# 本体的装载判据在实例表的启用位上;这一步缺了,插件装完当次能跑,重启即消失
|
||||
"mark_loadable",
|
||||
"stage_backup",
|
||||
"activate_backup",
|
||||
"target_reload",
|
||||
|
||||
135
tests/test_plugin_instance_default_target_endpoints.py
Normal file
135
tests/test_plugin_instance_default_target_endpoints.py
Normal file
@@ -0,0 +1,135 @@
|
||||
"""插件实例默认调用目标设置与清除接口测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.api.dependencies.auth import get_current_active_superuser
|
||||
from app.api.endpoints import plugintarget as plugintarget_endpoint
|
||||
from app.api.endpoints.plugintarget import (
|
||||
clear_plugin_instance_default_target,
|
||||
set_plugin_instance_default_target,
|
||||
)
|
||||
|
||||
|
||||
def _depends_default(func, parameter_name: str):
|
||||
"""取出端点函数指定参数的 FastAPI Depends 默认值。"""
|
||||
return inspect.signature(func).parameters[parameter_name].default
|
||||
|
||||
|
||||
def _manager(**methods):
|
||||
"""按方法名快速拼装一个鸭子类型的 Manager 替身。"""
|
||||
return type("Manager", (), methods)()
|
||||
|
||||
|
||||
def test_both_endpoints_require_superuser_dependency():
|
||||
"""设为默认与清除默认两个端点都要求超级管理员。"""
|
||||
for func in (set_plugin_instance_default_target, clear_plugin_instance_default_target):
|
||||
depends = _depends_default(func, "_")
|
||||
assert depends.dependency is get_current_active_superuser
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# PUT /instances/{plugin_id}/{instance_id}/default_target
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_put_delegates_to_manager_and_reports_success(monkeypatch):
|
||||
"""设置请求原样转交给 Manager,命中时返回成功。"""
|
||||
calls: list = []
|
||||
manager = _manager(
|
||||
set_plugin_instance_default_target=lambda self, *a: (calls.append(a), True)[1]
|
||||
)
|
||||
monkeypatch.setattr(plugintarget_endpoint, "get_plugin_manager", lambda: manager)
|
||||
|
||||
result = set_plugin_instance_default_target("DemoPlugin", "DemoPluginWork", None)
|
||||
|
||||
assert result.success is True
|
||||
assert calls == [("DemoPlugin", "DemoPluginWork")]
|
||||
|
||||
|
||||
def test_put_reports_missing_instance_as_404(monkeypatch):
|
||||
"""目标实例不归属该插件时,Manager 返回 False,接口须映射为 404。"""
|
||||
manager = _manager(set_plugin_instance_default_target=lambda self, *a: False)
|
||||
monkeypatch.setattr(plugintarget_endpoint, "get_plugin_manager", lambda: manager)
|
||||
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
set_plugin_instance_default_target("DemoPlugin", "Missing", None)
|
||||
|
||||
assert excinfo.value.status_code == 404
|
||||
|
||||
|
||||
def test_put_reports_missing_plugin_as_404(monkeypatch):
|
||||
"""插件本身不存在时返回 404。"""
|
||||
|
||||
def _raise(*_a):
|
||||
raise LookupError("插件 Missing 不存在")
|
||||
|
||||
manager = _manager(set_plugin_instance_default_target=_raise)
|
||||
monkeypatch.setattr(plugintarget_endpoint, "get_plugin_manager", lambda: manager)
|
||||
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
set_plugin_instance_default_target("Missing", "Missing", None)
|
||||
|
||||
assert excinfo.value.status_code == 404
|
||||
|
||||
|
||||
def test_put_maps_unique_index_violation_to_409(monkeypatch):
|
||||
"""并发置位撞上条件唯一索引时映射为可重试的 409,而不是 500。"""
|
||||
|
||||
def _raise(*_a):
|
||||
raise IntegrityError("stmt", {}, Exception("unique"))
|
||||
|
||||
manager = _manager(set_plugin_instance_default_target=_raise)
|
||||
monkeypatch.setattr(plugintarget_endpoint, "get_plugin_manager", lambda: manager)
|
||||
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
set_plugin_instance_default_target("DemoPlugin", "DemoPluginWork", None)
|
||||
|
||||
assert excinfo.value.status_code == 409
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# DELETE /instances/{plugin_id}/{instance_id}/default_target
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_delete_delegates_to_manager_and_is_idempotent(monkeypatch):
|
||||
"""清除请求原样转交给 Manager,重复调用同样返回成功。"""
|
||||
calls: list = []
|
||||
manager = _manager(
|
||||
clear_plugin_instance_default_target=lambda self, *a: calls.append(a)
|
||||
)
|
||||
monkeypatch.setattr(plugintarget_endpoint, "get_plugin_manager", lambda: manager)
|
||||
|
||||
first = clear_plugin_instance_default_target("DemoPlugin", "DemoPluginWork", None)
|
||||
second = clear_plugin_instance_default_target("DemoPlugin", "DemoPluginWork", None)
|
||||
|
||||
assert first.success is True
|
||||
assert second.success is True
|
||||
assert calls == [("DemoPlugin", "DemoPluginWork"), ("DemoPlugin", "DemoPluginWork")]
|
||||
|
||||
|
||||
def test_delete_reports_missing_plugin_as_404(monkeypatch):
|
||||
"""插件本身不存在时返回 404。"""
|
||||
|
||||
def _raise(*_a):
|
||||
raise LookupError("插件 Missing 不存在")
|
||||
|
||||
manager = _manager(clear_plugin_instance_default_target=_raise)
|
||||
monkeypatch.setattr(plugintarget_endpoint, "get_plugin_manager", lambda: manager)
|
||||
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
clear_plugin_instance_default_target("Missing", "Missing", None)
|
||||
|
||||
assert excinfo.value.status_code == 404
|
||||
|
||||
|
||||
def test_router_registers_default_target_paths():
|
||||
"""路由器暴露设为默认与清除默认两个路径,注册在插件前缀下。"""
|
||||
paths = {route.path for route in plugintarget_endpoint.router.routes}
|
||||
assert "/instances/{plugin_id}/{instance_id}/default_target" in paths
|
||||
177
tests/test_plugin_instance_default_target_migration.py
Normal file
177
tests/test_plugin_instance_default_target_migration.py
Normal file
@@ -0,0 +1,177 @@
|
||||
"""插件实例默认调用目标标记列与条件唯一索引 Alembic 迁移测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
from sqlalchemy.dialects import postgresql, sqlite
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.db.models.plugininstance import PluginInstance
|
||||
|
||||
MIGRATION_MODULE = "database.versions.e0e68cbd5756_3_0_37"
|
||||
|
||||
|
||||
def _bind_migration(monkeypatch, connection):
|
||||
"""把迁移绑定到隔离数据库连接。"""
|
||||
migration = importlib.import_module(MIGRATION_MODULE)
|
||||
context = MigrationContext.configure(connection)
|
||||
monkeypatch.setattr(migration, "op", Operations(context))
|
||||
return migration
|
||||
|
||||
|
||||
def _create_legacy_table(connection: sa.engine.Connection) -> None:
|
||||
"""建出加列前的表结构,模拟迁移前的存量数据库。"""
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
table = sa.Table(
|
||||
"plugininstance",
|
||||
sa.MetaData(),
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("instance_id", sa.String(length=128), nullable=False),
|
||||
sa.Column("source_plugin_id", sa.String(length=128), nullable=False),
|
||||
sa.Column("plugin_name", sa.String(length=255)),
|
||||
sa.Column("plugin_desc", sa.String(length=255)),
|
||||
sa.Column("plugin_icon", sa.String(length=255)),
|
||||
sa.Column("log_level", sa.String(length=16)),
|
||||
sa.Column("log_expires_at", sa.String(length=40)),
|
||||
sa.Column("config_data", sa.JSON()),
|
||||
sa.Column("created_at", sa.String(length=40), nullable=False),
|
||||
sa.Column("updated_at", sa.String(length=40), nullable=False),
|
||||
)
|
||||
table.create(connection)
|
||||
connection.execute(
|
||||
table.insert().values(
|
||||
instance_id="DemoPluginWork",
|
||||
source_plugin_id="DemoPlugin",
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_default_target_migration_adds_column_and_keeps_existing_rows(monkeypatch) -> None:
|
||||
"""新增列必须非空默认为假,且不得影响已有行;重复升级与完整回滚都要幂等。"""
|
||||
engine = sa.create_engine("sqlite://")
|
||||
with engine.begin() as connection:
|
||||
_create_legacy_table(connection)
|
||||
migration = _bind_migration(monkeypatch, connection)
|
||||
|
||||
migration.upgrade()
|
||||
migration.upgrade()
|
||||
|
||||
columns = {
|
||||
column["name"]: column
|
||||
for column in sa.inspect(connection).get_columns("plugininstance")
|
||||
}
|
||||
# 与该迁移自身的落点比对,而不是与持续演进的当前模型比对:后续迁移
|
||||
# 还会继续给该表加列,本断言不应该随之跟着变红。
|
||||
assert columns.keys() == {
|
||||
"id",
|
||||
"instance_id",
|
||||
"source_plugin_id",
|
||||
"plugin_name",
|
||||
"plugin_desc",
|
||||
"plugin_icon",
|
||||
"log_level",
|
||||
"log_expires_at",
|
||||
"config_data",
|
||||
"is_default_target",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
}
|
||||
assert columns["is_default_target"]["nullable"] is False
|
||||
|
||||
table = sa.Table("plugininstance", sa.MetaData(), autoload_with=connection)
|
||||
row = connection.execute(sa.select(table)).mappings().one()
|
||||
assert row["instance_id"] == "DemoPluginWork"
|
||||
assert bool(row["is_default_target"]) is False
|
||||
|
||||
migration.downgrade()
|
||||
remaining = {
|
||||
column["name"] for column in sa.inspect(connection).get_columns("plugininstance")
|
||||
}
|
||||
assert "is_default_target" not in remaining
|
||||
remaining_indexes = {
|
||||
index["name"] for index in sa.inspect(connection).get_indexes("plugininstance")
|
||||
}
|
||||
assert "ux_plugininstance_default_target" not in remaining_indexes
|
||||
|
||||
migration.upgrade()
|
||||
restored = {
|
||||
column["name"] for column in sa.inspect(connection).get_columns("plugininstance")
|
||||
}
|
||||
assert "is_default_target" in restored
|
||||
|
||||
|
||||
def test_default_target_migration_accepts_fresh_current_schema(monkeypatch) -> None:
|
||||
"""create_all 已建当前表时重复升级不得因列或索引已存在而报错。"""
|
||||
engine = sa.create_engine("sqlite://")
|
||||
with engine.begin() as connection:
|
||||
PluginInstance.__table__.create(connection)
|
||||
migration = _bind_migration(monkeypatch, connection)
|
||||
|
||||
migration.upgrade()
|
||||
migration.upgrade()
|
||||
|
||||
assert {
|
||||
column["name"]
|
||||
for column in sa.inspect(connection).get_columns("plugininstance")
|
||||
} == {column.name for column in PluginInstance.__table__.columns}
|
||||
assert "ux_plugininstance_default_target" in {
|
||||
index["name"] for index in sa.inspect(connection).get_indexes("plugininstance")
|
||||
}
|
||||
|
||||
|
||||
def test_default_target_migration_index_rejects_a_second_default_target(monkeypatch) -> None:
|
||||
"""迁移建出的条件唯一索引必须在真实数据库连接上拒绝第二条置位。"""
|
||||
engine = sa.create_engine("sqlite://")
|
||||
with engine.begin() as connection:
|
||||
_create_legacy_table(connection)
|
||||
migration = _bind_migration(monkeypatch, connection)
|
||||
migration.upgrade()
|
||||
|
||||
table = sa.Table("plugininstance", sa.MetaData(), autoload_with=connection)
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
connection.execute(
|
||||
table.insert().values(
|
||||
instance_id="DemoPlugin",
|
||||
source_plugin_id="DemoPlugin",
|
||||
is_default_target=True,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
connection.execute(
|
||||
table.update()
|
||||
.where(table.c.instance_id == "DemoPluginWork")
|
||||
.values(is_default_target=True)
|
||||
)
|
||||
|
||||
|
||||
def test_default_target_index_is_partial_in_both_dialects() -> None:
|
||||
"""模型(``create_all`` 路径)建出的索引在两种方言下都必须带谓词。
|
||||
|
||||
本仓测试库是 SQLite,PostgreSQL 分支只能靠编译期 DDL 证明:谓词整个丢失会
|
||||
退化成「每个源插件只能有一行实例」,把插件分身整个锁死。
|
||||
"""
|
||||
index = next(
|
||||
item for item in PluginInstance.__table__.indexes
|
||||
if item.name == "ux_plugininstance_default_target"
|
||||
)
|
||||
ddl = sa.schema.CreateIndex(index)
|
||||
|
||||
assert str(ddl.compile(dialect=sqlite.dialect())).strip() == (
|
||||
"CREATE UNIQUE INDEX ux_plugininstance_default_target "
|
||||
"ON plugininstance (source_plugin_id) WHERE is_default_target IS 1"
|
||||
)
|
||||
assert str(ddl.compile(dialect=postgresql.dialect())).strip() == (
|
||||
"CREATE UNIQUE INDEX ux_plugininstance_default_target "
|
||||
"ON plugininstance (source_plugin_id) WHERE is_default_target IS true"
|
||||
)
|
||||
135
tests/test_plugin_instance_default_target_oper.py
Normal file
135
tests/test_plugin_instance_default_target_oper.py
Normal file
@@ -0,0 +1,135 @@
|
||||
"""插件实例默认调用目标置位与清除的数据访问层测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import delete
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db.models.plugininstance import PluginInstance
|
||||
from app.db.oper.plugininstance import PluginInstanceOper
|
||||
from app.db.uow import run_sync_transaction
|
||||
|
||||
_INSTANCE_IDS = (
|
||||
"TargetOperHost",
|
||||
"TargetOperHostX2",
|
||||
"TargetOperHostX3",
|
||||
"TargetOperOther",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def purge_written_rows():
|
||||
"""删除用例写入的行,测试库在整个会话内共享,残留会干扰后续用例。"""
|
||||
yield
|
||||
|
||||
def purge(session: Session) -> None:
|
||||
"""按本文件使用的固定标识精确删除,不触碰其他用例的数据。"""
|
||||
session.execute(
|
||||
delete(PluginInstance).where(
|
||||
PluginInstance.instance_id.in_(_INSTANCE_IDS)
|
||||
)
|
||||
)
|
||||
|
||||
run_sync_transaction(purge)
|
||||
|
||||
|
||||
def _seed(oper: PluginInstanceOper) -> None:
|
||||
"""建出一个本体和两个分身,供置位与清除用例共用。"""
|
||||
oper.save(instance_id="TargetOperHost", source_plugin_id="TargetOperHost")
|
||||
oper.save(instance_id="TargetOperHostX2", source_plugin_id="TargetOperHost")
|
||||
oper.save(instance_id="TargetOperHostX3", source_plugin_id="TargetOperHost")
|
||||
|
||||
|
||||
def test_set_default_target_marks_only_the_requested_row():
|
||||
"""置位只落在目标行上,同插件其余行保持未置位。"""
|
||||
oper = PluginInstanceOper()
|
||||
_seed(oper)
|
||||
|
||||
assert oper.set_default_target("TargetOperHost", "TargetOperHostX2") is True
|
||||
|
||||
flags = {
|
||||
record.instance_id: record.is_default_target
|
||||
for record in oper.list_by_source("TargetOperHost")
|
||||
}
|
||||
assert flags == {
|
||||
"TargetOperHost": False,
|
||||
"TargetOperHostX2": True,
|
||||
"TargetOperHostX3": False,
|
||||
}
|
||||
|
||||
|
||||
def test_set_default_target_clears_the_previous_default_in_one_transaction():
|
||||
"""改置默认目标时旧置位必须一并清掉,不能出现两行同时为真。
|
||||
|
||||
「同一源插件至多一个默认目标」由条件唯一索引在库层强制,清旧与置新若分处两个
|
||||
事务就会撞上索引;这条用例正是在真实连接上证明清旧置新落在同一次写入里。
|
||||
"""
|
||||
oper = PluginInstanceOper()
|
||||
_seed(oper)
|
||||
oper.set_default_target("TargetOperHost", "TargetOperHostX2")
|
||||
|
||||
assert oper.set_default_target("TargetOperHost", "TargetOperHostX3") is True
|
||||
|
||||
marked = [
|
||||
record.instance_id
|
||||
for record in oper.list_by_source("TargetOperHost")
|
||||
if record.is_default_target
|
||||
]
|
||||
assert marked == ["TargetOperHostX3"]
|
||||
|
||||
|
||||
def test_set_default_target_rejects_a_row_belonging_to_another_plugin():
|
||||
"""目标行不归属该源插件时原样返回失败,且不动原有置位。"""
|
||||
oper = PluginInstanceOper()
|
||||
_seed(oper)
|
||||
oper.save(instance_id="TargetOperOther", source_plugin_id="TargetOperOther")
|
||||
oper.set_default_target("TargetOperHost", "TargetOperHostX2")
|
||||
|
||||
assert oper.set_default_target("TargetOperHost", "TargetOperOther") is False
|
||||
|
||||
marked = [
|
||||
record.instance_id
|
||||
for record in oper.list_by_source("TargetOperHost")
|
||||
if record.is_default_target
|
||||
]
|
||||
assert marked == ["TargetOperHostX2"]
|
||||
|
||||
|
||||
def test_set_default_target_reports_false_for_a_row_that_does_not_exist():
|
||||
"""目标行尚未落盘时如实返回失败,不隐式建行。"""
|
||||
oper = PluginInstanceOper()
|
||||
_seed(oper)
|
||||
|
||||
assert oper.set_default_target("TargetOperHost", "TargetOperHostMissing") is False
|
||||
assert oper.get("TargetOperHostMissing") is None
|
||||
|
||||
|
||||
def test_clear_default_target_is_idempotent():
|
||||
"""清除置位后重复调用保持幂等,不报错也不产生新的置位。"""
|
||||
oper = PluginInstanceOper()
|
||||
_seed(oper)
|
||||
oper.set_default_target("TargetOperHost", "TargetOperHostX2")
|
||||
|
||||
oper.clear_default_target("TargetOperHost")
|
||||
oper.clear_default_target("TargetOperHost")
|
||||
|
||||
assert not any(
|
||||
record.is_default_target for record in oper.list_by_source("TargetOperHost")
|
||||
)
|
||||
|
||||
|
||||
def test_host_row_carrying_only_a_default_target_is_not_recycled_as_empty():
|
||||
"""本体行只剩默认目标置位时不算「只剩身份列」,不能被空行回收清掉。
|
||||
|
||||
回收判据漏掉这一列会让用户把本体设为默认调用目标后,下一次清空配置就把置位
|
||||
连同整行一起删掉,默认目标无声失效。
|
||||
"""
|
||||
oper = PluginInstanceOper()
|
||||
_seed(oper)
|
||||
oper.set_default_target("TargetOperHost", "TargetOperHost")
|
||||
|
||||
record = oper.get("TargetOperHost")
|
||||
assert record is not None
|
||||
assert record.is_default_target is True
|
||||
assert record.carries_only_identity is False
|
||||
137
tests/test_plugin_instance_enabled_endpoint.py
Normal file
137
tests/test_plugin_instance_enabled_endpoint.py
Normal file
@@ -0,0 +1,137 @@
|
||||
"""插件实例启停接口与依赖分类装载过滤测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.api.dependencies.auth import get_current_active_superuser
|
||||
from app.api.endpoints import plugintarget as plugintarget_endpoint
|
||||
from app.api.endpoints.plugintarget import set_plugin_instance_enabled
|
||||
from app.runtime.extensions.plugin.dependency import PluginDependencyService
|
||||
from app.schemas.exception import PluginMutationRejectedError
|
||||
from app.schemas.plugin import PluginInstance, PluginInstanceEnabledRequest
|
||||
|
||||
|
||||
def _manager(**methods):
|
||||
"""按方法名快速拼装一个鸭子类型的 Manager 替身。"""
|
||||
return type("Manager", (), methods)()
|
||||
|
||||
|
||||
def test_endpoint_requires_superuser_dependency():
|
||||
"""启停端点要求超级管理员。"""
|
||||
depends = inspect.signature(set_plugin_instance_enabled).parameters["_"].default
|
||||
assert depends.dependency is get_current_active_superuser
|
||||
|
||||
|
||||
def test_endpoint_delegates_to_manager_and_reports_success(monkeypatch):
|
||||
"""请求原样转交给 Manager,状态确实变化时返回成功。"""
|
||||
calls: list = []
|
||||
manager = _manager(
|
||||
set_plugin_instance_enabled=lambda self, *a: (calls.append(a), True)[1]
|
||||
)
|
||||
monkeypatch.setattr(plugintarget_endpoint, "get_plugin_manager", lambda: manager)
|
||||
|
||||
result = set_plugin_instance_enabled(
|
||||
"DemoPluginWork", PluginInstanceEnabledRequest(enabled=False), None
|
||||
)
|
||||
|
||||
assert result.success is True
|
||||
assert calls == [("DemoPluginWork", False)]
|
||||
|
||||
|
||||
def test_endpoint_reports_unchanged_state_without_pretending_success(monkeypatch):
|
||||
"""实例不存在或已处于目标状态时如实回报失败,并给出完整句子而非中文片段。"""
|
||||
manager = _manager(set_plugin_instance_enabled=lambda self, *a: False)
|
||||
monkeypatch.setattr(plugintarget_endpoint, "get_plugin_manager", lambda: manager)
|
||||
|
||||
disabled = set_plugin_instance_enabled(
|
||||
"Missing", PluginInstanceEnabledRequest(enabled=False), None
|
||||
)
|
||||
enabled = set_plugin_instance_enabled(
|
||||
"Missing", PluginInstanceEnabledRequest(enabled=True), None
|
||||
)
|
||||
|
||||
assert disabled.success is False
|
||||
assert disabled.message == "实例 Missing 不存在或已处于停用状态"
|
||||
assert enabled.message == "实例 Missing 不存在或已处于启用状态"
|
||||
|
||||
|
||||
def test_endpoint_reports_mutation_rejection_as_a_failed_response(monkeypatch):
|
||||
"""处于停机准入窗口时返回失败响应而不是抛出。"""
|
||||
|
||||
def _raise(*_a):
|
||||
raise PluginMutationRejectedError("插件正在停机")
|
||||
|
||||
manager = _manager(set_plugin_instance_enabled=_raise)
|
||||
monkeypatch.setattr(plugintarget_endpoint, "get_plugin_manager", lambda: manager)
|
||||
|
||||
result = set_plugin_instance_enabled(
|
||||
"DemoPluginWork", PluginInstanceEnabledRequest(enabled=True), None
|
||||
)
|
||||
|
||||
assert result.success is False
|
||||
assert "插件正在停机" in result.message
|
||||
|
||||
|
||||
def test_router_registers_the_enabled_path():
|
||||
"""路由器暴露启停路径,注册在插件前缀下。"""
|
||||
paths = {route.path for route in plugintarget_endpoint.router.routes}
|
||||
assert "/instance/{instance_id}/enabled" in paths
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# 依赖分类必须按装载判据过滤
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_classification_drops_hosts_that_are_not_loadable():
|
||||
"""分类结果会被逐个 start(),停用的本体必须在这里就被剔除。
|
||||
|
||||
物理插件那一层按安装清单划分,而安装清单只回答「包在不在磁盘上」;不过滤的话
|
||||
停用的插件会在开机与配置热重载时被重新拉起来,启用位形同虚设。
|
||||
"""
|
||||
system = SimpleNamespace(
|
||||
dependency=SimpleNamespace(
|
||||
classify_plugins=lambda: (
|
||||
["PluginA", "PluginB"],
|
||||
["PluginC"],
|
||||
["PluginD"],
|
||||
)
|
||||
)
|
||||
)
|
||||
service = PluginDependencyService(
|
||||
system=lambda: system,
|
||||
instances=lambda: {
|
||||
"PluginAx2": PluginInstance(
|
||||
instance_id="PluginAx2", source_plugin_id="PluginA"
|
||||
)
|
||||
},
|
||||
loadable_hosts=lambda: {"PluginA"},
|
||||
log=SimpleNamespace(info=lambda *_a: None, error=lambda *_a: None),
|
||||
)
|
||||
|
||||
classification = service.classify_plugins()
|
||||
|
||||
assert classification.ready == ("PluginA", "PluginAx2")
|
||||
assert classification.missing_dependencies == ()
|
||||
assert classification.missing_source == ()
|
||||
|
||||
|
||||
def test_classification_without_a_loadable_port_keeps_every_plugin():
|
||||
"""未装配装载判据端口时保持原分类,测试与旧调用方不因此丢掉插件。"""
|
||||
system = SimpleNamespace(
|
||||
dependency=SimpleNamespace(
|
||||
classify_plugins=lambda: (["PluginA"], ["PluginC"], ["PluginD"])
|
||||
)
|
||||
)
|
||||
service = PluginDependencyService(
|
||||
system=lambda: system,
|
||||
log=SimpleNamespace(info=lambda *_a: None, error=lambda *_a: None),
|
||||
)
|
||||
|
||||
classification = service.classify_plugins()
|
||||
|
||||
assert classification.ready == ("PluginA",)
|
||||
assert classification.missing_dependencies == ("PluginC",)
|
||||
assert classification.missing_source == ("PluginD",)
|
||||
299
tests/test_plugin_instance_enablement.py
Normal file
299
tests/test_plugin_instance_enablement.py
Normal file
@@ -0,0 +1,299 @@
|
||||
"""插件实例启停语义测试:数据访问层、实例存储与运行期装载取数。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import delete
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db.models.plugininstance import PluginInstance as PluginInstanceRecord
|
||||
from app.db.oper.plugininstance import PluginInstanceOper
|
||||
from app.db.uow import run_sync_transaction
|
||||
from app.runtime.extensions.plugin.storage import PluginInstanceStore, PluginStorage
|
||||
from app.schemas.plugin import PluginInstance
|
||||
|
||||
_INSTANCE_IDS = ("EnablementHost", "EnablementHostX2", "EnablementOther")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def purge_written_rows():
|
||||
"""删除用例写入的行,测试库在整个会话内共享,残留会干扰后续用例。"""
|
||||
yield
|
||||
|
||||
def purge(session: Session) -> None:
|
||||
"""按本文件使用的固定标识精确删除,不触碰其他用例的数据。"""
|
||||
session.execute(
|
||||
delete(PluginInstanceRecord).where(
|
||||
PluginInstanceRecord.instance_id.in_(_INSTANCE_IDS)
|
||||
)
|
||||
)
|
||||
|
||||
run_sync_transaction(purge)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# PluginInstanceOper.set_enabled
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def test_set_enabled_keeps_configuration_when_disabling():
|
||||
"""停用只翻启用位,业务参数与展示信息原样留在那一行等待再次启用。
|
||||
|
||||
这正是这一列存在的理由:把「在册」与「有配置」拆开,让用户能停掉一个实例而
|
||||
不必在「删掉配置」和「留着它继续跑」之间二选一。
|
||||
"""
|
||||
oper = PluginInstanceOper()
|
||||
oper.save(
|
||||
instance_id="EnablementHostX2",
|
||||
source_plugin_id="EnablementHost",
|
||||
plugin_name="分身显示名",
|
||||
is_enabled=True,
|
||||
)
|
||||
oper.save_config_data(
|
||||
instance_id="EnablementHostX2",
|
||||
source_plugin_id="EnablementHost",
|
||||
config_data={"token": "kept"},
|
||||
)
|
||||
|
||||
assert oper.set_enabled(instance_id="EnablementHostX2", is_enabled=False) is True
|
||||
|
||||
record = oper.get("EnablementHostX2")
|
||||
assert record is not None
|
||||
assert record.is_enabled is False
|
||||
assert record.config_data == {"token": "kept"}
|
||||
assert record.plugin_name == "分身显示名"
|
||||
|
||||
# 再次启用即恢复,配置不需要重填
|
||||
assert oper.set_enabled(instance_id="EnablementHostX2", is_enabled=True) is True
|
||||
restored = oper.get("EnablementHostX2")
|
||||
assert restored is not None
|
||||
assert restored.is_enabled is True
|
||||
assert restored.config_data == {"token": "kept"}
|
||||
|
||||
|
||||
def test_disabling_clears_default_target_and_log_level_override():
|
||||
"""停用同时清掉默认调用目标置位与日志等级覆盖,两者只对在册实例才有意义。
|
||||
|
||||
不清默认目标,未指定实例的外部调用会被路由到一个不会被实例化的实例;不清日志
|
||||
等级,运行期停用时清掉的进程内覆盖与库里留下的那份会长期不一致。
|
||||
"""
|
||||
oper = PluginInstanceOper()
|
||||
oper.save(instance_id="EnablementHost", source_plugin_id="EnablementHost", is_enabled=True)
|
||||
oper.save(
|
||||
instance_id="EnablementHostX2",
|
||||
source_plugin_id="EnablementHost",
|
||||
is_enabled=True,
|
||||
)
|
||||
oper.set_default_target("EnablementHost", "EnablementHostX2")
|
||||
oper.set_log_level(
|
||||
instance_id="EnablementHostX2",
|
||||
log_level="DEBUG",
|
||||
log_expires_at=None,
|
||||
)
|
||||
|
||||
oper.set_enabled(instance_id="EnablementHostX2", is_enabled=False)
|
||||
|
||||
record = oper.get("EnablementHostX2")
|
||||
assert record is not None
|
||||
assert record.is_default_target is False
|
||||
assert record.log_level is None
|
||||
assert record.log_expires_at is None
|
||||
|
||||
|
||||
def test_set_enabled_reports_false_for_a_row_that_does_not_exist():
|
||||
"""行不存在时如实返回失败,不隐式建行。"""
|
||||
oper = PluginInstanceOper()
|
||||
|
||||
assert oper.set_enabled(instance_id="EnablementMissing", is_enabled=True) is False
|
||||
assert oper.get("EnablementMissing") is None
|
||||
|
||||
|
||||
def test_list_enabled_excludes_disabled_rows():
|
||||
"""运行期装载取数只看启用中的行。"""
|
||||
oper = PluginInstanceOper()
|
||||
oper.save(instance_id="EnablementHost", source_plugin_id="EnablementHost", is_enabled=True)
|
||||
oper.save(
|
||||
instance_id="EnablementHostX2",
|
||||
source_plugin_id="EnablementHost",
|
||||
is_enabled=False,
|
||||
)
|
||||
|
||||
enabled = {record.instance_id for record in oper.list_enabled()}
|
||||
listed = {record.instance_id for record in oper.list_by_source("EnablementHost")}
|
||||
|
||||
assert "EnablementHost" in enabled
|
||||
assert "EnablementHostX2" not in enabled
|
||||
# 停用的行仍然在册:卡片要看得见、卸载守卫要拦得住
|
||||
assert listed == {"EnablementHost", "EnablementHostX2"}
|
||||
|
||||
|
||||
def test_an_enabled_host_row_is_never_recycled_as_empty():
|
||||
"""启用中的本体行不算「只剩身份列」,清空配置不得把它连同装载判据一起回收。"""
|
||||
oper = PluginInstanceOper()
|
||||
oper.save(instance_id="EnablementHost", source_plugin_id="EnablementHost", is_enabled=True)
|
||||
oper.save_config_data(
|
||||
instance_id="EnablementHost",
|
||||
source_plugin_id="EnablementHost",
|
||||
config_data={"a": 1},
|
||||
)
|
||||
|
||||
oper.clear_config_data("EnablementHost")
|
||||
|
||||
record = oper.get("EnablementHost")
|
||||
assert record is not None, "启用中的本体行被当成空行回收,该插件将永不加载"
|
||||
assert record.is_enabled is True
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# PluginInstanceStore:分身与本体共用一个开关
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
class _FakeDirectory:
|
||||
"""在内存里模拟实例表读写的目录替身。"""
|
||||
|
||||
def __init__(self, records: dict[str, PluginInstance]) -> None:
|
||||
self.records = records
|
||||
|
||||
def get(self, instance_id: str):
|
||||
"""按实例 ID 读取单行。"""
|
||||
return self.records.get(instance_id)
|
||||
|
||||
def list_all(self):
|
||||
"""列出全部行,含停用的。"""
|
||||
return list(self.records.values())
|
||||
|
||||
def list_by_source(self, source_plugin_id: str):
|
||||
"""按源插件列出全部行。"""
|
||||
return [
|
||||
record
|
||||
for record in self.records.values()
|
||||
if record.source_plugin_id == source_plugin_id
|
||||
]
|
||||
|
||||
def list_enabled(self):
|
||||
"""列出启用中的行。"""
|
||||
return [record for record in self.records.values() if record.is_enabled]
|
||||
|
||||
def save(self, instance: PluginInstance) -> None:
|
||||
"""新增或更新一行。"""
|
||||
self.records[instance.instance_id] = instance
|
||||
|
||||
def delete(self, instance_id: str) -> bool:
|
||||
"""删除一行。"""
|
||||
return self.records.pop(instance_id, None) is not None
|
||||
|
||||
def set_enabled(self, instance_id: str, is_enabled: bool) -> bool:
|
||||
"""写入启用位。"""
|
||||
record = self.records.get(instance_id)
|
||||
if record is None:
|
||||
return False
|
||||
self.records[instance_id] = record.model_copy(update={"is_enabled": is_enabled})
|
||||
return True
|
||||
|
||||
|
||||
def _store(records: dict[str, PluginInstance]) -> tuple[PluginInstanceStore, _FakeDirectory]:
|
||||
"""构造挂接内存目录、且旧键导入已标记完成的实例存储。"""
|
||||
directory = _FakeDirectory(records)
|
||||
storage = PluginStorage(read=lambda _key: True, write=lambda _key, _value: None)
|
||||
return (
|
||||
PluginInstanceStore(storage=lambda: storage, directory=lambda: directory),
|
||||
directory,
|
||||
)
|
||||
|
||||
|
||||
def _clone(instance_id: str, source: str, *, enabled: bool = True) -> PluginInstance:
|
||||
"""构造一个分身实例描述。"""
|
||||
return PluginInstance(
|
||||
instance_id=instance_id, source_plugin_id=source, is_enabled=enabled
|
||||
)
|
||||
|
||||
|
||||
def _host(plugin_id: str, *, enabled: bool = True) -> PluginInstance:
|
||||
"""构造一个本体实例描述。"""
|
||||
return PluginInstance(
|
||||
instance_id=plugin_id, source_plugin_id=plugin_id, is_enabled=enabled
|
||||
)
|
||||
|
||||
|
||||
def test_enabled_hosts_is_the_host_loading_criterion():
|
||||
"""本体的装载取数只给出启用中的本体,停用的本体不在其中。"""
|
||||
store, _ = _store(
|
||||
{
|
||||
"PluginA": _host("PluginA"),
|
||||
"PluginB": _host("PluginB", enabled=False),
|
||||
"PluginAx2": _clone("PluginAx2", "PluginA"),
|
||||
}
|
||||
)
|
||||
|
||||
assert set(store.enabled_hosts()) == {"PluginA"}
|
||||
# 分身不混进本体取数
|
||||
assert set(store.enabled()) == {"PluginAx2"}
|
||||
|
||||
|
||||
def test_disabled_clone_stays_registered_and_visible():
|
||||
"""停用的分身仍在册:卡片列表、卸载守卫与默认目标候选都要看得见它。
|
||||
|
||||
读取口若替调用方把停用的行藏起来,卸载守卫会放过一个还留着行的分身,用户随后
|
||||
只能看到一个既列不出来、也删不掉的孤儿实例。
|
||||
"""
|
||||
store, _ = _store(
|
||||
{"PluginA": _host("PluginA"), "PluginAx2": _clone("PluginAx2", "PluginA")}
|
||||
)
|
||||
assert store.disable("PluginAx2") is True
|
||||
|
||||
assert set(store.all()) == {"PluginAx2"}
|
||||
assert [record.instance_id for record in store.for_source("PluginA")] == ["PluginAx2"]
|
||||
assert store.get("PluginAx2") is not None
|
||||
assert set(store.enabled()) == set()
|
||||
|
||||
|
||||
def test_enable_and_disable_report_whether_state_changed():
|
||||
"""重复启用或重复停用报告未发生变化,调用方据此决定要不要重载运行态。"""
|
||||
store, _ = _store(
|
||||
{"PluginA": _host("PluginA"), "PluginAx2": _clone("PluginAx2", "PluginA")}
|
||||
)
|
||||
|
||||
assert store.disable("PluginAx2") is True
|
||||
assert store.disable("PluginAx2") is False
|
||||
assert store.enable("PluginAx2") is True
|
||||
assert store.enable("PluginAx2") is False
|
||||
|
||||
|
||||
def test_enable_host_creates_the_row_when_the_plugin_has_none():
|
||||
"""安装收尾时本体还没有行,必须按默认视图建出并置为启用。
|
||||
|
||||
只往安装清单里加一条而不建这一行,插件会装完当次靠定向重载跑起来、重启后再也
|
||||
不加载。
|
||||
"""
|
||||
store, directory = _store({})
|
||||
|
||||
assert store.enable_host("PluginA") is True
|
||||
|
||||
record = directory.records["PluginA"]
|
||||
assert record.is_host is True
|
||||
assert record.is_enabled is True
|
||||
assert store.enable_host("PluginA") is False
|
||||
|
||||
|
||||
def test_disable_host_keeps_the_row_and_its_configuration():
|
||||
"""停用本体保留整行,只翻启用位。"""
|
||||
store, directory = _store({"PluginA": _host("PluginA")})
|
||||
|
||||
assert store.disable_host("PluginA") is True
|
||||
assert store.disable_host("PluginA") is False
|
||||
|
||||
assert directory.records["PluginA"].is_enabled is False
|
||||
assert store.get_host("PluginA") is not None
|
||||
|
||||
|
||||
def test_host_and_clone_views_never_leak_into_each_other():
|
||||
"""本体与分身两组读写口互不可见,避免按分身写入顶掉本体那一行。"""
|
||||
store, _ = _store(
|
||||
{"PluginA": _host("PluginA"), "PluginAx2": _clone("PluginAx2", "PluginA")}
|
||||
)
|
||||
|
||||
assert store.get("PluginA") is None
|
||||
assert store.get_host("PluginAx2") is None
|
||||
assert set(store.all_hosts()) == {"PluginA"}
|
||||
assert set(store.all()) == {"PluginAx2"}
|
||||
152
tests/test_plugin_instance_enablement_migration.py
Normal file
152
tests/test_plugin_instance_enablement_migration.py
Normal file
@@ -0,0 +1,152 @@
|
||||
"""插件实例启用位 Alembic 迁移测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
from app.db.models.plugininstance import PluginInstance
|
||||
|
||||
MIGRATION_MODULE = "database.versions.b7d1e4a9c206_3_0_38"
|
||||
|
||||
|
||||
def _bind_migration(monkeypatch, connection):
|
||||
"""把迁移绑定到隔离数据库连接。"""
|
||||
migration = importlib.import_module(MIGRATION_MODULE)
|
||||
context = MigrationContext.configure(connection)
|
||||
monkeypatch.setattr(migration, "op", Operations(context))
|
||||
return migration
|
||||
|
||||
|
||||
def _create_legacy_schema(connection: sa.engine.Connection, *, installed=None) -> sa.Table:
|
||||
"""建出加列前的实例表与系统设置表,模拟迁移前的存量数据库。"""
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
table = sa.Table(
|
||||
"plugininstance",
|
||||
sa.MetaData(),
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("instance_id", sa.String(length=128), nullable=False),
|
||||
sa.Column("source_plugin_id", sa.String(length=128), nullable=False),
|
||||
sa.Column("plugin_name", sa.String(length=255)),
|
||||
sa.Column("plugin_desc", sa.String(length=255)),
|
||||
sa.Column("plugin_icon", sa.String(length=255)),
|
||||
sa.Column("is_default_target", sa.Boolean(), nullable=False, server_default=sa.false()),
|
||||
sa.Column("log_level", sa.String(length=16)),
|
||||
sa.Column("log_expires_at", sa.String(length=40)),
|
||||
sa.Column("config_data", sa.JSON()),
|
||||
sa.Column("created_at", sa.String(length=40), nullable=False),
|
||||
sa.Column("updated_at", sa.String(length=40), nullable=False),
|
||||
)
|
||||
table.create(connection)
|
||||
connection.execute(
|
||||
table.insert().values(
|
||||
instance_id="DemoPluginWork",
|
||||
source_plugin_id="DemoPlugin",
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
systemconfig = sa.Table(
|
||||
"systemconfig",
|
||||
sa.MetaData(),
|
||||
sa.Column("id", sa.Integer(), primary_key=True),
|
||||
sa.Column("key", sa.String(length=255)),
|
||||
sa.Column("value", sa.Text()),
|
||||
)
|
||||
systemconfig.create(connection)
|
||||
if installed is not None:
|
||||
connection.execute(
|
||||
systemconfig.insert().values(
|
||||
key="UserInstalledPlugins",
|
||||
value=json.dumps(installed),
|
||||
)
|
||||
)
|
||||
return table
|
||||
|
||||
|
||||
def test_enablement_migration_enables_existing_rows_and_backfills_hosts(monkeypatch) -> None:
|
||||
"""存量分身一律置真,安装清单里的插件补出启用中的本体行;重复升级保持幂等。
|
||||
|
||||
列建出来默认为假而不回填,升级后全部插件都会变成「装着但永不加载」——这一列
|
||||
同时是本体的装载判据,回填因此是迁移的正文而不是附带步骤。
|
||||
"""
|
||||
engine = sa.create_engine("sqlite://")
|
||||
with engine.begin() as connection:
|
||||
_create_legacy_schema(connection, installed=["DemoPlugin", "OtherPlugin"])
|
||||
migration = _bind_migration(monkeypatch, connection)
|
||||
|
||||
migration.upgrade()
|
||||
migration.upgrade()
|
||||
|
||||
table = sa.Table("plugininstance", sa.MetaData(), autoload_with=connection)
|
||||
rows = {
|
||||
row["instance_id"]: row
|
||||
for row in connection.execute(sa.select(table)).mappings().all()
|
||||
}
|
||||
assert set(rows) == {"DemoPluginWork", "DemoPlugin", "OtherPlugin"}
|
||||
assert all(bool(row["is_enabled"]) for row in rows.values())
|
||||
# 本体行按自身 ID 建出,两列身份相等
|
||||
assert rows["OtherPlugin"]["source_plugin_id"] == "OtherPlugin"
|
||||
# 已有的分身行没有被重复插入,也没有被改写归属
|
||||
assert rows["DemoPluginWork"]["source_plugin_id"] == "DemoPlugin"
|
||||
|
||||
migration.downgrade()
|
||||
assert "is_enabled" not in {
|
||||
column["name"] for column in sa.inspect(connection).get_columns("plugininstance")
|
||||
}
|
||||
|
||||
|
||||
def test_enablement_migration_tolerates_a_missing_installed_list(monkeypatch) -> None:
|
||||
"""安装清单不存在时只补启用位,不因读不到清单而中断升级。"""
|
||||
engine = sa.create_engine("sqlite://")
|
||||
with engine.begin() as connection:
|
||||
_create_legacy_schema(connection, installed=None)
|
||||
migration = _bind_migration(monkeypatch, connection)
|
||||
|
||||
migration.upgrade()
|
||||
|
||||
table = sa.Table("plugininstance", sa.MetaData(), autoload_with=connection)
|
||||
rows = connection.execute(sa.select(table)).mappings().all()
|
||||
assert [row["instance_id"] for row in rows] == ["DemoPluginWork"]
|
||||
assert bool(rows[0]["is_enabled"]) is True
|
||||
|
||||
|
||||
def test_enablement_migration_ignores_a_malformed_installed_list(monkeypatch) -> None:
|
||||
"""安装清单不是字符串数组时按空清单处理,不能让升级崩在一条脏数据上。"""
|
||||
engine = sa.create_engine("sqlite://")
|
||||
with engine.begin() as connection:
|
||||
_create_legacy_schema(connection, installed=None)
|
||||
systemconfig = sa.Table("systemconfig", sa.MetaData(), autoload_with=connection)
|
||||
connection.execute(
|
||||
systemconfig.insert().values(key="UserInstalledPlugins", value="not-json")
|
||||
)
|
||||
migration = _bind_migration(monkeypatch, connection)
|
||||
|
||||
migration.upgrade()
|
||||
|
||||
table = sa.Table("plugininstance", sa.MetaData(), autoload_with=connection)
|
||||
assert [
|
||||
row["instance_id"]
|
||||
for row in connection.execute(sa.select(table)).mappings().all()
|
||||
] == ["DemoPluginWork"]
|
||||
|
||||
|
||||
def test_enablement_migration_accepts_fresh_current_schema(monkeypatch) -> None:
|
||||
"""create_all 已建当前表时重复升级不得因列已存在而报错。"""
|
||||
engine = sa.create_engine("sqlite://")
|
||||
with engine.begin() as connection:
|
||||
PluginInstance.__table__.create(connection)
|
||||
migration = _bind_migration(monkeypatch, connection)
|
||||
|
||||
migration.upgrade()
|
||||
migration.upgrade()
|
||||
|
||||
assert {
|
||||
column["name"]
|
||||
for column in sa.inspect(connection).get_columns("plugininstance")
|
||||
} == {column.name for column in PluginInstance.__table__.columns}
|
||||
@@ -38,7 +38,7 @@ def _lifecycle(*, plugins, running=None):
|
||||
classes=classes,
|
||||
running=running,
|
||||
load_plugins=lambda _pid, _installed, _check: list(plugins),
|
||||
installed_plugins=lambda: ["DemoPluginWork"],
|
||||
loadable_plugins=lambda: ["DemoPluginWork"],
|
||||
plugin_config=lambda _pid: {},
|
||||
auth_checker=lambda _plugin: True,
|
||||
clear_modules=MagicMock(),
|
||||
|
||||
@@ -41,7 +41,7 @@ def _lifecycle(
|
||||
classes=classes,
|
||||
running=running,
|
||||
load_plugins=lambda _plugin_id, _installed, _check: list(plugins),
|
||||
installed_plugins=lambda: ["DemoPlugin"],
|
||||
loadable_plugins=lambda: ["DemoPlugin"],
|
||||
plugin_config=lambda _plugin_id: {},
|
||||
auth_checker=lambda _plugin: auth,
|
||||
clear_modules=MagicMock(),
|
||||
|
||||
@@ -52,3 +52,73 @@ def test_invoke_plugin_keeps_legacy_action_id_fallback() -> None:
|
||||
_, result = _execute_with_action({"action_id": "cleanup"})
|
||||
|
||||
assert result.content == "before"
|
||||
|
||||
|
||||
def test_invoke_plugin_dispatches_to_resolved_default_target() -> None:
|
||||
"""插件 ID 有分身时,动作按裁决出的默认调用目标查询动作,而不是原样使用插件 ID。
|
||||
|
||||
这是历史工作流在源插件本体停用、仅分身启用后仍能继续工作的关键:存量工作流
|
||||
保存的还是物理插件 ID,必须经过默认调用目标裁决才能落到实际在跑的分身上。
|
||||
"""
|
||||
context = ActionContext(content="before")
|
||||
action = {"id": "cleanup"}
|
||||
action_fn = Mock(return_value=(True, context))
|
||||
action["func"] = action_fn
|
||||
plugin_manager = Mock()
|
||||
plugin_manager.resolve_plugin_call_target.return_value = "plugin-a-clone"
|
||||
plugin_manager.get_plugin_actions.return_value = [
|
||||
{"plugin_id": "plugin-a-clone", "actions": [action]}
|
||||
]
|
||||
|
||||
with patch(
|
||||
"app.workflow.actions.get_configured_system_config",
|
||||
return_value=Mock(),
|
||||
), patch(
|
||||
"app.workflow.actions.invoke_plugin.get_plugin_manager",
|
||||
return_value=plugin_manager,
|
||||
):
|
||||
action_runner = InvokePluginAction("invoke")
|
||||
action_runner.execute(
|
||||
workflow_id=1,
|
||||
params={
|
||||
"plugin_id": "plugin-a",
|
||||
"action_id": "cleanup",
|
||||
"action_params": {},
|
||||
},
|
||||
context=context,
|
||||
)
|
||||
|
||||
plugin_manager.resolve_plugin_call_target.assert_called_once_with("plugin-a")
|
||||
plugin_manager.get_plugin_actions.assert_called_once_with("plugin-a-clone")
|
||||
assert action_runner.success is True
|
||||
|
||||
|
||||
def test_invoke_plugin_fails_gracefully_when_default_target_undecidable() -> None:
|
||||
"""裁决报错(未设默认目标/默认目标已停用)时动作失败但不抛出,不误执行任何实例。"""
|
||||
context = ActionContext(content="before")
|
||||
plugin_manager = Mock()
|
||||
plugin_manager.resolve_plugin_call_target.side_effect = LookupError(
|
||||
"插件 plugin-a 未设置默认实例,调用必须显式指定实例;可选实例:a(已启用)、b(已启用)"
|
||||
)
|
||||
|
||||
with patch(
|
||||
"app.workflow.actions.get_configured_system_config",
|
||||
return_value=Mock(),
|
||||
), patch(
|
||||
"app.workflow.actions.invoke_plugin.get_plugin_manager",
|
||||
return_value=plugin_manager,
|
||||
):
|
||||
action_runner = InvokePluginAction("invoke")
|
||||
result = action_runner.execute(
|
||||
workflow_id=1,
|
||||
params={
|
||||
"plugin_id": "plugin-a",
|
||||
"action_id": "cleanup",
|
||||
"action_params": {},
|
||||
},
|
||||
context=context,
|
||||
)
|
||||
|
||||
plugin_manager.get_plugin_actions.assert_not_called()
|
||||
assert action_runner.success is False
|
||||
assert result.content == "before"
|
||||
|
||||
Reference in New Issue
Block a user