Files
o2o-weather/backend/tests/test_index_calc.py
T

485 lines
25 KiB
Python

import json
from dataclasses import replace
from datetime import date, datetime, timezone
from pathlib import Path
from types import SimpleNamespace
import pytest
from common.enums import RainType, Sky
from services.calc.index_calc import (
OUTING_HOURS, Context, DayForecast, Hour, air_score, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
priority_score, rank_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)
def _defn(**kw):
base = dict(
weight_temp=30, weight_rain=25, weight_wind=15, weight_humidity=10, weight_air=10, weight_time=10,
factor_rules={
"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 2, "limit": 10},
"humidity": {"type": "range", "lo": 40, "hi": 60}, "time": {"type": "weekday", "fri": 100, "default": 78},
},
zero_rules=[{"field": "rain_prob", "op": ">=", "value": 80}],
)
return SimpleNamespace(**{**base, **kw})
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():
r = evaluate(_defn(), [[_h(19, wind=1.0), _h(20, wind=1.0)]], CTX)
assert r.score == 100 and r.zero_reason is None
assert r.notes["temp"] == "체감 21°, 편한 범위 18~24° 안"
def test_rank_and_display_share_priority_adjusted_screenshot_scores():
items = [(83, 1), (82, 1), (80, 1), (91, 2), (77, 1), (77, 1), (76, 1), (89, 2), (87, 2)]
shown = [(priority_score(score, priority), priority) for score, priority in items]
ranked = sorted(shown, key=lambda item: rank_score(*item), reverse=True)
assert [score for score, _ in ranked] == [83, 82, 80, 77, 77, 77, 76, 76, 74]
assert priority_score(91, 2) == 77
assert priority_score(89, 2) == 76
def test_rank_uses_priority_only_to_break_ties():
items = [(80, 3), (80, 1), (81, 3), (80, 2)]
assert sorted(items, key=lambda item: rank_score(*item), reverse=True) == [(81, 3), (80, 1), (80, 2), (80, 3)]
@pytest.mark.parametrize("weight", [5, 10, 20])
def test_time_match_adds_only_its_weight_without_extra_penalty(weight):
rules = _defn().factor_rules | {"time": {"type": "fixed", "value": 55}}
defn = _defn(weight_temp=100 - weight, weight_rain=0, weight_wind=0, weight_humidity=0, weight_air=0,
weight_time=weight, factor_rules=rules)
hours = [[_h(12)]]
matched = evaluate(defn, hours, replace(CTX, time_matches=True))
unmatched = evaluate(defn, hours, replace(CTX, time_matches=False))
assert matched.factors["time"] == 100 and unmatched.factors["time"] == 0
assert matched.score == 100 and unmatched.score == 100 - weight
def test_time_matching_does_not_replace_weekday_score():
assert evaluate(_defn(), [[_h(12)]], replace(CTX, time_matches=False)).factors["time"] == 100
def test_time_mismatch_cap_only_applies_outside_activity_hours():
limit = [{"field": "time_matches", "op": "==", "value": False, "cap": 50}]
defn = _defn(factor_rules=_defn().factor_rules | {"time": {"type": "fixed", "value": 100}}, zero_rules=limit)
matched = evaluate(defn, [[_h(7, wind=1.0)]], CTX)
unmatched = evaluate(defn, [[_h(12, wind=1.0)]], replace(CTX, time_matches=False))
assert matched.score == 100 and matched.zero_reason is None
assert unmatched.score == 50 and unmatched.zero_reason == "활동 시간대가 아니라 최대 50점"
assert zero_rules_text(limit) == "활동 시간대가 아니면 최대 50점"
assert zero_rules_text(limit + [{"field": "rain_prob", "op": ">=", "value": 60, "cap": 50}]) == \
"활동 시간대가 아니거나 비 확률 60% 이상이면 최대 50점"
def test_good_but_not_perfect_stays_below_100():
assert evaluate(_defn(), [[_h(19, feels=23, hum=58, wind=1.8)]], CTX).score < 95
def test_one_bad_factor_pulls_total_down():
assert evaluate(_defn(), [[_h(19, wind=1.0, prob=75)]], CTX).score < 75
def test_temp_is_full_near_best_and_falls_gently_to_zero_outside():
rule = {"type": "range", "lo": 14, "hi": 28} # 최적 21 ±2 = 19~23 은 100
assert [temp_score(rule, t)[0] for t in (19, 21, 23)] == [100, 100, 100]
assert 85 < temp_score(rule, 25)[0] < 100 and temp_score(rule, 28)[0] == 85 # 범위 끝으로 갈수록 85까지
assert temp_score({"type": "range", "lo": 18, "hi": 24, "best": 22}, 22)[0] == 100
assert temp_score({"type": "range", "lo": 18, "hi": 24}, 15)[0] == 77 # 범위 밖 3°
assert temp_score({"type": "range", "lo": 18, "hi": 24}, 18 - 85 / 8)[0] == 0 # 예전 직선이 0이 되던 거리에서 0
assert temp_score({"type": "lower", "zero": 25, "full": 5}, 15)[0] == 70
assert temp_score({"type": "range", "lo": 10, "hi": 20, "offset": -6}, 21)[1].startswith("산 정상 기준 15°")
def test_temp_away_rises_outside_comfort():
rule = {"type": "away", "lo": 15, "hi": 24}
assert temp_score(rule, 20)[0] == 30
assert temp_score(rule, 34)[0] == 100
assert temp_score(rule, 5)[0] == 100
def test_rain_dry_and_wet():
assert rain_score({"dir": "dry"}, 30, False)[0] == 89
assert rain_score({"dir": "dry"}, 100, False)[0] == 0
assert rain_score({"dir": "dry"}, 30, True)[0] == 0
assert rain_score({"dir": "wet"}, 30, True)[0] == 100
def test_zero_rule_forces_zero_and_cap_limits():
assert evaluate(_defn(), [[_h(19, prob=80)]], CTX).score == 0
capped = _defn(zero_rules=[{"field": "rain_prob", "op": ">=", "value": 70, "cap": 20}])
r = evaluate(capped, [[_h(19, prob=70)]], CTX)
assert r.score <= 20 and r.zero_reason == "비 확률 70% 이상이라 최대 20점"
assert evaluate(_defn(), [[_h(19, prob=80)]], CTX).zero_reason == "비 확률 80% 이상이라 0점"
def test_lookahead_rain_is_named_in_note():
defn = _defn(windows=[{"from": 9, "to": 18, "lookahead_days": 2}])
r = evaluate(defn, [[_h(10, prob=0)]], replace(CTX, lookahead_rain_prob=60))
assert r.notes["rain"] == "모레까지 비 확률 60%"
assert evaluate(defn, [[_h(10, prob=0)]], CTX).notes["rain"] == "비 확률 0%"
def test_air_note_has_unit():
assert evaluate(_defn(), [[_h(19)]], CTX).notes["air"] == "초미세먼지 10㎍/㎥, 좋음"
def test_axis_label_reads_outward_as_good():
rules = _defn().factor_rules
assert [axis_label(a, rules) for a in ("temp", "rain", "wind", "humidity", "air", "time")] == \
["기온 알맞음", "비 안 옴", "바람 잔잔", "습도 알맞음", "공기 맑음", "요일 알맞음"]
wet = {"temp": {"type": "lower"}, "rain": {"dir": "wet"}, "wind": {"type": "strong"}, "humidity": {"type": "higher"}, "time": {"type": "moon"}}
assert [axis_label(a, wet) for a in ("temp", "rain", "wind", "humidity", "time")] == ["추움", "비 옴", "바람 셈", "습도 높음", "달 어두움"]
def test_best_window_is_chosen():
r = evaluate(_defn(), [[_h(7, feels=5)], [_h(20, feels=21)]], CTX)
assert r.window == (20, 20)
def test_zero_rules_text():
assert zero_rules_text([{"field": "rain_prob", "op": ">=", "value": 80}, {"field": "wind_ms", "op": ">=", "value": 14}]) == \
"비 확률 80% 이상이거나 바람 14m/s 이상이면 0점"
assert zero_rules_text([{"field": "rain_prob", "op": ">=", "value": 70}, {"field": "warning", "op": "==", "value": "wind"}]) == \
"비 확률 70% 이상이거나 강풍 특보가 있으면 0점"
assert zero_rules_text([{"field": "rain_prob", "op": ">=", "value": 70, "cap": 20}]) == "비 확률 70% 이상이면 최대 20점"
assert zero_rules_text([{"field": "pm25", "op": ">=", "value": 75}]) == "초미세먼지 75㎍/㎥ 이상이면 0점"
assert 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_fall_gently_and_unknown_is_70():
assert uv_score({"zero": 8, "full": 2}, 1)[0] == 100 and uv_score({"zero": 8, "full": 2}, 5)[0] == 70 and uv_score({"zero": 8, "full": 2}, 9)[0] == 0
assert sun_score({"zero": 0.2, "full": 0.8}, 0.5)[0] == 70 and sun_score({"zero": 0.2, "full": 0.8}, 1.0)[0] == 100
assert view_score({"zero": 5, "full": 20}, 12.5)[0] == 70 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)
def test_hour_temp_follows_min_at_dawn_and_max_mid_afternoon():
assert hour_temp(10, 20, 6) == 10 and hour_temp(10, 20, 15) == 20
assert 10 < hour_temp(10, 20, 21) < 20 and hour_temp(10, 20, 30) == 10
def test_estimate_is_flagged_and_unknown_factors_are_70():
r = estimate(_defn(), _fc(), [[19, 20]], CTX)
assert r.estimated is True
assert r.factors["wind"] == 70 and r.factors["humidity"] == 70 and r.factors["air"] == 70
assert "예상" in r.summary
def test_estimate_uses_rain_prob_of_the_window_half_day():
morning, evening = estimate(_defn(), _fc(am=60, pm=0), [[9, 10]], CTX), estimate(_defn(), _fc(am=60, pm=0), [[19, 20]], CTX)
assert morning.factors["rain"] == 58 and evening.factors["rain"] == 100
def test_estimate_applies_rain_zero_rule_only():
r = estimate(_defn(zero_rules=[{"field": "rain_prob", "op": ">=", "value": 80}, {"field": "wind_ms", "op": ">=", "value": 1}]), _fc(pm=80), [[19]], CTX)
assert r.score == 0 and r.zero_reason.startswith("비 확률 80% 이상")
def test_estimate_without_temps_gives_none():
assert estimate(_defn(), _fc(lo=None, hi=None), [[19]], CTX) is None
def _day(**kw):
return [_h(h, **kw) for h in range(*OUTING_HOURS)]
def test_outing_perfect_day_is_100_and_reason_names_rain_temp_sky():
r = outing(_day(wind=1.0))
assert r.score == 100 and r.estimated is False
assert r.reason == "비 0% · 체감 21° · 맑음"
def test_outing_cloudy_and_hot_days_lose_points():
clear, cloudy, hot = outing(_day()), outing(_day(sky=Sky.CLOUDY)), outing(_day(feels=30.0))
assert cloudy.score < clear.score and hot.score < clear.score
assert "흐림" in cloudy.reason
def test_outing_rain_lowers_score_without_a_cap():
"""비가 오면 비 점수와 가장 낮은 요소 때문에 점수가 내려가지만, 따로 상한으로 묶지는 않는다."""
clear = outing(_day())
likely = outing(_day(prob=70))
raining = outing([_h(10, prob=30, rain=RainType.RAIN)] + _day()[1:])
assert raining.score < likely.score < clear.score
assert likely.score > 30 and raining.score > 30
def test_outing_rainy_days_keep_their_differences():
"""전국이 비인 날에도 기온·하늘에 따라 점수가 갈린다 (예전엔 모두 상한 30점에 걸려 같은 점수였다)."""
mild = outing(_day(feels=16.0, sky=Sky.CLOUDY, rain=RainType.RAIN))
chilly = outing(_day(feels=14.0, sky=Sky.CLOUDY, rain=RainType.RAIN))
assert chilly.score < mild.score
def test_outing_needs_all_hours():
assert outing(_day()[:3]) is None
def test_outing_estimate_from_mid_forecast():
r = outing_estimate(_fc(lo=12, hi=22, am=10, pm=20))
assert r.estimated is True and r.factors["wind"] == 70
assert r.reason.startswith("비 20% · 낮 ")
assert 30 < outing_estimate(_fc(pm=60)).score < outing_estimate(_fc(pm=0)).score
assert outing_estimate(_fc(lo=None, hi=None)) is None
def test_air_rule_can_reverse_so_dusty_air_scores_high():
rule = {"zero": 15, "full": 75}
assert air_score(80, None, rule)[0] == 100 and air_score(10, None, rule)[0] == 0
assert air_score(10, None)[0] == 100
assert axis_label("air", {"air": rule}) == "공기 탁함" and axis_label("air", {}) == "공기 맑음"
_SEED = {x["code"]: SimpleNamespace(**x) for x in json.loads((Path(__file__).parents[1] / "seed" / "index_definition.json").read_text(encoding="utf-8"))}
_SAT, _WED = date(2026, 10, 10), date(2026, 10, 7)
def _seed_score(code, day=_SAT, pm25=10, **hour):
d = _SEED[code]
windows = [[_h(h, **hour) for h in range(w["from"], w["to"])] for w in d.windows]
return evaluate(d, windows, replace(CTX, day=day, pm25=pm25)).score
@pytest.mark.parametrize("prob, ceiling", [(60, 30), (69, 30), (70, 0)])
def test_running_high_rain_probability_limits_score(prob, ceiling):
assert _seed_score("running", feels=12, prob=prob) <= ceiling
@pytest.mark.parametrize("rain", [RainType.RAIN, RainType.SNOW, RainType.SLEET])
def test_running_any_precipitation_in_window_is_zero(rain):
hours = [_h(6, feels=12), _h(7, feels=12, prob=10, rain=rain)]
result = evaluate(_SEED["running"], [hours], CTX)
assert result.score == 0 and result.zero_reason == "비 소식이 있어 0점"
@pytest.mark.parametrize("feels, ceiling", [(-3, 0), (0, 40), (2, 40), (3, 40), (4.9, 40), (28, 30), (35, 0)])
def test_running_cold_and_heat_limit_score(feels, ceiling):
assert _seed_score("running", feels=feels) <= ceiling
def test_running_cold_limit_uses_coldest_hour():
hours = [_h(6, feels=3), _h(7, feels=12)]
assert evaluate(_SEED["running"], [hours], CTX).score <= 40
@pytest.mark.parametrize("hour", [6, 7, 19, 21])
@pytest.mark.parametrize("feels", [5, 8, 10, 12, 15])
def test_running_clear_cool_morning_and_evening_stay_good(hour, feels):
result = evaluate(_SEED["running"], [[_h(hour, feels=feels)]], CTX)
assert result.score >= 80 and result.zero_reason is None
@pytest.mark.parametrize("hour, feels", [(12, 12), (12, 14), (12, 25), (22, 12), (26, 12)])
def test_running_outside_activity_hours_stays_low(hour, feels):
result = evaluate(_SEED["running"], [[_h(hour, feels=feels)]], replace(CTX, time_matches=False))
assert result.factors["time"] == 0 and result.score <= 50
@pytest.mark.parametrize("wind, ceiling", [(6, 30), (8, 0)])
def test_running_strong_wind_limits_score(wind, ceiling):
assert _seed_score("running", feels=12, wind=wind) <= ceiling
def test_running_strong_gust_is_zero():
assert _seed_score("running", feels=12, gust_ms=15) == 0
@pytest.mark.parametrize("pm25, ceiling", [(36, 30), (75, 0)])
def test_running_bad_air_limits_score(pm25, ceiling):
assert _seed_score("running", feels=12, pm25=pm25) <= ceiling
def test_running_wind_warning_is_zero():
assert evaluate(_SEED["running"], [[_h(6, feels=12)]], replace(CTX, wind_warning=True)).score == 0
@pytest.mark.parametrize("hour", [dict(prob=60, feels=3), dict(prob=60, feels=35), dict(prob=60, wind=8)])
@pytest.mark.parametrize("time_matches", [True, False])
def test_running_stricter_limits_win_when_conditions_overlap(hour, time_matches):
result = evaluate(_SEED["running"], [[_h(6, **(dict(feels=12) | hour))]], replace(CTX, time_matches=time_matches))
assert result.score <= (30 if hour.get("feels") == 3 else 0)
@pytest.mark.parametrize("time_matches", [True, False])
@pytest.mark.parametrize("hour", [dict(feels=12), dict(feels=20, hum=80), dict(feels=3, prob=60), dict(feels=12, wind=8, rain=RainType.RAIN)])
def test_other_definitions_ignore_unused_time_match_condition(time_matches, hour):
from unittest.mock import patch
from services.calc import index_calc
ctx = replace(CTX, time_matches=time_matches, pm25=30)
windows = [[_h(7, **hour)]]
zero = index_calc._zero
for code, defn in _SEED.items():
if code == "running":
continue
assert all(r["field"] != "time_matches" for r in defn.zero_rules)
actual = evaluate(defn, windows, ctx)
with patch.object(index_calc, "_zero", side_effect=lambda rules, agg: zero(rules, {k: v for k, v in agg.items() if k != "time_matches"})):
assert actual == evaluate(defn, windows, ctx), code
@pytest.mark.parametrize("code, good, bad", [
("golf", dict(feels=19.0, wind=2.0, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
("jipkok", dict(feels=4.0, prob=90, rain=RainType.RAIN, wind=7.0, hum=85), dict(feels=20.0, wind=1.0, hum=40)),
("fishing", dict(feels=22.0, wind=3.0), dict(feels=17.0, wind=11.0)),
("drive", dict(feels=23.0, wind=4.0, hum=45, visibility_km=18.0), dict(feels=18.0, prob=80, rain=RainType.RAIN, visibility_km=5.0)),
("kite", dict(feels=19.0, wind=6.0), dict(feels=14.0, wind=0.5)),
("waterplay", dict(feels=28.0, wind=3.0, sunshine_ratio=0.7), dict(feels=18.0, wind=2.0, sunshine_ratio=0.3)),
("kimjang", dict(feels=9.0, wind=3.0), dict(feels=20.0, wind=2.0)),
])
def test_new_gak_good_day_high_bad_day_low(code, good, bad):
assert 80 <= _seed_score(code, pm25=60 if code == "jipkok" else 10, **good) < 100
assert _seed_score(code, **bad) <= 30
@pytest.mark.parametrize("code, good, bad", [
("flower", dict(feels=19.0, wind=2.0, sunshine_ratio=0.8, visibility_km=20.0), dict(feels=8.0, prob=80, rain=RainType.RAIN, sunshine_ratio=0.1, visibility_km=4.0)),
("blanket", dict(feels=22.0, wind=3.0, hum=35, sunshine_ratio=0.9), dict(feels=10.0, prob=70, rain=RainType.RAIN, hum=90, sunshine_ratio=0.1)),
("bingsu", dict(feels=33.0, hum=75), dict(feels=18.0, hum=40)),
("indoordry", dict(feels=27.0, prob=90, rain=RainType.RAIN, hum=55), dict(feels=14.0, hum=90)),
("riverwind", dict(feels=24.0, wind=3.0, hum=55), dict(feels=20.0, prob=80, rain=RainType.RAIN, wind=0.5, hum=90)),
("foliage", dict(feels=16.0, wind=2.0, sunshine_ratio=0.8, visibility_km=20.0), dict(feels=8.0, prob=80, rain=RainType.RAIN, sunshine_ratio=0.1, visibility_km=4.0)),
("sweetpotato", dict(feels=2.0, wind=6.0), dict(feels=20.0, wind=1.0)),
("bungeoppang", dict(feels=-5.0, wind=6.0), dict(feels=15.0, wind=1.0)),
("tangerine", dict(feels=-5.0, wind=7.0, prob=80, rain=RainType.SNOW), dict(feels=15.0, wind=1.0)),
])
def test_seasonal_gak_good_day_high_bad_day_low(code, good, bad):
assert _seed_score(code, **good) >= 80
assert _seed_score(code, **bad) <= 30
@pytest.mark.parametrize("code, good, bad", [
("hangang", dict(feels=20.0, wind=1.5, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
("themepark", dict(day=_WED, feels=20.0, wind=2.0), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
("date", dict(feels=20.0, wind=1.5), dict(feels=5.0, prob=90, rain=RainType.RAIN, pm25=60)),
("frizz", dict(feels=28.0, prob=90, rain=RainType.RAIN, hum=90), dict(feels=12.0, hum=35)),
("boiler", dict(feels=2.0, hum=85, prob=60), dict(feels=22.0, hum=40)),
("sunscreen", dict(feels=26.0, uv=8.0), dict(feels=8.0, uv=0.5)),
("mosquito", dict(feels=27.0, hum=85, wind=0.5), dict(feels=15.0, hum=40, wind=6.0)),
("tennis", dict(feels=18.0, wind=1.0, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
("hyodo", dict(feels=20.0, wind=1.5), dict(feels=20.0, prob=80, rain=RainType.RAIN)),
("thanks", dict(feels=0.0, prob=90, rain=RainType.RAIN), dict(feels=20.0)),
("gift", dict(feels=17.0, wind=1.5), dict(feels=17.0, prob=80, rain=RainType.RAIN)),
("party", dict(feels=3.0, prob=90, rain=RainType.RAIN), dict(day=_WED, feels=20.0)),
("game", dict(feels=3.0, prob=90, rain=RainType.RAIN, pm25=70), dict(day=_WED, feels=20.0)),
("selfie", dict(wind=1.0, hum=35, sunshine_ratio=0.8), dict(prob=90, rain=RainType.RAIN, hum=90, wind=8.0, sunshine_ratio=0.0)),
("sentimental", dict(feels=13.0, prob=90, rain=RainType.RAIN, wind=3.0, hum=85), dict(feels=28.0, hum=40, wind=0.5)),
])
def test_trend_and_mood_gak_good_day_high_bad_day_low(code, good, bad):
assert _seed_score(code, **good) >= 80
assert _seed_score(code, **bad) <= 30
def test_new_gak_100_only_when_every_factor_is_perfect():
perfect = dict(feels=19.5, wind=1.0, hum=35)
assert _seed_score("golf", **perfect) == 100
assert _seed_score("golf", day=_WED, **perfect) < 100
def test_weather_score_100_only_on_perfect_day():
from services.index_service import WEATHER_SCORE_DEF
perfect = Context(day=date(2026, 10, 2), is_holiday=False, pm25=8, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
hours = [_h(h, feels=21.0, prob=0, wind=0.8, hum=50, sunshine_ratio=1.0) for h in range(9, 22)]
assert evaluate(WEATHER_SCORE_DEF, [hours], perfect).score == 100
good = [_h(h, feels=22.5, prob=10, wind=2.5, hum=62, sunshine_ratio=0.7) for h in range(9, 22)]
assert evaluate(WEATHER_SCORE_DEF, [good], replace(perfect, pm25=15)).score < 95
def test_raining_now_caps_even_with_low_rain_prob():
"""초단기예보로 비가 들어온 시각은 예보 확률이 낮아도 '비 소식' 상한이 걸린다."""
defn = _defn(zero_rules=[{"field": "rain", "op": "==", "value": "yes", "cap": 20}])
r = evaluate(defn, [[_h(19, prob=30, rain=RainType.RAIN)]], CTX)
assert r.score <= 20 and r.zero_reason == "비 소식이 있어 최대 20점"
assert evaluate(defn, [[_h(19, prob=30)]], CTX).zero_reason is None
def test_humidity_cap():
defn = _defn(zero_rules=[{"field": "humidity", "op": ">=", "value": 85, "cap": 40}])
assert evaluate(defn, [[_h(19, hum=92)]], CTX).zero_reason == "습도 85% 이상이라 최대 40점"
assert zero_rules_text([{"field": "rain", "op": "==", "value": "yes"}]) == "비 소식이 있으면 0점"
def test_axis_label_can_be_overridden():
assert axis_label("temp", {"temp": {"type": "higher", "label": "덜 추움"}}) == "덜 추움"
def test_umbrella_lost_needs_rain_that_stopped():
"""우산분실각: 앞서 비가 왔다가 그친 시간대만 점수가 난다. 비가 안 온 날, 아직 비가 오는 시간대는 0점."""
defn = _defn(weight_temp=0, weight_rain=80, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=20,
zero_rules=[{"field": "rain_before", "op": "==", "value": "no"}, {"field": "rain", "op": "==", "value": "yes"}])
after_rain = replace(CTX, rain_hours=frozenset({9, 10}))
assert evaluate(defn, [[_h(13), _h(14)]], after_rain).score >= 80
assert evaluate(defn, [[_h(13), _h(14)]], CTX).zero_reason == "앞서 내린 비가 없어 0점"
assert evaluate(defn, [[_h(10, rain=RainType.RAIN)]], replace(CTX, rain_hours=frozenset({9, 10}))).score == 0
def test_weather_why_lists_every_condition_heaviest_first():
from services.index_service import WEATHER_SCORE_DEF, weather_why
ctx = Context(day=date(2026, 10, 2), is_holiday=False, pm25=12, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
r = evaluate(WEATHER_SCORE_DEF, [[_h(h, feels=19.0, prob=0, wind=2.0, hum=55, sunshine_ratio=0.9) for h in range(9, 22)]], ctx)
why = weather_why(r)
assert [w.label for w in why] == ["기온", "비", "햇볕", "바람", "습도", "미세먼지"]
assert sum(w.weight for w in why) == 100
assert why[0].note.startswith("체감 19°")