Files
o2o-weather/backend/tests/test_index_slots.py

123 lines
5.3 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_lower_day_and_late_night_but_keep_activity_hours():
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
assert results["day"].score <= 50 and results["early"].score <= 50
late = slot_results(RUNNING, SAT, REGION, hourly, {}, CTX, sunset, now=start + timedelta(hours=22))
assert late["night"].factors["time"] == 0 and late["night"].score <= 50
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