Files
o2o-weather/backend/tests/conftest.py
T
minaChoiandClaude Opus 5.5 e134295ce5 feat: 날씨각 백엔드 API (날씨·노을·지수·주말·계절·피드·로그인·반응)
- FastAPI + PostgreSQL + Redis, web·worker 분리, compose 에 backend·worker·postgres·redis 추가
- 기상청 단기·초단기·중기·특보, 에어코리아, Open-Meteo, TourAPI, 특일정보 연동 (첫 조회 때 받고 캐시)
- 매일 03:00 worker 가 전국 공통 피드 칸을 정하고 지난 데이터를 정리
- 시드: 시군구 256곳, 지수 23개, 노을 대표 지점·명소, 데이트 명소, 읽을거리
- pytest 66개 (테스트 전용 DB·Redis 사용)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 11:32:22 +09:00

115 lines
5.3 KiB
Python

import asyncio
import os
# 개발 DB·Redis 를 건드리지 않도록 테스트 전용 DB(<이름>_test)와 Redis 15번을 쓴다. 앱 import 전에 정해야 한다.
os.environ["DB_NAME"] = os.environ.get("TEST_DB_NAME", "nalssigak_test")
os.environ["REDIS_DB"] = "15"
import asyncpg # noqa: E402
import pytest # noqa: E402
from common.cache.redis_client import REDIS # noqa: E402
from common.database.db_session_manager import DB_SESSION_MNG # noqa: E402
from config.settings import settings # noqa: E402
INIT_SQL = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "postgres-init", "init.sql")
async def _create_test_db() -> None:
admin = await asyncpg.connect(host=settings.db_host, port=settings.db_port, user=settings.db_user, password=settings.db_password, database="postgres")
await admin.execute(f'DROP DATABASE IF EXISTS "{settings.db_name}" WITH (FORCE)')
await admin.execute(f'CREATE DATABASE "{settings.db_name}"')
await admin.close()
conn = await asyncpg.connect(host=settings.db_host, port=settings.db_port, user=settings.db_user, password=settings.db_password, database=settings.db_name)
with open(INIT_SQL, encoding="utf-8") as f:
await conn.execute(f.read())
await conn.close()
from scripts.load_seed import main as load_seed
assert await load_seed() == 0
await REDIS.conn.flushdb()
await REDIS.stop()
def pytest_sessionstart(session):
asyncio.run(_create_test_db())
@pytest.fixture
def anyio_backend():
return "asyncio"
_VOLATILE = (
"weather_hourly", "weather_daily", "cloud_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
"sky_score", "index_score", "post", "post_like", "post_save", "comment", "comment_like", "holiday", "solar_term", "users",
)
@pytest.fixture(autouse=True)
async def _reset_between_tests(anyio_backend):
"""테스트끼리 영향을 주지 않게 외부에서 받은 데이터와 Redis 를 비운다 (시드는 남김). 이벤트 루프가 테스트마다 새로 생겨 커넥션도 닫는다."""
yield
from sqlalchemy import text
await DB_SESSION_MNG.execute_lambda_run(
[lambda s: s.execute(text(f"TRUNCATE {', '.join(_VOLATILE)}")), lambda s: s.execute(text("DELETE FROM event WHERE source_id IS NOT NULL"))]
)
await REDIS.conn.flushdb()
await DB_SESSION_MNG.stop()
await REDIS.stop()
async def _async(v):
return v
@pytest.fixture
def offline(monkeypatch):
"""외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다."""
from datetime import timedelta
import services.air_service as air_service
import services.now_service as now_service
import services.season_service as season_service
import services.sky_service as sky_service
import services.warning_service as warning_service
import services.weather_service as weather_service
import services.week_service as week_service
from common.utils.kma_time import kst_midnight, now_kst
now = now_kst()
def hourly(hours: int, values: list[tuple[str, str]]) -> list[dict]:
start = kst_midnight(now.date())
return [
{"category": c, "fcstDate": (start + timedelta(hours=h)).strftime("%Y%m%d"), "fcstTime": (start + timedelta(hours=h)).strftime("%H%M"), "fcstValue": v}
for h in range(hours) for c, v in values
]
def clouds(client, points, days=3):
start = now.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None) - timedelta(days=1)
times = [(start + timedelta(hours=h)).strftime("%Y-%m-%dT%H:00") for h in range(24 * (days + 2))]
h = {"time": times}
for m in ("ecmwf_ifs025", "gfs_seamless", "jma_seamless", "icon_seamless"):
h |= {f"cloud_cover_low_{m}": [0] * len(times), f"cloud_cover_mid_{m}": [20] * len(times), f"cloud_cover_high_{m}": [50] * len(times)}
return _async([{"hourly": h} for _ in points])
clear = [("TMP", "20"), ("SKY", "1"), ("PTY", "0"), ("POP", "0"), ("PCP", "강수없음"), ("REH", "50"), ("WSD", "1.5")]
monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(hourly(24 * 4, clear)))
monkeypatch.setattr(now_service, "fetch_ultra", lambda *a: _async(hourly(24 * 2, [("PTY", "0"), ("RN1", "강수없음"), ("T1H", "20")])))
monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "테스트", "dmX": "37.56", "dmY": "126.91"}]))
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(sky_service, "fetch_clouds", clouds)
monkeypatch.setattr(week_service, "fetch_mid", lambda *a: _async(({}, {})))
monkeypatch.setattr(week_service, "fetch_holidays", lambda *a: _async([]))
monkeypatch.setattr(week_service, "fetch_festivals", lambda *a: _async([{
"contentid": "77", "title": "테스트 축제", "addr1": "서울", "eventstartdate": now.strftime("%Y%m%d"),
"eventenddate": (now + timedelta(days=2)).strftime("%Y%m%d"),
}]))
monkeypatch.setattr(season_service, "fetch_solar_terms", lambda *a: _async([]))