Files
dbx-main/tests/test_project_notifier_api.py
king 89ad338024 fix(project): review fixes — access leaks, open paths, save safety, concurrency
- Subproject tasks via parent /tasks are re-filtered by current access (FULL/READ kept)
- PUT /api/projects/order: every id must be manageable; bad/duplicate ids -> 400, all-or-nothing
- Inbox, web alert popup, PC notifier open tasks via /project/t/{id}; embed=1 survives redirect;
  old /p/{home}?task= redirects READ users to the linked project
- Project page / snapshot / workload include the opened archived or sub project only
- Alerts: DB-side filters + oldest-first paging (no 50-row cut); badges counted without caps;
  my tasks keep every open task (completed capped)
- Meeting results: next-week meeting open, or own meeting open when no next meeting;
  header edits + result checks under row locks (FOR UPDATE / FOR SHARE)
- Inbox panel waits for the task window save (same retry/discard flow) before switching/closing;
  read failures stay unread
- Attachment upload removes only its own file on DB failure
- New project modal: create once, retry only failed member assignments
- update_task / update_project: locked-row validation in one transaction; completion hints from real transition
- Creator added as explicit member when another owner is chosen
- _once lock lifetime managed by refcount (no leak on failure)
- Section default assignee must still be a registered project user; follower add uses can_assign
- Docs (PROJECT_MODULE 6-15, help), tests (DB-less, real PostgreSQL, jsdom, Chrome)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 11:08:56 +09:00

135 lines
6.0 KiB
Python

"""PC 알림 프로그램 API(023) — 토큰 인증·연결 요청/승인/발급·마이그레이션 미적용 503. DB 없이 가짜 저장소로."""
import importlib
import unittest
from unittest.mock import patch
from fastapi import FastAPI
from fastapi.testclient import TestClient
from psycopg.errors import UndefinedTable
api = importlib.import_module("app.modules.project.router")
ROWS = [
{"id": 8, "type": "mention", "title": "나를 태그함: A", "is_read": False, "task_id": 1, "project_id": 1},
{"id": 6, "type": "assigned", "title": "작업 배정: C", "is_read": False, "task_id": 3, "project_id": 1},
]
class FakeStore:
def __init__(self):
self.links = {} # poll → {"code", "email"}
self.tokens = {"good-token": "me@test.local"}
self.read = []
def list_notifications(self, recipient_email, unread_only=False, limit=100):
return ROWS[:limit]
def list_unread_after(self, recipient_email, after_id, types, limit=200):
return sorted((r for r in ROWS if not r["is_read"] and r["id"] > after_id and r["type"] in types),
key=lambda r: r["id"])[:limit]
def mark_read(self, notification_id, recipient_email):
self.read.append((notification_id, recipient_email))
def notifier_token_email(self, token):
return self.tokens.get(token)
def notifier_start_link(self, device_name):
self.links["poll-1"] = {"code": "ABCD-EFGH", "email": None, "device": device_name, "used": False}
return {"code": "ABCD-EFGH", "poll": "poll-1", "expires_in": 600}
def notifier_approve_link(self, code, email):
for link in self.links.values():
if link["code"] == code.upper() and link["email"] is None:
link["email"] = email
return True
return False
def notifier_poll_link(self, poll):
link = self.links.get(poll)
if not link or link["used"]:
return {"status": "expired"}
if not link["email"]:
return {"status": "pending"}
link["used"] = True
self.tokens["new-token"] = link["email"]
return {"status": "ok", "token": "new-token", "email": link["email"]}
def notifier_revoke_token(self, token):
self.tokens.pop(token, None)
USER = {"email": "me@test.local", "name": "나"}
class NotifierApiTests(unittest.TestCase):
def setUp(self):
app = FastAPI()
app.include_router(api.router)
self.client = TestClient(app)
self.st = FakeStore()
self.patches = [
patch.object(api, "_db_or_503", return_value=self.st),
patch.object(api, "_visible_notifications", side_effect=lambda st, user, items: items),
patch.object(api, "_user_by_email", side_effect=lambda e: dict(USER) if e == USER["email"] else None),
patch("app.store.has_module", return_value=True),
]
for p in self.patches:
p.start()
def tearDown(self):
for p in self.patches:
p.stop()
def alerts(self, token, qs="?after=0"):
return self.client.get("/project/api/notifier/alerts" + qs, headers={"Authorization": "Bearer " + token})
def test_alerts_with_token_returns_same_payload_as_web_plus_name(self):
res = self.alerts("good-token")
self.assertEqual(res.status_code, 200)
out = res.json()
self.assertEqual([a["id"] for a in out["alerts"]], [6, 8])
self.assertEqual((out["me"], out["latest_id"], out["name"]), ("me@test.local", 8, "나"))
# PC 알림 [열기] 도 웹과 같은 주소(작업 공유 링크) — 서버가 지금 권한으로 열 프로젝트를 고른다
self.assertEqual([a["href"] for a in out["alerts"]], ["/project/t/3", "/project/t/1"])
def test_alerts_rejects_missing_or_unknown_token(self):
self.assertEqual(self.client.get("/project/api/notifier/alerts").status_code, 401)
self.assertEqual(self.alerts("bad").status_code, 401)
def test_alerts_rejects_user_without_project_module(self):
with patch("app.store.has_module", return_value=False):
self.assertEqual(self.alerts("good-token").status_code, 401)
def test_read_marks_only_for_token_owner(self):
res = self.client.post("/project/api/notifier/alerts/8/read", headers={"Authorization": "Bearer good-token"})
self.assertEqual(res.status_code, 200)
self.assertEqual(self.st.read, [(8, "me@test.local")])
def test_link_flow_pending_then_token_once(self):
start = self.client.post("/project/api/notifier/link/start", json={"device": "KING-PC"}).json()
self.assertEqual(start["approve_path"], "/project/notifier?code=ABCD-EFGH")
self.assertEqual(self.client.post("/project/api/notifier/link/poll", json={"poll": start["poll"]}).json()["status"], "pending")
with patch.object(api, "_require_user", return_value=dict(USER)):
self.assertEqual(self.client.post("/project/api/notifier/link/approve", json={"code": "abcd-efgh"}).status_code, 200)
self.assertEqual(self.client.post("/project/api/notifier/link/approve", json={"code": "ABCD-EFGH"}).status_code, 404)
got = self.client.post("/project/api/notifier/link/poll", json={"poll": start["poll"]}).json()
self.assertEqual((got["status"], got["token"]), ("ok", "new-token"))
self.assertEqual(self.client.post("/project/api/notifier/link/poll", json={"poll": start["poll"]}).json()["status"], "expired")
self.assertEqual(self.alerts("new-token").status_code, 200)
def test_logout_revokes_token(self):
self.client.post("/project/api/notifier/logout", headers={"Authorization": "Bearer good-token"})
self.assertEqual(self.alerts("good-token").status_code, 401)
def test_missing_migration_is_503(self):
def boom(**_):
raise UndefinedTable("notifier_links")
self.st.notifier_start_link = boom
res = self.client.post("/project/api/notifier/link/start", json={"device": "X"})
self.assertEqual(res.status_code, 503)
if __name__ == "__main__":
unittest.main()