from datetime import date, timedelta import pytest from httpx import ASGITransport, AsyncClient from sqlalchemy import text from common.database.db_session_manager import DB_SESSION_MNG from common.enums import PostType from crud.feed_crud import FeedCRUD from crud.season_crud import SeasonCRUD from router.router import app from services.feed_service import build_feed_day REGION = "1114000000" async def _posts(day: date): _, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT post_type FROM post WHERE feed_date='{day}' ORDER BY position"))) return [r[0] for r in rows] @pytest.mark.anyio async def test_build_day_adds_weekend_post_every_day(): monday, thursday = date(2026, 10, 12), date(2026, 10, 15) await build_feed_day(monday, FeedCRUD(), SeasonCRUD()) await build_feed_day(thursday, FeedCRUD(), SeasonCRUD()) await build_feed_day(thursday, FeedCRUD(), SeasonCRUD()) assert (await _posts(monday)).count(PostType.WEEK.value) == 1 assert (await _posts(thursday)).count(PostType.WEEK.value) == 1 assert (await _posts(thursday))[0] == PostType.WEATHER.value def test_weekends_groups_this_and_next_weekend(): from types import SimpleNamespace from services.feed_service import _weekends days = [SimpleNamespace(day=date(2026, 10, 7) + timedelta(days=i)) for i in range(11)] assert [[d.day.day for d in w] for w in _weekends(days)] == [[10, 11], [17]] @pytest.mark.anyio async def test_feed_assembles_hero_stories_posts_and_bands(offline): async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: body = (await client.get("/v1/feed", params={"region": REGION})).json() assert body["result"]["success"] is True assert body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"] assert len(body["stories"]) == 27 weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value) assert [s["kind"] for s in weather["slides"]] == ["hours", "rows"] assert len(weather["slides"][0]["hours"]) == 8 assert body["bands"]["events"][0]["name"] == "테스트 축제" def test_feed_cache_expires_when_time_slot_changes(): """10:50 에 만든 피드 캐시는 11:00(낮 시간대 시작)에 끝나야 한다. 예보 갱신(11:10)까지 남으면 낮 순서가 늦게 보인다.""" from datetime import datetime from common.utils.kma_time import KST from services.feed_service import feed_ttl_sec now = datetime(2026, 10, 2, 10, 50, tzinfo=KST) sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST) assert feed_ttl_sec(now, sunset) <= 600 def _card(post_type, post_id=1): from datetime import datetime from router.v1.feed.protocol import PostData return PostData(post_id=post_id, post_type=post_type, title="", icon="", caption="", slides=[], like_count=0, comment_count=0, published_at=datetime(2026, 10, 2)) def test_slot_follows_sunset(): from datetime import datetime from common.utils.kma_time import KST from services.feed_service import slot_of sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST) at = lambda h, m=0: datetime(2026, 10, 2, h, m, tzinfo=KST) # noqa: E731 assert [slot_of(at(h, m), sunset) for h, m in ((4, 59), (5, 0), (11, 0), (16, 9), (16, 10), (20, 59), (21, 0))] == [ "night", "morning", "day", "day", "evening", "evening", "night"] def test_arrange_orders_by_slot_and_keeps_same_types_apart(): from datetime import datetime from common.utils.kma_time import KST from services.feed_service import arrange sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST) cards = [_card(t, n) for n, t in enumerate([ PostType.WEATHER, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.TOMORROW, PostType.WEEK, PostType.EVENT, PostType.SEASON, PostType.TIP, PostType.QUOTE, ])] types = lambda now, warn=False: [c.post_type for c in arrange(cards, slot, now, sunset, warn)] # noqa: E731 slot = "morning" morning = types(datetime(2026, 10, 2, 8, tzinfo=KST)) assert morning[:2] == [PostType.WEATHER, PostType.ALERT] and PostType.TOMORROW not in morning assert all(a is not b for a, b in zip(morning, morning[1:])) slot = "evening" # 금요일 저녁: 해 지기 전엔 노을이 맨 앞, 주말 추천이 두 번째 evening = types(datetime(2026, 10, 2, 17, tzinfo=KST)) assert evening[1:3] == [PostType.SUNSET, PostType.WEEK] slot = "night" night = types(datetime(2026, 10, 2, 22, tzinfo=KST), warn=True) assert night[:3] == [PostType.ALERT, PostType.WEATHER, PostType.TOMORROW] and night[-1] is PostType.QUOTE def test_arrange_scatters_up_to_three_events_same_spot_all_day(): from datetime import datetime from common.utils.kma_time import KST from services.feed_service import arrange sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST) cards = [_card(t, n) for n, t in enumerate([ PostType.WEATHER, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.WEEK, PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.EVENT, PostType.EVENT, PostType.EVENT, ])] run = lambda h, seed: [c.post_type for c in arrange(cards, "day", datetime(2026, 10, 2, h, tzinfo=KST), sunset, False, seed)] # noqa: E731 out = run(11, "2026-10-02:1144000000") assert out.count(PostType.EVENT) == 3 and out[0] is PostType.WEATHER assert all(not (a is PostType.EVENT and b is PostType.EVENT) for a, b in zip(out, out[1:])) assert run(14, "2026-10-02:1144000000") == out @pytest.mark.anyio async def test_build_day_makes_every_card_at_three(): thursday = date(2026, 10, 15) await build_feed_day(thursday, FeedCRUD(), SeasonCRUD()) _, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT post_type, published_at FROM post WHERE feed_date='{thursday}'"))) rows = list(rows) assert {PostType.ALERT.value, PostType.TOMORROW.value, PostType.QUOTE.value} <= {r[0] for r in rows} from common.utils.kma_time import KST assert {r[1].astimezone(KST).hour for r in rows} == {3} @pytest.mark.anyio async def test_feed_has_quote_and_no_adjacent_same_type(offline): async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: body = (await client.get("/v1/feed", params={"region": REGION})).json() articles = (await client.get("/v1/season/article/list")).json() types = [p["post_type"] for p in body["posts"]] assert body["slot"] in ("morning", "day", "evening", "night") assert types[0] == PostType.WEATHER.value and types.count(PostType.GAK.value) == 3 assert all(a != b for a, b in zip(types, types[1:])) assert PostType.QUOTE.value in types assert articles["articles"] and all(a["category"] != 4 for a in articles["articles"]) def test_gak_key_handles_sunset_window(): from types import SimpleNamespace from services.feed_service import _gak_key item = SimpleNamespace(definition=SimpleNamespace(windows=[{"around": "sunset", "hours": 1}]), rank=1) assert _gak_key(item, 9) == (0, 8, 1) assert _gak_key(item, 21) == (1, 0, 1) @pytest.mark.anyio async def test_feed_missing_gak_is_cached_only_briefly(offline, monkeypatch): from common.cache.redis_client import REDIS from common.enums import ErrorType from services.index_service import IndexService async def fail(*_): return ErrorType.EXTERNAL_API_ERROR, None monkeypatch.setattr(IndexService, "board", fail) async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: body = (await client.get("/v1/feed", params={"region": REGION})).json() assert PostType.GAK.value not in [p["post_type"] for p in body["posts"]] keys = [k async for k in REDIS.conn.scan_iter(f"feed:{REGION}:*")] assert keys and 0 < await REDIS.conn.ttl(keys[0]) <= 60