Files
o2o-weather/backend/tests/test_feed.py
T
minaChoi ddf05aeb5c feat: 로딩 스켈레톤·행사 사진·전시·주말 예상 점수·노을 탭 재정리 등 화면 전반 개선
- 화면 전체 스켈레톤, 로딩·완료·실패 사이 레이아웃 고정, 값 없음은 '?'
- 행사 사진·출처 표시, 문화정보 API 전시 연결, 행사 30km 거리 기준
- 각 상세 점수 칸 오늘/내일/토/일, 단기예보 밖 주말은 중기예보 예상 점수
- 6각 차트 축 이름을 좋은 방향으로, 계산 근거 문구 정리
- 아이콘 오용·뜻 모를 표시·빈 데이터·포스트 본문 반복 수정
- 미세먼지 별도 포스트, 노을 명소 전국 155곳 거리 기준, 노을 탭 결론 중심 재구성
- 밤 다크 테마·별똥별, 댓글·좋아요 대기·실패 표시
- 주말 전국 랭킹·당일치기 카드, 계절 이야기 사진 수집
- 문서: 포스트 타입별 내용, 각 데이터 정리, TODO 진행 순서
2026-10-06 16:36:11 +09:00

336 lines
16 KiB
Python

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
@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())
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())
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):
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", "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"]] == [("초미세먼지", "10㎍/㎥ · 좋음"), ("미세먼지", "20㎍/㎥ · 좋음")]
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 _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
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):
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))
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 == "이렇게 해요"
very = _air(20, 160)
assert very.title == "미세먼지 매우나쁨" and "측정소" in very.caption and very.slides[0].rows[1].value == "160㎍/㎥ · 매우나쁨"
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)
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"