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", "blue"] assert plan["situation_label"] == "하늘이 넓게 물들 수 있어요" and plan["models_agree"] == plan["models_total"] == 2 assert plan["outlook"] == "" assert body["sunset"]["verdict"] == "go" and body["spots"][0]["direction"] @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_only_when_a_later_day_has_a_better_verdict(): from datetime import date, timedelta from common.database.model.models import SkyScore from common.enums import SkySituation today = date(2026, 10, 6) day = lambda i, v: SkyScore(score_date=today + timedelta(days=i), score=v) # noqa: E731 sit = lambda i, s: SkyScore(score_date=today + timedelta(days=i), score=48, situation=s.value) # noqa: E731 assert sky_service.outlook(day(0, 30), [day(0, 30), day(1, 35), day(2, 72)], today) == "모레가 더 나아요 · 나가 볼 만해요" assert sky_service.outlook(day(0, 80), [day(0, 80), day(1, 50), day(2, 40)], today) == "" 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) == "" few, glow = SkySituation.FEW, SkySituation.GLOW assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few), sit(2, glow)], today) == "모레가 더 나아요 · 하늘이 넓게 물들 수 있어요" assert sky_service.outlook(sit(0, few), [sit(0, few), sit(1, few)], 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 def test_score_rows_apply_air_at_sunset_and_keep_cloud_score_without_air(): from datetime import date, datetime, timedelta, timezone from types import SimpleNamespace from common.enums import SkyType from services.calc.sky_score import Layers from services.calc.sun import sun_times region = SimpleNamespace(code="R", lat=37.56, lon=126.91) today = date(2026, 10, 7) hour = sky_service._nearest_hour(sun_times(today, region.lat, region.lon).sunset_at) clouds = {("R", SkyType.SUNSET.value, km, hour, 3): Layers(0, 20, 0) for km in (20, 100)} now = datetime(2026, 10, 7, 3, tzinfo=timezone.utc) plain = sky_service._score_rows(region, today, clouds, now)[0]["score"] hourly = {("R", hour): SimpleNamespace(humidity=90, rain_prob=0)} om = {("R", sky_service._nearest_slot(hour)): SimpleNamespace(visibility_m=5000)} hazy = sky_service._score_rows(region, today, clouds, now, hourly, om)[0]["score"] assert hazy == round(plain * 0.6 * 0.75) rain = {("R", hour - timedelta(hours=3)): SimpleNamespace(humidity=50, rain_prob=80), ("R", hour): SimpleNamespace(humidity=50, rain_prob=10)} assert sky_service._score_rows(region, today, clouds, now, rain, {})[0]["score"] == min(100, round(plain * 1.15)) def test_nearest_slot_is_closest_three_hour_end(): from datetime import datetime, timezone at = lambda h, m=0: datetime(2026, 10, 7, h, m, tzinfo=timezone.utc) # noqa: E731 assert [sky_service._nearest_slot(at(h, m)).hour for h, m in ((8, 0), (9, 0), (10, 29), (10, 31))] == [9, 9, 9, 12]