fix: 각을 시간대와 관계없이 활성화하고 시간 적합도를 가중치로 반영
This commit is contained in:
1 parent
3b5afba8a1
commit
799a46f53c
13 files changed
+124
-66
No files matched your search
@@ -48,11 +48,10 @@ def test_current_slot_before_5_is_previous_night():
|
||||
assert current_slot(datetime(2026, 10, 8, 16, 30, tzinfo=KST), SUNSET) == "evening"
|
||||
|
||||
|
||||
def test_gak_hidden_in_slots_outside_its_window():
|
||||
def test_gak_scores_every_slot_and_time_match_is_binary():
|
||||
parts = slot_results(_defn([{"from": 17, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
|
||||
assert set(parts) == {"evening", "night"}
|
||||
# 18시 한 시간만 저녁 구간(16~18시)과 겹치면 저녁 점수는 내지 않는다
|
||||
assert set(slot_results(_defn([{"from": 18, "to": 24}]), DAY, REGION, _rows(), {}, CTX, SUNSET)) == {"night"}
|
||||
assert set(parts) == {"morning", "day", "evening", "night", EARLY}
|
||||
assert {k: r.factors["time"] for k, r in parts.items()} == {"morning": 0, "day": 0, "evening": 100, "night": 100, EARLY: 0}
|
||||
|
||||
|
||||
def test_rain_in_evening_lowers_only_later_slots():
|
||||
@@ -102,12 +101,25 @@ def test_ultra_rain_lowers_slot_score():
|
||||
assert wet < dry
|
||||
|
||||
|
||||
def test_slot_needs_two_overlapping_hours():
|
||||
"""10~17시 각은 아침 구간(5~11시)과 10시 한 시간만 겹쳐서 아침 점수를 내지 않는다. 한 시간짜리 각은 한 시간이면 된다."""
|
||||
def test_time_match_includes_one_overlapping_hour():
|
||||
by_at = _rows()
|
||||
assert "morning" not in slot_results(_defn([{"from": 10, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
assert "morning" in slot_results(_defn([{"from": 9, "to": 17}]), DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
assert "morning" in slot_results(_defn([{"from": 10, "to": 11}]), DAY, REGION, by_at, {}, CTX, SUNSET)
|
||||
for start, end in ((10, 17), (9, 17), (10, 11)):
|
||||
assert slot_results(_defn([{"from": start, "to": end}]), DAY, REGION, by_at, {}, CTX, SUNSET)["morning"].factors["time"] == 100
|
||||
|
||||
|
||||
def test_outside_window_uses_current_weather_instead_of_daily_weather():
|
||||
parts = slot_results(_defn([{"from": 7, "to": 11}]), DAY, REGION, _rows(rain_from=16), {}, CTX, SUNSET)
|
||||
assert parts["morning"].score == 100
|
||||
assert parts["night"].score < parts["morning"].score
|
||||
assert parts["night"].factors["rain"] == 0 and parts["night"].factors["time"] == 0
|
||||
|
||||
|
||||
def test_early_hours_match_windows_crossing_midnight():
|
||||
parts = slot_results(_defn([{"from": 21, "to": 26}]), DAY, REGION, _rows(), {}, CTX, SUNSET)
|
||||
assert parts[EARLY].factors["time"] == 100
|
||||
now = datetime(2026, 10, 8, 2, 0, tzinfo=KST)
|
||||
parts = slot_results(_defn([{"from": 21, "to": 26}]), DAY, REGION, _rows(), {}, CTX, SUNSET, now)
|
||||
assert parts[EARLY].factors["time"] == 0
|
||||
|
||||
|
||||
def test_current_slot_skips_passed_hours():
|
||||
|
||||
@@ -8,10 +8,12 @@ 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.index_crud import IndexCRUD
|
||||
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
|
||||
from services.index_service import in_season
|
||||
from services.week_service import collect_events
|
||||
|
||||
REGION = "1114000000"
|
||||
@@ -61,7 +63,10 @@ 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"]) == 40
|
||||
_, definitions = await DB_SESSION_MNG.execute_lambda(lambda s: IndexCRUD().definitions(s))
|
||||
expected = {d.code for d in definitions if in_season(d, now_kst().month)}
|
||||
assert {g["code"] for g in body["stories"]} == expected
|
||||
assert all(g["active"] for g in body["stories"])
|
||||
assert body["hero"]["weather_score"] == body["hero"]["weather_slots"][body["slot"]]
|
||||
assert all(g["slots"][body["slot"]] == g["score"] and g["slot_ranks"][body["slot"]] == g["rank"] for g in body["stories"] if g["active"])
|
||||
weather = next(p for p in body["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
|
||||
@@ -8,7 +8,7 @@ import services.air_service as air_service
|
||||
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.database.model.models import IndexScore, OpenMeteoHourly, WeatherHourly
|
||||
from common.enums import ErrorType
|
||||
from common.utils.kma_time import kst_midnight, now_kst
|
||||
from crud.region_crud import RegionCRUD
|
||||
@@ -24,6 +24,14 @@ async def _async(v):
|
||||
return v
|
||||
|
||||
|
||||
def _board_score(index_id, day, score, slot_score=None):
|
||||
value = score if slot_score is None else slot_score
|
||||
return IndexScore(index_id=index_id, score_date=day, score=score, slots={
|
||||
k: {"score": value, "summary": "", "factors": {}, "zero_reason": None, "notes": {}}
|
||||
for k in ("morning", "day", "evening", "night", "early")
|
||||
})
|
||||
|
||||
|
||||
def _vilage(*_):
|
||||
start = kst_midnight(now_kst().date())
|
||||
items = []
|
||||
@@ -61,7 +69,8 @@ async def test_index_list_ranks_every_gak_with_today_tomorrow_weekend_trend(fake
|
||||
assert body["result"]["success"] is True
|
||||
assert len(body["items"]) == len(_seed()) and len(body["top3"]) == 3
|
||||
priority = {d["code"]: d["priority"] for d in _seed()}
|
||||
# 지금 구간에 해당하는 각이 먼저(순위), 해당 없는 각은 그 뒤, 제철 아닌 각은 맨 끝. 앞 두 묶음 안에서는 점수 × 중요도 순
|
||||
# 시간대와 관계없이 제철인 각은 모두 활성화하고, 제철 아닌 각은 맨 끝.
|
||||
assert all(i["active"] for i in body["items"] if i["in_season"])
|
||||
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"]]
|
||||
@@ -139,7 +148,7 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat
|
||||
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))]
|
||||
scores = [_board_score(x, today, v) 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})))
|
||||
@@ -159,7 +168,7 @@ async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
|
||||
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, slots={}) for x, v in ((1, 90), (2, 80), (3, 70))]
|
||||
scores = [_board_score(x, today, 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, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50})))
|
||||
@@ -175,7 +184,7 @@ async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
|
||||
defs = [SimpleNamespace(index_id=1, code="low", priority=3), SimpleNamespace(index_id=2, code="high", priority=1)]
|
||||
every = ("morning", "day", "evening", "night", "early")
|
||||
slots = {1: {k: {"score": 90, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every},
|
||||
2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every if k not in ("night", "early")}}
|
||||
2: {k: {"score": 20 if k == "morning" else 70, "summary": "", "factors": {}, "zero_reason": None, "notes": []} for k in every}}
|
||||
scores = [SimpleNamespace(index_id=x, score_date=today, score=80, slots=slots[x]) for x in (1, 2)]
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async(scores))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
@@ -183,10 +192,32 @@ async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
|
||||
monkeypatch.setattr("services.index_service._with_slot", lambda row, data: SimpleNamespace(score=data["score"]))
|
||||
_, board = await service.board(REGION)
|
||||
ranks = {i.definition.code: i.slot_ranks for i in board.items}
|
||||
# 아침: 하 90(63) > 상 20(20). 낮: 상 70(70) > 하 90(63). 상은 밤 구간이 없어 밤 순위도 없다
|
||||
# 아침: 하 90(63) > 상 20(20). 낮·밤: 상 70(70) > 하 90(63).
|
||||
assert ranks["low"]["morning"] == 1 and ranks["high"]["morning"] == 2
|
||||
assert ranks["high"]["day"] == 1 and ranks["low"]["day"] == 2
|
||||
assert "night" not in ranks["high"]
|
||||
assert ranks["high"]["night"] == 1 and ranks["low"]["night"] == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("cur", ["morning", "day", "evening", "night", "early"])
|
||||
async def test_board_activates_gak_outside_its_time_window(monkeypatch, cur):
|
||||
today = now_kst().date()
|
||||
defs = [SimpleNamespace(index_id=1, code="outside", priority=1)]
|
||||
row = _board_score(1, today, 85, slot_score=65)
|
||||
crud = SimpleNamespace(definitions=lambda s: _async(defs), scores=lambda s, *a: _async([row]))
|
||||
service = IndexService(RegionCRUD(), crud, None, None, None, None, None, None)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {cur: 50})))
|
||||
monkeypatch.setattr("services.index_service.current_slot", lambda *a: cur)
|
||||
|
||||
err, board = await service.board(REGION)
|
||||
|
||||
assert err is ErrorType.SUCCESS
|
||||
assert len(board.ranked) == 1
|
||||
item = board.ranked[0]
|
||||
assert item.active and item.score.score == 65 and item.rank == 1
|
||||
assert item.trend == [item.score] and item.slot == ("night" if cur == "early" else cur)
|
||||
assert item.slots == {k: 65 for k in ("morning", "day", "evening", "night")}
|
||||
assert item.slot_ranks == {k: 1 for k in item.slots}
|
||||
|
||||
|
||||
def _om_row(at, **over):
|
||||
|
||||
@@ -38,6 +38,22 @@ def test_perfect_evening_scores_100():
|
||||
assert r.notes["temp"] == "체감 21°, 편한 범위 18~24° 안"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("weight", [5, 10, 20])
|
||||
def test_time_match_adds_only_its_weight_without_extra_penalty(weight):
|
||||
rules = _defn().factor_rules | {"time": {"type": "fixed", "value": 55}}
|
||||
defn = _defn(weight_temp=100 - weight, weight_rain=0, weight_wind=0, weight_humidity=0, weight_air=0,
|
||||
weight_time=weight, factor_rules=rules)
|
||||
hours = [[_h(12)]]
|
||||
matched = evaluate(defn, hours, replace(CTX, time_matches=True))
|
||||
unmatched = evaluate(defn, hours, replace(CTX, time_matches=False))
|
||||
assert matched.factors["time"] == 100 and unmatched.factors["time"] == 0
|
||||
assert matched.score == 100 and unmatched.score == 100 - weight
|
||||
|
||||
|
||||
def test_time_matching_does_not_replace_weekday_score():
|
||||
assert evaluate(_defn(), [[_h(12)]], replace(CTX, time_matches=False)).factors["time"] == 100
|
||||
|
||||
|
||||
def test_good_but_not_perfect_stays_below_100():
|
||||
assert evaluate(_defn(), [[_h(19, feels=23, hum=58, wind=1.8)]], CTX).score < 95
|
||||
|
||||
|
||||
Reference in new issue
Block a user