Files
o2o-weather/backend/tests/test_sky_api.py
T
skkim 7c12651068 feat: Open-Meteo 구름 20·100km 구 코드 저장, 보조값 수집, 활동 지수 10개에 자외선·햇빛·가시거리 반영
구름
- 노을·일출 점수를 구 중심 20·100km 두 지점으로 계산 (50km 제외), 모델은 JMA·ICON 두 개만 사용
- cloud_hourly를 (구 코드, 방향, 거리, 시각, 모델) 키로 바꾸고 점수에 쓰는 시각만 저장

보조값
- openmeteo_hourly 신규: 자외선·가시거리·돌풍·기압·지표면 온도(끝 시각 값), 일조(3시간 합), 일사(평균·최대)
- worker가 03·09·15·21시 10분에 구 256곳을 요청 11번으로 일괄 수집, 7일 지난 행 정리
- 새 응답에서 값이 비어 오면 이전 값을 유지(COALESCE)

지수
- 새 축 uv·sun·view 추가 (index_definition/index_score 칼럼, 비중 있는 지수에만 상세에 표시)
- 빨래·멍뭉산책·피크닉·등산·러닝·가드닝·별보기·사진산책에 비중 배분, 자전거·캠핑·멍뭉산책에 돌풍·지표면 온도 0점 조건
- 자외선·가시거리 등 순간값은 가장 가까운 3시간 구간, 일조는 덮는 구간을 계산 창에 연결
- 보조값이 새로 오면 지수를 다시 계산하도록 재계산 기준에 fetched_at 추가

테스트 102개 통과 (PGSSLMODE=disable, JWT는 테스트용 환경변수).
2026-10-06 17:21:59 +09:00

85 lines
3.5 KiB
Python

import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import text
import services.sky_service as sky_service
from common.cache.redis_client import REDIS
from common.database.db_session_manager import DB_SESSION_MNG
from router.router import app
def _fake_response(points, days):
from datetime import datetime, timedelta
start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=1)
times = [(start + timedelta(hours=h)).strftime("%Y-%m-%dT%H:00") for h in range(24 * (days + 1))]
hourly = {"time": times}
for m in ("ecmwf_ifs025", "gfs_seamless", "jma_seamless", "icon_seamless"):
hourly[f"cloud_cover_low_{m}"] = [0] * len(times)
hourly[f"cloud_cover_mid_{m}"] = [20] * len(times)
hourly[f"cloud_cover_high_{m}"] = [50] * len(times)
return [{"hourly": hourly} for _ in points]
@pytest.fixture
async def clean():
async def wipe():
await DB_SESSION_MNG.execute_lambda_run([
lambda s: s.execute(text("DELETE FROM sky_score")),
lambda s: s.execute(text("DELETE FROM cloud_hourly")),
])
keys = [k async for k in REDIS.conn.scan_iter("sky:*")]
if keys:
await REDIS.conn.delete(*keys)
await wipe()
yield
await wipe()
@pytest.mark.anyio
async def test_sky_view_scores_three_days_with_spots(monkeypatch, clean):
async def fake_fetch(client, points, days=3):
return _fake_response(points, days)
monkeypatch.setattr(sky_service, "fetch_clouds", fake_fetch)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/sky", params={"region": "1144000000"})).json()
assert body["result"]["success"] is True
assert body["sunset"]["grade"] == 4 and body["sunset"]["grade_label"] == "붉음"
assert body["sunset"]["confidence"] == 1
assert len(body["days"]) == 3
assert [s["name"] for s in body["spots"]] == ["망원한강공원", "하늘공원", "선유도공원"]
assert 255 <= body["sunset_azimuth"] <= 280
@pytest.mark.anyio
async def test_sky_ranking_has_30_spots_sorted(monkeypatch, clean):
async def fake_fetch(client, points, days=3):
return _fake_response(points, days)
monkeypatch.setattr(sky_service, "fetch_clouds", fake_fetch)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/sky/ranking")).json()
scores = [i["score"] for i in body["items"]]
assert len(scores) == 30 and scores == sorted(scores, reverse=True)
assert body["items"][0]["rank"] == 1 and body["items"][0]["note"]
@pytest.mark.anyio
async def test_clouds_are_stored_by_region_with_only_needed_hours(monkeypatch, clean):
async def fake_fetch(client, points, days=3):
return _fake_response(points, days)
monkeypatch.setattr(sky_service, "fetch_clouds", fake_fetch)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
await client.get("/v1/sky", params={"region": "1144000000"})
err, rows = await DB_SESSION_MNG.execute_lambda(
lambda s: s.execute(text("SELECT kind, distance_km, forecast_at, model FROM cloud_hourly WHERE region_code = '1144000000'"))
)
rows = rows.all()
assert len(rows) == 2 * 2 * 3 * 2
assert {(r.kind, r.distance_km) for r in rows} == {(1, 20), (1, 100), (2, 20), (2, 100)}
assert {r.model for r in rows} == {3, 4}
assert len({r.forecast_at for r in rows}) == 6