Files
o2o-weather/backend/tests/test_sky_api.py
T
minaChoi 997a366e76 feat: 축제·전시·콘서트·팝업 7일마다 수집, 피드 행사 종류 섞기
- 행사 수집을 화면 요청에서 빼고 worker 가 월 04:00(켤 때 7일 기록 없으면 한 번) 전국 17개 시도를 받는다
- 문화정보원 음악/콘서트(B000) 추가, 쪽·시도 사이 1초 간격으로 초당 요청 제한 회피
- 팝가(popga.co.kr) 팝업스토어 수집: 사이트맵 + 상세 JSON-LD, 바뀐 페이지만 다시 읽음
- 수집이 끝나면 Teams Workflows webhook 으로 종류별 건수 알림 (TEAMS_WEBHOOK_URL)
- event.kind(1=축제 2=전시 3=콘서트 4=팝업) 칸과 종류별 아이콘 추가
- 피드 행사 카드·띠를 축제→팝업→전시→콘서트 차례로 섞음
- 포스트 종류별 내용·피드 기획 문서 갱신

같은 작업 폴더의 다른 작업(외부 API 가드, 노을·달 계산, 각 API, 문서 파일 이름 정리 등)도 함께 담김.
2026-10-07 12:03:48 +09:00

125 lines
5.9 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", "blue"]
assert plan["situation_label"] == "하늘이 넓게 물들 수 있어요" and plan["models_agree"] == plan["models_total"] == 4
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) == ""