from __future__ import annotations import asyncio import importlib import sys import tempfile import unittest import zipfile from pathlib import Path from PIL import Image from tests.helpers import install_httpx_stub, install_runtime_stubs install_runtime_stubs() httpx_stub = install_httpx_stub() sys.modules.pop("services.komga", None) from services.archive import ArchiveService # noqa: E402 from services.download import DownloadedComic # noqa: E402 from services.settings import PluginSettings # noqa: E402 komga_module = importlib.import_module("services.komga") KomgaClient = komga_module.KomgaClient class ArchiveKomgaIntegrationTest(unittest.TestCase): def test_archive_then_trigger_komga_scan(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, 4): path = image_dir / f"{index:05d}.jpg" Image.new("RGB", (8, 8), (index * 40, 0, 0)).save(path) image_files.append(path) settings = PluginSettings.from_config( { "archive_root": str(root / "library"), "archive_format": "cbz", "komga": { "enabled": True, "base_url": "http://komga.local", "library_id": "library/中文", "api_key": "secret", }, }, root / "data", ) settings.ensure_dirs() comic = DownloadedComic( comic_id="654321", title="集成测试", work_dir=root / "work", download_dir=image_dir, image_files=image_files, ) archive_result = asyncio.run(ArchiveService(settings).archive(comic)) scan_result = asyncio.run(KomgaClient(settings.komga).scan_library()) self.assertTrue(archive_result.path.exists()) with zipfile.ZipFile(archive_result.path) as archive: self.assertIn("ComicInfo.xml", archive.namelist()) self.assertIn("0003.jpg", archive.namelist()) self.assertTrue(scan_result.success) self.assertEqual(len(httpx_stub.calls), 1) self.assertEqual( httpx_stub.calls[0]["url"], "http://komga.local/api/v1/libraries/library%2F%E4%B8%AD%E6%96%87/scan", ) self.assertEqual(httpx_stub.calls[0]["headers"], {"X-API-Key": "secret"}) self.assertIsNone(httpx_stub.calls[0]["auth"]) if __name__ == "__main__": unittest.main()