feat: 날씨각 백엔드 API (날씨·노을·지수·주말·계절·피드·로그인·반응)
- FastAPI + PostgreSQL + Redis, web·worker 분리, compose 에 backend·worker·postgres·redis 추가 - 기상청 단기·초단기·중기·특보, 에어코리아, Open-Meteo, TourAPI, 특일정보 연동 (첫 조회 때 받고 캐시) - 매일 03:00 worker 가 전국 공통 피드 칸을 정하고 지난 데이터를 정리 - 시드: 시군구 256곳, 지수 23개, 노을 대표 지점·명소, 데이트 명소, 읽을거리 - pytest 66개 (테스트 전용 DB·Redis 사용) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9cdc0d8fea
commit
e134295ce5
135 files changed
+9123
No files matched your search
@@ -0,0 +1,114 @@
|
||||
import asyncio
|
||||
import os
|
||||
|
||||
# 개발 DB·Redis 를 건드리지 않도록 테스트 전용 DB(<이름>_test)와 Redis 15번을 쓴다. 앱 import 전에 정해야 한다.
|
||||
os.environ["DB_NAME"] = os.environ.get("TEST_DB_NAME", "nalssigak_test")
|
||||
os.environ["REDIS_DB"] = "15"
|
||||
|
||||
import asyncpg # noqa: E402
|
||||
import pytest # noqa: E402
|
||||
|
||||
from common.cache.redis_client import REDIS # noqa: E402
|
||||
from common.database.db_session_manager import DB_SESSION_MNG # noqa: E402
|
||||
from config.settings import settings # noqa: E402
|
||||
|
||||
INIT_SQL = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "postgres-init", "init.sql")
|
||||
|
||||
|
||||
async def _create_test_db() -> None:
|
||||
admin = await asyncpg.connect(host=settings.db_host, port=settings.db_port, user=settings.db_user, password=settings.db_password, database="postgres")
|
||||
await admin.execute(f'DROP DATABASE IF EXISTS "{settings.db_name}" WITH (FORCE)')
|
||||
await admin.execute(f'CREATE DATABASE "{settings.db_name}"')
|
||||
await admin.close()
|
||||
conn = await asyncpg.connect(host=settings.db_host, port=settings.db_port, user=settings.db_user, password=settings.db_password, database=settings.db_name)
|
||||
with open(INIT_SQL, encoding="utf-8") as f:
|
||||
await conn.execute(f.read())
|
||||
await conn.close()
|
||||
|
||||
from scripts.load_seed import main as load_seed
|
||||
assert await load_seed() == 0
|
||||
await REDIS.conn.flushdb()
|
||||
await REDIS.stop()
|
||||
|
||||
|
||||
def pytest_sessionstart(session):
|
||||
asyncio.run(_create_test_db())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
_VOLATILE = (
|
||||
"weather_hourly", "weather_daily", "cloud_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",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def _reset_between_tests(anyio_backend):
|
||||
"""테스트끼리 영향을 주지 않게 외부에서 받은 데이터와 Redis 를 비운다 (시드는 남김). 이벤트 루프가 테스트마다 새로 생겨 커넥션도 닫는다."""
|
||||
yield
|
||||
from sqlalchemy import text
|
||||
|
||||
await DB_SESSION_MNG.execute_lambda_run(
|
||||
[lambda s: s.execute(text(f"TRUNCATE {', '.join(_VOLATILE)}")), lambda s: s.execute(text("DELETE FROM event WHERE source_id IS NOT NULL"))]
|
||||
)
|
||||
await REDIS.conn.flushdb()
|
||||
await DB_SESSION_MNG.stop()
|
||||
await REDIS.stop()
|
||||
|
||||
|
||||
async def _async(v):
|
||||
return v
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def offline(monkeypatch):
|
||||
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
|
||||
from datetime import timedelta
|
||||
|
||||
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 common.utils.kma_time import kst_midnight, now_kst
|
||||
|
||||
now = now_kst()
|
||||
|
||||
def hourly(hours: int, values: list[tuple[str, str]]) -> list[dict]:
|
||||
start = kst_midnight(now.date())
|
||||
return [
|
||||
{"category": c, "fcstDate": (start + timedelta(hours=h)).strftime("%Y%m%d"), "fcstTime": (start + timedelta(hours=h)).strftime("%H%M"), "fcstValue": v}
|
||||
for h in range(hours) for c, v in values
|
||||
]
|
||||
|
||||
def clouds(client, points, days=3):
|
||||
start = now.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None) - timedelta(days=1)
|
||||
times = [(start + timedelta(hours=h)).strftime("%Y-%m-%dT%H:00") for h in range(24 * (days + 2))]
|
||||
h = {"time": times}
|
||||
for m in ("ecmwf_ifs025", "gfs_seamless", "jma_seamless", "icon_seamless"):
|
||||
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])
|
||||
|
||||
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")])))
|
||||
monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "테스트", "dmX": "37.56", "dmY": "126.91"}]))
|
||||
monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{
|
||||
"stationName": "테스트", "pm25Value": "10", "pm10Value": "20", "pm25Grade": "1", "pm10Grade": "1",
|
||||
"dataTime": now.replace(minute=0).strftime("%Y-%m-%d %H:%M"),
|
||||
}]))
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([]))
|
||||
monkeypatch.setattr(sky_service, "fetch_clouds", clouds)
|
||||
monkeypatch.setattr(week_service, "fetch_mid", lambda *a: _async(({}, {})))
|
||||
monkeypatch.setattr(week_service, "fetch_holidays", lambda *a: _async([]))
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda *a: _async([{
|
||||
"contentid": "77", "title": "테스트 축제", "addr1": "서울", "eventstartdate": now.strftime("%Y%m%d"),
|
||||
"eventenddate": (now + timedelta(days=2)).strftime("%Y%m%d"),
|
||||
}]))
|
||||
monkeypatch.setattr(season_service, "fetch_solar_terms", lambda *a: _async([]))
|
||||
@@ -0,0 +1,78 @@
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from router.router import app
|
||||
|
||||
REGION = "1144000000"
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _signup(c, login_id="mina_01", nickname="망원동주민"):
|
||||
return (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": nickname})).json()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_signup_login_refresh_me():
|
||||
async with client() as c:
|
||||
body = await _signup(c)
|
||||
assert body["result"]["success"] is True and body["me"]["nickname"] == "망원동주민"
|
||||
dup = await _signup(c)
|
||||
assert dup["result"]["desc"] == "AUTH_DUPLICATE_ID"
|
||||
bad = (await c.post("/v1/auth/login", json={"login_id": "mina_01", "password": "wrong-pass"})).json()
|
||||
assert bad["result"]["desc"] == "AUTH_FAILED"
|
||||
ok = (await c.post("/v1/auth/login", json={"login_id": "mina_01", "password": "password1"})).json()
|
||||
me = (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {ok['access_token']}"})).json()
|
||||
assert me["me"]["login_id"] == "mina_01"
|
||||
again = (await c.post("/v1/auth/refresh", json={"refresh_token": ok["refresh_token"]})).json()
|
||||
assert again["access_token"]
|
||||
assert (await c.post("/v1/auth/refresh", json={"refresh_token": ok["access_token"]})).json()["result"]["desc"] == "AUTH_TOKEN_INVALID"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_signup_rejects_bad_input():
|
||||
async with client() as c:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": "AB", "password": "short", "nickname": "x"})).json()
|
||||
assert body["result"]["desc"] == "INVALID_INPUT"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_reactions_require_login_and_update_feed(offline):
|
||||
async with client() as c:
|
||||
feed = (await c.get("/v1/feed", params={"region": REGION})).json()
|
||||
post_id = feed["posts"][0]["post_id"]
|
||||
assert (await c.post(f"/v1/reaction/post/{post_id}/like")).status_code == 401
|
||||
|
||||
token = (await _signup(c))["access_token"]
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
liked = (await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)).json()
|
||||
again = (await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)).json()
|
||||
assert liked["like_count"] == 1 and again["like_count"] == 1
|
||||
assert (await c.post(f"/v1/reaction/post/{post_id}/save", headers=h)).json()["saved"] is True
|
||||
|
||||
comment = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": " 빨래 지금 널어요! "})).json()["comment"]
|
||||
assert comment["body"] == "빨래 지금 널어요!" and comment["mine"] is True
|
||||
too_long = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": "가" * 61})).json()
|
||||
assert too_long["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await c.post(f"/v1/reaction/comment/{comment['comment_id']}/like", headers=h)).json()["like_count"] == 1
|
||||
|
||||
listed = (await c.get(f"/v1/reaction/post/{post_id}/comment/list")).json()
|
||||
assert [x["body"] for x in listed["comments"]] == ["빨래 지금 널어요!"] and listed["comments"][0]["mine"] is False
|
||||
|
||||
mine = (await c.get("/v1/feed", params={"region": REGION}, headers=h)).json()
|
||||
p = next(x for x in mine["posts"] if x["post_id"] == post_id)
|
||||
assert p["liked"] is True and p["saved"] is True and p["like_count"] == 1 and p["comment_count"] == 1
|
||||
|
||||
other = (await _signup(c, "other_02", "다른사람"))["access_token"]
|
||||
assert (await c.delete(f"/v1/reaction/comment/{comment['comment_id']}", headers={"Authorization": f"Bearer {other}"})).json()["result"]["desc"] == "NOT_FOUND"
|
||||
assert (await c.delete(f"/v1/reaction/comment/{comment['comment_id']}", headers=h)).json()["result"]["success"] is True
|
||||
assert (await c.get("/v1/reaction/save/list", headers=h)).json()["posts"][0]["post_id"] == post_id
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_bad_token_is_401():
|
||||
async with client() as c:
|
||||
res = await c.get("/v1/auth/me", headers={"Authorization": "Bearer not-a-token"})
|
||||
assert res.status_code == 401
|
||||
@@ -0,0 +1,43 @@
|
||||
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 crud.feed_crud import FeedCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from router.router import app
|
||||
from services.feed_service import build_feed_day
|
||||
|
||||
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")))
|
||||
return [r[0] for r in rows]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_build_day_adds_weekend_post_only_from_thursday():
|
||||
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())
|
||||
assert PostType.WEEK.value not in await _posts(monday)
|
||||
assert (await _posts(thursday)).count(PostType.WEEK.value) == 1
|
||||
assert (await _posts(thursday))[0] == PostType.WEATHER.value
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
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
|
||||
assert body["hero"]["temp_c"] == 20 and len(body["hero"]["top3"]) == 3
|
||||
assert len(body["stories"]) == 23
|
||||
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", "rows"]
|
||||
assert len(weather["slides"][0]["hours"]) == 8
|
||||
assert body["bands"]["events"][0]["name"] == "테스트 축제"
|
||||
@@ -0,0 +1,9 @@
|
||||
from common.utils.geo import haversine_km
|
||||
|
||||
|
||||
def test_haversine_seoul_busan_about_325km():
|
||||
assert 320 < haversine_km(37.5665, 126.9780, 35.1796, 129.0756) < 330
|
||||
|
||||
|
||||
def test_haversine_same_point_is_zero():
|
||||
assert haversine_km(37.5, 127.0, 37.5, 127.0) == 0
|
||||
@@ -0,0 +1,14 @@
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from router.router import app
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_healthz_reports_db_and_redis():
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
res = await client.get("/healthz")
|
||||
body = res.json()
|
||||
assert res.status_code == 200
|
||||
assert body["db"] is True
|
||||
assert body["redis"] is True
|
||||
@@ -0,0 +1,68 @@
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
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.utils.kma_time import kst_midnight, now_kst
|
||||
from router.router import app
|
||||
|
||||
REGION = "1141000000"
|
||||
|
||||
|
||||
async def _async(v):
|
||||
return v
|
||||
|
||||
|
||||
def _vilage(*_):
|
||||
start = kst_midnight(now_kst().date())
|
||||
items = []
|
||||
for h in range(24 * 4):
|
||||
at = start + timedelta(hours=h)
|
||||
for c, v in [("TMP", "21"), ("SKY", "1"), ("PTY", "0"), ("POP", "0"), ("PCP", "강수없음"), ("REH", "50"), ("WSD", "1.5")]:
|
||||
items.append({"category": c, "fcstDate": at.strftime("%Y%m%d"), "fcstTime": at.strftime("%H%M"), "fcstValue": v})
|
||||
return items
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fakes(monkeypatch):
|
||||
now = now_kst()
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage()))
|
||||
monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "신촌동", "dmX": "37.565", "dmY": "126.937"}]))
|
||||
monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{
|
||||
"stationName": "신촌동", "pm25Value": "10", "pm10Value": "20", "pm25Grade": "1", "pm10Grade": "1",
|
||||
"dataTime": now.replace(minute=0).strftime("%Y-%m-%d %H:%M"),
|
||||
}]))
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([]))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_ranks_all_23_with_3_day_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"]) == 23 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"])
|
||||
assert 0 <= body["weather_score"] <= 100
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_filters_core(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/list", params={"region": REGION, "core": True})).json()
|
||||
assert {i["code"] for i in body["items"]} == {"picnic", "hiking", "camping", "stars"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
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 sum(f["weight"] for f in body["factors"]) == 100
|
||||
assert body["zero_rules"] == "비 확률 80% 이상 또는 바람 14m/s 이상이면 바로 0점"
|
||||
assert body["limit"].startswith("모기")
|
||||
@@ -0,0 +1,64 @@
|
||||
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, temp_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)
|
||||
|
||||
|
||||
def _defn(**kw):
|
||||
base = dict(
|
||||
weight_temp=30, weight_rain=25, weight_wind=15, weight_humidity=10, weight_air=10, weight_time=10,
|
||||
factor_rules={
|
||||
"temp": {"type": "range", "lo": 18, "hi": 24}, "rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 2, "limit": 10},
|
||||
"humidity": {"type": "range", "lo": 40, "hi": 60}, "time": {"type": "weekday", "fri": 100, "default": 78},
|
||||
},
|
||||
zero_rules=[{"field": "rain_prob", "op": ">=", "value": 80}],
|
||||
)
|
||||
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 test_perfect_evening_scores_100():
|
||||
r = evaluate(_defn(), [[_h(19), _h(20)]], CTX)
|
||||
assert r.score == 100 and r.zero_reason is None
|
||||
assert r.notes["temp"] == "체감 21°, 편한 범위 18~24° 안"
|
||||
|
||||
|
||||
def test_temp_outside_range_loses_8_per_degree():
|
||||
assert temp_score({"type": "range", "lo": 18, "hi": 24}, 15)[0] == 76
|
||||
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°")
|
||||
|
||||
|
||||
def test_rain_dry_and_wet():
|
||||
assert rain_score({"dir": "dry"}, 30, False)[0] == 70
|
||||
assert rain_score({"dir": "dry"}, 30, True)[0] == 0
|
||||
assert rain_score({"dir": "wet"}, 30, True)[0] == 100
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_best_window_is_chosen():
|
||||
r = evaluate(_defn(), [[_h(7, feels=5)], [_h(20, feels=21)]], CTX)
|
||||
assert r.window == (20, 20)
|
||||
|
||||
|
||||
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점"
|
||||
assert zero_rules_text([]) == "없음 (재미로 보는 지수)"
|
||||
|
||||
|
||||
def test_moon_full_and_new():
|
||||
assert illumination(datetime(2000, 1, 6, 18, 14, tzinfo=timezone.utc)) < 0.01
|
||||
assert illumination(datetime(2000, 1, 21, 12, tzinfo=timezone.utc)) > 0.95
|
||||
@@ -0,0 +1,52 @@
|
||||
from datetime import datetime
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import KST, latest_ultra_base, latest_vilage_base
|
||||
from services.external.kma import parse_amount, parse_vilage
|
||||
|
||||
|
||||
def _kst(y, mo, d, h, mi=0):
|
||||
return datetime(y, mo, d, h, mi, tzinfo=KST)
|
||||
|
||||
|
||||
def test_latest_vilage_base_waits_10_minutes_after_issue():
|
||||
assert latest_vilage_base(_kst(2026, 10, 1, 17, 9)) == _kst(2026, 10, 1, 14)
|
||||
assert latest_vilage_base(_kst(2026, 10, 1, 17, 10)) == _kst(2026, 10, 1, 17)
|
||||
|
||||
|
||||
def test_latest_vilage_base_before_first_issue_uses_yesterday_23():
|
||||
assert latest_vilage_base(_kst(2026, 10, 1, 2, 5)) == _kst(2026, 9, 30, 23)
|
||||
|
||||
|
||||
def test_latest_ultra_base_available_from_45_minutes():
|
||||
assert latest_ultra_base(_kst(2026, 10, 1, 10, 44)) == _kst(2026, 10, 1, 9, 30)
|
||||
assert latest_ultra_base(_kst(2026, 10, 1, 10, 45)) == _kst(2026, 10, 1, 10, 30)
|
||||
|
||||
|
||||
def test_parse_amount_text():
|
||||
assert parse_amount("강수없음") == 0
|
||||
assert parse_amount("1mm 미만") == 0.5
|
||||
assert parse_amount("1.0mm") == 1.0
|
||||
assert parse_amount("30.0~50.0mm") == 30.0
|
||||
assert parse_amount("50.0mm 이상") == 50.0
|
||||
|
||||
|
||||
def _item(d, t, cat, val):
|
||||
return {"baseDate": "20261001", "baseTime": "1400", "category": cat, "fcstDate": d, "fcstTime": t, "fcstValue": val, "nx": 59, "ny": 127}
|
||||
|
||||
|
||||
def test_parse_vilage_groups_rows_by_hour_and_maps_codes():
|
||||
items = [
|
||||
_item("20261001", "1500", c, v)
|
||||
for c, v in [("TMP", "24"), ("SKY", "3"), ("PTY", "1"), ("POP", "60"), ("PCP", "1mm 미만"), ("REH", "55"), ("WSD", "2.1")]
|
||||
] + [_item("20261002", "0600", "TMN", "13.0"), _item("20261002", "1500", "TMX", "23.0")]
|
||||
hourly, daily = parse_vilage(items)
|
||||
v = hourly[_kst(2026, 10, 1, 15)]
|
||||
assert (v["temp_c"], v["sky"], v["rain_type"], v["rain_prob"], v["rain_mm"], v["wind_ms"]) == (24.0, Sky.PARTLY, RainType.RAIN, 60, 0.5, 2.1)
|
||||
assert daily[datetime(2026, 10, 2).date()] == {"temp_min_c": 13.0, "temp_max_c": 23.0}
|
||||
|
||||
|
||||
def test_service_key_is_decoded_when_given_encoded():
|
||||
from config.settings import Settings
|
||||
assert Settings(data_go_kr_service_key="a%2Bb%3D%3D").data_go_kr_service_key == "a+b=="
|
||||
assert Settings(data_go_kr_service_key="a+b==").data_go_kr_service_key == "a+b=="
|
||||
@@ -0,0 +1,74 @@
|
||||
from datetime import datetime
|
||||
|
||||
from common.database.model.models import WeatherHourly
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import KST
|
||||
from services.external.airkorea import parse_realtime
|
||||
from services.external.kma import active_warnings, parse_ultra
|
||||
from services.now_service import _tomorrow
|
||||
from services.warning_service import warning_applies
|
||||
|
||||
|
||||
def _kst(d, h):
|
||||
return datetime(2026, 10, d, h, tzinfo=KST)
|
||||
|
||||
|
||||
def test_parse_ultra_reads_rain_and_temp():
|
||||
items = [
|
||||
{"category": c, "fcstDate": "20261002", "fcstTime": "1000", "fcstValue": v}
|
||||
for c, v in [("PTY", "1"), ("RN1", "1mm 미만"), ("T1H", "17")]
|
||||
]
|
||||
assert parse_ultra(items) == [{"at": _kst(2, 10), "rain_type": RainType.RAIN, "rain_mm": 0.5, "temp_c": 17.0}]
|
||||
|
||||
|
||||
def _event(area, var, cmd, tm, seq=1, stress=0):
|
||||
return {"areaCode": area, "warnVar": var, "warnStress": stress, "command": cmd, "cancel": "0", "tmFc": tm, "tmSeq": seq}
|
||||
|
||||
|
||||
def test_active_warnings_uses_latest_command_per_zone_and_type():
|
||||
events = [
|
||||
_event("L1100400", 1, 1, 202610010900),
|
||||
_event("L1100400", 1, 2, 202610011800),
|
||||
_event("L1090000", 7, 1, 202610020300, stress=1),
|
||||
_event("S1323400", 6, 1, 202610020900),
|
||||
]
|
||||
assert active_warnings(events) == [{"warning_zone_code": "L1090000", "warning_type": 7, "level": 2}]
|
||||
|
||||
|
||||
def test_warning_applies_to_parent_and_child_zones():
|
||||
assert warning_applies("L1100400", "L1100400")
|
||||
assert warning_applies("L1100400", "L1100000")
|
||||
assert warning_applies("L1120000", "L1120100")
|
||||
assert not warning_applies("L1100400", "L1100100")
|
||||
assert not warning_applies("L1100400", "L1090000")
|
||||
|
||||
|
||||
def test_parse_realtime_handles_24h_and_missing_values():
|
||||
rows = parse_realtime([
|
||||
{"stationName": "마포구", "pm25Value": "11", "pm10Value": "24", "pm25Grade": "1", "pm10Grade": "2", "dataTime": "2026-10-01 24:00"},
|
||||
{"stationName": "점검중", "pm25Value": "-", "pm10Value": "-", "pm25Grade": None, "pm10Grade": None, "dataTime": "2026-10-02 08:00"},
|
||||
])
|
||||
assert rows[0] == {"station_name": "마포구", "pm25": 11, "pm10": 24, "grade": 2, "measured_at": _kst(2, 0)}
|
||||
assert rows[1]["pm25"] is None and rows[1]["grade"] is None
|
||||
|
||||
|
||||
def _row(h, rain=RainType.NONE, mm=0.0, sky=Sky.CLEAR, temp=16.0):
|
||||
return WeatherHourly(forecast_at=_kst(3, h), rain_type=rain.value, rain_mm=mm, sky=sky.value, temp_c=temp)
|
||||
|
||||
|
||||
def test_tomorrow_text_and_commute_rows():
|
||||
rain_from, text, commute = _tomorrow([_row(8), _row(15, RainType.RAIN, 0.5), _row(19, RainType.RAIN, 2.0, temp=18.0)])
|
||||
assert rain_from == _kst(3, 15)
|
||||
assert text == "내일은 오후 3시쯤부터 부슬부슬 와요"
|
||||
assert [(c.label, c.text) for c in commute] == [("내일 출근 8시", "맑음 16°"), ("내일 퇴근 7시", "비 18°")]
|
||||
|
||||
|
||||
def test_tomorrow_without_rain():
|
||||
assert _tomorrow([_row(8)])[1] == "내일은 비 소식이 없어요"
|
||||
|
||||
|
||||
def test_ieyo_particle():
|
||||
from common.utils.text import ieyo
|
||||
assert ieyo("환기") == "환기예요"
|
||||
assert ieyo("야장각") == "야장각이에요"
|
||||
assert ieyo("아아→뜨아") == "아아→뜨아예요"
|
||||
@@ -0,0 +1,42 @@
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from router.router import app
|
||||
|
||||
|
||||
async def _get(path: str, **params):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
return (await client.get(path, params=params)).json()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_region_list_has_all_256_districts():
|
||||
body = await _get("/v1/region/list")
|
||||
assert body["result"]["success"] is True
|
||||
assert len(body["regions"]) == 256
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_region_search_by_name():
|
||||
body = await _get("/v1/region/list", q="마포")
|
||||
assert [r["name"] for r in body["regions"]] == ["서울 마포구"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_nearest_from_mangwon_park_is_mapo():
|
||||
body = await _get("/v1/region/nearest", lat=37.5555, lon=126.8950)
|
||||
assert body["region"]["name"] == "서울 마포구"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_nearest_rejects_point_outside_korea():
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
res = await client.get("/v1/region/nearest", params={"lat": 10, "lon": 127})
|
||||
assert res.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_enum_query_param_accepts_numeric_string():
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
res = await client.get("/v1/season/article/list", params={"category": "2"})
|
||||
assert res.status_code == 200 and all(a["category"] == 2 for a in res.json()["articles"])
|
||||
@@ -0,0 +1,40 @@
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
import services.season_service as season_service
|
||||
from common.utils.kma_time import now_kst
|
||||
from router.router import app
|
||||
|
||||
|
||||
async def _async(v):
|
||||
return v
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_season_week_composes_headline_and_term_progress(monkeypatch):
|
||||
today = now_kst().date()
|
||||
past, nxt = today - timedelta(days=5), today + timedelta(days=10)
|
||||
|
||||
async def fake_terms(client, year, month):
|
||||
rows = [{"term_date": past, "name": "추분"}, {"term_date": nxt, "name": "한로"}]
|
||||
return [r for r in rows if r["term_date"].year == year and r["term_date"].month == month]
|
||||
|
||||
monkeypatch.setattr(season_service, "fetch_solar_terms", fake_terms)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/season/week")).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert body["term_now"]["name"] == "추분" and body["term_next"]["name"] == "한로"
|
||||
assert body["headline"].startswith("추분 지나 5일째")
|
||||
assert body["progress"] == round(5 / 15, 2)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_article_detail_and_not_found():
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
listed = (await client.get("/v1/season/article/list")).json()["articles"]
|
||||
first = (await client.get(f"/v1/season/article/{listed[0]['article_id']}")).json()
|
||||
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"
|
||||
@@ -0,0 +1,65 @@
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
import services.sky_service as sky_service
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from router.router import app
|
||||
|
||||
|
||||
def _fake_response(points, days):
|
||||
from datetime import datetime, timedelta
|
||||
start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=1)
|
||||
times = [(start + timedelta(hours=h)).strftime("%Y-%m-%dT%H:00") for h in range(24 * (days + 1))]
|
||||
hourly = {"time": times}
|
||||
for m in ("ecmwf_ifs025", "gfs_seamless", "jma_seamless", "icon_seamless"):
|
||||
hourly[f"cloud_cover_low_{m}"] = [0] * len(times)
|
||||
hourly[f"cloud_cover_mid_{m}"] = [20] * len(times)
|
||||
hourly[f"cloud_cover_high_{m}"] = [50] * len(times)
|
||||
return [{"hourly": hourly} for _ in points]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def clean():
|
||||
async def wipe():
|
||||
await DB_SESSION_MNG.execute_lambda_run([
|
||||
lambda s: s.execute(text("DELETE FROM sky_score")),
|
||||
lambda s: s.execute(text("DELETE FROM cloud_hourly")),
|
||||
])
|
||||
keys = [k async for k in REDIS.conn.scan_iter("sky:*")]
|
||||
if keys:
|
||||
await REDIS.conn.delete(*keys)
|
||||
await wipe()
|
||||
yield
|
||||
await wipe()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_sky_view_scores_three_days_with_spots(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:
|
||||
body = (await client.get("/v1/sky", params={"region": "1144000000"})).json()
|
||||
|
||||
assert body["result"]["success"] is True
|
||||
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 255 <= body["sunset_azimuth"] <= 280
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_sky_ranking_has_30_spots_sorted(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:
|
||||
body = (await client.get("/v1/sky/ranking")).json()
|
||||
scores = [i["score"] for i in body["items"]]
|
||||
assert len(scores) == 30 and scores == sorted(scores, reverse=True)
|
||||
assert body["items"][0]["rank"] == 1 and body["items"][0]["note"]
|
||||
@@ -0,0 +1,45 @@
|
||||
from datetime import datetime, 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
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_clear_sky_is_only_soft():
|
||||
assert grade(score(CLEAR, 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
|
||||
|
||||
|
||||
def test_overcast_low_clouds_is_gray():
|
||||
gray = Layers(low=100, mid=100, high=100)
|
||||
assert grade(score(gray, gray, gray)) is SkyGrade.GRAY
|
||||
|
||||
|
||||
def test_confidence_from_model_spread():
|
||||
assert confidence([70, 72, 68, 71]) is Confidence.HIGH
|
||||
assert confidence([40, 80, 60, 90]) is Confidence.LOW
|
||||
assert confidence([70]) is Confidence.LOW
|
||||
|
||||
|
||||
def test_destination_point_is_at_given_distance():
|
||||
lat, lon = destination(37.56, 126.91, 266, 50)
|
||||
assert abs(haversine_km(37.56, 126.91, lat, lon) - 50) < 0.1
|
||||
assert lon < 126.91
|
||||
|
||||
|
||||
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 == ["해 져요", "가장 붉을 때", "보랏빛 하늘"]
|
||||
@@ -0,0 +1,34 @@
|
||||
from datetime import date, datetime
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from services.calc.sun import sun_times
|
||||
from services.calc.weather_calc import discomfort_index, feels_like_c
|
||||
|
||||
|
||||
def test_discomfort_index_21c_68pct():
|
||||
assert discomfort_index(21, 68) == 68
|
||||
|
||||
|
||||
def test_feels_like_winter_uses_wind_chill():
|
||||
assert feels_like_c(0, 50, 5.0, 1) < -4
|
||||
|
||||
|
||||
def test_feels_like_winter_no_wind_is_same_temp():
|
||||
assert feels_like_c(5, 50, 0.5, 12) == 5
|
||||
|
||||
|
||||
def test_feels_like_summer_humid_is_hotter():
|
||||
assert feels_like_c(30, 80, 2.0, 8) > feels_like_c(30, 30, 2.0, 8)
|
||||
|
||||
|
||||
def _minutes_kst(dt: datetime) -> int:
|
||||
k = dt.astimezone(KST)
|
||||
return k.hour * 60 + k.minute
|
||||
|
||||
|
||||
def test_sun_times_seoul_matches_open_meteo_within_3_minutes():
|
||||
t = sun_times(date(2026, 10, 1), 37.55, 126.875)
|
||||
assert abs(_minutes_kst(t.sunrise_at) - (6 * 60 + 27)) <= 3
|
||||
assert abs(_minutes_kst(t.sunset_at) - (18 * 60 + 16)) <= 3
|
||||
assert 20 <= (t.dusk_end_at - t.sunset_at).total_seconds() / 60 <= 35
|
||||
assert 255 <= t.sunset_azimuth <= 268
|
||||
@@ -0,0 +1,102 @@
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
import services.air_service as air_service
|
||||
import services.now_service as now_service
|
||||
import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
from common.cache.redis_client import REDIS
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from router.router import app
|
||||
|
||||
REGION = "1144000000"
|
||||
|
||||
|
||||
def _vilage(*_):
|
||||
start = kst_midnight(now_kst().date())
|
||||
items = []
|
||||
for h in range(48):
|
||||
at = start + timedelta(hours=h)
|
||||
rainy = h == 24 + 15
|
||||
for c, v in [("TMP", "16"), ("SKY", "1"), ("PTY", "1" if rainy else "0"), ("POP", "60" if rainy else "0"),
|
||||
("PCP", "1mm 미만" if rainy else "강수없음"), ("REH", "60"), ("WSD", "1.5")]:
|
||||
items.append({"category": c, "fcstDate": at.strftime("%Y%m%d"), "fcstTime": at.strftime("%H%M"), "fcstValue": v})
|
||||
return items
|
||||
|
||||
|
||||
def _ultra(*_):
|
||||
start = now_kst().replace(minute=0, second=0, microsecond=0)
|
||||
items = []
|
||||
for h in range(1, 7):
|
||||
at = start + timedelta(hours=h)
|
||||
for c, v in [("PTY", "0"), ("RN1", "강수없음"), ("T1H", "17")]:
|
||||
items.append({"category": c, "fcstDate": at.strftime("%Y%m%d"), "fcstTime": at.strftime("%H%M"), "fcstValue": v})
|
||||
return items
|
||||
|
||||
|
||||
async def _async(v):
|
||||
return v
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def clean():
|
||||
async def wipe():
|
||||
await DB_SESSION_MNG.execute_lambda_run([
|
||||
lambda s: s.execute(text(f"DELETE FROM weather_hourly WHERE region_code='{REGION}'")),
|
||||
lambda s: s.execute(text(f"DELETE FROM weather_daily WHERE region_code='{REGION}'")),
|
||||
lambda s: s.execute(text("DELETE FROM air_quality")),
|
||||
lambda s: s.execute(text("DELETE FROM air_station")),
|
||||
lambda s: s.execute(text("DELETE FROM weather_warning")),
|
||||
])
|
||||
keys = [k async for k in REDIS.conn.scan_iter("ultra:*")] + [k async for k in REDIS.conn.scan_iter("warning:*")] + ["air:tried"]
|
||||
await REDIS.conn.delete(*keys)
|
||||
await wipe()
|
||||
yield
|
||||
await wipe()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_now_combines_rain_tomorrow_air_and_warnings(monkeypatch, clean):
|
||||
now = now_kst()
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage()))
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
||||
monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "마포구", "dmX": "37.5555", "dmY": "126.9055"}]))
|
||||
monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{
|
||||
"stationName": "마포구", "pm25Value": "11", "pm10Value": "24", "pm25Grade": "1", "pm10Grade": "1",
|
||||
"dataTime": now.replace(minute=0).strftime("%Y-%m-%d %H:%M"),
|
||||
}]))
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", lambda *a: _async([
|
||||
{"areaCode": "L1100000", "warnVar": 4, "warnStress": 0, "command": 1, "cancel": "0", "tmFc": 202610020300, "tmSeq": 1},
|
||||
]))
|
||||
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/weather/now", params={"region": REGION})).json()
|
||||
|
||||
assert body["result"]["success"] is True
|
||||
assert body["rain_2h"]["will_rain"] is False and len(body["rain_2h"]["hours"]) == 2
|
||||
assert body["tomorrow"]["text"] == "내일은 오후 3시쯤부터 부슬부슬 와요"
|
||||
assert [c["text"] for c in body["tomorrow"]["commute"]] == ["맑음 16°", "맑음 16°"]
|
||||
assert body["air"]["station_name"] == "마포구" and body["air"]["text"] == "초미세먼지 11 좋음"
|
||||
assert body["warnings"] == [{"warning_type": 4, "level": 1, "text": "건조주의보"}]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_now_warning_failure_is_unknown_not_none(monkeypatch, clean):
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
|
||||
async def fail(*a):
|
||||
raise DataGoKrRequestFailed("HTTP 504")
|
||||
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage()))
|
||||
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(_ultra()))
|
||||
monkeypatch.setattr(air_service, "fetch_stations", fail)
|
||||
monkeypatch.setattr(air_service, "fetch_realtime", fail)
|
||||
monkeypatch.setattr(warning_service, "fetch_warning_events", fail)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/weather/now", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert "warnings" not in body and "air" not in body
|
||||
@@ -0,0 +1,92 @@
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
import services.weather_service as weather_service
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from router.router import app
|
||||
|
||||
REGION = "1144000000"
|
||||
|
||||
|
||||
def _fake_items(base):
|
||||
"""그날 0시부터 이틀치, 맑음·18도·비 없음."""
|
||||
start = kst_midnight(now_kst().date())
|
||||
items = []
|
||||
for h in range(48):
|
||||
at = start + timedelta(hours=h)
|
||||
d, t = at.strftime("%Y%m%d"), at.strftime("%H%M")
|
||||
for c, v in [("TMP", "18"), ("SKY", "1"), ("PTY", "0"), ("POP", "0"), ("PCP", "강수없음"), ("REH", "60"), ("WSD", "1.5")]:
|
||||
items.append({"category": c, "fcstDate": d, "fcstTime": t, "fcstValue": v})
|
||||
return items
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def clean_region():
|
||||
async def wipe():
|
||||
await DB_SESSION_MNG.execute_lambda_run([
|
||||
lambda s: s.execute(text(f"DELETE FROM weather_hourly WHERE region_code='{REGION}'")),
|
||||
lambda s: s.execute(text(f"DELETE FROM weather_daily WHERE region_code='{REGION}'")),
|
||||
lambda s: s.execute(text(f"DELETE FROM sun_time WHERE region_code='{REGION}'")),
|
||||
])
|
||||
await wipe()
|
||||
yield
|
||||
await wipe()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_today_fetches_stores_and_returns_8_slots(monkeypatch, clean_region):
|
||||
calls = []
|
||||
|
||||
async def fake_fetch(client, nx, ny, base):
|
||||
calls.append(base)
|
||||
return _fake_items(base)
|
||||
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", fake_fetch)
|
||||
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"]["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"][6]["icon"] == "sunset" and body["slots"][6]["note"] == "노을"
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_today_second_call_uses_db_without_fetching(monkeypatch, clean_region):
|
||||
calls = []
|
||||
|
||||
async def fake_fetch(client, nx, ny, base):
|
||||
calls.append(base)
|
||||
return _fake_items(base)
|
||||
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", fake_fetch)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
await client.get("/v1/weather/today", params={"region": REGION})
|
||||
await client.get("/v1/weather/today", params={"region": REGION})
|
||||
assert len(calls) == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_today_unknown_region_is_not_found():
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/weather/today", params={"region": "0000000000"})).json()
|
||||
assert body["result"]["success"] is False and body["result"]["desc"] == "NOT_FOUND"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_today_fetch_failure_without_data_is_external_error(monkeypatch, clean_region):
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
|
||||
async def failing_fetch(client, nx, ny, base):
|
||||
raise DataGoKrRequestFailed("HTTP 403")
|
||||
|
||||
monkeypatch.setattr(weather_service, "fetch_vilage", failing_fetch)
|
||||
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"
|
||||
@@ -0,0 +1,113 @@
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
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
|
||||
import services.week_service as week_service
|
||||
from common.database.model.models import Event
|
||||
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.week_service import _status
|
||||
|
||||
REGION = "1144000000"
|
||||
|
||||
|
||||
def test_mid_word_maps_text():
|
||||
assert mid_word("맑음") == (Sky.CLEAR, RainType.NONE)
|
||||
assert mid_word("구름많고 소나기") == (Sky.PARTLY, RainType.SHOWER)
|
||||
assert mid_word("흐리고 비/눈") == (Sky.CLOUDY, RainType.SLEET)
|
||||
|
||||
|
||||
def test_parse_mid_days_from_base():
|
||||
base = datetime(2026, 10, 2, 6, tzinfo=KST)
|
||||
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}
|
||||
|
||||
|
||||
def test_latest_mid_base():
|
||||
assert latest_mid_base(datetime(2026, 10, 2, 6, 20, tzinfo=KST)) == datetime(2026, 10, 1, 18, tzinfo=KST)
|
||||
assert latest_mid_base(datetime(2026, 10, 2, 6, 30, tzinfo=KST)) == datetime(2026, 10, 2, 6, tzinfo=KST)
|
||||
|
||||
|
||||
def test_event_status_labels():
|
||||
today = date(2026, 10, 2)
|
||||
ev = lambda s, e: Event(start_date=s, end_date=e) # noqa: E731
|
||||
assert _status(ev(date(2026, 10, 1), date(2026, 10, 5)), today) == ("live", "진행 중")
|
||||
assert _status(ev(date(2026, 10, 3), date(2026, 10, 3)), today) == ("soon", "이번 토요일")
|
||||
assert _status(ev(date(2026, 10, 20), date(2026, 10, 21)), today) == ("soon", "D-18")
|
||||
|
||||
|
||||
async def _async(v):
|
||||
return v
|
||||
|
||||
|
||||
def _vilage(*_):
|
||||
start = kst_midnight(now_kst().date())
|
||||
items = []
|
||||
for h in range(24 * 4):
|
||||
at = start + timedelta(hours=h)
|
||||
rainy = h == 24 * 2 + 15
|
||||
for c, v in [("TMP", "18"), ("SKY", "1"), ("PTY", "1" if rainy else "0"), ("POP", "70" if rainy else "0"),
|
||||
("PCP", "1.0mm" if rainy else "강수없음"), ("REH", "50"), ("WSD", "1.5")]:
|
||||
items.append({"category": c, "fcstDate": at.strftime("%Y%m%d"), "fcstTime": at.strftime("%H%M"), "fcstValue": v})
|
||||
return items
|
||||
|
||||
|
||||
def _mid(*_):
|
||||
land = {f"wf{n}{p}": "맑음" for n in range(4, 8) for p in ("Am", "Pm")} | {f"rnSt{n}{p}": 10 for n in range(4, 8) for p in ("Am", "Pm")}
|
||||
ta = {f"taMin{n}": 11 for n in range(4, 8)} | {f"taMax{n}": 23 for n in range(4, 8)}
|
||||
return land, ta
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
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(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([
|
||||
{"contentid": "1", "title": "가을 축제", "addr1": "서울 마포구", "eventstartdate": (today + timedelta(days=3)).strftime("%Y%m%d"),
|
||||
"eventenddate": (today + timedelta(days=4)).strftime("%Y%m%d")},
|
||||
{"contentid": "2", "title": "상설 전시", "addr1": "서울", "eventstartdate": "20250101", "eventenddate": "20261231"},
|
||||
]))
|
||||
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([]))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_week_has_seven_days_with_holiday_and_rain(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week", params={"region": REGION})).json()
|
||||
days = body["days"]
|
||||
assert len(days) == 7
|
||||
assert days[1]["holiday"] == "테스트공휴일"
|
||||
assert days[2]["is_rainy"] is True and days[2]["rain_hours"] == [15, 16]
|
||||
assert days[6]["temp_max_c"] == 23
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_events_exclude_long_running_and_add_weather_fit(fakes):
|
||||
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"]] == ["가을 축제"]
|
||||
assert body["events"][0]["fit"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_places_put_indoor_first_on_rainy_day(fakes):
|
||||
rainy_day = (now_kst().date() + timedelta(days=2)).isoformat()
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
await client.get("/v1/week", params={"region": REGION})
|
||||
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
|
||||
Reference in new issue
Block a user