feat: 10/20 회의 반영 — 이야기 탭을 오늘 피드로 합침(글쓰기 칸·사진 올리기·위치 정보 삭제), 오늘의 각 카드와 히어로·각 공유 템플릿, 나만의 각을 이름+날씨 조건 저장으로, 로그인 없이 좋아요(IP 해시), 피드 순서·불쾌지수 상시·포스트 그림 배경, 새 각 아이콘

This commit is contained in:
minaChoi committed 2026-10-20 17:29:14 +09:00
1 parent 017022a0b0
commit d0213f41a6
81 files changed
+3503 -593

No files matched your search

+1 -1
View File
@@ -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",
)
+87
View File
@@ -0,0 +1,87 @@
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
+2 -2
View File
@@ -50,11 +50,11 @@ async def test_signup_rejects_bad_input():
@pytest.mark.anyio
async def test_reactions_require_login_and_update_feed(offline):
async def test_comment_requires_login_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
assert (await c.post(f"/v1/reaction/post/{post_id}/comment", json={"body": "안녕"})).status_code == 401
token = (await _signup(c))["access_token"]
h = {"Authorization": f"Bearer {token}"}
+21
View File
@@ -151,6 +151,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
+2 -3
View File
@@ -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():
+22
View File
@@ -275,6 +275,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
+64 -37
View File
@@ -1,10 +1,15 @@
from datetime import date
import pytest
from httpx import ASGITransport, AsyncClient
from common.database.db_session_manager import DB_SESSION_MNG
from crud.index_crud import IndexCRUD
from common.enums import RainType, Sky
from router.router import app
from services.my_gak_service import MAX_PER_USER
from services.calc.index_calc import Context, Hour, evaluate
from services.calc.my_gak_calc import MyRule, axes, definition
from services.my_gak_service import MAX_PER_USER, gak_name
RULE = {"temp": [15, 25], "rain": "dry", "slots": ["evening", "night"]}
def client():
@@ -12,48 +17,70 @@ def client():
async def _login(c, login_id: str) -> dict:
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": "섞기토끼"})).json()
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": "조건토끼"})).json()
return {"Authorization": f"Bearer {body['access_token']}"}
@pytest.mark.anyio
async def test_mixable_without_login_excludes_life_gak():
async with client() as c:
body = (await c.get("/v1/my-gak")).json()
_, defs = await DB_SESSION_MNG.execute_lambda(lambda s: IndexCRUD().definitions(s))
ids = {d.name: d.index_id for d in defs}
assert body["items"] == []
mixable = set(body["mixable"])
assert {ids["러닝각"], ids["치맥각"]} <= mixable
assert not {ids["우산각"], ids["교통체증각"]} & mixable
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_same_pair_is_one():
async def test_add_list_delete_and_limits():
async with client() as c:
assert (await c.post("/v1/my-gak", json={"index_ids": [1, 2]})).status_code == 401
h = await _login(c, "mix_01")
a, b = sorted((await c.get("/v1/my-gak")).json()["mixable"])[:2]
first = (await c.post("/v1/my-gak", json={"index_ids": [b, a]}, headers=h)).json()["item"]
assert first["index_ids"] == [a, b]
again = (await c.post("/v1/my-gak", json={"index_ids": [a, b]}, headers=h)).json()["item"]
assert again["my_gak_id"] == first["my_gak_id"]
assert [g["my_gak_id"] for g in (await c.get("/v1/my-gak", headers=h)).json()["items"]] == [first["my_gak_id"]]
assert (await c.delete(f"/v1/my-gak/{first['my_gak_id']}", headers=h)).json()["result"]["success"] is True
assert (await c.get("/v1/my-gak", headers=h)).json()["items"] == []
assert (await c.delete(f"/v1/my-gak/{first['my_gak_id']}", headers=h)).json()["result"]["desc"] == "NOT_FOUND"
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_same_gak_unmixable_and_over_limit():
async def test_rejects_bad_rules():
async with client() as c:
h = await _login(c, "mix_02")
mixable = sorted((await c.get("/v1/my-gak")).json()["mixable"])
bad = lambda ids: c.post("/v1/my-gak", json={"index_ids": ids}, headers=h) # noqa: E731
assert (await bad([mixable[0], mixable[0]])).json()["result"]["desc"] == "INVALID_INPUT"
assert (await bad([mixable[0], 9999])).json()["result"]["desc"] == "INVALID_INPUT"
assert (await bad([mixable[0]])).status_code == 422
pairs = [(mixable[0], x) for x in mixable[1 : MAX_PER_USER + 1]]
for p in pairs:
assert (await bad(list(p))).json()["item"]
assert (await bad([mixable[1], mixable[2]])).json()["result"]["desc"] == "INVALID_INPUT"
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
+59
View File
@@ -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