from __future__ import annotations import json import tempfile import unittest from pathlib import Path from unittest.mock import patch from PIL import Image from pixiv_app.core.library import PixivLibrary from pixiv_app.core.gallery_service import LocalGalleryService from pixiv_app.core.thumbnails import ThumbnailCache from pixiv_app.gui.app import SakuraDownloaderGUI class _HealthResponse: status = 200 def __enter__(self) -> "_HealthResponse": return self def __exit__(self, *args) -> None: return None def read(self, _limit: int) -> bytes: return json.dumps({"status": "ok"}).encode("utf-8") class LocalGalleryCreationTests(unittest.TestCase): def test_gallery_readiness_uses_health_endpoint(self) -> None: app = object.__new__(SakuraDownloaderGUI) with patch("pixiv_app.gui.app.urllib.request.urlopen", return_value=_HealthResponse()) as mocked: self.assertTrue(app.is_gallery_wall_ready("http://127.0.0.1:8765")) self.assertEqual(mocked.call_args.args[0], "http://127.0.0.1:8765/api/health") def test_thumbnail_cache_creates_local_parent_directories(self) -> None: with tempfile.TemporaryDirectory() as directory: root = Path(directory) db_path = root / "data" / "library.db" cache_dir = root / "data" / "runtime" / "thumbnails" source = root / "source.png" Image.new("RGB", (640, 480), "#f4aac6").save(source) library = PixivLibrary(db_path) try: library.connection.execute( "INSERT INTO artworks (artwork_id, type, title, created_at, updated_at) VALUES (?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)", (1001, "illust", "local thumbnail"), ) library.connection.execute( "INSERT INTO artwork_files (artwork_id, page_index, file_path, source_url, status, updated_at) VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)", (1001, 0, str(source), "", "downloaded"), ) library.connection.commit() finally: library.close() results = ThumbnailCache(db_path=db_path, cache_dir=cache_dir).ensure_for_artwork(1001) self.assertEqual(len(results), 1) self.assertTrue(Path(results[0].thumbnail_path).is_file()) self.assertTrue(db_path.is_file()) def test_gallery_service_creates_database_immediately(self) -> None: with tempfile.TemporaryDirectory() as directory: root = Path(directory) db_path = root / "data" / "library.db" LocalGalleryService(db_path=db_path, thumbnail_dir=root / "data" / "thumbs") self.assertTrue(db_path.is_file()) if __name__ == "__main__": unittest.main()