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 common.utils.kma_time import now_kst from crud.feed_crud import FeedCRUD from crud.region_crud import RegionCRUD from crud.season_crud import SeasonCRUD from router.router import app from services.feed_service import build_feed_day from services.week_service import collect_events REGION = "1114000000" async def _posts(day: date, sido: str = REGION[:2]): """한 시도가 보는 그날 카드 (전국 + 그 시도).""" _, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text( f"SELECT post_type FROM post WHERE feed_date='{day}' AND scope IN ('00', '{sido}') 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(), RegionCRUD()) await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD()) await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD()) 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 @pytest.mark.anyio async def test_build_day_adds_new_card_types_to_existing_day(): """이미 만든 날에 새 종류(미세먼지)가 생기면 빠진 카드만 더한다.""" thursday = date(2026, 10, 15) await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD()) await DB_SESSION_MNG.execute_lambda_run([lambda s: s.execute(text(f"DELETE FROM post WHERE feed_date='{thursday}' AND post_type={PostType.AIR.value}"))]) before = len(await _posts(thursday)) await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD()) after = await _posts(thursday) assert len(after) == before + 1 and after.count(PostType.AIR.value) == 1 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): await collect_events("11", now_kst().date()) 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"]) == 40 assert body["hero"]["weather_score"] == body["hero"]["weather_slots"][body["slot"]] assert all(g["slots"][body["slot"]] == g["score"] and g["slot_ranks"][body["slot"]] == g["rank"] for g in body["stories"] if g["active"]) weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value) assert [s["kind"] for s in weather["slides"]] == ["hours", "hours"] assert len(weather["slides"][0]["hours"]) == 8 assert body["bands"]["events"][0]["name"] == "테스트 축제" assert body["bands"]["events"][0]["image"] == "https://tong.visitkorea.or.kr/test.jpg" assert body["bands"]["events"][0]["image_credit"] == "ⓒ한국관광공사" assert "미세먼지" not in weather["caption"] air = next(p for p in body["posts"] if p["post_type"] == PostType.AIR.value) assert [(r["label"], r["value"]) for r in air["slides"][0]["rows"]] == [("초미세먼지", "좋음"), ("미세먼지", "좋음")] event = next(p for p in body["posts"] if p["post_type"] == PostType.EVENT.value) assert event["slides"][0]["eyebrow"].startswith("가까운 행사 · ") 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 test_feed_cache_expires_when_ultra_forecast_arrives(): """초단기예보 비가 각 점수에 들어가니, 다음 초단기예보가 나오는 :45 에 캐시가 끝나야 한다.""" from datetime import datetime from common.utils.kma_time import KST from services.feed_service import feed_ttl_sec now = datetime(2026, 10, 2, 13, 20, tzinfo=KST) sunset = datetime(2026, 10, 2, 18, 10, tzinfo=KST) assert feed_ttl_sec(now, sunset) == 25 * 60 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), (19, 9), (19, 10), (23, 0))] == [ "night", "morning", "day", "day", "evening", "evening", "night", "night"] summer = datetime(2026, 6, 21, 19, 57, tzinfo=KST) assert slot_of(datetime(2026, 6, 21, 20, 30, tzinfo=KST), summer) == "evening" assert slot_of(datetime(2026, 6, 21, 20, 57, tzinfo=KST), summer) == "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(), RegionCRUD()) _, 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): await collect_events("11", now_kst().date()) 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 def _alert_ctx(warnings=(), rain_prob=0): from datetime import datetime from types import SimpleNamespace from common.utils.kma_time import KST now = datetime(2026, 10, 2, 9, tzinfo=KST) hourly = [SimpleNamespace(forecast_at=datetime(2026, 10, 2, 15, tzinfo=KST), rain_prob=rain_prob)] return SimpleNamespace(now=now, hourly=hourly, region=SimpleNamespace(short_name="종로구"), now_w=SimpleNamespace(warnings=list(warnings))) def _base(): from datetime import datetime return dict(post_id=1, post_type=PostType.ALERT, like_count=0, comment_count=0, published_at=datetime(2026, 10, 2)) def _alert(ctx): from services.feed_service import FeedService return FeedService._alert(None, _base(), ctx) def test_alert_uses_umbrella_only_for_rain(): from common.enums import WarningLevel, WarningType from services.warning_service import WarningItem heat = _alert(_alert_ctx([WarningItem(WarningType.HEAT, WarningLevel.ADVISORY, "폭염주의보")])) cold = _alert(_alert_ctx([WarningItem(WarningType.COLD, WarningLevel.WARNING, "한파경보")])) rain = _alert(_alert_ctx(rain_prob=60)) assert heat.icon != "umbrella" and "우산" not in heat.share_messages[0] assert cold.icon == "coldwind" and "우산" not in cold.share_messages[0] assert rain.icon == "umbrella" and rain.share_messages[0].endswith("☔ 우산 챙겨!") def test_event_caption_adds_what_slide_lacks(): from types import SimpleNamespace from services.feed_service import _event_caption from services.week_service import EventItem ev = lambda confirmed=True: SimpleNamespace(is_confirmed=confirmed) # noqa: E731 full = EventItem(event=ev(), status="live", status_label="진행 중", fit="토요일 맑음 22°", distance_km=12.3) assert _event_caption(full) == "지금 진행 중 · 여기서 12km · 토요일 맑음 22°" bare = EventItem(event=ev(False), status="soon", status_label="D-12", fit=None) assert _event_caption(bare) == "올해 정확한 일정은 공식 안내로 확인해 주세요." def test_text_helpers_short_day_and_compass(): from common.utils.text import compass, day_range assert day_range(date(2026, 10, 4), date(2026, 10, 11)) == "10.4~10.11" assert compass(263) == "서" and compass(247) == "서남서" def _air(pm25, pm10, measured_hours_ago=0, rain=False): from datetime import datetime from types import SimpleNamespace from common.utils.kma_time import KST from services.feed_service import FeedService now = datetime(2026, 10, 2, 9, 30, tzinfo=KST) air = None if pm25 is None and pm10 is None else SimpleNamespace( station_name="테스트", pm25=pm25, pm10=pm10, measured_at=now.replace(minute=0) - timedelta(hours=measured_hours_ago)) ctx = SimpleNamespace(now=now, region=SimpleNamespace(short_name="종로구"), now_w=SimpleNamespace(air=air, will_rain_2h=rain)) return FeedService._air(None, _base() | {"post_type": PostType.AIR}, ctx) def test_air_post_shows_both_values_and_advice_only_when_bad(): good = _air(10, 20) assert [r.label for r in good.slides[0].rows] == ["초미세먼지", "미세먼지"] and good.title == "미세먼지 좋음" bad = _air(40, 60) assert bad.title == "미세먼지 나쁨" and bad.slides[0].rows[-1].label == "이렇게 해요" wet = _air(10, 20, rain=True) assert "창문은 닫아" in wet.slides[0].line and wet.icon == "umbrella" assert "창문은 닫아" not in _air(40, 60, rain=True).slides[0].line very = _air(20, 160) assert very.title == "미세먼지 매우나쁨" and "측정소" in very.caption and very.slides[0].rows[1].value == "매우나쁨" def test_air_post_off_without_fresh_data(): assert _air(None, None) is None assert _air(10, 20, measured_hours_ago=4) is None def _score(code, day, score, prob=10): from services.weekend_rank import DayScore return DayScore(region_code=code, day=day, score=score, reason=f"비 {prob}% · 체감 21° · 맑음", icon="sun", temp_min_c=12.0, temp_max_c=22.0, rain_prob=prob, estimated=False) def test_pick_trip_takes_best_city_within_reach(): from types import SimpleNamespace from services.weekend_rank import TripCity, pick_trip sat, sun = date(2026, 10, 10), date(2026, 10, 11) bundang = SimpleNamespace(lat=37.38, lon=127.12) city = lambda code, lat, lon, label: (code, (SimpleNamespace(code=code, lat=lat, lon=lon), TripCity(name=label, label=label, note=""))) # noqa: E731 cities = dict([city("gn", 37.75, 128.88, "강릉"), city("cc", 37.88, 127.73, "춘천"), city("bs", 35.16, 129.16, "부산")]) scores = [_score("gn", sat, 70), _score("gn", sun, 88), _score("cc", sat, 80), _score("bs", sat, 99)] pick = pick_trip(bundang, scores, cities, [sat, sun]) assert pick.label == "강릉" and pick.best.day == sun and 150 < pick.distance_km < 170 assert pick.runner_up[0] == "춘천" and pick.runner_up[1].score == 80 assert pick_trip(bundang, [_score("gn", sat, 40)], cities, [sat, sun]) is None @pytest.mark.anyio async def test_feed_has_day_trip_card_with_city_event(offline, monkeypatch): """분당 사용자: 캐시된 주말 점수에서 강릉이 1위면 강릉 당일치기 카드 + 강릉 근처 행사 사진.""" import json from dataclasses import asdict import services.week_service as week_service from common.cache.redis_client import REDIS from common.utils.kma_time import now_kst from services.weekend_rank import _KEY, _sat, weekend_days today = now_kst().date() day = weekend_days(today)[-1] scores = [_score("5115000000", day, 90), _score("5111000000", day, 75), _score("2611000000", day, 99)] await REDIS.conn.set(_KEY.format(_sat(today)), json.dumps([{**asdict(x), "day": x.day.isoformat()} for x in scores])) async def festivals(client, sido, since): return [{"contentid": "51", "title": "강릉 커피축제", "addr1": "강원 강릉시", "mapy": "37.77", "mapx": "128.90", "eventstartdate": today.strftime("%Y%m%d"), "eventenddate": (today + timedelta(days=7)).strftime("%Y%m%d"), "firstimage": "http://tong.visitkorea.or.kr/c.jpg"}] if sido == "51" else [] monkeypatch.setattr(week_service, "fetch_festivals", festivals) await week_service.collect_events("51", today) async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: body = (await client.get("/v1/feed", params={"region": "4113500000"})).json() trip = next(p for p in body["posts"] if p["post_type"] == PostType.DAY_TRIP.value) first, event = trip["slides"] assert "강릉" in first["line"] and "90점" in first["line"] rows = dict((r["label"], r["value"]) for r in first["rows"]) assert rows["거리"].startswith("여기서 약 ") and rows["날씨"] == "비 10% · 체감 21° · 맑음" assert "춘천" in trip["caption"] assert event["line"] == "강릉 커피축제" and event["image"] == "https://tong.visitkorea.or.kr/c.jpg" def test_gak_caption_starts_with_score_band_sentence(): from types import SimpleNamespace from services.feed_service import _gak_caption d = SimpleNamespace(sentences={"0": "쉬어요", "30": "애매", "60": "괜찮아요", "80": "딱 좋아요!"}, windows=[{"from": 18, "to": 24}]) item = SimpleNamespace(definition=d, score=SimpleNamespace(score=83, score_date=date(2026, 10, 7)), trend=[], rank=1) assert _gak_caption(item) == "딱 좋아요! 하기 좋은 때는 18~24시예요." item.definition.sentences = {} assert _gak_caption(item) == "하기 좋은 때는 18~24시예요." def test_uv_post_only_when_moderate_or_higher(): from datetime import datetime from types import SimpleNamespace from common.utils.kma_time import KST from services.feed_service import FeedService at = lambda h: datetime(2026, 10, 7, h, tzinfo=KST) # noqa: E731 base = dict(post_id=1, post_type=PostType.UV, like_count=0, comment_count=0, published_at=at(9)) ctx = lambda vals: SimpleNamespace(region=SimpleNamespace(short_name="분당구"), uv=[SimpleNamespace(forecast_at=at(h), uv_index=v) for h, v in vals]) # noqa: E731 post = FeedService._uv_post(None, base, ctx([(9, 2.0), (12, 6.4), (15, 4.0)])) assert post.title == "자외선 지수 높음" and post.caption == "가장 셀 때 낮 12시" assert post.slides[0].line == "오늘 자외선 지수 높음\n점심때 나가면 선크림·모자·선글라스 챙기고 그늘로 다녀요" assert [(r.label, r.value, r.level) for r in post.slides[0].rows] == [("9시", "낮음", 1), ("12시", "높음", 3), ("15시", "보통", 2)] assert FeedService._uv_post(None, base, ctx([(12, 2.0), (15, 3.4)])).slides[0].line == "오늘 자외선 지수 보통\n오후 3시 무렵 나가면 선크림·모자 챙겨요" assert FeedService._uv_post(None, base, ctx([(9, 1.0), (12, 2.5)])) is None assert FeedService._uv_post(None, base, ctx([])) is None