from datetime import timedelta import pytest from httpx import ASGITransport, AsyncClient from sqlalchemy import text import services.weather_service as weather_service from common.database.db_session_manager import DB_SESSION_MNG from common.utils.kma_time import kst_midnight, now_kst from router.router import app REGION = "1144000000" def _fake_items(base): """그날 0시부터 이틀치, 맑음·18도·비 없음.""" start = kst_midnight(now_kst().date()) items = [] for h in range(48): at = start + timedelta(hours=h) d, t = at.strftime("%Y%m%d"), at.strftime("%H%M") for c, v in [("TMP", "18"), ("SKY", "1"), ("PTY", "0"), ("POP", "0"), ("PCP", "강수없음"), ("REH", "60"), ("WSD", "1.5")]: items.append({"category": c, "fcstDate": d, "fcstTime": t, "fcstValue": v}) return items @pytest.fixture async def clean_region(): async def wipe(): await DB_SESSION_MNG.execute_lambda_run([ lambda s: s.execute(text(f"DELETE FROM weather_hourly WHERE region_code='{REGION}'")), lambda s: s.execute(text(f"DELETE FROM weather_daily WHERE region_code='{REGION}'")), lambda s: s.execute(text(f"DELETE FROM sun_time WHERE region_code='{REGION}'")), ]) await wipe() yield await wipe() @pytest.mark.anyio async def test_today_fetches_stores_and_returns_8_slots(monkeypatch, clean_region): calls = [] async def fake_fetch(client, nx, ny, base): calls.append(base) return _fake_items(base) monkeypatch.setattr(weather_service, "fetch_vilage", fake_fetch) async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: body = (await client.get("/v1/weather/today", params={"region": REGION})).json() assert body["result"]["success"] is True assert [s["label"] for s in body["slots"]] == ["0시", "3시", "6시", "9시", "12시", "15시", "18시", "21시"] assert all(s["temp_c"] == 18 for s in body["slots"]) assert body["slots"][0]["icon"] == "moon" assert body["slots"][6]["icon"] == "sunset" and body["slots"][6]["note"] == "노을" assert len(calls) == 2 @pytest.mark.anyio async def test_today_second_call_uses_db_without_fetching(monkeypatch, clean_region): calls = [] async def fake_fetch(client, nx, ny, base): calls.append(base) return _fake_items(base) monkeypatch.setattr(weather_service, "fetch_vilage", fake_fetch) async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: await client.get("/v1/weather/today", params={"region": REGION}) await client.get("/v1/weather/today", params={"region": REGION}) assert len(calls) == 2 @pytest.mark.anyio async def test_today_unknown_region_is_not_found(): async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: body = (await client.get("/v1/weather/today", params={"region": "0000000000"})).json() assert body["result"]["success"] is False and body["result"]["desc"] == "NOT_FOUND" @pytest.mark.anyio async def test_today_fetch_failure_without_data_is_external_error(monkeypatch, clean_region): from services.external.data_go_kr import DataGoKrRequestFailed async def failing_fetch(client, nx, ny, base): raise DataGoKrRequestFailed("HTTP 403") monkeypatch.setattr(weather_service, "fetch_vilage", failing_fetch) async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: body = (await client.get("/v1/weather/today", params={"region": REGION})).json() assert body["result"]["desc"] == "EXTERNAL_API_ERROR" def test_slot_view_shows_sunset_only_when_clear(): from datetime import datetime from types import SimpleNamespace from common.enums import RainType, Sky from common.utils.kma_time import KST from services.weather_service import _slot_view at = datetime(2026, 10, 2, 18, tzinfo=KST) sun = SimpleNamespace(sunrise_at=at.replace(hour=6), sunset_at=at.replace(minute=10), dusk_end_at=at.replace(minute=40)) row = lambda sky: SimpleNamespace(rain_type=RainType.NONE.value, sky=sky.value, temp_c=18, rain_prob=0) # noqa: E731 assert _slot_view(at, row(Sky.CLEAR), sun)[0::2] == ("sunset", "노을") assert _slot_view(at, row(Sky.CLOUDY), sun)[0::2] == ("cloud", "흐림") assert _slot_view(at, row(Sky.PARTLY), sun)[0::2] == ("cloud", "구름 많음")