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, 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_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_caps_score(): r = outing(_day(prob=70)) assert r.score <= 30 and r.capped assert outing([_h(10, prob=30, rain=RainType.RAIN)] + _day()[1:]).score <= 30 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 outing_estimate(_fc(pm=60)).score <= 30 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("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 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