feat: 지금 날씨를 초단기실황 관측값으로, 각 점수에서 시간대 알맞음 제거·우산각 계산식 변경

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

No files matched your search

+8
View File
@@ -73,6 +73,14 @@ def _no_seoul_crawl(monkeypatch):
monkeypatch.setattr(week_service, "fetch_seoul_festivals", lambda *a: _async([]))
@pytest.fixture(autouse=True)
def _no_ncst_call(monkeypatch):
"""초단기실황은 실제 기상청을 부르지 않게 기본으로 '값 없음'으로 막는다 (실황을 쓰는 테스트는 자기 값으로 바꾼다)."""
import services.weather_service as weather_service
monkeypatch.setattr(weather_service, "fetch_ncst", lambda *a: _async([]))
@pytest.fixture
def no_bot_comments(monkeypatch):
"""사람이 단 댓글·좋아요만 세는 테스트용: 포스트를 만들 때 캐릭터 댓글을 달지 않는다 (캐릭터 댓글은 test_bot_comment)."""
+65
View File
@@ -133,6 +133,71 @@ def test_current_slot_skips_passed_hours():
assert with_now["morning"].score == without["morning"].score
def _rain_at(hours: set[int]):
start = kst_midnight(DAY)
return {
start + timedelta(hours=h): SimpleNamespace(
forecast_at=start + timedelta(hours=h), feels_c=21.0, rain_type=RainType.RAIN.value if h in hours else RainType.NONE.value,
rain_prob=100 if h in hours else 0, wind_ms=1.0, humidity=50, sky=Sky.CLEAR.value,
)
for h in range(0, 30)
}
def _umbrella_defn():
defn = _defn([{"from": 6, "to": 24}])
defn.weight_temp, defn.weight_rain = 0, 100
defn.factor_rules = defn.factor_rules | {"rain": {"dir": "wet", "span": "rest_of_day", "now_base": 70}}
return defn
def test_umbrella_current_slot_counts_the_rest_of_the_day_not_just_the_slot():
"""11:30 낮 구간(11~15시): 16~23시 비가 점수에 들어간다. 지금은 안 오니 8/13시간 → 62점."""
now = datetime(2026, 10, 8, 11, 30, tzinfo=KST)
parts = slot_results(_umbrella_defn(), DAY, REGION, _rain_at(set(range(16, 24))), {}, CTX, SUNSET, now)
assert parts["day"].score == 62
def test_umbrella_raining_now_and_all_remaining_hours_rain_is_100():
now = datetime(2026, 10, 8, 13, 30, tzinfo=KST)
parts = slot_results(_umbrella_defn(), DAY, REGION, _rain_at(set(range(13, 24))), {}, CTX, SUNSET, now)
assert parts["day"].score == 100
def test_umbrella_raining_now_needs_the_current_hours_own_forecast():
"""13시 예보 행이 없고 14시에만 비가 오면 '지금 비'가 아니다. 다음 시각의 비를 지금으로 읽으면 안 된다 → 남은 10시간 중 1시간, 10점."""
now = datetime(2026, 10, 8, 13, 30, tzinfo=KST)
by_at = {k: v for k, v in _rain_at({14}).items() if k != kst_midnight(DAY) + timedelta(hours=13)}
parts = slot_results(_umbrella_defn(), DAY, REGION, by_at, {}, CTX, SUNSET, now)
assert parts["day"].score == 10
def test_umbrella_raining_now_comes_from_the_observed_weather():
"""예보는 지금 비가 없어도 실황이 비를 관측했으면 '지금 비'다: 70 + 30 × 평균 → 81 (실황 없이는 평균 30 → 30)."""
from common.enums import RainType
from services.weather_service import Observed, with_observed
now = datetime(2026, 10, 8, 13, 30, tzinfo=KST)
by_at = {r.forecast_at: r for r in (_hourly(h) for h in range(5, 30))}
observed = Observed(at=kst_midnight(DAY) + timedelta(hours=13), rain_type=RainType.RAIN, rain_mm=0.3, temp_c=21.0, humidity=60, wind_ms=1.0)
dry = slot_results(_umbrella_defn(), DAY, REGION, by_at, {}, CTX, SUNSET, now)["day"].score
wet = slot_results(_umbrella_defn(), DAY, REGION, with_observed(by_at, observed), {}, CTX, SUNSET, now)["day"].score
assert (dry, wet) == (30, 81)
def test_umbrella_other_slots_have_no_raining_now_bonus():
"""13:30 에 낮 구간이 지금. 저녁 구간(16시~)은 16시에만 비가 와도 지금 비 보너스 없이 평균 × 100 → 약 12점."""
now = datetime(2026, 10, 8, 13, 30, tzinfo=KST)
parts = slot_results(_umbrella_defn(), DAY, REGION, _rain_at({16}), {}, CTX, SUNSET, now)
assert 10 <= parts["evening"].score <= 13
def test_umbrella_rest_of_day_stops_at_midnight():
"""밤 구간 시각 24~28시는 다음 날 새벽이라 '남은 하루'에 넣지 않는다."""
parts = slot_results(_umbrella_defn(), DAY, REGION, _rain_at(set(range(24, 29))), {}, CTX, SUNSET)
assert parts["night"].score == 0
def test_current_slot_keeps_last_hour():
"""구간 끝 한 시간만 남아도 지금 구간 점수를 낸다."""
now = datetime(2026, 10, 8, 15, 10, tzinfo=KST)
+48
View File
@@ -5,6 +5,7 @@ import pytest
from httpx import ASGITransport, AsyncClient
import services.air_service as air_service
import services.index_service as index_service
import services.warning_service as warning_service
import services.weather_service as weather_service
from common.database.db_session_manager import DB_SESSION_MNG
@@ -91,6 +92,53 @@ async def test_index_list_ranks_every_gak_with_today_tomorrow_weekend_trend(fake
assert 0 <= body["weather_score"] <= 100
@pytest.mark.anyio
async def test_index_list_asks_for_the_observed_weather_once(fakes, monkeypatch):
calls = []
async def fake_ncst(client, nx, ny, base):
calls.append(base)
return []
monkeypatch.setattr(weather_service, "fetch_ncst", fake_ncst)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
assert (await client.get("/v1/index/list", params={"region": REGION})).json()["result"]["success"] is True
assert len(calls) == 1
@pytest.mark.anyio
async def test_index_scores_are_recomputed_once_the_new_hours_observation_is_out(fakes, monkeypatch):
"""14:05 에 계산한 점수는 14:08 에 그대로 쓰고, 14시 실황이 나오는 14:10 이후엔 다시 계산한다."""
day = kst_midnight(now_kst().date())
clock = [day + timedelta(hours=14, minutes=5)]
computed = []
real_day_result = index_service.day_result
def counting(*a, **k):
computed.append(1)
return real_day_result(*a, **k)
async def observed(*_a):
return [{"category": c, "obsrValue": v} for c, v in {"PTY": "0", "REH": "50", "RN1": "0", "T1H": "21", "WSD": "1.5"}.items()]
monkeypatch.setattr(index_service, "now_kst", lambda: clock[0])
monkeypatch.setattr(index_service, "day_result", counting)
monkeypatch.setattr(weather_service, "fetch_ncst", observed)
monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{
"stationName": "신촌동", "pm25Value": "10", "pm10Value": "20", "pm25Grade": "1", "pm10Grade": "1", "dataTime": f"{day:%Y-%m-%d} 14:00",
}]))
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
await client.get("/v1/index/list", params={"region": REGION})
first = len(computed)
assert first > 0
clock[0] = day + timedelta(hours=14, minutes=8)
await client.get("/v1/index/list", params={"region": REGION})
assert len(computed) == first
clock[0] = day + timedelta(hours=14, minutes=12)
await client.get("/v1/index/list", params={"region": REGION})
assert len(computed) > first
@pytest.mark.anyio
async def test_index_list_filters_core_to_gak_in_season_now(fakes):
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
+123 -21
View File
@@ -327,9 +327,11 @@ def test_running_clear_cool_morning_and_evening_stay_good(hour, feels):
@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
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)])
@@ -351,29 +353,73 @@ def test_running_wind_warning_is_zero():
@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))
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("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)
def test_activity_hours_never_change_any_gak_score(hour):
"""어느 각도 활동 시간대에 해당하는지로 점수나 0점 조건이 달라지지 않는다."""
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
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}
assert _SEED["umbrella_lost"].factor_rules["rain"]["dir"] == "dry"
@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", [
@@ -416,7 +462,7 @@ def test_seasonal_gak_good_day_high_bad_day_low(code, good, bad):
("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)),
("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)),
@@ -473,6 +519,62 @@ def test_umbrella_lost_needs_rain_that_stopped():
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 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
+5 -4
View File
@@ -89,17 +89,18 @@ def test_running_slot_rain_outside_activity_hours_still_zero():
assert results["night"].score >= 80
def test_running_slots_lower_day_and_late_night_but_keep_activity_hours():
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
assert results["day"].score <= 50 and results["early"].score <= 50
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"].factors["time"] == 0 and late["night"].score <= 50
assert late["night"].score >= 80
def test_running_muggy_morning_does_not_exceed_original_weather_score():
+36 -2
View File
@@ -1,8 +1,8 @@
from datetime import datetime
from common.enums import RainType, Sky
from common.utils.kma_time import KST, latest_ultra_base, latest_vilage_base
from services.external.kma import parse_amount, parse_vilage
from common.utils.kma_time import KST, latest_ncst_base, latest_ultra_base, latest_vilage_base
from services.external.kma import parse_amount, parse_ncst, parse_vilage
def _kst(y, mo, d, h, mi=0):
@@ -23,6 +23,40 @@ def test_latest_ultra_base_available_from_45_minutes():
assert latest_ultra_base(_kst(2026, 10, 1, 10, 45)) == _kst(2026, 10, 1, 10, 30)
def test_latest_ncst_base_available_from_10_minutes():
assert latest_ncst_base(_kst(2026, 10, 1, 10, 9)) == _kst(2026, 10, 1, 9)
assert latest_ncst_base(_kst(2026, 10, 1, 10, 10)) == _kst(2026, 10, 1, 10)
assert latest_ncst_base(_kst(2026, 10, 1, 0, 5)) == _kst(2026, 9, 30, 23)
# 2026-11-23 14시 서울 실황 응답 그대로
_NCST = {"PTY": "1", "REH": "78", "RN1": "0.3", "T1H": "9.8", "UUU": "1.1", "VEC": "194", "VVV": "4.4", "WSD": "4.5"}
def _ncst(**override):
return [{"baseDate": "20261123", "baseTime": "1400", "category": c, "nx": 60, "ny": 127, "obsrValue": v} for c, v in (_NCST | override).items()]
def test_parse_ncst_reads_what_is_observed_now():
assert parse_ncst(_ncst()) == {"rain_type": RainType.RAIN, "rain_mm": 0.3, "temp_c": 9.8, "humidity": 78, "wind_ms": 4.5}
def test_parse_ncst_reads_no_rain_and_drizzle_codes():
assert parse_ncst(_ncst(PTY="0", RN1="0"))["rain_type"] is RainType.NONE
assert [parse_ncst(_ncst(PTY=c))["rain_type"] for c in ("5", "6", "7")] == [RainType.RAIN, RainType.SLEET, RainType.SNOW]
def test_parse_ncst_without_every_value_is_nothing():
assert parse_ncst([]) is None
assert parse_ncst([i for i in _ncst() if i["category"] != "T1H"]) is None
def test_parse_ncst_treats_900_or_more_as_missing():
"""가이드: +900 이상, -900 이하 값은 결측."""
for category, value in (("T1H", "-999"), ("WSD", "900"), ("REH", "-999"), ("RN1", "-999")):
assert parse_ncst(_ncst(**{category: value})) is None, category
def test_parse_amount_text():
assert parse_amount("강수없음") == 0
assert parse_amount("1mm 미만") == 0.5
+95
View File
@@ -0,0 +1,95 @@
from datetime import datetime, timedelta
from types import SimpleNamespace
import pytest
import services.weather_service as weather_service
from common.database.model.models import WeatherHourly
from common.enums import RainType, Sky
from common.utils.kma_time import KST
from services.calc.weather_calc import discomfort_index, feels_like_c
from services.external.data_go_kr import DataGoKrRequestFailed
from services.weather_service import Observed, observed_now, with_observed
REGION = SimpleNamespace(code="1", nx=60, ny=127)
def _at(h: int, mi: int = 0) -> datetime:
return datetime(2026, 10, 8, 0, 0, tzinfo=KST) + timedelta(hours=h, minutes=mi)
def _hourly(h: int) -> WeatherHourly:
return WeatherHourly(
region_code="1", forecast_at=_at(h), temp_c=21, feels_c=21, discomfort_index=60, sky=Sky.CLOUDY.value, rain_type=RainType.NONE.value,
rain_prob=30, rain_mm=0, humidity=60, wind_ms=1.0, issued_at=_at(h),
)
_OBS = Observed(at=_at(14), rain_type=RainType.RAIN, rain_mm=0.3, temp_c=9.8, humidity=78, wind_ms=4.5)
def test_observed_replaces_the_observed_hour_with_what_is_measured():
rows = {r.forecast_at: r for r in (_hourly(13), _hourly(14), _hourly(15))}
r = with_observed(rows, _OBS)[_at(14)]
assert (r.rain_type, float(r.rain_mm), float(r.temp_c), r.humidity, float(r.wind_ms)) == (RainType.RAIN.value, 0.3, 9.8, 78, 4.5)
assert float(r.feels_c) == feels_like_c(9.8, 78, 4.5, 10) and r.discomfort_index == discomfort_index(9.8, 78)
def test_observed_keeps_forecast_only_values_and_other_hours():
rows = {r.forecast_at: r for r in (_hourly(13), _hourly(14), _hourly(15))}
out = with_observed(rows, _OBS)
assert (out[_at(14)].rain_prob, out[_at(14)].sky) == (30, Sky.CLOUDY.value)
assert out[_at(13)] is rows[_at(13)] and out[_at(15)] is rows[_at(15)]
assert rows[_at(14)].rain_type == RainType.NONE.value # 원본은 그대로
def test_observed_does_nothing_without_an_observation_or_the_hours_row():
rows = {_at(13): _hourly(13)}
assert with_observed(rows, None) == rows
assert with_observed(rows, _OBS) == rows
_ITEMS = [{"category": c, "obsrValue": v} for c, v in {"PTY": "1", "REH": "78", "RN1": "0.3", "T1H": "9.8", "WSD": "4.5"}.items()]
@pytest.fixture
def ncst_calls(monkeypatch):
calls = []
async def fetch(client, nx, ny, base):
calls.append(base)
return _ITEMS
monkeypatch.setattr(weather_service, "fetch_ncst", fetch)
return calls
@pytest.mark.anyio
async def test_observed_now_reads_the_latest_hour_and_keeps_it_for_that_hour(ncst_calls):
first = await observed_now(REGION, _at(14, 20))
again = await observed_now(REGION, _at(14, 50))
assert first == again == _OBS
assert ncst_calls == [_at(14)]
@pytest.mark.anyio
async def test_observed_now_asks_again_when_a_new_hour_is_out(ncst_calls):
await observed_now(REGION, _at(14, 20))
await observed_now(REGION, _at(15, 5)) # 15시 실황은 15:10부터라 아직 14시 것
assert ncst_calls == [_at(14)]
await observed_now(REGION, _at(15, 10))
assert ncst_calls == [_at(14), _at(15)]
@pytest.mark.anyio
async def test_observed_now_is_nothing_when_the_api_fails_or_answers_with_gaps(monkeypatch):
async def down(*_a):
raise DataGoKrRequestFailed("down")
async def gaps(*_a):
return [i for i in _ITEMS if i["category"] != "T1H"]
monkeypatch.setattr(weather_service, "fetch_ncst", down)
assert await observed_now(REGION, _at(14, 20)) is None
monkeypatch.setattr(weather_service, "fetch_ncst", gaps)
assert await observed_now(REGION, _at(14, 20)) is None
+1
View File
@@ -16,6 +16,7 @@ ENDPOINTS = ["/v1/feed", "/v1/weather/today", "/v1/weather/now", "/v1/sky", "/v1
SOURCES = {
"vilage": (weather_service, "fetch_vilage", DataGoKrRequestFailed),
"ultra": (weather_service, "fetch_ultra", DataGoKrRequestFailed),
"ncst": (weather_service, "fetch_ncst", DataGoKrRequestFailed),
"air": (air_service, "fetch_realtime", DataGoKrRequestFailed),
"warning": (warning_service, "fetch_warning_events", DataGoKrRequestFailed),
"clouds": (sky_service, "fetch_clouds", OpenMeteoRequestFailed),
+25
View File
@@ -67,6 +67,31 @@ async def test_today_fetches_stores_and_returns_8_slots(monkeypatch, clean_regio
assert len(calls) == 2
@pytest.mark.anyio
async def test_today_current_hour_shows_the_observed_weather(monkeypatch, clean_region):
"""실황이 있으면 지금이 든 칸은 지금 시각 예보(맑음·18도) 대신 관측한 비·기온을 보인다. 다른 칸은 예보 그대로."""
now = kst_midnight(now_kst().date()) + timedelta(hours=14, minutes=20)
observed = [{"category": c, "obsrValue": v} for c, v in {"PTY": "1", "REH": "78", "RN1": "0.3", "T1H": "9.8", "WSD": "4.5"}.items()]
async def fake_vilage(client, nx, ny, base):
return _fake_items(base)
async def no_ultra(*_a):
return []
async def fake_ncst(*_a):
return observed
monkeypatch.setattr(weather_service, "now_kst", lambda: now)
monkeypatch.setattr(weather_service, "fetch_vilage", fake_vilage)
monkeypatch.setattr(weather_service, "fetch_ultra", no_ultra)
monkeypatch.setattr(weather_service, "fetch_ncst", fake_ncst)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
slots = (await client.get("/v1/weather/today", params={"region": REGION})).json()["slots"]
assert (slots[4]["label"], slots[4]["temp_c"], slots[4]["icon"]) == ("12시", 9.8, "rain")
assert all(s["temp_c"] == 18 for i, s in enumerate(slots) if i != 4)
@pytest.mark.anyio
async def test_today_second_call_uses_db_without_fetching(monkeypatch, clean_region):
calls = []