astrbot_plugin_imagestudio/tests/test_media_index_service.py
2026-07-06 03:18:33 +08:00

68 行
2.7 KiB
Python

from __future__ import annotations
import tempfile
import unittest
from pathlib import Path
from backend.routes.media_routes import index_media
from backend.services.media_index_service import MediaIndexService
from backend.services.media_service import MediaService
from core.config_service import ConfigService
from core.identity import RequestContext
class MediaIndexServiceTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.root = Path(self.tmp.name)
self.config_path = self.root / "config.yaml"
self.config_path.write_text(
f"""
storage:
images_path: "{(self.root / "images").as_posix()}"
thumbnails_path: "{(self.root / "thumbnails").as_posix()}"
materials_path: "{(self.root / "materials").as_posix()}"
styles_path: "{(self.root / "styles").as_posix()}"
archives_path: "{(self.root / "archives").as_posix()}"
temp_path: "{(self.root / "temp").as_posix()}"
""",
encoding="utf-8",
)
for folder in ("images", "thumbnails", "materials", "styles", "archives", "temp"):
(self.root / folder).mkdir(parents=True, exist_ok=True)
(self.root / "images" / "a.png").write_bytes(b"aaa")
(self.root / "images" / "nested").mkdir()
(self.root / "images" / "nested" / "b.png").write_bytes(b"bb")
(self.root / "materials" / "mat.png").write_bytes(b"m")
self.media_service = MediaService(ConfigService(self.config_path))
self.index_service = MediaIndexService(self.media_service)
self.ctx = RequestContext.from_astrbot(username="admin", user_id="user_001")
def tearDown(self):
self.tmp.cleanup()
def test_index_files_returns_storage_uris_without_local_paths(self):
index = self.index_service.index_files(root="images")
self.assertEqual(index["total"], 2)
self.assertFalse(index["truncated"])
self.assertEqual(
[item["uri"] for item in index["items"]],
["storage://images/a.png", "storage://images/nested/b.png"],
)
self.assertEqual(index["items"][0]["bytes"], 3)
self.assertNotIn(str(self.root), str(index))
def test_index_media_route_requires_authentication_and_honors_limit(self):
response = index_media(self.ctx, {"limit": "1"}, self.index_service)
anonymous = index_media(RequestContext(), {}, self.index_service)
self.assertTrue(response["ok"])
self.assertEqual(len(response["data"]["items"]), 1)
self.assertTrue(response["data"]["truncated"])
self.assertFalse(anonymous["ok"])
self.assertEqual(anonymous["error_code"], "UNAUTHORIZED")
if __name__ == "__main__":
unittest.main()