Merge remote-tracking branch 'origin/main' into feat/watch-summary

This commit is contained in:
HyeongBaeYang committed 2026-10-07 14:29:43 +09:00
commit f6ec296130
84 files changed
+3406 -879

No files matched your search

+17 -3
View File
@@ -2,8 +2,9 @@ import asyncio
import os
# 개발 DB·Redis 를 건드리지 않도록 테스트 전용 DB(<이름>_test)와 Redis 15번을 쓴다. 앱 import 전에 정해야 한다.
# 여러 작업 폴더에서 동시에 돌릴 땐 TEST_DB_NAME·TEST_REDIS_DB 를 폴더마다 다르게 준다 (시작할 때 DB 를 지우고 Redis 를 비우므로).
os.environ["DB_NAME"] = os.environ.get("TEST_DB_NAME", "nalssigak_test")
os.environ["REDIS_DB"] = "15"
os.environ["REDIS_DB"] = os.environ.get("TEST_REDIS_DB", "15")
import asyncpg # noqa: E402
import pytest # noqa: E402
@@ -41,7 +42,7 @@ def anyio_backend():
_VOLATILE = (
"weather_hourly", "weather_daily", "cloud_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
"sky_score", "index_score", "post", "post_like", "post_save", "comment", "comment_like", "holiday", "solar_term", "users",
)
@@ -67,8 +68,9 @@ async def _async(v):
@pytest.fixture
def offline(monkeypatch):
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
from datetime import timedelta
from datetime import datetime, timedelta, timezone
import scheduler.jobs as jobs
import services.air_service as air_service
import services.now_service as now_service
import services.season_service as season_service
@@ -95,6 +97,17 @@ def offline(monkeypatch):
h |= {f"cloud_cover_low_{m}": [0] * len(times), f"cloud_cover_mid_{m}": [20] * len(times), f"cloud_cover_high_{m}": [50] * len(times)}
return _async([{"hourly": h} for _ in points])
def openmeteo_weather(client, points, days=4):
start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
times = [(start + timedelta(hours=h)).strftime("%Y-%m-%dT%H:00") for h in range(24 * days)]
n = len(times)
h = {
"time": times, "uv_index": [3.0] * n, "uv_index_clear_sky": [3.0] * n, "visibility": [20000.0] * n,
"wind_gusts_10m": [4.0] * n, "pressure_msl": [1015.0] * n, "sunshine_duration": [3600.0] * n,
"shortwave_radiation": [300.0] * n, "soil_temperature_0cm": [18.0] * n,
}
return _async([{"hourly": h} for _ in points])
clear = [("TMP", "20"), ("SKY", "1"), ("PTY", "0"), ("POP", "0"), ("PCP", "강수없음"), ("REH", "50"), ("WSD", "1.5")]
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(hourly(24 * 4, clear)))
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(hourly(24 * 2, [("PTY", "0"), ("RN1", "강수없음"), ("T1H", "20")])))
@@ -105,6 +118,7 @@ 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(weather_service, "fetch_mid", lambda *a: _async(({}, {})))
monkeypatch.setattr(week_service, "fetch_holidays", lambda *a: _async([]))
monkeypatch.setattr(week_service, "fetch_festivals", lambda c, sido, since: _async([{
+95
View File
@@ -0,0 +1,95 @@
import asyncio
import time
import httpx
import pytest
from config.settings import settings
from services.external import data_go_kr, guard, open_meteo
from services.external.data_go_kr import DataGoKrRequestFailed, get_body
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds
URL = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst"
@pytest.fixture
def fast(monkeypatch):
monkeypatch.setattr(settings, "data_go_kr_service_key", "fake-key")
monkeypatch.setattr(data_go_kr, "_BACKOFF_SEC", 0)
monkeypatch.setattr(guard, "BUDGET_SEC", 0.3)
def _client(handler) -> httpx.AsyncClient:
return httpx.AsyncClient(transport=httpx.MockTransport(handler))
def _ok(_req: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"response": {"header": {"resultCode": "00"}, "body": {"items": []}}})
@pytest.mark.anyio
async def test_hanging_api_gives_up_within_budget_then_is_skipped(fast):
calls = []
async def hang(req: httpx.Request) -> httpx.Response:
calls.append(1)
await asyncio.sleep(5)
return _ok(req)
async with _client(hang) as client:
start = time.perf_counter()
with pytest.raises(DataGoKrRequestFailed, match="no answer within"):
await get_body(client, URL, {})
assert time.perf_counter() - start < 1
start = time.perf_counter()
with pytest.raises(DataGoKrRequestFailed, match="skipped"):
await get_body(client, URL, {})
assert time.perf_counter() - start < 0.1
assert len(calls) == 1
@pytest.mark.anyio
async def test_refused_connection_is_skipped_but_other_apis_still_called(fast):
def handler(req: httpx.Request) -> httpx.Response:
if req.url.path.endswith("getVilageFcst"):
raise httpx.ConnectError("refused")
return _ok(req)
async with _client(handler) as client:
with pytest.raises(DataGoKrRequestFailed, match="failed after 3 attempts: ConnectError"):
await get_body(client, URL, {})
with pytest.raises(DataGoKrRequestFailed, match="skipped"):
await get_body(client, URL, {})
assert await get_body(client, URL.replace("getVilageFcst", "getUltraSrtFcst"), {}) == {"items": []}
@pytest.mark.anyio
async def test_error_code_from_api_does_not_pause_it(fast):
calls = []
def handler(req: httpx.Request) -> httpx.Response:
calls.append(1)
return httpx.Response(200, json={"response": {"header": {"resultCode": "03", "resultMsg": "NO_DATA"}}})
async with _client(handler) as client:
for _ in range(2):
with pytest.raises(DataGoKrRequestFailed, match="03 NO_DATA"):
await get_body(client, URL, {})
assert len(calls) == 2
@pytest.mark.anyio
async def test_open_meteo_down_is_skipped(monkeypatch):
monkeypatch.setattr(open_meteo, "_BUDGET_SEC", 0.3)
calls = []
async def hang(req: httpx.Request) -> httpx.Response:
calls.append(1)
await asyncio.sleep(5)
return httpx.Response(200, json=[])
async with _client(hang) as client:
for _ in range(2):
with pytest.raises(OpenMeteoRequestFailed):
await fetch_clouds(client, [(37.5, 127.0)])
assert len(calls) == 1
+24 -1
View File
@@ -3,9 +3,10 @@ from datetime import date
import httpx
import pytest
from common.enums import EventKind
from config.settings import settings
from services.external import culture_api
from services.external.culture_api import fetch_exhibitions, parse_exhibitions
from services.external.culture_api import CONCERT, 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>
@@ -23,6 +24,7 @@ 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)
monkeypatch.setattr(culture_api, "_PAGE_GAP_SEC", 0)
def _client(handler) -> httpx.AsyncClient:
@@ -45,6 +47,19 @@ async def test_fetch_exhibitions_pages_through_xml(key):
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_asks_concert_realm(key):
seen = []
def handler(req: httpx.Request) -> httpx.Response:
seen.append(dict(req.url.params))
return httpx.Response(200, text=_page([], 0))
async with _client(handler) as client:
assert await fetch_exhibitions(client, "26", date(2026, 10, 6), 30, CONCERT) == []
assert seen[0]["realmCode"] == "B000" and seen[0]["sido"] == "부산"
@pytest.mark.anyio
async def test_fetch_exhibitions_reports_unregistered_key(key):
body = ("<OpenAPI_ServiceResponse><cmmMsgHeader><errMsg>SERVICE_KEY_IS_NOT_REGISTERED_ERROR</errMsg>"
@@ -76,4 +91,12 @@ def test_parse_exhibitions_maps_fields_and_drops_ended_or_duplicate():
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 rows[0]["kind"] == EventKind.EXHIBITION
assert all(len(r["source_id"]) <= 20 for r in rows)
def test_parse_exhibitions_unescapes_title_and_place():
items = [{"seq": "601", "title": "테스트 콘서트 &lt;가을밤&gt;", "place": "테스트 홀 &amp; 라운지", "startDate": "20261010", "endDate": "20261010"}]
rows = parse_exhibitions(items, "11", date(2026, 10, 6), CONCERT)
assert rows[0]["name"] == "테스트 콘서트 <가을밤>" and rows[0]["place_name"] == "테스트 홀 & 라운지"
assert rows[0]["kind"] == EventKind.CONCERT and rows[0]["icon"] == "concert"
+83
View File
@@ -0,0 +1,83 @@
import httpx
import pytest
import scheduler.jobs as jobs
from common.cache.redis_client import REDIS
from common.enums import ErrorType
from config.settings import settings
from services.external import teams_webhook
async def _async(v):
return v
@pytest.fixture
def sent(monkeypatch):
calls = []
async def send(title, detail):
calls.append((title, detail))
return True
monkeypatch.setattr(jobs.teams_webhook, "send", send)
monkeypatch.setattr(jobs, "_SIDO_GAP_SEC", 0)
monkeypatch.setattr(jobs, "refresh_popups", lambda: _async(ErrorType.SUCCESS))
return calls
@pytest.mark.anyio
async def test_refresh_events_sums_kinds_and_notifies(sent, monkeypatch):
monkeypatch.setattr(jobs, "collect_events", lambda sido, today: _async((ErrorType.SUCCESS, {"festival": 2, "exhibition": 1, "concert": 3})))
assert await jobs.refresh_events() is ErrorType.SUCCESS
n = len(jobs.SIDO_NAME)
assert sent[0][0] == "행사 수집 완료"
assert f"축제 {2 * n}, 전시 {n}, 콘서트 {3 * n}, 팝업 0" in sent[0][1]
assert await REDIS.conn.exists(jobs.EVENTS_DONE)
@pytest.mark.anyio
async def test_refresh_events_reports_failed_sido_and_does_not_mark_done(sent, monkeypatch):
monkeypatch.setattr(jobs, "collect_events", lambda sido, today: _async(
(ErrorType.EXTERNAL_API_ERROR, {}) if sido == "46" else (ErrorType.SUCCESS, {"festival": 1, "exhibition": 0, "concert": 0})))
assert await jobs.refresh_events() is ErrorType.EXTERNAL_API_ERROR
assert sent[0][0] == "행사 수집 일부 실패" and "실패한 시도: 전남" in sent[0][1]
assert not await REDIS.conn.exists(jobs.EVENTS_DONE)
@pytest.mark.anyio
async def test_refresh_events_skips_when_done_within_7_days(sent, monkeypatch):
await REDIS.conn.set(jobs.EVENTS_DONE, "2026-10-05")
monkeypatch.setattr(jobs, "collect_events", lambda *a: pytest.fail("수집하면 안 된다"))
assert await jobs.refresh_events(only_if_missing=True) is ErrorType.SUCCESS
assert sent == []
@pytest.mark.anyio
async def test_teams_send_posts_adaptive_card_only_when_configured(monkeypatch):
posted = []
class Client:
def __init__(self, **_):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *_):
return False
async def post(self, url, json):
posted.append((url, json))
return httpx.Response(202, request=httpx.Request("POST", url))
monkeypatch.setattr(teams_webhook.httpx, "AsyncClient", Client)
monkeypatch.setattr(settings, "teams_webhook_url", "")
assert await teams_webhook.send("t", "d") is False
monkeypatch.setattr(settings, "teams_webhook_url", "http://example.test/hook")
assert await teams_webhook.send("t", "d") is False
monkeypatch.setattr(settings, "teams_webhook_url", "https://example.test/hook")
assert await teams_webhook.send("행사 수집 완료", "축제 1") is True
card = posted[0][1]["attachments"][0]["content"]
assert [b["text"] for b in card["body"]] == ["행사 수집 완료", "축제 1"]
assert len(posted) == 1
+5
View File
@@ -6,10 +6,12 @@ from sqlalchemy import text
from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import PostType
from common.utils.kma_time import now_kst
from crud.feed_crud import FeedCRUD
from crud.season_crud import SeasonCRUD
from router.router import app
from services.feed_service import build_feed_day
from services.week_service import collect_events
REGION = "1114000000"
@@ -51,6 +53,7 @@ def test_weekends_groups_this_and_next_weekend():
@pytest.mark.anyio
async def test_feed_assembles_hero_stories_posts_and_bands(offline):
await collect_events("11", now_kst().date())
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/feed", params={"region": REGION})).json()
assert body["result"]["success"] is True
@@ -160,6 +163,7 @@ async def test_build_day_makes_every_card_at_three():
@pytest.mark.anyio
async def test_feed_has_quote_and_no_adjacent_same_type(offline):
await collect_events("11", now_kst().date())
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/feed", params={"region": REGION})).json()
articles = (await client.get("/v1/season/article/list")).json()
@@ -324,6 +328,7 @@ async def test_feed_has_day_trip_card_with_city_event(offline, monkeypatch):
"firstimage": "http://tong.visitkorea.or.kr/c.jpg"}] if sido == "51" else []
monkeypatch.setattr(week_service, "fetch_festivals", festivals)
await week_service.collect_events("51", today)
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)
+113 -1
View File
@@ -1,4 +1,5 @@
from datetime import date, timedelta
from types import SimpleNamespace
import pytest
from httpx import ASGITransport, AsyncClient
@@ -6,9 +7,12 @@ from httpx import ASGITransport, AsyncClient
import services.air_service as air_service
import services.warning_service as warning_service
import services.weather_service as weather_service
from common.database.db_session_manager import DB_SESSION_MNG
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 slot_days, slot_label
from services.index_service import _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
REGION = "1141000000"
@@ -78,3 +82,111 @@ async def test_index_detail_has_six_factors_and_rules(fakes):
assert sum(f["weight"] for f in body["factors"]) == 100
assert body["zero_rules"] == "비 확률 80% 이상이거나 바람 14m/s 이상이면 0점"
assert body["limit"].startswith("모기")
@pytest.mark.anyio
async def test_index_detail_has_four_score_bands_with_today_marked(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()
bands = body["bands"]
assert [(b["low"], b["high"]) for b in bands] == [(0, 29), (30, 59), (60, 79), (80, 100)]
assert all(b["text"] for b in bands)
current = [b for b in bands if b["current"]]
assert len(current) == 1 and current[0]["low"] <= body["index"]["score"] <= current[0]["high"]
def test_every_index_has_four_band_sentences():
import json
import os
seed = json.load(open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "index_definition.json"), encoding="utf-8"))
assert all(sorted(d["sentences"], key=int) == ["0", "30", "60", "80"] and all(d["sentences"].values()) for d in seed)
def _om_row(at, **over):
row = {
"region_code": REGION, "forecast_at": at, "fetched_at": now_kst(), "uv_index": 2.0, "uv_index_clear_sky": 2.0,
"visibility_m": 25000, "wind_gust_ms": 5.0, "pressure_hpa": 1015.0, "soil_temp_c": 20.0,
"sunshine_s": 10800, "shortwave_avg_wm2": 500, "shortwave_max_wm2": 600,
}
return row | over
async def _put_om(rows):
await DB_SESSION_MNG.execute_lambda_run([lambda s: WeatherCRUD().upsert_openmeteo(s, rows)])
async def _laundry_sun(client):
items = (await client.get("/v1/index/list", params={"region": REGION})).json()["items"]
index_id = next(i["index_id"] for i in items if i["code"] == "laundry")
body = (await client.get(f"/v1/index/{index_id}", params={"region": REGION})).json()
return {f["axis"]: f for f in body["factors"]}
def test_slot_end_hours_for_covering_and_nearest_slot():
hours = (0, 2, 3, 7, 8, 9, 10, 11, 12, 15, 21, 23, 26)
assert [_slot_end_hour(h) for h in hours] == [3, 3, 6, 9, 9, 12, 12, 12, 15, 18, 24, 24, 27]
assert [_nearest_slot_end_hour(h) for h in hours] == [0, 3, 3, 9, 9, 9, 12, 12, 12, 15, 21, 24, 27]
def test_windows_attach_instant_values_from_nearest_slot_and_sunshine_from_covering_slot():
day = date(2026, 10, 6)
start = kst_midnight(day)
by_at = {
start + timedelta(hours=h): WeatherHourly(
forecast_at=start + timedelta(hours=h), feels_c=20, rain_type=1, rain_prob=0, wind_ms=1.0, humidity=50, sky=1
)
for h in range(7, 16)
}
by_om = {
start + timedelta(hours=end): OpenMeteoHourly(
forecast_at=start + timedelta(hours=end), uv_index=uv, sunshine_s=sun, visibility_m=12000, wind_gust_ms=7.5, soil_temp_c=20.0
)
for end, uv, sun in ((9, 1.0, 1800), (12, 2.0, 5400), (15, 3.0, 9000), (18, 4.0, 10800))
}
morning, noon = windows_for(SimpleNamespace(windows=[{"from": 7, "to": 9}, {"from": 11, "to": 16}]), day, None, by_at, by_om)
assert [h.uv for h in morning] == [1.0, 1.0]
assert [h.uv for h in noon] == [2.0, 2.0, 3.0, 3.0, 3.0] # 순간값은 가장 가까운 구간 (11·12시→12시, 13~15시→15시)
assert [h.sunshine_ratio for h in noon] == [0.5, 9000 / 10800, 9000 / 10800, 9000 / 10800, 1.0] # 일조는 덮는 구간 (직전 3시간 합)
assert morning[0].visibility_km == 12.0 and morning[0].gust_ms == 7.5 and morning[0].ground_c == 20.0
no_om = windows_for(SimpleNamespace(windows=[{"from": 7, "to": 9}]), day, None, by_at, None)[0]
assert all(h.uv is None and h.sunshine_ratio is None for h in no_om)
def test_dark_slots_count_as_no_sun_not_unknown():
day = date(2026, 10, 6)
start = kst_midnight(day)
by_at = {
start + timedelta(hours=h): WeatherHourly(
forecast_at=start + timedelta(hours=h), feels_c=20, rain_type=1, rain_prob=0, wind_ms=1.0, humidity=50, sky=1
)
for h in (22, 23)
}
by_om = {start + timedelta(hours=24): OpenMeteoHourly(forecast_at=start + timedelta(hours=24), uv_index=None, sunshine_s=None, visibility_m=20000)}
hours = windows_for(SimpleNamespace(windows=[{"from": 22, "to": 24}]), day, None, by_at, by_om)[0]
assert [(h.uv, h.sunshine_ratio, h.visibility_km) for h in hours] == [(0.0, 0.0, 20.0)] * 2
@pytest.mark.anyio
async def test_new_axis_shows_only_for_weighted_indices_and_unknown_without_data(fakes):
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
laundry = await _laundry_sun(client)
yajang = (await client.get("/v1/index/1", params={"region": REGION})).json()["factors"]
assert laundry["sun"]["weight"] == 25 and laundry["sun"]["value"] == 70 and laundry["sun"]["note"] == "햇빛 정보 없음"
assert sum(f["weight"] for f in laundry.values()) == 100
assert [f["axis"] for f in yajang] == ["temp", "rain", "wind", "humidity", "air", "time"]
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
items = (await client.get("/v1/index/list", params={"region": REGION})).json()["items"]
stars_id = next(i["index_id"] for i in items if i["code"] == "stars")
stars = (await client.get(f"/v1/index/{stars_id}", params={"region": REGION})).json()["factors"]
assert {f["axis"]: f["label"] for f in stars}["view"] == "가시거리"
@pytest.mark.anyio
async def test_openmeteo_data_changes_index_and_triggers_recompute(fakes):
today = kst_midnight(now_kst().date())
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
before = await _laundry_sun(client)
assert before["sun"]["value"] == 70
await _put_om([_om_row(today + timedelta(hours=h), fetched_at=now_kst() + timedelta(hours=1)) for h in (12, 15, 18)])
after = await _laundry_sun(client)
assert after["sun"]["value"] == 100 and after["sun"]["note"] == "해 난 비율 100%"
+50 -4
View File
@@ -4,8 +4,8 @@ from types import SimpleNamespace
from common.enums import RainType, Sky
from services.calc.index_calc import (
OUTING_HOURS, Context, DayForecast, Hour, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, temp_score,
zero_rules_text,
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
@@ -24,8 +24,8 @@ def _defn(**kw):
return SimpleNamespace(**{**base, **kw})
def _h(hour, feels=21.0, prob=0, rain=RainType.NONE, wind=1.5, hum=50, sky=Sky.CLEAR):
return Hour(hour=hour, feels_c=feels, rain_type=rain, rain_prob=prob, wind_ms=wind, humidity=hum, sky=sky)
def _h(hour, feels=21.0, prob=0, rain=RainType.NONE, wind=1.5, hum=50, sky=Sky.CLEAR, **extra):
return Hour(hour=hour, feels_c=feels, rain_type=rain, rain_prob=prob, wind_ms=wind, humidity=hum, sky=sky, **extra)
def test_perfect_evening_scores_100():
@@ -111,6 +111,52 @@ def test_moon_full_and_new():
assert illumination(datetime(2000, 1, 21, 12, tzinfo=timezone.utc)) > 0.95
def test_uv_sun_view_scores_are_linear_and_unknown_is_70():
assert uv_score({"zero": 8, "full": 2}, 1)[0] == 100 and uv_score({"zero": 8, "full": 2}, 5)[0] == 50 and uv_score({"zero": 8, "full": 2}, 9)[0] == 0
assert sun_score({"zero": 0.2, "full": 0.8}, 0.5)[0] == 50 and sun_score({"zero": 0.2, "full": 0.8}, 1.0)[0] == 100
assert view_score({"zero": 5, "full": 20}, 12.5)[0] == 50 and view_score({"zero": 5, "full": 20}, 3)[0] == 0
assert (uv_score({"zero": 8, "full": 2}, None)[0], sun_score({"zero": 0.2, "full": 0.8}, None)[0], view_score({"zero": 5, "full": 20}, None)[0]) == (70, 70, 70)
assert uv_score({"zero": 8, "full": 2}, 5)[1] == "자외선 5.0"
assert view_score({"zero": 5, "full": 20}, 12.5)[1] == "가시거리 12.5km" and view_score({"zero": 5, "full": 20}, None)[1] == "가시거리 정보 없음"
def _uv_defn():
rules = _defn().factor_rules | {"uv": {"zero": 8, "full": 2}}
return _defn(weight_temp=25, weight_humidity=5, weight_uv=10, factor_rules=rules)
def test_weighted_uv_axis_lowers_score_when_uv_is_high_and_is_unknown_when_missing():
low = evaluate(_uv_defn(), [[_h(19, wind=1.0, uv=1.0)]], CTX)
high = evaluate(_uv_defn(), [[_h(19, wind=1.0, uv=9.0)]], CTX)
missing = evaluate(_uv_defn(), [[_h(19, wind=1.0)]], CTX)
assert low.score == 100 and low.factors["uv"] == 100
assert high.factors["uv"] == 0 and high.score < 80
assert missing.factors["uv"] == 70 and missing.notes["uv"] == "자외선 정보 없음"
def test_unweighted_new_axes_do_not_affect_score_and_use_max_uv_in_window():
plain = evaluate(_defn(), [[_h(19, wind=1.0, uv=9.0)]], CTX)
assert plain.score == 100 and plain.factors["uv"] == 0
window = evaluate(_uv_defn(), [[_h(19, wind=1.0, uv=1.0), _h(20, wind=1.0, uv=9.0)]], CTX)
assert window.factors["uv"] == 0
def test_gust_and_ground_temperature_zero_rules():
gust = _defn(zero_rules=[{"field": "gust_ms", "op": ">=", "value": 15}])
assert evaluate(gust, [[_h(19, wind=1.0, gust_ms=16.0)]], CTX).score == 0
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° 이상이라 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)
+40
View File
@@ -0,0 +1,40 @@
from datetime import datetime, timezone
from types import SimpleNamespace
from common.enums import PostType
from common.utils.kma_time import KST
from services.calc.moon import nearest, phase_name
from services.feed_service import FeedService, _tonight
def test_true_phases_match_published_times_within_five_minutes():
known = [(True, datetime(2024, 4, 23, 23, 49, tzinfo=timezone.utc)), (False, datetime(2024, 4, 8, 18, 21, tzinfo=timezone.utc)),
(True, datetime(2025, 10, 7, 3, 47, tzinfo=timezone.utc)), (False, datetime(2017, 8, 21, 18, 30, tzinfo=timezone.utc))]
for full, at in known:
assert abs((nearest(at, full) - at).total_seconds()) < 300
def test_phase_names():
assert phase_name(datetime(2025, 10, 7, 3, 47, tzinfo=timezone.utc)) == "보름달"
assert phase_name(datetime(2024, 4, 8, 18, 21, tzinfo=timezone.utc)) == "삭"
def test_tonight_follows_feed_day_starting_at_3am():
assert _tonight(datetime(2024, 4, 9, 1, 0, tzinfo=KST)) == datetime(2024, 4, 8, 22, 0, tzinfo=KST)
assert _tonight(datetime(2024, 4, 8, 20, 0, tzinfo=KST)) == datetime(2024, 4, 8, 22, 0, tzinfo=KST)
assert _tonight(datetime(2024, 4, 9, 9, 0, tzinfo=KST)) == datetime(2024, 4, 9, 22, 0, tzinfo=KST)
def _moon_post(now: datetime):
base = dict(post_id=1, post_type=PostType.MOON, like_count=0, comment_count=0, published_at=now)
c = SimpleNamespace(now=now, region=SimpleNamespace(short_name="분당구"), hourly=[], board=None)
return FeedService._moon(None, base, c)
def test_moon_post_every_night_with_full_and_new_moon_stories():
full = _moon_post(datetime(2025, 10, 7, 20, 0, tzinfo=KST)) # 보름 10.07 12:47
assert full.title == "오늘 밤 보름달" and "12:4" in full.slides[0].line
new = _moon_post(datetime(2024, 4, 9, 1, 0, tzinfo=KST)) # 삭 04.09 03:21, 자정 넘긴 새벽에도 그 밤
assert new.title == "오늘 밤 달 없는 밤"
plain = _moon_post(datetime(2025, 10, 4, 20, 0, tzinfo=KST)) # 보름 사흘 전
assert plain.title == "오늘 밤 차오르는 달" and plain.slides[0].rows[-1].label == "다음 보름" and plain.slides[0].rows[-1].value.startswith("10.07")
+113
View File
@@ -0,0 +1,113 @@
import pytest
from sqlalchemy import text
import scheduler.jobs as jobs
from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import ErrorType
from services.external.open_meteo import OpenMeteoRequestFailed, parse_weather
SLOTS_PER_REGION = 31 # 96시간 응답에서 직전 3시간이 다 있는 3시간 구간 (끝 시각 03시 ~ 다음다음다음날 21시)
def _hourly(**over):
times = [f"2026-10-06T{h:02d}:00" for h in range(9)]
base = {
"time": times,
"uv_index": [round(0.1 * h, 1) for h in range(9)],
"uv_index_clear_sky": [round(0.2 * h, 1) for h in range(9)],
"visibility": [10000.0 + h for h in range(9)],
"wind_gusts_10m": [1.0 + h for h in range(9)],
"pressure_msl": [1000.0 + h for h in range(9)],
"sunshine_duration": [0, 600, 1200, 1800, 2400, 3000, 3600, 3600, 3600],
"shortwave_radiation": [0, 10, 20, 30, 40, 60, 100, 200, 300],
"soil_temperature_0cm": [10.0 + h for h in range(9)],
}
return {"hourly": base | over}
def test_three_hour_slots_sum_sunshine_and_average_radiation():
rows = {r["forecast_at"].hour: r for r in parse_weather(_hourly())}
assert sorted(rows) == [3, 6] # 00시 구간은 앞 두 시간이 없어 만들지 않는다
assert rows[3]["sunshine_s"] == 600 + 1200 + 1800
assert rows[3]["shortwave_avg_wm2"] == 20 and rows[3]["shortwave_max_wm2"] == 30
assert rows[6]["sunshine_s"] == 2400 + 3000 + 3600
assert rows[6]["shortwave_avg_wm2"] == 67 and rows[6]["shortwave_max_wm2"] == 100
def test_other_values_are_taken_at_slot_end():
row = {r["forecast_at"].hour: r for r in parse_weather(_hourly())}[6]
assert row["uv_index"] == 0.6 and row["uv_index_clear_sky"] == 1.2
assert row["visibility_m"] == 10006 and row["wind_gust_ms"] == 7.0
assert row["pressure_hpa"] == 1006.0 and row["soil_temp_c"] == 16.0
def test_missing_hour_value_makes_aggregate_none_but_keeps_instant_values():
sun = [0, 600, None, 1800, 2400, 3000, 3600, 3600, 3600]
rows = {r["forecast_at"].hour: r for r in parse_weather(_hourly(sunshine_duration=sun))}
assert rows[3]["sunshine_s"] is None and rows[3]["uv_index"] == 0.3
assert rows[6]["sunshine_s"] == 9000
def test_dark_slots_drop_sun_values_but_keep_others():
times = [f"2026-10-06T{h:02d}:00" for h in range(24)]
full = {k: [1.0] * 24 for k in ("uv_index", "uv_index_clear_sky", "visibility", "wind_gusts_10m", "pressure_msl", "soil_temperature_0cm")}
rows = {r["forecast_at"].hour: r for r in parse_weather({"hourly": {"time": times, "sunshine_duration": [600] * 24, "shortwave_radiation": [50] * 24} | full})}
dark = {15, 18, 21} # GMT 끝 시각 = KST 0·3·6시 (21~06시). KST 21시 구간(18~21시)은 남긴다
assert sorted(rows) == [3, 6, 9, 12, 15, 18, 21]
for hour, row in rows.items():
sun = (row["uv_index"], row["uv_index_clear_sky"], row["sunshine_s"], row["shortwave_avg_wm2"], row["shortwave_max_wm2"])
assert (sun == (None,) * 5) is (hour in dark)
assert row["visibility_m"] == 1 and row["soil_temp_c"] == 1.0
@pytest.mark.anyio
async def test_refresh_stores_every_region_and_is_repeatable(offline):
assert await jobs.refresh_openmeteo_weather() is ErrorType.SUCCESS
first = await _counts()
assert first["regions"] == 256 and first["rows"] == 256 * SLOTS_PER_REGION and first["slots"] == SLOTS_PER_REGION
assert await jobs.refresh_openmeteo_weather() is ErrorType.SUCCESS
assert (await _counts())["rows"] == first["rows"]
@pytest.mark.anyio
async def test_refresh_failure_returns_error_and_stores_nothing(offline, monkeypatch):
async def fail(client, points, days=4):
raise OpenMeteoRequestFailed("boom")
monkeypatch.setattr(jobs, "fetch_weather", fail)
assert await jobs.refresh_openmeteo_weather() is ErrorType.EXTERNAL_API_ERROR
assert (await _counts())["rows"] == 0
async def _counts() -> dict:
err, res = await DB_SESSION_MNG.execute_lambda(
lambda s: s.execute(text("SELECT count(*) AS rows, count(DISTINCT region_code) AS regions, count(DISTINCT forecast_at) AS slots FROM openmeteo_hourly"))
)
return dict(res.one()._mapping)
@pytest.mark.anyio
async def test_upsert_keeps_previous_value_when_new_value_is_missing():
from datetime import datetime, timedelta, timezone
from crud.weather_crud import WeatherCRUD
at = datetime(2026, 10, 6, 3, tzinfo=timezone.utc)
first = {
"region_code": "1144000000", "forecast_at": at, "fetched_at": at, "uv_index": 3.0, "uv_index_clear_sky": 3.5,
"visibility_m": 20000, "wind_gust_ms": 4.0, "pressure_hpa": 1015.0, "soil_temp_c": 18.0,
"sunshine_s": 3600, "shortwave_avg_wm2": 300, "shortwave_max_wm2": 400,
}
second = first | {"fetched_at": at + timedelta(hours=6), "uv_index": None, "sunshine_s": None, "visibility_m": 15000}
for row in (first, second):
await DB_SESSION_MNG.execute_lambda_run([lambda s, r=row: WeatherCRUD().upsert_openmeteo(s, [r])])
err, res = await DB_SESSION_MNG.execute_lambda(
lambda s: s.execute(text("SELECT uv_index, sunshine_s, visibility_m, fetched_at FROM openmeteo_hourly WHERE region_code = '1144000000'"))
)
row = res.one()
assert float(row.uv_index) == 3.0 and row.sunshine_s == 3600 # 비어 온 값은 이전 값 유지
assert row.visibility_m == 15000 # 값이 있으면 덮어씀
assert row.fetched_at == second["fetched_at"]
+64
View File
@@ -0,0 +1,64 @@
import json
from datetime import date
import httpx
import pytest
from common.enums import EventKind
from services.external import popga
from services.external.popga import fetch_popup_index, parse_popup, sido_of
def _page(popup_id: int, kind: str, start: str, end: str, address: str = "서울 성동구 테스트로 1") -> str:
ld = {
"@context": "https://schema.org", "@type": "Event", "name": "테스트 팝업 &amp; 굿즈", "startDate": start, "endDate": end,
"location": {"@type": "Place", "name": "테스트 빌딩 1F", "address": {"@type": "PostalAddress", "streetAddress": address},
"geo": {"@type": "GeoCoordinates", "latitude": 37.5446123, "longitude": 127.0557456}},
}
payload = f'self.__next_f.push([1,"{{\\"data\\":{{\\"id\\":{popup_id},\\"type\\":\\"{kind}\\",\\"source\\":null}}}}"])'
return f'<html><script type="application/ld+json">{json.dumps(ld, ensure_ascii=False)}</script><script>{payload}</script></html>'
def test_parse_popup_maps_store():
row = parse_popup(_page(501, "STORE", "2026-10-02", "2026-10-11"), 501, date(2026, 10, 1))
assert row == {
"source_id": "popga:501", "sido_code": "11", "name": "테스트 팝업 & 굿즈", "place_name": "테스트 빌딩 1F",
"start_date": date(2026, 10, 2), "end_date": date(2026, 10, 11), "is_confirmed": True,
"source_url": "https://popga.co.kr/popup/501", "image_url": None, "lat": 37.54461, "lon": 127.05575, "kind": EventKind.POPUP, "icon": "popup",
}
@pytest.mark.parametrize("kind,end,address", [
("PERFORMANCE", "2026-10-11", "서울 성동구 테스트로 1"),
("STORE", "2026-09-30", "서울 성동구 테스트로 1"),
("STORE", "2026-10-11", "알 수 없는 주소"),
])
def test_parse_popup_skips_non_store_ended_or_unknown_sido(kind, end, address):
assert parse_popup(_page(502, kind, "2026-09-01", end, address), 502, date(2026, 10, 1)) is None
def test_parse_popup_reads_type_of_its_own_id():
page = _page(503, "STORE", "2026-10-02", "2026-10-11").replace('\\"id\\":503,\\"type\\":\\"STORE\\"', '\\"id\\":999,\\"type\\":\\"STORE\\"')
assert parse_popup(page, 503, date(2026, 10, 1)) is None
@pytest.mark.parametrize("address,code", [
("서울 마포구 테스트로 1", "11"), ("서울특별시 마포구", "11"), ("경기 수원시", "41"), ("경상남도 진주시", "48"),
("강원특별자치도 춘천시", "51"), ("전북특별자치도 전주시", "52"), ("", None),
])
def test_sido_of(address, code):
assert sido_of(address) == code
@pytest.mark.anyio
async def test_fetch_popup_index_reads_popup_pages_only(monkeypatch):
monkeypatch.setattr(popga, "REQUEST_GAP_SEC", 0)
pages = {
"/sitemap.xml": "<sitemapindex><sitemap><loc>https://popga.co.kr/sitemap/2.xml</loc></sitemap>"
"<sitemap><loc>https://popga.co.kr/sitemap/5.xml</loc></sitemap></sitemapindex>",
"/sitemap/2.xml": "<urlset><url><loc>https://popga.co.kr/popup/12</loc><lastmod>2026-10-06T00:00:00Z</lastmod></url>"
"<url><loc>https://popga.co.kr/popup/11</loc></url></urlset>",
"/sitemap/5.xml": "<urlset><url><loc>https://popga.co.kr/popup/12/review/3</loc><lastmod>2026-10-06</lastmod></url></urlset>",
}
async with httpx.AsyncClient(transport=httpx.MockTransport(lambda req: httpx.Response(200, text=pages[req.url.path]))) as client:
assert await fetch_popup_index(client) == {12: "2026-10-06T00:00:00Z", 11: ""}
+32 -6
View File
@@ -54,8 +54,10 @@ async def test_sky_view_scores_three_days_with_spots(monkeypatch, clean):
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("비슷해요")
assert [t["kind"] for t in plan["timeline"]] == ["golden", "sun", "blue"]
assert plan["situation_label"] == "하늘이 넓게 물들 수 있어요" and plan["models_agree"] == plan["models_total"] == 2
assert plan["outlook"] == ""
assert body["sunset"]["verdict"] == "go" and body["spots"][0]["direction"]
@pytest.mark.anyio
@@ -104,14 +106,38 @@ def test_nearest_spots_west_first_and_empty_outside_radius():
assert sky_service.nearest_spots(33.0, 127.0, spots) == []
def test_outlook_points_to_a_better_day_only_when_clearly_better():
def test_outlook_only_when_a_later_day_has_a_better_verdict():
from datetime import date, timedelta
from common.database.model.models import SkyScore
from common.enums import SkySituation
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) == "내일·모레도 비슷해요"
sit = lambda i, s: SkyScore(score_date=today + timedelta(days=i), score=48, situation=s.value) # noqa: E731
assert sky_service.outlook(day(0, 30), [day(0, 30), day(1, 35), day(2, 72)], today) == "모레가 더 나아요 · 나가 볼 만해요"
assert sky_service.outlook(day(0, 80), [day(0, 80), day(1, 50), day(2, 40)], today) == ""
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) == ""
few, glow = SkySituation.FEW, SkySituation.GLOW
assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few), sit(2, glow)], today) == "모레가 더 나아요 · 하늘이 넓게 물들 수 있어요"
assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few)], 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):
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:
await client.get("/v1/sky", params={"region": "1144000000"})
err, rows = await DB_SESSION_MNG.execute_lambda(
lambda s: s.execute(text("SELECT kind, distance_km, forecast_at, model FROM cloud_hourly WHERE region_code = '1144000000'"))
)
rows = rows.all()
assert len(rows) == 2 * 2 * 3 * 2
assert {(r.kind, r.distance_km) for r in rows} == {(1, 20), (1, 100), (2, 20), (2, 100)}
assert {r.model for r in rows} == {3, 4}
assert len({r.forecast_at for r in rows}) == 6
+30 -10
View File
@@ -2,7 +2,7 @@ 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 GRADE_LABEL, Layers, best_times, confidence, grade, reason, score, sunset_timeline, verdict
from services.calc.sky_score import GRADE_LABEL, Layers, best_times, confidence, grade, reason, score, situation, sunset_timeline, verdict
from services.calc.sun import sun_times
CLEAR = Layers(0, 0, 0)
@@ -10,21 +10,21 @@ CLEAR = Layers(0, 0, 0)
def test_high_clouds_overhead_and_clear_horizon_is_best():
canvas = Layers(low=0, mid=20, high=50)
assert score(canvas, canvas, CLEAR) == 100
assert score(canvas, CLEAR) == 100
def test_clear_sky_is_only_soft():
assert grade(score(CLEAR, CLEAR, CLEAR)) is SkyGrade.SOFT
assert grade(score(CLEAR, CLEAR)) is SkyGrade.SOFT
def test_low_clouds_toward_sun_block_the_light():
canvas = Layers(low=0, mid=20, high=50)
assert grade(score(canvas, canvas, Layers(low=90, mid=50, high=0))) is SkyGrade.GRAY
assert grade(score(canvas, Layers(low=90, mid=50, high=0))) is SkyGrade.GRAY
def test_overcast_low_clouds_is_gray():
gray = Layers(low=100, mid=100, high=100)
assert grade(score(gray, gray, gray)) is SkyGrade.GRAY
assert grade(score(gray, gray)) is SkyGrade.GRAY
def test_confidence_from_model_spread():
@@ -43,15 +43,15 @@ def test_sunset_best_times_order():
sunset = datetime(2026, 10, 2, 9, 15, tzinfo=timezone.utc)
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 == ["해 져요", "가장 붉을 때", "보랏빛 하늘"]
assert labels == ["해 져요", "가장 붉을 때", "블루아워"]
def test_reason_names_what_decided_the_score():
canvas = Layers(low=0, mid=20, high=50)
assert "알맞게" in reason(canvas, canvas, CLEAR)
assert "먼 하늘" in reason(canvas, canvas, Layers(low=90, mid=50, high=0))
assert "낮은 구름" in reason(Layers(100, 0, 0), Layers(80, 0, 0), CLEAR)
assert "거의 없어" in reason(CLEAR, CLEAR, CLEAR)
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():
@@ -65,3 +65,23 @@ def test_sunset_timeline_runs_golden_to_blue():
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
def test_situation_follows_reason_order():
from common.enums import SkySituation
clear, glow = Layers(0, 0, 0), Layers(0, 40, 50)
assert situation(clear, clear) is SkySituation.FEW
assert situation(glow, clear) is SkySituation.GLOW
assert situation(Layers(0, 90, 95), clear) is SkySituation.THICK
assert situation(Layers(80, 0, 0), clear) is SkySituation.LOW_CLOUD
assert situation(glow, Layers(70, 0, 0)) is SkySituation.COVERED
def test_ranking_summary_only_when_most_spots_share_a_situation():
from types import SimpleNamespace
from common.enums import SkySituation
from services.sky_service import ranking_summary
item = lambda s: SimpleNamespace(score=SimpleNamespace(situation=s.value)) # noqa: E731
assert ranking_summary([item(SkySituation.FEW)] * 8 + [item(SkySituation.GLOW)] * 2) == "오늘은 전국이 맑아 대부분 짧게 끝나요"
assert ranking_summary([item(SkySituation.FEW)] * 5 + [item(SkySituation.GLOW)] * 5) is None
+21 -10
View File
@@ -8,12 +8,12 @@ import services.warning_service as warning_service
import services.weather_service as weather_service
import services.week_service as week_service
from common.database.model.models import Event
from common.enums import RainType, Sky
from common.enums import EventKind, 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
from services.week_service import EventItem, _status, mix_kinds
REGION = "1144000000"
@@ -45,6 +45,15 @@ def test_event_status_labels():
assert _status(ev(date(2026, 10, 20), date(2026, 10, 21)), today) == ("soon", "D-18")
def test_mix_kinds_rotates_festival_popup_exhibition_concert():
item = lambda name, kind: EventItem(event=Event(name=name, kind=kind), status="soon", status_label="", fit=None) # noqa: E731
items = [item("연주회1", EventKind.CONCERT), item("연주회2", EventKind.CONCERT), item("전시1", EventKind.EXHIBITION),
item("팝업1", EventKind.POPUP), item("연주회3", EventKind.CONCERT), item("축제1", EventKind.FESTIVAL)]
assert [e.event.name for e in mix_kinds(items)] == ["축제1", "팝업1", "전시1", "연주회1", "연주회2", "연주회3"]
only = [item(f"연주회{i}", EventKind.CONCERT) for i in range(3)]
assert [e.event.name for e in mix_kinds(only)] == ["연주회0", "연주회1", "연주회2"]
async def _async(v):
return v
@@ -67,6 +76,11 @@ def _mid(*_):
return land, ta
async def _collect(*sidos):
for sido in sidos:
await week_service.collect_events(sido, now_kst().date())
@pytest.fixture
def fakes(monkeypatch):
today = now_kst().date()
@@ -99,6 +113,7 @@ async def test_week_reaches_mid_forecast_end_with_holiday_and_rain(fakes):
@pytest.mark.anyio
async def test_events_exclude_long_running_and_add_weather_fit(fakes):
await _collect("11")
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"]] == ["가을 축제"]
@@ -114,6 +129,7 @@ async def test_events_include_culture_exhibitions_with_their_credit(fakes, monke
"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",
}]))
await _collect("11")
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"]}
@@ -129,6 +145,7 @@ async def test_events_keep_tour_festivals_when_culture_api_fails(fakes, monkeypa
raise DataGoKrRequestFailed("realm2 30 SERVICE_KEY_IS_NOT_REGISTERED_ERROR")
monkeypatch.setattr(week_service, "fetch_exhibitions", fail)
await _collect("11")
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"]] == ["가을 축제"]
@@ -145,16 +162,10 @@ async def test_events_pick_within_30km_across_sido(fakes, monkeypatch):
"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)
monkeypatch.setattr(week_service, "fetch_festivals", lambda client, sido, since: _async(by_sido.get(sido, [])))
await _collect("11", "41")
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"]} == {"잠실 축제", "좌표 없는 경기 축제"}