- FastAPI + PostgreSQL + Redis, web·worker 분리, compose 에 backend·worker·postgres·redis 추가 - 기상청 단기·초단기·중기·특보, 에어코리아, Open-Meteo, TourAPI, 특일정보 연동 (첫 조회 때 받고 캐시) - 매일 03:00 worker 가 전국 공통 피드 칸을 정하고 지난 데이터를 정리 - 시드: 시군구 256곳, 지수 23개, 노을 대표 지점·명소, 데이트 명소, 읽을거리 - pytest 66개 (테스트 전용 DB·Redis 사용) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
103 lines
4.6 KiB
Python
103 lines
4.6 KiB
Python
from datetime import timedelta
|
|
|
|
import pytest
|
|
from httpx import ASGITransport, AsyncClient
|
|
from sqlalchemy import text
|
|
|
|
import services.air_service as air_service
|
|
import services.now_service as now_service
|
|
import services.warning_service as warning_service
|
|
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, now_kst
|
|
from router.router import app
|
|
|
|
REGION = "1144000000"
|
|
|
|
|
|
def _vilage(*_):
|
|
start = kst_midnight(now_kst().date())
|
|
items = []
|
|
for h in range(48):
|
|
at = start + timedelta(hours=h)
|
|
rainy = h == 24 + 15
|
|
for c, v in [("TMP", "16"), ("SKY", "1"), ("PTY", "1" if rainy else "0"), ("POP", "60" if rainy else "0"),
|
|
("PCP", "1mm 미만" if rainy else "강수없음"), ("REH", "60"), ("WSD", "1.5")]:
|
|
items.append({"category": c, "fcstDate": at.strftime("%Y%m%d"), "fcstTime": at.strftime("%H%M"), "fcstValue": v})
|
|
return items
|
|
|
|
|
|
def _ultra(*_):
|
|
start = now_kst().replace(minute=0, second=0, microsecond=0)
|
|
items = []
|
|
for h in range(1, 7):
|
|
at = start + timedelta(hours=h)
|
|
for c, v in [("PTY", "0"), ("RN1", "강수없음"), ("T1H", "17")]:
|
|
items.append({"category": c, "fcstDate": at.strftime("%Y%m%d"), "fcstTime": at.strftime("%H%M"), "fcstValue": v})
|
|
return items
|
|
|
|
|
|
async def _async(v):
|
|
return v
|
|
|
|
|
|
@pytest.fixture
|
|
async def clean():
|
|
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("DELETE FROM air_quality")),
|
|
lambda s: s.execute(text("DELETE FROM air_station")),
|
|
lambda s: s.execute(text("DELETE FROM weather_warning")),
|
|
])
|
|
keys = [k async for k in REDIS.conn.scan_iter("ultra:*")] + [k async for k in REDIS.conn.scan_iter("warning:*")] + ["air:tried"]
|
|
await REDIS.conn.delete(*keys)
|
|
await wipe()
|
|
yield
|
|
await wipe()
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_now_combines_rain_tomorrow_air_and_warnings(monkeypatch, clean):
|
|
now = now_kst()
|
|
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage()))
|
|
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
|
monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "마포구", "dmX": "37.5555", "dmY": "126.9055"}]))
|
|
monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{
|
|
"stationName": "마포구", "pm25Value": "11", "pm10Value": "24", "pm25Grade": "1", "pm10Grade": "1",
|
|
"dataTime": now.replace(minute=0).strftime("%Y-%m-%d %H:%M"),
|
|
}]))
|
|
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([
|
|
{"areaCode": "L1100000", "warnVar": 4, "warnStress": 0, "command": 1, "cancel": "0", "tmFc": 202610020300, "tmSeq": 1},
|
|
]))
|
|
|
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
|
body = (await client.get("/v1/weather/now", params={"region": REGION})).json()
|
|
|
|
assert body["result"]["success"] is True
|
|
assert body["rain_2h"]["will_rain"] is False and len(body["rain_2h"]["hours"]) == 2
|
|
assert body["tomorrow"]["text"] == "내일은 오후 3시쯤부터 부슬부슬 와요"
|
|
assert [c["text"] for c in body["tomorrow"]["commute"]] == ["맑음 16°", "맑음 16°"]
|
|
assert body["air"]["station_name"] == "마포구" and body["air"]["text"] == "초미세먼지 11 좋음"
|
|
assert body["warnings"] == [{"warning_type": 4, "level": 1, "text": "건조주의보"}]
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_now_warning_failure_is_unknown_not_none(monkeypatch, clean):
|
|
from services.external.data_go_kr import DataGoKrRequestFailed
|
|
|
|
async def fail(*a):
|
|
raise DataGoKrRequestFailed("HTTP 504")
|
|
|
|
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage()))
|
|
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
|
monkeypatch.setattr(air_service, "fetch_stations", fail)
|
|
monkeypatch.setattr(air_service, "fetch_realtime", fail)
|
|
monkeypatch.setattr(warning_service, "fetch_warning_events", fail)
|
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
|
body = (await client.get("/v1/weather/now", params={"region": REGION})).json()
|
|
assert body["result"]["success"] is True
|
|
assert "warnings" not in body and "air" not in body
|