Merge branch 'main' into feat/open-meteo
# Conflicts: # backend/router/v1/index/index.py # backend/services/calc/index_calc.py # backend/services/index_service.py # backend/tests/conftest.py # backend/tests/test_index_api.py # backend/tests/test_index_calc.py # backend/tests/test_sky_api.py # backend/worker_main.py
This commit is contained in:
commit
1a1df4bb87
111 files changed
+5787
-679
No files matched your search
@@ -118,10 +118,11 @@ def offline(monkeypatch):
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([]))
|
||||
monkeypatch.setattr(sky_service, "fetch_clouds", clouds)
|
||||
monkeypatch.setattr(jobs, "fetch_weather", openmeteo_weather)
|
||||
monkeypatch.setattr(week_service, "fetch_mid", lambda *a: _async(({}, {})))
|
||||
monkeypatch.setattr(weather_service, "fetch_mid", lambda *a: _async(({}, {})))
|
||||
monkeypatch.setattr(week_service, "fetch_holidays", lambda *a: _async([]))
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda *a: _async([{
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda c, sido, since: _async([{
|
||||
"contentid": "77", "title": "테스트 축제", "addr1": "서울", "eventstartdate": now.strftime("%Y%m%d"),
|
||||
"eventenddate": (now + timedelta(days=2)).strftime("%Y%m%d"),
|
||||
}]))
|
||||
"eventenddate": (now + timedelta(days=2)).strftime("%Y%m%d"), "firstimage": "http://tong.visitkorea.or.kr/test.jpg",
|
||||
}] if sido == "11" else []))
|
||||
monkeypatch.setattr(week_service, "fetch_exhibitions", lambda *a: _async([]))
|
||||
monkeypatch.setattr(season_service, "fetch_solar_terms", lambda *a: _async([]))
|
||||
@@ -0,0 +1,79 @@
|
||||
from datetime import date
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from config.settings import settings
|
||||
from services.external import culture_api
|
||||
from services.external.culture_api import fetch_exhibitions, parse_exhibitions
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
|
||||
_ITEM = """<item><serviceName>공연/전시</serviceName><seq>{seq}</seq><title>{title}</title><startDate>{start}</startDate><endDate>{end}</endDate>
|
||||
<place>테스트 미술관</place><realmName>전시</realmName><area>서울</area><sigungu>종로구</sigungu><thumbnail>{thumb}</thumbnail>
|
||||
<gpsX>126.97689</gpsX><gpsY>37.57592</gpsY></item>"""
|
||||
|
||||
|
||||
def _page(items: list[str], total: int) -> str:
|
||||
return (f"<?xml version='1.0' encoding='UTF-8'?><response><header><resultCode>00</resultCode><resultMsg>NORMAL SERVICE.</resultMsg></header>"
|
||||
f"<body><items>{''.join(items)}</items><numOfrows>2</numOfrows><PageNo>1</PageNo><totalCount>{total}</totalCount></body></response>")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def key(monkeypatch):
|
||||
monkeypatch.setattr(settings, "data_go_kr_service_key", "fake-key")
|
||||
monkeypatch.setattr(culture_api, "_PAGE_SIZE", 2)
|
||||
monkeypatch.setattr(culture_api, "_BACKOFF_SEC", 0)
|
||||
|
||||
|
||||
def _client(handler) -> httpx.AsyncClient:
|
||||
return httpx.AsyncClient(transport=httpx.MockTransport(handler))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_exhibitions_pages_through_xml(key):
|
||||
seen = []
|
||||
|
||||
def handler(req: httpx.Request) -> httpx.Response:
|
||||
seen.append(dict(req.url.params))
|
||||
page = int(req.url.params["PageNo"])
|
||||
items = [_ITEM.format(seq=page * 10 + i, title=f"전시{page}-{i}", start="20261001", end="20261130", thumb="") for i in range(2 if page == 1 else 1)]
|
||||
return httpx.Response(200, text=_page(items, 3), headers={"content-type": "application/xml"})
|
||||
|
||||
async with _client(handler) as client:
|
||||
items = await fetch_exhibitions(client, "11", date(2026, 10, 6), 30)
|
||||
assert [it["title"] for it in items] == ["전시1-0", "전시1-1", "전시2-0"]
|
||||
assert seen[0]["realmCode"] == "D000" and seen[0]["sido"] == "서울" and seen[0]["from"] == "20261006" and seen[0]["to"] == "20261105"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_exhibitions_reports_unregistered_key(key):
|
||||
body = ("<OpenAPI_ServiceResponse><cmmMsgHeader><errMsg>SERVICE_KEY_IS_NOT_REGISTERED_ERROR</errMsg>"
|
||||
"<returnAuthMsg>등록되지 않은 서비스키</returnAuthMsg><returnReasonCode>30</returnReasonCode></cmmMsgHeader></OpenAPI_ServiceResponse>")
|
||||
async with _client(lambda req: httpx.Response(403, text=body)) as client:
|
||||
with pytest.raises(DataGoKrRequestFailed, match="30 SERVICE_KEY_IS_NOT_REGISTERED_ERROR"):
|
||||
await fetch_exhibitions(client, "11", date(2026, 10, 6), 30)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_fetch_exhibitions_skips_unknown_sido(key):
|
||||
async with _client(lambda req: pytest.fail("호출하면 안 된다")) as client:
|
||||
assert await fetch_exhibitions(client, "99", date(2026, 10, 6), 30) == []
|
||||
|
||||
|
||||
def test_parse_exhibitions_maps_fields_and_drops_ended_or_duplicate():
|
||||
items = [
|
||||
{"seq": "501", "title": "가을 특별전", "place": "테스트 미술관", "startDate": "20261001", "endDate": "2026-11-30",
|
||||
"thumbnail": "http://www.culture.go.kr/upload/a.jpg", "gpsX": "126.97689", "gpsY": "37.57592"},
|
||||
{"seq": "501", "title": "가을 특별전", "place": "테스트 미술관", "startDate": "20261001", "endDate": "20261130", "thumbnail": "", "gpsX": "", "gpsY": ""},
|
||||
{"seq": "502", "title": "끝난 전시", "place": "테스트 박물관", "startDate": "20260101", "endDate": "20261005"},
|
||||
{"seq": "503", "title": "날짜 없음", "place": "테스트 박물관", "startDate": "", "endDate": ""},
|
||||
{"seq": "504", "title": "좌표 뒤바뀜", "place": "테스트 박물관", "startDate": "20261001", "endDate": "20261010", "gpsX": "37.5", "gpsY": "127.0"},
|
||||
]
|
||||
rows = parse_exhibitions(items, "11", date(2026, 10, 6))
|
||||
assert [r["source_id"] for r in rows] == ["kcis:501", "kcis:504"]
|
||||
assert rows[0]["end_date"] == date(2026, 11, 30)
|
||||
assert rows[1]["lat"] == 37.5 and rows[1]["lon"] == 127.0
|
||||
assert rows[0]["image_url"] == "https://www.culture.go.kr/upload/a.jpg"
|
||||
assert rows[0]["lat"] == 37.57592 and rows[0]["lon"] == 126.97689
|
||||
assert rows[0]["sido_code"] == "11" and rows[0]["place_name"] == "테스트 미술관"
|
||||
assert all(len(r["source_id"]) <= 20 for r in rows)
|
||||
+159
-1
@@ -30,6 +30,18 @@ async def test_build_day_adds_weekend_post_every_day():
|
||||
assert (await _posts(thursday))[0] == PostType.WEATHER.value
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_build_day_adds_new_card_types_to_existing_day():
|
||||
"""이미 만든 날에 새 종류(미세먼지)가 생기면 빠진 카드만 더한다."""
|
||||
thursday = date(2026, 10, 15)
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: s.execute(text(f"DELETE FROM post WHERE feed_date='{thursday}' AND post_type={PostType.AIR.value}"))])
|
||||
before = len(await _posts(thursday))
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
after = await _posts(thursday)
|
||||
assert len(after) == before + 1 and after.count(PostType.AIR.value) == 1
|
||||
|
||||
|
||||
def test_weekends_groups_this_and_next_weekend():
|
||||
from types import SimpleNamespace
|
||||
from services.feed_service import _weekends
|
||||
@@ -45,9 +57,16 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
assert body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"]
|
||||
assert len(body["stories"]) == 27
|
||||
weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert [s["kind"] for s in weather["slides"]] == ["hours", "rows"]
|
||||
assert [s["kind"] for s in weather["slides"]] == ["hours", "hours"]
|
||||
assert len(weather["slides"][0]["hours"]) == 8
|
||||
assert body["bands"]["events"][0]["name"] == "테스트 축제"
|
||||
assert body["bands"]["events"][0]["image"] == "https://tong.visitkorea.or.kr/test.jpg"
|
||||
assert body["bands"]["events"][0]["image_credit"] == "ⓒ한국관광공사"
|
||||
assert "미세먼지" not in weather["caption"]
|
||||
air = next(p for p in body["posts"] if p["post_type"] == PostType.AIR.value)
|
||||
assert [(r["label"], r["value"]) for r in air["slides"][0]["rows"]] == [("초미세먼지", "10㎍/㎥ · 좋음"), ("미세먼지", "20㎍/㎥ · 좋음")]
|
||||
event = next(p for p in body["posts"] if p["post_type"] == PostType.EVENT.value)
|
||||
assert event["slides"][0]["eyebrow"].startswith("가까운 행사 · ")
|
||||
|
||||
|
||||
def test_feed_cache_expires_when_time_slot_changes():
|
||||
@@ -175,3 +194,142 @@ async def test_feed_missing_gak_is_cached_only_briefly(offline, monkeypatch):
|
||||
assert PostType.GAK.value not in [p["post_type"] for p in body["posts"]]
|
||||
keys = [k async for k in REDIS.conn.scan_iter(f"feed:{REGION}:*")]
|
||||
assert keys and 0 < await REDIS.conn.ttl(keys[0]) <= 60
|
||||
|
||||
|
||||
def _alert_ctx(warnings=(), rain_prob=0):
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
|
||||
now = datetime(2026, 10, 2, 9, tzinfo=KST)
|
||||
hourly = [SimpleNamespace(forecast_at=datetime(2026, 10, 2, 15, tzinfo=KST), rain_prob=rain_prob)]
|
||||
return SimpleNamespace(now=now, hourly=hourly, region=SimpleNamespace(short_name="종로구"), now_w=SimpleNamespace(warnings=list(warnings)))
|
||||
|
||||
|
||||
def _base():
|
||||
from datetime import datetime
|
||||
|
||||
return dict(post_id=1, post_type=PostType.ALERT, like_count=0, comment_count=0, published_at=datetime(2026, 10, 2))
|
||||
|
||||
|
||||
def _alert(ctx):
|
||||
from services.feed_service import FeedService
|
||||
|
||||
return FeedService._alert(None, _base(), ctx)
|
||||
|
||||
|
||||
def test_alert_uses_umbrella_only_for_rain():
|
||||
from common.enums import WarningLevel, WarningType
|
||||
from services.warning_service import WarningItem
|
||||
|
||||
heat = _alert(_alert_ctx([WarningItem(WarningType.HEAT, WarningLevel.ADVISORY, "폭염주의보")]))
|
||||
cold = _alert(_alert_ctx([WarningItem(WarningType.COLD, WarningLevel.WARNING, "한파경보")]))
|
||||
rain = _alert(_alert_ctx(rain_prob=60))
|
||||
assert heat.icon != "umbrella" and "우산" not in heat.share_messages[0]
|
||||
assert cold.icon == "coldwind" and "우산" not in cold.share_messages[0]
|
||||
assert rain.icon == "umbrella" and rain.share_messages[0].endswith("☔ 우산 챙겨!")
|
||||
|
||||
|
||||
def test_event_caption_adds_what_slide_lacks():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.feed_service import _event_caption
|
||||
from services.week_service import EventItem
|
||||
|
||||
ev = lambda confirmed=True: SimpleNamespace(is_confirmed=confirmed) # noqa: E731
|
||||
full = EventItem(event=ev(), status="live", status_label="진행 중", fit="토요일 맑음 22°", distance_km=12.3)
|
||||
assert _event_caption(full) == "지금 진행 중 · 여기서 12km · 토요일 맑음 22°"
|
||||
bare = EventItem(event=ev(False), status="soon", status_label="D-12", fit=None)
|
||||
assert _event_caption(bare) == "올해 정확한 일정은 공식 안내로 확인해 주세요."
|
||||
|
||||
|
||||
def test_text_helpers_short_day_and_compass():
|
||||
from common.utils.text import compass, day_range
|
||||
|
||||
assert day_range(date(2026, 10, 4), date(2026, 10, 11)) == "10.4~10.11"
|
||||
assert compass(263) == "서" and compass(247) == "서남서"
|
||||
|
||||
|
||||
def _air(pm25, pm10, measured_hours_ago=0):
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from services.feed_service import FeedService
|
||||
|
||||
now = datetime(2026, 10, 2, 9, 30, tzinfo=KST)
|
||||
air = None if pm25 is None and pm10 is None else SimpleNamespace(
|
||||
station_name="테스트", pm25=pm25, pm10=pm10, measured_at=now.replace(minute=0) - timedelta(hours=measured_hours_ago))
|
||||
ctx = SimpleNamespace(now=now, region=SimpleNamespace(short_name="종로구"), now_w=SimpleNamespace(air=air))
|
||||
return FeedService._air(None, _base() | {"post_type": PostType.AIR}, ctx)
|
||||
|
||||
|
||||
def test_air_post_shows_both_values_and_advice_only_when_bad():
|
||||
good = _air(10, 20)
|
||||
assert [r.label for r in good.slides[0].rows] == ["초미세먼지", "미세먼지"] and good.title == "미세먼지 좋음"
|
||||
bad = _air(40, 60)
|
||||
assert bad.title == "미세먼지 나쁨" and bad.slides[0].rows[-1].label == "이렇게 해요"
|
||||
very = _air(20, 160)
|
||||
assert very.title == "미세먼지 매우나쁨" and "측정소" in very.caption and very.slides[0].rows[1].value == "160㎍/㎥ · 매우나쁨"
|
||||
|
||||
|
||||
def test_air_post_off_without_fresh_data():
|
||||
assert _air(None, None) is None
|
||||
assert _air(10, 20, measured_hours_ago=4) is None
|
||||
|
||||
|
||||
def _score(code, day, score, prob=10):
|
||||
from services.weekend_rank import DayScore
|
||||
|
||||
return DayScore(region_code=code, day=day, score=score, reason=f"비 {prob}% · 체감 21° · 맑음", icon="sun", temp_min_c=12.0, temp_max_c=22.0,
|
||||
rain_prob=prob, estimated=False)
|
||||
|
||||
|
||||
def test_pick_trip_takes_best_city_within_reach():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.weekend_rank import TripCity, pick_trip
|
||||
|
||||
sat, sun = date(2026, 10, 10), date(2026, 10, 11)
|
||||
bundang = SimpleNamespace(lat=37.38, lon=127.12)
|
||||
city = lambda code, lat, lon, label: (code, (SimpleNamespace(code=code, lat=lat, lon=lon), TripCity(name=label, label=label, note=""))) # noqa: E731
|
||||
cities = dict([city("gn", 37.75, 128.88, "강릉"), city("cc", 37.88, 127.73, "춘천"), city("bs", 35.16, 129.16, "부산")])
|
||||
scores = [_score("gn", sat, 70), _score("gn", sun, 88), _score("cc", sat, 80), _score("bs", sat, 99)]
|
||||
pick = pick_trip(bundang, scores, cities, [sat, sun])
|
||||
assert pick.label == "강릉" and pick.best.day == sun and 150 < pick.distance_km < 170
|
||||
assert pick.runner_up[0] == "춘천" and pick.runner_up[1].score == 80
|
||||
assert pick_trip(bundang, [_score("gn", sat, 40)], cities, [sat, sun]) is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_feed_has_day_trip_card_with_city_event(offline, monkeypatch):
|
||||
"""분당 사용자: 캐시된 주말 점수에서 강릉이 1위면 강릉 당일치기 카드 + 강릉 근처 행사 사진."""
|
||||
import json
|
||||
from dataclasses import asdict
|
||||
|
||||
import services.week_service as week_service
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.utils.kma_time import now_kst
|
||||
from services.weekend_rank import _KEY, _sat, weekend_days
|
||||
|
||||
today = now_kst().date()
|
||||
day = weekend_days(today)[-1]
|
||||
scores = [_score("5115000000", day, 90), _score("5111000000", day, 75), _score("2611000000", day, 99)]
|
||||
await REDIS.conn.set(_KEY.format(_sat(today)), json.dumps([{**asdict(x), "day": x.day.isoformat()} for x in scores]))
|
||||
|
||||
async def festivals(client, sido, since):
|
||||
return [{"contentid": "51", "title": "강릉 커피축제", "addr1": "강원 강릉시", "mapy": "37.77", "mapx": "128.90",
|
||||
"eventstartdate": today.strftime("%Y%m%d"), "eventenddate": (today + timedelta(days=7)).strftime("%Y%m%d"),
|
||||
"firstimage": "http://tong.visitkorea.or.kr/c.jpg"}] if sido == "51" else []
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", festivals)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/feed", params={"region": "4113500000"})).json()
|
||||
trip = next(p for p in body["posts"] if p["post_type"] == PostType.DAY_TRIP.value)
|
||||
first, event = trip["slides"]
|
||||
assert "강릉" in first["line"] and "90점" in first["line"]
|
||||
rows = dict((r["label"], r["value"]) for r in first["rows"])
|
||||
assert rows["거리"].startswith("여기서 약 ") and rows["날씨"] == "비 10% · 체감 21° · 맑음"
|
||||
assert "춘천" in trip["caption"]
|
||||
assert event["line"] == "강릉 커피축제" and event["image"] == "https://tong.visitkorea.or.kr/c.jpg"
|
||||
@@ -12,7 +12,7 @@ from common.database.model.models import OpenMeteoHourly, WeatherHourly
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.router import app
|
||||
from services.index_service import _nearest_slot_end_hour, _slot_end_hour, windows_for
|
||||
from services.index_service import _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
|
||||
REGION = "1141000000"
|
||||
|
||||
@@ -31,6 +31,12 @@ def _vilage(*_):
|
||||
return items
|
||||
|
||||
|
||||
def _mid(*_):
|
||||
land = {f"wf{n}{p}": "맑음" for n in range(4, 11) for p in ("Am", "Pm")} | {f"rnSt{n}{p}": 10 for n in range(4, 11) for p in ("Am", "Pm")}
|
||||
ta = {f"taMin{n}": 12 for n in range(4, 11)} | {f"taMax{n}": 22 for n in range(4, 11)}
|
||||
return land, ta
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fakes(monkeypatch):
|
||||
now = now_kst()
|
||||
@@ -41,17 +47,22 @@ def fakes(monkeypatch):
|
||||
"dataTime": now.replace(minute=0).strftime("%Y-%m-%d %H:%M"),
|
||||
}]))
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([]))
|
||||
monkeypatch.setattr(weather_service, "fetch_mid", lambda *a: _async(_mid()))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_ranks_all_27_with_3_day_trend(fakes):
|
||||
async def test_index_list_ranks_all_27_with_today_tomorrow_weekend_trend(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/list", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert len(body["items"]) == 27 and len(body["top3"]) == 3
|
||||
scores = [i["score"] for i in body["items"]]
|
||||
assert scores == sorted(scores, reverse=True)
|
||||
assert all(len(i["trend"]) == 3 for i in body["items"])
|
||||
today = now_kst().date()
|
||||
for i in body["items"]:
|
||||
assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)]
|
||||
assert not any(t["estimated"] for t in i["trend"][:2])
|
||||
assert all(t["estimated"] for t in i["trend"][2:] if date.fromisoformat(t["day"]) > today + timedelta(days=3))
|
||||
assert 0 <= body["weather_score"] <= 100
|
||||
|
||||
|
||||
@@ -67,9 +78,9 @@ async def test_index_detail_has_six_factors_and_rules(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/1", params={"region": REGION})).json()
|
||||
assert body["index"]["code"] == "yajang"
|
||||
assert [f["label"] for f in body["factors"]] == ["기온", "비", "바람", "습도", "공기", "시간대"]
|
||||
assert [f["label"] for f in body["factors"]] == ["기온 알맞음", "비 안 옴", "바람 잔잔", "습도 알맞음", "공기 맑음", "요일 알맞음"]
|
||||
assert sum(f["weight"] for f in body["factors"]) == 100
|
||||
assert body["zero_rules"] == "비 확률 80% 이상 또는 바람 14m/s 이상이면 바로 0점"
|
||||
assert body["zero_rules"] == "비 확률 80% 이상이거나 바람 14m/s 이상이면 0점"
|
||||
assert body["limit"].startswith("모기")
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from services.calc.index_calc import Context, Hour, evaluate, rain_score, sun_score, temp_score, uv_score, view_score, zero_rules_text
|
||||
from services.calc.index_calc import (
|
||||
OUTING_HOURS, Context, DayForecast, Hour, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
|
||||
uv_score, view_score, zero_rules_text,
|
||||
)
|
||||
from services.calc.moon import illumination
|
||||
|
||||
CTX = Context(day=date(2026, 10, 2), is_holiday=False, pm25=10, air_label="좋음", moon=0.5, sunset_score=80, wind_warning=False, lookahead_rain_prob=0)
|
||||
@@ -44,7 +48,7 @@ def test_temp_peaks_at_best_and_loses_8_per_degree_outside():
|
||||
assert temp_score({"type": "range", "lo": 18, "hi": 24, "best": 22}, 22)[0] == 100
|
||||
assert temp_score({"type": "range", "lo": 18, "hi": 24}, 15)[0] == 61
|
||||
assert temp_score({"type": "lower", "zero": 25, "full": 5}, 15)[0] == 50
|
||||
assert temp_score({"type": "range", "lo": 10, "hi": 20, "offset": -6}, 21)[1].startswith("정상 15°")
|
||||
assert temp_score({"type": "range", "lo": 10, "hi": 20, "offset": -6}, 21)[1].startswith("산 정상 기준 15°")
|
||||
|
||||
|
||||
def test_temp_away_rises_outside_comfort():
|
||||
@@ -63,7 +67,28 @@ def test_rain_dry_and_wet():
|
||||
def test_zero_rule_forces_zero_and_cap_limits():
|
||||
assert evaluate(_defn(), [[_h(19, prob=80)]], CTX).score == 0
|
||||
capped = _defn(zero_rules=[{"field": "rain_prob", "op": ">=", "value": 70, "cap": 20}])
|
||||
assert evaluate(capped, [[_h(19, prob=70)]], CTX).score <= 20
|
||||
r = evaluate(capped, [[_h(19, prob=70)]], CTX)
|
||||
assert r.score <= 20 and r.zero_reason == "비 확률 70% 이상이라 최대 20점"
|
||||
assert evaluate(_defn(), [[_h(19, prob=80)]], CTX).zero_reason == "비 확률 80% 이상이라 0점"
|
||||
|
||||
|
||||
def test_lookahead_rain_is_named_in_note():
|
||||
defn = _defn(windows=[{"from": 9, "to": 18, "lookahead_days": 2}])
|
||||
r = evaluate(defn, [[_h(10, prob=0)]], replace(CTX, lookahead_rain_prob=60))
|
||||
assert r.notes["rain"] == "모레까지 비 확률 60%"
|
||||
assert evaluate(defn, [[_h(10, prob=0)]], CTX).notes["rain"] == "비 확률 0%"
|
||||
|
||||
|
||||
def test_air_note_has_unit():
|
||||
assert evaluate(_defn(), [[_h(19)]], CTX).notes["air"] == "초미세먼지 10㎍/㎥, 좋음"
|
||||
|
||||
|
||||
def test_axis_label_reads_outward_as_good():
|
||||
rules = _defn().factor_rules
|
||||
assert [axis_label(a, rules) for a in ("temp", "rain", "wind", "humidity", "air", "time")] == \
|
||||
["기온 알맞음", "비 안 옴", "바람 잔잔", "습도 알맞음", "공기 맑음", "요일 알맞음"]
|
||||
wet = {"temp": {"type": "lower"}, "rain": {"dir": "wet"}, "wind": {"type": "strong"}, "humidity": {"type": "higher"}, "time": {"type": "moon"}}
|
||||
assert [axis_label(a, wet) for a in ("temp", "rain", "wind", "humidity", "time")] == ["추움", "비 옴", "바람 셈", "습도 높음", "달 어두움"]
|
||||
|
||||
|
||||
def test_best_window_is_chosen():
|
||||
@@ -73,7 +98,11 @@ def test_best_window_is_chosen():
|
||||
|
||||
def test_zero_rules_text():
|
||||
assert zero_rules_text([{"field": "rain_prob", "op": ">=", "value": 80}, {"field": "wind_ms", "op": ">=", "value": 14}]) == \
|
||||
"비 확률 80% 이상 또는 바람 14m/s 이상이면 바로 0점"
|
||||
"비 확률 80% 이상이거나 바람 14m/s 이상이면 0점"
|
||||
assert zero_rules_text([{"field": "rain_prob", "op": ">=", "value": 70}, {"field": "warning", "op": "==", "value": "wind"}]) == \
|
||||
"비 확률 70% 이상이거나 강풍 특보가 있으면 0점"
|
||||
assert zero_rules_text([{"field": "rain_prob", "op": ">=", "value": 70, "cap": 20}]) == "비 확률 70% 이상이면 최대 20점"
|
||||
assert zero_rules_text([{"field": "pm25", "op": ">=", "value": 75}]) == "초미세먼지 75㎍/㎥ 이상이면 0점"
|
||||
assert zero_rules_text([]) == "없음 (재미로 보는 지수)"
|
||||
|
||||
|
||||
@@ -118,5 +147,75 @@ def test_gust_and_ground_temperature_zero_rules():
|
||||
assert evaluate(gust, [[_h(19, wind=1.0, gust_ms=10.0)]], CTX).score == 100
|
||||
assert evaluate(gust, [[_h(19, wind=1.0)]], CTX).score == 100 # 값이 없으면 걸리지 않는다
|
||||
ground = [{"field": "ground_c", "op": ">=", "value": 45}]
|
||||
assert zero_rules_text(ground) == "지표면 온도 45° 이상이면 바로 0점"
|
||||
assert evaluate(_defn(zero_rules=ground), [[_h(19, wind=1.0, ground_c=47.0)]], CTX).zero_reason == "지표면 온도 45° 이상이면"
|
||||
assert zero_rules_text(ground) == "지표면 온도 45° 이상이면 0점"
|
||||
assert evaluate(_defn(zero_rules=ground), [[_h(19, wind=1.0, ground_c=47.0)]], CTX).zero_reason == "지표면 온도 45° 이상이라 0점"
|
||||
|
||||
|
||||
def test_estimate_and_labels_cover_openmeteo_axes():
|
||||
r = estimate(_uv_defn(), _fc(), [[19, 20]], CTX)
|
||||
assert r.factors["uv"] == 70 and r.factors["sun"] == 0 and r.factors["view"] == 0
|
||||
assert [axis_label(a, {}) for a in ("uv", "sun", "view")] == ["자외선", "햇빛", "가시거리"]
|
||||
|
||||
|
||||
def _fc(lo=15.0, hi=23.0, am=0, pm=0, sky=Sky.CLEAR):
|
||||
return DayForecast(temp_min_c=lo, temp_max_c=hi, rain_prob_am=am, rain_prob_pm=pm, sky=sky)
|
||||
|
||||
|
||||
def test_hour_temp_follows_min_at_dawn_and_max_mid_afternoon():
|
||||
assert hour_temp(10, 20, 6) == 10 and hour_temp(10, 20, 15) == 20
|
||||
assert 10 < hour_temp(10, 20, 21) < 20 and hour_temp(10, 20, 30) == 10
|
||||
|
||||
|
||||
def test_estimate_is_flagged_and_unknown_factors_are_70():
|
||||
r = estimate(_defn(), _fc(), [[19, 20]], CTX)
|
||||
assert r.estimated is True
|
||||
assert r.factors["wind"] == 70 and r.factors["humidity"] == 70 and r.factors["air"] == 70
|
||||
assert "예상" in r.summary
|
||||
|
||||
|
||||
def test_estimate_uses_rain_prob_of_the_window_half_day():
|
||||
morning, evening = estimate(_defn(), _fc(am=60, pm=0), [[9, 10]], CTX), estimate(_defn(), _fc(am=60, pm=0), [[19, 20]], CTX)
|
||||
assert morning.factors["rain"] == 40 and evening.factors["rain"] == 100
|
||||
|
||||
|
||||
def test_estimate_applies_rain_zero_rule_only():
|
||||
r = estimate(_defn(zero_rules=[{"field": "rain_prob", "op": ">=", "value": 80}, {"field": "wind_ms", "op": ">=", "value": 1}]), _fc(pm=80), [[19]], CTX)
|
||||
assert r.score == 0 and r.zero_reason.startswith("비 확률 80% 이상")
|
||||
|
||||
|
||||
def test_estimate_without_temps_gives_none():
|
||||
assert estimate(_defn(), _fc(lo=None, hi=None), [[19]], CTX) is None
|
||||
|
||||
|
||||
def _day(**kw):
|
||||
return [_h(h, **kw) for h in range(*OUTING_HOURS)]
|
||||
|
||||
|
||||
def test_outing_perfect_day_is_100_and_reason_names_rain_temp_sky():
|
||||
r = outing(_day(wind=1.0))
|
||||
assert r.score == 100 and r.estimated is False
|
||||
assert r.reason == "비 0% · 체감 21° · 맑음"
|
||||
|
||||
|
||||
def test_outing_cloudy_and_hot_days_lose_points():
|
||||
clear, cloudy, hot = outing(_day()), outing(_day(sky=Sky.CLOUDY)), outing(_day(feels=30.0))
|
||||
assert cloudy.score < clear.score and hot.score < clear.score
|
||||
assert "흐림" in cloudy.reason
|
||||
|
||||
|
||||
def test_outing_rain_caps_score():
|
||||
r = outing(_day(prob=70))
|
||||
assert r.score <= 30 and r.capped
|
||||
assert outing([_h(10, prob=30, rain=RainType.RAIN)] + _day()[1:]).score <= 30
|
||||
|
||||
|
||||
def test_outing_needs_all_hours():
|
||||
assert outing(_day()[:3]) is None
|
||||
|
||||
|
||||
def test_outing_estimate_from_mid_forecast():
|
||||
r = outing_estimate(_fc(lo=12, hi=22, am=10, pm=20))
|
||||
assert r.estimated is True and r.factors["wind"] == 70
|
||||
assert r.reason.startswith("비 20% · 낮 ")
|
||||
assert outing_estimate(_fc(pm=60)).score <= 30
|
||||
assert outing_estimate(_fc(lo=None, hi=None)) is None
|
||||
@@ -0,0 +1,73 @@
|
||||
from datetime import date, timedelta
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import kst_midnight
|
||||
from services.calc.index_calc import Context, DayForecast
|
||||
from services.index_service import day_result, slot_days, slot_label
|
||||
|
||||
REGION = SimpleNamespace(lat=37.56, lon=126.97)
|
||||
SAT = date(2026, 10, 10)
|
||||
CTX = Context(day=SAT, is_holiday=False, pm25=10, air_label="좋음", moon=0.5, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
DEFN = SimpleNamespace(
|
||||
weight_temp=40, weight_rain=40, weight_wind=20, weight_humidity=0, weight_air=0, weight_time=0,
|
||||
factor_rules={
|
||||
"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 4, "limit": 12},
|
||||
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100},
|
||||
},
|
||||
zero_rules=[], windows=[{"from": 11, "to": 16}],
|
||||
)
|
||||
FC = {SAT: DayForecast(temp_min_c=12, temp_max_c=22, rain_prob_am=10, rain_prob_pm=20, sky=Sky.CLEAR)}
|
||||
|
||||
|
||||
def _hourly(day: date) -> dict:
|
||||
start = kst_midnight(day)
|
||||
return {
|
||||
start + timedelta(hours=h): SimpleNamespace(
|
||||
forecast_at=start + timedelta(hours=h), feels_c=21, rain_type=RainType.NONE.value, rain_prob=0, wind_ms=1.0, humidity=50, sky=Sky.CLEAR.value,
|
||||
)
|
||||
for h in range(24)
|
||||
}
|
||||
|
||||
|
||||
def _d(day: int) -> date:
|
||||
return date(2026, 10, day)
|
||||
|
||||
|
||||
def test_slots_on_weekdays_are_today_tomorrow_sat_sun():
|
||||
for today in (5, 6, 7, 8):
|
||||
assert slot_days(_d(today)) == [_d(today), _d(today + 1), _d(10), _d(11)]
|
||||
|
||||
|
||||
def test_slots_on_friday_keep_this_sunday_then_next_saturday():
|
||||
assert slot_days(_d(9)) == [_d(9), _d(10), _d(11), _d(17)]
|
||||
|
||||
|
||||
def test_slots_on_saturday_and_sunday_move_to_next_weekend():
|
||||
assert slot_days(_d(10)) == [_d(10), _d(11), _d(17), _d(18)]
|
||||
assert slot_days(_d(11)) == [_d(11), _d(12), _d(17), _d(18)]
|
||||
|
||||
|
||||
def test_slot_labels():
|
||||
today = date(2026, 10, 6)
|
||||
assert [slot_label(d, today) for d in slot_days(today)] == ["오늘", "내일", "토 10.10", "일 10.11"]
|
||||
assert [slot_label(d, _d(9)) for d in slot_days(_d(9))] == ["오늘", "내일", "일 10.11", "토 10.17"]
|
||||
|
||||
|
||||
def test_weekend_in_short_range_uses_hourly_score():
|
||||
r = day_result(DEFN, SAT, REGION, _hourly(SAT), FC, CTX, short=False)
|
||||
assert r.estimated is False and r.factors["wind"] == 100
|
||||
|
||||
|
||||
def test_weekend_beyond_short_range_uses_mid_forecast_estimate():
|
||||
r = day_result(DEFN, SAT, REGION, {}, FC, CTX, short=False)
|
||||
assert r.estimated is True and r.factors["wind"] == 70 and r.factors["rain"] == 80
|
||||
|
||||
|
||||
def test_partial_hourly_falls_back_to_estimate():
|
||||
partial = {k: v for k, v in _hourly(SAT).items() if k.hour < 13}
|
||||
assert day_result(DEFN, SAT, REGION, partial, FC, CTX, short=False).estimated is True
|
||||
|
||||
|
||||
def test_no_mid_forecast_gives_no_score():
|
||||
assert day_result(DEFN, SAT, REGION, {}, {}, CTX, short=False) is None
|
||||
@@ -0,0 +1,49 @@
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
import services.air_service as air_service
|
||||
import services.now_service as now_service
|
||||
import services.season_service as season_service
|
||||
import services.sky_service as sky_service
|
||||
import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
import services.week_service as week_service
|
||||
from router.router import app
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
from services.external.open_meteo import OpenMeteoRequestFailed
|
||||
|
||||
REGION = "1114000000"
|
||||
ENDPOINTS = ["/v1/feed", "/v1/weather/today", "/v1/weather/now", "/v1/sky", "/v1/week", "/v1/index/list", "/v1/season/week"]
|
||||
SOURCES = {
|
||||
"vilage": (weather_service, "fetch_vilage", DataGoKrRequestFailed),
|
||||
"ultra": (now_service, "fetch_ultra", DataGoKrRequestFailed),
|
||||
"air": (air_service, "fetch_realtime", DataGoKrRequestFailed),
|
||||
"warning": (warning_service, "fetch_warning_events", DataGoKrRequestFailed),
|
||||
"clouds": (sky_service, "fetch_clouds", OpenMeteoRequestFailed),
|
||||
"mid": (weather_service, "fetch_mid", DataGoKrRequestFailed),
|
||||
"holiday": (week_service, "fetch_holidays", DataGoKrRequestFailed),
|
||||
"festival": (week_service, "fetch_festivals", DataGoKrRequestFailed),
|
||||
"solar_term": (season_service, "fetch_solar_terms", DataGoKrRequestFailed),
|
||||
}
|
||||
|
||||
|
||||
def _break(monkeypatch, source: str, mode: str) -> None:
|
||||
module, name, exc = SOURCES[source]
|
||||
|
||||
async def fail(*_a, **_k):
|
||||
raise exc(f"{source} down")
|
||||
|
||||
async def empty(*_a, **_k):
|
||||
return ({}, {}) if source == "mid" else []
|
||||
|
||||
monkeypatch.setattr(module, name, {"fail": fail, "empty": empty}[mode])
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("mode", ["fail", "empty"])
|
||||
@pytest.mark.parametrize("source", list(SOURCES))
|
||||
async def test_every_screen_survives_one_broken_source(offline, monkeypatch, source, mode):
|
||||
_break(monkeypatch, source, mode)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
codes = {path: (await client.get(path, params={"region": REGION})).status_code for path in ENDPOINTS}
|
||||
assert all(c == 200 for c in codes.values()), codes
|
||||
@@ -48,8 +48,14 @@ async def test_sky_view_scores_three_days_with_spots(monkeypatch, clean):
|
||||
assert body["sunset"]["grade"] == 4 and body["sunset"]["grade_label"] == "붉음"
|
||||
assert body["sunset"]["confidence"] == 1
|
||||
assert len(body["days"]) == 3
|
||||
assert [s["name"] for s in body["spots"]] == ["망원한강공원", "하늘공원", "선유도공원"]
|
||||
assert [s["name"] for s in body["spots"]] == ["망원한강공원", "선유도공원", "하늘공원"]
|
||||
assert 255 <= body["sunset_azimuth"] <= 280
|
||||
plan = body["plan"]
|
||||
assert plan["verdict"] == "go" and plan["headline"] == "나가 볼 만해요" and plan["when"] in ("오늘", "내일")
|
||||
assert "알맞게" in plan["reason"]
|
||||
assert plan["spot"]["name"] == "망원한강공원" and plan["best_at"]
|
||||
assert [t["kind"] for t in plan["timeline"]] == ["golden", "sun", "peak", "blue"]
|
||||
assert plan["outlook"].endswith("비슷해요")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -65,6 +71,52 @@ async def test_sky_ranking_has_30_spots_sorted(monkeypatch, clean):
|
||||
assert body["items"][0]["rank"] == 1 and body["items"][0]["note"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("region, expected", [
|
||||
("4113500000", "일자산 허브천문공원"), # 분당구: 자기 구엔 명소가 없어도 30km 안 서울 명소
|
||||
("2812500000", "북성포구"), # 인천 제물포구(옛 중구)
|
||||
("2635000000", "중리노을전망대"), # 해운대구: 동쪽 바다보다 서쪽이 트인 영도가 먼저
|
||||
])
|
||||
async def test_sky_spots_by_distance(monkeypatch, clean, region, expected):
|
||||
async def fake_fetch(client, points, days=3):
|
||||
return _fake_response(points, days)
|
||||
|
||||
monkeypatch.setattr(sky_service, "fetch_clouds", fake_fetch)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/sky", params={"region": region})).json()
|
||||
|
||||
spots = body["spots"]
|
||||
assert len(spots) == 3 and spots[0]["name"] == expected
|
||||
assert all(s["distance_km"] <= sky_service.SPOT_RADIUS_KM for s in spots)
|
||||
assert [s["distance_km"] for s in spots] == sorted(s["distance_km"] for s in spots)
|
||||
|
||||
|
||||
def test_nearest_spots_west_first_and_empty_outside_radius():
|
||||
from decimal import Decimal
|
||||
|
||||
from common.database.model.models import SunsetSpot
|
||||
|
||||
def spot(name, lat, west):
|
||||
return SunsetSpot(name=name, description="", lat=Decimal(str(lat)), lon=Decimal("127.0"), sort_order=0 if west else 1)
|
||||
|
||||
spots = [spot("가까운 동쪽", 37.01, False), spot("먼 서쪽", 37.1, True), spot("반경 밖", 37.5, True)]
|
||||
assert [x.spot.name for x in sky_service.nearest_spots(37.0, 127.0, spots)] == ["먼 서쪽", "가까운 동쪽"]
|
||||
assert sky_service.nearest_spots(33.0, 127.0, spots) == []
|
||||
|
||||
|
||||
def test_outlook_points_to_a_better_day_only_when_clearly_better():
|
||||
from datetime import date, timedelta
|
||||
|
||||
from common.database.model.models import SkyScore
|
||||
|
||||
today = date(2026, 10, 6)
|
||||
day = lambda i, v: SkyScore(score_date=today + timedelta(days=i), score=v) # noqa: E731
|
||||
assert sky_service.outlook(day(0, 30), [day(0, 30), day(1, 35), day(2, 72)], today) == "모레가 더 나아요 — 72점, 나가 볼 만해요"
|
||||
assert sky_service.outlook(day(0, 80), [day(0, 80), day(1, 50), day(2, 40)], today).startswith("오늘이 가장 나아요")
|
||||
assert sky_service.outlook(day(0, 50), [day(0, 50), day(1, 55), day(2, 45)], today) == "내일·모레도 비슷해요"
|
||||
assert sky_service.outlook(day(2, 50), [day(2, 50)], today) == ""
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_clouds_are_stored_by_region_with_only_needed_hours(monkeypatch, clean):
|
||||
async def fake_fetch(client, points, days=3):
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
from datetime import datetime, timezone
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
|
||||
from common.enums import Confidence, SkyGrade, SkyType
|
||||
from common.utils.geo import destination, haversine_km
|
||||
from services.calc.sky_score import Layers, best_times, confidence, grade, score
|
||||
from services.calc.sky_score import GRADE_LABEL, Layers, best_times, confidence, grade, reason, score, sunset_timeline, verdict
|
||||
from services.calc.sun import sun_times
|
||||
|
||||
CLEAR = Layers(0, 0, 0)
|
||||
|
||||
@@ -43,3 +44,24 @@ def test_sunset_best_times_order():
|
||||
dusk = datetime(2026, 10, 2, 9, 41, tzinfo=timezone.utc)
|
||||
labels = [t["label"] for t in best_times(SkyType.SUNSET, sunset, dusk, 50)]
|
||||
assert labels == ["해 져요", "가장 붉을 때", "보랏빛 하늘"]
|
||||
|
||||
|
||||
def test_reason_names_what_decided_the_score():
|
||||
canvas = Layers(low=0, mid=20, high=50)
|
||||
assert "알맞게" in reason(canvas, CLEAR)
|
||||
assert "먼 하늘" in reason(canvas, Layers(low=90, mid=50, high=0))
|
||||
assert "낮은 구름" in reason(Layers(100, 0, 0), CLEAR)
|
||||
assert "거의 없어" in reason(CLEAR, CLEAR)
|
||||
|
||||
|
||||
def test_verdict_bands_and_gray_label_is_not_weather_word():
|
||||
assert [verdict(v) for v in (60, 59, 40, 39)] == ["go", "maybe", "maybe", "rest"]
|
||||
assert GRADE_LABEL[SkyGrade.GRAY] != "흐림"
|
||||
|
||||
|
||||
def test_sunset_timeline_runs_golden_to_blue():
|
||||
sun = sun_times(date(2026, 10, 6), 37.56, 126.91)
|
||||
rows = sunset_timeline(sun.golden_start_at, sun.sunset_at, sun.sunset_at + timedelta(minutes=15), sun.dusk_end_at)
|
||||
assert [r["kind"] for r in rows] == ["golden", "sun", "peak", "blue"]
|
||||
ats = [datetime.fromisoformat(r["at"]) for r in rows]
|
||||
assert ats == sorted(ats) and 15 <= (ats[1] - ats[0]).total_seconds() / 60 <= 60
|
||||
@@ -52,7 +52,7 @@ async def test_today_fetches_stores_and_returns_8_slots(monkeypatch, clean_regio
|
||||
assert body["result"]["success"] is True
|
||||
assert [s["label"] for s in body["slots"]] == ["0시", "3시", "6시", "9시", "12시", "15시", "18시", "21시"]
|
||||
assert all(s["temp_c"] == 18 for s in body["slots"])
|
||||
assert body["slots"][0]["icon"] == "stars"
|
||||
assert body["slots"][0]["icon"] == "moon"
|
||||
assert body["slots"][6]["icon"] == "sunset" and body["slots"][6]["note"] == "노을"
|
||||
assert len(calls) == 2
|
||||
|
||||
@@ -90,3 +90,19 @@ async def test_today_fetch_failure_without_data_is_external_error(monkeypatch, c
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/weather/today", params={"region": REGION})).json()
|
||||
assert body["result"]["desc"] == "EXTERNAL_API_ERROR"
|
||||
|
||||
|
||||
def test_slot_view_shows_sunset_only_when_clear():
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import KST
|
||||
from services.weather_service import _slot_view
|
||||
|
||||
at = datetime(2026, 10, 2, 18, tzinfo=KST)
|
||||
sun = SimpleNamespace(sunrise_at=at.replace(hour=6), sunset_at=at.replace(minute=10), dusk_end_at=at.replace(minute=40))
|
||||
row = lambda sky: SimpleNamespace(rain_type=RainType.NONE.value, sky=sky.value, temp_c=18, rain_prob=0) # noqa: E731
|
||||
assert _slot_view(at, row(Sky.CLEAR), sun)[0::2] == ("sunset", "노을")
|
||||
assert _slot_view(at, row(Sky.CLOUDY), sun)[0::2] == ("cloud", "흐림")
|
||||
assert _slot_view(at, row(Sky.PARTLY), sun)[0::2] == ("cloud", "구름 많음")
|
||||
@@ -12,6 +12,7 @@ from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from router.router import app
|
||||
from services.external.kma import latest_mid_base, mid_word, parse_mid
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
from services.week_service import _status
|
||||
|
||||
REGION = "1144000000"
|
||||
@@ -28,7 +29,7 @@ def test_parse_mid_days_from_base():
|
||||
land = {"wf4Am": "맑음", "wf4Pm": "흐리고 비", "rnSt4Am": 10, "rnSt4Pm": 60}
|
||||
ta = {"taMin4": 10, "taMax4": 22}
|
||||
day = parse_mid(land, ta, base)[date(2026, 10, 6)]
|
||||
assert day == {"temp_min_c": 10.0, "temp_max_c": 22.0, "sky": Sky.CLOUDY, "rain_type": RainType.RAIN, "rain_prob": 60}
|
||||
assert day == {"temp_min_c": 10.0, "temp_max_c": 22.0, "sky": Sky.CLOUDY, "rain_type": RainType.RAIN, "rain_prob": 60, "rain_prob_am": 10, "rain_prob_pm": 60}
|
||||
|
||||
|
||||
def test_latest_mid_base():
|
||||
@@ -70,15 +71,16 @@ def _mid(*_):
|
||||
def fakes(monkeypatch):
|
||||
today = now_kst().date()
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage()))
|
||||
monkeypatch.setattr(week_service, "fetch_mid", lambda *a: _async(_mid()))
|
||||
monkeypatch.setattr(weather_service, "fetch_mid", lambda *a: _async(_mid()))
|
||||
monkeypatch.setattr(week_service, "fetch_holidays", lambda c, y, m: _async(
|
||||
[{"holiday_date": today + timedelta(days=1), "name": "테스트공휴일"}] if m == (today + timedelta(days=1)).month and y == today.year else []
|
||||
))
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda *a: _async([
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda c, sido, since: _async([
|
||||
{"contentid": "1", "title": "가을 축제", "addr1": "서울 마포구", "eventstartdate": (today + timedelta(days=3)).strftime("%Y%m%d"),
|
||||
"eventenddate": (today + timedelta(days=4)).strftime("%Y%m%d")},
|
||||
"eventenddate": (today + timedelta(days=4)).strftime("%Y%m%d"), "firstimage": "http://tong.visitkorea.or.kr/a.jpg"},
|
||||
{"contentid": "2", "title": "상설 전시", "addr1": "서울", "eventstartdate": "20250101", "eventenddate": "20261231"},
|
||||
]))
|
||||
] if sido == "11" else []))
|
||||
monkeypatch.setattr(week_service, "fetch_exhibitions", lambda *a: _async([]))
|
||||
monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([]))
|
||||
monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([]))
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([]))
|
||||
@@ -101,6 +103,59 @@ async def test_events_exclude_long_running_and_add_weather_fit(fakes):
|
||||
body = (await client.get("/v1/week/event/list", params={"region": REGION})).json()
|
||||
assert [e["name"] for e in body["events"]] == ["가을 축제"]
|
||||
assert body["events"][0]["fit"]
|
||||
assert body["events"][0]["image"] == "https://tong.visitkorea.or.kr/a.jpg"
|
||||
assert body["events"][0]["image_credit"] == "ⓒ한국관광공사"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_events_include_culture_exhibitions_with_their_credit(fakes, monkeypatch):
|
||||
today = now_kst().date()
|
||||
monkeypatch.setattr(week_service, "fetch_exhibitions", lambda *a: _async([{
|
||||
"seq": "123", "title": "가을 특별전", "place": "테스트 미술관", "startDate": (today + timedelta(days=1)).strftime("%Y%m%d"),
|
||||
"endDate": (today + timedelta(days=20)).strftime("%Y%m%d"), "thumbnail": "http://www.culture.go.kr/x.jpg", "gpsX": "126.97", "gpsY": "37.57",
|
||||
}]))
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": REGION})).json()
|
||||
by_name = {e["name"]: e for e in body["events"]}
|
||||
assert set(by_name) == {"가을 축제", "가을 특별전"}
|
||||
assert by_name["가을 특별전"]["image"] == "https://www.culture.go.kr/x.jpg"
|
||||
assert by_name["가을 특별전"]["image_credit"] == "ⓒ한국문화정보원"
|
||||
assert by_name["가을 축제"]["image_credit"] == "ⓒ한국관광공사"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_events_keep_tour_festivals_when_culture_api_fails(fakes, monkeypatch):
|
||||
async def fail(*_):
|
||||
raise DataGoKrRequestFailed("realm2 30 SERVICE_KEY_IS_NOT_REGISTERED_ERROR")
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_exhibitions", fail)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": REGION})).json()
|
||||
assert [e["name"] for e in body["events"]] == ["가을 축제"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_events_pick_within_30km_across_sido(fakes, monkeypatch):
|
||||
"""분당 사용자: 서울 잠실(약 15km)은 들어오고 같은 경기도 연천(약 80km)은 빠진다. 좌표 없는 행사는 같은 시도만."""
|
||||
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 = {
|
||||
"11": [{"contentid": "11", "title": "잠실 축제", "addr1": "서울 송파구", "mapy": "37.5133", "mapx": "127.1001", **span},
|
||||
{"contentid": "12", "title": "좌표 없는 서울 축제", "addr1": "서울", **span}],
|
||||
"41": [{"contentid": "41", "title": "연천 축제", "addr1": "경기 연천군", "mapy": "38.0963", "mapx": "127.0750", **span},
|
||||
{"contentid": "42", "title": "좌표 없는 경기 축제", "addr1": "경기", **span}],
|
||||
}
|
||||
asked = []
|
||||
|
||||
def festivals(client, sido, since):
|
||||
asked.append(sido)
|
||||
return _async(by_sido.get(sido, []))
|
||||
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", festivals)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/event/list", params={"region": "4113500000"})).json()
|
||||
assert {"11", "41"} <= set(asked) and "26" not in asked
|
||||
assert {e["name"] for e in body["events"]} == {"잠실 축제", "좌표 없는 경기 축제"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -111,3 +166,26 @@ async def test_places_put_indoor_first_on_rainy_day(fakes):
|
||||
body = (await client.get("/v1/week/place/list", params={"region": REGION, "day": rainy_day})).json()
|
||||
assert body["rainy"] is True
|
||||
assert body["places"][0]["is_outdoor"] is False and body["places"][0]["is_good"] is True
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_weekend_ranking_scores_30_spots_and_caches(fakes, monkeypatch):
|
||||
from services.weekend_rank import weekend_days
|
||||
|
||||
calls = []
|
||||
|
||||
def vilage(*a):
|
||||
calls.append(a)
|
||||
return _async(_vilage())
|
||||
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", vilage)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/ranking")).json()
|
||||
first = len(calls)
|
||||
again = (await client.get("/v1/week/ranking")).json()
|
||||
days = body["days"]
|
||||
assert [d["day"] for d in days] == [d.isoformat() for d in weekend_days(now_kst().date())]
|
||||
for d in days:
|
||||
assert len(d["items"]) == 30 and [x["rank"] for x in d["items"]] == list(range(1, 31))
|
||||
assert d["items"][0]["reason"].startswith("비 ") and 0 <= d["items"][0]["score"] <= 100
|
||||
assert first >= 34 and len(calls) == first and again == body
|
||||
@@ -0,0 +1,81 @@
|
||||
from datetime import date, datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from services.week_service import DayPlan, EventItem
|
||||
from services.weekend_plan import day_plan, forecast, pick_events
|
||||
|
||||
SAT, SUN = date(2026, 10, 10), date(2026, 10, 11)
|
||||
|
||||
|
||||
def _day(d: date, lo=12.0, hi=26.0, rainy=False, rain_hours=None, prob=10) -> DayPlan:
|
||||
weekday = "토" if d.weekday() == 5 else "일"
|
||||
return DayPlan(day=d, weekday=weekday, holiday=None, icon="rain" if rainy else "sun", temp_min_c=lo, temp_max_c=hi,
|
||||
headline="", summary="", pick="", rain_hours=rain_hours, is_rainy=rainy, rain_prob=prob)
|
||||
|
||||
|
||||
def _event(name, start, end, dist, image="https://img/x.jpg") -> EventItem:
|
||||
e = SimpleNamespace(event_id=hash(name), name=name, icon="fireworks", start_date=start, end_date=end, place_name="경기도 고양시 일산동구 호수로 595", image_url=image, source_id="1")
|
||||
return EventItem(event=e, status="live", status_label="진행 중", fit=None, distance_km=dist)
|
||||
|
||||
|
||||
def test_forecast_both_clear_with_big_gap_warns_about_jacket():
|
||||
f = forecast([_day(SAT), _day(SUN, lo=13)])
|
||||
assert f.line.startswith("토·일 둘 다 맑음!")
|
||||
assert "겉옷" in f.tip and "12°" in f.tip
|
||||
|
||||
|
||||
def test_forecast_one_rainy_day_picks_the_other():
|
||||
f = forecast([_day(SAT, rainy=True, prob=70), _day(SUN)])
|
||||
assert f.line.startswith("일요일이 정답!")
|
||||
assert f.tip == "토요일은 비 70%, 우산 꼭 챙겨요!"
|
||||
|
||||
|
||||
def test_saturday_plan_runs_morning_to_sunset_with_nearest_event():
|
||||
events = [_event("먼 축제", SAT, SUN, 40.0), _event("가까운 축제", SAT, SUN, 12.0)]
|
||||
card = day_plan(_day(SAT), datetime(2026, 10, 10, 18, 3, tzinfo=KST), pick_events(SAT, events), 13.0)
|
||||
assert [s.time for s in card.steps] == ["오전", "오전", "12~16시", "오후", "18:03"]
|
||||
assert card.steps[1].title == "가까운 축제"
|
||||
assert card.steps[-1].icon == "sunset"
|
||||
assert card.eyebrow == "토요일 10.10 · 이렇게 놀아요"
|
||||
|
||||
|
||||
def test_sunday_plan_leads_with_events_ending_today_and_ends_early():
|
||||
events = [_event("이어지는 축제", SAT, date(2026, 10, 20), 5.0), _event("끝나는 축제", date(2026, 10, 1), SUN, 30.0)]
|
||||
card = day_plan(_day(SUN), None, pick_events(SUN, events), 13.0)
|
||||
assert card.line == "끝나는 축제\n오늘이 마지막 날!"
|
||||
assert card.steps[-1].title == "일찍 귀가 추천" and "13°" in card.steps[-1].sub
|
||||
assert any(s.title == "끝나는 축제" and s.sub.startswith("오늘이 마지막 날") for s in card.steps)
|
||||
|
||||
|
||||
def test_afternoon_rain_moves_outdoor_time_before_it():
|
||||
card = day_plan(_day(SAT, rainy=True, rain_hours=(15, 19), prob=60), None, [], None)
|
||||
assert [s.time for s in card.steps[:2]] == ["~15시", "15~19시"]
|
||||
assert card.line.startswith("비 오는 토요일")
|
||||
|
||||
|
||||
def test_saturday_ignores_ending_hook_and_sunday_skips_saturday_events():
|
||||
near = _event("가까운 축제", SAT, SUN, 3.0)
|
||||
ends_sat = _event("토요일 끝", SAT, SAT, 50.0)
|
||||
far = _event("먼 축제", SAT, SUN, 40.0)
|
||||
sat = pick_events(SAT, [ends_sat, near, far])
|
||||
assert [e.event.name for e in sat] == ["가까운 축제", "먼 축제"]
|
||||
assert day_plan(_day(SAT), None, sat, None).line.startswith("해 좋은 낮")
|
||||
assert pick_events(SUN, [near, far], frozenset(e.event.event_id for e in sat)) == []
|
||||
|
||||
|
||||
def test_cloudy_weekend_is_not_called_clear():
|
||||
cloudy = [_day(SAT), _day(SUN)]
|
||||
for d in cloudy:
|
||||
d.icon = "cloud"
|
||||
f = forecast(cloudy)
|
||||
assert "맑음" not in f.line
|
||||
card = day_plan(cloudy[0], None, [], None)
|
||||
assert all(s.icon != "sun" for s in card.steps) and not card.line.startswith("해 좋은")
|
||||
|
||||
|
||||
def test_event_step_uses_event_icon():
|
||||
e = _event("가까운 축제", SAT, SUN, 3.0)
|
||||
e.event.icon = "photo"
|
||||
card = day_plan(_day(SAT), None, [e], None)
|
||||
assert next(s for s in card.steps if s.title == "가까운 축제").icon == "photo"
|
||||
Reference in new issue
Block a user