Merge origin/main into main-2: Open-Meteo 구름 20·100km·모델 2개 구조에 노을 하늘 상황 판정 맞춤
- 하늘 상황 판정·테스트를 구름 지점 2곳(20·100km), 모델 2개(JMA·ICON) 기준으로 - Open-Meteo 보조값 호출(fetch_weather)도 장애 대처(8초 끊기·2분 건너뛰기) 적용 - worker: 행사 수집 스케줄과 Open-Meteo 보조값 스케줄 둘 다 유지 - 지수 seed: main 의 한계 설명 + main-2 의 점수 구간 설명 - 옛 data-pipeline 문서는 삭제 유지, 내용은 openmeteo-data.md·데이터_흐름.html 에 반영
This commit is contained in:
commit
3f8f7daeb1
21 files changed
+1068
-111
No files matched your search
@@ -42,7 +42,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",
|
||||
)
|
||||
|
||||
@@ -68,8 +68,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
|
||||
@@ -96,6 +97,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")])))
|
||||
@@ -106,6 +118,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(weather_service, "fetch_mid", lambda *a: _async(({}, {})))
|
||||
monkeypatch.setattr(week_service, "fetch_holidays", lambda *a: _async([]))
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda c, sido, since: _async([{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from datetime import date, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
@@ -6,9 +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 slot_days, slot_label
|
||||
from services.index_service import _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
|
||||
REGION = "1141000000"
|
||||
|
||||
@@ -96,3 +100,93 @@ def test_every_index_has_four_band_sentences():
|
||||
import os
|
||||
seed = json.load(open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "index_definition.json"), encoding="utf-8"))
|
||||
assert all(sorted(d["sentences"], key=int) == ["0", "30", "60", "80"] and all(d["sentences"].values()) for d in seed)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def test_dark_slots_count_as_no_sun_not_unknown():
|
||||
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 (22, 23)
|
||||
}
|
||||
by_om = {start + timedelta(hours=24): OpenMeteoHourly(forecast_at=start + timedelta(hours=24), uv_index=None, sunshine_s=None, visibility_m=20000)}
|
||||
hours = windows_for(SimpleNamespace(windows=[{"from": 22, "to": 24}]), day, None, by_at, by_om)[0]
|
||||
assert [(h.uv, h.sunshine_ratio, h.visibility_km) for h in hours] == [(0.0, 0.0, 20.0)] * 2
|
||||
|
||||
|
||||
@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%"
|
||||
@@ -4,8 +4,8 @@ from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from services.calc.index_calc import (
|
||||
OUTING_HOURS, Context, DayForecast, Hour, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, temp_score,
|
||||
zero_rules_text,
|
||||
OUTING_HOURS, Context, DayForecast, Hour, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
|
||||
uv_score, view_score, zero_rules_text,
|
||||
)
|
||||
from services.calc.moon import illumination
|
||||
|
||||
@@ -24,8 +24,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():
|
||||
@@ -111,6 +111,52 @@ def test_moon_full_and_new():
|
||||
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° 이상이라 0점"
|
||||
|
||||
|
||||
def test_estimate_and_labels_cover_openmeteo_axes():
|
||||
r = estimate(_uv_defn(), _fc(), [[19, 20]], CTX)
|
||||
assert r.factors["uv"] == 70 and r.factors["sun"] == 0 and r.factors["view"] == 0
|
||||
assert [axis_label(a, {}) for a in ("uv", "sun", "view")] == ["자외선", "햇빛", "가시거리"]
|
||||
|
||||
|
||||
def _fc(lo=15.0, hi=23.0, am=0, pm=0, sky=Sky.CLEAR):
|
||||
return DayForecast(temp_min_c=lo, temp_max_c=hi, rain_prob_am=am, rain_prob_pm=pm, sky=sky)
|
||||
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
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
|
||||
|
||||
|
||||
def test_dark_slots_drop_sun_values_but_keep_others():
|
||||
times = [f"2026-10-06T{h:02d}:00" for h in range(24)]
|
||||
full = {k: [1.0] * 24 for k in ("uv_index", "uv_index_clear_sky", "visibility", "wind_gusts_10m", "pressure_msl", "soil_temperature_0cm")}
|
||||
rows = {r["forecast_at"].hour: r for r in parse_weather({"hourly": {"time": times, "sunshine_duration": [600] * 24, "shortwave_radiation": [50] * 24} | full})}
|
||||
dark = {15, 18, 21} # GMT 끝 시각 = KST 0·3·6시 (21~06시). KST 21시 구간(18~21시)은 남긴다
|
||||
assert sorted(rows) == [3, 6, 9, 12, 15, 18, 21]
|
||||
for hour, row in rows.items():
|
||||
sun = (row["uv_index"], row["uv_index_clear_sky"], row["sunshine_s"], row["shortwave_avg_wm2"], row["shortwave_max_wm2"])
|
||||
assert (sun == (None,) * 5) is (hour in dark)
|
||||
assert row["visibility_m"] == 1 and row["soil_temp_c"] == 1.0
|
||||
|
||||
|
||||
@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"]
|
||||
@@ -55,7 +55,7 @@ async def test_sky_view_scores_three_days_with_spots(monkeypatch, clean):
|
||||
assert "알맞게" in plan["reason"]
|
||||
assert plan["spot"]["name"] == "망원한강공원" and plan["best_at"]
|
||||
assert [t["kind"] for t in plan["timeline"]] == ["golden", "sun", "blue"]
|
||||
assert plan["situation_label"] == "하늘이 넓게 물들 수 있어요" and plan["models_agree"] == plan["models_total"] == 4
|
||||
assert plan["situation_label"] == "하늘이 넓게 물들 수 있어요" and plan["models_agree"] == plan["models_total"] == 2
|
||||
assert plan["outlook"] == ""
|
||||
assert body["sunset"]["verdict"] == "go" and body["spots"][0]["direction"]
|
||||
|
||||
@@ -122,3 +122,22 @@ def test_outlook_only_when_a_later_day_has_a_better_verdict():
|
||||
few, glow = SkySituation.FEW, SkySituation.GLOW
|
||||
assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few), sit(2, glow)], today) == "모레가 더 나아요 · 하늘이 넓게 물들 수 있어요"
|
||||
assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few)], today) == ""
|
||||
|
||||
|
||||
@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
|
||||
@@ -10,21 +10,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():
|
||||
@@ -48,10 +48,10 @@ def test_sunset_best_times_order():
|
||||
|
||||
def test_reason_names_what_decided_the_score():
|
||||
canvas = Layers(low=0, mid=20, high=50)
|
||||
assert "알맞게" in reason(canvas, canvas, CLEAR)
|
||||
assert "먼 하늘" in reason(canvas, canvas, Layers(low=90, mid=50, high=0))
|
||||
assert "낮은 구름" in reason(Layers(100, 0, 0), Layers(80, 0, 0), CLEAR)
|
||||
assert "거의 없어" in reason(CLEAR, CLEAR, CLEAR)
|
||||
assert "알맞게" in reason(canvas, CLEAR)
|
||||
assert "먼 하늘" in reason(canvas, Layers(low=90, mid=50, high=0))
|
||||
assert "낮은 구름" in reason(Layers(100, 0, 0), CLEAR)
|
||||
assert "거의 없어" in reason(CLEAR, CLEAR)
|
||||
|
||||
|
||||
def test_verdict_bands_and_gray_label_is_not_weather_word():
|
||||
@@ -70,11 +70,11 @@ def test_sunset_timeline_runs_golden_to_blue():
|
||||
def test_situation_follows_reason_order():
|
||||
from common.enums import SkySituation
|
||||
clear, glow = Layers(0, 0, 0), Layers(0, 40, 50)
|
||||
assert situation(clear, clear, clear) is SkySituation.FEW
|
||||
assert situation(glow, glow, clear) is SkySituation.GLOW
|
||||
assert situation(Layers(0, 90, 95), Layers(0, 90, 95), clear) is SkySituation.THICK
|
||||
assert situation(Layers(80, 0, 0), Layers(70, 0, 0), clear) is SkySituation.LOW_CLOUD
|
||||
assert situation(glow, glow, Layers(70, 0, 0)) is SkySituation.COVERED
|
||||
assert situation(clear, clear) is SkySituation.FEW
|
||||
assert situation(glow, clear) is SkySituation.GLOW
|
||||
assert situation(Layers(0, 90, 95), clear) is SkySituation.THICK
|
||||
assert situation(Layers(80, 0, 0), clear) is SkySituation.LOW_CLOUD
|
||||
assert situation(glow, Layers(70, 0, 0)) is SkySituation.COVERED
|
||||
|
||||
|
||||
def test_ranking_summary_only_when_most_spots_share_a_situation():
|
||||
|
||||
Reference in new issue
Block a user