S-14 单元测试

这个提交存在于:
Codex 2026-07-07 00:38:01 +08:00
父节点 a28ef3e971
当前提交 4230203c49
共有 6 个文件被更改,包括 184 次插入 和 0 次删除

查看文件

@ -45,3 +45,9 @@ CBZ 内部会包含:
```text
POST /api/v1/libraries/{libraryId}/scan
```
## 测试
```bash
python -m unittest discover -s tests
```

26
tests/helpers.py 普通文件
查看文件

@ -0,0 +1,26 @@
from __future__ import annotations
import sys
import types
def install_runtime_stubs() -> None:
"""Install tiny stubs for optional runtime modules used by service imports."""
if "astrbot.api" not in sys.modules:
logger = types.SimpleNamespace(
info=lambda *args, **kwargs: None,
warning=lambda *args, **kwargs: None,
error=lambda *args, **kwargs: None,
exception=lambda *args, **kwargs: None,
)
astrbot = types.ModuleType("astrbot")
api = types.ModuleType("astrbot.api")
api.logger = logger
sys.modules["astrbot"] = astrbot
sys.modules["astrbot.api"] = api
if "yaml" not in sys.modules:
yaml = types.ModuleType("yaml")
yaml.safe_dump = lambda *args, **kwargs: ""
sys.modules["yaml"] = yaml

58
tests/test_archive.py 普通文件
查看文件

@ -0,0 +1,58 @@
from __future__ import annotations
import asyncio
import tempfile
import unittest
import zipfile
from pathlib import Path
from PIL import Image
from tests.helpers import install_runtime_stubs
install_runtime_stubs()
from services.archive import ArchiveService # noqa: E402
from services.download import DownloadedComic # noqa: E402
from services.settings import PluginSettings # noqa: E402
class ArchiveServiceTest(unittest.TestCase):
def test_cbz_contains_comic_info_and_ordered_pages(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
root = Path(temp_dir)
image_dir = root / "downloaded"
image_dir.mkdir()
image_files = []
for index in range(1, 3):
path = image_dir / f"{index:05d}.jpg"
Image.new("RGB", (8, 8), (index * 60, 0, 0)).save(path)
image_files.append(path)
settings = PluginSettings.from_config(
{"archive_root": str(root / "library"), "archive_format": "cbz"},
root / "data",
)
settings.ensure_dirs()
comic = DownloadedComic(
comic_id="123456",
title="测试标题",
work_dir=root / "work",
download_dir=image_dir,
image_files=image_files,
)
result = asyncio.run(ArchiveService(settings).archive(comic))
with zipfile.ZipFile(result.path) as archive:
names = archive.namelist()
self.assertIn("ComicInfo.xml", names)
self.assertIn("0001.jpg", names)
self.assertIn("0002.jpg", names)
comic_info = archive.read("ComicInfo.xml").decode("utf-8")
self.assertIn("<Series>测试标题</Series>", comic_info)
self.assertIn("<Number>123456</Number>", comic_info)
if __name__ == "__main__":
unittest.main()

44
tests/test_cleanup.py 普通文件
查看文件

@ -0,0 +1,44 @@
from __future__ import annotations
import tempfile
import unittest
from pathlib import Path
from tests.helpers import install_runtime_stubs
install_runtime_stubs()
from services.download import JMDownloadService # noqa: E402
from services.errors import DownloadError # noqa: E402
from services.settings import PluginSettings # noqa: E402
class CleanupTest(unittest.TestCase):
def test_cleanup_old_work_dirs_removes_children_only(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
settings = PluginSettings.from_config(
{"cleanup_retention_days": 0},
Path(temp_dir) / "data",
)
settings.ensure_dirs()
child = settings.work_root / "old-job"
child.mkdir(parents=True)
removed = JMDownloadService(settings).cleanup_old_work_dirs()
self.assertEqual(removed, 1)
self.assertFalse(child.exists())
def test_cleanup_refuses_path_outside_work_root(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
root = Path(temp_dir)
settings = PluginSettings.from_config({}, root / "data")
settings.ensure_dirs()
service = JMDownloadService(settings)
with self.assertRaises(DownloadError):
service._remove_work_dir(root)
if __name__ == "__main__":
unittest.main()

18
tests/test_images.py 普通文件
查看文件

@ -0,0 +1,18 @@
from __future__ import annotations
import unittest
from services.images import natural_key, safe_filename
class ImageHelpersTest(unittest.TestCase):
def test_safe_filename_removes_invalid_characters(self) -> None:
self.assertEqual(safe_filename('A:B*C?"D<>|'), "A_B_C__D___")
def test_natural_key_sorts_numbered_names(self) -> None:
names = ["10.jpg", "2.jpg", "1.jpg"]
self.assertEqual(sorted(names, key=natural_key), ["1.jpg", "2.jpg", "10.jpg"])
if __name__ == "__main__":
unittest.main()

32
tests/test_settings.py 普通文件
查看文件

@ -0,0 +1,32 @@
from __future__ import annotations
import tempfile
import unittest
from pathlib import Path
from services.settings import PluginSettings
class SettingsTest(unittest.TestCase):
def test_invalid_numbers_fall_back_to_defaults(self) -> None:
with tempfile.TemporaryDirectory() as temp_dir:
settings = PluginSettings.from_config(
{
"archive_format": "invalid",
"pdf_chunk_size": "bad",
"download_timeout_seconds": "bad",
"jm_batch_count": "bad",
"komga": {"scan_timeout_seconds": "bad"},
},
Path(temp_dir),
)
self.assertEqual(settings.archive_format, "cbz")
self.assertEqual(settings.pdf_chunk_size, 80)
self.assertEqual(settings.download_timeout_seconds, 3600)
self.assertEqual(settings.jm_batch_count, 20)
self.assertEqual(settings.komga.scan_timeout_seconds, 30)
if __name__ == "__main__":
unittest.main()