- 화면 전체 스켈레톤, 로딩·완료·실패 사이 레이아웃 고정, 값 없음은 '?' - 행사 사진·출처 표시, 문화정보 API 전시 연결, 행사 30km 거리 기준 - 각 상세 점수 칸 오늘/내일/토/일, 단기예보 밖 주말은 중기예보 예상 점수 - 6각 차트 축 이름을 좋은 방향으로, 계산 근거 문구 정리 - 아이콘 오용·뜻 모를 표시·빈 데이터·포스트 본문 반복 수정 - 미세먼지 별도 포스트, 노을 명소 전국 155곳 거리 기준, 노을 탭 결론 중심 재구성 - 밤 다크 테마·별똥별, 댓글·좋아요 대기·실패 표시 - 주말 전국 랭킹·당일치기 카드, 계절 이야기 사진 수집 - 문서: 포스트 타입별 내용, 각 데이터 정리, TODO 진행 순서
116 lines
5.4 KiB
Python
116 lines
5.4 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(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([]))
|