Files
o2o-weather/backend/tests/test_talk.py
minaChoi ffe6153148 feat: 내 각 아이콘·상세, 이야기 내 글·무한 스크롤, 공유 이미지 얇은 띠, 행사 주소 수집
- 내 각: 아이콘 고르기(my_gak.icon), 카드는 아이콘·점수·아쉬운 조건만, 눌러서 상세(시간대·조건별 점수), 공유는 공통 공유 창
- 이야기: 오늘 쓴 내 글 묶음, '내 글' 칩·탭, 무한 스크롤, 사진 카메라 버튼, 지우기 확인, ⋯ 메뉴 하트 옆, 글 시간 서버 계산(1일 전)
- 공유 이미지: 1:1·4:5 는 아래 얇은 띠 한 줄로 카드를 크게
- 행사: 수집 때 주소 저장(event.address), 행사 포스트에 장소·주소·기간
- 히어로 말풍선 '오늘 낮은 / 내일 낮은', 내일을 볼 때 배경도 따라감, 달 보름 순간이 낮이면 뜨는 시각으로
- 단풍 지도 피드 맨 위, 행사·계절 띠 포스트 틀 되돌림, 쇼츠 홈 버튼 가림·닫기 버튼, 하단 여백, 회색 글자 대비
- 토스 앱에선 쇼츠 플레이어를 하나만 띄움
2026-10-27 18:55:42 +09:00

208 lines
9.6 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"]]
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주 전"