feat: 10/21 회의 반영 — 공유 링크·로그인 없이 댓글·구글 로그인만, 히어로·오늘의 각 좋아요·댓글, 히어로 오늘/내일 스위치, 단풍 지도 65곳·3단계

- 공유: 이미지와 함께 고정 URL을 넘기고 링크도 클립보드에 복사
- 로그인 창은 구글만, 댓글은 로그인 없이 '동네 익명'(링크·전화번호 막기, IP당 하루 20개, 같은 IP만 지우기)
- 히어로·오늘의 각 카드에 좋아요·댓글 (PostType HERO·TODAY_GAK)
- 히어로 오늘/내일 스위치: 내일 구간별 날씨 점수·기온·최저최고·습도·1위 각, /v1/weather/today?day=tomorrow
- 단풍 지도: 단풍 그림 지도, 단풍 전·첫 단풍·절정, 단풍잎·은행잎, 명소 65곳(산림청 예측 + 가까운 지점 날짜)
- 하단 탭 바 불투명 (홈 바 자리로 글이 비치지 않게)
- 사람 글 동네 우선 정렬·내 글 목록, 내 각 '있는 각에서 불러오기'
- 댓글 표 user_id NULL 허용·ip_hash·region_name (운영 DB ALTER 필요)
This commit is contained in:
minaChoi committed 2026-10-21 17:10:29 +09:00
1 parent 14f24d1ab0
commit 93e041bb91
46 files changed
+1820 -337

No files matched your search

+62
View File
@@ -85,3 +85,65 @@ async def test_anon_talk_like():
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"]
+3 -2
View File
@@ -50,11 +50,12 @@ async def test_signup_rejects_bad_input():
@pytest.mark.anyio
async def test_comment_requires_login_and_reactions_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}/comment", json={"body": "안녕"})).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}"}
+3 -3
View File
@@ -145,7 +145,7 @@ async def test_board_puts_out_of_season_gak_last_without_rank_or_badge(monkeypat
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) 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, _WEATHER_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]
# 점수가 가장 높아도 제철이 아니면 순위 밖 맨 끝. 계절 표시는 제철 달이 정해진 각에만
@@ -165,7 +165,7 @@ async def test_board_ranks_by_score_times_priority_weight(monkeypatch):
scores = [SimpleNamespace(index_id=x, score_date=today, score=v, slots={}) 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, _WEATHER_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). 보이는 점수는 그대로
@@ -182,7 +182,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: _RESULT_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}
+34 -1
View File
@@ -1,12 +1,16 @@
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
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"]}
@@ -84,3 +88,32 @@ async def test_rejects_bad_rules():
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"])
+59 -3
View File
@@ -1,10 +1,13 @@
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, weather_line
from services.talk_service import DAILY_MAX, HIDE_AT, parse_cursor, spread_authors, weather_line
REGION = "1144000000"
BUSAN = "2611000000"
def client():
@@ -16,8 +19,8 @@ async def _login(c, login_id: str) -> dict:
return {"Authorization": f"Bearer {body['access_token']}"}
async def _write(c, h, body="망원동 하늘 진짜 맑아요"):
return (await c.post("/v1/talk", json={"region_code": REGION, "body": body}, headers=h)).json()
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
@@ -87,3 +90,56 @@ def test_weather_line():
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