# Conflicts: # backend/router/v1/index/index.py # backend/services/calc/index_calc.py # backend/services/index_service.py # backend/tests/conftest.py # backend/tests/test_index_api.py # backend/tests/test_index_calc.py # backend/tests/test_sky_api.py # backend/worker_main.py
137 lines
6.2 KiB
Python
137 lines
6.2 KiB
Python
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
|
|
plan = body["plan"]
|
|
assert plan["verdict"] == "go" and plan["headline"] == "나가 볼 만해요" and plan["when"] in ("오늘", "내일")
|
|
assert "알맞게" in plan["reason"]
|
|
assert plan["spot"]["name"] == "망원한강공원" and plan["best_at"]
|
|
assert [t["kind"] for t in plan["timeline"]] == ["golden", "sun", "peak", "blue"]
|
|
assert plan["outlook"].endswith("비슷해요")
|
|
|
|
|
|
@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"]
|
|
|
|
|
|
@pytest.mark.anyio
|
|
@pytest.mark.parametrize("region, expected", [
|
|
("4113500000", "일자산 허브천문공원"), # 분당구: 자기 구엔 명소가 없어도 30km 안 서울 명소
|
|
("2812500000", "북성포구"), # 인천 제물포구(옛 중구)
|
|
("2635000000", "중리노을전망대"), # 해운대구: 동쪽 바다보다 서쪽이 트인 영도가 먼저
|
|
])
|
|
async def test_sky_spots_by_distance(monkeypatch, clean, region, expected):
|
|
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": region})).json()
|
|
|
|
spots = body["spots"]
|
|
assert len(spots) == 3 and spots[0]["name"] == expected
|
|
assert all(s["distance_km"] <= sky_service.SPOT_RADIUS_KM for s in spots)
|
|
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():
|
|
from decimal import Decimal
|
|
|
|
from common.database.model.models import SunsetSpot
|
|
|
|
def spot(name, lat, west):
|
|
return SunsetSpot(name=name, description="", lat=Decimal(str(lat)), lon=Decimal("127.0"), sort_order=0 if west else 1)
|
|
|
|
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) == []
|
|
|
|
|
|
def test_outlook_points_to_a_better_day_only_when_clearly_better():
|
|
from datetime import date, timedelta
|
|
|
|
from common.database.model.models import SkyScore
|
|
|
|
today = date(2026, 10, 6)
|
|
day = lambda i, v: SkyScore(score_date=today + timedelta(days=i), score=v) # noqa: E731
|
|
assert sky_service.outlook(day(0, 30), [day(0, 30), day(1, 35), day(2, 72)], today) == "모레가 더 나아요 — 72점, 나가 볼 만해요"
|
|
assert sky_service.outlook(day(0, 80), [day(0, 80), day(1, 50), day(2, 40)], today).startswith("오늘이 가장 나아요")
|
|
assert sky_service.outlook(day(0, 50), [day(0, 50), day(1, 55), day(2, 45)], today) == "내일·모레도 비슷해요"
|
|
assert sky_service.outlook(day(2, 50), [day(2, 50)], today) == ""
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_clouds_are_stored_by_region_with_only_needed_hours(monkeypatch, clean):
|
|
async def fake_fetch(client, points, days=3):
|
|
return _fake_response(points, days)
|
|
|
|
monkeypatch.setattr(sky_service, "fetch_clouds", fake_fetch)
|
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
|
await client.get("/v1/sky", params={"region": "1144000000"})
|
|
|
|
err, rows = await DB_SESSION_MNG.execute_lambda(
|
|
lambda s: s.execute(text("SELECT kind, distance_km, forecast_at, model FROM cloud_hourly WHERE region_code = '1144000000'"))
|
|
)
|
|
rows = rows.all()
|
|
assert len(rows) == 2 * 2 * 3 * 2
|
|
assert {(r.kind, r.distance_km) for r in rows} == {(1, 20), (1, 100), (2, 20), (2, 100)}
|
|
assert {r.model for r in rows} == {3, 4}
|
|
assert len({r.forecast_at for r in rows}) == 6
|