Files
o2o-weather/backend/tests/test_openmeteo_weather.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

102 lines
4.5 KiB
Python

import pytest
from sqlalchemy import text
import scheduler.jobs as jobs
from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import ErrorType
from services.external.open_meteo import OpenMeteoRequestFailed, parse_weather
SLOTS_PER_REGION = 31 # 96시간 응답에서 직전 3시간이 다 있는 3시간 구간 (끝 시각 03시 ~ 다음다음다음날 21시)
def _hourly(**over):
times = [f"2026-10-06T{h:02d}:00" for h in range(9)]
base = {
"time": times,
"uv_index": [round(0.1 * h, 1) for h in range(9)],
"uv_index_clear_sky": [round(0.2 * h, 1) for h in range(9)],
"visibility": [10000.0 + h for h in range(9)],
"wind_gusts_10m": [1.0 + h for h in range(9)],
"pressure_msl": [1000.0 + h for h in range(9)],
"sunshine_duration": [0, 600, 1200, 1800, 2400, 3000, 3600, 3600, 3600],
"shortwave_radiation": [0, 10, 20, 30, 40, 60, 100, 200, 300],
"soil_temperature_0cm": [10.0 + h for h in range(9)],
}
return {"hourly": base | over}
def test_three_hour_slots_sum_sunshine_and_average_radiation():
rows = {r["forecast_at"].hour: r for r in parse_weather(_hourly())}
assert sorted(rows) == [3, 6] # 00시 구간은 앞 두 시간이 없어 만들지 않는다
assert rows[3]["sunshine_s"] == 600 + 1200 + 1800
assert rows[3]["shortwave_avg_wm2"] == 20 and rows[3]["shortwave_max_wm2"] == 30
assert rows[6]["sunshine_s"] == 2400 + 3000 + 3600
assert rows[6]["shortwave_avg_wm2"] == 67 and rows[6]["shortwave_max_wm2"] == 100
def test_other_values_are_taken_at_slot_end():
row = {r["forecast_at"].hour: r for r in parse_weather(_hourly())}[6]
assert row["uv_index"] == 0.6 and row["uv_index_clear_sky"] == 1.2
assert row["visibility_m"] == 10006 and row["wind_gust_ms"] == 7.0
assert row["pressure_hpa"] == 1006.0 and row["soil_temp_c"] == 16.0
def test_missing_hour_value_makes_aggregate_none_but_keeps_instant_values():
sun = [0, 600, None, 1800, 2400, 3000, 3600, 3600, 3600]
rows = {r["forecast_at"].hour: r for r in parse_weather(_hourly(sunshine_duration=sun))}
assert rows[3]["sunshine_s"] is None and rows[3]["uv_index"] == 0.3
assert rows[6]["sunshine_s"] == 9000
@pytest.mark.anyio
async def test_refresh_stores_every_region_and_is_repeatable(offline):
assert await jobs.refresh_openmeteo_weather() is ErrorType.SUCCESS
first = await _counts()
assert first["regions"] == 256 and first["rows"] == 256 * SLOTS_PER_REGION and first["slots"] == SLOTS_PER_REGION
assert await jobs.refresh_openmeteo_weather() is ErrorType.SUCCESS
assert (await _counts())["rows"] == first["rows"]
@pytest.mark.anyio
async def test_refresh_failure_returns_error_and_stores_nothing(offline, monkeypatch):
async def fail(client, points, days=4):
raise OpenMeteoRequestFailed("boom")
monkeypatch.setattr(jobs, "fetch_weather", fail)
assert await jobs.refresh_openmeteo_weather() is ErrorType.EXTERNAL_API_ERROR
assert (await _counts())["rows"] == 0
async def _counts() -> dict:
err, res = await DB_SESSION_MNG.execute_lambda(
lambda s: s.execute(text("SELECT count(*) AS rows, count(DISTINCT region_code) AS regions, count(DISTINCT forecast_at) AS slots FROM openmeteo_hourly"))
)
return dict(res.one()._mapping)
@pytest.mark.anyio
async def test_upsert_keeps_previous_value_when_new_value_is_missing():
from datetime import datetime, timedelta, timezone
from crud.weather_crud import WeatherCRUD
at = datetime(2026, 10, 6, 3, tzinfo=timezone.utc)
first = {
"region_code": "1144000000", "forecast_at": at, "fetched_at": at, "uv_index": 3.0, "uv_index_clear_sky": 3.5,
"visibility_m": 20000, "wind_gust_ms": 4.0, "pressure_hpa": 1015.0, "soil_temp_c": 18.0,
"sunshine_s": 3600, "shortwave_avg_wm2": 300, "shortwave_max_wm2": 400,
}
second = first | {"fetched_at": at + timedelta(hours=6), "uv_index": None, "sunshine_s": None, "visibility_m": 15000}
for row in (first, second):
await DB_SESSION_MNG.execute_lambda_run([lambda s, r=row: WeatherCRUD().upsert_openmeteo(s, [r])])
err, res = await DB_SESSION_MNG.execute_lambda(
lambda s: s.execute(text("SELECT uv_index, sunshine_s, visibility_m, fetched_at FROM openmeteo_hourly WHERE region_code = '1144000000'"))
)
row = res.one()
assert float(row.uv_index) == 3.0 and row.sunshine_s == 3600 # 비어 온 값은 이전 값 유지
assert row.visibility_m == 15000 # 값이 있으면 덮어씀
assert row.fetched_at == second["fetched_at"]