Files
o2o-weather/backend/tests/test_index_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

99 lines
4.6 KiB
Python

from datetime import date, timedelta
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.utils.kma_time import kst_midnight, now_kst
from router.router import app
from services.index_service import slot_days, slot_label
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
def _mid(*_):
land = {f"wf{n}{p}": "맑음" for n in range(4, 11) for p in ("Am", "Pm")} | {f"rnSt{n}{p}": 10 for n in range(4, 11) for p in ("Am", "Pm")}
ta = {f"taMin{n}": 12 for n in range(4, 11)} | {f"taMax{n}": 22 for n in range(4, 11)}
return land, ta
@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([]))
monkeypatch.setattr(weather_service, "fetch_mid", lambda *a: _async(_mid()))
@pytest.mark.anyio
async def test_index_list_ranks_all_27_with_today_tomorrow_weekend_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)
today = now_kst().date()
for i in body["items"]:
assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)]
assert not any(t["estimated"] for t in i["trend"][:2])
assert all(t["estimated"] for t in i["trend"][2:] if date.fromisoformat(t["day"]) > today + timedelta(days=3))
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("모기")
@pytest.mark.anyio
async def test_index_detail_has_four_score_bands_with_today_marked(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()
bands = body["bands"]
assert [(b["low"], b["high"]) for b in bands] == [(0, 29), (30, 59), (60, 79), (80, 100)]
assert all(b["text"] for b in bands)
current = [b for b in bands if b["current"]]
assert len(current) == 1 and current[0]["low"] <= body["index"]["score"] <= current[0]["high"]
def test_every_index_has_four_band_sentences():
import json
import os
seed = json.load(open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "index_definition.json"), encoding="utf-8"))
assert all(sorted(d["sentences"], key=int) == ["0", "30", "60", "80"] and all(d["sentences"].values()) for d in seed)