Files
dbx-main/tests/test_notice_db.py
T
king c7cc94a09c fix: 2026-10-15 코드 검토 F01~F10 — 수집 실패 전파·트랜잭션 경계·저장 실패·공지 버전/확인 조건·테스트 체계
- F01 쿠팡: HTTP 200 비JSON·data 목록 없음은 수집 실패(기간 교체 안 함), 정상 빈 목록과 구분
- F02 회의록 [적용]: 업무 INSERT 와 줄 연결을 한 연결·한 트랜잭션(_insert_task), 확인은 잠그기 전·알림/메일은 커밋 뒤, 줄 바뀜 409
- F03 업무 등록 표: persist 실패 전파, 미저장이면 [적용] 중단, 초안 유지·다시 저장·이탈 경고
- F04 인증정보 변경 시 내부 토큰 삭제 + 네이버·토스 토큰을 발급 인증정보 지문(SHA-256)에 묶음, GS샵 방식 캐시도 키 지문 기준
- F05 쪽 수 상한·커서 반복 = 실패(쿠팡은 구간을 하루까지 나눠 재시도), 네이버·카카오·토스·GS샵 동일 기준
- F06 [중지] 확인과 저장 시작을 같은 잠금(begin_saving), 저장 시작 뒤 중지 불가
- F07/F08 긴급 공지: 내용 version·고친 공지 다시 그리기·확인에 version(409), 확인은 행 잠금 트랜잭션에서 수신자·표시 시각·취소 검증
- F09 쇼핑몰 연결 테스트도 clear 처리·저장 안 한 시험은 상태 유지(광고 테스트와 같은 계약)
- F10 DB 테스트 skip·가짜 app.main/time.sleep 파일 범위 fixture, 오래된 기대값 갱신, pytest.ini·requirements-dev·tests/js/package.json·docs/TESTING.md
- 결과·후속 과제: docs/CODE_REVIEW_2026-10-15_RESULT.md (마이그레이션·환경변수 변경 없음)

Python 440 passed/63 skipped(DB 없음), 503 passed(로컬 PostgreSQL), jsdom 7종·Edge 6종 통과

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 18:41:42 +09:00

145 lines
8.7 KiB
Python

"""긴급 공지 저장소 — 실제 PostgreSQL(로컬 테스트 DB 전용, PROJECT_TEST_DB_URL 이 localhost 일 때만).
PROJECT_TEST_DB_URL=postgresql://postgres@127.0.0.1:55432/project_db python -m pytest tests/test_notice_db.py
project_db init + 마이그레이션(024 포함)이 적용돼 있어야 한다. 가상의 사용자·공지만 만든다.
"""
import os
import unittest
import uuid
from datetime import datetime, timedelta
from urllib.parse import urlparse
from app.timezone import KST
DSN = os.getenv("PROJECT_TEST_DB_URL", "")
ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
PNG = b"\x89PNG\r\n\x1a\n" + b"1" * 32
@unittest.skipUnless(ENABLED, "PROJECT_TEST_DB_URL(localhost) not set")
class NoticeDbTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
from app.modules.notice.db import NoticeStore
from app.modules.project.db import ProjectStore
cls.ps = ProjectStore(DSN)
cls.st = NoticeStore(cls.ps.pool)
cls.tag = uuid.uuid4().hex[:6]
@classmethod
def tearDownClass(cls):
cls.ps.close()
def em(self, name):
return f"{name}-{self.tag}@test.local"
def ids(self, email, now=None):
return [n["id"] for n in self.st.pending_for(email=email, now=now)]
def test_schedule_targets_ack_cancel_reshow(self):
boss, a, b = self.em("boss"), self.em("a"), self.em("b")
now = datetime.now(KST)
allp = self.st.create_notice(title="전체", body="<p>x</p>", show_at="", to_all=True, targets=[], by=boss)
some = self.st.create_notice(title="a 만", body="", show_at="", to_all=False, targets=[a], by=boss)
later = self.st.create_notice(title="예약", body="", show_at=(now + timedelta(hours=2)).isoformat(),
to_all=True, targets=[], by=boss)
self.assertIn(allp["id"], self.ids(a))
self.assertIn(some["id"], self.ids(a))
self.assertNotIn(some["id"], self.ids(b)) # 고른 사람만
self.assertNotIn(later["id"], self.ids(a)) # 띄울 시각 전
self.assertIn(later["id"], self.ids(a, now=now + timedelta(hours=3)))
self.assertEqual(self.st.ack(notice_id=allp["id"], email=a), "acked")
self.assertEqual(self.st.ack(notice_id=allp["id"], email=a), "already") # 두 번 눌러도 한 번
self.assertNotIn(allp["id"], self.ids(a))
self.assertIn(allp["id"], self.ids(b))
self.st.cancel_notice(notice_id=allp["id"], by=boss)
self.assertNotIn(allp["id"], self.ids(b)) # 취소 = 아무에게도 안 뜸
self.st.cancel_notice(notice_id=allp["id"], by=boss, cancel=False)
self.assertIn(allp["id"], self.ids(b))
row = next(n for n in self.st.list_notices() if n["id"] == allp["id"])
self.assertEqual(list(row["acks"]), [a])
# 고치기 — 받는 사람 바꾸기, reshow 면 확인한 사람에게도 다시
self.st.update_notice(notice_id=allp["id"], title="전체(수정)", body="", show_at="", to_all=True, targets=[], by=boss)
self.assertNotIn(allp["id"], self.ids(a))
self.st.update_notice(notice_id=allp["id"], title="전체(다시)", body="", show_at="", to_all=True, targets=[], by=boss, reshow=True)
self.assertIn(allp["id"], self.ids(a))
self.st.update_notice(notice_id=some["id"], title="b 로", body="", show_at="", to_all=False, targets=[b], by=boss)
self.assertNotIn(some["id"], self.ids(a))
self.assertIn(some["id"], self.ids(b))
with self.assertRaises(KeyError):
self.st.update_notice(notice_id=10 ** 12, title="x", body="", show_at="", to_all=True, targets=[], by=boss)
def test_ack_only_shown_uncancelled_for_recipients(self):
"""2026-10-15 검토 F08 — 예약(띄울 시각 전)·취소·받는 사람 아님은 확인 기록을 남기지 않는다(같은 트랜잭션에서 판단)."""
boss, a, b = self.em("boss"), self.em("a8"), self.em("b8")
now = datetime.now(KST)
later = self.st.create_notice(title="예약", body="", show_at=(now + timedelta(hours=2)).isoformat(),
to_all=True, targets=[], by=boss)
only_a = self.st.create_notice(title="a 만", body="", show_at="", to_all=False, targets=[a], by=boss)
gone = self.st.create_notice(title="취소", body="", show_at="", to_all=True, targets=[], by=boss)
self.st.cancel_notice(notice_id=gone["id"], by=boss)
self.assertEqual(self.st.ack(notice_id=later["id"], email=a), "denied") # 미래 공지
self.assertEqual(self.st.ack(notice_id=gone["id"], email=a), "denied") # 취소 공지
self.assertEqual(self.st.ack(notice_id=only_a["id"], email=b), "denied") # 받는 사람 아님
self.assertEqual(self.st.ack(notice_id=10 ** 12, email=a), "denied")
acks = {n["id"]: n["acks"] for n in self.st.list_notices()}
self.assertEqual((acks[later["id"]], acks[gone["id"]], acks[only_a["id"]]), ({}, {}, {}))
# 표시 시각이 되면 확인 가능, 미리 확인해 두는 일은 없으니 그 시각에 pending 에 그대로 뜬다
self.assertIn(later["id"], self.ids(a, now=now + timedelta(hours=3)))
self.assertEqual(self.st.ack(notice_id=later["id"], email=a, now=now + timedelta(hours=3)), "acked")
self.assertEqual(self.st.ack(notice_id=only_a["id"], email=a), "acked")
def test_ack_version_and_reshow(self):
"""F07 — 읽은 내용(version)이 지금과 다르면 stale(기록 안 함), 같으면 기록. reshow 는 다시 띄운다."""
boss, a = self.em("boss"), self.em("a7")
n = self.st.create_notice(title="VERSION ONE", body="<p>1</p>", show_at="", to_all=True, targets=[], by=boss)
v1 = next(x["version"] for x in self.st.pending_for(email=a) if x["id"] == n["id"])
self.st.update_notice(notice_id=n["id"], title="VERSION TWO", body="<p>2</p>", show_at="", to_all=True, targets=[], by=boss)
cur = next(x for x in self.st.pending_for(email=a) if x["id"] == n["id"])
self.assertNotEqual(cur["version"], v1)
self.assertEqual(cur["title"], "VERSION TWO")
self.assertEqual(self.st.ack(notice_id=n["id"], email=a, version=v1), "stale") # 고치기 전 내용을 읽고 누름
self.assertIn(n["id"], self.ids(a))
self.assertEqual(self.st.ack(notice_id=n["id"], email=a, version=cur["version"]), "acked")
self.assertNotIn(n["id"], self.ids(a))
self.st.update_notice(notice_id=n["id"], title="VERSION THREE", body="", show_at="", to_all=True, targets=[], by=boss,
reshow=True)
self.assertIn(n["id"], self.ids(a)) # reshow — 확인한 사람에게도 다시
def test_ack_waits_for_concurrent_cancel(self):
"""F08 — 다른 연결이 공지를 취소하는 중(커밋 전)이면 확인은 기다렸다가 취소된 행으로 다시 판단해 기록하지 않는다."""
import threading
boss, a = self.em("boss"), self.em("ac")
n = self.st.create_notice(title="곧 취소", body="", show_at="", to_all=True, targets=[], by=boss)
out = {}
with self.ps.pool.connection() as conn:
conn.execute("BEGIN")
conn.execute("UPDATE urgent_notices SET cancelled_at = now() WHERE id = %s", (n["id"],)) # 잠금 + 커밋 전
th = threading.Thread(target=lambda: out.setdefault("r", self.st.ack(notice_id=n["id"], email=a)))
th.start()
th.join(1.0)
self.assertTrue(th.is_alive()) # 행 잠금 때문에 기다린다
conn.execute("COMMIT")
th.join(10)
self.assertEqual(out.get("r"), "denied")
acks = next(x["acks"] for x in self.st.list_notices() if x["id"] == n["id"])
self.assertEqual(acks, {})
def test_images_link_only_own_uploads(self):
boss, other = self.em("boss"), self.em("other")
mine = self.st.add_image(data=PNG, filename="a.png", by=boss)
theirs = self.st.add_image(data=PNG, filename="b.png", by=other)
body = f'<p>그림</p><img src="{mine["url"]}"><img src="{theirs["url"]}">'
n = self.st.create_notice(title="그림", body=body, show_at="", to_all=True, targets=[], by=boss)
self.assertEqual(self.st.get_image(image_id=mine["id"])["notice_id"], n["id"])
self.assertIsNone(self.st.get_image(image_id=theirs["id"])["notice_id"]) # 남이 올린 이미지는 묶이지 않는다
self.assertEqual(bytes(self.st.get_image(image_id=mine["id"])["data"]), PNG)
with self.assertRaises(ValueError):
self.st.add_image(data=b"<svg/>", filename="x.svg", by=boss)
if __name__ == "__main__":
unittest.main()