114 lines
5.4 KiB
Python
114 lines
5.4 KiB
Python
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"]
|