Files
o2o-weather/backend/tests/test_post_scope.py
T

114 lines
5.8 KiB
Python

import csv
import os
from collections import defaultdict
from datetime import date
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import text
from common.database.db_session_manager import DB_SESSION_MNG
from common.enums import PostType
from common.utils.kma_time import now_kst
from crud.feed_crud import FeedCRUD
from crud.region_crud import RegionCRUD
from crud.season_crud import SeasonCRUD
from router.router import app
from services.feed_service import LINEUP, NATIONAL_SCOPE, NATIONAL_TYPES, build_feed_day, feed_day, sido_of
SEOUL_A, SEOUL_B, BUSAN = "1111000000", "1114000000", "2611000000"
REGION_CSV = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "region.csv")
def client():
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
def _ids(feed: dict) -> dict[int, set[int]]:
out: dict[int, set[int]] = defaultdict(set)
for p in feed["posts"]:
out[p["post_type"]].add(p["post_id"])
return out
def test_every_region_maps_to_one_sido():
with open(REGION_CSV, encoding="utf-8") as f:
regions = list(csv.DictReader(f))
assert len(regions) == 256
by_name: dict[str, set[str]] = defaultdict(set)
for r in regions:
by_name[r["name"].split()[0]].add(sido_of(r["code"]))
assert all(len(codes) == 1 for codes in by_name.values()), by_name
sidos = {sido_of(r["code"]) for r in regions}
assert all(len(c) == 2 and c.isdigit() and c != NATIONAL_SCOPE for c in sidos)
sejong = [r for r in regions if r["name"].startswith("세종")]
assert len(sejong) == 1 and sido_of(sejong[0]["code"]) == "36"
assert sum(1 for r in regions if sido_of(r["code"]) == "36") == 1
@pytest.mark.anyio
async def test_build_day_makes_national_once_and_regional_per_sido():
day = date(2026, 10, 15)
await build_feed_day(day, FeedCRUD(), SeasonCRUD(), RegionCRUD())
await build_feed_day(day, FeedCRUD(), SeasonCRUD(), RegionCRUD())
_, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(f"SELECT scope, post_type FROM post WHERE feed_date='{day}'")))
rows = list(rows)
_, regions = await DB_SESSION_MNG.execute_lambda(lambda s: RegionCRUD().search(s))
sidos = {sido_of(r.code) for r in regions}
regional = [x for x in LINEUP if x[1] not in NATIONAL_TYPES]
assert {scope for scope, t in rows if PostType(t) in NATIONAL_TYPES} == {NATIONAL_SCOPE}
assert {scope for scope, t in rows if PostType(t) not in NATIONAL_TYPES} == sidos
assert sum(1 for scope, t in rows if PostType(t) not in NATIONAL_TYPES) == len(regional) * len(sidos)
@pytest.mark.anyio
async def test_regional_posts_shared_within_sido_split_across_sido(offline):
async with client() as c:
a, b, busan = [(await c.get("/v1/feed", params={"region": r})).json() for r in (SEOUL_A, SEOUL_B, BUSAN)]
ia, ib, ibusan = _ids(a), _ids(b), _ids(busan)
regional = [t for t in ia if PostType(t) not in NATIONAL_TYPES]
assert PostType.WEATHER.value in regional and PostType.GAK.value in regional
for t in regional:
if t in ib:
assert ia[t] == ib[t], PostType(t)
if t in ibusan:
assert not ia[t] & ibusan[t], PostType(t)
national = [t for t in ia if PostType(t) in NATIONAL_TYPES]
assert PostType.MOON.value in national
for t in national:
assert ia[t] == ib[t] == ibusan[t], PostType(t)
@pytest.mark.anyio
async def test_like_in_one_sido_not_seen_in_another(offline):
async with client() as c:
token = (await c.post("/v1/auth/signup", json={"login_id": "scope_01", "password": "password1", "nickname": "시도테스트"})).json()["access_token"]
h = {"Authorization": f"Bearer {token}"}
await c.post("/v1/auth/terms", headers=h)
seoul = (await c.get("/v1/feed", params={"region": SEOUL_A}, headers=h)).json()
post_id = next(p["post_id"] for p in seoul["posts"] if p["post_type"] == PostType.WEATHER.value)
assert (await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)).json()["like_count"] == 1
await c.post(f"/v1/reaction/post/{post_id}/comment", json={"body": "서울 맑음"}, headers=h)
same = (await c.get("/v1/feed", params={"region": SEOUL_B}, headers=h)).json()
busan = (await c.get("/v1/feed", params={"region": BUSAN}, headers=h)).json()
mine = next(p for p in same["posts"] if p["post_id"] == post_id)
assert mine["liked"] is True and mine["like_count"] == 1 and mine["comment_count"] == 1
weather = next(p for p in busan["posts"] if p["post_type"] == PostType.WEATHER.value)
assert weather["post_id"] != post_id and weather["like_count"] == 0 and weather["comment_count"] == 0 and not weather.get("liked")
@pytest.mark.anyio
async def test_day_built_before_split_keeps_national_rows_for_regional_cards(offline):
"""그날 지역 카드가 이미 전국 행으로 있으면 시도 행을 만들지 않고, 모든 시도가 그 행(과 반응)을 같이 쓴다."""
day = feed_day(now_kst())
rows = ", ".join(f"('{day}', {pos}, '{NATIONAL_SCOPE}', {t.value}, {ref.value}, {rank if rank else 'NULL'}, now(), {5 if t is PostType.WEATHER else 0})"
for pos, t, ref, rank in LINEUP if ref.value == 1)
await DB_SESSION_MNG.execute_lambda_run([lambda s: s.execute(text(
f"INSERT INTO post (feed_date, position, scope, post_type, ref_type, index_rank, published_at, like_count) VALUES {rows}"))])
async with client() as c:
seoul, busan = [(await c.get("/v1/feed", params={"region": r})).json() for r in (SEOUL_A, BUSAN)]
_, n = await DB_SESSION_MNG.execute_lambda(lambda s: s.scalar(text(f"SELECT count(*) FROM post WHERE feed_date='{day}' AND scope <> '{NATIONAL_SCOPE}'")))
assert n == 0
ws, wb = [next(p for p in f["posts"] if p["post_type"] == PostType.WEATHER.value) for f in (seoul, busan)]
assert ws["post_id"] == wb["post_id"] and ws["like_count"] == 5