144 lines
6.1 KiB
Python
144 lines
6.1 KiB
Python
import asyncio
|
|
from datetime import timedelta
|
|
|
|
import pytest
|
|
from httpx import ASGITransport, AsyncClient
|
|
from sqlalchemy import text
|
|
|
|
import services.weather_service as weather_service
|
|
from common.cache.redis_client import REDIS
|
|
from common.database.db_session_manager import DB_SESSION_MNG
|
|
from common.utils.kma_time import kst_midnight, latest_vilage_base, now_kst
|
|
from services.external.kma import day_start_base
|
|
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 REDIS.conn.delete(f"vilage0:{REGION}:{now_kst():%Y%m%d}")
|
|
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", "구름 많음")
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_today_refetches_midnight_when_first_fetch_missed_it(monkeypatch, clean_region):
|
|
"""전날 23시 발표 받기가 실패해 0시~ 칸이 비면, 다음 요청 때 그 발표를 다시 받아 채운다."""
|
|
midnight_base = day_start_base(now_kst().date())
|
|
if latest_vilage_base(now_kst()) == midnight_base:
|
|
pytest.skip("최신 발표가 전날 23시면 두 발표가 같다")
|
|
calls = []
|
|
fail_midnight = True
|
|
|
|
async def fake_fetch(client, nx, ny, base):
|
|
from services.external.data_go_kr import DataGoKrRequestFailed
|
|
|
|
calls.append(base)
|
|
if base == midnight_base and fail_midnight:
|
|
raise DataGoKrRequestFailed("timeout")
|
|
return [it for it in _fake_items(base) if base == midnight_base or it["fcstDate"] + it["fcstTime"] > base.strftime("%Y%m%d%H%M")]
|
|
|
|
monkeypatch.setattr(weather_service, "fetch_vilage", fake_fetch)
|
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
|
first = (await client.get("/v1/weather/today", params={"region": REGION})).json()
|
|
assert first["slots"][0].get("temp_c") is None
|
|
fail_midnight = False
|
|
await REDIS.conn.delete(f"vilage0:{REGION}:{now_kst():%Y%m%d}")
|
|
await client.get("/v1/weather/today", params={"region": REGION})
|
|
await asyncio.gather(*weather_service._background)
|
|
body = (await client.get("/v1/weather/today", params={"region": REGION})).json()
|
|
|
|
assert calls.count(midnight_base) == 2
|
|
assert body["slots"][0]["temp_c"] == 18
|