fix: 출시 전 QA 버그 3건 — 주말 플랜 500, 광주·전남 행사 0건, 미세먼지 갱신 멈춤
- 주말 플랜: '14시~' 같은 시간 라벨에서 정렬이 멈춰 피드 전체가 500 (광산구·울릉군) - 광주·전남: 구 코드는 12인데 행사는 29·46으로 저장돼 27개 구에서 행사를 못 찾음 - 미세먼지: 에어코리아 전국 조회가 15~20초 걸려 8초 한도에 매번 걸림 → 45초
This commit is contained in:
1 parent
5734b57758
commit
1fa0695c84
7 files changed
+60
-12
No files matched your search
+4
-2
@@ -8,6 +8,8 @@ from services.external.data_go_kr import get_all_items
|
||||
|
||||
REALTIME_URL = "https://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getCtprvnRltmMesureDnsty"
|
||||
STATION_URL = "https://apis.data.go.kr/B552584/MsrstnInfoInqireSvc/getMsrstnList"
|
||||
# 전국 조회는 한 번에 15~20초 걸린다. 갱신은 피드 응답과 따로 돌아 기다리게 하지 않는다.
|
||||
BUDGET_SEC = 45.0
|
||||
|
||||
|
||||
def _int(v) -> Optional[int]:
|
||||
@@ -26,11 +28,11 @@ def _measured_at(text: str) -> datetime:
|
||||
|
||||
|
||||
async def fetch_realtime(client: httpx.AsyncClient) -> list[dict]:
|
||||
return await get_all_items(client, REALTIME_URL, {"returnType": "json", "sidoName": "전국", "ver": "1.0"})
|
||||
return await get_all_items(client, REALTIME_URL, {"returnType": "json", "sidoName": "전국", "ver": "1.0"}, budget_sec=BUDGET_SEC)
|
||||
|
||||
|
||||
async def fetch_stations(client: httpx.AsyncClient) -> list[dict]:
|
||||
return await get_all_items(client, STATION_URL, {"returnType": "json"})
|
||||
return await get_all_items(client, STATION_URL, {"returnType": "json"}, budget_sec=BUDGET_SEC)
|
||||
|
||||
|
||||
def parse_realtime(items: list[dict]) -> list[dict]:
|
||||
|
||||
+5
-4
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -17,12 +18,12 @@ class DataGoKrRequestFailed(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
async def get_body(client: httpx.AsyncClient, url: str, params: dict) -> dict:
|
||||
async def get_body(client: httpx.AsyncClient, url: str, params: dict, budget_sec: Optional[float] = None) -> dict:
|
||||
"""data.go.kr 공통 호출. 가끔 오는 504(SERVICETIMEOUT)는 다시 시도하고, 응답이 없으면 잠시 그 API 를 쉰다. 로그·예외에 키를 남기지 않는다."""
|
||||
if not settings.data_go_kr_service_key:
|
||||
raise DataGoKrNotConfigured("DATA_GO_KR_SERVICE_KEY is empty")
|
||||
op = url.rsplit("/", 1)[-1]
|
||||
return await guarded(f"datagokr:{op}", lambda: _get_body(client, url, op, params), DataGoKrRequestFailed)
|
||||
return await guarded(f"datagokr:{op}", lambda: _get_body(client, url, op, params), DataGoKrRequestFailed, budget_sec)
|
||||
|
||||
|
||||
async def _get_body(client: httpx.AsyncClient, url: str, op: str, params: dict) -> dict:
|
||||
@@ -44,11 +45,11 @@ async def _get_body(client: httpx.AsyncClient, url: str, op: str, params: dict)
|
||||
raise Unreachable(f"failed after {_ATTEMPTS} attempts: {last or 'unexpected body'}")
|
||||
|
||||
|
||||
async def get_all_items(client: httpx.AsyncClient, url: str, params: dict, page_size: int = 1000) -> list[dict]:
|
||||
async def get_all_items(client: httpx.AsyncClient, url: str, params: dict, page_size: int = 1000, budget_sec: Optional[float] = None) -> list[dict]:
|
||||
items: list[dict] = []
|
||||
page = 1
|
||||
while True:
|
||||
body = await get_body(client, url, {**params, "numOfRows": page_size, "pageNo": page})
|
||||
body = await get_body(client, url, {**params, "numOfRows": page_size, "pageNo": page}, budget_sec)
|
||||
raw = body.get("items") or []
|
||||
chunk = raw.get("item", []) if isinstance(raw, dict) else raw
|
||||
chunk = [chunk] if isinstance(chunk, dict) else chunk
|
||||
|
||||
@@ -43,6 +43,8 @@ MAX_EVENT_DAYS = 60
|
||||
EVENT_RADIUS_KM = 30
|
||||
# 행사는 시도 단위로 받는다. 구 중심이 이 거리 안에 있는 시도는 경계가 반경에 걸칠 수 있어 같이 받는다.
|
||||
_SIDO_REACH_KM = EVENT_RADIUS_KM + 20
|
||||
# 구 코드는 광주·전남을 한 시도(12)로 묶지만, 행사는 TourAPI·문화정보 시도 코드(광주 29 · 전남 46)로 받는다.
|
||||
_EVENT_SIDOS = {"12": ("29", "46")}
|
||||
PLACE_RADIUS_KM = EVENT_RADIUS_KM
|
||||
PLACE_LIMIT = 10
|
||||
# 반경 안에 명소가 하나도 없는 구는 가장 가까운 곳을 이만큼 거리와 함께 보여 준다.
|
||||
@@ -129,11 +131,18 @@ def mix_kinds(items: list[EventItem]) -> list[EventItem]:
|
||||
return mixed
|
||||
|
||||
|
||||
def event_sidos(region_code: str) -> tuple[str, ...]:
|
||||
"""구가 속한 시도의 행사 시도 코드들."""
|
||||
sido = region_code[:2]
|
||||
return _EVENT_SIDOS.get(sido, (sido,))
|
||||
|
||||
|
||||
def nearby_sidos(region: Region, regions: list[Region]) -> list[str]:
|
||||
"""반경 안에 걸칠 수 있는 시도들. 자기 시도는 항상 앞에."""
|
||||
"""반경 안에 걸칠 수 있는 시도들(행사 시도 코드). 자기 시도는 항상 앞에."""
|
||||
lat, lon = float(region.lat), float(region.lon)
|
||||
near = {r.code[:2] for r in regions if haversine_km(lat, lon, float(r.lat), float(r.lon)) <= _SIDO_REACH_KM}
|
||||
return [region.code[:2]] + sorted(near - {region.code[:2]})
|
||||
own = event_sidos(region.code)
|
||||
near = {s for r in regions if haversine_km(lat, lon, float(r.lat), float(r.lon)) <= _SIDO_REACH_KM for s in event_sidos(r.code)}
|
||||
return list(own) + sorted(near - set(own))
|
||||
|
||||
|
||||
def event_distance(region: Region, e: Event) -> Optional[float]:
|
||||
@@ -148,7 +157,7 @@ def is_nearby(region: Region, e: Event, distance_km: Optional[float]) -> bool:
|
||||
return distance_km <= EVENT_RADIUS_KM
|
||||
if e.region_code is not None:
|
||||
return e.region_code == region.code
|
||||
return e.sido_code == region.code[:2]
|
||||
return e.sido_code in event_sidos(region.code)
|
||||
|
||||
|
||||
def pick_places(region: Region, places: list[Place], rainy: bool, area: Optional[str]) -> tuple[list[PlaceItem], list[str]]:
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
@@ -158,7 +159,7 @@ def _sort(steps: list[Step]) -> list[Step]:
|
||||
def key(s: Step) -> float:
|
||||
t = s.time
|
||||
if t[0].isdigit():
|
||||
h = int(t.split("~")[0].split(":")[0])
|
||||
h = int(re.match(r"\d+", t).group())
|
||||
return 5.5 if h >= 17 else 1.5 if h < 12 else 3
|
||||
if t.startswith("~"):
|
||||
return 0
|
||||
|
||||
@@ -5,7 +5,8 @@ import httpx
|
||||
import pytest
|
||||
|
||||
from config.settings import settings
|
||||
from services.external import data_go_kr, guard, open_meteo
|
||||
from services.external import airkorea, data_go_kr, guard, open_meteo
|
||||
from services.external.airkorea import fetch_realtime
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed, get_body
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds
|
||||
|
||||
@@ -93,3 +94,16 @@ async def test_open_meteo_down_is_skipped(monkeypatch):
|
||||
with pytest.raises(OpenMeteoRequestFailed):
|
||||
await fetch_clouds(client, [(37.5, 127.0)])
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_airkorea_nationwide_call_waits_past_default_budget(fast, monkeypatch):
|
||||
"""전국 미세먼지 조회는 15~20초 걸려 기본 한도로는 늘 실패한다."""
|
||||
monkeypatch.setattr(airkorea, "BUDGET_SEC", 2.0)
|
||||
|
||||
async def slow(req: httpx.Request) -> httpx.Response:
|
||||
await asyncio.sleep(0.5)
|
||||
return httpx.Response(200, json={"response": {"header": {"resultCode": "00"}, "body": {"items": [{"stationName": "x"}], "totalCount": 1}}})
|
||||
|
||||
async with _client(slow) as client:
|
||||
assert await fetch_realtime(client) == [{"stationName": "x"}]
|
||||
@@ -169,6 +169,22 @@ async def test_events_pick_within_30km_across_sido(fakes, monkeypatch):
|
||||
assert {e["name"] for e in body["events"]} == {"잠실 축제", "좌표 없는 경기 축제"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gwangju_jeonnam_region_finds_events_saved_as_29_and_46(fakes, monkeypatch):
|
||||
"""구 코드는 광주·전남이 12로 묶이지만 행사는 광주 29 · 전남 46으로 저장된다. 광산구에서 둘 다 보여야 한다."""
|
||||
today = now_kst().date()
|
||||
span = {"eventstartdate": (today + timedelta(days=1)).strftime("%Y%m%d"), "eventenddate": (today + timedelta(days=3)).strftime("%Y%m%d")}
|
||||
by_sido = {
|
||||
"29": [{"contentid": "29", "title": "광주 축제", "addr1": "광주 광산구", "mapy": "35.1396", "mapx": "126.7937", **span}],
|
||||
"46": [{"contentid": "46", "title": "좌표 없는 전남 축제", "addr1": "전남", **span}],
|
||||
}
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda client, sido, since: _async(by_sido.get(sido, [])))
|
||||
await _collect("29", "46")
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": "1233000000"})).json()
|
||||
assert {e["name"] for e in body["events"]} == {"광주 축제", "좌표 없는 전남 축제"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_places_put_indoor_first_on_rainy_day(fakes):
|
||||
rainy_day = (now_kst().date() + timedelta(days=2)).isoformat()
|
||||
|
||||
@@ -55,6 +55,11 @@ def test_afternoon_rain_moves_outdoor_time_before_it():
|
||||
assert card.line.startswith("비 오는 토요일")
|
||||
|
||||
|
||||
def test_morning_rain_then_outdoor_after_it_ends():
|
||||
card = day_plan(_day(SAT, rainy=True, rain_hours=(9, 14), prob=60), None, [], None)
|
||||
assert [s.time for s in card.steps] == ["9~14시", "14시~"]
|
||||
|
||||
|
||||
def test_saturday_ignores_ending_hook_and_sunday_skips_saturday_events():
|
||||
near = _event("가까운 축제", SAT, SUN, 3.0)
|
||||
ends_sat = _event("토요일 끝", SAT, SAT, 50.0)
|
||||
|
||||
Reference in new issue
Block a user