Merge remote-tracking branch 'origin/main' into merge/festivals
# Conflicts: # backend/services/week_service.py
This commit is contained in:
commit
b4fcb313c7
56 files changed
+4132
-251
No files matched your search
@@ -8,6 +8,7 @@ from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import PostType
|
||||
from common.utils.kma_time import now_kst
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from router.router import app
|
||||
from services.feed_service import build_feed_day
|
||||
@@ -16,17 +17,19 @@ from services.week_service import collect_events
|
||||
REGION = "1114000000"
|
||||
|
||||
|
||||
async def _posts(day: date):
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT post_type FROM post WHERE feed_date='{day}' ORDER BY position")))
|
||||
async def _posts(day: date, sido: str = REGION[:2]):
|
||||
"""한 시도가 보는 그날 카드 (전국 + 그 시도)."""
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(
|
||||
f"SELECT post_type FROM post WHERE feed_date='{day}' AND scope IN ('00', '{sido}') ORDER BY position")))
|
||||
return [r[0] for r in rows]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_build_day_adds_weekend_post_every_day():
|
||||
monday, thursday = date(2026, 10, 12), date(2026, 10, 15)
|
||||
await build_feed_day(monday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(monday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
assert (await _posts(monday)).count(PostType.WEEK.value) == 1
|
||||
assert (await _posts(thursday)).count(PostType.WEEK.value) == 1
|
||||
assert (await _posts(thursday))[0] == PostType.WEATHER.value
|
||||
@@ -36,10 +39,10 @@ async def test_build_day_adds_weekend_post_every_day():
|
||||
async def test_build_day_adds_new_card_types_to_existing_day():
|
||||
"""이미 만든 날에 새 종류(미세먼지)가 생기면 빠진 카드만 더한다."""
|
||||
thursday = date(2026, 10, 15)
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: s.execute(text(f"DELETE FROM post WHERE feed_date='{thursday}' AND post_type={PostType.AIR.value}"))])
|
||||
before = len(await _posts(thursday))
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
after = await _posts(thursday)
|
||||
assert len(after) == before + 1 and after.count(PostType.AIR.value) == 1
|
||||
|
||||
@@ -58,7 +61,7 @@ async def test_feed_assembles_hero_stories_posts_and_bands(offline):
|
||||
body = (await client.get("/v1/feed", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert body["hero"]["temp_c"] == 20 and body["hero"]["top1"]["rank"] == 1 and "top3" not in body["hero"]
|
||||
assert len(body["stories"]) == 27
|
||||
assert len(body["stories"]) == 34
|
||||
weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert [s["kind"] for s in weather["slides"]] == ["hours", "hours"]
|
||||
assert len(weather["slides"][0]["hours"]) == 8
|
||||
@@ -155,7 +158,7 @@ def test_arrange_scatters_up_to_three_events_same_spot_all_day():
|
||||
@pytest.mark.anyio
|
||||
async def test_build_day_makes_every_card_at_three():
|
||||
thursday = date(2026, 10, 15)
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD())
|
||||
await build_feed_day(thursday, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT post_type, published_at FROM post WHERE feed_date='{thursday}'")))
|
||||
rows = list(rows)
|
||||
assert {PostType.ALERT.value, PostType.TOMORROW.value, PostType.QUOTE.value} <= {r[0] for r in rows}
|
||||
|
||||
@@ -9,10 +9,13 @@ import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import OpenMeteoHourly, WeatherHourly
|
||||
from common.enums import ErrorType
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.router import app
|
||||
from services.index_service import _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
from services.calc.index_calc import rank_score
|
||||
from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, slot_days, slot_label, windows_for
|
||||
|
||||
REGION = "1141000000"
|
||||
|
||||
@@ -51,13 +54,14 @@ def fakes(monkeypatch):
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_ranks_all_27_with_today_tomorrow_weekend_trend(fakes):
|
||||
async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/list", params={"region": REGION})).json()
|
||||
assert body["result"]["success"] is True
|
||||
assert len(body["items"]) == 27 and len(body["top3"]) == 3
|
||||
scores = [i["score"] for i in body["items"]]
|
||||
assert scores == sorted(scores, reverse=True)
|
||||
assert len(body["items"]) == 34 and len(body["top3"]) == 3
|
||||
priority = {d["code"]: d["priority"] for d in _seed()}
|
||||
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"]]
|
||||
assert weighted == sorted(weighted, reverse=True)
|
||||
today = now_kst().date()
|
||||
for i in body["items"]:
|
||||
assert [t["label"] for t in i["trend"]] == [slot_label(d, today) for d in slot_days(today)]
|
||||
@@ -95,13 +99,40 @@ async def test_index_detail_has_four_score_bands_with_today_marked(fakes):
|
||||
assert len(current) == 1 and current[0]["low"] <= body["index"]["score"] <= current[0]["high"]
|
||||
|
||||
|
||||
def test_every_index_has_four_band_sentences():
|
||||
def _seed() -> list[dict]:
|
||||
import json
|
||||
import os
|
||||
seed = json.load(open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "index_definition.json"), encoding="utf-8"))
|
||||
with open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "index_definition.json"), encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def test_every_index_has_four_band_sentences():
|
||||
seed = _seed()
|
||||
assert all(sorted(d["sentences"], key=int) == ["0", "30", "60", "80"] and all(d["sentences"].values()) for d in seed)
|
||||
|
||||
|
||||
def test_every_index_has_priority():
|
||||
assert all(d["priority"] in (1, 2, 3) for d in _seed())
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
|
||||
today = now_kst().date()
|
||||
defs = [
|
||||
SimpleNamespace(index_id=1, code="low", priority=3),
|
||||
SimpleNamespace(index_id=2, code="mid", priority=2),
|
||||
SimpleNamespace(index_id=3, code="high", priority=1),
|
||||
]
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=v) for x, v in ((1, 90), (2, 80), (3, 70))]
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, 50)))
|
||||
err, board = await service.board(REGION)
|
||||
assert err is ErrorType.SUCCESS
|
||||
# 하 90점(63) < 중 80점(68) < 상 70점(70). 보이는 점수는 그대로
|
||||
assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 80, 2), ("low", 90, 3)]
|
||||
|
||||
|
||||
def _om_row(at, **over):
|
||||
row = {
|
||||
"region_code": REGION, "forecast_at": at, "fetched_at": now_kst(), "uv_index": 2.0, "uv_index_clear_sky": 2.0,
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import json
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from services.calc.index_calc import (
|
||||
OUTING_HOURS, Context, DayForecast, Hour, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
|
||||
OUTING_HOURS, Context, DayForecast, Hour, air_score, axis_label, estimate, evaluate, hour_temp, outing, outing_estimate, rain_score, sun_score, temp_score,
|
||||
uv_score, view_score, zero_rules_text,
|
||||
)
|
||||
from services.calc.moon import illumination
|
||||
@@ -222,3 +226,40 @@ def test_outing_estimate_from_mid_forecast():
|
||||
assert r.reason.startswith("비 20% · 낮 ")
|
||||
assert outing_estimate(_fc(pm=60)).score <= 30
|
||||
assert outing_estimate(_fc(lo=None, hi=None)) is None
|
||||
|
||||
|
||||
def test_air_rule_can_reverse_so_dusty_air_scores_high():
|
||||
rule = {"zero": 15, "full": 75}
|
||||
assert air_score(80, None, rule)[0] == 100 and air_score(10, None, rule)[0] == 0
|
||||
assert air_score(10, None)[0] == 100
|
||||
assert axis_label("air", {"air": rule}) == "공기 탁함" and axis_label("air", {}) == "공기 맑음"
|
||||
|
||||
|
||||
_SEED = {x["code"]: SimpleNamespace(**x) for x in json.loads((Path(__file__).parents[1] / "seed" / "index_definition.json").read_text(encoding="utf-8"))}
|
||||
_SAT, _WED = date(2026, 10, 10), date(2026, 10, 7)
|
||||
|
||||
|
||||
def _seed_score(code, day=_SAT, pm25=10, **hour):
|
||||
d = _SEED[code]
|
||||
windows = [[_h(h, **hour) for h in range(w["from"], w["to"])] for w in d.windows]
|
||||
return evaluate(d, windows, replace(CTX, day=day, pm25=pm25)).score
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code, good, bad", [
|
||||
("golf", dict(feels=19.0, wind=2.0, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
|
||||
("jipkok", dict(feels=4.0, prob=90, rain=RainType.RAIN, wind=7.0, hum=85), dict(feels=20.0, wind=1.0, hum=40)),
|
||||
("fishing", dict(feels=22.0, wind=3.0), dict(feels=17.0, wind=11.0)),
|
||||
("drive", dict(feels=23.0, wind=4.0, hum=45, visibility_km=18.0), dict(feels=18.0, prob=80, rain=RainType.RAIN, visibility_km=5.0)),
|
||||
("kite", dict(feels=19.0, wind=6.0), dict(feels=14.0, wind=0.5)),
|
||||
("waterplay", dict(feels=28.0, wind=3.0, sunshine_ratio=0.7), dict(feels=18.0, wind=2.0, sunshine_ratio=0.3)),
|
||||
("kimjang", dict(feels=9.0, wind=3.0), dict(feels=20.0, wind=2.0)),
|
||||
])
|
||||
def test_new_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert 80 <= _seed_score(code, pm25=60 if code == "jipkok" else 10, **good) < 100
|
||||
assert _seed_score(code, **bad) <= 30
|
||||
|
||||
|
||||
def test_new_gak_100_only_when_every_factor_is_perfect():
|
||||
perfect = dict(feels=19.5, wind=1.0, hum=35)
|
||||
assert _seed_score("golf", **perfect) == 100
|
||||
assert _seed_score("golf", day=_WED, **perfect) < 100
|
||||
@@ -0,0 +1,112 @@
|
||||
import csv
|
||||
import os
|
||||
from collections import defaultdict
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.enums import PostType
|
||||
from common.utils.kma_time import now_kst
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.region_crud import RegionCRUD
|
||||
from crud.season_crud import SeasonCRUD
|
||||
from router.router import app
|
||||
from services.feed_service import LINEUP, NATIONAL_SCOPE, NATIONAL_TYPES, build_feed_day, feed_day, sido_of
|
||||
|
||||
SEOUL_A, SEOUL_B, BUSAN = "1111000000", "1114000000", "2611000000"
|
||||
REGION_CSV = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "region.csv")
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
def _ids(feed: dict) -> dict[int, set[int]]:
|
||||
out: dict[int, set[int]] = defaultdict(set)
|
||||
for p in feed["posts"]:
|
||||
out[p["post_type"]].add(p["post_id"])
|
||||
return out
|
||||
|
||||
|
||||
def test_every_region_maps_to_one_sido():
|
||||
with open(REGION_CSV, encoding="utf-8") as f:
|
||||
regions = list(csv.DictReader(f))
|
||||
assert len(regions) == 256
|
||||
by_name: dict[str, set[str]] = defaultdict(set)
|
||||
for r in regions:
|
||||
by_name[r["name"].split()[0]].add(sido_of(r["code"]))
|
||||
assert all(len(codes) == 1 for codes in by_name.values()), by_name
|
||||
sidos = {sido_of(r["code"]) for r in regions}
|
||||
assert all(len(c) == 2 and c.isdigit() and c != NATIONAL_SCOPE for c in sidos)
|
||||
sejong = [r for r in regions if r["name"].startswith("세종")]
|
||||
assert len(sejong) == 1 and sido_of(sejong[0]["code"]) == "36"
|
||||
assert sum(1 for r in regions if sido_of(r["code"]) == "36") == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_build_day_makes_national_once_and_regional_per_sido():
|
||||
day = date(2026, 10, 15)
|
||||
await build_feed_day(day, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
await build_feed_day(day, FeedCRUD(), SeasonCRUD(), RegionCRUD())
|
||||
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT scope, post_type FROM post WHERE feed_date='{day}'")))
|
||||
rows = list(rows)
|
||||
_, regions = await DB_SESSION_MNG.execute_lambda(lambda s: RegionCRUD().search(s))
|
||||
sidos = {sido_of(r.code) for r in regions}
|
||||
regional = [x for x in LINEUP if x[1] not in NATIONAL_TYPES]
|
||||
assert {scope for scope, t in rows if PostType(t) in NATIONAL_TYPES} == {NATIONAL_SCOPE}
|
||||
assert {scope for scope, t in rows if PostType(t) not in NATIONAL_TYPES} == sidos
|
||||
assert sum(1 for scope, t in rows if PostType(t) not in NATIONAL_TYPES) == len(regional) * len(sidos)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_regional_posts_shared_within_sido_split_across_sido(offline):
|
||||
async with client() as c:
|
||||
a, b, busan = [(await c.get("/v1/feed", params={"region": r})).json() for r in (SEOUL_A, SEOUL_B, BUSAN)]
|
||||
ia, ib, ibusan = _ids(a), _ids(b), _ids(busan)
|
||||
regional = [t for t in ia if PostType(t) not in NATIONAL_TYPES]
|
||||
assert PostType.WEATHER.value in regional and PostType.GAK.value in regional
|
||||
for t in regional:
|
||||
if t in ib:
|
||||
assert ia[t] == ib[t], PostType(t)
|
||||
if t in ibusan:
|
||||
assert not ia[t] & ibusan[t], PostType(t)
|
||||
national = [t for t in ia if PostType(t) in NATIONAL_TYPES]
|
||||
assert PostType.MOON.value in national
|
||||
for t in national:
|
||||
assert ia[t] == ib[t] == ibusan[t], PostType(t)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_like_in_one_sido_not_seen_in_another(offline):
|
||||
async with client() as c:
|
||||
token = (await c.post("/v1/auth/signup", json={"login_id": "scope_01", "password": "password1", "nickname": "시도테스트"})).json()["access_token"]
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
seoul = (await c.get("/v1/feed", params={"region": SEOUL_A}, headers=h)).json()
|
||||
post_id = next(p["post_id"] for p in seoul["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert (await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)).json()["like_count"] == 1
|
||||
await c.post(f"/v1/reaction/post/{post_id}/comment", json={"body": "서울 맑음"}, headers=h)
|
||||
same = (await c.get("/v1/feed", params={"region": SEOUL_B}, headers=h)).json()
|
||||
busan = (await c.get("/v1/feed", params={"region": BUSAN}, headers=h)).json()
|
||||
mine = next(p for p in same["posts"] if p["post_id"] == post_id)
|
||||
assert mine["liked"] is True and mine["like_count"] == 1 and mine["comment_count"] == 1
|
||||
weather = next(p for p in busan["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert weather["post_id"] != post_id and weather["like_count"] == 0 and weather["comment_count"] == 0 and not weather.get("liked")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_day_built_before_split_keeps_national_rows_for_regional_cards(offline):
|
||||
"""그날 지역 카드가 이미 전국 행으로 있으면 시도 행을 만들지 않고, 모든 시도가 그 행(과 반응)을 같이 쓴다."""
|
||||
day = feed_day(now_kst())
|
||||
rows = ", ".join(f"('{day}', {pos}, '{NATIONAL_SCOPE}', {t.value}, {ref.value}, {rank if rank else 'NULL'}, now(), {5 if t is PostType.WEATHER else 0})"
|
||||
for pos, t, ref, rank in LINEUP if ref.value == 1)
|
||||
await DB_SESSION_MNG.execute_lambda_run([lambda s: s.execute(text(
|
||||
f"INSERT INTO post (feed_date, position, scope, post_type, ref_type, index_rank, published_at, like_count) VALUES {rows}"))])
|
||||
async with client() as c:
|
||||
seoul, busan = [(await c.get("/v1/feed", params={"region": r})).json() for r in (SEOUL_A, BUSAN)]
|
||||
_, n = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(text(f"SELECT count(*) FROM post WHERE feed_date='{day}' AND scope <> '{NATIONAL_SCOPE}'")))
|
||||
assert n == 0
|
||||
ws, wb = [next(p for p in f["posts"] if p["post_type"] == PostType.WEATHER.value) for f in (seoul, busan)]
|
||||
assert ws["post_id"] == wb["post_id"] and ws["like_count"] == 5
|
||||
@@ -2,8 +2,10 @@ from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
|
||||
import services.season_service as season_service
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.utils.kma_time import now_kst
|
||||
from router.router import app
|
||||
|
||||
@@ -38,3 +40,15 @@ async def test_article_detail_and_not_found():
|
||||
missing = (await client.get("/v1/season/article/9999")).json()
|
||||
assert first["body"] and first["article"]["title"] == listed[0]["title"]
|
||||
assert missing["result"]["desc"] == "NOT_FOUND"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_article_photo_only_when_seeded():
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
listed = {a["code"]: a for a in (await client.get("/v1/season/article/list")).json()["articles"]}
|
||||
umbrella = (await client.get(f"/v1/season/article/{listed['umbrella']['article_id']}")).json()["article"]
|
||||
_, maple_id = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(text("SELECT article_id FROM article WHERE code = 'maple'")))
|
||||
maple = (await client.get(f"/v1/season/article/{maple_id}")).json()["article"]
|
||||
assert umbrella["image"] == "/season/umbrella.jpg" and "image_credit" not in umbrella
|
||||
assert maple["image"] == "/season/maple.jpg" and maple["image_credit"] == "ⓒJoycekim77 · CC BY-SA 3.0"
|
||||
assert "image" not in listed["howgak"] and "image" not in listed["di"]
|
||||
@@ -93,7 +93,7 @@ async def test_sky_spots_by_distance(monkeypatch, clean, region, expected):
|
||||
assert [s["distance_km"] for s in spots] == sorted(s["distance_km"] for s in spots)
|
||||
|
||||
|
||||
def test_nearest_spots_west_first_and_empty_outside_radius():
|
||||
def test_nearest_spots_west_first_and_nearest_one_outside_radius():
|
||||
from decimal import Decimal
|
||||
|
||||
from common.database.model.models import SunsetSpot
|
||||
@@ -103,7 +103,7 @@ def test_nearest_spots_west_first_and_empty_outside_radius():
|
||||
|
||||
spots = [spot("가까운 동쪽", 37.01, False), spot("먼 서쪽", 37.1, True), spot("반경 밖", 37.5, True)]
|
||||
assert [x.spot.name for x in sky_service.nearest_spots(37.0, 127.0, spots)] == ["먼 서쪽", "가까운 동쪽"]
|
||||
assert sky_service.nearest_spots(33.0, 127.0, spots) == []
|
||||
assert [x.spot.name for x in sky_service.nearest_spots(36.0, 127.0, spots)] == ["가까운 동쪽"]
|
||||
|
||||
|
||||
def test_outlook_only_when_a_later_day_has_a_better_verdict():
|
||||
|
||||
@@ -7,13 +7,13 @@ import services.air_service as air_service
|
||||
import services.warning_service as warning_service
|
||||
import services.weather_service as weather_service
|
||||
import services.week_service as week_service
|
||||
from common.database.model.models import Event
|
||||
from common.database.model.models import Event, Place, Region
|
||||
from common.enums import EventKind, RainType, Sky
|
||||
from common.utils.kma_time import KST, kst_midnight, now_kst
|
||||
from router.router import app
|
||||
from services.external.kma import latest_mid_base, mid_word, parse_mid
|
||||
from services.external.data_go_kr import DataGoKrRequestFailed
|
||||
from services.week_service import EventItem, _status, mix_kinds
|
||||
from services.week_service import PLACE_FALLBACK, PLACE_RADIUS_KM, EventItem, _status, mix_kinds, pick_places
|
||||
|
||||
REGION = "1144000000"
|
||||
|
||||
@@ -179,6 +179,46 @@ async def test_places_put_indoor_first_on_rainy_day(fakes):
|
||||
assert body["places"][0]["is_outdoor"] is False and body["places"][0]["is_good"] is True
|
||||
|
||||
|
||||
def _place(name: str, lat: float, lon: float, outdoor: bool = True, area: str = "가") -> Place:
|
||||
return Place(name=name, lat=lat, lon=lon, is_outdoor=outdoor, area=area)
|
||||
|
||||
|
||||
def test_pick_places_within_radius_good_first_then_near():
|
||||
region = Region(lat=37.0, lon=127.0)
|
||||
places = [
|
||||
_place("먼 공원", 37.2, 127.0), _place("가까운 공원", 37.01, 127.0, area="나"),
|
||||
_place("미술관", 37.1, 127.0, outdoor=False), _place("반경 밖", 37.5, 127.0),
|
||||
]
|
||||
items, areas = pick_places(region, places, rainy=False, area=None)
|
||||
assert [i.place.name for i in items] == ["가까운 공원", "먼 공원", "미술관"]
|
||||
assert all(i.distance_km <= PLACE_RADIUS_KM for i in items) and items[0].distance_km == 1.1
|
||||
assert areas == ["나", "가"]
|
||||
items, _ = pick_places(region, places, rainy=True, area=None)
|
||||
assert [i.place.name for i in items][0] == "미술관" and items[0].is_good
|
||||
items, _ = pick_places(region, places, rainy=False, area="가")
|
||||
assert [i.place.name for i in items] == ["먼 공원", "미술관"]
|
||||
|
||||
|
||||
def test_pick_places_falls_back_to_nearest_when_none_in_radius():
|
||||
region = Region(lat=37.0, lon=127.0)
|
||||
places = [_place(f"{k}km", 37.0 + k / 111, 127.0) for k in (90, 40, 60, 200)]
|
||||
items, _ = pick_places(region, places, rainy=False, area=None)
|
||||
assert [i.place.name for i in items] == ["40km", "60km", "90km"][:PLACE_FALLBACK]
|
||||
assert items[0].distance_km > PLACE_RADIUS_KM
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("region", ["2635000000", "5013000000", "4794000000"])
|
||||
async def test_places_outside_seoul_come_by_distance(fakes, region):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/week/place/list", params={"region": region, "day": now_kst().date().isoformat()})).json()
|
||||
places = body["places"]
|
||||
assert places and all(p["distance_km"] <= PLACE_RADIUS_KM for p in places)
|
||||
good = [p["distance_km"] for p in places if p["is_good"]]
|
||||
assert good == sorted(good)
|
||||
assert all(p["image_credit"] == "ⓒ한국관광공사" for p in places if p.get("image"))
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_weekend_ranking_scores_30_spots_and_caches(fakes, monkeypatch):
|
||||
from services.weekend_rank import weekend_days
|
||||
|
||||
Reference in new issue
Block a user