# 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
129 lines
6.2 KiB
Python
129 lines
6.2 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", "openmeteo_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 datetime, timedelta, timezone
|
|
|
|
import scheduler.jobs as jobs
|
|
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])
|
|
|
|
def openmeteo_weather(client, points, days=4):
|
|
start = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
|
|
times = [(start + timedelta(hours=h)).strftime("%Y-%m-%dT%H:00") for h in range(24 * days)]
|
|
n = len(times)
|
|
h = {
|
|
"time": times, "uv_index": [3.0] * n, "uv_index_clear_sky": [3.0] * n, "visibility": [20000.0] * n,
|
|
"wind_gusts_10m": [4.0] * n, "pressure_msl": [1015.0] * n, "sunshine_duration": [3600.0] * n,
|
|
"shortwave_radiation": [300.0] * n, "soil_temperature_0cm": [18.0] * n,
|
|
}
|
|
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(jobs, "fetch_weather", openmeteo_weather)
|
|
monkeypatch.setattr(weather_service, "fetch_mid", lambda *a: _async(({}, {})))
|
|
monkeypatch.setattr(week_service, "fetch_holidays", lambda *a: _async([]))
|
|
monkeypatch.setattr(week_service, "fetch_festivals", lambda c, sido, since: _async([{
|
|
"contentid": "77", "title": "테스트 축제", "addr1": "서울", "eventstartdate": now.strftime("%Y%m%d"),
|
|
"eventenddate": (now + timedelta(days=2)).strftime("%Y%m%d"), "firstimage": "http://tong.visitkorea.or.kr/test.jpg",
|
|
}] if sido == "11" else []))
|
|
monkeypatch.setattr(week_service, "fetch_exhibitions", lambda *a: _async([]))
|
|
monkeypatch.setattr(season_service, "fetch_solar_terms", lambda *a: _async([]))
|