Files
o2o-weather/backend/tests/test_feed.py
T
minaChoi a9ddbaab3c feat: 피드를 시간대별 카드로 다시 짜고 하늘 배경·내 캐릭터 추가, 다른 시안 정리
- 피드: 그날 카드 12장을 03:00에 한 번에 만들고, 시간대(아침·낮·저녁·밤, 저녁은 일몰 2시간 전부터)마다 순서를 바꾸고 조건이 맞는 카드만 켠다. 새 카드 우산·특보, 내일 미리보기, 한 문장·시(예시 seed). 흐린 날 노을은 한 줄 카드.
- 캐시를 feed:{구}:{시간대}로 나누고 시간대 경계·일몰·예보 갱신 때 만료해 새 카드가 늦게 보이던 문제를 고친다.
- 히어로는 오늘 1위 각만 보여 준다.
- 각 점수·노을 점수를 7일 지나면 지운다.
- 화면 전체 하늘 배경(시간대별 색, 느린 일렁임, 밤 별)과 화면 끝까지 이어지는 위·아래 바.
- 상단바 로그인 버튼, 내 정보 창(캐릭터 6종·배경색 6종·오늘 기분 8종·닉네임·로그아웃), PATCH /v1/auth/me, 댓글·상단바에 캐릭터·배경색·기분 표시. users.character·color·mood 칸 추가.
- 카드 슬라이드와 가로 줄을 Embla 카로셀로 바꿔 PC에서도 마우스로 끌어 넘기고 화살표로 넘긴다.
- 좋아요·저장을 받아 둔 피드 데이터에도 반영해 다른 탭에 다녀와도 유지되게 고치고, 좋아요 때 하트가 터지는 애니메이션을 넣는다.
- 보내기에서 게시물을 인스타 스토리 크기(1080×1920) 이미지로 공유하거나 내려받는다 (modern-screenshot).
- 창이 열려 있는 동안 뒤 페이지 스크롤을 잠근다.
- 시안 B 확정: 시안 A 아이콘(public/a)과 쓰지 않는 전역 스타일·글꼴 삭제.
- 문서: 데이터 흐름 지도(backend/docs/data-flow-map.html), 확정 시안(docs/시안B_확정.html), 피드 기획 v2, 호출량·DB 크기 추정, data-pipeline 갱신. 보고 폴더와 예전 시안 html 삭제.
2026-10-02 15:47:20 +09:00

128 lines
5.6 KiB
Python

from datetime import date
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_only_from_thursday():
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 PostType.WEEK.value not in await _posts(monday)
assert (await _posts(thursday)).count(PostType.WEEK.value) == 1
assert (await _posts(thursday))[0] == PostType.WEATHER.value
@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"]) == 23
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
@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"])