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는 테스트용 환경변수).
This commit is contained in:
skkim committed 2026-10-06 17:21:59 +09:00
1 parent 7244449b7a
commit 7c12651068
19 files changed
+712 -82

No files matched your search

+15 -2
View File
@@ -41,7 +41,7 @@ def anyio_backend():
_VOLATILE = (
"weather_hourly", "weather_daily", "cloud_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
"sky_score", "index_score", "post", "post_like", "post_save", "comment", "comment_like", "holiday", "solar_term", "users",
)
@@ -67,8 +67,9 @@ async def _async(v):
@pytest.fixture
def offline(monkeypatch):
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
from datetime import timedelta
from datetime import datetime, timedelta, timezone
import scheduler.jobs as jobs
import services.air_service as air_service
import services.now_service as now_service
import services.season_service as season_service
@@ -95,6 +96,17 @@ def offline(monkeypatch):
h |= {f"cloud_cover_low_{m}": [0] * len(times), f"cloud_cover_mid_{m}": [20] * len(times), f"cloud_cover_high_{m}": [50] * len(times)}
return _async([{"hourly": h} for _ in points])
def openmeteo_weather(client, points, days=4):
start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
times = [(start + timedelta(hours=h)).strftime("%Y-%m-%dT%H:00") for h in range(24 * days)]
n = len(times)
h = {
"time": times, "uv_index": [3.0] * n, "uv_index_clear_sky": [3.0] * n, "visibility": [20000.0] * n,
"wind_gusts_10m": [4.0] * n, "pressure_msl": [1015.0] * n, "sunshine_duration": [3600.0] * n,
"shortwave_radiation": [300.0] * n, "soil_temperature_0cm": [18.0] * n,
}
return _async([{"hourly": h} for _ in points])
clear = [("TMP", "20"), ("SKY", "1"), ("PTY", "0"), ("POP", "0"), ("PCP", "강수없음"), ("REH", "50"), ("WSD", "1.5")]
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(hourly(24 * 4, clear)))
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(hourly(24 * 2, [("PTY", "0"), ("RN1", "강수없음"), ("T1H", "20")])))
@@ -105,6 +117,7 @@ def offline(monkeypatch):
}]))
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([]))
monkeypatch.setattr(sky_service, "fetch_clouds", clouds)
monkeypatch.setattr(jobs, "fetch_weather", openmeteo_weather)
monkeypatch.setattr(week_service, "fetch_mid", lambda *a: _async(({}, {})))
monkeypatch.setattr(week_service, "fetch_holidays", lambda *a: _async([]))
monkeypatch.setattr(week_service, "fetch_festivals", lambda *a: _async([{
+82 -1
View File
@@ -1,4 +1,5 @@
from datetime import timedelta
from datetime import date, timedelta
from types import SimpleNamespace
import pytest
from httpx import ASGITransport, AsyncClient
@@ -6,8 +7,12 @@ from httpx import ASGITransport, AsyncClient
import services.air_service as air_service
import services.warning_service as warning_service
import services.weather_service as weather_service
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import OpenMeteoHourly, WeatherHourly
from common.utils.kma_time import kst_midnight, now_kst
from crud.weather_crud import WeatherCRUD
from router.router import app
from services.index_service import _nearest_slot_end_hour, _slot_end_hour, windows_for
REGION = "1141000000"
@@ -66,3 +71,79 @@ async def test_index_detail_has_six_factors_and_rules(fakes):
assert sum(f["weight"] for f in body["factors"]) == 100
assert body["zero_rules"] == "비 확률 80% 이상 또는 바람 14m/s 이상이면 바로 0점"
assert body["limit"].startswith("모기")
def _om_row(at, **over):
row = {
"region_code": REGION, "forecast_at": at, "fetched_at": now_kst(), "uv_index": 2.0, "uv_index_clear_sky": 2.0,
"visibility_m": 25000, "wind_gust_ms": 5.0, "pressure_hpa": 1015.0, "soil_temp_c": 20.0,
"sunshine_s": 10800, "shortwave_avg_wm2": 500, "shortwave_max_wm2": 600,
}
return row | over
async def _put_om(rows):
await DB_SESSION_MNG.execute_lambda_run([lambda s: WeatherCRUD().upsert_openmeteo(s, rows)])
async def _laundry_sun(client):
items = (await client.get("/v1/index/list", params={"region": REGION})).json()["items"]
index_id = next(i["index_id"] for i in items if i["code"] == "laundry")
body = (await client.get(f"/v1/index/{index_id}", params={"region": REGION})).json()
return {f["axis"]: f for f in body["factors"]}
def test_slot_end_hours_for_covering_and_nearest_slot():
hours = (0, 2, 3, 7, 8, 9, 10, 11, 12, 15, 21, 23, 26)
assert [_slot_end_hour(h) for h in hours] == [3, 3, 6, 9, 9, 12, 12, 12, 15, 18, 24, 24, 27]
assert [_nearest_slot_end_hour(h) for h in hours] == [0, 3, 3, 9, 9, 9, 12, 12, 12, 15, 21, 24, 27]
def test_windows_attach_instant_values_from_nearest_slot_and_sunshine_from_covering_slot():
day = date(2026, 10, 6)
start = kst_midnight(day)
by_at = {
start + timedelta(hours=h): WeatherHourly(
forecast_at=start + timedelta(hours=h), feels_c=20, rain_type=1, rain_prob=0, wind_ms=1.0, humidity=50, sky=1
)
for h in range(7, 16)
}
by_om = {
start + timedelta(hours=end): OpenMeteoHourly(
forecast_at=start + timedelta(hours=end), uv_index=uv, sunshine_s=sun, visibility_m=12000, wind_gust_ms=7.5, soil_temp_c=20.0
)
for end, uv, sun in ((9, 1.0, 1800), (12, 2.0, 5400), (15, 3.0, 9000), (18, 4.0, 10800))
}
morning, noon = windows_for(SimpleNamespace(windows=[{"from": 7, "to": 9}, {"from": 11, "to": 16}]), day, None, by_at, by_om)
assert [h.uv for h in morning] == [1.0, 1.0]
assert [h.uv for h in noon] == [2.0, 2.0, 3.0, 3.0, 3.0] # 순간값은 가장 가까운 구간 (11·12시→12시, 13~15시→15시)
assert [h.sunshine_ratio for h in noon] == [0.5, 9000 / 10800, 9000 / 10800, 9000 / 10800, 1.0] # 일조는 덮는 구간 (직전 3시간 합)
assert morning[0].visibility_km == 12.0 and morning[0].gust_ms == 7.5 and morning[0].ground_c == 20.0
no_om = windows_for(SimpleNamespace(windows=[{"from": 7, "to": 9}]), day, None, by_at, None)[0]
assert all(h.uv is None and h.sunshine_ratio is None for h in no_om)
@pytest.mark.anyio
async def test_new_axis_shows_only_for_weighted_indices_and_unknown_without_data(fakes):
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
laundry = await _laundry_sun(client)
yajang = (await client.get("/v1/index/1", params={"region": REGION})).json()["factors"]
assert laundry["sun"]["weight"] == 25 and laundry["sun"]["value"] == 70 and laundry["sun"]["note"] == "햇빛 정보 없음"
assert sum(f["weight"] for f in laundry.values()) == 100
assert [f["axis"] for f in yajang] == ["temp", "rain", "wind", "humidity", "air", "time"]
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
items = (await client.get("/v1/index/list", params={"region": REGION})).json()["items"]
stars_id = next(i["index_id"] for i in items if i["code"] == "stars")
stars = (await client.get(f"/v1/index/{stars_id}", params={"region": REGION})).json()["factors"]
assert {f["axis"]: f["label"] for f in stars}["view"] == "가시거리"
@pytest.mark.anyio
async def test_openmeteo_data_changes_index_and_triggers_recompute(fakes):
today = kst_midnight(now_kst().date())
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
before = await _laundry_sun(client)
assert before["sun"]["value"] == 70
await _put_om([_om_row(today + timedelta(hours=h), fetched_at=now_kst() + timedelta(hours=1)) for h in (12, 15, 18)])
after = await _laundry_sun(client)
assert after["sun"]["value"] == 100 and after["sun"]["note"] == "해 난 비율 100%"
+43 -3
View File
@@ -2,7 +2,7 @@ from datetime import date, datetime, timezone
from types import SimpleNamespace
from common.enums import RainType, Sky
from services.calc.index_calc import Context, Hour, evaluate, rain_score, temp_score, zero_rules_text
from services.calc.index_calc import Context, Hour, evaluate, rain_score, sun_score, temp_score, uv_score, view_score, zero_rules_text
from services.calc.moon import illumination
CTX = Context(day=date(2026, 10, 2), is_holiday=False, pm25=10, air_label="좋음", moon=0.5, sunset_score=80, wind_warning=False, lookahead_rain_prob=0)
@@ -20,8 +20,8 @@ def _defn(**kw):
return SimpleNamespace(**{**base, **kw})
def _h(hour, feels=21.0, prob=0, rain=RainType.NONE, wind=1.5, hum=50, sky=Sky.CLEAR):
return Hour(hour=hour, feels_c=feels, rain_type=rain, rain_prob=prob, wind_ms=wind, humidity=hum, sky=sky)
def _h(hour, feels=21.0, prob=0, rain=RainType.NONE, wind=1.5, hum=50, sky=Sky.CLEAR, **extra):
return Hour(hour=hour, feels_c=feels, rain_type=rain, rain_prob=prob, wind_ms=wind, humidity=hum, sky=sky, **extra)
def test_perfect_evening_scores_100():
@@ -80,3 +80,43 @@ def test_zero_rules_text():
def test_moon_full_and_new():
assert illumination(datetime(2000, 1, 6, 18, 14, tzinfo=timezone.utc)) < 0.01
assert illumination(datetime(2000, 1, 21, 12, tzinfo=timezone.utc)) > 0.95
def test_uv_sun_view_scores_are_linear_and_unknown_is_70():
assert uv_score({"zero": 8, "full": 2}, 1)[0] == 100 and uv_score({"zero": 8, "full": 2}, 5)[0] == 50 and uv_score({"zero": 8, "full": 2}, 9)[0] == 0
assert sun_score({"zero": 0.2, "full": 0.8}, 0.5)[0] == 50 and sun_score({"zero": 0.2, "full": 0.8}, 1.0)[0] == 100
assert view_score({"zero": 5, "full": 20}, 12.5)[0] == 50 and view_score({"zero": 5, "full": 20}, 3)[0] == 0
assert (uv_score({"zero": 8, "full": 2}, None)[0], sun_score({"zero": 0.2, "full": 0.8}, None)[0], view_score({"zero": 5, "full": 20}, None)[0]) == (70, 70, 70)
assert uv_score({"zero": 8, "full": 2}, 5)[1] == "자외선 5.0"
assert view_score({"zero": 5, "full": 20}, 12.5)[1] == "가시거리 12.5km" and view_score({"zero": 5, "full": 20}, None)[1] == "가시거리 정보 없음"
def _uv_defn():
rules = _defn().factor_rules | {"uv": {"zero": 8, "full": 2}}
return _defn(weight_temp=25, weight_humidity=5, weight_uv=10, factor_rules=rules)
def test_weighted_uv_axis_lowers_score_when_uv_is_high_and_is_unknown_when_missing():
low = evaluate(_uv_defn(), [[_h(19, wind=1.0, uv=1.0)]], CTX)
high = evaluate(_uv_defn(), [[_h(19, wind=1.0, uv=9.0)]], CTX)
missing = evaluate(_uv_defn(), [[_h(19, wind=1.0)]], CTX)
assert low.score == 100 and low.factors["uv"] == 100
assert high.factors["uv"] == 0 and high.score < 80
assert missing.factors["uv"] == 70 and missing.notes["uv"] == "자외선 정보 없음"
def test_unweighted_new_axes_do_not_affect_score_and_use_max_uv_in_window():
plain = evaluate(_defn(), [[_h(19, wind=1.0, uv=9.0)]], CTX)
assert plain.score == 100 and plain.factors["uv"] == 0
window = evaluate(_uv_defn(), [[_h(19, wind=1.0, uv=1.0), _h(20, wind=1.0, uv=9.0)]], CTX)
assert window.factors["uv"] == 0
def test_gust_and_ground_temperature_zero_rules():
gust = _defn(zero_rules=[{"field": "gust_ms", "op": ">=", "value": 15}])
assert evaluate(gust, [[_h(19, wind=1.0, gust_ms=16.0)]], CTX).score == 0
assert evaluate(gust, [[_h(19, wind=1.0, gust_ms=10.0)]], CTX).score == 100
assert evaluate(gust, [[_h(19, wind=1.0)]], CTX).score == 100 # 값이 없으면 걸리지 않는다
ground = [{"field": "ground_c", "op": ">=", "value": 45}]
assert zero_rules_text(ground) == "지표면 온도 45° 이상이면 바로 0점"
assert evaluate(_defn(zero_rules=ground), [[_h(19, wind=1.0, ground_c=47.0)]], CTX).zero_reason == "지표면 온도 45° 이상이면"
+101
View File
@@ -0,0 +1,101 @@
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"]
+19
View File
@@ -63,3 +63,22 @@ async def test_sky_ranking_has_30_spots_sorted(monkeypatch, clean):
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
+4 -4
View File
@@ -9,21 +9,21 @@ CLEAR = Layers(0, 0, 0)
def test_high_clouds_overhead_and_clear_horizon_is_best():
canvas = Layers(low=0, mid=20, high=50)
assert score(canvas, canvas, CLEAR) == 100
assert score(canvas, CLEAR) == 100
def test_clear_sky_is_only_soft():
assert grade(score(CLEAR, CLEAR, CLEAR)) is SkyGrade.SOFT
assert grade(score(CLEAR, CLEAR)) is SkyGrade.SOFT
def test_low_clouds_toward_sun_block_the_light():
canvas = Layers(low=0, mid=20, high=50)
assert grade(score(canvas, canvas, Layers(low=90, mid=50, high=0))) is SkyGrade.GRAY
assert grade(score(canvas, Layers(low=90, mid=50, high=0))) is SkyGrade.GRAY
def test_overcast_low_clouds_is_gray():
gray = Layers(low=100, mid=100, high=100)
assert grade(score(gray, gray, gray)) is SkyGrade.GRAY
assert grade(score(gray, gray)) is SkyGrade.GRAY
def test_confidence_from_model_spread():