구름 - 노을·일출 점수를 구 중심 20·100km 두 지점으로 계산 (50km 제외), 모델은 JMA·ICON 두 개만 사용 - cloud_hourly를 (구 코드, 방향, 거리, 시각, 모델) 키로 바꾸고 점수에 쓰는 시각만 저장 보조값 - openmeteo_hourly 신규: 자외선·가시거리·돌풍·기압·지표면 온도(끝 시각 값), 일조(3시간 합), 일사(평균·최대) - worker가 03·09·15·21시 10분에 구 256곳을 요청 11번으로 일괄 수집, 7일 지난 행 정리 - 새 응답에서 값이 비어 오면 이전 값을 유지(COALESCE) 지수 - 새 축 uv·sun·view 추가 (index_definition/index_score 칼럼, 비중 있는 지수에만 상세에 표시) - 빨래·멍뭉산책·피크닉·등산·러닝·가드닝·별보기·사진산책에 비중 배분, 자전거·캠핑·멍뭉산책에 돌풍·지표면 온도 0점 조건 - 자외선·가시거리 등 순간값은 가장 가까운 3시간 구간, 일조는 덮는 구간을 계산 창에 연결 - 보조값이 새로 오면 지수를 다시 계산하도록 재계산 기준에 fetched_at 추가 테스트 102개 통과 (PGSSLMODE=disable, JWT는 테스트용 환경변수).
150 lines
7.4 KiB
Python
150 lines
7.4 KiB
Python
from datetime import date, timedelta
|
|
from types import SimpleNamespace
|
|
|
|
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.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 _nearest_slot_end_hour, _slot_end_hour, windows_for
|
|
|
|
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_27_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"]) == 27 and len(body["top3"]) == 3
|
|
scores = [i["score"] for i in body["items"]]
|
|
assert scores == sorted(scores, reverse=True)
|
|
assert all(len(i["trend"]) == 3 for i in body["items"])
|
|
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("모기")
|
|
|
|
|
|
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)
|
|
|
|
|
|
@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%"
|