Files
o2o-weather/backend/tests/test_weather_today.py
T
minaChoiandClaude Opus 5.5 e134295ce5 feat: 날씨각 백엔드 API (날씨·노을·지수·주말·계절·피드·로그인·반응)
- 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>
2026-10-02 11:32:22 +09:00

93 lines
3.6 KiB
Python

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"] == "stars"
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"