Files
o2o-weather/backend/tests/test_index_slots.py
T
skkim 5ab2381f79 feat: 지금 날씨를 초단기실황 관측값으로, 각 점수에서 시간대 알맞음 제거·우산각 계산식 변경
- 초단기실황(getUltraSrtNcst)을 받아 지금 정시 한 시각의 비·기온·습도·바람을 예보 대신 관측값으로 덮어씀 (체감·불쾌지수는 다시 계산). 지역별 1시간 캐시, 실패하면 초단기예보·단기예보로 되돌아감, 새 시각 실황이 나오면 각 점수를 다시 계산. 가이드대로 ±900 이상은 결측 처리. 테스트가 실제 기상청을 부르지 않게 실황 호출을 기본으로 막음
- 시간대 알맞음 요소를 31개 각에서 빼고 비중을 5% 단위로 나눔. 요소가 3개 미만이 된 뜨아각·파전각·감성노래각·감사각·선크림각에 요소를 더함. 러닝각의 활동 시간대 밖 점수 상한도 없앰. 요소가 하나뿐인 각은 가장 낮은 요소로 깎지 않음
- 우산각은 비 한 가지: 남은 하루(지금~자정) 비 확률 평균이 점수, 지금 비가 오면 70점에서 시작해 평균 × 30점을 더함. 내일·토·일 칸은 그날 6~24시 평균 × 100. 우산분실각도 비 한 가지
- 각 계산 기준 문서는 생성기를 새 규칙에 맞게 고쳐 다시 생성, 점수 계산식·서비스 동작 안내 문서 갱신
2026-11-23 14:51:04 +09:00

124 lines
5.4 KiB
Python

import json
from dataclasses import replace
from datetime import date, timedelta
from pathlib import Path
from types import SimpleNamespace
from common.enums import RainType, Sky
from common.utils.kma_time import kst_midnight
from services.calc.index_calc import Context, DayForecast
from services.index_service import day_result, slot_days, slot_label, slot_results
REGION = SimpleNamespace(lat=37.56, lon=126.97)
SAT = date(2026, 10, 10)
CTX = Context(day=SAT, is_holiday=False, pm25=10, air_label="좋음", moon=0.5, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
DEFN = SimpleNamespace(
weight_temp=40, weight_rain=40, weight_wind=20, weight_humidity=0, weight_air=0, weight_time=0,
factor_rules={
"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 4, "limit": 12},
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100},
},
zero_rules=[], windows=[{"from": 11, "to": 16}],
)
FC = {SAT: DayForecast(temp_min_c=12, temp_max_c=22, rain_prob_am=10, rain_prob_pm=20, sky=Sky.CLEAR)}
RUNNING = SimpleNamespace(**next(x for x in json.loads((Path(__file__).parents[1] / "seed" / "index_definition.json").read_text(encoding="utf-8")) if x["code"] == "running"))
def _hourly(day: date) -> dict:
start = kst_midnight(day)
return {
start + timedelta(hours=h): SimpleNamespace(
forecast_at=start + timedelta(hours=h), feels_c=21, rain_type=RainType.NONE.value, rain_prob=0, wind_ms=1.0, humidity=50, sky=Sky.CLEAR.value,
)
for h in range(24)
}
def _d(day: int) -> date:
return date(2026, 10, day)
def test_slots_on_weekdays_are_today_tomorrow_sat_sun():
for today in (5, 6, 7, 8):
assert slot_days(_d(today)) == [_d(today), _d(today + 1), _d(10), _d(11)]
def test_slots_on_friday_keep_this_sunday_then_next_saturday():
assert slot_days(_d(9)) == [_d(9), _d(10), _d(11), _d(17)]
def test_slots_on_saturday_and_sunday_move_to_next_weekend():
assert slot_days(_d(10)) == [_d(10), _d(11), _d(17), _d(18)]
assert slot_days(_d(11)) == [_d(11), _d(12), _d(17), _d(18)]
def test_slot_labels():
today = date(2026, 10, 6)
assert [slot_label(d, today) for d in slot_days(today)] == ["오늘", "내일", "토 10.10", "일 10.11"]
assert [slot_label(d, _d(9)) for d in slot_days(_d(9))] == ["오늘", "내일", "일 10.11", "토 10.17"]
def test_weekend_in_short_range_uses_hourly_score():
r = day_result(DEFN, SAT, REGION, _hourly(SAT), FC, CTX, short=False)
assert r.estimated is False and r.factors["wind"] == 100
def test_weekend_beyond_short_range_uses_mid_forecast_estimate():
r = day_result(DEFN, SAT, REGION, {}, FC, CTX, short=False)
assert r.estimated is True and r.factors["wind"] == 70 and r.factors["rain"] == 95
def test_partial_hourly_falls_back_to_estimate():
partial = {k: v for k, v in _hourly(SAT).items() if k.hour < 13}
assert day_result(DEFN, SAT, REGION, partial, FC, CTX, short=False).estimated is True
def test_no_mid_forecast_gives_no_score():
assert day_result(DEFN, SAT, REGION, {}, {}, CTX, short=False) is None
def test_running_slot_rain_outside_activity_hours_still_zero():
start = kst_midnight(SAT)
hourly = _hourly(SAT)
for row in hourly.values():
row.feels_c = 12
hourly[start + timedelta(hours=9)].rain_type = RainType.RAIN.value
results = slot_results(RUNNING, SAT, REGION, hourly, {}, CTX, start + timedelta(hours=18))
assert results["morning"].score == 0
assert results["morning"].zero_reason == "비 소식이 있어 0점"
assert results["night"].score >= 80
def test_running_slots_follow_the_weather_not_the_activity_hours():
"""낮이 낮은 건 25°가 더워서일 뿐이다. 활동 시간대(6~8시·19~22시) 밖이라는 이유의 점수 상한은 없다."""
start = kst_midnight(SAT)
hourly = _hourly(SAT) | _hourly(SAT + timedelta(days=1))
for row in hourly.values():
row.feels_c = 25 if 11 <= row.forecast_at.hour < 16 else 12
sunset = start + timedelta(hours=18)
results = slot_results(RUNNING, SAT, REGION, hourly, {}, CTX, sunset)
assert results["morning"].score >= 80 and results["night"].score >= 80 and results["early"].score >= 80
assert 50 < results["day"].score < results["morning"].score
late = slot_results(RUNNING, SAT, REGION, hourly, {}, CTX, sunset, now=start + timedelta(hours=22))
assert late["night"].score >= 80
def test_running_muggy_morning_does_not_exceed_original_weather_score():
start = kst_midnight(SAT)
hourly = _hourly(SAT)
for row in hourly.values():
row.feels_c, row.humidity, row.wind_ms = 20, 80, 1.5
results = slot_results(RUNNING, SAT, REGION, hourly, {}, replace(CTX, pm25=30), start + timedelta(hours=18))
assert results["morning"].factors["time"] == 100
assert results["morning"].score <= 67
def test_now_slot_summary_shows_current_hour_not_middle_of_rest():
"""오후 4시 10분이면 지금 구간 줄은 남은 16~18시의 가운데(5시)가 아니라 지금(4시) 날씨로."""
start = kst_midnight(SAT)
hourly = _hourly(SAT) | _hourly(SAT + timedelta(days=1))
sunset = start + timedelta(hours=17, minutes=30)
results = slot_results(RUNNING, SAT, REGION, hourly, {}, CTX, sunset, now=start + timedelta(hours=16, minutes=10))
assert results["evening"].summary.startswith("오후 4시"), results["evening"].summary
assert results["night"].summary.startswith("오후 4시") is False