feat: 로딩 스켈레톤·행사 사진·전시·주말 예상 점수·노을 탭 재정리 등 화면 전반 개선
- 화면 전체 스켈레톤, 로딩·완료·실패 사이 레이아웃 고정, 값 없음은 '?' - 행사 사진·출처 표시, 문화정보 API 전시 연결, 행사 30km 거리 기준 - 각 상세 점수 칸 오늘/내일/토/일, 단기예보 밖 주말은 중기예보 예상 점수 - 6각 차트 축 이름을 좋은 방향으로, 계산 근거 문구 정리 - 아이콘 오용·뜻 모를 표시·빈 데이터·포스트 본문 반복 수정 - 미세먼지 별도 포스트, 노을 명소 전국 155곳 거리 기준, 노을 탭 결론 중심 재구성 - 밤 다크 테마·별똥별, 댓글·좋아요 대기·실패 표시 - 주말 전국 랭킹·당일치기 카드, 계절 이야기 사진 수집 - 문서: 포스트 타입별 내용, 각 데이터 정리, TODO 진행 순서
This commit is contained in:
1 parent
296a09d6db
commit
ddf05aeb5c
97 files changed
+5475
-720
No files matched your search
+159
-1
@@ -30,6 +30,18 @@ async def test_build_day_adds_weekend_post_every_day():
|
||||
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
|
||||
@@ -45,9 +57,16 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
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 [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():
|
||||
@@ -175,3 +194,142 @@ async def test_feed_missing_gak_is_cached_only_briefly(offline, monkeypatch):
|
||||
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"
|
||||
Reference in new issue
Block a user