feat: 계절 각 — 각마다 제철 달(months), 제철 각에 지금 계절 표시·철 지난 각은 순위 밖 맨 끝, 새 각 12개(꽃구경·이불빨래·빙수·실내건조·한강밤바람·단풍·억새·군고구마·해돋이·눈사람·붕어빵·귤까먹기), 해 뜰 무렵 시간대·일출 점수·눈 조건
This commit is contained in:
1 parent
43e1925d70
commit
5c05824ce0
14 files changed
+1130
-66
No files matched your search
@@ -15,7 +15,7 @@ from crud.region_crud import RegionCRUD
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.router import app
|
||||
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
|
||||
from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, season_of, slot_days, slot_label, windows_for
|
||||
|
||||
REGION = "1141000000"
|
||||
|
||||
@@ -54,17 +54,19 @@ def fakes(monkeypatch):
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes):
|
||||
async def test_index_list_ranks_every_gak_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"]) == 34 and len(body["top3"]) == 3
|
||||
assert len(body["items"]) == len(_seed()) and len(body["top3"]) == 3
|
||||
priority = {d["code"]: d["priority"] for d in _seed()}
|
||||
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤. 각 묶음 안에서는 점수 × 중요도 순
|
||||
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤, 제철 아닌 각은 맨 끝. 앞 두 묶음 안에서는 점수 × 중요도 순
|
||||
actives = [i["active"] for i in body["items"]]
|
||||
assert actives == sorted(actives, reverse=True) and all(i["active"] for i in body["top3"])
|
||||
seasons = [i["in_season"] for i in body["items"]]
|
||||
assert seasons == sorted(seasons, reverse=True) and all(i["active"] is False for i in body["items"] if not i["in_season"])
|
||||
for group in (True, False):
|
||||
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group]
|
||||
weighted = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group and i["in_season"]]
|
||||
assert weighted == sorted(weighted, reverse=True)
|
||||
today = now_kst().date()
|
||||
for i in body["items"]:
|
||||
@@ -75,10 +77,12 @@ async def test_index_list_ranks_all_34_with_today_tomorrow_weekend_trend(fakes):
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_index_list_filters_core(fakes):
|
||||
async def test_index_list_filters_core_to_gak_in_season_now(fakes):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
body = (await client.get("/v1/index/list", params={"region": REGION, "core": True})).json()
|
||||
assert {i["code"] for i in body["items"]} == {"picnic", "hiking", "camping", "stars"}
|
||||
month = now_kst().month
|
||||
assert {i["code"] for i in body["items"]} == {d["code"] for d in _seed() if month in d["months"]}
|
||||
assert all(i["season"] == season_of(month) for i in body["items"])
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -119,6 +123,33 @@ def test_every_index_has_priority():
|
||||
assert all(d["priority"] in (1, 2, 3) for d in _seed())
|
||||
|
||||
|
||||
def test_every_index_has_valid_months_and_weights():
|
||||
for d in _seed():
|
||||
assert isinstance(d["months"], list) and all(1 <= m <= 12 for m in d["months"]), d["code"]
|
||||
assert sum(d[f"weight_{a}"] for a in ("temp", "rain", "wind", "humidity", "air", "uv", "sun", "view", "time")) == 100, d["code"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypatch):
|
||||
today = now_kst().date()
|
||||
other = [m for m in range(1, 13) if m != today.month]
|
||||
defs = [
|
||||
SimpleNamespace(index_id=1, code="always", priority=2, months=[], sort_order=1),
|
||||
SimpleNamespace(index_id=2, code="now", priority=2, months=[today.month], sort_order=2),
|
||||
SimpleNamespace(index_id=3, code="off", priority=1, months=other[:3], sort_order=3),
|
||||
]
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) for x, v in ((1, 50), (2, 60), (3, 99))]
|
||||
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, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50})))
|
||||
_, board = await service.board(REGION)
|
||||
view = [(i.definition.code, i.active, i.in_season, i.season) for i in board.items]
|
||||
# 점수가 가장 높아도 제철이 아니면 순위 밖 맨 끝. 계절 표시는 제철 달이 정해진 각에만
|
||||
assert view == [("now", True, True, season_of(today.month)), ("always", True, True, None), ("off", False, False, None)]
|
||||
assert [i.definition.code for i in board.ranked] == ["now", "always"]
|
||||
assert all(not i.slot_ranks for i in board.items if not i.in_season)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
|
||||
today = now_kst().date()
|
||||
|
||||
@@ -259,6 +259,22 @@ def test_new_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert _seed_score(code, **bad) <= 30
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code, good, bad", [
|
||||
("flower", dict(feels=19.0, wind=2.0, sunshine_ratio=0.8, visibility_km=20.0), dict(feels=8.0, prob=80, rain=RainType.RAIN, sunshine_ratio=0.1, visibility_km=4.0)),
|
||||
("blanket", dict(feels=22.0, wind=3.0, hum=35, sunshine_ratio=0.9), dict(feels=10.0, prob=70, rain=RainType.RAIN, hum=90, sunshine_ratio=0.1)),
|
||||
("bingsu", dict(feels=33.0, hum=75), dict(feels=18.0, hum=40)),
|
||||
("indoordry", dict(feels=27.0, prob=90, rain=RainType.RAIN, hum=55), dict(feels=14.0, hum=90)),
|
||||
("riverwind", dict(feels=24.0, wind=3.0, hum=55), dict(feels=20.0, prob=80, rain=RainType.RAIN, wind=0.5, hum=90)),
|
||||
("foliage", dict(feels=16.0, wind=2.0, sunshine_ratio=0.8, visibility_km=20.0), dict(feels=8.0, prob=80, rain=RainType.RAIN, sunshine_ratio=0.1, visibility_km=4.0)),
|
||||
("sweetpotato", dict(feels=2.0, wind=6.0), dict(feels=20.0, wind=1.0)),
|
||||
("bungeoppang", dict(feels=-5.0, wind=6.0), dict(feels=15.0, wind=1.0)),
|
||||
("tangerine", dict(feels=-5.0, wind=7.0, prob=80, rain=RainType.SNOW), dict(feels=15.0, wind=1.0)),
|
||||
])
|
||||
def test_seasonal_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert _seed_score(code, **good) >= 80
|
||||
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
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from common.utils.kma_time import KST
|
||||
from services.calc.index_calc import Context, DayForecast, Hour, estimate, evaluate, time_score, zero_rules_text
|
||||
from services.calc.sun import sun_times
|
||||
from services.index_service import in_season, season_badge, season_of, window_hours
|
||||
|
||||
CTX = Context(day=date(2027, 1, 9), is_holiday=False, pm25=10, air_label="좋음", moon=0.5, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
SNOWMAN = SimpleNamespace(
|
||||
weight_temp=50, weight_rain=10, weight_wind=20, weight_humidity=0, weight_air=0, weight_time=20,
|
||||
factor_rules={"temp": {"type": "range", "lo": -5, "hi": 2, "best": -1}, "rain": {"dir": "wet"}, "wind": {"type": "calm", "ok": 3, "limit": 10},
|
||||
"humidity": {"type": "ignore"}, "time": {"type": "fixed", "value": 100}},
|
||||
zero_rules=[{"field": "snow", "op": "==", "value": "no"}], windows=[{"from": 9, "to": 16}],
|
||||
)
|
||||
|
||||
|
||||
def _h(hour, rain=RainType.NONE, feels=-1.0):
|
||||
return Hour(hour=hour, feels_c=feels, rain_type=rain, rain_prob=80 if rain is not RainType.NONE else 0, wind_ms=1.0, humidity=70, sky=Sky.CLOUDY)
|
||||
|
||||
|
||||
def test_season_names_and_in_season():
|
||||
assert [season_of(m) for m in (1, 3, 6, 9, 12)] == ["겨울", "봄", "여름", "가을", "겨울"]
|
||||
always, winter = SimpleNamespace(months=[]), SimpleNamespace(months=[12, 1, 2])
|
||||
assert in_season(always, 7) and in_season(winter, 1) and not in_season(winter, 7)
|
||||
# 일 년 내내인 각엔 계절 표시가 없다
|
||||
assert season_badge(always, 1) is None and season_badge(winter, 1) == "겨울" and season_badge(winter, 7) is None
|
||||
assert in_season(SimpleNamespace(), 5)
|
||||
|
||||
|
||||
def test_snowman_is_zero_without_snow_and_high_when_snowing_near_zero():
|
||||
dry = evaluate(SNOWMAN, [[_h(h) for h in range(9, 16)]], CTX)
|
||||
assert dry.score == 0 and dry.zero_reason == "눈 소식이 없어 0점"
|
||||
snowy = evaluate(SNOWMAN, [[_h(h, RainType.SNOW) for h in range(9, 16)]], CTX)
|
||||
assert snowy.score >= 80 and snowy.zero_reason is None
|
||||
assert zero_rules_text(SNOWMAN.zero_rules) == "눈 소식이 없으면 0점"
|
||||
|
||||
|
||||
def test_snowman_estimate_from_mid_forecast_is_zero():
|
||||
fc = DayForecast(temp_min_c=-4, temp_max_c=1, rain_prob_am=70, rain_prob_pm=70, sky=Sky.CLOUDY)
|
||||
assert estimate(SNOWMAN, fc, [list(range(9, 16))], CTX).score == 0
|
||||
|
||||
|
||||
def test_sunrise_score_time_rule():
|
||||
assert time_score({"type": "sunrise_score"}, Context(**{**CTX.__dict__, "sunrise_score": 72})) == (72, "일출 하늘 점수 72")
|
||||
assert time_score({"type": "sunrise_score"}, CTX)[0] == 70
|
||||
|
||||
|
||||
def test_window_around_sunrise_covers_sunrise_hour():
|
||||
region = SimpleNamespace(lat=37.56, lon=126.97)
|
||||
day = date(2027, 1, 1)
|
||||
h = sun_times(day, region.lat, region.lon).sunrise_at.astimezone(KST).hour
|
||||
assert window_hours(SimpleNamespace(windows=[{"around": "sunrise", "hours": 1}]), day, region) == [[h - 1, h, h + 1]]
|
||||
|
||||
Reference in new issue
Block a user