- 예전 식은 '그 구간에 비 소식이 있으면 0점, 앞서 내린 비가 없으면 0점'이라 구간마다 비 예보가 있는 날은 종일 0점이었고, 앞서 내린 비는 관측이 아니라 저장된 예보로 판단해 실제와 어긋났음
- 새 식: 우산을 챙겼을 정도(지금 비가 오면 100%, 아니면 지금부터 자정까지 가장 높은 비 확률) × 비가 안 오는 시간의 비율(100% − 남은 시각 비 확률 평균). 지난 시각은 보지 않고 0점 조건을 없앰. 내일·토·일 칸은 그날 9~22시로 같은 식
- 설명·요소 이름('우산 안 쓰는 시간')·점수 구간 문장을 새 뜻에 맞춤 (문구는 검토 전), 각 계산 기준 문서 다시 생성
643 lines
34 KiB
Python
643 lines
34 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_can_be_done_at_any_hour(hour, feels):
|
||
"""러닝각은 활동 시간대 밖이라고 점수 상한을 두지 않는다."""
|
||
outside = evaluate(_SEED["running"], [[_h(hour, feels=feels)]], replace(CTX, time_matches=False))
|
||
inside = evaluate(_SEED["running"], [[_h(hour, feels=feels)]], replace(CTX, time_matches=True))
|
||
assert outside.score == inside.score
|
||
|
||
|
||
@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)])
|
||
def test_running_stricter_limits_win_when_conditions_overlap(hour):
|
||
result = evaluate(_SEED["running"], [[_h(6, **(dict(feels=12) | hour))]], CTX)
|
||
assert result.score <= (30 if hour.get("feels") == 3 else 0)
|
||
|
||
|
||
@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_activity_hours_never_change_any_gak_score(hour):
|
||
"""어느 각도 활동 시간대에 해당하는지로 점수나 0점 조건이 달라지지 않는다."""
|
||
windows = [[_h(7, **hour)]]
|
||
for code, defn in _SEED.items():
|
||
assert all(r["field"] != "time_matches" for r in defn.zero_rules), code
|
||
on, off = (evaluate(defn, windows, replace(CTX, time_matches=m, pm25=30)) for m in (True, False))
|
||
assert (on.score, on.zero_reason) == (off.score, off.zero_reason), code
|
||
|
||
|
||
_AXES = ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")
|
||
|
||
|
||
def _weights(code):
|
||
return {a: getattr(_SEED[code], f"weight_{a}") for a in _AXES if getattr(_SEED[code], f"weight_{a}")}
|
||
|
||
|
||
def test_no_gak_scores_activity_hours_as_a_factor():
|
||
assert [c for c, d in _SEED.items() if d.factor_rules["time"]["type"] == "fixed" and d.weight_time] == []
|
||
|
||
|
||
def test_gak_weights_are_5_percent_steps_that_sum_to_100():
|
||
for code in _SEED:
|
||
weights = _weights(code)
|
||
assert sum(weights.values()) == 100 and all(v % 5 == 0 for v in weights.values()), code
|
||
|
||
|
||
def test_every_gak_has_three_factors_except_the_two_umbrella_gak():
|
||
assert {c for c in _SEED if len(_weights(c)) < 3} == {"umbrella", "umbrella_lost"}
|
||
|
||
|
||
@pytest.mark.parametrize("code, expected", [
|
||
("umbrella", {"rain": 100}),
|
||
("umbrella_lost", {"rain": 100}),
|
||
("iced_hot", {"temp": 80, "rain": 10, "wind": 10}),
|
||
("pajeon", {"temp": 20, "rain": 65, "humidity": 15}),
|
||
("mood_song", {"temp": 30, "rain": 55, "humidity": 15}),
|
||
("thanks", {"temp": 50, "rain": 30, "wind": 20}),
|
||
("sunscreen", {"uv": 70, "sun": 15, "temp": 15}),
|
||
("walk", {"temp": 35, "rain": 25, "wind": 15, "humidity": 10, "air": 15}),
|
||
("running", {"temp": 40, "rain": 20, "wind": 10, "humidity": 15, "air": 15}),
|
||
("sentimental", {"temp": 40, "rain": 35, "wind": 15, "humidity": 10}),
|
||
("selfie", {"rain": 20, "wind": 15, "humidity": 35, "sun": 30}),
|
||
])
|
||
def test_gak_weights_after_removing_activity_hours(code, expected):
|
||
assert _weights(code) == expected
|
||
|
||
|
||
def test_umbrella_gak_use_the_rain_rules_the_owner_asked_for():
|
||
assert _SEED["umbrella"].factor_rules["rain"] == {"dir": "wet", "span": "rest_of_day", "now_base": 70}
|
||
lost = _SEED["umbrella_lost"]
|
||
assert lost.factor_rules["rain"] == {"dir": "dry", "span": "rest_of_day", "kind": "unused", "label": "우산 안 쓰는 시간"}
|
||
# 지난 시각(앞서 내린 비)은 보지 않는다. 지금과 앞으로만으로 점수를 내므로 0점 조건이 없다
|
||
assert lost.zero_rules == [] and lost.windows == [{"from": 9, "to": 22}]
|
||
|
||
|
||
@pytest.mark.parametrize("code, calm, lively", [
|
||
("iced_hot", dict(feels=8.0, prob=0), dict(feels=8.0, prob=0, wind=7.0)),
|
||
("thanks", dict(feels=0.0, wind=0.5), dict(feels=0.0, wind=7.0)),
|
||
("pajeon", dict(feels=15.0, prob=90, rain=RainType.RAIN, hum=40), dict(feels=15.0, prob=90, rain=RainType.RAIN, hum=90)),
|
||
("mood_song", dict(feels=15.0, prob=90, rain=RainType.RAIN, hum=40), dict(feels=15.0, prob=90, rain=RainType.RAIN, hum=90)),
|
||
("sunscreen", dict(feels=26.0, uv=6.0, sunshine_ratio=0.1), dict(feels=26.0, uv=6.0, sunshine_ratio=0.9)),
|
||
])
|
||
def test_added_factor_raises_the_score_in_the_direction_the_gak_means(code, calm, lively):
|
||
assert _seed_score(code, **lively) > _seed_score(code, **calm)
|
||
|
||
|
||
@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, wind=6.0), 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": "덜 추움"}}) == "덜 추움"
|
||
assert axis_label("rain", {"rain": {"dir": "dry", "label": "우산 안 쓰는 시간"}}) == "우산 안 쓰는 시간"
|
||
assert axis_label("rain", {"rain": {"dir": "dry"}}) == "비 안 옴"
|
||
|
||
|
||
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 _umbrella_defn():
|
||
"""우산각 방식: 요소는 비 하나. 지금 비가 오면 70점에서 시작해 남은 시각의 비 확률 평균으로 30점까지, 아니면 평균 × 100."""
|
||
return _defn(
|
||
weight_temp=0, weight_rain=100, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=0,
|
||
factor_rules=_defn().factor_rules | {"rain": {"dir": "wet", "span": "rest_of_day", "now_base": 70}}, zero_rules=[],
|
||
)
|
||
|
||
|
||
def _umbrella(probs, raining_now, at_now=True):
|
||
"""11시부터 시각마다 비 확률 probs. raining_now 면 첫 시각(지금)에 비가 오는 중."""
|
||
hours = [_h(11 + i, prob=p, rain=RainType.RAIN if i == 0 and raining_now else RainType.NONE) for i, p in enumerate(probs)]
|
||
return evaluate(_umbrella_defn(), [hours], replace(CTX, at_now=at_now))
|
||
|
||
|
||
def test_umbrella_is_100_only_when_raining_now_and_every_remaining_hour_is_certain():
|
||
assert _umbrella([100] * 13, raining_now=True).score == 100
|
||
assert _umbrella([100] * 12 + [0], raining_now=True).score == 98
|
||
|
||
|
||
@pytest.mark.parametrize("probs, score", [([100] + [0] * 12, 72), ([100] * 4 + [0] * 9, 79)])
|
||
def test_umbrella_raining_now_starts_at_70_and_adds_up_to_30_by_remaining_hours(probs, score):
|
||
assert _umbrella(probs, raining_now=True).score == score
|
||
|
||
|
||
def test_umbrella_raining_now_counts_current_hour_as_certain_even_if_its_forecast_is_low():
|
||
assert _umbrella([40] + [0] * 12, raining_now=True).score == 72
|
||
|
||
|
||
@pytest.mark.parametrize("probs, score", [([0] * 7 + [100] * 6, 46), ([30] * 13, 30), ([100] * 13, 100), ([0] * 13, 0)])
|
||
def test_umbrella_not_raining_now_is_the_time_weighted_probability_out_of_100(probs, score):
|
||
assert _umbrella(probs, raining_now=False).score == score
|
||
|
||
|
||
def test_umbrella_has_no_raining_now_bonus_unless_the_evaluation_starts_now():
|
||
"""다른 구간·내일 칸은 '지금'이 없다. 첫 시각에 비가 와도 평균 × 100 만."""
|
||
assert _umbrella([100] + [0] * 12, raining_now=True, at_now=False).score == 8
|
||
|
||
|
||
def test_umbrella_note_says_it_counts_the_rest_of_the_day():
|
||
assert "남은 시간" in _umbrella([100] * 13, raining_now=True).notes["rain"]
|
||
assert "지금 비" in _umbrella([100] * 13, raining_now=True).notes["rain"]
|
||
assert "지금 비" not in _umbrella([30] * 13, raining_now=False).notes["rain"]
|
||
|
||
|
||
def test_umbrella_estimate_averages_the_window_hours_of_the_mid_forecast():
|
||
"""중기예보 날: 오전(~11시) 비 100%, 오후 0% 이면 6~23시 중 6시간 → 33점."""
|
||
r = estimate(_umbrella_defn(), _fc(am=100, pm=0), [list(range(6, 24))], CTX)
|
||
assert r.score == 33
|
||
|
||
|
||
def _lost(probs, raining_now, at_now=True):
|
||
"""우산분실각 방식: 우산을 챙겼을 정도(지금 비가 오면 100%, 아니면 남은 시각 중 가장 높은 비 확률) × 비가 안 오는 시간의 비율."""
|
||
defn = _defn(
|
||
weight_temp=0, weight_rain=100, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=0,
|
||
factor_rules=_defn().factor_rules | {"rain": {"dir": "dry", "span": "rest_of_day", "kind": "unused"}}, zero_rules=[],
|
||
)
|
||
hours = [_h(11 + i, prob=p, rain=RainType.RAIN if i == 0 and raining_now else RainType.NONE) for i, p in enumerate(probs)]
|
||
return evaluate(defn, [hours], replace(CTX, at_now=at_now))
|
||
|
||
|
||
@pytest.mark.parametrize("probs, raining_now, score", [
|
||
([100] + [0] * 12, True, 92), # 지금 비 오고 곧 그침: 들고 나온 우산을 12/13 시간 안 씀
|
||
([0] * 7 + [100] * 6, False, 54), # 지금은 안 오는데 저녁에 비: 챙긴 우산을 7/13 시간 들고만 다님
|
||
([0] * 7 + [80] * 6, False, 50), # 저녁 비 80%: 챙겼을 정도 80% × 안 쓰는 시간 63%
|
||
([60] * 13, True, 37), # 지금 비 오고 계속 60%
|
||
([30] * 13, False, 21), # 하루 종일 30%: 챙겼을 정도 30% × 안 쓰는 시간 70%
|
||
([100] * 13, True, 0), # 하루 종일 비: 계속 쓰니 두고 올 일이 없음
|
||
([0] * 13, False, 0), # 비 소식 없음: 들고 나온 우산이 없음
|
||
])
|
||
def test_umbrella_lost_is_how_much_a_carried_umbrella_goes_unused(probs, raining_now, score):
|
||
assert _lost(probs, raining_now).score == score
|
||
|
||
|
||
def test_umbrella_lost_counts_raining_now_only_when_the_evaluation_starts_now():
|
||
"""지금 비가 오면 우산은 확실히 들고 있다(100%). 다른 구간·내일 칸은 '지금'이 없어 예보 확률만큼만."""
|
||
assert _lost([40] + [0] * 12, raining_now=True).score == 92
|
||
assert _lost([40] + [0] * 12, raining_now=True, at_now=False).score == 39
|
||
|
||
|
||
def test_umbrella_lost_note_shows_both_parts():
|
||
note = _lost([0] * 7 + [80] * 6, raining_now=False).notes["rain"]
|
||
assert "80%" in note and "63%" in note and "지금 비" not in note
|
||
assert "지금 비" in _lost([100] + [0] * 12, raining_now=True).notes["rain"]
|
||
|
||
|
||
def test_umbrella_lost_estimate_uses_the_mid_forecast_hours():
|
||
"""중기예보 날 9~21시: 오전(9~11시) 비 100%, 오후 0% → 챙겼을 정도 100% × 안 쓰는 시간 10/13 → 77점."""
|
||
defn = _defn(
|
||
weight_temp=0, weight_rain=100, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=0,
|
||
factor_rules=_defn().factor_rules | {"rain": {"dir": "dry", "span": "rest_of_day", "kind": "unused"}}, zero_rules=[],
|
||
)
|
||
assert estimate(defn, _fc(am=100, pm=0), [list(range(9, 22))], CTX).score == 77
|
||
|
||
|
||
def test_umbrella_lost_seed_no_longer_scores_zero_while_it_rains():
|
||
"""운영에서 본 문제: 비가 오는 날은 하루 종일 0점이었다. 지금 비가 오고 저녁에 그치면 점수가 난다."""
|
||
hours = [_h(h, prob=100 if h < 18 else 10, rain=RainType.RAIN if h < 18 else RainType.NONE) for h in range(16, 24)]
|
||
r = evaluate(_SEED["umbrella_lost"], [hours], replace(CTX, at_now=True))
|
||
assert r.score == 68 and r.zero_reason is None # 16·17시 비, 18~23시 10%: 100 − (100×2 + 10×6) ÷ 8
|
||
|
||
|
||
def test_single_factor_gak_is_not_pulled_down_by_its_own_weakest_factor():
|
||
"""요소가 하나면 '가장 낮은 요소로 깎기'를 하지 않는다. 안 그러면 72점이 67점이 된다."""
|
||
r = _umbrella([100] + [0] * 12, raining_now=True)
|
||
assert r.score == r.factors["rain"] == 72
|
||
|
||
|
||
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°")
|