diff --git a/main.py b/main.py index 4989126..e4d59b2 100644 --- a/main.py +++ b/main.py @@ -6,8 +6,16 @@ dispatch helpers for the runtime layer without starting a standalone server. from __future__ import annotations +import sys +from pathlib import Path from typing import Any + +PLUGIN_ROOT = Path(__file__).resolve().parent +if str(PLUGIN_ROOT) not in sys.path: + # AstrBot may import the plugin entrypoint without adding the plugin root. + sys.path.insert(0, str(PLUGIN_ROOT)) + from adapters.astrbot_adapter import ( dispatch_extension_request, register_astrbot_runtime, diff --git a/tests/test_astrbot_entrypoint_import.py b/tests/test_astrbot_entrypoint_import.py new file mode 100644 index 0000000..08f045a --- /dev/null +++ b/tests/test_astrbot_entrypoint_import.py @@ -0,0 +1,47 @@ +import os +import subprocess +import sys +import tempfile +import textwrap +import unittest +from pathlib import Path + + +class AstrBotEntrypointImportTest(unittest.TestCase): + def test_main_imports_when_plugin_root_is_not_on_sys_path(self): + repo_root = Path(__file__).resolve().parents[1] + code = textwrap.dedent( + f""" + import importlib.util + import json + import sys + from pathlib import Path + + repo_root = Path({str(repo_root)!r}) + sys.path = [p for p in sys.path if Path(p or ".").resolve() != repo_root] + spec = importlib.util.spec_from_file_location( + "imagestudio_runtime_entry", + repo_root / "main.py", + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + manifest = module.get_plugin_manifest() + print(json.dumps({{"plugin_name": manifest["plugin_name"]}})) + """ + ) + with tempfile.TemporaryDirectory() as tmp: + env = dict(os.environ) + env.pop("PYTHONPATH", None) + result = subprocess.run( + [sys.executable, "-c", code], + cwd=tmp, + env=env, + check=True, + capture_output=True, + text=True, + ) + self.assertIn("astrbot_plugin_imagestudio", result.stdout) + + +if __name__ == "__main__": + unittest.main()