feat: main 병합 + 인스타 올리기 API(/v1/card/{id}/instagram), 관리자 올릴 곳 선택(로컬·킹서버), 만든 카드 화면
This commit is contained in:
commit
572b2a05c8
188 files changed
+16605
-741
No files matched your search
@@ -43,7 +43,7 @@ def anyio_backend():
|
||||
|
||||
_VOLATILE = (
|
||||
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
|
||||
"sky_score", "index_score", "post", "post_like", "post_save", "comment", "comment_like", "holiday", "solar_term", "users", "card_set", "card_image",
|
||||
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "holiday", "solar_term", "users", "card_set", "card_image",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from router.router import app
|
||||
|
||||
REGION = "1144000000"
|
||||
IP_A = {"X-Forwarded-For": "203.0.113.10"}
|
||||
IP_B = {"X-Forwarded-For": "203.0.113.20"}
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_post_like_counts_once_per_ip(offline):
|
||||
async with client() as c:
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
url = f"/v1/reaction/post/{post_id}/like"
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_B)).json()["like_count"] == 2
|
||||
h = await _login(c, "anon_like_01")
|
||||
assert (await c.post(url, headers={**h, **IP_A})).json()["like_count"] == 3
|
||||
|
||||
feed_a = (await c.get("/v1/feed", params={"region": REGION}, headers=IP_A)).json()
|
||||
p = next(x for x in feed_a["posts"] if x["post_id"] == post_id)
|
||||
assert p["liked"] is True and p["like_count"] == 3 and "saved" not in p
|
||||
other = (await c.get("/v1/feed", params={"region": REGION}, headers={"X-Forwarded-For": "203.0.113.30"})).json()
|
||||
assert next(x for x in other["posts"] if x["post_id"] == post_id)["liked"] is False
|
||||
|
||||
assert (await c.delete(url, headers=IP_A)).json()["like_count"] == 2
|
||||
assert (await c.delete(url, headers=IP_A)).json()["like_count"] == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_only_last_forwarded_ip_counts(offline):
|
||||
"""클라이언트가 X-Forwarded-For 앞쪽을 바꿔도 nginx 가 붙인 마지막 주소가 같으면 같은 사람이다."""
|
||||
async with client() as c:
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
url = f"/v1/reaction/post/{post_id}/like"
|
||||
assert (await c.post(url, headers={"X-Forwarded-For": "1.1.1.1, 203.0.113.10"})).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers={"X-Forwarded-For": "2.2.2.2, 203.0.113.10"})).json()["like_count"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_comment_like(offline):
|
||||
async with client() as c:
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
h = await _login(c, "anon_like_02")
|
||||
comment_id = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": "맑아요"})).json()["comment"]["comment_id"]
|
||||
url = f"/v1/reaction/comment/{comment_id}/like"
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_B)).json()["like_count"] == 2
|
||||
assert (await c.post(url, headers=h)).json()["like_count"] == 3
|
||||
|
||||
listed = (await c.get(f"/v1/reaction/post/{post_id}/comment/list", headers=IP_A)).json()["comments"]
|
||||
assert listed[0]["liked"] is True
|
||||
listed = (await c.get(f"/v1/reaction/post/{post_id}/comment/list", headers={"X-Forwarded-For": "203.0.113.30"})).json()["comments"]
|
||||
assert listed[0]["liked"] is False
|
||||
|
||||
assert (await c.delete(url, headers=IP_B)).json()["like_count"] == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_talk_like():
|
||||
async with client() as c:
|
||||
h = await _login(c, "anon_like_03")
|
||||
talk_id = (await c.post("/v1/talk", json={"region_code": REGION, "body": "바람 불어요"}, headers=h)).json()["talk"]["talk_id"]
|
||||
url = f"/v1/talk/{talk_id}/like"
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(url, headers=IP_B)).json()["like_count"] == 2
|
||||
assert (await c.post(url, headers=h)).json()["like_count"] == 3
|
||||
|
||||
talks = (await c.get("/v1/talk/list", headers=IP_A)).json()["talks"]
|
||||
assert next(x for x in talks if x["talk_id"] == talk_id)["liked"] is True
|
||||
talks = (await c.get("/v1/talk/list", headers={"X-Forwarded-For": "203.0.113.30"})).json()["talks"]
|
||||
assert next(x for x in talks if x["talk_id"] == talk_id)["liked"] is False
|
||||
|
||||
assert (await c.delete(url, headers=IP_A)).json()["like_count"] == 2
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_comment_shows_region_and_only_same_ip_deletes(offline):
|
||||
async with client() as c:
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
url = f"/v1/reaction/post/{post_id}/comment"
|
||||
made = (await c.post(url, headers=IP_A, json={"body": " 우산 챙겨요 ", "region": REGION})).json()["comment"]
|
||||
assert made["body"] == "우산 챙겨요" and made["nickname"] == "마포구 익명" and made["mine"] is True
|
||||
assert (await c.post(url, headers=IP_A, json={"body": "www.example.com 보세요"})).json()["result"]["desc"] == "LINK_NOT_ALLOWED"
|
||||
no_region = (await c.post(url, headers=IP_A, json={"body": "안녕"})).json()["comment"]
|
||||
assert no_region["nickname"] == "익명"
|
||||
|
||||
listed = (await c.get(f"{url}/list", headers=IP_B)).json()["comments"]
|
||||
assert [(x["nickname"], x["mine"]) for x in listed] == [("마포구 익명", False), ("익명", False)]
|
||||
assert next(x for x in (await c.get(f"{url}/list", headers=IP_A)).json()["comments"] if x["comment_id"] == made["comment_id"])["mine"] is True
|
||||
|
||||
h = await _login(c, "anon_cmt_01")
|
||||
delete = f"/v1/reaction/comment/{made['comment_id']}"
|
||||
assert (await c.delete(delete, headers=IP_B)).json()["result"]["desc"] == "NOT_FOUND"
|
||||
assert (await c.delete(delete, headers={**h, **IP_A})).json()["result"]["desc"] == "NOT_FOUND"
|
||||
assert (await c.delete(delete, headers=IP_A)).json()["result"]["success"] is True
|
||||
feed = (await c.get("/v1/feed", params={"region": REGION})).json()
|
||||
assert next(x for x in feed["posts"] if x["post_id"] == post_id)["comment_count"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_anon_comment_daily_limit_per_ip(offline):
|
||||
async with client() as c:
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
url = f"/v1/reaction/post/{post_id}/comment"
|
||||
ip = {"X-Forwarded-For": "203.0.113.40"}
|
||||
for i in range(20):
|
||||
assert (await c.post(url, headers=ip, json={"body": f"댓글{i}"})).json()["result"]["success"] is True
|
||||
assert (await c.post(url, headers=ip, json={"body": "하나 더"})).json()["result"]["desc"] == "DAILY_LIMIT"
|
||||
assert (await c.post(url, headers=IP_B, json={"body": "다른 사람"})).json()["result"]["success"] is True
|
||||
h = await _login(c, "anon_cmt_02")
|
||||
assert (await c.post(url, headers={**h, **ip}, json={"body": "로그인하면 따로"})).json()["result"]["success"] is True
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_hero_and_today_gak_take_likes_and_comments(offline):
|
||||
async with client() as c:
|
||||
feed = (await c.get("/v1/feed", params={"region": REGION})).json()
|
||||
hero, gak = feed["hero_post"]["post_id"], feed["gak_post"]["post_id"]
|
||||
assert hero != gak and {hero, gak}.isdisjoint(p["post_id"] for p in feed["posts"])
|
||||
assert (await c.post(f"/v1/reaction/post/{hero}/like", headers=IP_A)).json()["like_count"] == 1
|
||||
assert (await c.post(f"/v1/reaction/post/{gak}/comment", headers=IP_A, json={"body": "좋다"})).json()["result"]["success"] is True
|
||||
|
||||
mine = (await c.get("/v1/feed", params={"region": REGION}, headers=IP_A)).json()
|
||||
assert mine["hero_post"] == {"post_id": hero, "like_count": 1, "comment_count": 0, "liked": True}
|
||||
assert mine["gak_post"] == {"post_id": gak, "like_count": 0, "comment_count": 1, "liked": False}
|
||||
assert (await c.get("/v1/feed", params={"region": REGION}, headers=IP_B)).json()["hero_post"]["liked"] is False
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_hero_tomorrow_and_tomorrow_slots(offline):
|
||||
async with client() as c:
|
||||
hero = (await c.get("/v1/feed", params={"region": REGION})).json()["hero"]
|
||||
assert set(hero["tomorrow"]["weather_slots"]) <= {"morning", "day", "evening", "night"}
|
||||
res = (await c.get("/v1/weather/today", params={"region": REGION, "day": "tomorrow"})).json()
|
||||
assert res["day"] == hero["tomorrow"]["day"]
|
||||
@@ -50,11 +50,12 @@ async def test_signup_rejects_bad_input():
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_reactions_require_login_and_update_feed(offline):
|
||||
async def test_comment_without_login_is_anonymous_and_reactions_update_feed(offline):
|
||||
async with client() as c:
|
||||
feed = (await c.get("/v1/feed", params={"region": REGION})).json()
|
||||
post_id = feed["posts"][0]["post_id"]
|
||||
assert (await c.post(f"/v1/reaction/post/{post_id}/like")).status_code == 401
|
||||
anon = (await c.post(f"/v1/reaction/post/{feed['posts'][1]['post_id']}/comment", json={"body": "안녕"})).json()
|
||||
assert anon["result"]["success"] is True and anon["comment"]["nickname"] == "익명"
|
||||
|
||||
token = (await _signup(c))["access_token"]
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
|
||||
@@ -93,3 +93,52 @@ async def test_list_cards_newest_first_with_image_urls(offline, admin_key):
|
||||
first = res["items"][0]
|
||||
assert first["title"] == "둘째 카드" and first["status"] == CardStatus.PUBLISHED.value and first["post_id"] and len(first["image_urls"]) == 3
|
||||
assert res["items"][1]["status"] == CardStatus.WAITING.value and res["items"][1].get("published_at") is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_instagram_publish_carousel_and_store_media_id(offline, admin_key, monkeypatch):
|
||||
import httpx
|
||||
|
||||
from services.external import instagram
|
||||
|
||||
monkeypatch.setattr(settings, "instagram_access_token", "tok")
|
||||
monkeypatch.setattr(settings, "instagram_user_id", "1789")
|
||||
monkeypatch.setattr(settings, "public_base_url", "https://weather.example")
|
||||
calls: list[tuple[str, dict]] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
data = dict(httpx.QueryParams(request.content.decode())) if request.method == "POST" else dict(request.url.params)
|
||||
calls.append((request.url.path, data))
|
||||
assert data["access_token"] == "tok"
|
||||
if request.url.path.endswith("/1789/media"):
|
||||
if data.get("media_type") == "CAROUSEL":
|
||||
assert data["children"] == "c1,c2,c3" and data["caption"].startswith("오늘의 썸 타로")
|
||||
return httpx.Response(200, json={"id": "car"})
|
||||
assert data["image_url"].startswith("https://weather.example/v1/card/") and data["is_carousel_item"] == "true"
|
||||
return httpx.Response(200, json={"id": f"c{len([c for c in calls if 'is_carousel_item' in c[1]])}"})
|
||||
if request.url.path.endswith("/car"):
|
||||
return httpx.Response(200, json={"status_code": "FINISHED"})
|
||||
if request.url.path.endswith("/media_publish"):
|
||||
assert data["creation_id"] == "car"
|
||||
return httpx.Response(200, json={"id": "media99"})
|
||||
return httpx.Response(404, json={"error": {"message": "no"}})
|
||||
|
||||
real = httpx.AsyncClient
|
||||
monkeypatch.setattr(instagram.httpx, "AsyncClient", lambda **kw: real(transport=httpx.MockTransport(handler)))
|
||||
async with client() as c:
|
||||
made = (await c.post("/v1/card", json=body(publish=True), headers=admin_key)).json()
|
||||
res = (await c.post(f"/v1/card/{made['card_id']}/instagram", headers=admin_key)).json()
|
||||
again = (await c.post(f"/v1/card/{made['card_id']}/instagram", headers=admin_key)).json()
|
||||
listed = (await c.get("/v1/card", headers=admin_key)).json()["items"][0]
|
||||
assert res["result"]["success"] and res["ig_media_id"] == "media99"
|
||||
assert again["ig_media_id"] == "media99" and len([p for p, _ in calls if p.endswith("/media_publish")]) == 1
|
||||
assert listed["ig_media_id"] == "media99"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_instagram_requires_token(offline, admin_key, monkeypatch):
|
||||
monkeypatch.setattr(settings, "instagram_access_token", "")
|
||||
async with client() as c:
|
||||
made = (await c.post("/v1/card", json=body(), headers=admin_key)).json()
|
||||
res = (await c.post(f"/v1/card/{made['card_id']}/instagram", headers=admin_key)).json()
|
||||
assert res["result"]["success"] is False and "INSTAGRAM" in res["msg"]
|
||||
@@ -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)
|
||||
@@ -151,6 +156,27 @@ def test_arrange_orders_by_slot_and_keeps_same_types_apart():
|
||||
assert night[:3] == [PostType.ALERT, PostType.WEATHER, PostType.TOMORROW] and night[-1] is PostType.QUOTE
|
||||
|
||||
|
||||
def test_arrange_puts_shareable_cards_before_plain_info():
|
||||
"""주말·노을·행사는 앞쪽 절반, 공기·자외선·상식은 각 뒤로."""
|
||||
from datetime import datetime
|
||||
|
||||
from common.utils.kma_time import KST
|
||||
from services.feed_service import arrange
|
||||
|
||||
sunset = datetime(2026, 10, 1, 18, 10, tzinfo=KST)
|
||||
cards = [_card(t, n) for n, t in enumerate([
|
||||
PostType.WEATHER, PostType.ALERT, PostType.GAK, PostType.GAK, PostType.GAK, PostType.SUNSET, PostType.TOMORROW, PostType.WEEK,
|
||||
PostType.EVENT, PostType.EVENT, PostType.SEASON, PostType.TIP, PostType.QUOTE, PostType.WEEKEND_PLAN, PostType.AIR, PostType.UV, PostType.MOON,
|
||||
])]
|
||||
for slot, h in (("morning", 8), ("day", 13), ("evening", 17), ("evening", 19), ("night", 22)):
|
||||
out = [c.post_type for c in arrange(cards, slot, datetime(2026, 10, 1, h, tzinfo=KST), sunset, False, "2026-10-01:1114000000")]
|
||||
half = len(out) // 2
|
||||
assert PostType.SUNSET in out[:half] and PostType.WEEK in out[:half], (slot, out)
|
||||
assert all(i < half + 2 for i, t in enumerate(out) if t is PostType.EVENT), (slot, out)
|
||||
first_gak = out.index(PostType.GAK)
|
||||
assert all(out.index(t) > first_gak for t in (PostType.AIR, PostType.TIP) if t in out), (slot, out)
|
||||
|
||||
|
||||
def test_arrange_scatters_up_to_three_events_same_spot_all_day():
|
||||
from datetime import datetime
|
||||
|
||||
@@ -362,14 +388,14 @@ async def test_feed_has_day_trip_card_with_city_event(offline, monkeypatch):
|
||||
assert event["line"] == "강릉 커피축제" and event["image"] == "https://tong.visitkorea.or.kr/c.jpg"
|
||||
|
||||
|
||||
def test_gak_caption_starts_with_score_band_sentence():
|
||||
def test_gak_band_sentence_moves_to_slide_and_caption_keeps_hours():
|
||||
"""점수 구간 설명 문장은 슬라이드(say)에 두고, 글 설명엔 내일 점수나 하기 좋은 때만."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.feed_service import _gak_caption
|
||||
from services.feed_service import _band_sentence, _gak_caption
|
||||
d = SimpleNamespace(sentences={"0": "쉬어요", "30": "애매", "60": "괜찮아요", "80": "딱 좋아요!"}, windows=[{"from": 18, "to": 24}])
|
||||
item = SimpleNamespace(definition=d, score=SimpleNamespace(score=83, score_date=date(2026, 10, 7)), trend=[], rank=1)
|
||||
assert _gak_caption(item) == "딱 좋아요! 하기 좋은 때는 18~24시예요."
|
||||
item.definition.sentences = {}
|
||||
assert _band_sentence(d.sentences, 83) == "딱 좋아요!"
|
||||
assert _gak_caption(item) == "하기 좋은 때는 18~24시예요."
|
||||
|
||||
|
||||
@@ -389,3 +415,19 @@ def test_uv_post_only_when_moderate_or_higher():
|
||||
assert FeedService._uv_post(None, base, ctx([(12, 2.0), (15, 3.4)])).slides[0].line == "오늘 자외선 지수 보통\n오후 3시 무렵 나가면 선크림·모자 챙겨요"
|
||||
assert FeedService._uv_post(None, base, ctx([(9, 1.0), (12, 2.5)])) is None
|
||||
assert FeedService._uv_post(None, base, ctx([])) is None
|
||||
|
||||
|
||||
def test_gak_rows_shows_heaviest_conditions_with_short_values():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.feed_service import gak_rows
|
||||
|
||||
d = SimpleNamespace(weight_temp=30, weight_rain=25, weight_wind=10, weight_humidity=0, weight_air=15, weight_uv=0, weight_sun=0, weight_view=0, weight_time=20)
|
||||
notes = {"temp": "체감 18°, 편한 범위 15~25° 안", "rain": "비 확률 20%", "wind": "바람 초속 3.1m", "air": "초미세먼지 16㎍/㎥, 좋음", "time": "수요일"}
|
||||
item = SimpleNamespace(definition=d, score=SimpleNamespace(notes=notes))
|
||||
assert [(r.label, r.value) for r in gak_rows(item, 3)] == [("기온", "체감 18°"), ("비", "확률 20%"), ("미세먼지", "좋음")]
|
||||
# 점수에 안 쓰는 조건은 뒤에 지금 날씨로 채운다
|
||||
d.weight_wind = 0
|
||||
assert [r.label for r in gak_rows(item)] == ["기온", "비", "미세먼지", "바람"]
|
||||
item.score.notes = {**notes, "rain": "비 소식, 내일까지 비 확률 70%"}
|
||||
assert gak_rows(item)[1].value == "확률 70%"
|
||||
@@ -0,0 +1,80 @@
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from jose import jwk, jwt
|
||||
|
||||
import common.google_id as google_id
|
||||
import services.auth_service as auth_service
|
||||
from config.settings import settings
|
||||
from router.router import app
|
||||
|
||||
CLIENT_ID = "test-client.apps.googleusercontent.com"
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def google_keys(monkeypatch):
|
||||
"""가짜 구글 서명키. 공개키는 _keys 대신 돌려준다."""
|
||||
monkeypatch.setattr(settings, "google_client_id", CLIENT_ID)
|
||||
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
|
||||
public = jwk.construct(key.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo), "RS256").to_dict()
|
||||
public["kid"] = "k1"
|
||||
|
||||
async def keys(force: bool = False):
|
||||
return [public]
|
||||
|
||||
monkeypatch.setattr(google_id, "_keys", keys)
|
||||
|
||||
def sign(**over):
|
||||
claims = {"iss": "https://accounts.google.com", "aud": CLIENT_ID, "sub": "1234567890", "exp": int(time.time()) + 600, "iat": int(time.time()), "name": "홍길동", "email": "a@example.com"}
|
||||
claims.update(over)
|
||||
return jwt.encode(claims, pem, algorithm="RS256", headers={"kid": "k1"})
|
||||
|
||||
return sign
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_verify_accepts_only_our_valid_tokens(google_keys):
|
||||
assert await google_id.verify(google_keys()) == "1234567890"
|
||||
assert await google_id.verify(google_keys(aud="other.apps.googleusercontent.com")) is None
|
||||
assert await google_id.verify(google_keys(iss="https://evil.example")) is None
|
||||
assert await google_id.verify(google_keys(exp=int(time.time()) - 10)) is None
|
||||
assert await google_id.verify(google_keys()[:-4] + "abcd") is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_google_login_creates_once_with_auto_nickname_and_no_real_name(google_keys):
|
||||
async with client() as c:
|
||||
first = (await c.post("/v1/auth/google", json={"credential": google_keys()})).json()
|
||||
assert first["access_token"] and first["me"]["provider"] == 2
|
||||
nick = first["me"]["nickname"]
|
||||
assert "홍길동" not in nick and "@" not in nick
|
||||
again = (await c.post("/v1/auth/google", json={"credential": google_keys()})).json()
|
||||
assert again["me"]["nickname"] == nick and again["me"]["login_id"] == first["me"]["login_id"]
|
||||
other = (await c.post("/v1/auth/google", json={"credential": google_keys(sub="999")})).json()
|
||||
assert other["me"]["login_id"] != first["me"]["login_id"]
|
||||
bad = (await c.post("/v1/auth/google", json={"credential": google_keys(aud="x")})).json()
|
||||
assert bad["result"]["desc"] == "AUTH_FAILED"
|
||||
me = (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {first['access_token']}"})).json()["me"]
|
||||
assert me["nickname"] == nick
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_config_exposes_client_id_only_when_set(monkeypatch):
|
||||
async with client() as c:
|
||||
monkeypatch.setattr(settings, "google_client_id", "")
|
||||
assert "google_client_id" not in (await c.get("/v1/auth/config")).json()
|
||||
monkeypatch.setattr(settings, "google_client_id", CLIENT_ID)
|
||||
assert (await c.get("/v1/auth/config")).json()["google_client_id"] == CLIENT_ID
|
||||
|
||||
|
||||
def test_auto_nickname_fits_nickname_rule():
|
||||
for _ in range(50):
|
||||
assert auth_service.NICKNAME.match(auth_service.auto_nickname())
|
||||
@@ -60,10 +60,9 @@ def test_status_line_has_four_by_day_and_warns_only_caution():
|
||||
assert _status(x) == [("습도", "습함", "normal"), ("불쾌지수", "쾌적", "normal"), ("자외선", "높음", "warn"), ("미세먼지", "나쁨", "warn")]
|
||||
|
||||
|
||||
def test_status_line_shows_discomfort_only_june_to_september():
|
||||
"""불쾌지수는 더위 지표라 10월 비 오는 날에도 '쾌적'이 나온다. 기상청처럼 6~9월에만."""
|
||||
def test_status_line_shows_discomfort_all_year():
|
||||
x = HeroInput(now=NOW, night=False, humidity=95, discomfort=66, uv=1.0, air=AirGrade.GOOD)
|
||||
assert [s.label for s in hero_status(x)] == ["습도", "자외선", "미세먼지"]
|
||||
assert [s.label for s in hero_status(x)] == ["습도", "불쾌지수", "자외선", "미세먼지"]
|
||||
|
||||
|
||||
def test_status_line_drops_uv_at_night_and_missing_values():
|
||||
|
||||
@@ -8,15 +8,18 @@ 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
|
||||
from crud.weather_crud import WeatherCRUD
|
||||
from router.router import app
|
||||
from services.calc.index_calc import rank_score
|
||||
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"
|
||||
|
||||
|
||||
@@ -24,6 +27,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,14 +72,17 @@ 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"]]
|
||||
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 and i["in_season"]]
|
||||
assert weighted == sorted(weighted, reverse=True)
|
||||
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)]
|
||||
@@ -139,10 +153,10 @@ 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})))
|
||||
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]
|
||||
# 점수가 가장 높아도 제철이 아니면 순위 밖 맨 끝. 계절 표시는 제철 달이 정해진 각에만
|
||||
@@ -152,41 +166,71 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
|
||||
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 = [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))]
|
||||
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, {"morning": 50, "day": 50, "evening": 50, "night": 50, "early": 50})))
|
||||
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
|
||||
# 하 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)]
|
||||
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_with_priority_weight(monkeypatch):
|
||||
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 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)
|
||||
monkeypatch.setattr(service, "ensure", lambda *a: _async((ErrorType.SUCCESS, {k: 50 for k in every})))
|
||||
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) > 상 20(20). 낮: 상 70(70) > 하 90(63). 상은 밤 구간이 없어 밤 순위도 없다
|
||||
# 하 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 "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, {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):
|
||||
|
||||
@@ -9,7 +9,7 @@ import pytest
|
||||
from common.enums import RainType, Sky
|
||||
from services.calc.index_calc import (
|
||||
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,
|
||||
priority_score, rank_score, uv_score, view_score, zero_rules_text,
|
||||
)
|
||||
from services.calc.moon import illumination
|
||||
|
||||
@@ -38,6 +38,36 @@ def test_perfect_evening_scores_100():
|
||||
assert r.notes["temp"] == "체감 21°, 편한 범위 18~24° 안"
|
||||
|
||||
|
||||
def test_rank_and_display_share_priority_adjusted_screenshot_scores():
|
||||
items = [(83, 1), (82, 1), (80, 1), (91, 2), (77, 1), (77, 1), (76, 1), (89, 2), (87, 2)]
|
||||
shown = [(priority_score(score, priority), priority) for score, priority in items]
|
||||
ranked = sorted(shown, key=lambda item: rank_score(*item), reverse=True)
|
||||
assert [score for score, _ in ranked] == [83, 82, 80, 77, 77, 77, 76, 76, 74]
|
||||
assert priority_score(91, 2) == 77
|
||||
assert priority_score(89, 2) == 76
|
||||
|
||||
|
||||
def test_rank_uses_priority_only_to_break_ties():
|
||||
items = [(80, 3), (80, 1), (81, 3), (80, 2)]
|
||||
assert sorted(items, key=lambda item: rank_score(*item), reverse=True) == [(81, 3), (80, 1), (80, 2), (80, 3)]
|
||||
|
||||
|
||||
@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
|
||||
|
||||
@@ -275,6 +305,28 @@ def test_seasonal_gak_good_day_high_bad_day_low(code, good, bad):
|
||||
assert _seed_score(code, **bad) <= 30
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code, good, bad", [
|
||||
("hangang", dict(feels=20.0, wind=1.5, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
|
||||
("themepark", dict(day=_WED, feels=20.0, wind=2.0), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
|
||||
("date", dict(feels=20.0, wind=1.5), dict(feels=5.0, prob=90, rain=RainType.RAIN, pm25=60)),
|
||||
("frizz", dict(feels=28.0, prob=90, rain=RainType.RAIN, hum=90), dict(feels=12.0, hum=35)),
|
||||
("boiler", dict(feels=2.0, hum=85, prob=60), dict(feels=22.0, hum=40)),
|
||||
("sunscreen", dict(feels=26.0, uv=8.0), dict(feels=8.0, uv=0.5)),
|
||||
("mosquito", dict(feels=27.0, hum=85, wind=0.5), dict(feels=15.0, hum=40, wind=6.0)),
|
||||
("tennis", dict(feels=18.0, wind=1.0, hum=45), dict(feels=18.0, prob=80, rain=RainType.RAIN)),
|
||||
("hyodo", dict(feels=20.0, wind=1.5), dict(feels=20.0, prob=80, rain=RainType.RAIN)),
|
||||
("thanks", dict(feels=0.0, prob=90, rain=RainType.RAIN), dict(feels=20.0)),
|
||||
("gift", dict(feels=17.0, wind=1.5), dict(feels=17.0, prob=80, rain=RainType.RAIN)),
|
||||
("party", dict(feels=3.0, prob=90, rain=RainType.RAIN), dict(day=_WED, feels=20.0)),
|
||||
("game", dict(feels=3.0, prob=90, rain=RainType.RAIN, pm25=70), dict(day=_WED, feels=20.0)),
|
||||
("selfie", dict(wind=1.0, hum=35, sunshine_ratio=0.8), dict(prob=90, rain=RainType.RAIN, hum=90, wind=8.0, sunshine_ratio=0.0)),
|
||||
("sentimental", dict(feels=13.0, prob=90, rain=RainType.RAIN, wind=3.0, hum=85), dict(feels=28.0, hum=40, wind=0.5)),
|
||||
])
|
||||
def test_trend_and_mood_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
|
||||
@@ -318,3 +370,14 @@ def test_umbrella_lost_needs_rain_that_stopped():
|
||||
assert evaluate(defn, [[_h(13), _h(14)]], after_rain).score >= 80
|
||||
assert evaluate(defn, [[_h(13), _h(14)]], CTX).zero_reason == "앞서 내린 비가 없어 0점"
|
||||
assert evaluate(defn, [[_h(10, rain=RainType.RAIN)]], replace(CTX, rain_hours=frozenset({9, 10}))).score == 0
|
||||
|
||||
|
||||
def test_weather_why_lists_every_condition_heaviest_first():
|
||||
from services.index_service import WEATHER_SCORE_DEF, weather_why
|
||||
|
||||
ctx = Context(day=date(2026, 10, 2), is_holiday=False, pm25=12, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
r = evaluate(WEATHER_SCORE_DEF, [[_h(h, feels=19.0, prob=0, wind=2.0, hum=55, sunshine_ratio=0.9) for h in range(9, 22)]], ctx)
|
||||
why = weather_why(r)
|
||||
assert [w.label for w in why] == ["기온", "비", "햇볕", "바람", "습도", "미세먼지"]
|
||||
assert sum(w.weight for w in why) == 100
|
||||
assert why[0].note.startswith("체감 19°")
|
||||
@@ -0,0 +1,119 @@
|
||||
import json
|
||||
import os
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from common.enums import RainType, Sky
|
||||
from router.router import app
|
||||
from router.v1.my_gak.protocol import MyGakRule
|
||||
from services.calc.index_calc import Context, Hour, evaluate
|
||||
from services.calc.my_gak_calc import MyRule, axes, definition, preset
|
||||
from services.my_gak_service import MAX_PER_USER, gak_name
|
||||
|
||||
RULE = {"temp": [15, 25], "rain": "dry", "slots": ["evening", "night"]}
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": "조건토끼"})).json()
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
def _hours(feels: float, rain: RainType = RainType.NONE, prob: int = 0, wind: float = 1.0, humidity: int = 50) -> list[Hour]:
|
||||
return [Hour(hour=h, feels_c=feels, rain_type=rain, rain_prob=prob, wind_ms=wind, humidity=humidity, sky=Sky.CLEAR) for h in (19, 20, 21)]
|
||||
|
||||
|
||||
def _score(rule: MyRule, hours: list[Hour], pm25: int | None = 10) -> int:
|
||||
ctx = Context(day=date(2026, 10, 20), is_holiday=False, pm25=pm25, air_label=None, moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
return evaluate(definition(rule), [hours], ctx).score
|
||||
|
||||
|
||||
def test_name_gets_gak_suffix_and_rejects_links_and_numbers():
|
||||
assert gak_name(" 소맥 ") == "소맥각"
|
||||
assert gak_name("야독각") == "야독각"
|
||||
assert gak_name("naver.com") is None
|
||||
assert gak_name("01012345678") is None
|
||||
assert gak_name("가" * 12) is None
|
||||
|
||||
|
||||
def test_only_chosen_conditions_count_and_score_falls_with_distance():
|
||||
rule = MyRule(temp=(15, 25), rain="dry")
|
||||
assert axes(rule) == ["temp", "rain"]
|
||||
inside = _score(rule, _hours(20))
|
||||
near = _score(rule, _hours(27))
|
||||
far = _score(rule, _hours(33))
|
||||
assert inside >= 90 and inside > near > far
|
||||
# 고르지 않은 바람·습도는 아무리 나빠도 점수에 안 들어간다
|
||||
assert _score(rule, _hours(20, wind=15, humidity=95)) == inside
|
||||
|
||||
|
||||
def test_dry_rule_caps_when_raining_and_wet_rule_likes_rain():
|
||||
assert _score(MyRule(rain="dry"), _hours(20, RainType.RAIN, 90)) <= 20
|
||||
assert _score(MyRule(rain="wet"), _hours(20, RainType.RAIN, 90)) >= 90
|
||||
|
||||
|
||||
def test_wind_and_air_limits():
|
||||
assert _score(MyRule(wind_max=4), _hours(20, wind=2)) > _score(MyRule(wind_max=4), _hours(20, wind=9))
|
||||
assert _score(MyRule(air="good"), _hours(20), pm25=10) > _score(MyRule(air="good"), _hours(20), pm25=40)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_add_list_delete_and_limits():
|
||||
async with client() as c:
|
||||
assert (await c.post("/v1/my-gak", json={"name": "소맥", "rule": RULE})).status_code == 401
|
||||
h = await _login(c, "rule_01")
|
||||
assert (await c.get("/v1/my-gak")).json()["items"] == []
|
||||
item = (await c.post("/v1/my-gak", json={"name": "소맥", "rule": RULE}, headers=h)).json()["item"]
|
||||
assert item["name"] == "소맥각" and item["rule"]["temp"] == [15, 25] and item["rule"]["slots"] == ["evening", "night"]
|
||||
assert [g["my_gak_id"] for g in (await c.get("/v1/my-gak", headers=h)).json()["items"]] == [item["my_gak_id"]]
|
||||
assert (await c.delete(f"/v1/my-gak/{item['my_gak_id']}", headers=h)).json()["result"]["success"] is True
|
||||
assert (await c.delete(f"/v1/my-gak/{item['my_gak_id']}", headers=h)).json()["result"]["desc"] == "NOT_FOUND"
|
||||
for i in range(MAX_PER_USER):
|
||||
assert (await c.post("/v1/my-gak", json={"name": f"각{chr(0xAC00 + i)}", "rule": RULE}, headers=h)).json()["item"]
|
||||
assert (await c.post("/v1/my-gak", json={"name": "하나더", "rule": RULE}, headers=h)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_rejects_bad_rules():
|
||||
async with client() as c:
|
||||
h = await _login(c, "rule_02")
|
||||
bad = lambda rule: c.post("/v1/my-gak", json={"name": "야독", "rule": rule}, headers=h) # noqa: E731
|
||||
assert (await bad({})).status_code == 422
|
||||
assert (await bad({"temp": [25, 15]})).status_code == 422
|
||||
assert (await bad({"temp": [15, 25], "slots": []})).status_code == 422
|
||||
assert (await bad({"humidity": [10, 120]})).status_code == 422
|
||||
|
||||
|
||||
def _defn(rules: dict, windows: list[dict], **weights) -> SimpleNamespace:
|
||||
w = {"temp": 30, "rain": 30, "wind": 0, "humidity": 0, "air": 0} | weights
|
||||
return SimpleNamespace(factor_rules=rules, windows=windows, **{f"weight_{k}": v for k, v in w.items()})
|
||||
|
||||
|
||||
def test_preset_copies_rules_that_fit_and_drops_the_rest():
|
||||
base = {"rain": {"dir": "dry"}, "wind": {"type": "calm", "ok": 3, "limit": 10}, "humidity": {"type": "range", "lo": 30, "hi": 60}}
|
||||
p = preset(_defn(base | {"temp": {"type": "range", "lo": 18, "hi": 24}}, [{"from": 18, "to": 24}], wind=15, humidity=10, air=10))
|
||||
assert p == {"slots": ["evening", "night"], "temp": [18, 24], "rain": "dry", "wind_max": 3, "air": "normal", "humidity": [30, 60]}
|
||||
# 더울수록·추울수록은 만점 기온부터 끝까지, 산 정상 보정은 되돌린다
|
||||
assert preset(_defn(base | {"temp": {"type": "higher", "zero": 16, "full": 27}}, [{"from": 9, "to": 11}]))["temp"] == [27, 40]
|
||||
assert preset(_defn(base | {"temp": {"type": "lower", "zero": 10, "full": -5}}, [{"from": 9, "to": 11}]))["temp"] == [-20, -5]
|
||||
assert preset(_defn(base | {"temp": {"type": "range", "lo": 10, "hi": 20, "offset": -4}}, [{"from": 9, "to": 11}]))["temp"] == [14, 24]
|
||||
# 범위에서 멀수록 좋은 기온, 탁할수록 좋은 미세먼지, 비중 0인 바람은 옮기지 않는다
|
||||
p = preset(_defn(base | {"temp": {"type": "away", "lo": 15, "hi": 24}, "air": {"zero": 15, "full": 75}}, [{"around": "sunset", "hours": 1}], air=20))
|
||||
assert p == {"slots": ["evening"], "rain": "dry"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_presets_cover_every_gak_with_valid_rules():
|
||||
async with client() as c:
|
||||
body = (await c.get("/v1/my-gak/presets")).json()
|
||||
with open(os.path.join(os.path.dirname(os.path.dirname(__file__)), "seed", "index_definition.json"), encoding="utf-8") as f:
|
||||
seed = json.load(f)
|
||||
assert [x["code"] for x in body["items"]] == [x["code"] for x in sorted(seed, key=lambda x: x["sort_order"])]
|
||||
for x in body["items"]:
|
||||
MyGakRule(**x["rule"])
|
||||
@@ -0,0 +1,58 @@
|
||||
from common.enums import RainType, Sky
|
||||
from services.calc.index_calc import Hour, Outing, outing
|
||||
from services.weekend_rank import OUTING_SCORE_TABLE, TRIP_MIN_SCORE, calibrated_outing, outing_day_score
|
||||
|
||||
|
||||
def test_table_is_a_monotonic_0_to_100_lookup():
|
||||
assert len(OUTING_SCORE_TABLE) == 101
|
||||
assert all(0 <= v <= 100 for v in OUTING_SCORE_TABLE)
|
||||
assert all(a <= b for a, b in zip(OUTING_SCORE_TABLE, OUTING_SCORE_TABLE[1:]))
|
||||
assert OUTING_SCORE_TABLE[0] < OUTING_SCORE_TABLE[100] == 100
|
||||
|
||||
|
||||
def test_table_makes_top_scores_rare_and_centers_60():
|
||||
"""원래 점수가 높을수록 표시 점수가 오르되, 90점 이상으로 가는 원래 점수는 위쪽 일부뿐."""
|
||||
assert any(55 <= v <= 65 for v in OUTING_SCORE_TABLE)
|
||||
assert sum(v >= 90 for v in OUTING_SCORE_TABLE) <= 15
|
||||
# 맑고 알맞은 날(원래 100)과 조금 못 미치는 날(원래 97)이 모두 100점으로 몰리지 않는다
|
||||
assert calibrated_outing(95) < 100
|
||||
|
||||
|
||||
def test_calibrated_outing_reads_the_table():
|
||||
assert calibrated_outing(70) == OUTING_SCORE_TABLE[70]
|
||||
assert calibrated_outing(0) == OUTING_SCORE_TABLE[0]
|
||||
|
||||
|
||||
def test_day_score_uses_calibrated_value_for_hourly_and_estimated_results():
|
||||
for estimated in (False, True):
|
||||
r = Outing(score=80, factors={}, notes={}, reason="비 0% · 체감 21° · 맑음", capped=False, estimated=estimated)
|
||||
assert outing_day_score(r) == OUTING_SCORE_TABLE[80]
|
||||
|
||||
|
||||
def test_trip_min_score_keeps_the_same_weather_quality():
|
||||
"""당일치기 최소 기준은 원래 점수 50과 같은 날씨 수준을 표시 점수로 옮긴 값."""
|
||||
assert TRIP_MIN_SCORE == calibrated_outing(50)
|
||||
# 표는 가까운 원래 점수끼리 같은 값이 될 수 있어, 눈에 띄게 낮은 날은 빠지고 높은 날은 들어가는지만 본다
|
||||
assert calibrated_outing(45) < TRIP_MIN_SCORE <= calibrated_outing(55)
|
||||
|
||||
|
||||
def _day(feels: float = 21.0, wind: float = 0.5, prob: int = 0, sky: Sky = Sky.CLEAR) -> list[Hour]:
|
||||
return [Hour(hour=h, feels_c=feels, rain_type=RainType.NONE, rain_prob=prob, wind_ms=wind, humidity=50, sky=sky) for h in range(10, 18)]
|
||||
|
||||
|
||||
def test_outing_100_needs_exact_temperature_and_very_calm_wind():
|
||||
"""맑고 비 없는 날도 체감 21° 근처(±0.5°)·바람 초속 1m 이하여야 100점. 그래야 같은 예보의 여러 지역이 한꺼번에 100점이 되지 않는다."""
|
||||
assert outing(_day()).score == 100
|
||||
assert outing(_day(feels=21.4)).factors["temp"] == 100
|
||||
assert outing(_day(feels=22.3)).factors["temp"] < 100
|
||||
assert outing(_day(wind=1.0)).factors["wind"] == 100
|
||||
assert outing(_day(wind=1.8)).factors["wind"] < 95
|
||||
assert outing(_day(wind=1.2)).score > outing(_day(wind=1.8)).score > outing(_day(wind=2.0)).score
|
||||
|
||||
|
||||
def test_100_only_for_a_perfect_original_score_and_top_scores_stay_distinct():
|
||||
"""맨 위가 100으로 잘려 원래 96·97·99가 모두 100점이 되던 것을 막는다: 100점은 원래 100뿐, 그 아래는 서로 다른 점수."""
|
||||
assert OUTING_SCORE_TABLE[100] == 100
|
||||
assert OUTING_SCORE_TABLE[99] < 100
|
||||
top = OUTING_SCORE_TABLE[90:]
|
||||
assert all(a < b for a, b in zip(top, top[1:]))
|
||||
@@ -7,7 +7,7 @@ from common.utils.kma_time import KST
|
||||
from common.database.model.models import WeatherHourly
|
||||
from router.router import app
|
||||
from router.v1.feed.protocol import Bands, Hero, HeroStat, Res_Feed, TopIndex
|
||||
from services.seo_service import SeoService, day_summary, fill, today_line
|
||||
from services.seo_service import SeoService, day_summary, fill, today_line, tomorrow_line
|
||||
|
||||
REGION = "1114000000"
|
||||
TEMPLATE = (
|
||||
@@ -76,3 +76,25 @@ async def test_gu_page_of_city_has_its_own_address(offline, monkeypatch):
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
page = await client.get("/v1/seo/today/gyeonggi/seongnam/bundang")
|
||||
assert page.status_code == 200 and "지금 20°" in page.text
|
||||
|
||||
|
||||
def test_tomorrow_line_has_day_and_sunset():
|
||||
line = tomorrow_line([_hour(12, 19.5, prob=10)], datetime(2026, 10, 15, 17, 51, tzinfo=KST))
|
||||
assert line == "최저 20°·최고 20°, 강수확률 10%, 맑음. 해 지는 시각 오후 5시 51분."
|
||||
assert tomorrow_line([], datetime(2026, 10, 15, 17, 51, tzinfo=KST)) == ""
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_tomorrow_page_fills_tomorrow_forecast(offline, monkeypatch):
|
||||
tmpl = TEMPLATE.replace("오늘 날씨", "내일 날씨")
|
||||
|
||||
async def template(self, path):
|
||||
return tmpl if path == "tomorrow/gyeonggi/seongnam/bundang" else None
|
||||
|
||||
monkeypatch.setattr(SeoService, "template", template)
|
||||
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
||||
page = await client.get("/v1/seo/tomorrow/gyeonggi/seongnam/bundang")
|
||||
missing = await client.get("/v1/seo/tomorrow/seoul/nowhere")
|
||||
assert page.status_code == 200 and "<h1>서울 중구 내일 날씨, 뭐 할까?</h1><p>최저 " in page.text
|
||||
assert "지금 " not in page.text and "<ol>" not in page.text
|
||||
assert missing.status_code == 404
|
||||
@@ -0,0 +1,193 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from router.router import app
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from services.talk_service import DAILY_MAX, GROUP_MAX, HIDE_AT, parse_cursor, pick_group, spread_authors, weather_line
|
||||
|
||||
REGION = "1144000000"
|
||||
BUSAN = "2611000000"
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
async def _write(c, h, body="망원동 하늘 진짜 맑아요", region=REGION):
|
||||
return (await c.post("/v1/talk", json={"region_code": region, "body": body}, headers=h)).json()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_write_list_like_delete():
|
||||
async with client() as c:
|
||||
assert (await c.post("/v1/talk", json={"region_code": REGION, "body": "안녕"})).status_code == 401
|
||||
h = await _login(c, "talk_01")
|
||||
t = (await _write(c, h, " 바람 많이 불어요 "))["talk"]
|
||||
assert t["body"] == "바람 많이 불어요" and t["mine"] is True and t["region_name"]
|
||||
|
||||
anon = (await c.get("/v1/talk/list")).json()["talks"]
|
||||
mine = next(x for x in anon if x["talk_id"] == t["talk_id"])
|
||||
assert mine["mine"] is False and mine["nickname"] == "talk_01"
|
||||
|
||||
liked = (await c.post(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()
|
||||
assert liked["liked"] is True and liked["like_count"] == 1
|
||||
assert (await c.post(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()["like_count"] == 1
|
||||
assert (await c.delete(f"/v1/talk/{t['talk_id']}/like", headers=h)).json()["like_count"] == 0
|
||||
|
||||
other = await _login(c, "talk_02")
|
||||
assert (await c.delete(f"/v1/talk/{t['talk_id']}", headers=other)).json()["result"]["desc"] == "NOT_FOUND"
|
||||
assert (await c.delete(f"/v1/talk/{t['talk_id']}", headers=h)).json()["result"]["success"] is True
|
||||
assert t["talk_id"] not in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_rejects_links_phone_long_and_daily_limit():
|
||||
async with client() as c:
|
||||
h = await _login(c, "talk_03")
|
||||
assert (await _write(c, h, "여기 보세요 https://spam.example"))["result"]["desc"] == "LINK_NOT_ALLOWED"
|
||||
assert (await _write(c, h, "연락 주세요 010-1234-5678"))["result"]["desc"] == "LINK_NOT_ALLOWED"
|
||||
assert (await _write(c, h, "가" * 101))["result"]["desc"] == "INVALID_INPUT"
|
||||
bad_region = (await c.post("/v1/talk", json={"region_code": "0000000000", "body": "안녕"}, headers=h)).json()
|
||||
assert bad_region["result"]["desc"] == "INVALID_INPUT"
|
||||
for i in range(DAILY_MAX):
|
||||
assert (await _write(c, h, f"오늘 {i}번째"))["talk"]
|
||||
assert (await _write(c, h))["result"]["desc"] == "DAILY_LIMIT"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_reports_hide_and_block_hides_author():
|
||||
async with client() as c:
|
||||
author = await _login(c, "talk_04")
|
||||
t = (await _write(c, author))["talk"]
|
||||
assert (await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 1}, headers=author)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
|
||||
viewer = await _login(c, "talk_05")
|
||||
assert (await c.post(f"/v1/talk/{t['talk_id']}/block", headers=viewer)).json()["result"]["success"] is True
|
||||
seen = [x["talk_id"] for x in (await c.get("/v1/talk/list", headers=viewer)).json()["talks"]]
|
||||
assert t["talk_id"] not in seen
|
||||
assert t["talk_id"] in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
|
||||
|
||||
for i in range(HIDE_AT):
|
||||
h = await _login(c, f"talk_r{i}")
|
||||
await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 2}, headers=h)
|
||||
await c.post(f"/v1/talk/{t['talk_id']}/report", json={"reason": 2}, headers=h)
|
||||
assert t["talk_id"] not in [x["talk_id"] for x in (await c.get("/v1/talk/list")).json()["talks"]]
|
||||
|
||||
|
||||
def test_weather_line():
|
||||
class Row:
|
||||
temp_c, sky, rain_type = 18.4, 1, 1
|
||||
|
||||
class Wet:
|
||||
temp_c, sky, rain_type = 11.6, 3, 2
|
||||
|
||||
assert weather_line(Row()) == "18° 맑음"
|
||||
assert weather_line(Wet()) == "12° 비"
|
||||
assert weather_line(None) is None
|
||||
|
||||
|
||||
def _ids(body: dict) -> list[int]:
|
||||
return [x["talk_id"] for x in body["talks"]]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_same_sido_talks_come_first_for_that_viewer():
|
||||
async with client() as c:
|
||||
busan = (await _write(c, await _login(c, "talk_bs1"), "광안리 바람 시원해요", BUSAN))["talk"]["talk_id"]
|
||||
seoul = (await _write(c, await _login(c, "talk_se1"), "망원동 비 그쳤어요"))["talk"]["talk_id"]
|
||||
nation = _ids((await c.get("/v1/talk/list")).json())
|
||||
local = _ids((await c.get("/v1/talk/list", params={"region": BUSAN})).json())
|
||||
assert nation.index(seoul) < nation.index(busan)
|
||||
assert local.index(busan) < local.index(seoul)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_pages_follow_cursor_without_repeats():
|
||||
async with client() as c:
|
||||
mine = []
|
||||
for i in range(5):
|
||||
h = await _login(c, f"talk_pg{i}")
|
||||
for j in range(DAILY_MAX):
|
||||
mine.append((await _write(c, h, f"페이지 글 {i}-{j}", BUSAN if j % 2 else REGION))["talk"]["talk_id"])
|
||||
seen, cursor = [], None
|
||||
while True:
|
||||
body = (await c.get("/v1/talk/list", params={"region": BUSAN} | ({"cursor": cursor} if cursor else {}))).json()
|
||||
seen += _ids(body)
|
||||
cursor = body.get("next_cursor")
|
||||
if not cursor:
|
||||
break
|
||||
assert (await c.get("/v1/talk/list", params={"cursor": "abc"})).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
assert len(seen) == len(set(seen)) and set(mine) <= set(seen)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mine_lists_only_my_talks_newest_first():
|
||||
async with client() as c:
|
||||
assert (await c.get("/v1/talk/mine")).status_code == 401
|
||||
h = await _login(c, "talk_mine")
|
||||
ids = [(await _write(c, h, f"내 글 {i}"))["talk"]["talk_id"] for i in range(3)]
|
||||
await _write(c, await _login(c, "talk_notmine"), "남의 글")
|
||||
await c.delete(f"/v1/talk/{ids[0]}", headers=h)
|
||||
body = (await c.get("/v1/talk/mine", headers=h)).json()
|
||||
assert _ids(body) == [ids[2], ids[1]] and all(x["mine"] for x in body["talks"])
|
||||
|
||||
|
||||
def test_spread_authors_and_cursor():
|
||||
v = lambda who: SimpleNamespace(author=SimpleNamespace(user_id=who)) # noqa: E731
|
||||
assert [x.author.user_id for x in spread_authors([v("a"), v("a"), v("a"), v("b"), v("c")])] == ["a", "b", "a", "c", "a"]
|
||||
assert parse_cursor("1760000000_42") == (1760000000, 42)
|
||||
assert parse_cursor("12") is None and parse_cursor("x_1") is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_topic_is_saved_and_filters_list():
|
||||
async with client() as c:
|
||||
h = await _login(c, "talk_tp1")
|
||||
sky = (await c.post("/v1/talk", json={"region_code": REGION, "body": "노을 분홍빛", "topic": 2}, headers=h)).json()["talk"]
|
||||
plain = (await _write(c, h, "그냥 동네 이야기"))["talk"]
|
||||
assert sky["topic"] == 2 and plain["topic"] == 1
|
||||
only_sky = _ids((await c.get("/v1/talk/list", params={"topic": 2})).json())
|
||||
only_foliage = _ids((await c.get("/v1/talk/list", params={"topic": 4})).json())
|
||||
assert sky["talk_id"] in only_sky and plain["talk_id"] not in only_sky
|
||||
assert sky["talk_id"] not in only_foliage
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_groups_have_near_group_and_topic_group_from_three_people():
|
||||
async with client() as c:
|
||||
for i in range(3):
|
||||
h = await _login(c, f"talk_gr{i}")
|
||||
for j in range(2):
|
||||
await c.post("/v1/talk", json={"region_code": REGION, "body": f"단풍 물들었어요 {i}-{j}", "topic": 4}, headers=h)
|
||||
groups = {g["topic"]: g["talks"] for g in (await c.get("/v1/talk/groups", params={"region": REGION})).json()["groups"]}
|
||||
assert 0 in groups and 4 in groups
|
||||
assert all(t["topic"] == 4 for t in groups[4])
|
||||
for talks in groups.values():
|
||||
names = [t["nickname"] for t in talks]
|
||||
assert len(names) == len(set(names)) and len(talks) <= GROUP_MAX
|
||||
|
||||
|
||||
def _view(talk_id, user, region, hours_ago, likes=0, reports=0):
|
||||
now = datetime(2026, 10, 23, 12, tzinfo=timezone.utc)
|
||||
talk = SimpleNamespace(talk_id=talk_id, region_code=region, created_at=now - timedelta(hours=hours_ago), like_count=likes, report_count=reports)
|
||||
return SimpleNamespace(talk=talk, author=SimpleNamespace(user_id=user))
|
||||
|
||||
|
||||
def test_pick_group_orders_near_fresh_first_one_per_person_clean_first():
|
||||
now = datetime(2026, 10, 23, 12, tzinfo=timezone.utc)
|
||||
far = _view(1, "a", BUSAN, 1)
|
||||
same_sido = _view(2, "b", "1111000000", 1)
|
||||
same_gu = _view(3, "c", REGION, 1)
|
||||
old_popular = _view(4, "d", REGION, 30, likes=50)
|
||||
again = _view(5, "c", REGION, 0)
|
||||
assert [v.talk.talk_id for v in pick_group([far, same_sido, same_gu, old_popular, again], REGION, now)] == [5, 2, 1, 4]
|
||||
reported = _view(6, "e", REGION, 0, reports=1)
|
||||
assert pick_group([reported, far], REGION, now)[0].talk.talk_id == 1
|
||||
@@ -0,0 +1,59 @@
|
||||
import io
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from PIL import Image
|
||||
|
||||
from router.router import app
|
||||
|
||||
REGION = "1144000000"
|
||||
GPS_IFD = 0x8825
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _login(c, login_id: str) -> dict:
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json()
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
def _jpeg_with_gps(w: int = 2400, h: int = 1600) -> bytes:
|
||||
exif = Image.Exif()
|
||||
exif[0x010F] = "PhoneMaker"
|
||||
exif[GPS_IFD] = {1: "N", 2: (37.0, 33.0, 0.0), 3: "E", 4: (126.0, 58.0, 0.0)}
|
||||
buf = io.BytesIO()
|
||||
Image.new("RGB", (w, h), (120, 180, 230)).save(buf, "JPEG", exif=exif)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_upload_strips_location_resizes_and_attaches_to_talk():
|
||||
src = _jpeg_with_gps()
|
||||
assert Image.open(io.BytesIO(src)).getexif().get_ifd(GPS_IFD)
|
||||
async with client() as c:
|
||||
assert (await c.post("/v1/talk/image", files={"file": ("a.jpg", src, "image/jpeg")})).status_code == 401
|
||||
h = await _login(c, "photo_01")
|
||||
url = (await c.post("/v1/talk/image", files={"file": ("a.jpg", src, "image/jpeg")}, headers=h)).json()["image"]
|
||||
got = await c.get(url)
|
||||
assert got.status_code == 200 and got.headers["content-type"] == "image/webp"
|
||||
img = Image.open(io.BytesIO(got.content))
|
||||
assert max(img.size) == 1080
|
||||
assert not img.getexif()
|
||||
talk = (await c.post("/v1/talk", json={"region_code": REGION, "body": "하늘 사진", "image": url}, headers=h)).json()["talk"]
|
||||
assert talk["image"] == url
|
||||
listed = (await c.get("/v1/talk/list")).json()["talks"][0]
|
||||
assert listed["image"] == url
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_rejects_non_images_and_foreign_paths():
|
||||
async with client() as c:
|
||||
h = await _login(c, "photo_02")
|
||||
bad = (await c.post("/v1/talk/image", files={"file": ("a.txt", b"not an image", "text/plain")}, headers=h)).json()
|
||||
assert bad["result"]["desc"] == "INVALID_INPUT"
|
||||
for image in ("https://evil.example/a.webp", "/v1/talk/image/../../etc/passwd", "/v1/talk/image/" + "0" * 32 + ".webp"):
|
||||
res = (await c.post("/v1/talk", json={"region_code": REGION, "body": "안녕", "image": image}, headers=h)).json()
|
||||
assert res["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await c.get("/v1/talk/image/" + "0" * 32 + ".webp")).status_code == 404
|
||||
@@ -0,0 +1,74 @@
|
||||
from dataclasses import replace
|
||||
from datetime import date
|
||||
|
||||
from services.calc.index_calc import Context, evaluate
|
||||
from scripts.gen_weather_score_table import straighten_top
|
||||
from services.index_service import EARLY, WEATHER_SCORE_DEF, WEATHER_SCORE_TABLE, calibrated_weather, weather_slot_scores
|
||||
from tests.test_index_calc import _defn, _h
|
||||
|
||||
PERFECT = Context(day=date(2026, 10, 2), is_holiday=False, pm25=8, air_label="좋음", moon=0, sunset_score=None, wind_warning=False, lookahead_rain_prob=0)
|
||||
SLOTS = ("morning", "day", "evening", "night")
|
||||
|
||||
|
||||
def test_weather_score_has_no_worst_factor_pull():
|
||||
"""해 난 비율만 0점(밤)이어도 나머지가 만점이면 비중대로 85점. 가장 낮은 요소로 25% 더 깎지 않는다."""
|
||||
hours = [_h(h, feels=21.0, prob=0, wind=0.8, hum=50, sunshine_ratio=0.0) for h in range(19, 23)]
|
||||
r = evaluate(WEATHER_SCORE_DEF, [hours], PERFECT)
|
||||
assert r.factors["sun"] == 0
|
||||
assert r.score == 85
|
||||
|
||||
|
||||
def test_gak_scores_keep_worst_factor_pull():
|
||||
"""각 점수는 그대로: 한 요소가 0점이면 섞은 점수에서 25% 깎인다."""
|
||||
defn = _defn(zero_rules=[])
|
||||
r = evaluate(defn, [[_h(19, wind=12.0)]], PERFECT)
|
||||
assert r.factors["wind"] == 0
|
||||
plain = round(sum(r.factors[a] * getattr(defn, f"weight_{a}", 0) for a in r.factors) / 100)
|
||||
assert r.score == round(plain * 0.75)
|
||||
|
||||
|
||||
def test_table_covers_every_slot_and_never_goes_down():
|
||||
for slot in SLOTS:
|
||||
table = WEATHER_SCORE_TABLE[slot]
|
||||
assert len(table) == 101
|
||||
assert all(0 <= v <= 100 for v in table)
|
||||
assert all(a <= b for a, b in zip(table, table[1:]))
|
||||
assert table[100] == 100
|
||||
|
||||
|
||||
def test_table_makes_90_rare_and_centers_60():
|
||||
"""구간마다 원래 점수 중앙값 근처가 60점 근처로, 90점 이상은 원래 점수 상위 몇 칸뿐."""
|
||||
for slot in SLOTS:
|
||||
table = WEATHER_SCORE_TABLE[slot]
|
||||
assert any(55 <= v <= 65 for v in table)
|
||||
assert sum(v >= 90 for v in table) < sum(v < 90 for v in table)
|
||||
|
||||
|
||||
def test_calibrated_uses_slot_table_and_last_night_for_early():
|
||||
assert calibrated_weather("day", 70) == WEATHER_SCORE_TABLE["day"][70]
|
||||
assert calibrated_weather(EARLY, 70) == WEATHER_SCORE_TABLE["night"][70]
|
||||
|
||||
|
||||
def test_weather_slot_scores_keeps_results_with_calibrated_scores():
|
||||
"""점수 근거(factors)는 그대로 두고 점수만 표시 점수로 바꾼 결과를 돌려준다."""
|
||||
results = {k: replace(evaluate(WEATHER_SCORE_DEF, [[_h(12)]], PERFECT), score=s) for k, s in {"morning": 40, "night": 60, EARLY: 60}.items()}
|
||||
shown = weather_slot_scores(results)
|
||||
assert {k: r.score for k, r in shown.items()} == {"morning": WEATHER_SCORE_TABLE["morning"][40], "night": WEATHER_SCORE_TABLE["night"][60], EARLY: WEATHER_SCORE_TABLE["night"][60]}
|
||||
assert all(shown[k].factors == results[k].factors for k in results)
|
||||
assert results["morning"].score == 40 # 원래 결과는 바뀌지 않는다
|
||||
|
||||
|
||||
def test_straighten_top_makes_100_only_at_the_top_and_keeps_the_rest():
|
||||
clamped = list(range(0, 80)) + [85, 90, 95] + [100] * 18 # 맨 위가 100으로 잘린 표 (원래 80~82 → 85·90·95, 83 이상은 모두 100)
|
||||
fixed = straighten_top(clamped, top=100)
|
||||
assert fixed[:80] == clamped[:80] # 아래쪽은 그대로
|
||||
assert fixed[100] == 100 and max(fixed[:100]) < 100
|
||||
above = fixed[80:]
|
||||
assert all(a < b for a, b in zip(above, above[1:])) or above[-1] == 100 # 위쪽은 구별되는 점수로 오른다
|
||||
assert straighten_top(clamped, top=90)[90] == 100 # 완벽한 점수가 100보다 낮은 구간(밤)은 거기서 100
|
||||
|
||||
|
||||
def test_weather_table_gives_100_only_at_the_best_reachable_original_score():
|
||||
assert WEATHER_SCORE_TABLE["day"][99] < 100 == WEATHER_SCORE_TABLE["day"][100]
|
||||
night_top = 100 - WEATHER_SCORE_DEF.weight_sun # 밤은 해 난 비율이 늘 0점이라 원래 점수가 85까지만 나온다
|
||||
assert WEATHER_SCORE_TABLE["night"][night_top - 1] < 100 == WEATHER_SCORE_TABLE["night"][night_top]
|
||||
Reference in new issue
Block a user