Merge remote-tracking branch 'origin/main' into feat/share-image
This commit is contained in:
commit
794e70e419
15 files changed
+290
-77
No files matched your search
@@ -118,10 +118,12 @@ light = 1 - min(low100 + 0.5×mid100, 100) / 100
|
||||
|
||||
| 축 | 값 (지수 계산 창 안에서) | 점수 규칙 (기본값, 지수별로 시드 JSON에서 바꿈) | 칼럼 |
|
||||
|---|---|---|---|
|
||||
| `uv` 자외선 | `uv_index` **최대** | 2 이하 100점, 8 이상 0점, 사이는 선형 | `weight_uv`, `uv_score` |
|
||||
| `sun` 햇빛 | 해 난 비율(`sunshine_s ÷ 10,800`)의 **평균** | 80% 이상 100점, 20% 이하 0점, 사이는 선형 | `weight_sun`, `sun_score` |
|
||||
| `view` 가시거리 | `visibility_m` **최소**(km) | 20km 이상 100점, 5km 이하 0점, 사이는 선형 | `weight_view`, `view_score` |
|
||||
| `uv` 자외선 | `uv_index` **최대** | 2 이하 100점, 8 이상 0점, 사이는 완만한 곡선 | `weight_uv`, `uv_score` |
|
||||
| `sun` 햇빛 | 해 난 비율(`sunshine_s ÷ 10,800`)의 **평균** | 80% 이상 100점, 20% 이하 0점, 사이는 완만한 곡선 | `weight_sun`, `sun_score` |
|
||||
| `view` 가시거리 | `visibility_m` **최소**(km) | 20km 이상 100점, 5km 이하 0점, 사이는 완만한 곡선 | `weight_view`, `view_score` |
|
||||
|
||||
- 완만한 곡선: 만점 구간 끝에서 0점 지점까지를 정규분포 곡선(σ = 그 거리) 모양으로 내려간다 (`index_calc._fall`). 가운데 지점이 50점이 아니라 70점이라 만점 근처는 천천히, 0점 근처는 빨리 내려간다. 모든 축(기온·비·바람·습도·미세먼지 포함)에 같은 곡선을 쓰고, 만점 기준·0점 지점·0점 조건은 그대로다.
|
||||
- 기온·습도 편한 범위(`range`): 최적값(`best`, 없으면 범위 가운데) ±2°(습도 ±5%p)는 100점, 범위 끝은 85점, 사이는 완만한 곡선. 100점 구간은 최적값~범위 끝 거리의 1/3을 넘지 않는다 (`index_calc._range`). 100점은 완벽에 가까운 조건에만 준다는 10/2 회의 결정을 따른 것이다.
|
||||
- 값이 없으면(수집 전, 구간 없음) 미세먼지처럼 **70점(정보 없음)**.
|
||||
- 비중이 0인 지수에서는 점수에 영향이 없고, 상세 API(`/v1/index/{id}`)에도 나오지 않는다. 기존 6개 축도 같은 규칙으로, 비중이 0이면 나오지 않는다.
|
||||
- 중기예보로 내는 예상 점수(`estimate`)에서는 값이 없으므로 비중이 있으면 70점(정보 없음)이다.
|
||||
|
||||
@@ -27,6 +27,13 @@ class WatchSlot(WebPacketProtocol):
|
||||
rain_prob: Optional[int] = None
|
||||
|
||||
|
||||
class WatchEvent(WebPacketProtocol):
|
||||
name: str
|
||||
place_name: str
|
||||
status_label: str
|
||||
fit: Optional[str] = None
|
||||
|
||||
|
||||
class WatchTimeline(WebPacketProtocol):
|
||||
start_at: datetime
|
||||
kind: Literal["gak", "sunset"]
|
||||
@@ -45,3 +52,4 @@ class Res_WatchSummary(Res_WebPacketProtocol):
|
||||
sunset: Optional[WatchSunset] = None
|
||||
slots: list[WatchSlot] = []
|
||||
timeline: list[WatchTimeline] = []
|
||||
events: list[WatchEvent] = []
|
||||
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
@@ -6,9 +7,10 @@ from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from common.database.model.models import SkyScore
|
||||
from common.enums import ErrorType, SkyGrade
|
||||
from common.logger import LOG
|
||||
from common.models.errors import error_info
|
||||
from common.utils.kma_time import KST, now_kst
|
||||
from router.v1.watch.protocol import Res_WatchSummary, WatchNow, WatchSlot, WatchSunset, WatchTimeline
|
||||
from router.v1.watch.protocol import Res_WatchSummary, WatchEvent, WatchNow, WatchSlot, WatchSunset, WatchTimeline
|
||||
from services.calc.sky_score import GRADE_LABEL
|
||||
from services.calc.sun import sun_times
|
||||
from services.feed_service import _SUNSET_FULL, _top, feed_ttl_sec, slot_of
|
||||
@@ -16,18 +18,32 @@ from services.index_service import IndexService
|
||||
from services.now_service import NowService
|
||||
from services.sky_service import SkyService
|
||||
from services.weather_service import WeatherService
|
||||
from services.week_service import EventItem, WeekService
|
||||
|
||||
router = APIRouter(prefix="/v1/watch", tags=["watch"])
|
||||
|
||||
MAX_PICKS = 3
|
||||
# 워치 스킨이 큰 원(1위) + 둘레 링 6개(2~7위)를 채운다
|
||||
TOP_N = 7
|
||||
MAX_EVENTS = 2
|
||||
# 워치 readTimeout(10초) 안에 끝나도록. 첫 조회라 TourAPI 를 부르다 늦으면 이번 요약엔 축제를 빼고, 캐시는 다음 조회가 채운다
|
||||
EVENTS_TIMEOUT_SEC = 4
|
||||
# "[하트하트아트앤컬처] 마음의 각도" 처럼 이름 앞 주최·분류 괄호. 워치 칸이 좁아 뺀다
|
||||
_NAME_PREFIX = re.compile(r"^(\[[^\]]*\]\s*)+")
|
||||
|
||||
|
||||
def _best(score: SkyScore, kind: str) -> datetime:
|
||||
return datetime.fromisoformat(next(b["at"] for b in score.best_times if b["kind"] == kind)).astimezone(KST)
|
||||
|
||||
|
||||
async def _events(week: WeekService, region: str) -> tuple[ErrorType, list[EventItem]]:
|
||||
try:
|
||||
return await asyncio.wait_for(week.events(region, None), EVENTS_TIMEOUT_SEC)
|
||||
except TimeoutError:
|
||||
LOG.warning(f"[watch] events {region}: {EVENTS_TIMEOUT_SEC}초 넘어 생략")
|
||||
return ErrorType.EXTERNAL_API_ERROR, []
|
||||
|
||||
|
||||
def timeline(now: datetime, sunset: Optional[SkyScore], is_today: bool) -> list[WatchTimeline]:
|
||||
"""컴플리케이션이 언제 무엇을 보여줄지. 오늘 노을이 볼 만하면(60점 이상) 일몰 2시간 전부터 보랏빛 하늘까지 노을, 나머지는 각."""
|
||||
if sunset is None or not is_today or sunset.score < _SUNSET_FULL:
|
||||
@@ -47,9 +63,10 @@ async def get_watch_summary(
|
||||
now_service: NowService = Depends(),
|
||||
sky: SkyService = Depends(),
|
||||
index: IndexService = Depends(),
|
||||
week: WeekService = Depends(),
|
||||
) -> Res_WatchSummary:
|
||||
(err_t, today), (err_n, now_w), (err_s, view), (err_i, board) = await asyncio.gather(
|
||||
weather.today(region), now_service.now(region), sky.view(region), index.board(region),
|
||||
(err_t, today), (err_n, now_w), (err_s, view), (err_i, board), (err_e, events) = await asyncio.gather(
|
||||
weather.today(region), now_service.now(region), sky.view(region), index.board(region), _events(week, region),
|
||||
)
|
||||
today = today if err_t is ErrorType.SUCCESS else None
|
||||
now_w = now_w if err_n is ErrorType.SUCCESS else None
|
||||
@@ -95,4 +112,11 @@ async def get_watch_summary(
|
||||
sunset_at=_best(target, "sun"), best_at=_best(target, "peak"),
|
||||
)
|
||||
res.timeline = timeline(now, target, is_today)
|
||||
# 축제를 못 가져와도 요약은 그대로 낸다 (err_e 면 빈 목록)
|
||||
if err_e is ErrorType.SUCCESS:
|
||||
res.events = [
|
||||
WatchEvent(name=_NAME_PREFIX.sub("", i.event.name) or i.event.name, place_name=i.event.place_name, status_label=i.status_label, fit=i.fit)
|
||||
# 진행 중인 행사를 먼저 (스킨은 첫 번째 하나만 보여 준다). 같은 상태 안에서는 서버 순서(가까운 날짜·거리) 그대로
|
||||
for i in sorted(events, key=lambda i: i.status != "live")[:MAX_EVENTS]
|
||||
]
|
||||
return res
|
||||
@@ -1,7 +1,7 @@
|
||||
from collections import Counter
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from math import cos, pi
|
||||
from math import cos, exp, pi
|
||||
from statistics import mean
|
||||
from typing import Optional
|
||||
|
||||
@@ -14,6 +14,10 @@ _WEEKDAY_KO = ("월", "화", "수", "목", "금", "토", "일")
|
||||
_UNKNOWN = 70
|
||||
_EDGE = 85
|
||||
_WORST_PULL = 0.25
|
||||
_FALL_FLOOR = exp(-0.5)
|
||||
# 편한 범위 안에서 최적값 ±이만큼은 100점 (기온 °, 습도 %p)
|
||||
_TEMP_PLATEAU = 2
|
||||
_HUMIDITY_PLATEAU = 5
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -70,17 +74,33 @@ def _clamp(v: float) -> int:
|
||||
return round(max(0.0, min(100.0, v)))
|
||||
|
||||
|
||||
def _fall(t: float) -> float:
|
||||
"""만점 구간 끝(t=0)에서 0점 지점(t=1)까지 1→0. 정규분포 곡선(σ = 그 거리) 모양이라 만점 근처는 천천히 내려간다."""
|
||||
if t <= 0:
|
||||
return 1.0
|
||||
if t >= 1:
|
||||
return 0.0
|
||||
return (exp(-t * t / 2) - _FALL_FLOOR) / (1 - _FALL_FLOOR)
|
||||
|
||||
|
||||
def _linear(v: float, zero: float, full: float) -> int:
|
||||
return _clamp((v - zero) / (full - zero) * 100)
|
||||
"""full 쪽은 100, zero 에서 0. 사이는 _fall 곡선."""
|
||||
return _clamp(100 * _fall((v - full) / (zero - full)))
|
||||
|
||||
|
||||
def _peak(v: float, lo: float, hi: float, best: Optional[float], per_out: float) -> int:
|
||||
"""최적값에서만 100. 편한 범위 끝은 _EDGE, 범위 밖은 한 단위마다 per_out 씩 깎는다."""
|
||||
best = (lo + hi) / 2 if best is None else best
|
||||
def _range(v: float, lo: float, hi: float, best: Optional[float], plateau: float, per_out: float) -> int:
|
||||
"""편한 범위 안: 최적값 ±plateau 는 100, 범위 끝으로 갈수록 _EDGE 까지 _fall 곡선으로 내려간다.
|
||||
100점 구간은 최적값~범위 끝 거리의 1/3 을 넘지 않아 범위가 좁아도 끝에서 뚝 떨어지지 않는다.
|
||||
범위 밖: _EDGE 에서 예전 직선(한 단위마다 per_out)이 0이 되던 거리까지 _fall 곡선으로 0."""
|
||||
if v < lo or v > hi:
|
||||
return _clamp(_EDGE - per_out * min(abs(v - lo), abs(v - hi)))
|
||||
side = (best - lo) if v < best else (hi - best)
|
||||
return _clamp(100 - (100 - _EDGE) * (abs(v - best) / side if side else 0))
|
||||
return _clamp(_EDGE * _fall(min(abs(v - lo), abs(v - hi)) * per_out / _EDGE))
|
||||
best = (lo + hi) / 2 if best is None else best
|
||||
side = abs((lo if v < best else hi) - best)
|
||||
flat = min(plateau, side / 3)
|
||||
off = abs(v - best) - flat
|
||||
if off <= 0:
|
||||
return 100
|
||||
return _clamp(_EDGE + (100 - _EDGE) * _fall(off / (side - flat)))
|
||||
|
||||
|
||||
def temp_score(rule: dict, feels: float) -> tuple[int, str]:
|
||||
@@ -88,7 +108,7 @@ def temp_score(rule: dict, feels: float) -> tuple[int, str]:
|
||||
shown = f"산 정상 기준 {round(t)}°" if rule.get("offset") else f"체감 {round(t)}°"
|
||||
if rule["type"] == "range":
|
||||
lo, hi = rule["lo"], rule["hi"]
|
||||
return _peak(t, lo, hi, rule.get("best"), 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}"
|
||||
return _range(t, lo, hi, rule.get("best"), _TEMP_PLATEAU, 8), f"{shown}, 편한 범위 {lo}~{hi}° {'안' if lo <= t <= hi else '밖'}"
|
||||
if rule["type"] == "away":
|
||||
lo, hi = rule["lo"], rule["hi"]
|
||||
dist = 0 if lo <= t <= hi else min(abs(t - lo), abs(t - hi))
|
||||
@@ -99,8 +119,8 @@ def temp_score(rule: dict, feels: float) -> tuple[int, str]:
|
||||
def rain_score(rule: dict, max_prob: int, raining: bool, until: str = "") -> tuple[int, str]:
|
||||
prob = f"{until} 비 확률 {max_prob}%" if until else f"비 확률 {max_prob}%"
|
||||
if rule["dir"] == "wet":
|
||||
return (100 if raining else _clamp(max_prob)), (f"비 소식, {prob}" if raining else f"{prob}, 비 오면 올라가요")
|
||||
return (0 if raining else _clamp(100 - max_prob)), (f"비 소식, {prob}" if raining else prob)
|
||||
return (100 if raining else _linear(max_prob, 0, 100)), (f"비 소식, {prob}" if raining else f"{prob}, 비 오면 올라가요")
|
||||
return (0 if raining else _linear(max_prob, 100, 0)), (f"비 소식, {prob}" if raining else prob)
|
||||
|
||||
|
||||
def wind_score(rule: dict, wind: Optional[float]) -> tuple[int, str]:
|
||||
@@ -115,7 +135,7 @@ def wind_score(rule: dict, wind: Optional[float]) -> tuple[int, str]:
|
||||
return 100, note
|
||||
if wind <= ok:
|
||||
return _clamp(100 - (100 - _EDGE) * (wind - ok / 2) / (ok / 2)), note
|
||||
return _clamp(_EDGE * (rule["limit"] - wind) / (rule["limit"] - ok)), note
|
||||
return _clamp(_EDGE * _fall((wind - ok) / (rule["limit"] - ok))), note
|
||||
if rule["type"] == "moderate":
|
||||
if 2 <= wind <= 5:
|
||||
return 100, note
|
||||
@@ -126,7 +146,7 @@ def wind_score(rule: dict, wind: Optional[float]) -> tuple[int, str]:
|
||||
def humidity_score(rule: dict, humidity: float) -> tuple[int, str]:
|
||||
note = f"습도 {round(humidity)}%"
|
||||
if rule["type"] == "range":
|
||||
return _peak(humidity, rule["lo"], rule["hi"], rule.get("best"), 2), note
|
||||
return _range(humidity, rule["lo"], rule["hi"], rule.get("best"), _HUMIDITY_PLATEAU, 2), note
|
||||
if rule["type"] == "higher":
|
||||
return _linear(humidity, 40, 90), note
|
||||
if rule["type"] == "lower":
|
||||
|
||||
@@ -39,15 +39,17 @@ def test_good_but_not_perfect_stays_below_100():
|
||||
|
||||
|
||||
def test_one_bad_factor_pulls_total_down():
|
||||
assert evaluate(_defn(), [[_h(19, wind=1.0, prob=60)]], CTX).score < 80
|
||||
assert evaluate(_defn(), [[_h(19, wind=1.0, prob=75)]], CTX).score < 75
|
||||
|
||||
|
||||
def test_temp_peaks_at_best_and_loses_8_per_degree_outside():
|
||||
assert temp_score({"type": "range", "lo": 18, "hi": 24}, 21)[0] == 100
|
||||
assert temp_score({"type": "range", "lo": 18, "hi": 24}, 24)[0] == 85
|
||||
def test_temp_is_full_near_best_and_falls_gently_to_zero_outside():
|
||||
rule = {"type": "range", "lo": 14, "hi": 28} # 최적 21 ±2 = 19~23 은 100
|
||||
assert [temp_score(rule, t)[0] for t in (19, 21, 23)] == [100, 100, 100]
|
||||
assert 85 < temp_score(rule, 25)[0] < 100 and temp_score(rule, 28)[0] == 85 # 범위 끝으로 갈수록 85까지
|
||||
assert temp_score({"type": "range", "lo": 18, "hi": 24, "best": 22}, 22)[0] == 100
|
||||
assert temp_score({"type": "range", "lo": 18, "hi": 24}, 15)[0] == 61
|
||||
assert temp_score({"type": "lower", "zero": 25, "full": 5}, 15)[0] == 50
|
||||
assert temp_score({"type": "range", "lo": 18, "hi": 24}, 15)[0] == 77 # 범위 밖 3°
|
||||
assert temp_score({"type": "range", "lo": 18, "hi": 24}, 18 - 85 / 8)[0] == 0 # 예전 직선이 0이 되던 거리에서 0
|
||||
assert temp_score({"type": "lower", "zero": 25, "full": 5}, 15)[0] == 70
|
||||
assert temp_score({"type": "range", "lo": 10, "hi": 20, "offset": -6}, 21)[1].startswith("산 정상 기준 15°")
|
||||
|
||||
|
||||
@@ -59,7 +61,8 @@ def test_temp_away_rises_outside_comfort():
|
||||
|
||||
|
||||
def test_rain_dry_and_wet():
|
||||
assert rain_score({"dir": "dry"}, 30, False)[0] == 70
|
||||
assert rain_score({"dir": "dry"}, 30, False)[0] == 89
|
||||
assert rain_score({"dir": "dry"}, 100, False)[0] == 0
|
||||
assert rain_score({"dir": "dry"}, 30, True)[0] == 0
|
||||
assert rain_score({"dir": "wet"}, 30, True)[0] == 100
|
||||
|
||||
@@ -111,10 +114,10 @@ def test_moon_full_and_new():
|
||||
assert illumination(datetime(2000, 1, 21, 12, tzinfo=timezone.utc)) > 0.95
|
||||
|
||||
|
||||
def test_uv_sun_view_scores_are_linear_and_unknown_is_70():
|
||||
assert uv_score({"zero": 8, "full": 2}, 1)[0] == 100 and uv_score({"zero": 8, "full": 2}, 5)[0] == 50 and uv_score({"zero": 8, "full": 2}, 9)[0] == 0
|
||||
assert sun_score({"zero": 0.2, "full": 0.8}, 0.5)[0] == 50 and sun_score({"zero": 0.2, "full": 0.8}, 1.0)[0] == 100
|
||||
assert view_score({"zero": 5, "full": 20}, 12.5)[0] == 50 and view_score({"zero": 5, "full": 20}, 3)[0] == 0
|
||||
def test_uv_sun_view_scores_fall_gently_and_unknown_is_70():
|
||||
assert uv_score({"zero": 8, "full": 2}, 1)[0] == 100 and uv_score({"zero": 8, "full": 2}, 5)[0] == 70 and uv_score({"zero": 8, "full": 2}, 9)[0] == 0
|
||||
assert sun_score({"zero": 0.2, "full": 0.8}, 0.5)[0] == 70 and sun_score({"zero": 0.2, "full": 0.8}, 1.0)[0] == 100
|
||||
assert view_score({"zero": 5, "full": 20}, 12.5)[0] == 70 and view_score({"zero": 5, "full": 20}, 3)[0] == 0
|
||||
assert (uv_score({"zero": 8, "full": 2}, None)[0], sun_score({"zero": 0.2, "full": 0.8}, None)[0], view_score({"zero": 5, "full": 20}, None)[0]) == (70, 70, 70)
|
||||
assert uv_score({"zero": 8, "full": 2}, 5)[1] == "자외선 5.0"
|
||||
assert view_score({"zero": 5, "full": 20}, 12.5)[1] == "가시거리 12.5km" and view_score({"zero": 5, "full": 20}, None)[1] == "가시거리 정보 없음"
|
||||
@@ -175,7 +178,7 @@ def test_estimate_is_flagged_and_unknown_factors_are_70():
|
||||
|
||||
def test_estimate_uses_rain_prob_of_the_window_half_day():
|
||||
morning, evening = estimate(_defn(), _fc(am=60, pm=0), [[9, 10]], CTX), estimate(_defn(), _fc(am=60, pm=0), [[19, 20]], CTX)
|
||||
assert morning.factors["rain"] == 40 and evening.factors["rain"] == 100
|
||||
assert morning.factors["rain"] == 58 and evening.factors["rain"] == 100
|
||||
|
||||
|
||||
def test_estimate_applies_rain_zero_rule_only():
|
||||
|
||||
@@ -61,7 +61,7 @@ def test_weekend_in_short_range_uses_hourly_score():
|
||||
|
||||
def test_weekend_beyond_short_range_uses_mid_forecast_estimate():
|
||||
r = day_result(DEFN, SAT, REGION, {}, FC, CTX, short=False)
|
||||
assert r.estimated is True and r.factors["wind"] == 70 and r.factors["rain"] == 80
|
||||
assert r.estimated is True and r.factors["wind"] == 70 and r.factors["rain"] == 95
|
||||
|
||||
|
||||
def test_partial_hourly_falls_back_to_estimate():
|
||||
|
||||
@@ -4,7 +4,8 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
import services.week_service as week_service
|
||||
from common.utils.kma_time import KST, now_kst
|
||||
from router.router import app
|
||||
from router.v1.watch.watch import timeline
|
||||
|
||||
@@ -12,6 +13,10 @@ REGION = "1141000000"
|
||||
SUN = datetime(2026, 10, 6, 18, 0, tzinfo=KST)
|
||||
|
||||
|
||||
async def _async(v):
|
||||
return v
|
||||
|
||||
|
||||
def _sunset(score: int) -> SimpleNamespace:
|
||||
return SimpleNamespace(score=score, best_times=[
|
||||
{"at": SUN.isoformat(), "kind": "sun", "label": "해 져요"},
|
||||
@@ -42,6 +47,8 @@ def test_timeline_skips_weak_tomorrow_or_finished_sunset():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_watch_summary_bundles_now_top_picks_sunset(offline):
|
||||
# 행사는 스케줄러가 7일마다 모아 둔다. 요청은 DB 만 읽으니 먼저 모아 둔다
|
||||
await week_service.collect_events("11", now_kst().date())
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/watch/summary", params={"region": REGION, "pick": "laundry, nope,running,carwash,bike"})).json()
|
||||
assert body["result"]["success"] is True
|
||||
@@ -53,6 +60,22 @@ async def test_watch_summary_bundles_now_top_picks_sunset(offline):
|
||||
assert body["sunset"]["best_at"] > body["sunset"]["sunset_at"]
|
||||
assert all(s["at"] > body["issued_at"] for s in body["slots"])
|
||||
assert body["timeline"][0]["start_at"] == body["issued_at"]
|
||||
assert [(e["name"], e["status_label"]) for e in body["events"]] == [("테스트 축제", "진행 중")]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_watch_summary_puts_live_event_first_without_bracket_prefix(offline, monkeypatch):
|
||||
# 서버 순서는 시작일이 가까운 순이라 내일 시작이 먼저지만, 스킨에 하나만 띄우니 진행 중을 앞으로. 이름 앞 [주최] 는 뺀다
|
||||
today = now_kst().date()
|
||||
day = lambda n: (today + timedelta(days=n)).strftime("%Y%m%d")
|
||||
monkeypatch.setattr(week_service, "fetch_festivals", lambda c, sido, since: _async([
|
||||
{"contentid": "1", "title": "내일 축제", "addr1": "서울", "eventstartdate": day(1), "eventenddate": day(2)},
|
||||
{"contentid": "2", "title": "[주최] 열리는 축제", "addr1": "서울", "eventstartdate": day(-3), "eventenddate": day(2)},
|
||||
] if sido == "11" else []))
|
||||
await week_service.collect_events("11", today)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/watch/summary", params={"region": REGION})).json()
|
||||
assert [e["name"] for e in body["events"]] == ["열리는 축제", "내일 축제"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
|
||||
Reference in new issue
Block a user