Files
skkim 5ab2381f79 feat: 지금 날씨를 초단기실황 관측값으로, 각 점수에서 시간대 알맞음 제거·우산각 계산식 변경
- 초단기실황(getUltraSrtNcst)을 받아 지금 정시 한 시각의 비·기온·습도·바람을 예보 대신 관측값으로 덮어씀 (체감·불쾌지수는 다시 계산). 지역별 1시간 캐시, 실패하면 초단기예보·단기예보로 되돌아감, 새 시각 실황이 나오면 각 점수를 다시 계산. 가이드대로 ±900 이상은 결측 처리. 테스트가 실제 기상청을 부르지 않게 실황 호출을 기본으로 막음
- 시간대 알맞음 요소를 31개 각에서 빼고 비중을 5% 단위로 나눔. 요소가 3개 미만이 된 뜨아각·파전각·감성노래각·감사각·선크림각에 요소를 더함. 러닝각의 활동 시간대 밖 점수 상한도 없앰. 요소가 하나뿐인 각은 가장 낮은 요소로 깎지 않음
- 우산각은 비 한 가지: 남은 하루(지금~자정) 비 확률 평균이 점수, 지금 비가 오면 70점에서 시작해 평균 × 30점을 더함. 내일·토·일 칸은 그날 6~24시 평균 × 100. 우산분실각도 비 한 가지
- 각 계산 기준 문서는 생성기를 새 규칙에 맞게 고쳐 다시 생성, 점수 계산식·서비스 동작 안내 문서 갱신
2026-11-23 14:51:04 +09:00

154 lines
7.6 KiB
Python

import asyncio
import os
# 개발 DB·Redis 를 건드리지 않도록 테스트 전용 DB(<이름>_test)와 Redis 15번을 쓴다. 앱 import 전에 정해야 한다.
# 여러 작업 폴더에서 동시에 돌릴 땐 TEST_DB_NAME·TEST_REDIS_DB 를 폴더마다 다르게 준다 (시작할 때 DB 를 지우고 Redis 를 비우므로).
os.environ["DB_NAME"] = os.environ.get("TEST_DB_NAME", "nalssigak_test")
os.environ["REDIS_DB"] = os.environ.get("TEST_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_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "comment_report", "user_block", "holiday", "solar_term", "users", "card_set", "card_image", "reel",
)
@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(autouse=True)
def _no_seoul_crawl(monkeypatch):
"""서울문화포털은 키 없이 바로 긁어 오므로, 테스트가 실제 사이트를 부르지 않게 기본으로 막는다."""
import services.week_service as week_service
monkeypatch.setattr(week_service, "fetch_seoul_festivals", lambda *a: _async([]))
@pytest.fixture(autouse=True)
def _no_ncst_call(monkeypatch):
"""초단기실황은 실제 기상청을 부르지 않게 기본으로 '값 없음'으로 막는다 (실황을 쓰는 테스트는 자기 값으로 바꾼다)."""
import services.weather_service as weather_service
monkeypatch.setattr(weather_service, "fetch_ncst", lambda *a: _async([]))
@pytest.fixture
def no_bot_comments(monkeypatch):
"""사람이 단 댓글·좋아요만 세는 테스트용: 포스트를 만들 때 캐릭터 댓글을 달지 않는다 (캐릭터 댓글은 test_bot_comment)."""
import services.feed_service as feed_service
from common.enums import ErrorType
monkeypatch.setattr(feed_service, "fill_bot_comments", lambda *a: _async(ErrorType.SUCCESS))
@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.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(weather_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([]))