feat(weather): KMA forecasts for a later day (days_ahead, days)
getWeather takes days_ahead (days from today, up to 10) and days (a span, 2 for a weekend). Inside Korea with the app's KMA key: 단기예보 for today to 3 days ahead (morning and afternoon weather, lowest and highest, highest chance of rain), then 중기기온 and 중기육상 for the nearest of 32 KMA cities and its region. Days KMA does not give, and every KMA failure, come from open-meteo's daily forecast. days_ahead 0 with more days gives the weather now, then each day. Eval: evals/test_weather_forecast_days.py. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,6 +3,7 @@
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch
|
||||
import requests
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from src.jarvis.tools.builtin.weather import (
|
||||
WeatherTool,
|
||||
@@ -824,3 +825,220 @@ class TestKmaWeather:
|
||||
|
||||
assert "흐림" in result.reply_text or "구름 많음" in result.reply_text
|
||||
assert any(p.get("authKey") == self.KEY for u, p in calls if "apihub.kma.go.kr" in u)
|
||||
|
||||
|
||||
class TestForecast:
|
||||
"""A later day (days_ahead/days): KMA 단기예보 and 중기예보 inside Korea, else open-meteo's daily forecast."""
|
||||
|
||||
KEY = "kma-test-key-123"
|
||||
# Wednesday 18 November 2026, 10:20 KST.
|
||||
NOW = datetime(2026, 11, 18, 10, 20, tzinfo=timezone(timedelta(hours=9)))
|
||||
|
||||
def setup_method(self):
|
||||
self.tool = WeatherTool()
|
||||
self.context = Mock(spec=ToolContext)
|
||||
self.context.user_print = Mock()
|
||||
self.context.cfg = Mock()
|
||||
self.context.cfg.location_name = None
|
||||
self.context.redacted_text = ""
|
||||
|
||||
@staticmethod
|
||||
def _ok(payload):
|
||||
r = Mock(status_code=200, raise_for_status=Mock())
|
||||
r.json.return_value = payload
|
||||
return r
|
||||
|
||||
def _kma(self, items):
|
||||
return self._ok({"response": {"header": {"resultCode": "00"}, "body": {"items": {"item": items}}}})
|
||||
|
||||
@staticmethod
|
||||
def _vilage_items():
|
||||
"""단기예보: tomorrow (19th) clear in the morning, rain in the afternoon; Saturday (21st) cloudy."""
|
||||
items = []
|
||||
for date, sky_am, sky_pm, pty_pm, pops in [
|
||||
("20261119", "1", "4", "1", ("10", "60")),
|
||||
("20261120", "3", "3", "0", ("20", "20")),
|
||||
("20261121", "4", "4", "0", ("30", "30")),
|
||||
]:
|
||||
for hour in range(0, 24):
|
||||
t = f"{hour:02d}00"
|
||||
am = hour < 12
|
||||
items += [
|
||||
{"category": "SKY", "fcstDate": date, "fcstTime": t, "fcstValue": sky_am if am else sky_pm},
|
||||
{"category": "PTY", "fcstDate": date, "fcstTime": t, "fcstValue": "0" if am else pty_pm},
|
||||
{"category": "POP", "fcstDate": date, "fcstTime": t, "fcstValue": pops[0] if am else pops[1]},
|
||||
{"category": "TMP", "fcstDate": date, "fcstTime": t, "fcstValue": str(hour % 7)},
|
||||
]
|
||||
items += [{"category": "TMN", "fcstDate": date, "fcstTime": "0600", "fcstValue": "-1.0"},
|
||||
{"category": "TMX", "fcstDate": date, "fcstTime": "1500", "fcstValue": "4.0"}]
|
||||
return items
|
||||
|
||||
def _routes(self, country_code="KR", lat=37.566, lon=126.9784, calls=None, fail_kma=False):
|
||||
def get(url, *a, **k):
|
||||
params = k.get("params") or {}
|
||||
if calls is not None:
|
||||
calls.append((url, params))
|
||||
if "geocoding" in url:
|
||||
return self._ok({"results": [{"latitude": lat, "longitude": lon, "name": "Seoul",
|
||||
"country_code": country_code}]})
|
||||
if "apihub.kma.go.kr" in url:
|
||||
if fail_kma:
|
||||
raise requests.exceptions.Timeout(f"timed out: {url}?authKey={self.KEY}")
|
||||
if "getVilageFcst" in url:
|
||||
return self._kma(self._vilage_items())
|
||||
if "getMidTa" in url:
|
||||
return self._kma([{"regId": params["regId"], "taMin4": -4, "taMax4": 5,
|
||||
"taMin5": -2, "taMax5": 7, "taMin10": 2, "taMax10": 10}])
|
||||
if "getMidLandFcst" in url:
|
||||
return self._kma([{"regId": params["regId"], "wf4Am": "맑음", "wf4Pm": "구름많음",
|
||||
"rnSt4Am": 10, "rnSt4Pm": 20, "wf5Am": "흐림", "wf5Pm": "흐리고 비",
|
||||
"rnSt5Am": 30, "rnSt5Pm": 60, "wf10": "맑음", "rnSt10": 10}])
|
||||
raise AssertionError(url)
|
||||
assert "api.open-meteo.com/v1/forecast" in url, url
|
||||
return self._ok({"current": {"temperature_2m": 11.0, "weather_code": 0}, "daily": {
|
||||
"time": [f"2026-11-{d}" for d in range(18, 29)],
|
||||
"weather_code": [0, 61, 3, 2, 0, 0, 0, 0, 0, 0, 0],
|
||||
"temperature_2m_min": [1.2, 2.6, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
"temperature_2m_max": [9.0, 11.4, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
"precipitation_probability_max": [0, 80, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||
}})
|
||||
return get
|
||||
|
||||
def _run(self, args, monkeypatch, key=True, now=None, **routes):
|
||||
if key:
|
||||
monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY)
|
||||
else:
|
||||
monkeypatch.delenv("JARVIS_KMA_API_KEY", raising=False)
|
||||
calls = []
|
||||
with patch('requests.get', side_effect=self._routes(calls=calls, **routes)), \
|
||||
patch('src.jarvis.tools.builtin.weather._now', return_value=now or self.NOW):
|
||||
result = self.tool.run({"location": "Seoul", **args}, self.context)
|
||||
return result, calls
|
||||
|
||||
def test_the_schema_offers_a_later_day_and_a_span_of_days(self):
|
||||
props = self.tool.inputSchema["properties"]
|
||||
assert props["days_ahead"]["type"] == "integer" and props["days"]["type"] == "integer"
|
||||
assert self.tool.inputSchema["required"] == []
|
||||
|
||||
def test_tomorrow_in_korea_comes_from_the_kma_short_term_forecast(self, monkeypatch):
|
||||
result, calls = self._run({"days_ahead": 1}, monkeypatch)
|
||||
|
||||
assert result.success is True
|
||||
text = result.reply_text
|
||||
assert text.startswith("내일(11월 19일 목요일) Seoul 날씨는")
|
||||
assert "오전 맑음" in text and "오후 비" in text
|
||||
assert "최저 -1도" in text and "최고 4도" in text and "강수확률 60%" in text
|
||||
assert not any("open-meteo.com/v1/forecast" in u for u, _ in calls)
|
||||
vilage = [p for u, p in calls if "getVilageFcst" in u]
|
||||
assert len(vilage) == 1 and vilage[0]["authKey"] == self.KEY
|
||||
assert (vilage[0]["nx"], vilage[0]["ny"]) == (60, 127)
|
||||
assert (vilage[0]["base_date"], vilage[0]["base_time"]) == ("20261118", "0800")
|
||||
assert not any("MidFcstInfoService" in u for u, _ in calls)
|
||||
|
||||
def test_five_days_ahead_in_korea_comes_from_the_kma_mid_term_forecast(self, monkeypatch):
|
||||
result, calls = self._run({"days_ahead": 5}, monkeypatch)
|
||||
|
||||
text = result.reply_text
|
||||
assert text.startswith("11월 23일 월요일 Seoul 날씨는")
|
||||
assert "오전 흐림" in text and "오후 흐리고 비" in text
|
||||
assert "최저 -2도" in text and "최고 7도" in text and "강수확률 60%" in text
|
||||
mid = {u.rsplit("/", 1)[-1]: p for u, p in calls if "MidFcstInfoService" in u}
|
||||
assert mid["getMidTa"]["regId"] == "11B10101" and mid["getMidLandFcst"]["regId"] == "11B00000"
|
||||
assert mid["getMidTa"]["tmFc"] == "202611180600" and mid["getMidTa"]["authKey"] == self.KEY
|
||||
assert not any("getVilageFcst" in u for u, _ in calls)
|
||||
|
||||
def test_the_weekend_spans_the_short_and_mid_term_forecasts(self, monkeypatch):
|
||||
result, _ = self._run({"days_ahead": 3, "days": 2}, monkeypatch)
|
||||
|
||||
lines = result.reply_text.split("\n")
|
||||
assert len(lines) == 2
|
||||
assert lines[0].startswith("11월 21일 토요일") and "흐림" in lines[0] and "강수확률 30%" in lines[0]
|
||||
assert lines[1].startswith("11월 22일 일요일") and "오전 맑음" in lines[1] and "오후 구름많음" in lines[1]
|
||||
assert "최저 -4도" in lines[1] and "최고 5도" in lines[1]
|
||||
|
||||
def test_the_same_weather_all_day_is_said_once(self, monkeypatch):
|
||||
result, _ = self._run({"days_ahead": 2}, monkeypatch)
|
||||
|
||||
assert result.reply_text.startswith("모레(11월 20일 금요일) Seoul 날씨는 구름 많음,")
|
||||
assert "오전" not in result.reply_text
|
||||
|
||||
@pytest.mark.parametrize("lat,lon,city,region", [
|
||||
(35.1796, 129.0756, "11H20201", "11H20000"), # 부산
|
||||
(33.4996, 126.5312, "11G00201", "11G00000"), # 제주
|
||||
(35.9676, 126.7369, "21F10501", "11F10000"), # 군산
|
||||
(37.7519, 128.8761, "11D20501", "11D20000"), # 강릉
|
||||
])
|
||||
def test_the_mid_term_forecast_is_for_the_nearest_kma_city_and_its_region(
|
||||
self, lat, lon, city, region, monkeypatch):
|
||||
_, calls = self._run({"days_ahead": 6}, monkeypatch, lat=lat, lon=lon)
|
||||
|
||||
mid = {u.rsplit("/", 1)[-1]: p for u, p in calls if "MidFcstInfoService" in u}
|
||||
assert mid["getMidTa"]["regId"] == city and mid["getMidLandFcst"]["regId"] == region
|
||||
|
||||
@pytest.mark.parametrize("now,vilage,tmfc", [
|
||||
(datetime(2026, 11, 18, 1, 50), ("20261117", "2300"), "202611171800"),
|
||||
(datetime(2026, 11, 18, 2, 20), ("20261118", "0200"), "202611171800"),
|
||||
(datetime(2026, 11, 18, 6, 40), ("20261118", "0500"), "202611180600"),
|
||||
(datetime(2026, 11, 18, 23, 59), ("20261118", "2300"), "202611181800"),
|
||||
])
|
||||
def test_kma_forecasts_are_the_latest_published(self, now, vilage, tmfc, monkeypatch):
|
||||
"""단기예보 is out about 10 minutes after 02, 05, ..., 23 h; 중기예보 about 30 minutes after 06 and 18 h."""
|
||||
now = now.replace(tzinfo=timezone(timedelta(hours=9)))
|
||||
_, calls = self._run({"days_ahead": 1}, monkeypatch, now=now)
|
||||
_, mid_calls = self._run({"days_ahead": 7}, monkeypatch, now=now)
|
||||
|
||||
(p,) = [p for u, p in calls if "getVilageFcst" in u]
|
||||
assert (p["base_date"], p["base_time"]) == vilage
|
||||
assert {p["tmFc"] for u, p in mid_calls if "MidFcstInfoService" in u} == {tmfc}
|
||||
|
||||
def test_an_evening_mid_term_forecast_from_yesterday_counts_its_days_from_yesterday(self, monkeypatch):
|
||||
# 05:00 on the 19th: the latest 중기예보 is the 18th's 18:00, whose day 5 is the 23rd = 4 days ahead.
|
||||
now = datetime(2026, 11, 19, 5, 0, tzinfo=timezone(timedelta(hours=9)))
|
||||
result, _ = self._run({"days_ahead": 4}, monkeypatch, now=now)
|
||||
|
||||
assert result.reply_text.startswith("11월 23일 월요일") and "최고 7도" in result.reply_text
|
||||
|
||||
def test_when_kma_fails_open_meteo_gives_the_forecast_and_the_key_is_not_logged(self, monkeypatch):
|
||||
with patch("src.jarvis.tools.builtin.weather.debug_log") as log:
|
||||
result, calls = self._run({"days_ahead": 1}, monkeypatch, fail_kma=True)
|
||||
|
||||
assert result.success is True
|
||||
assert result.reply_text.startswith("내일(11월 19일 목요일) Seoul 날씨는 약한 비,")
|
||||
assert "최저 3도" in result.reply_text and "최고 11도" in result.reply_text
|
||||
assert "강수확률 80%" in result.reply_text
|
||||
assert not any(self.KEY in str(c) for c in log.call_args_list)
|
||||
|
||||
def test_outside_korea_the_forecast_is_open_meteos_daily_one(self, monkeypatch):
|
||||
result, calls = self._run({"days_ahead": 1}, monkeypatch, country_code="JP")
|
||||
|
||||
assert "약한 비" in result.reply_text and "최고 11도" in result.reply_text
|
||||
assert not any("apihub.kma.go.kr" in u for u, _ in calls)
|
||||
(p,) = [p for u, p in calls if "open-meteo.com/v1/forecast" in u]
|
||||
assert "precipitation_probability_max" in p["daily"] and p["forecast_days"] >= 2
|
||||
|
||||
def test_this_week_starts_with_the_weather_now(self, monkeypatch):
|
||||
"""days_ahead 0 with more days: the current weather, then a line for each day."""
|
||||
result, _ = self._run({"days": 3}, monkeypatch, key=False)
|
||||
|
||||
lines = result.reply_text.split("\n")
|
||||
assert lines[0].startswith("지금 Seoul 날씨는")
|
||||
assert lines[1].startswith("오늘(11월 18일 수요일)") and lines[2].startswith("내일(11월 19일 목요일)")
|
||||
assert lines[3].startswith("모레(11월 20일 금요일)") and len(lines) == 4
|
||||
|
||||
def test_more_than_ten_days_ahead_is_the_tenth_day(self, monkeypatch):
|
||||
result, _ = self._run({"days_ahead": 30, "days": 5}, monkeypatch)
|
||||
|
||||
assert result.reply_text.split("\n") == [result.reply_text]
|
||||
assert result.reply_text.startswith("11월 28일 토요일") and "맑음" in result.reply_text
|
||||
|
||||
def test_when_no_forecast_is_available_the_answer_says_so(self, monkeypatch):
|
||||
def down(url, *a, **k):
|
||||
if "geocoding" in url:
|
||||
return self._ok({"results": [{"latitude": 1.0, "longitude": 2.0, "name": "X",
|
||||
"country_code": "FR"}]})
|
||||
raise requests.exceptions.ConnectionError("down")
|
||||
with patch('requests.get', side_effect=down), \
|
||||
patch('src.jarvis.tools.builtin.weather._now', return_value=self.NOW):
|
||||
result = self.tool.run({"location": "X", "days_ahead": 2}, self.context)
|
||||
|
||||
assert result.success is False and "forecast" in result.reply_text.lower()
|
||||
|
||||
Reference in New Issue
Block a user