Files

103 lines
5.2 KiB
Python

from datetime import datetime, timedelta
from types import SimpleNamespace
import pytest
from httpx import ASGITransport, AsyncClient
import services.weather_service as weather_service
import services.week_service as week_service
from common.cache.redis_client import REDIS
from common.utils.kma_time import KST, now_kst
from router.router import app
from router.v1.watch.watch import timeline
REGION = "1141000000"
SUN = datetime(2026, 10, 6, 18, 0, tzinfo=KST)
async def _async(v):
return v
def _sunset(score: int) -> SimpleNamespace:
return SimpleNamespace(score=score, best_times=[
{"at": SUN.isoformat(), "kind": "sun", "label": "해 져요"},
{"at": (SUN + timedelta(minutes=15)).isoformat(), "kind": "peak", "label": "가장 붉을 때"},
{"at": (SUN + timedelta(minutes=30)).isoformat(), "kind": "twilight", "label": "보랏빛 하늘"},
])
def test_timeline_switches_to_sunset_two_hours_before_and_back_after_twilight():
now = SUN.replace(hour=12)
assert [(t.start_at.hour, t.start_at.minute, t.kind) for t in timeline(now, _sunset(80), True)] == [
(12, 0, "gak"), (16, 0, "sunset"), (18, 30, "gak"),
]
def test_timeline_starts_with_sunset_inside_window():
now = SUN.replace(hour=17)
assert [t.kind for t in timeline(now, _sunset(80), True)] == ["sunset", "gak"]
def test_timeline_skips_weak_tomorrow_or_finished_sunset():
noon, late = SUN.replace(hour=12), SUN.replace(hour=19)
assert [t.kind for t in timeline(noon, _sunset(59), True)] == ["gak"]
assert [t.kind for t in timeline(noon, _sunset(80), False)] == ["gak"]
assert [t.kind for t in timeline(late, _sunset(80), True)] == ["gak"]
assert [t.kind for t in timeline(noon, None, True)] == ["gak"]
@pytest.mark.anyio
async def test_watch_summary_bundles_now_top_picks_sunset(offline):
# 행사는 스케줄러가 7일마다 모아 둔다. 요청은 DB 만 읽으니 먼저 모아 둔다
await week_service.collect_events("11", now_kst().date())
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/watch/summary", params={"region": REGION, "pick": "laundry, nope,running,carwash,bike"})).json()
assert body["result"]["success"] is True
assert body["region_code"] == REGION and body["mode"] in ("morning", "day", "evening", "night")
assert body["refresh_at"] > body["issued_at"]
assert body["now"]["rain_2h"] is False and body["now"]["temp_c"] == 20.0
assert [t["rank"] for t in body["top"]] == list(range(1, 8))
assert [p["code"] for p in body["picks"]] == ["laundry", "running"]
assert body["sunset"]["best_at"] > body["sunset"]["sunset_at"]
assert all(s["at"] > body["issued_at"] for s in body["slots"])
assert body["timeline"][0]["start_at"] == body["issued_at"]
assert [(e["name"], e["status_label"]) for e in body["events"]] == [("테스트 축제", "진행 중")]
@pytest.mark.anyio
async def test_watch_summary_puts_live_event_first_without_bracket_prefix(offline, monkeypatch):
# 서버 순서는 시작일이 가까운 순이라 내일 시작이 먼저지만, 스킨에 하나만 띄우니 진행 중을 앞으로. 이름 앞 [주최] 는 뺀다
today = now_kst().date()
day = lambda n: (today + timedelta(days=n)).strftime("%Y%m%d")
monkeypatch.setattr(week_service, "fetch_festivals", lambda c, sido, since: _async([
{"contentid": "1", "title": "내일 축제", "addr1": "서울", "eventstartdate": day(1), "eventenddate": day(2)},
{"contentid": "2", "title": "[주최] 열리는 축제", "addr1": "서울", "eventstartdate": day(-3), "eventenddate": day(2)},
] if sido == "11" else []))
await week_service.collect_events("11", today)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/watch/summary", params={"region": REGION})).json()
assert [e["name"] for e in body["events"]] == ["열리는 축제", "내일 축제"]
@pytest.mark.anyio
async def test_watch_summary_unknown_region_fails(offline):
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/watch/summary", params={"region": "0000000000"})).json()
assert body["result"]["success"] is False
@pytest.mark.anyio
async def test_watch_summary_flags_thunder_within_2_hours(offline, monkeypatch):
start = now_kst().replace(minute=0, second=0, microsecond=0)
items = [
{"category": c, "fcstDate": (start + timedelta(hours=h)).strftime("%Y%m%d"), "fcstTime": (start + timedelta(hours=h)).strftime("%H%M"), "fcstValue": v}
for h in range(1, 7) for c, v in [("PTY", "1"), ("RN1", "5.0mm"), ("T1H", "20"), ("LGT", "2" if h == 1 else "0")]
]
monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async(items))
# 앞 테스트가 받아 둔 초단기예보 캐시(비 없음)를 지워야 새 예보를 읽는다
await REDIS.conn.delete(f"ultra:{REGION}", f"lock:ultra:{REGION}")
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/watch/summary", params={"region": REGION})).json()
assert body["now"]["rain_2h"] is True and body["now"]["thunder"] is True