- 사람 글 큰 카드: 머리줄·4:5 본문(사진, 없으면 글을 크게)·좋아요·댓글·보내기 - 사람 글 댓글: 로그인한 사람만, comment 표에 talk_id, talk.comment_count (init.sql) - '오늘 내 글'·'동네 사람들'·주제별 묶음, '이번 주 가까운 행사' 띠 제거 - 행사 포스트 자리 최대 40개, 앞쪽 절반에 다 못 들어가면 끝까지 한 장씩 걸러 - GA: feed_item_view(talk·event 노출), talk_comment
234 lines
11 KiB
Python
234 lines
11 KiB
Python
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"]]
|
|
|
|
|
|
@pytest.mark.anyio
|
|
async def test_talk_comments_need_login_and_keep_count_on_talk():
|
|
async with client() as c:
|
|
h = await _login(c, "talk_c1")
|
|
t = (await _write(c, h))["talk"]
|
|
url = f"/v1/reaction/talk/{t['talk_id']}/comment"
|
|
count = lambda talks: next(x for x in talks if x["talk_id"] == t["talk_id"])["comment_count"] # noqa: E731
|
|
assert (await c.post(url, json={"body": "저도 봤어요"})).status_code == 401
|
|
other = await _login(c, "talk_c2")
|
|
assert (await c.post(url, headers=other, json={"body": "저도 봤어요"})).json()["result"]["desc"] == "TERMS_REQUIRED"
|
|
await c.post("/v1/auth/terms", headers=other)
|
|
assert (await c.post(url, headers=other, json={"body": "연락 010-1234-5678"})).json()["result"]["desc"] == "LINK_NOT_ALLOWED"
|
|
assert (await c.post(url, headers=other, json={"body": "가" * 61})).json()["result"]["desc"] == "INVALID_INPUT"
|
|
|
|
made = (await c.post(url, headers=other, json={"body": " 저도 봤어요 "})).json()["comment"]
|
|
assert made["body"] == "저도 봤어요" and made["mine"] is True
|
|
listed = (await c.get(f"{url}/list")).json()["comments"]
|
|
assert [x["comment_id"] for x in listed] == [made["comment_id"]] and listed[0]["nickname"] == "talk_c2"
|
|
assert count((await c.get("/v1/talk/list")).json()["talks"]) == 1
|
|
|
|
assert (await c.delete(f"/v1/reaction/comment/{made['comment_id']}", headers=other)).json()["result"]["success"] is True
|
|
assert (await c.get(f"{url}/list")).json()["comments"] == []
|
|
assert count((await c.get("/v1/talk/list")).json()["talks"]) == 0
|
|
assert (await c.post("/v1/reaction/talk/999999999/comment", headers=other, json={"body": "안녕"})).json()["result"]["desc"] == "NOT_FOUND"
|
|
|
|
|
|
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
|
|
|
|
|
|
def test_ago_text_switches_to_days_after_a_day():
|
|
from datetime import datetime, timedelta
|
|
|
|
from services.talk_service import ago_text
|
|
|
|
now = datetime(2026, 10, 27, 18, 0)
|
|
assert ago_text(now - timedelta(minutes=2), now) == "방금"
|
|
assert ago_text(now - timedelta(minutes=12), now) == "12분 전"
|
|
assert ago_text(now - timedelta(hours=23, minutes=59), now) == "23시간 전"
|
|
assert ago_text(now - timedelta(hours=24), now) == "1일 전"
|
|
assert ago_text(now - timedelta(hours=140), now) == "5일 전"
|
|
assert ago_text(now - timedelta(days=15), now) == "2주 전"
|