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 def _line(**kw): from services.calc.index_calc import Hour, summary_line base = dict(hour=16, feels_c=11.0, rain_type=RainType.NONE, rain_prob=60, wind_ms=1.5, humidity=90, sky=Sky.CLOUDY) return summary_line(Hour(**{**base, **kw})) def test_observed_hour_line_says_it_is_raining_instead_of_a_probability(): """실황은 관측이라 확률이 없다. 지금 비가 오면 '비 60%' 가 아니라 오는 중이라고 쓴다.""" assert _line(observed=True, rain_type=RainType.RAIN) == "오후 4시 11°, 비 오는 중" assert _line(observed=True, rain_type=RainType.SHOWER) == "오후 4시 11°, 비 오는 중" assert _line(observed=True, rain_type=RainType.SNOW) == "오후 4시 11°, 눈 오는 중" assert _line(observed=True, rain_type=RainType.SLEET) == "오후 4시 11°, 진눈깨비 오는 중" def test_observed_hour_line_without_rain_never_shows_a_probability(): """관측으로 비가 없으면 예보 확률이 60% 여도 확률을 쓰지 않는다.""" assert _line(observed=True) == "오후 4시 11°, 바람 살랑" assert _line(observed=True, wind_ms=None) == "오후 4시 11°, 흐림" def test_forecast_hour_line_keeps_the_probability(): assert _line() == "오후 4시 11°, 비 60%" assert _line(rain_type=RainType.RAIN) == "오후 4시 11°, 비 60%" def test_only_the_observed_row_is_marked_observed(): from services.index_service import _hour rows = {r.forecast_at: r for r in (_hourly(13), _hourly(14))} out = with_observed(rows, _OBS) assert _hour(out[_at(14)]).observed is True and _hour(out[_at(13)]).observed is False def test_current_slot_line_of_a_gak_uses_the_observed_rain(): from datetime import date from services.calc.index_calc import Context from services.index_service import slot_results day = date(2026, 10, 8) defn = SimpleNamespace( weight_temp=50, weight_rain=50, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=0, factor_rules={"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "ignore"}, "humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100}}, zero_rules=[], windows=[{"from": 9, "to": 20}], ) ctx = Context(day=day, is_holiday=False, pm25=10, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0) by_at = with_observed({r.forecast_at: r for r in (_hourly(h) for h in range(5, 24))}, _OBS) parts = slot_results(defn, day, SimpleNamespace(lat=37.5, lon=127.0), by_at, {}, ctx, _at(18), _at(14, 20)) assert parts["day"].summary == "오후 2시 8°, 비 오는 중" _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