"""긴급 공지 저장소 — 실제 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="

x

", 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="

1

", 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="

2

", 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'

그림

' 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"", filename="x.svg", by=boss) if __name__ == "__main__": unittest.main()