feat(weather): KMA current weather inside Korea with the app's stored key

The 기능 screen's 기상청 날씨 card stores the KMA API hub key encrypted
(kmaApiKey, masked in logs). On start the app passes it to the worker in
JARVIS_KMA_API_KEY; the worker takes it out of its environment before any
child process starts. Inside Korea getWeather reads 초단기실황 and the
coming hour's sky from 초단기예보, and falls back to open-meteo, then
met.no, on any KMA failure. The key is in KMA's URLs, so failures are
logged by their kind only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-18 10:05:31 +09:00
parent e99831e540
commit 282f114e60
10 changed files with 383 additions and 22 deletions

View File

@@ -649,3 +649,178 @@ class TestExtractPlaceFromUserText:
with patch("src.jarvis.llm.call_llm_direct", return_value="x" * 200):
got = _extract_place_from_user_text("weather", self._cfg())
assert got is None
class TestKmaWeather:
"""Inside Korea, with the app's KMA key, the current weather comes from KMA (기상청 API허브)."""
KEY = "kma-test-key-123"
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 _geo(country_code):
geo = Mock(status_code=200, raise_for_status=Mock())
geo.json.return_value = {"results": [{"latitude": 37.566, "longitude": 126.9784,
"name": "Seoul", "country_code": country_code}]}
return geo
@staticmethod
def _kma(items, code="00"):
r = Mock(status_code=200, raise_for_status=Mock())
r.json.return_value = {"response": {"header": {"resultCode": code},
"body": {"items": {"item": items}}}}
return r
def _obs(self, pty="0", t1h="4.9"):
return self._kma([{"category": c, "obsrValue": v} for c, v in
[("PTY", pty), ("REH", "72"), ("RN1", "0"), ("T1H", t1h), ("WSD", "2.5")]])
def _sky(self, first="3"):
# The coming hours, out of order: the earliest one is the sky now.
return self._kma([
{"category": "SKY", "fcstDate": "20261118", "fcstTime": "1100", "fcstValue": "1"},
{"category": "SKY", "fcstDate": "20261118", "fcstTime": "1000", "fcstValue": first},
{"category": "T1H", "fcstDate": "20261118", "fcstTime": "1000", "fcstValue": "6"},
])
def _routes(self, country_code="KR", obs=None, sky=None, calls=None):
weather = Mock(status_code=200, raise_for_status=Mock())
weather.json.return_value = {"current": {"temperature_2m": 11.0, "weather_code": 0}}
def get(url, *a, **k):
if calls is not None:
calls.append((url, k.get("params") or {}))
if "geocoding" in url:
return self._geo(country_code)
if "getUltraSrtNcst" in url:
return obs if obs is not None else self._obs()
if "getUltraSrtFcst" in url:
return sky if sky is not None else self._sky()
assert "open-meteo" in url, url
return weather
return get
@patch('requests.get')
def test_with_a_key_korean_weather_comes_from_kma(self, mock_get, monkeypatch):
monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY)
calls = []
mock_get.side_effect = self._routes(calls=calls)
result = self.tool.run({"location": "Seoul"}, self.context)
assert result.success is True
assert "구름 많음" in result.reply_text and "기온 5도" in result.reply_text
assert not any("api.open-meteo.com/v1/forecast" in u for u, _ in calls)
kma = [p for u, p in calls if "apihub.kma.go.kr" in u]
assert len(kma) == 2 and all(p["authKey"] == self.KEY for p in kma)
assert all((p["nx"], p["ny"]) == (60, 127) for p in kma)
@patch('requests.get')
def test_precipitation_wins_over_the_sky(self, mock_get, monkeypatch):
monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY)
mock_get.side_effect = self._routes(obs=self._obs(pty="3", t1h="-1.4"), sky=self._sky(first="1"))
result = self.tool.run({"location": "Seoul"}, self.context)
assert "눈" in result.reply_text and "맑음" not in result.reply_text
assert "기온 -1도" in result.reply_text
@patch('requests.get')
def test_without_a_key_open_meteo_answers_also_in_korea(self, mock_get, monkeypatch):
monkeypatch.delenv("JARVIS_KMA_API_KEY", raising=False)
calls = []
mock_get.side_effect = self._routes(calls=calls)
result = self.tool.run({"location": "Seoul"}, self.context)
assert "기온 11도" in result.reply_text
assert not any("apihub.kma.go.kr" in u for u, _ in calls)
@patch('requests.get')
def test_outside_korea_kma_is_not_asked(self, mock_get, monkeypatch):
monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY)
calls = []
mock_get.side_effect = self._routes(country_code="JP", calls=calls)
result = self.tool.run({"location": "Fukuoka"}, self.context)
assert "기온 11도" in result.reply_text
assert not any("apihub.kma.go.kr" in u for u, _ in calls)
@pytest.mark.parametrize("failure", ["result_code", "timeout", "no_sky"])
@patch('requests.get')
def test_when_kma_fails_open_meteo_answers_and_the_key_is_not_logged(
self, mock_get, failure, monkeypatch):
monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY)
if failure == "result_code": # e.g. the API's use not applied for
routes = self._routes(obs=self._kma([], code="30"))
elif failure == "timeout":
base = self._routes()
def routes(url, *a, **k):
if "apihub.kma.go.kr" in url:
raise requests.exceptions.Timeout(f"timed out: {url}?authKey={self.KEY}")
return base(url, *a, **k)
else:
routes = self._routes(sky=self._kma([]))
mock_get.side_effect = routes
with patch("src.jarvis.tools.builtin.weather.debug_log") as log:
result = self.tool.run({"location": "Seoul"}, self.context)
assert result.success is True and "기온 11도" in result.reply_text
assert not any(self.KEY in str(c) for c in log.call_args_list)
@pytest.mark.parametrize("place,lat,lon,grid", [
("서울", 37.5665, 126.9780, (60, 127)),
("부산", 35.1796, 129.0756, (98, 76)),
("제주", 33.4996, 126.5312, (53, 38)),
])
def test_kma_grid_point(self, place, lat, lon, grid):
from src.jarvis.tools.builtin.weather import _kma_grid
assert _kma_grid(lat, lon) == grid, place
@patch('requests.get')
def test_kma_base_times_are_the_latest_published(self, mock_get):
"""초단기실황 for hour H is out at about H:40, 초단기예보 for H:30 at about H:45 (KST)."""
from datetime import datetime, timezone, timedelta
from src.jarvis.tools.builtin.weather import _kma_current
calls = []
mock_get.side_effect = self._routes(calls=calls)
# 00:20 KST on 1 Jan: both still from the day before.
_kma_current(37.566, 126.978, self.KEY,
now=datetime(2026, 12, 31, 15, 20, tzinfo=timezone.utc))
(_, obs), (_, fc) = calls
assert (obs["base_date"], obs["base_time"]) == ("20261231", "2300")
assert (fc["base_date"], fc["base_time"]) == ("20261231", "2330")
calls.clear()
_kma_current(37.566, 126.978, self.KEY,
now=datetime(2026, 11, 18, 9, 50, tzinfo=timezone(timedelta(hours=9))))
(_, obs), (_, fc) = calls
assert obs["base_time"] == "0900" and fc["base_time"] == "0930"
@patch('requests.get')
def test_the_worker_takes_the_key_out_of_the_environment_and_still_uses_it(self, mock_get, monkeypatch):
"""No child process (MCP servers, MeloTTS) inherits the key; the weather tool keeps it."""
import os
import src.jarvis.tools.builtin.weather as weather
monkeypatch.setenv("JARVIS_KMA_API_KEY", self.KEY)
monkeypatch.setattr(weather, "_kma_key", "")
weather.take_kma_key()
assert "JARVIS_KMA_API_KEY" not in os.environ
calls = []
mock_get.side_effect = self._routes(calls=calls)
result = self.tool.run({"location": "Seoul"}, self.context)
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)