import json import httpx import pytest from common.cache.redis_client import REDIS from common.enums import ErrorType from services import shorts_service from services.external.youtube import channel_shorts, feed_shorts, seconds, video_title from services.shorts_service import CACHE_KEY, ShortsService def test_seconds_parses_iso_duration(): assert seconds("PT45S") == 45 assert seconds("PT1M5S") == 65 assert seconds("PT1H") == 3600 assert seconds("P1D") is None def _api(videos: list[dict]) -> httpx.MockTransport: def handle(req: httpx.Request) -> httpx.Response: if req.url.path.endswith("/channels"): return httpx.Response(200, json={"items": [{"contentDetails": {"relatedPlaylists": {"uploads": "UUtest"}}}]}) if req.url.path.endswith("/playlistItems"): assert req.url.params["playlistId"] == "UUtest" return httpx.Response(200, json={"items": [{"contentDetails": {"videoId": v["id"]}} for v in videos]}) return httpx.Response(200, json={"items": videos}) return httpx.MockTransport(handle) def _video(vid: str, duration: str, published: str, embeddable: bool = True, privacy: str = "public") -> dict: return {"id": vid, "snippet": {"title": f"제목 {vid}", "publishedAt": published}, "contentDetails": {"duration": duration}, "status": {"embeddable": embeddable, "privacyStatus": privacy}} @pytest.mark.anyio async def test_channel_shorts_keeps_public_embeddable_short_videos_newest_first(): videos = [ _video("old", "PT30S", "2026-10-20T00:00:00Z"), _video("new", "PT58S", "2026-10-26T00:00:00Z"), _video("long", "PT10M", "2026-10-25T00:00:00Z"), _video("noembed", "PT20S", "2026-10-24T00:00:00Z", embeddable=False), _video("private", "PT20S", "2026-10-23T00:00:00Z", privacy="unlisted"), ] async with httpx.AsyncClient(transport=_api(videos)) as client: found = await channel_shorts(client, "key", "UCtest", 10) assert [v["id"] for v in found] == ["new", "old"] @pytest.mark.anyio async def test_video_title_none_when_embedding_blocked(): def handle(req: httpx.Request) -> httpx.Response: if "blocked" in req.url.params["url"]: return httpx.Response(401) return httpx.Response(200, content=json.dumps({"title": "오늘 자전거각"})) async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client: assert await video_title(client, "ok") == "오늘 자전거각" assert await video_title(client, "blocked") is None def _feed(entries: list[tuple[str, str]]) -> str: items = "".join( f"{vid}제목 {vid}{published}" for vid, published in entries ) return f'{items}' @pytest.mark.anyio async def test_feed_shorts_reads_channel_shorts_feed_newest_first_without_blocked(): seen = {} def handle(req: httpx.Request) -> httpx.Response: if req.url.path.endswith("/feeds/videos.xml"): seen["playlist"] = req.url.params["playlist_id"] return httpx.Response(200, text=_feed([("old", "2026-10-20T00:00:00+00:00"), ("new", "2026-10-28T00:00:00+00:00"), ("blocked", "2026-10-27T00:00:00+00:00")])) if "blocked" in req.url.params["url"]: return httpx.Response(401) return httpx.Response(200, content=json.dumps({"title": "x"})) async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client: found = await feed_shorts(client, "UCtest", 10) assert seen["playlist"] == "UUSHtest" assert [v["id"] for v in found] == ["new", "old"] assert found[0]["title"] == "제목 new" @pytest.mark.anyio async def test_items_reads_cache_and_fetches_only_when_missing(monkeypatch): calls = [] async def fake_fetch(self, client): calls.append(1) return [{"id": "abc", "title": "오늘 자전거각"}] monkeypatch.setattr(shorts_service.ShortsService, "_fetch", fake_fetch) await REDIS.conn.delete(CACHE_KEY) assert await ShortsService().items() == (ErrorType.SUCCESS, [{"id": "abc", "title": "오늘 자전거각"}]) assert await ShortsService().items() == (ErrorType.SUCCESS, [{"id": "abc", "title": "오늘 자전거각"}]) assert len(calls) == 1