from datetime import date, timedelta from types import SimpleNamespace import pytest from httpx import ASGITransport, AsyncClient import services.air_service as air_service import services.index_service as index_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 IndexScore, 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.calc.index_calc import AXES, Result, rank_score from services.index_service import IndexService, _nearest_slot_end_hour, _slot_end_hour, season_of, slot_days, slot_label, windows_for _RESULT_50 = Result(score=50, factors={a: 50 for a in AXES}, notes={}, zero_reason=None, summary="") _WEATHER_50 = {k: _RESULT_50 for k in ("morning", "day", "evening", "night", "early")} REGION = "1141000000" 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 = [] for h in range(24 * 4): at = start + timedelta(hours=h) for c, v in [("TMP", "21"), ("SKY", "1"), ("PTY", "0"), ("POP", "0"), ("PCP", "강수없음"), ("REH", "50"), ("WSD", "1.5")]: items.append({"category": c, "fcstDate": at.strftime("%Y%m%d"), "fcstTime": at.strftime("%H%M"), "fcstValue": v}) return items def _mid(*_): land = {f"wf{n}{p}": "맑음" for n in range(4, 11) for p in ("Am", "Pm")} | {f"rnSt{n}{p}": 10 for n in range(4, 11) for p in ("Am", "Pm")} ta = {f"taMin{n}": 12 for n in range(4, 11)} | {f"taMax{n}": 22 for n in range(4, 11)} return land, ta @pytest.fixture def fakes(monkeypatch): now = now_kst() monkeypatch.setattr(weather_service, "fetch_vilage", lambda *a: _async(_vilage())) monkeypatch.setattr(air_service, "fetch_stations", lambda *a: _async([{"stationName": "신촌동", "dmX": "37.565", "dmY": "126.937"}])) 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(weather_service, "fetch_mid", lambda *a: _async(_mid())) monkeypatch.setattr(weather_service, "fetch_ultra", lambda *a: _async([])) @pytest.mark.anyio 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"]) == 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"]] 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): scores = [i["score"] for i in body["items"] if i["active"] is group and i["in_season"]] assert scores == sorted(scores, reverse=True) order = [rank_score(i["score"], priority[i["code"]]) for i in body["items"] if i["active"] is group and i["in_season"]] assert order == sorted(order, 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)] assert not any(t["estimated"] for t in i["trend"][:2]) assert all(t["estimated"] for t in i["trend"][2:] if date.fromisoformat(t["day"]) > today + timedelta(days=3)) assert 0 <= body["weather_score"] <= 100 @pytest.mark.anyio async def test_index_list_asks_for_the_observed_weather_once(fakes, monkeypatch): calls = [] async def fake_ncst(client, nx, ny, base): calls.append(base) return [] monkeypatch.setattr(weather_service, "fetch_ncst", fake_ncst) async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: assert (await client.get("/v1/index/list", params={"region": REGION})).json()["result"]["success"] is True assert len(calls) == 1 @pytest.mark.anyio async def test_index_scores_are_recomputed_once_the_new_hours_observation_is_out(fakes, monkeypatch): """14:05 에 계산한 점수는 14:12 에도 그대로 쓰고, 14시 실황을 쓰기 시작하는 14:15 이후엔 다시 계산한다.""" day = kst_midnight(now_kst().date()) clock = [day + timedelta(hours=14, minutes=5)] computed = [] real_day_result = index_service.day_result def counting(*a, **k): computed.append(1) return real_day_result(*a, **k) async def observed(*_a): return [{"category": c, "obsrValue": v} for c, v in {"PTY": "0", "REH": "50", "RN1": "0", "T1H": "21", "WSD": "1.5"}.items()] monkeypatch.setattr(index_service, "now_kst", lambda: clock[0]) monkeypatch.setattr(index_service, "day_result", counting) monkeypatch.setattr(weather_service, "fetch_ncst", observed) monkeypatch.setattr(air_service, "fetch_realtime", lambda *a: _async([{ "stationName": "신촌동", "pm25Value": "10", "pm10Value": "20", "pm25Grade": "1", "pm10Grade": "1", "dataTime": f"{day:%Y-%m-%d} 14:00", }])) async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: await client.get("/v1/index/list", params={"region": REGION}) first = len(computed) assert first > 0 clock[0] = day + timedelta(hours=14, minutes=12) await client.get("/v1/index/list", params={"region": REGION}) assert len(computed) == first clock[0] = day + timedelta(hours=14, minutes=16) await client.get("/v1/index/list", params={"region": REGION}) assert len(computed) > first @pytest.mark.anyio 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() 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 async def test_index_detail_has_six_factors_and_rules(fakes): async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: body = (await client.get("/v1/index/1", params={"region": REGION})).json() assert body["index"]["code"] == "yajang" assert [f["label"] for f in body["factors"]] == ["기온 알맞음", "비 안 옴", "바람 잔잔", "습도 알맞음", "공기 맑음", "요일 알맞음"] assert sum(f["weight"] for f in body["factors"]) == 100 assert body["zero_rules"] == "비 소식이 있거나 비 확률 70% 이상이거나 바람 14m/s 이상이면 0점" assert body["limit"].startswith("모기") @pytest.mark.anyio async def test_index_detail_has_four_score_bands_with_today_marked(fakes): async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: body = (await client.get("/v1/index/1", params={"region": REGION})).json() bands = body["bands"] assert [(b["low"], b["high"]) for b in bands] == [(0, 29), (30, 59), (60, 79), (80, 100)] assert all(b["text"] for b in bands) current = [b for b in bands if b["current"]] assert len(current) == 1 and current[0]["low"] <= body["index"]["score"] <= current[0]["high"] def _seed() -> list[dict]: import json import os 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()) 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 = [_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, {now_kst().date(): _WEATHER_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_displays_and_ranks_by_priority_adjusted_score(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 = [_board_score(x, today, v) for x, v in ((1, 90), (2, 80), (3, 70))] scores += [_board_score(x, today + timedelta(days=1), 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, {now_kst().date(): _WEATHER_50}))) err, board = await service.board(REGION) assert err is ErrorType.SUCCESS assert [(i.definition.code, i.score.score, i.rank) for i in board.items] == [("high", 70, 1), ("mid", 68, 2), ("low", 63, 3)] for item in board.items: assert item.trend[0].score == item.score.score assert item.trend[1].score == item.score.score assert all(value == item.score.score for value in item.slots.values()) # 응답용 보정은 DB에서 읽은 원점수를 바꾸지 않으며, 같은 요청을 다시 해도 중복 적용하지 않는다. assert [row.score for row in scores] == [90, 80, 70, 90, 80, 70] _, again = await service.board(REGION) assert [i.score.score for i in again.items] == [70, 68, 63] @pytest.mark.anyio async def test_board_ranks_each_slot_by_displayed_score(monkeypatch): today = now_kst().date() 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}} 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) monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {now_kst().date(): {k: _RESULT_50 for k in every}}))) 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점, 상 70점은 표시 70점으로 순위와 화면 숫자가 일치한다. assert ranks["low"]["morning"] == 1 and ranks["high"]["morning"] == 2 assert ranks["high"]["day"] == 1 and ranks["low"]["day"] == 2 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, {today: {cur: _RESULT_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): row = { "region_code": REGION, "forecast_at": at, "fetched_at": now_kst(), "uv_index": 2.0, "uv_index_clear_sky": 2.0, "visibility_m": 25000, "wind_gust_ms": 5.0, "pressure_hpa": 1015.0, "soil_temp_c": 20.0, "sunshine_s": 10800, "shortwave_avg_wm2": 500, "shortwave_max_wm2": 600, } return row | over async def _put_om(rows): await DB_SESSION_MNG.execute_lambda_run([lambda s: WeatherCRUD().upsert_openmeteo(s, rows)]) async def _laundry_sun(client): items = (await client.get("/v1/index/list", params={"region": REGION})).json()["items"] index_id = next(i["index_id"] for i in items if i["code"] == "laundry") body = (await client.get(f"/v1/index/{index_id}", params={"region": REGION})).json() return {f["axis"]: f for f in body["factors"]} def test_slot_end_hours_for_covering_and_nearest_slot(): hours = (0, 2, 3, 7, 8, 9, 10, 11, 12, 15, 21, 23, 26) assert [_slot_end_hour(h) for h in hours] == [3, 3, 6, 9, 9, 12, 12, 12, 15, 18, 24, 24, 27] assert [_nearest_slot_end_hour(h) for h in hours] == [0, 3, 3, 9, 9, 9, 12, 12, 12, 15, 21, 24, 27] def test_windows_attach_instant_values_from_nearest_slot_and_sunshine_from_covering_slot(): day = date(2026, 10, 6) start = kst_midnight(day) by_at = { start + timedelta(hours=h): WeatherHourly( forecast_at=start + timedelta(hours=h), feels_c=20, rain_type=1, rain_prob=0, wind_ms=1.0, humidity=50, sky=1 ) for h in range(7, 16) } by_om = { start + timedelta(hours=end): OpenMeteoHourly( forecast_at=start + timedelta(hours=end), uv_index=uv, sunshine_s=sun, visibility_m=12000, wind_gust_ms=7.5, soil_temp_c=20.0 ) for end, uv, sun in ((9, 1.0, 1800), (12, 2.0, 5400), (15, 3.0, 9000), (18, 4.0, 10800)) } morning, noon = windows_for(SimpleNamespace(windows=[{"from": 7, "to": 9}, {"from": 11, "to": 16}]), day, None, by_at, by_om) assert [h.uv for h in morning] == [1.0, 1.0] assert [h.uv for h in noon] == [2.0, 2.0, 3.0, 3.0, 3.0] # 순간값은 가장 가까운 구간 (11·12시→12시, 13~15시→15시) assert [h.sunshine_ratio for h in noon] == [0.5, 9000 / 10800, 9000 / 10800, 9000 / 10800, 1.0] # 일조는 덮는 구간 (직전 3시간 합) assert morning[0].visibility_km == 12.0 and morning[0].gust_ms == 7.5 and morning[0].ground_c == 20.0 no_om = windows_for(SimpleNamespace(windows=[{"from": 7, "to": 9}]), day, None, by_at, None)[0] assert all(h.uv is None and h.sunshine_ratio is None for h in no_om) def test_dark_slots_count_as_no_sun_not_unknown(): day = date(2026, 10, 6) start = kst_midnight(day) by_at = { start + timedelta(hours=h): WeatherHourly( forecast_at=start + timedelta(hours=h), feels_c=20, rain_type=1, rain_prob=0, wind_ms=1.0, humidity=50, sky=1 ) for h in (22, 23) } by_om = {start + timedelta(hours=24): OpenMeteoHourly(forecast_at=start + timedelta(hours=24), uv_index=None, sunshine_s=None, visibility_m=20000)} hours = windows_for(SimpleNamespace(windows=[{"from": 22, "to": 24}]), day, None, by_at, by_om)[0] assert [(h.uv, h.sunshine_ratio, h.visibility_km) for h in hours] == [(0.0, 0.0, 20.0)] * 2 @pytest.mark.anyio async def test_new_axis_shows_only_for_weighted_indices_and_unknown_without_data(fakes): async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: laundry = await _laundry_sun(client) yajang = (await client.get("/v1/index/1", params={"region": REGION})).json()["factors"] assert laundry["sun"]["weight"] == 25 and laundry["sun"]["value"] == 70 and laundry["sun"]["note"] == "햇빛 정보 없음" assert sum(f["weight"] for f in laundry.values()) == 100 assert [f["axis"] for f in yajang] == ["temp", "rain", "wind", "humidity", "air", "time"] async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: items = (await client.get("/v1/index/list", params={"region": REGION})).json()["items"] stars_id = next(i["index_id"] for i in items if i["code"] == "stars") stars = (await client.get(f"/v1/index/{stars_id}", params={"region": REGION})).json()["factors"] assert {f["axis"]: f["label"] for f in stars}["view"] == "가시거리" @pytest.mark.anyio async def test_openmeteo_data_changes_index_and_triggers_recompute(fakes): today = kst_midnight(now_kst().date()) async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client: before = await _laundry_sun(client) assert before["sun"]["value"] == 70 await _put_om([_om_row(today + timedelta(hours=h), fetched_at=now_kst() + timedelta(hours=1)) for h in (12, 15, 18)]) after = await _laundry_sun(client) assert after["sun"]["value"] == 100 and after["sun"]["note"] == "해 난 비율 100%"