From 0fbbd79a51e16bc7b05a88be479125bc0827819b Mon Sep 17 00:00:00 2001 From: zzz27578 <2950506809@qq.com> Date: Tue, 10 Nov 2026 17:48:08 +0800 Subject: [PATCH 1/2] fix(plugins): report missing entries and update reload failures --- astrbot/core/star/star_manager.py | 12 +- astrbot/dashboard/services/plugin_service.py | 1 - tests/test_fastapi_v1_dashboard.py | 68 ++++++++ tests/test_plugin_manager.py | 156 +++++++++++++++++++ 4 files changed, 235 insertions(+), 2 deletions(-) diff --git a/astrbot/core/star/star_manager.py b/astrbot/core/star/star_manager.py index df2c5e13b97..f45aa7f7dd2 100644 --- a/astrbot/core/star/star_manager.py +++ b/astrbot/core/star/star_manager.py @@ -1101,6 +1101,7 @@ async def load( return False, "未找到任何插件模块" has_load_error = False + found_plugin = False # 导入插件模块,并尝试实例化插件类 for plugin_module in plugin_modules: @@ -1129,6 +1130,8 @@ async def load( if specified_dir_name and root_dir_name != specified_dir_name: continue + found_plugin = True + # Use the directory name until plugin metadata is available. plugin_logger = logging.LoggerAdapter( logger, {"plugin_name": root_dir_name} @@ -1504,6 +1507,9 @@ async def load( self._rebuild_failed_plugin_info() if has_load_error: return False, self.failed_plugin_info + if (specified_module_path or specified_dir_name) and not found_plugin: + target = specified_dir_name or specified_module_path + return False, f"No entry module found for plugin {target}." return True, None async def _cleanup_failed_plugin_install( @@ -1925,7 +1931,11 @@ async def update_plugin( plugin_dir_path, plugin_name, ) - await self.reload(plugin_name) + success, error = await self.reload(plugin_name) + if not success: + raise Exception( + error or f"Failed to reload plugin {plugin_name} after update." + ) async def turn_off_plugin(self, plugin_name: str) -> None: """禁用一个插件。 diff --git a/astrbot/dashboard/services/plugin_service.py b/astrbot/dashboard/services/plugin_service.py index 36e9fa4aba3..8d79c4ca247 100644 --- a/astrbot/dashboard/services/plugin_service.py +++ b/astrbot/dashboard/services/plugin_service.py @@ -1809,7 +1809,6 @@ async def update_plugin(self, data: object) -> tuple[None, str]: repo_url=repo_url, ) await self.refresh_plugin_install_source_after_update(plugin_name, update_info) - await self.plugin_manager.reload(plugin_name) await self.sync_skills_after_plugin_change() logger.info(f"Updated plugin {plugin_name} successfully.") return None, "更新成功。" diff --git a/tests/test_fastapi_v1_dashboard.py b/tests/test_fastapi_v1_dashboard.py index 3926278ab8e..537819ccefb 100644 --- a/tests/test_fastapi_v1_dashboard.py +++ b/tests/test_fastapi_v1_dashboard.py @@ -23,6 +23,7 @@ import astrbot.dashboard.services.config_service as config_service import astrbot.dashboard.services.stat_service as stat_service from astrbot.core import file_token_service +from astrbot.core.star.star_manager import PluginManager from astrbot.core.utils import llm_metadata from astrbot.dashboard.api.app import create_dashboard_asgi_app from astrbot.dashboard.api.backups import download_backup as download_backup_route @@ -3358,6 +3359,73 @@ async def fake_get_plugin_install_sources(): assert update_info["record"]["install_method"] == "repository" +@pytest.mark.asyncio +@pytest.mark.parametrize("batch", [False, True]) +@pytest.mark.parametrize("reload_success", [False, True]) +async def test_v1_plugin_update_reports_reload_result( + asgi_app: FastAPI, + asgi_client: httpx.AsyncClient, + monkeypatch: pytest.MonkeyPatch, + batch: bool, + reload_success: bool, +): + """Report the manager's reload outcome without reloading a second time.""" + plugin_name = "astrbot_plugin_demo" + plugin = SimpleNamespace(name=plugin_name, root_dir_name=None, reserved=False) + reload_error = "Plugin initialization failed" + manager = SimpleNamespace( + context=SimpleNamespace(get_registered_star=Mock(return_value=plugin)), + _updater=SimpleNamespace(update=AsyncMock()), + reload=AsyncMock( + return_value=(reload_success, None if reload_success else reload_error) + ), + ) + + async def update_plugin(*args, **kwargs): + await PluginManager.update_plugin(manager, *args, **kwargs) + + manager.update_plugin = update_plugin + service = asgi_app.state.services.plugins + update_info = {"repo": "https://github.com/example/plugin", "download_url": ""} + refresh_source = AsyncMock() + sync_skills = AsyncMock() + monkeypatch.setattr(service, "plugin_manager", manager) + monkeypatch.setattr( + service, "resolve_market_update_info", AsyncMock(return_value=update_info) + ) + monkeypatch.setattr( + service, "refresh_plugin_install_source_after_update", refresh_source + ) + monkeypatch.setattr(service, "sync_skills_after_plugin_change", sync_skills) + + response = await asgi_client.post( + "/api/v1/plugins/update", + json={"plugin_ids": [plugin_name]} if batch else {"plugin_id": plugin_name}, + headers=_jwt_headers(), + ) + + assert response.status_code == 200 + data = response.json() + if batch: + assert data["status"] == "ok" + result = data["data"]["results"][0] + assert result["name"] == plugin_name + else: + result = data + assert result["status"] == ("ok" if reload_success else "error") + manager.reload.assert_awaited_once_with(plugin_name) + manager._updater.update.assert_awaited_once_with( + plugin, proxy="", download_url="", repo_url=update_info["repo"] + ) + if reload_success: + refresh_source.assert_awaited_once_with(plugin_name, update_info) + sync_skills.assert_awaited_once_with() + else: + assert reload_error not in result["message"] + refresh_source.assert_not_awaited() + sync_skills.assert_not_awaited() + + @pytest.mark.asyncio async def test_v1_plugin_update_all_hides_internal_exceptions( asgi_client: httpx.AsyncClient, diff --git a/tests/test_plugin_manager.py b/tests/test_plugin_manager.py index 77e1fb70cc4..0f6b08bb2de 100644 --- a/tests/test_plugin_manager.py +++ b/tests/test_plugin_manager.py @@ -422,6 +422,30 @@ def local_updater(plugin_manager_pm): return path +@pytest.fixture +def isolated_plugin_loader(plugin_manager_pm, tmp_path, monkeypatch): + """Keep real plugin discovery and loading isolated from persistent state.""" + _clear_star_runtime_state() + monkeypatch.setattr( + plugin_manager_pm, "reserved_plugin_path", str(tmp_path / "reserved") + ) + monkeypatch.setattr( + plugin_manager_pm, "plugin_config_path", str(tmp_path / "config") + ) + monkeypatch.setattr( + plugin_manager_pm.context, "stars", star_manager_module.star_registry + ) + monkeypatch.setattr( + star_manager_module.sp, + "global_get", + AsyncMock(side_effect=lambda key, default=None: default), + ) + monkeypatch.setattr(star_manager_module, "sync_command_configs", AsyncMock()) + yield plugin_manager_pm + _clear_star_runtime_state() + _clear_module_cache() + + # --- Tests --- @@ -1474,6 +1498,111 @@ async def mock_sync_command_configs(): llm_tools.func_list = original_func_list +@pytest.mark.asyncio +@pytest.mark.parametrize("selector", ["specified_dir_name", "specified_module_path"]) +@pytest.mark.parametrize("layout", ["absent", "wrong_entry"]) +async def test_targeted_load_rejects_missing_entry_module( + isolated_plugin_loader: PluginManager, selector: str, layout: str +): + plugin_path = Path(isolated_plugin_loader.plugin_store_path) / TEST_PLUGIN_DIR + if layout == "wrong_entry": + _write_local_test_plugin(plugin_path, TEST_PLUGIN_REPO) + (plugin_path / "main.py").rename(plugin_path / "plugin.py") + else: + other_plugin = plugin_path.with_name("unrelated_plugin") + other_plugin.mkdir() + (other_plugin / "main.py").write_text( + "raise AssertionError('Unrelated plugin must not be imported')\n", + encoding="utf-8", + ) + target = ( + TEST_PLUGIN_DIR + if selector == "specified_dir_name" + else f"data.plugins.{TEST_PLUGIN_DIR}.main" + ) + + success, error = await isolated_plugin_loader.load(**{selector: target}) + + assert success is False + assert error is not None and TEST_PLUGIN_DIR in error + assert star_manager_module.star_registry == [] + star_manager_module.sync_command_configs.assert_awaited_once_with() + + +@pytest.mark.asyncio +async def test_install_uploaded_plugin_rejects_missing_entry_module( + isolated_plugin_loader: PluginManager, tmp_path: Path +): + source_path = tmp_path / "source" + _write_local_test_plugin(source_path, TEST_PLUGIN_REPO) + archive_path = tmp_path / "plugin.zip" + with zipfile.ZipFile(archive_path, "w") as archive: + archive.write(source_path / "metadata.yaml", "metadata.yaml") + archive.writestr("plugin.py", "VALUE = 1\n") + + with pytest.raises(Exception, match=TEST_PLUGIN_DIR): + await isolated_plugin_loader.install_plugin_from_file(str(archive_path)) + + failed_plugin = isolated_plugin_loader.failed_plugin_dict[TEST_PLUGIN_DIR] + assert TEST_PLUGIN_DIR in failed_plugin["error"] + assert star_manager_module.star_registry == [] + + +@pytest.mark.asyncio +async def test_reload_failed_plugin_preserves_failure_when_directory_is_missing( + isolated_plugin_loader: PluginManager, +): + original_failure = {"error": "Original import failure", "reserved": False} + isolated_plugin_loader.failed_plugin_dict[TEST_PLUGIN_DIR] = original_failure + isolated_plugin_loader._rebuild_failed_plugin_info() + + success, error = await isolated_plugin_loader.reload_failed_plugin(TEST_PLUGIN_DIR) + + assert success is False + assert error is not None and TEST_PLUGIN_DIR in error + assert ( + isolated_plugin_loader.failed_plugin_dict[TEST_PLUGIN_DIR] == original_failure + ) + assert "Original import failure" in isolated_plugin_loader.failed_plugin_info + + +@pytest.mark.asyncio +@pytest.mark.parametrize("entry_name", ["main", TEST_PLUGIN_DIR]) +@pytest.mark.parametrize("selector", ["specified_dir_name", "specified_module_path"]) +async def test_targeted_load_accepts_supported_entry_modules( + isolated_plugin_loader: PluginManager, + monkeypatch, + entry_name: str, + selector: str, +): + plugin_store = Path(isolated_plugin_loader.plugin_store_path) + plugin_path = plugin_store / TEST_PLUGIN_DIR + _write_local_test_plugin(plugin_path, TEST_PLUGIN_REPO) + (plugin_path / "main.py").unlink() + (plugin_path / f"{entry_name}.py").write_text( + "from astrbot.api.star import Star\n" + "class Main(Star):\n" + " async def initialize(self):\n" + " self.initialized = True\n", + encoding="utf-8", + ) + for name, path in (("data", plugin_store.parent), ("data.plugins", plugin_store)): + package = ModuleType(name) + package.__path__ = [str(path)] + monkeypatch.setitem(sys.modules, name, package) + module_path = f"data.plugins.{TEST_PLUGIN_DIR}.{entry_name}" + target = TEST_PLUGIN_DIR if selector == "specified_dir_name" else module_path + + success, error = await isolated_plugin_loader.load(**{selector: target}) + + assert success is True, error + plugin = isolated_plugin_loader.context.get_registered_star(TEST_PLUGIN_NAME) + assert plugin is not None + assert plugin.module_path == module_path + assert plugin.star_cls.initialized is True + assert isolated_plugin_loader.failed_plugin_dict == {} + + @pytest.mark.asyncio async def test_load_reports_unregistered_plugin_without_index_error( plugin_manager_pm: PluginManager, monkeypatch @@ -2037,6 +2166,33 @@ def fake_import(name, globals=None, locals=None, fromlist=(), level=0): ] +@pytest.mark.asyncio +@pytest.mark.parametrize( + "reload_result", + [(True, None), (False, "Updated plugin import failed"), (False, None)], + ids=["success", "failure-with-detail", "failure-without-detail"], +) +async def test_update_plugin_propagates_reload_result( + plugin_manager_pm: PluginManager, monkeypatch, reload_result +): + plugin = MockStar() + cast(Any, plugin_manager_pm.context).stars.append(plugin) + update = AsyncMock() + reload = AsyncMock(return_value=reload_result) + monkeypatch.setattr(plugin_manager_pm._updater, "update", update) + monkeypatch.setattr(plugin_manager_pm, "_ensure_plugin_requirements", AsyncMock()) + monkeypatch.setattr(plugin_manager_pm, "reload", reload) + + if reload_result[0]: + await plugin_manager_pm.update_plugin(TEST_PLUGIN_NAME) + else: + with pytest.raises(Exception, match=reload_result[1] or TEST_PLUGIN_NAME): + await plugin_manager_pm.update_plugin(TEST_PLUGIN_NAME) + + update.assert_awaited_once_with(plugin, proxy="", download_url="", repo_url="") + reload.assert_awaited_once_with(TEST_PLUGIN_NAME) + + @pytest.mark.asyncio @pytest.mark.parametrize("dependency_install_fails", [False, True]) async def test_update_plugin_dependency_install_flow( From 81037ac5bb1b648e62d54cb8fb8b03db6515782f Mon Sep 17 00:00:00 2001 From: zzz27578 <2950506809@qq.com> Date: Tue, 10 Nov 2026 18:35:59 +0800 Subject: [PATCH 2/2] fix(plugins): preserve entry changes and sync failed updates --- astrbot/core/star/star_manager.py | 34 ++++++- astrbot/dashboard/services/plugin_service.py | 25 +++-- tests/test_fastapi_v1_dashboard.py | 95 ++++++++++++++++-- tests/test_plugin_manager.py | 100 +++++++++++++++++++ 4 files changed, 235 insertions(+), 19 deletions(-) diff --git a/astrbot/core/star/star_manager.py b/astrbot/core/star/star_manager.py index f45aa7f7dd2..3e4dd75cf71 100644 --- a/astrbot/core/star/star_manager.py +++ b/astrbot/core/star/star_manager.py @@ -1036,6 +1036,8 @@ async def reload(self, specified_plugin_name=None): specified_module_path = smd.module_path break + load_module_path = specified_module_path + # 终止插件 if not specified_module_path: # 重载所有插件 @@ -1058,6 +1060,17 @@ async def reload(self, specified_plugin_name=None): # 只重载指定插件 smd = star_map.get(specified_module_path) if smd: + # Updates may change the entry filename within this plugin. + for plugin_module in self._get_plugin_modules(): + if ( + plugin_module["pname"] == smd.root_dir_name + and plugin_module.get("reserved", False) == smd.reserved + ): + module_prefix = specified_module_path.rsplit(".", 1)[0] + load_module_path = ( + f"{module_prefix}.{plugin_module['module']}" + ) + break try: await self._terminate_plugin(smd) except Exception as e: @@ -1066,10 +1079,27 @@ async def reload(self, specified_plugin_name=None): f"Plugin {smd.name} did not terminate cleanly: {e!s}. " "The plugin may not work correctly.", ) - if smd.name and smd.activated: + if smd.name and ( + smd.activated or load_module_path != specified_module_path + ): await self._unbind_plugin(smd.name, specified_module_path) + if load_module_path != specified_module_path: + # Disabled state is persisted under the entry module path. + inactivated_plugins = await sp.global_get( + "inactivated_plugins", [] + ) + if specified_module_path in inactivated_plugins: + await sp.global_put( + "inactivated_plugins", + [ + load_module_path + if path == specified_module_path + else path + for path in inactivated_plugins + ], + ) - result = await self.load(specified_module_path) + result = await self.load(load_module_path) return result diff --git a/astrbot/dashboard/services/plugin_service.py b/astrbot/dashboard/services/plugin_service.py index 8d79c4ca247..10d48eb28d4 100644 --- a/astrbot/dashboard/services/plugin_service.py +++ b/astrbot/dashboard/services/plugin_service.py @@ -1802,14 +1802,18 @@ async def update_plugin(self, data: object) -> tuple[None, str]: download_url = str(update_info.get("download_url") or "").strip() repo_url = str(update_info.get("repo") or "").strip() logger.info(f"Updating plugin {plugin_name}") - await self.plugin_manager.update_plugin( - plugin_name, - proxy or "", - download_url=download_url, - repo_url=repo_url, - ) - await self.refresh_plugin_install_source_after_update(plugin_name, update_info) - await self.sync_skills_after_plugin_change() + try: + await self.plugin_manager.update_plugin( + plugin_name, + proxy or "", + download_url=download_url, + repo_url=repo_url, + ) + await self.refresh_plugin_install_source_after_update( + plugin_name, update_info + ) + finally: + await self.sync_skills_after_plugin_change() logger.info(f"Updated plugin {plugin_name} successfully.") return None, "更新成功。" @@ -1824,14 +1828,17 @@ async def update_all_plugins(self, data: object) -> tuple[dict, str]: results = [] sem = asyncio.Semaphore(PLUGIN_UPDATE_CONCURRENCY) + attempted_update = False async def _update_one(name: str): + nonlocal attempted_update async with sem: try: logger.info(f"Updating plugin {name} as part of a batch update.") update_info = await self.resolve_market_update_info(name) download_url = str(update_info.get("download_url") or "").strip() repo_url = str(update_info.get("repo") or "").strip() + attempted_update = True await self.plugin_manager.update_plugin( name, proxy, @@ -1886,7 +1893,7 @@ async def _update_one(name: str): results.append(result) failed = [result for result in results if result["status"] == "error"] - if len(failed) < len(results): + if attempted_update: await self.sync_skills_after_plugin_change() message = ( "批量更新完成,全部成功。" diff --git a/tests/test_fastapi_v1_dashboard.py b/tests/test_fastapi_v1_dashboard.py index 537819ccefb..637ceb61b16 100644 --- a/tests/test_fastapi_v1_dashboard.py +++ b/tests/test_fastapi_v1_dashboard.py @@ -3366,19 +3366,51 @@ async def test_v1_plugin_update_reports_reload_result( asgi_app: FastAPI, asgi_client: httpx.AsyncClient, monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, batch: bool, reload_success: bool, ): """Report the manager's reload outcome without reloading a second time.""" + from astrbot.core.astr_agent_runtime.computer import computer_client + from astrbot.core.skills.skill_manager import SkillManager + from astrbot.core.star import star as star_module + plugin_name = "astrbot_plugin_demo" - plugin = SimpleNamespace(name=plugin_name, root_dir_name=None, reserved=False) + plugin = SimpleNamespace( + name=plugin_name, root_dir_name=plugin_name, reserved=False, activated=True + ) + loaded_plugins = [plugin] + plugin_store = tmp_path / "plugins" + skill_dir = plugin_store / plugin_name / "skills" / "demo-skill" + skill_dir.mkdir(parents=True) + (skill_dir / "SKILL.md").write_text("# Demo skill\n", encoding="utf-8") + skill_manager = SkillManager( + skills_root=str(tmp_path / "skills"), plugins_root=str(plugin_store) + ) + skill_manager.config_path = str(tmp_path / "skills.json") + skill_manager.sandbox_skills_cache_path = str(tmp_path / "sandbox-skills.json") + monkeypatch.setattr(star_module, "star_registry", loaded_plugins) + monkeypatch.setattr(computer_client, "SkillManager", lambda **kwargs: skill_manager) + assert computer_client._collect_sync_skill_dirs() == [("demo-skill", skill_dir)] + reload_error = "Plugin initialization failed" + + async def reload_plugin(name): + assert name == plugin_name + if not reload_success: + loaded_plugins.clear() + return reload_success, None if reload_success else reload_error + manager = SimpleNamespace( - context=SimpleNamespace(get_registered_star=Mock(return_value=plugin)), - _updater=SimpleNamespace(update=AsyncMock()), - reload=AsyncMock( - return_value=(reload_success, None if reload_success else reload_error) + context=SimpleNamespace( + get_registered_star=Mock( + side_effect=lambda name: plugin if plugin in loaded_plugins else None + ) ), + plugin_store_path=str(plugin_store), + _updater=SimpleNamespace(update=AsyncMock()), + _ensure_plugin_requirements=AsyncMock(), + reload=AsyncMock(side_effect=reload_plugin), ) async def update_plugin(*args, **kwargs): @@ -3388,7 +3420,12 @@ async def update_plugin(*args, **kwargs): service = asgi_app.state.services.plugins update_info = {"repo": "https://github.com/example/plugin", "download_url": ""} refresh_source = AsyncMock() - sync_skills = AsyncMock() + synced_skills = [] + sync_skills = AsyncMock( + side_effect=lambda: synced_skills.append( + computer_client._collect_sync_skill_dirs() + ) + ) monkeypatch.setattr(service, "plugin_manager", manager) monkeypatch.setattr( service, "resolve_market_update_info", AsyncMock(return_value=update_info) @@ -3417,13 +3454,55 @@ async def update_plugin(*args, **kwargs): manager._updater.update.assert_awaited_once_with( plugin, proxy="", download_url="", repo_url=update_info["repo"] ) + sync_skills.assert_awaited_once_with() + assert synced_skills == [[("demo-skill", skill_dir)] if reload_success else []] if reload_success: refresh_source.assert_awaited_once_with(plugin_name, update_info) - sync_skills.assert_awaited_once_with() else: assert reload_error not in result["message"] refresh_source.assert_not_awaited() - sync_skills.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("batch", [False, True]) +async def test_v1_plugin_update_source_failure_skips_skill_sync( + asgi_app: FastAPI, + asgi_client: httpx.AsyncClient, + monkeypatch: pytest.MonkeyPatch, + batch: bool, +): + """Avoid syncing unchanged plugins when update source resolution fails.""" + plugin_name = "astrbot_plugin_demo" + service = asgi_app.state.services.plugins + update_plugin = AsyncMock() + sync_skills = AsyncMock() + monkeypatch.setattr( + service.plugin_manager, "update_plugin", update_plugin, raising=False + ) + monkeypatch.setattr( + service, + "resolve_market_update_info", + AsyncMock(side_effect=PluginServiceError("Update source is unavailable")), + ) + monkeypatch.setattr(service, "sync_skills_after_plugin_change", sync_skills) + + response = await asgi_client.post( + "/api/v1/plugins/update", + json={"plugin_ids": [plugin_name]} if batch else {"plugin_id": plugin_name}, + headers=_jwt_headers(), + ) + + assert response.status_code == 200 + data = response.json() + if batch: + assert data["status"] == "ok" + result = data["data"]["results"][0] + else: + result = data + assert result["status"] == "error" + assert result["message"] == "Update source is unavailable" + update_plugin.assert_not_awaited() + sync_skills.assert_not_awaited() @pytest.mark.asyncio diff --git a/tests/test_plugin_manager.py b/tests/test_plugin_manager.py index 0f6b08bb2de..d78ab2a920d 100644 --- a/tests/test_plugin_manager.py +++ b/tests/test_plugin_manager.py @@ -1603,6 +1603,106 @@ async def test_targeted_load_accepts_supported_entry_modules( assert isolated_plugin_loader.failed_plugin_dict == {} +@pytest.mark.asyncio +@pytest.mark.parametrize("initial_entry", ["main", TEST_PLUGIN_DIR]) +@pytest.mark.parametrize("disabled", [False, True]) +@pytest.mark.parametrize("reserved", [False, True], ids=["user", "builtin"]) +async def test_plugin_reload_follows_entry_changes_and_preserves_identity( + isolated_plugin_loader: PluginManager, + tmp_path: Path, + monkeypatch, + initial_entry: str, + disabled: bool, + reserved: bool, +): + user_root = Path(isolated_plugin_loader.plugin_store_path) + builtin_root = tmp_path / "reserved" + target_root = builtin_root if reserved else user_root + other_root = user_root if reserved else builtin_root + plugin_path = target_root / TEST_PLUGIN_DIR + other_plugin_path = other_root / TEST_PLUGIN_DIR + _write_local_test_plugin(plugin_path, TEST_PLUGIN_REPO) + _write_local_test_plugin(other_plugin_path, TEST_PLUGIN_REPO) + (other_plugin_path / "main.py").write_text( + "raise AssertionError('Plugin in the other namespace must not be imported')\n", + encoding="utf-8", + ) + namespace = "astrbot.builtin_stars" if reserved else "data.plugins" + next_entry = TEST_PLUGIN_DIR if initial_entry == "main" else "main" + old_module_path = f"{namespace}.{TEST_PLUGIN_DIR}.{initial_entry}" + new_module_path = f"{namespace}.{TEST_PLUGIN_DIR}.{next_entry}" + source = ( + "from astrbot.api.star import Star\n" + "class Main(Star):\n" + " async def initialize(self):\n" + " self.context.initializations.append(__name__)\n" + ) + (plugin_path / "main.py").unlink() + (plugin_path / f"{initial_entry}.py").write_text(source, encoding="utf-8") + for name, path in ( + ("data", user_root.parent), + ("data.plugins", user_root), + ("astrbot.builtin_stars", builtin_root), + ): + package = ModuleType(name) + package.__path__ = [str(path)] + monkeypatch.setitem(sys.modules, name, package) + preferences = {"inactivated_plugins": [old_module_path] if disabled else []} + + async def global_get(key, default=None): + return preferences.get(key, default) + + async def global_put(key, value): + preferences[key] = value + + def replace_entry(*args, **kwargs): + (plugin_path / f"{initial_entry}.py").unlink() + (plugin_path / f"{next_entry}.py").write_text(source, encoding="utf-8") + + monkeypatch.setattr(star_manager_module.sp, "global_get", global_get) + monkeypatch.setattr(star_manager_module.sp, "global_put", global_put) + monkeypatch.setattr( + isolated_plugin_loader.context, "initializations", [], raising=False + ) + monkeypatch.setattr( + isolated_plugin_loader._updater, "update", AsyncMock(side_effect=replace_entry) + ) + try: + success, error = await isolated_plugin_loader.load( + specified_module_path=old_module_path + ) + assert success, error + + if reserved: + replace_entry() + success, error = await isolated_plugin_loader.reload(TEST_PLUGIN_NAME) + assert success, error + else: + await isolated_plugin_loader.update_plugin(TEST_PLUGIN_NAME) + + plugin = isolated_plugin_loader.context.get_registered_star(TEST_PLUGIN_NAME) + assert plugin is not None + assert plugin.module_path == new_module_path + assert plugin.reserved is reserved + assert plugin.activated is (not disabled) + assert (plugin.star_cls is None) is disabled + assert len(star_manager_module.star_registry) == 1 + assert old_module_path not in star_manager_module.star_map + assert old_module_path not in sys.modules + assert isolated_plugin_loader.failed_plugin_dict == {} + assert isolated_plugin_loader.context.initializations == ( + [] if disabled else [old_module_path, new_module_path] + ) + assert preferences["inactivated_plugins"] == ( + [new_module_path] if disabled else [] + ) + finally: + prefix = f"{namespace}.{TEST_PLUGIN_DIR}" + for module_name in list(sys.modules): + if module_name == prefix or module_name.startswith(prefix + "."): + sys.modules.pop(module_name) + + @pytest.mark.asyncio async def test_load_reports_unregistered_plugin_without_index_error( plugin_manager_pm: PluginManager, monkeypatch