chore: main 병합 — 지금 날씨 점수 보정을 바꾸기 표로 통일
- index_service.py 충돌: main 의 오늘·내일 날씨 점수 계산은 그대로 쓰고, 보정만 strict_weather 에서 구간별 바꾸기 표(weather_slot_scores)로 바꿈
- weather_slot_scores 는 main 의 weather_why 가 쓰는 점수 근거(factors)를 그대로 둔 Result 를 돌려줌
- strict_weather 와 그 테스트(test_weather_score_is_strict_near_top) 삭제 (바꾸기 표로 통일하기로 정함)
- test_board_activates_gak_outside_its_time_window 의 ensure 스텁을 main 의 {날짜: {구간: Result}} 모양으로 맞춤
This commit is contained in:
commit
621a0cf90d
133 files changed
+8963
-489
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",
|
||||
"sky_score", "index_score", "post", "post_like", "post_like_anon", "post_save", "comment", "comment_like", "comment_like_anon", "holiday", "solar_term", "users",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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}"}
|
||||
|
||||
@@ -156,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
|
||||
|
||||
@@ -367,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시예요."
|
||||
|
||||
|
||||
@@ -394,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():
|
||||
|
||||
@@ -14,9 +14,12 @@ 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"
|
||||
|
||||
|
||||
@@ -151,7 +154,7 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat
|
||||
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]
|
||||
# 점수가 가장 높아도 제철이 아니면 순위 밖 맨 끝. 계절 표시는 제철 달이 정해진 각에만
|
||||
@@ -171,7 +174,7 @@ async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
|
||||
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})))
|
||||
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). 보이는 점수는 그대로
|
||||
@@ -188,7 +191,7 @@ async def test_board_ranks_each_slot_with_priority_weight(monkeypatch):
|
||||
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}
|
||||
@@ -206,7 +209,7 @@ async def test_board_activates_gak_outside_its_time_window(monkeypatch, cur):
|
||||
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(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)
|
||||
|
||||
@@ -291,6 +291,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
|
||||
@@ -334,3 +356,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"])
|
||||
@@ -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,145 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from router.router import app
|
||||
from services.talk_service import DAILY_MAX, HIDE_AT, parse_cursor, 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
|
||||
@@ -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
|
||||
@@ -1,5 +1,5 @@
|
||||
from dataclasses import replace
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
|
||||
from services.calc.index_calc import Context, evaluate
|
||||
from services.index_service import EARLY, WEATHER_SCORE_DEF, WEATHER_SCORE_TABLE, calibrated_weather, weather_slot_scores
|
||||
@@ -48,6 +48,10 @@ def test_calibrated_uses_slot_table_and_last_night_for_early():
|
||||
assert calibrated_weather(EARLY, 70) == WEATHER_SCORE_TABLE["night"][70]
|
||||
|
||||
|
||||
def test_weather_slot_scores_shows_calibrated_values():
|
||||
results = {k: SimpleNamespace(score=s) for k, s in {"morning": 40, "night": 60, EARLY: 60}.items()}
|
||||
assert weather_slot_scores(results) == {"morning": WEATHER_SCORE_TABLE["morning"][40], "night": WEATHER_SCORE_TABLE["night"][60], EARLY: WEATHER_SCORE_TABLE["night"][60]}
|
||||
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 # 원래 결과는 바뀌지 않는다
|
||||
Reference in new issue
Block a user