Merge branch 'main' into feat/open-meteo

This commit is contained in:
skkim committed 2026-10-12 14:43:39 +09:00
commit aa05d870a2
80 files changed
+4893 -351

No files matched your search

+8
View File
@@ -65,6 +65,14 @@ async def _async(v):
return v
@pytest.fixture(autouse=True)
def _no_seoul_crawl(monkeypatch):
"""서울문화포털은 키 없이 바로 긁어 오므로, 테스트가 실제 사이트를 부르지 않게 기본으로 막는다."""
import services.week_service as week_service
monkeypatch.setattr(week_service, "fetch_seoul_festivals", lambda *a: _async([]))
@pytest.fixture
def offline(monkeypatch):
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
+15 -1
View File
@@ -5,7 +5,8 @@ import httpx
import pytest
from config.settings import settings
from services.external import data_go_kr, guard, open_meteo
from services.external import airkorea, data_go_kr, guard, open_meteo
from services.external.airkorea import fetch_realtime
from services.external.data_go_kr import DataGoKrRequestFailed, get_body
from services.external.open_meteo import OpenMeteoRequestFailed, fetch_clouds
@@ -93,3 +94,16 @@ async def test_open_meteo_down_is_skipped(monkeypatch):
with pytest.raises(OpenMeteoRequestFailed):
await fetch_clouds(client, [(37.5, 127.0)])
assert len(calls) == 1
@pytest.mark.anyio
async def test_airkorea_nationwide_call_waits_past_default_budget(fast, monkeypatch):
"""전국 미세먼지 조회는 15~20초 걸려 기본 한도로는 늘 실패한다."""
monkeypatch.setattr(airkorea, "BUDGET_SEC", 2.0)
async def slow(req: httpx.Request) -> httpx.Response:
await asyncio.sleep(0.5)
return httpx.Response(200, json={"response": {"header": {"resultCode": "00"}, "body": {"items": [{"stationName": "x"}], "totalCount": 1}}})
async with _client(slow) as client:
assert await fetch_realtime(client) == [{"stationName": "x"}]
+63
View File
@@ -0,0 +1,63 @@
from datetime import date, datetime, timedelta
from types import SimpleNamespace
from common.enums import RainType, Sky
from common.utils.kma_time import KST, kst_midnight
from services.calc.day_slot import slot_hours
from services.calc.index_calc import Context
from services.index_service import EARLY, WEATHER_SCORE_DEF, current_slot, slot_results
DAY = date(2026, 10, 8)
SUNSET = datetime(2026, 10, 8, 18, 0, tzinfo=KST)
REGION = SimpleNamespace(lat=37.5, lon=127.0)
CTX = Context(day=DAY, is_holiday=False, pm25=10, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
def _rows(rain_from: int = 99):
start = kst_midnight(DAY)
return {
start + timedelta(hours=h): SimpleNamespace(
forecast_at=start + timedelta(hours=h), feels_c=21.0, rain_type=RainType.RAIN.value if h >= rain_from else RainType.NONE.value,
rain_prob=90 if h >= rain_from else 0, wind_ms=1.0, humidity=50, sky=Sky.CLEAR.value,
)
for h in range(0, 30)
}
def _defn(windows):
return SimpleNamespace(
weight_temp=50, weight_rain=50, weight_wind=0, weight_humidity=0, weight_air=0, weight_time=0,
factor_rules={"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "ignore"},
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100}},
zero_rules=[], windows=windows,
)
def test_slot_hours_split_by_sunset():
hours = slot_hours(DAY, SUNSET)
assert hours["morning"] == set(range(5, 11))
assert hours["day"] == set(range(11, 16))
assert hours["evening"] == {16, 17, 18}
assert hours["night"] == set(range(19, 29))
def test_current_slot_before_5_is_previous_night():
assert current_slot(datetime(2026, 10, 8, 2, 0, tzinfo=KST), SUNSET) == EARLY
assert current_slot(datetime(2026, 10, 8, 16, 30, tzinfo=KST), SUNSET) == "evening"
def test_gak_hidden_in_slots_outside_its_window():
parts = slot_results(_defn([{"from": 18, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
assert set(parts) == {"evening", "night"}
def test_rain_in_evening_lowers_only_later_slots():
parts = slot_results(_defn([{"from": 7, "to": 23}]), DAY, REGION, _rows(rain_from=16), {}, CTX, SUNSET)
assert parts["morning"].score > 80
assert parts["evening"].score < parts["morning"].score
assert parts["night"].score < parts["morning"].score
def test_weather_score_covers_every_slot():
parts = slot_results(WEATHER_SCORE_DEF, DAY, REGION, _rows(), {}, CTX, SUNSET)
assert set(parts) == {"morning", "day", "evening", "night", EARLY}
+12 -9
View File
@@ -8,6 +8,7 @@ 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.region_crud import RegionCRUD
from crud.season_crud import SeasonCRUD
from router.router import app
from services.feed_service import build_feed_day
@@ -16,17 +17,19 @@ from services.week_service import collect_events
REGION = "1114000000"
async def _posts(day: date):
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT post_type FROM post WHERE feed_date='{day}' ORDER BY position")))
async def _posts(day: date, sido: str = REGION[:2]):
"""한 시도가 보는 그날 카드 (전국 + 그 시도)."""
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(
f"SELECT post_type FROM post WHERE feed_date='{day}' AND scope IN ('00', '{sido}') ORDER BY position")))
return [r[0] for r in rows]
@pytest.mark.anyio
async def test_build_day_adds_weekend_post_every_day():
monday, thursday = date(2026, 10, 12), date(2026, 10, 15)
await build_feed_day(monday, FeedCRUD(), SeasonCRUD())
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
await build_feed_day(monday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
assert (await _posts(monday)).count(PostType.WEEK.value) == 1
assert (await _posts(thursday)).count(PostType.WEEK.value) == 1
assert (await _posts(thursday))[0] == PostType.WEATHER.value
@@ -36,10 +39,10 @@ async def test_build_day_adds_weekend_post_every_day():
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 build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
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())
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
after = await _posts(thursday)
assert len(after) == before + 1 and after.count(PostType.AIR.value) == 1
@@ -58,7 +61,7 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
body = (await client.get("/v1/feed", params={"region": REGION})).json()
assert body["result"]["success"] is True
assert body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"]
assert len(body["stories"]) == 27
assert len(body["stories"]) == 34
weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
assert [s["kind"] for s in weather["slides"]] == ["hours", "hours"]
assert len(weather["slides"][0]["hours"]) == 8
@@ -155,7 +158,7 @@ def test_arrange_scatters_up_to_three_events_same_spot_all_day():
@pytest.mark.anyio
async def test_build_day_makes_every_card_at_three():
thursday = date(2026, 10, 15)
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT post_type, published_at FROM post WHERE feed_date='{thursday}'")))
rows = list(rows)
assert {PostType.ALERT.value, PostType.TOMORROW.value, PostType.QUOTE.value} <= {r[0] for r in rows}
+42 -7
View File
@@ -9,10 +9,13 @@ 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.enums import ErrorType
from common.utils.kma_time import kst_midnight, now_kst
from crud.region_crud import RegionCRUD
from crud.weather_crud import WeatherCRUD
from router.router import app
from services.index_service import _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
from services.calc.index_calc import rank_score
from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
REGION = "1141000000"
@@ -51,13 +54,18 @@ def fakes(monkeypatch):
@pytest.mark.anyio
async def test_index_list_ranks_all_27_with_today_tomorrow_weekend_trend(fakes):
async def test_index_list_ranks_all_34_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 len(body["items"]) == 34 and len(body["top3"]) == 3
priority = {d["code"]: d["priority"] for d in _seed()}
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤. 각 묶음 안에서는 점수 × 중요도 순
actives = [i["active"] for i in body["items"]]
assert actives == sorted(actives, reverse=True) and all(i["active"] for i in body["top3"])
for group in (True, False):
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group]
assert weighted == sorted(weighted, reverse=True)
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)]
@@ -95,13 +103,40 @@ async def test_index_detail_has_four_score_bands_with_today_marked(fakes):
assert len(current) == 1 and current[0]["low"] <= body["index"]["score"] <= current[0]["high"]
def test_every_index_has_four_band_sentences():
def _seed() -> list[dict]:
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"))
with open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "index_definition.json"), encoding="utf-8") as f:
return json.load(f)
def test_every_index_has_four_band_sentences():
seed = _seed()
assert all(sorted(d["sentences"], key=int) == ["0", "30", "60", "80"] and all(d["sentences"].values()) for d in seed)
def test_every_index_has_priority():
assert all(d["priority"] in (1, 2, 3) for d in _seed())
@pytest.mark.anyio
async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
today = now_kst().date()
defs = [
SimpleNamespace(index_id=1, code="low", priority=3),
SimpleNamespace(index_id=2, code="mid", priority=2),
SimpleNamespace(index_id=3, code="high", priority=1),
]
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 90), (2, 80), (3, 70))]
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, 50)))
err, board = await service.board(REGION)
assert err is ErrorType.SUCCESS
# 하 90점(63) < 중 80점(68) < 상 70점(70). 보이는 점수는 그대로
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 80, 2), ("low", 90, 3)]
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,
+53 -1
View File
@@ -1,10 +1,14 @@
import json
from dataclasses import replace
from datetime import date, datetime, timezone
from pathlib import Path
from types import SimpleNamespace
import pytest
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, sun_score, temp_score,
OUTING_HOURS, Context, DayForecast, Hour, air_score, 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
@@ -222,3 +226,51 @@ def test_outing_estimate_from_mid_forecast():
assert r.reason.startswith("비 20% · 낮 ")
assert outing_estimate(_fc(pm=60)).score <= 30
assert outing_estimate(_fc(lo=None, hi=None)) is None
def test_air_rule_can_reverse_so_dusty_air_scores_high():
rule = {"zero": 15, "full": 75}
assert air_score(80, None, rule)[0] == 100 and air_score(10, None, rule)[0] == 0
assert air_score(10, None)[0] == 100
assert axis_label("air", {"air": rule}) == "공기 탁함" and axis_label("air", {}) == "공기 맑음"
_SEED = {x["code"]: SimpleNamespace(**x) for x in json.loads((Path(__file__).parents[1] / "seed" / "index_definition.json").read_text(encoding="utf-8"))}
_SAT, _WED = date(2026, 10, 10), date(2026, 10, 7)
def _seed_score(code, day=_SAT, pm25=10, **hour):
d = _SEED[code]
windows = [[_h(h, **hour) for h in range(w["from"], w["to"])] for w in d.windows]
return evaluate(d, windows, replace(CTX, day=day, pm25=pm25)).score
@pytest.mark.parametrize("code, good, bad", [
("golf", dict(feels=19.0, wind=2.0, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
("jipkok", dict(feels=4.0, prob=90, rain=RainType.RAIN, wind=7.0, hum=85), dict(feels=20.0, wind=1.0, hum=40)),
("fishing", dict(feels=22.0, wind=3.0), dict(feels=17.0, wind=11.0)),
("drive", dict(feels=23.0, wind=4.0, hum=45, visibility_km=18.0), dict(feels=18.0, prob=80, rain=RainType.RAIN, visibility_km=5.0)),
("kite", dict(feels=19.0, wind=6.0), dict(feels=14.0, wind=0.5)),
("waterplay", dict(feels=28.0, wind=3.0, sunshine_ratio=0.7), dict(feels=18.0, wind=2.0, sunshine_ratio=0.3)),
("kimjang", dict(feels=9.0, wind=3.0), dict(feels=20.0, wind=2.0)),
])
def test_new_gak_good_day_high_bad_day_low(code, good, bad):
assert 80 <= _seed_score(code, pm25=60 if code == "jipkok" else 10, **good) < 100
assert _seed_score(code, **bad) <= 30
def test_new_gak_100_only_when_every_factor_is_perfect():
perfect = dict(feels=19.5, wind=1.0, hum=35)
assert _seed_score("golf", **perfect) == 100
assert _seed_score("golf", day=_WED, **perfect) < 100
def test_weather_score_100_only_on_perfect_day():
from services.index_service import WEATHER_SCORE_DEF
perfect = Context(day=date(2026, 10, 2), is_holiday=False, pm25=8, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
hours = [_h(h, feels=21.0, prob=0, wind=0.8, hum=50, sunshine_ratio=1.0) for h in range(9, 22)]
assert evaluate(WEATHER_SCORE_DEF, [hours], perfect).score == 100
good = [_h(h, feels=22.5, prob=10, wind=2.5, hum=62, sunshine_ratio=0.7) for h in range(9, 22)]
assert evaluate(WEATHER_SCORE_DEF, [good], replace(perfect, pm25=15)).score < 95
+10
View File
@@ -28,6 +28,16 @@ def test_parse_popup_maps_store():
}
def test_parse_popup_maps_festival():
row = parse_popup(_page(504, "FESTIVAL", "2026-10-02", "2026-10-11", "경기 수원시 팔달구 테스트로 1"), 504, date(2026, 10, 1))
assert (row["kind"], row["icon"], row["sido_code"]) == (EventKind.FESTIVAL, "fireworks", "41")
def test_parse_popup_moves_festival_shows_in_theaters_to_concert():
page = _page(505, "FESTIVAL", "2026-10-02", "2026-10-11").replace("테스트 빌딩 1F", "대학로예술극장 소극장")
assert parse_popup(page, 505, date(2026, 10, 1))["kind"] is EventKind.CONCERT
@pytest.mark.parametrize("kind,end,address", [
("PERFORMANCE", "2026-10-11", "서울 성동구 테스트로 1"),
("STORE", "2026-09-30", "서울 성동구 테스트로 1"),
+112
View File
@@ -0,0 +1,112 @@
import csv
import os
from collections import defaultdict
from datetime import date
import pytest
from httpx import ASGITransport, AsyncClient
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.region_crud import RegionCRUD
from crud.season_crud import SeasonCRUD
from router.router import app
from services.feed_service import LINEUP, NATIONAL_SCOPE, NATIONAL_TYPES, build_feed_day, feed_day, sido_of
SEOUL_A, SEOUL_B, BUSAN = "1111000000", "1114000000", "2611000000"
REGION_CSV = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "region.csv")
def client():
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
def _ids(feed: dict) -> dict[int, set[int]]:
out: dict[int, set[int]] = defaultdict(set)
for p in feed["posts"]:
out[p["post_type"]].add(p["post_id"])
return out
def test_every_region_maps_to_one_sido():
with open(REGION_CSV, encoding="utf-8") as f:
regions = list(csv.DictReader(f))
assert len(regions) == 256
by_name: dict[str, set[str]] = defaultdict(set)
for r in regions:
by_name[r["name"].split()[0]].add(sido_of(r["code"]))
assert all(len(codes) == 1 for codes in by_name.values()), by_name
sidos = {sido_of(r["code"]) for r in regions}
assert all(len(c) == 2 and c.isdigit() and c != NATIONAL_SCOPE for c in sidos)
sejong = [r for r in regions if r["name"].startswith("세종")]
assert len(sejong) == 1 and sido_of(sejong[0]["code"]) == "36"
assert sum(1 for r in regions if sido_of(r["code"]) == "36") == 1
@pytest.mark.anyio
async def test_build_day_makes_national_once_and_regional_per_sido():
day = date(2026, 10, 15)
await build_feed_day(day, FeedCRUD(), SeasonCRUD(), RegionCRUD())
await build_feed_day(day, FeedCRUD(), SeasonCRUD(), RegionCRUD())
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT scope, post_type FROM post WHERE feed_date='{day}'")))
rows = list(rows)
_, regions = await DB_SESSION_MNG.execute_lambda(lambda s: RegionCRUD().search(s))
sidos = {sido_of(r.code) for r in regions}
regional = [x for x in LINEUP if x[1] not in NATIONAL_TYPES]
assert {scope for scope, t in rows if PostType(t) in NATIONAL_TYPES} == {NATIONAL_SCOPE}
assert {scope for scope, t in rows if PostType(t) not in NATIONAL_TYPES} == sidos
assert sum(1 for scope, t in rows if PostType(t) not in NATIONAL_TYPES) == len(regional) * len(sidos)
@pytest.mark.anyio
async def test_regional_posts_shared_within_sido_split_across_sido(offline):
async with client() as c:
a, b, busan = [(await c.get("/v1/feed", params={"region": r})).json() for r in (SEOUL_A, SEOUL_B, BUSAN)]
ia, ib, ibusan = _ids(a), _ids(b), _ids(busan)
regional = [t for t in ia if PostType(t) not in NATIONAL_TYPES]
assert PostType.WEATHER.value in regional and PostType.GAK.value in regional
for t in regional:
if t in ib:
assert ia[t] == ib[t], PostType(t)
if t in ibusan:
assert not ia[t] & ibusan[t], PostType(t)
national = [t for t in ia if PostType(t) in NATIONAL_TYPES]
assert PostType.MOON.value in national
for t in national:
assert ia[t] == ib[t] == ibusan[t], PostType(t)
@pytest.mark.anyio
async def test_like_in_one_sido_not_seen_in_another(offline):
async with client() as c:
token = (await c.post("/v1/auth/signup", json={"login_id": "scope_01", "password": "password1", "nickname": "시도테스트"})).json()["access_token"]
h = {"Authorization": f"Bearer {token}"}
seoul = (await c.get("/v1/feed", params={"region": SEOUL_A}, headers=h)).json()
post_id = next(p["post_id"] for p in seoul["posts"] if p["post_type"] == PostType.WEATHER.value)
assert (await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)).json()["like_count"] == 1
await c.post(f"/v1/reaction/post/{post_id}/comment", json={"body": "서울 맑음"}, headers=h)
same = (await c.get("/v1/feed", params={"region": SEOUL_B}, headers=h)).json()
busan = (await c.get("/v1/feed", params={"region": BUSAN}, headers=h)).json()
mine = next(p for p in same["posts"] if p["post_id"] == post_id)
assert mine["liked"] is True and mine["like_count"] == 1 and mine["comment_count"] == 1
weather = next(p for p in busan["posts"] if p["post_type"] == PostType.WEATHER.value)
assert weather["post_id"] != post_id and weather["like_count"] == 0 and weather["comment_count"] == 0 and not weather.get("liked")
@pytest.mark.anyio
async def test_day_built_before_split_keeps_national_rows_for_regional_cards(offline):
"""그날 지역 카드가 이미 전국 행으로 있으면 시도 행을 만들지 않고, 모든 시도가 그 행(과 반응)을 같이 쓴다."""
day = feed_day(now_kst())
rows = ", ".join(f"('{day}', {pos}, '{NATIONAL_SCOPE}', {t.value}, {ref.value}, {rank if rank else 'NULL'}, now(), {5 if t is PostType.WEATHER else 0})"
for pos, t, ref, rank in LINEUP if ref.value == 1)
await DB_SESSION_MNG.execute_lambda_run([lambda s: s.execute(text(
f"INSERT INTO post (feed_date, position, scope, post_type, ref_type, index_rank, published_at, like_count) VALUES {rows}"))])
async with client() as c:
seoul, busan = [(await c.get("/v1/feed", params={"region": r})).json() for r in (SEOUL_A, BUSAN)]
_, n = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(text(f"SELECT count(*) FROM post WHERE feed_date='{day}' AND scope <> '{NATIONAL_SCOPE}'")))
assert n == 0
ws, wb = [next(p for p in f["posts"] if p["post_type"] == PostType.WEATHER.value) for f in (seoul, busan)]
assert ws["post_id"] == wb["post_id"] and ws["like_count"] == 5
+14
View File
@@ -2,8 +2,10 @@ from datetime import timedelta
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import text
import services.season_service as season_service
from common.database.db_session_manager import DB_SESSION_MNG
from common.utils.kma_time import now_kst
from router.router import app
@@ -38,3 +40,15 @@ async def test_article_detail_and_not_found():
missing = (await client.get("/v1/season/article/9999")).json()
assert first["body"] and first["article"]["title"] == listed[0]["title"]
assert missing["result"]["desc"] == "NOT_FOUND"
@pytest.mark.anyio
async def test_article_photo_only_when_seeded():
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
listed = {a["code"]: a for a in (await client.get("/v1/season/article/list")).json()["articles"]}
umbrella = (await client.get(f"/v1/season/article/{listed['umbrella']['article_id']}")).json()["article"]
_, maple_id = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(text("SELECT article_id FROM article WHERE code = 'maple'")))
maple = (await client.get(f"/v1/season/article/{maple_id}")).json()["article"]
assert umbrella["image"] == "/season/umbrella.jpg" and "image_credit" not in umbrella
assert maple["image"] == "/season/maple.jpg" and maple["image_credit"] == "ⓒJoycekim77 · CC BY-SA 3.0"
assert "image" not in listed["howgak"] and "image" not in listed["di"]
+83
View File
@@ -0,0 +1,83 @@
from datetime import date
import httpx
import pytest
import services.week_service as week_service
from services.external.seoul_culture import LIST_URL, fetch_seoul_festivals, parse_seoul_festivals
from services.week_service import _seoul
ITEM = {
"cultcode": 159216, "title": "[중랑문화재단] 2026 중랑용마폭포축제", "strtdate": "2026-10-10", "endDate": "2026-10-10",
"atchFileId": "abc", "xCoord": "37.5118239", "yCoord": "127.0591590", "facName": "용마폭포공원", "addr": "서울특별시 중랑구",
}
def test_parse_reads_lat_from_x_and_builds_image_and_link():
[row] = parse_seoul_festivals([ITEM, {**ITEM, "cultcode": None}, {**ITEM, "cultcode": 2, "strtdate": ""}])
assert row["source_id"] == "seoul:159216" and row["sido_code"] == "11"
assert (row["lat"], row["lon"]) == (37.51182, 127.05916)
assert row["name"] == "2026 중랑용마폭포축제"
assert row["place_name"] == "용마폭포공원" and row["start_date"] == date(2026, 10, 10)
assert row["image_url"].endswith("atchFileId=abc&thumb=Y") and "cultcode=159216" in row["source_url"]
@pytest.mark.anyio
async def test_fetch_pages_until_empty(monkeypatch):
monkeypatch.setattr("services.external.seoul_culture.REQUEST_GAP_SEC", 0)
pages = []
def handler(req: httpx.Request) -> httpx.Response:
assert str(req.url) == LIST_URL
page = int(dict(x.split("=") for x in req.content.decode().split("&"))["pageIndex"])
pages.append(page)
return httpx.Response(200, json={"resultList": [ITEM] * 10 if page < 3 else []})
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
items = await fetch_seoul_festivals(client, date(2026, 10, 8), 30)
assert len(items) == 20 and pages == [1, 2, 3]
@pytest.mark.anyio
async def test_seoul_skips_festivals_tour_api_already_has_and_other_sidos(monkeypatch):
other = {**ITEM, "cultcode": 2, "title": "2026 서울어텀페스타"}
async def fake(client, since, days):
return [ITEM, other]
monkeypatch.setattr(week_service, "fetch_seoul_festivals", fake)
known = [{"name": "제3회 중랑용마폭포축제"}]
rows = await _seoul(None, "11", date(2026, 10, 8), known)
assert [r["name"] for r in rows] == ["2026 서울어텀페스타"]
assert await _seoul(None, "41", date(2026, 10, 8), known) == []
@pytest.mark.anyio
async def test_seoul_failure_keeps_other_sources(monkeypatch):
async def broken(client, since, days):
raise httpx.ConnectError("down")
monkeypatch.setattr(week_service, "fetch_seoul_festivals", broken)
assert await _seoul(None, "11", date(2026, 10, 8), []) == []
def _row(source_id, name, start, end, sido="11"):
return {"source_id": source_id, "sido_code": sido, "name": name, "place_name": "", "start_date": start, "end_date": end,
"is_confirmed": True, "source_url": None, "image_url": None, "lat": None, "lon": None, "kind": 1, "icon": "fireworks"}
@pytest.mark.anyio
async def test_drop_known_skips_same_festival_from_another_source():
from common.database.db_session_manager import DB_SESSION_MNG
from crud.week_crud import WeekCRUD
from services.week_service import drop_known
tour = _row("9001", "경복궁 별빛야행", date(2026, 10, 1), date(2026, 10, 24))
await DB_SESSION_MNG.execute_lambda_run([lambda s: WeekCRUD().upsert_events(s, [tour])])
rows = [
_row("popga:1", "2026 경복궁 별빛야행", date(2026, 10, 8), date(2026, 10, 10)),
_row("popga:2", "경복궁 별빛야행", date(2026, 11, 1), date(2026, 11, 2)),
_row("popga:3", "경복궁 별빛야행", date(2026, 10, 8), date(2026, 10, 10), sido="41"),
_row("9001", "경복궁 별빛야행", date(2026, 10, 1), date(2026, 10, 25)),
]
assert [r["source_id"] for r in await drop_known(rows)] == ["popga:2", "popga:3", "9001"]
+2 -2
View File
@@ -93,7 +93,7 @@ async def test_sky_spots_by_distance(monkeypatch, clean, region, expected):
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():
def test_nearest_spots_west_first_and_nearest_one_outside_radius():
from decimal import Decimal
from common.database.model.models import SunsetSpot
@@ -103,7 +103,7 @@ def test_nearest_spots_west_first_and_empty_outside_radius():
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) == []
assert [x.spot.name for x in sky_service.nearest_spots(36.0, 127.0, spots)] == ["가까운 동쪽"]
def test_outlook_only_when_a_later_day_has_a_better_verdict():
+58 -2
View File
@@ -7,13 +7,13 @@ import services.air_service as air_service
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.database.model.models import Event, Place, Region
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 EventItem, _status, mix_kinds
from services.week_service import PLACE_FALLBACK, PLACE_RADIUS_KM, EventItem, _status, mix_kinds, pick_places
REGION = "1144000000"
@@ -169,6 +169,22 @@ async def test_events_pick_within_30km_across_sido(fakes, monkeypatch):
assert {e["name"] for e in body["events"]} == {"잠실 축제", "좌표 없는 경기 축제"}
@pytest.mark.anyio
async def test_gwangju_jeonnam_region_finds_events_saved_as_29_and_46(fakes, monkeypatch):
"""구 코드는 광주·전남이 12로 묶이지만 행사는 광주 29 · 전남 46으로 저장된다. 광산구에서 둘 다 보여야 한다."""
today = now_kst().date()
span = {"eventstartdate": (today + timedelta(days=1)).strftime("%Y%m%d"), "eventenddate": (today + timedelta(days=3)).strftime("%Y%m%d")}
by_sido = {
"29": [{"contentid": "29", "title": "광주 축제", "addr1": "광주 광산구", "mapy": "35.1396", "mapx": "126.7937", **span}],
"46": [{"contentid": "46", "title": "좌표 없는 전남 축제", "addr1": "전남", **span}],
}
monkeypatch.setattr(week_service, "fetch_festivals", lambda client, sido, since: _async(by_sido.get(sido, [])))
await _collect("29", "46")
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/week/event/list", params={"region": "1233000000"})).json()
assert {e["name"] for e in body["events"]} == {"광주 축제", "좌표 없는 전남 축제"}
@pytest.mark.anyio
async def test_places_put_indoor_first_on_rainy_day(fakes):
rainy_day = (now_kst().date() + timedelta(days=2)).isoformat()
@@ -179,6 +195,46 @@ async def test_places_put_indoor_first_on_rainy_day(fakes):
assert body["places"][0]["is_outdoor"] is False and body["places"][0]["is_good"] is True
def _place(name: str, lat: float, lon: float, outdoor: bool = True, area: str = "가") -> Place:
return Place(name=name, lat=lat, lon=lon, is_outdoor=outdoor, area=area)
def test_pick_places_within_radius_good_first_then_near():
region = Region(lat=37.0, lon=127.0)
places = [
_place("먼 공원", 37.2, 127.0), _place("가까운 공원", 37.01, 127.0, area="나"),
_place("미술관", 37.1, 127.0, outdoor=False), _place("반경 밖", 37.5, 127.0),
]
items, areas = pick_places(region, places, rainy=False, area=None)
assert [i.place.name for i in items] == ["가까운 공원", "먼 공원", "미술관"]
assert all(i.distance_km <= PLACE_RADIUS_KM for i in items) and items[0].distance_km == 1.1
assert areas == ["나", "가"]
items, _ = pick_places(region, places, rainy=True, area=None)
assert [i.place.name for i in items][0] == "미술관" and items[0].is_good
items, _ = pick_places(region, places, rainy=False, area="가")
assert [i.place.name for i in items] == ["먼 공원", "미술관"]
def test_pick_places_falls_back_to_nearest_when_none_in_radius():
region = Region(lat=37.0, lon=127.0)
places = [_place(f"{k}km", 37.0 + k / 111, 127.0) for k in (90, 40, 60, 200)]
items, _ = pick_places(region, places, rainy=False, area=None)
assert [i.place.name for i in items] == ["40km", "60km", "90km"][:PLACE_FALLBACK]
assert items[0].distance_km > PLACE_RADIUS_KM
@pytest.mark.anyio
@pytest.mark.parametrize("region", ["2635000000", "5013000000", "4794000000"])
async def test_places_outside_seoul_come_by_distance(fakes, region):
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
body = (await client.get("/v1/week/place/list", params={"region": region, "day": now_kst().date().isoformat()})).json()
places = body["places"]
assert places and all(p["distance_km"] <= PLACE_RADIUS_KM for p in places)
good = [p["distance_km"] for p in places if p["is_good"]]
assert good == sorted(good)
assert all(p["image_credit"] == "ⓒ한국관광공사" for p in places if p.get("image"))
@pytest.mark.anyio
async def test_weekend_ranking_scores_30_spots_and_caches(fakes, monkeypatch):
from services.weekend_rank import weekend_days
+5
View File
@@ -55,6 +55,11 @@ def test_afternoon_rain_moves_outdoor_time_before_it():
assert card.line.startswith("비 오는 토요일")
def test_morning_rain_then_outdoor_after_it_ends():
card = day_plan(_day(SAT, rainy=True, rain_hours=(9, 14), prob=60), None, [], None)
assert [s.time for s in card.steps] == ["9~14시", "14시~"]
def test_saturday_ignores_ending_hook_and_sunday_skips_saturday_events():
near = _event("가까운 축제", SAT, SUN, 3.0)
ends_sat = _event("토요일 끝", SAT, SAT, 50.0)