"""프로젝트 관리 모듈 — 권한·저장·댓글 첨부·알림 회귀 테스트 (실제 PostgreSQL + FastAPI TestClient). 운영 DB 와 분리된 **로컬 테스트용 PostgreSQL** 에서만 돈다. 가상의 사용자·프로젝트만 만든다. # 1) 로컬 테스트 DB 에 스키마 적용(최초 1회): project_db_init.sql + project_db_0*.sql # 2) 실행 PROJECT_TEST_DB_URL=postgresql://postgres@localhost:55432/project_db \ python tests/test_project_module.py PROJECT_TEST_DB_URL 이 없거나 localhost/127.0.0.1 이 아니면 전부 건너뛴다(운영 DB 보호). 메일은 app.mail.send_email 을 가짜로 바꿔 기록만 한다(실제 발송 없음). """ from __future__ import annotations import io import os import sys import tempfile import threading import types import uuid from datetime import timedelta from urllib.parse import urlparse sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) DSN = os.getenv("PROJECT_TEST_DB_URL", "") _host = urlparse(DSN).hostname if DSN else None ENABLED = bool(DSN) and _host in ("localhost", "127.0.0.1") # ── app.main 대역(전체 앱을 띄우지 않고 프로젝트 라우터만 시험) ────────────── class _Users: def __init__(self) -> None: self.d: dict[str, dict] = {} def add(self, email: str, *, role: str = "user", project: bool = True, super_: bool = False) -> str: email = email.lower() self.d[email] = {"email": email, "name": email.split("@")[0], "role": role, "modules": {"project": project}, "is_super_admin": super_} return email def get(self, email: str): return self.d.get((email or "").lower()) def list_all(self): return list(self.d.values()) USERS = _Users() SENT_MAIL: list[dict] = [] if ENABLED: from fastapi.responses import HTMLResponse fake_main = types.ModuleType("app.main") fake_main.user_store = USERS def _current(request): return USERS.get(request.headers.get("x-test-user", "")) fake_main.get_current_user_record = _current fake_main.build_erp_nav = lambda user, active="": [] fake_main.render_template = lambda request, name, ctx, status_code=200: HTMLResponse( f"{name}|{ctx.get('reason', '')}", status_code=status_code) sys.modules["app.main"] = fake_main for k in list(os.environ): if k.startswith("SMTP_") or k == "PROJECT_NOTIFY_EMAIL": os.environ.pop(k) import app.mail as _mail # noqa: E402 _mail.send_email = lambda **kw: SENT_MAIL.append(kw) from fastapi import FastAPI # noqa: E402 from fastapi.testclient import TestClient # noqa: E402 from app.modules.project import reminders # noqa: E402 from app.modules.project import router as project_api_router # noqa: E402 - 패키지가 APIRouter 를 내보낸다 from app.modules.project.db import ProjectStore # noqa: E402 from app.timezone import today_kst # noqa: E402 ST = ProjectStore(DSN) DATA_DIR = tempfile.mkdtemp(prefix="pj-test-") APP = FastAPI() APP.include_router(project_api_router) APP.state.project_store = ST APP.state.data_dir = DATA_DIR CLIENT = TestClient(APP) RUN = uuid.uuid4().hex[:6] ADMIN = USERS.add(f"admin-{RUN}@test.local", role="admin") SUPER = USERS.add("king@dbxcorp.co.kr", role="admin", super_=True) ALICE = USERS.add(f"alice-{RUN}@test.local") BOB = USERS.add(f"bob-{RUN}@test.local") CAROL = USERS.add(f"carol-{RUN}@test.local") DAVE = USERS.add(f"dave-{RUN}@test.local") # 프로젝트 권한은 있으나 어디에도 멤버 아님 EVE = USERS.add(f"eve-{RUN}@test.local", project=False) # 프로젝트 모듈 권한 없음 def req(method: str, url: str, who: str, **kw): return CLIENT.request(method, url, headers={"x-test-user": who}, **kw) def _project(name: str, owner: str, members: tuple[str, ...] = ()) -> dict: p = ST.create_project(name=f"{name}-{uuid.uuid4().hex[:4]}", owner_email=owner, created_by=owner) for m in members: ST.add_member(project_id=p["id"], user_email=m) return p def _stage(pid: int, name: str = "할 일", done: bool = False, by: str = "") -> dict: return ST.add_stage(project_id=pid, name=name, is_done_stage=done, created_by=by) def _count(sql: str, *args) -> int: with ST._pool.connection() as conn: # noqa: SLF001 - 테스트 전용 확인 쿼리 return int(conn.execute(sql, args).fetchone()["n"]) # ════════════════════════════════════════════════════════════ # [07] 소유자 변경은 관리자만 # ════════════════════════════════════════════════════════════ def test_owner_change_admin_only(): p = _project("P-owner", ADMIN, (BOB,)) r = req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": BOB}) assert r.status_code == 403, r.text assert ST.get_project(project_id=p["id"])["owner_email"] == ADMIN r = req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": CAROL, "name": "x"}) assert r.status_code == 403 and ST.get_project(project_id=p["id"])["name"] != "x" # 같은 값을 같이 보내는 건(화면 저장) 통과 assert req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": ADMIN, "name": "ok"}).status_code == 200 # 관리자: 모듈 권한 없는 사람은 소유자 불가, 정상 사용자는 가능 assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": EVE}).status_code == 400 assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": CAROL}).status_code == 200 assert ST.get_project(project_id=p["id"])["owner_email"] == CAROL # 소유자에서 빠지면(관리자가 다시 바꿈) 멤버가 아닌 CAROL 은 관리 권한을 잃는다 assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": ADMIN}).status_code == 200 assert req("GET", f"/project/api/projects/{p['id']}/snapshot", CAROL).status_code == 403 # 생성: 비관리자가 남을 소유자로 지정 → 거절, 본인·미지정 → 본인이 소유자 assert req("POST", "/project/api/projects", BOB, json={"name": "n1", "owner_email": CAROL}).status_code == 403 r = req("POST", "/project/api/projects", BOB, json={"name": "n2"}) assert r.status_code == 201 and r.json()["project"]["owner_email"] == BOB # ════════════════════════════════════════════════════════════ # [06] 삭제 — 생성자 규칙 + 지금 권한 # ════════════════════════════════════════════════════════════ def test_delete_requires_current_access(): p = _project("P-del", ADMIN, (ALICE, BOB)) s = _stage(p["id"], by=ADMIN) t = req("POST", f"/project/api/projects/{p['id']}/tasks", ALICE, json={"title": "alice task", "stage_id": s["id"]}).json()["task"] ST.add_comment(task_id=t["id"], author_email=ALICE, author_name="a", body="hi") trash_before = _count("SELECT COUNT(*) AS n FROM project_trash") # 현재 멤버인 타인 → 생성자 규칙으로 거절 assert req("DELETE", f"/project/api/tasks/{t['id']}", BOB).status_code == 403 # 멤버에서 빠진 생성자 → 거절, 행·댓글·휴지통 변화 없음 ST.remove_member(project_id=p["id"], user_email=ALICE) assert req("DELETE", f"/project/api/tasks/{t['id']}", ALICE).status_code == 403 assert ST.get_task(task_id=t["id"]) is not None assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id = %s", t["id"]) == 1 assert _count("SELECT COUNT(*) AS n FROM project_trash") == trash_before # 다시 멤버가 된 생성자 → 삭제(휴지통) ST.add_member(project_id=p["id"], user_email=ALICE) r = req("DELETE", f"/project/api/tasks/{t['id']}", ALICE) assert r.status_code == 200 and ST.get_task(task_id=t["id"]) is None # 프로젝트 삭제: 만든 사람이어도 지금 권한이 없으면 거절, 슈퍼관리자는 예외 p2 = _project("P-del2", ALICE) ST.update_project(project_id=p2["id"], fields={"owner_email": ADMIN}) # 관리자가 소유자를 바꿈 assert req("DELETE", f"/project/api/projects/{p2['id']}", ALICE).status_code == 403 assert ST.get_project(project_id=p2["id"]) is not None assert req("DELETE", f"/project/api/projects/{p2['id']}", SUPER).status_code == 200 # ════════════════════════════════════════════════════════════ # [02] 권한 회수 후 조회·변경·알림 # ════════════════════════════════════════════════════════════ def test_revoked_member_loses_everything(): p = _project("P-rev", ADMIN, (ALICE, BOB)) s = _stage(p["id"], by=ADMIN) t = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "shared", "stage_id": s["id"], "assignee_email": ALICE, "description": f'@a'}).json()["task"] c = req("POST", f"/project/api/tasks/{t['id']}/comments", ALICE, json={"body": "mine"}).json()["comment"] assert any(x["id"] == t["id"] for x in req("GET", "/project/api/my-tasks", ALICE).json()["tasks"]) assert any(x["id"] == t["id"] for x in req("GET", "/project/api/mentions", ALICE).json()["tasks"]) assert any(n["task_id"] == t["id"] for n in req("GET", "/project/api/notifications", ALICE).json()["notifications"]) ST.remove_member(project_id=p["id"], user_email=ALICE) assert not any(x["id"] == t["id"] for x in req("GET", "/project/api/my-tasks", ALICE).json()["tasks"]) assert not any(x["id"] == t["id"] for x in req("GET", "/project/api/mentions", ALICE).json()["tasks"]) assert not any(n.get("task_id") == t["id"] for n in req("GET", "/project/api/notifications", ALICE).json()["notifications"]) for m, u, body in (("GET", f"/project/api/tasks/{t['id']}", None), ("GET", f"/project/api/tasks/{t['id']}/comments", None), ("GET", f"/project/api/tasks/{t['id']}/attachments", None), ("PUT", f"/project/api/tasks/{t['id']}", {"title": "x"}), ("PUT", f"/project/api/comments/{c['id']}", {"body": "edited"}), ("DELETE", f"/project/api/comments/{c['id']}", None), ("POST", f"/project/api/tasks/{t['id']}/followers", {})): r = req(m, u, ALICE, json=body) if body is not None else req(m, u, ALICE) assert r.status_code == 403, (m, u, r.status_code) assert ST.get_comment(comment_id=c["id"])["body"] == "mine" assert req("GET", f"/project/t/{t['id']}", ALICE, follow_redirects=False).status_code == 403 # 옛 공유 링크 # 완료 알림은 권한 잃은 담당자에게 가지 않는다(담당자 기록은 남음) before = _count("SELECT COUNT(*) AS n FROM project_notifications WHERE recipient_email=%s AND task_id=%s", ALICE, t["id"]) assert req("PUT", f"/project/api/tasks/{t['id']}", BOB, json={"completed": True}).status_code == 200 assert _count("SELECT COUNT(*) AS n FROM project_notifications WHERE recipient_email=%s AND task_id=%s", ALICE, t["id"]) == before assert ST.get_task(task_id=t["id"])["assignee_email"] == ALICE # 권한 없는 사람을 새 담당자로 지정할 수 없다 assert req("PUT", f"/project/api/tasks/{t['id']}", BOB, json={"assignee_email": DAVE}).status_code == 400 # 관리자·owner·멤버는 그대로 assert req("GET", f"/project/api/tasks/{t['id']}", ADMIN).status_code == 200 assert req("GET", f"/project/api/tasks/{t['id']}", BOB).status_code == 200 # ════════════════════════════════════════════════════════════ # [08] 비멤버 @태그 # ════════════════════════════════════════════════════════════ def test_mentions_only_for_people_who_can_see(): p = _project("P-men", ADMIN, (BOB,)) s = _stage(p["id"], by=ADMIN) desc = "".join(f'@x' for e in (DAVE, EVE, "ghost@nowhere.test")) r = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "m", "stage_id": s["id"], "description": desc}) t = r.json()["task"] assert set(r.json()["mention_skipped"]) == {DAVE, EVE, "ghost@nowhere.test"} assert _count("SELECT COUNT(*) AS n FROM task_mentions WHERE task_id=%s", t["id"]) == 0 r = req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "@dave hi", "mentions": [DAVE]}) assert r.status_code == 201 and r.json()["mention_skipped"] == [DAVE] assert not req("GET", "/project/api/mentions", DAVE).json()["tasks"] or \ all(x["id"] != t["id"] for x in req("GET", "/project/api/mentions", DAVE).json()["tasks"]) # 멘션이 접근 권한을 만들지 않는다 assert req("GET", f"/project/api/tasks/{t['id']}", DAVE).status_code == 403 # 연결된 프로젝트 멤버는 태그 가능(읽기 권한) p2 = _project("P-men2", ADMIN, (BOB, CAROL)) s2 = _stage(p2["id"], by=ADMIN) assert req("POST", f"/project/api/tasks/{t['id']}/links", BOB, json={"project_id": p2["id"], "stage_id": s2["id"]}).status_code == 201 r = req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "@carol", "mentions": [CAROL]}) assert r.json()["mention_skipped"] == [] assert any(x["id"] == t["id"] for x in req("GET", "/project/api/mentions", CAROL).json()["tasks"]) # 태그 후보 API 도 같은 기준 cands = {u["email"] for u in req("GET", f"/project/api/all-users?task_id={t['id']}", BOB).json()["users"]} assert CAROL in cands and BOB in cands and DAVE not in cands and EVE not in cands # ════════════════════════════════════════════════════════════ # [12] 연결된 프로젝트 — 읽기 전용 # ════════════════════════════════════════════════════════════ def test_linked_task_is_read_only(): home = _project("P-home", ADMIN, (BOB,)) other = _project("P-link", ADMIN, (BOB, CAROL)) secret = _project("P-secret", ADMIN, (BOB,)) hs, os_ = _stage(home["id"], by=ADMIN), _stage(other["id"], by=ADMIN) os2 = _stage(other["id"], name="진행", by=ADMIN) ss = _stage(secret["id"], by=ADMIN) t = ST.create_task(project_id=home["id"], title="linked", stage_id=hs["id"], created_by=BOB) sib = ST.create_task(project_id=home["id"], title="sibling", stage_id=hs["id"], created_by=BOB) sub = ST.create_task(project_id=home["id"], title="child", parent_task_id=t["id"], created_by=BOB) for pid, sid in ((other["id"], os_["id"]), (secret["id"], ss["id"])): assert req("POST", f"/project/api/tasks/{t['id']}/links", BOB, json={"project_id": pid, "stage_id": sid}).status_code == 201 r = req("GET", f"/project/api/tasks/{t['id']}", CAROL) assert r.status_code == 200 and r.json()["task"]["access"] == "read" assert [ln["project_id"] for ln in r.json()["task"]["links"]] == [other["id"]] # 비밀 프로젝트는 숨김 assert r.json()["task"]["followers"] is None assert req("GET", f"/project/api/tasks/{sub['id']}", CAROL).json()["task"]["access"] == "read" # 하위 작업도 읽기 assert req("GET", f"/project/api/tasks/{sib['id']}", CAROL).status_code == 403 # 원 소속의 다른 작업은 안 보임 assert req("GET", f"/project/api/projects/{home['id']}/members", CAROL).status_code == 403 assert req("GET", f"/project/api/tasks/{t['id']}/comments", CAROL).status_code == 200 for m, u, body in (("PUT", f"/project/api/tasks/{t['id']}", {"title": "hack"}), ("POST", f"/project/api/tasks/{t['id']}/comments", {"body": "hi"}), ("DELETE", f"/project/api/tasks/{t['id']}", None)): r = req(m, u, CAROL, json=body) if body is not None else req(m, u, CAROL) assert r.status_code == 403, (m, u, r.status_code) assert ST.get_task(task_id=t["id"])["title"] == "linked" # 연결된 프로젝트 안의 섹션 이동은 예전처럼 허용 assert req("POST", f"/project/api/tasks/{t['id']}/links", CAROL, json={"project_id": other["id"], "stage_id": os2["id"]}).status_code == 201 # 공유 링크 — 연결된 프로젝트 화면으로 r = req("GET", f"/project/t/{t['id']}", CAROL, follow_redirects=False) assert r.status_code == 303 and r.headers["location"] == f"/project/p/{other['id']}?task={t['id']}" # 전체 스냅샷에서 연결 행은 연결된 프로젝트 맥락으로 한 번씩(원 소속 행은 CAROL 에게 없음) snap = req("GET", f"/project/api/projects/{other['id']}/snapshot?scope=all", CAROL).json() rows = [x for x in snap["tasks"] if x["id"] == t["id"]] assert [(x["context_project_id"], x["is_linked"]) for x in rows] == [(other["id"], True)] # 연결 해제 후엔 볼 수 없다 assert req("DELETE", f"/project/api/tasks/{t['id']}/links/{other['id']}", BOB).status_code == 200 assert req("GET", f"/project/api/tasks/{t['id']}", CAROL).status_code == 403 # ════════════════════════════════════════════════════════════ # [03] 파일 댓글 — 원자적 등록·재전송 중복 방지 # ════════════════════════════════════════════════════════════ def test_file_comment_atomic_and_idempotent(): p = _project("P-file", ADMIN, (BOB, CAROL)) s = _stage(p["id"], by=ADMIN) t = ST.create_task(project_id=p["id"], title="files", stage_id=s["id"], created_by=BOB) url = f"/project/api/tasks/{t['id']}/comments/files" n0 = _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) # JSON 경로: 예전 has_attachment 플래그로 빈 댓글을 만들 수 없다 assert req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "", "has_attachment": True}).status_code == 400 # 한 파일이라도 문제면(빈 파일) 아무것도 만들지 않고 어느 파일인지 알려 준다 r = req("POST", url, BOB, files=[("files", ("ok.txt", b"hello", "text/plain")), ("files", ("empty.txt", b"", "text/plain"))]) assert r.status_code == 400 and [f["name"] for f in r.json()["detail"]["failed"]] == ["empty.txt"] assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) == n0 assert not os.path.isdir(os.path.join(DATA_DIR, "project", str(t["id"]))) or \ not os.listdir(os.path.join(DATA_DIR, "project", str(t["id"]))) # 정상: 본문 없이 파일 두 개, 같은 토큰으로 두 번 보내도 한 번만 files = [("files", ("a.png", b"\x89PNG....", "image/png")), ("files", ("b.pdf", b"%PDF-1", "application/pdf"))] r1 = req("POST", url, BOB, data={"client_token": "tok-1"}, files=files) r2 = req("POST", url, BOB, data={"client_token": "tok-1"}, files=files) assert r1.status_code == 201 and r2.status_code == 201 assert r1.json()["comment"]["id"] == r2.json()["comment"]["id"] and r2.json().get("duplicate") cid = r1.json()["comment"]["id"] assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) == n0 + 1 assert _count("SELECT COUNT(*) AS n FROM task_attachments WHERE comment_id=%s", cid) == 2 # DB 저장 실패 → 방금 쓴 파일도 지우고 댓글 없음 orig = ST.add_comment_with_attachments ST.add_comment_with_attachments = lambda **kw: (_ for _ in ()).throw(RuntimeError("db down")) try: before_files = set(os.listdir(os.path.join(DATA_DIR, "project", str(t["id"])))) try: req("POST", url, BOB, files=[("files", ("c.txt", b"data", "text/plain"))]) except RuntimeError: pass # TestClient 가 서버 예외를 그대로 올린다(운영에선 500) assert set(os.listdir(os.path.join(DATA_DIR, "project", str(t["id"])))) == before_files finally: ST.add_comment_with_attachments = orig assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) == n0 + 1 # 남의 댓글에 파일을 붙일 수 없다 r = req("POST", f"/project/api/tasks/{t['id']}/attachments", CAROL, data={"comment_id": str(cid)}, files={"file": ("x.txt", b"x", "text/plain")}) assert r.status_code == 403 # 동시에 같은 토큰 두 개 → 댓글 하나 out = [] ths = [threading.Thread(target=lambda: out.append(req("POST", url, BOB, data={"client_token": "tok-par"}, files=[("files", ("p.txt", b"p", "text/plain"))]).json())) for _ in range(2)] [th.start() for th in ths] [th.join() for th in ths] assert len({o["comment"]["id"] for o in out}) == 1 # ════════════════════════════════════════════════════════════ # [04] 날짜 범위 # ════════════════════════════════════════════════════════════ def test_date_range_validation(): p = _project("P-date", ADMIN, (BOB,)) s = _stage(p["id"], by=ADMIN) base = f"/project/api/projects/{p['id']}/tasks" assert req("POST", base, BOB, json={"title": "bad", "stage_id": s["id"], "start_date": "2026-10-05", "due_date": "2026-10-01"}).status_code == 400 t = req("POST", base, BOB, json={"title": "ok", "stage_id": s["id"], "start_date": "2026-10-01", "due_date": "2026-10-05"}).json()["task"] u = f"/project/api/tasks/{t['id']}" assert req("PUT", u, BOB, json={"due_date": "2026-09-30"}).status_code == 400 # 한쪽만 바꿔도 최종 상태 검사 assert ST.get_task(task_id=t["id"])["due_date"] == "2026-10-05" assert req("PUT", u, BOB, json={"start_date": None}).status_code == 200 # null 로 지우기 assert req("PUT", u, BOB, json={"due_date": "2026-09-30"}).status_code == 200 # 시작일 없으면 허용 assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "18:00", "due_time": "09:00"}).status_code == 400 assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "00:00", "due_time": "23:59"}).status_code == 200 assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "09:00", "due_time": "09:00"}).status_code == 200 # 프로젝트도 같은 규칙(부분 수정 포함) pu = f"/project/api/projects/{p['id']}" assert req("PUT", pu, BOB, json={"start_date": "2026-11-01", "due_date": "2026-10-01"}).status_code == 400 assert req("PUT", pu, BOB, json={"due_date": "2026-10-01"}).status_code == 200 assert req("PUT", pu, BOB, json={"start_date": "2026-11-01"}).status_code == 400 assert req("POST", "/project/api/projects", BOB, json={"name": "d", "start_date": "2026-11-02", "due_date": "2026-11-01"}).status_code == 400 # ════════════════════════════════════════════════════════════ # [11] 완료 섹션에 바로 만든 작업 # ════════════════════════════════════════════════════════════ def test_create_in_done_stage_completes(): p = _project("P-done", ADMIN, (ALICE, BOB)) todo, done = _stage(p["id"], by=ADMIN), _stage(p["id"], name="완료", done=True, by=ADMIN) SENT_MAIL.clear() r = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "done now", "stage_id": done["id"], "assignee_email": ALICE}) t = r.json()["task"] assert t["completed_at"] and "_newly_completed" not in t assert _count("SELECT COUNT(*) AS n FROM project_activity WHERE task_id=%s AND action='completed'", t["id"]) == 1 assert _count("SELECT COUNT(*) AS n FROM project_notifications WHERE task_id=%s AND type='completed' AND recipient_email=%s", t["id"], ALICE) == 1 # 일반 섹션 생성 → 미완료, 완료 섹션으로 이동 → 완료(이력 1건 더), 이탈 → 미완료 t2 = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "later", "stage_id": todo["id"]}).json()["task"] assert not t2["completed_at"] assert req("PUT", f"/project/api/tasks/{t2['id']}", BOB, json={"stage_id": done["id"]}).json()["task"]["completed_at"] assert not req("PUT", f"/project/api/tasks/{t2['id']}", BOB, json={"stage_id": todo["id"]}).json()["task"]["completed_at"] # 섹션 없는 하위 작업: 수동 완료/취소 sub = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "sub", "parent_task_id": t2["id"]}).json()["task"] assert sub["stage_id"] is None and not sub["completed_at"] assert req("PUT", f"/project/api/tasks/{sub['id']}", BOB, json={"completed": True}).json()["task"]["completed_at"] assert not req("PUT", f"/project/api/tasks/{sub['id']}", BOB, json={"completed": False}).json()["task"]["completed_at"] # ════════════════════════════════════════════════════════════ # [15] 마감 알림 — 원자적·재시도·중복 방지·권한 # ════════════════════════════════════════════════════════════ def test_due_reminders_atomic_and_access(): p = _project("P-rem", ADMIN, (ALICE, BOB)) s = _stage(p["id"], by=ADMIN) today = today_kst() t_ok = ST.create_task(project_id=p["id"], title=f"rem-ok-{RUN}", stage_id=s["id"], assignee_email=BOB, due_date=today.isoformat(), created_by=BOB) t_gone = ST.create_task(project_id=p["id"], title=f"rem-gone-{RUN}", stage_id=s["id"], assignee_email=ALICE, due_date=today.isoformat(), created_by=BOB) t_fail = ST.create_task(project_id=p["id"], title=f"FAILME-{RUN}", stage_id=s["id"], assignee_email=BOB, due_date=today.isoformat(), created_by=BOB) ST.remove_member(project_id=p["id"], user_email=ALICE) q = "SELECT COUNT(*) AS n FROM project_notifications WHERE task_id=%s AND type='due_today'" qr = "SELECT COUNT(*) AS n FROM task_reminders WHERE task_id=%s" with ST._pool.connection() as conn: # noqa: SLF001 - 테스트 DB 에서만: 알림 생성 실패 흉내 conn.execute(f"ALTER TABLE project_notifications ADD CONSTRAINT test_fail_{RUN} CHECK (title NOT LIKE '%%FAILME-{RUN}%%')") try: reminders.run_due_reminders(ST, today=today, lookup=USERS.get) assert _count(q, t_ok["id"]) == 1 and _count(q, t_gone["id"]) == 0 assert _count(q, t_fail["id"]) == 0 and _count(qr, t_fail["id"]) == 0 # 실패 → 기록도 되돌려짐 finally: with ST._pool.connection() as conn: # noqa: SLF001 conn.execute(f"ALTER TABLE project_notifications DROP CONSTRAINT test_fail_{RUN}") reminders.run_due_reminders(ST, today=today, lookup=USERS.get) # 재실행: 실패분만 생성 assert _count(q, t_fail["id"]) == 1 and _count(q, t_ok["id"]) == 1 # 동시 실행에도 중복 없음 t_par = ST.create_task(project_id=p["id"], title=f"rem-par-{RUN}", stage_id=s["id"], assignee_email=BOB, due_date=today.isoformat(), created_by=BOB) ths = [threading.Thread(target=reminders.run_due_reminders, args=(ST,), kwargs={"today": today, "lookup": USERS.get}) for _ in range(4)] [th.start() for th in ths] [th.join() for th in ths] assert _count(q, t_par["id"]) == 1 assert _count(q, t_gone["id"]) == 0 and _count(qr, t_gone["id"]) == 0 # ════════════════════════════════════════════════════════════ # [01] 전체 범위 스냅샷 — 다른 프로젝트의 생성·삭제·섹션 변경·권한 회수 # ════════════════════════════════════════════════════════════ def test_snapshot_all_scope(): a = _project("P-sa", ADMIN, (BOB,)) b = _project("P-sb", ADMIN, (BOB,)) sa, sb = _stage(a["id"], by=ADMIN), _stage(b["id"], by=ADMIN) tb = ST.create_task(project_id=b["id"], title="in b", stage_id=sb["id"], created_by=BOB) snap = req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).json() assert {a["id"], b["id"]} <= {x["id"] for x in snap["projects"]} assert any(x["id"] == tb["id"] for x in snap["tasks"]) and str(b["id"]) in snap["stages_by_project"] sb2 = _stage(b["id"], name="new", by=ADMIN) ST.delete_task(task_id=tb["id"], deleted_by=BOB) snap = req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).json() assert not any(x["id"] == tb["id"] for x in snap["tasks"]) assert sb2["id"] in [s["id"] for s in snap["stages_by_project"][str(b["id"])]] ST.remove_member(project_id=b["id"], user_email=BOB) snap = req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).json() assert b["id"] not in {x["id"] for x in snap["projects"]} and str(b["id"]) not in snap["stages_by_project"] ST.remove_member(project_id=a["id"], user_email=BOB) assert req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).status_code == 403 _ = sa def test_store_date_range_unit(): from app.modules.project import store store.validate_date_range(None, "2026-01-01") store.validate_date_range("2026-01-01", None, "10:00", None) store.validate_date_range("2026-01-01", "2026-01-01", "23:59", None) for args in (("2026-01-02", "2026-01-01"), ("2026-01-01", "2026-01-01", "10:01", "10:00")): try: store.validate_date_range(*args) except ValueError: continue raise AssertionError(args) def test_store_goal_merge_unit(): from app.modules.project import store assert store.validate_goal_merge(3, 1) == (1, 3) assert store.validate_goal_merge(7, 12) == (7, 12) assert store.validate_goal_month(13, allow_year=True) == 13 for args in ((6, 7), (3, 3), (0, 2), (11, 13)): try: store.validate_goal_merge(*args) except ValueError: continue raise AssertionError(args) # ════════════════════════════════════════════════════════════ # 연간 목표 — 상·하반기 글 칸 · 월 칸 병합(마이그레이션 014) · 로아스 % 표기 # ════════════════════════════════════════════════════════════ def test_goal_halves_and_merges(): year = 2060 + int(RUN, 16) % 40 ST.delete_goal_year(year=year) if year in ST.list_goal_years() else None assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201 try: board = ST.get_goal_board(year=year) assert board["halves"] is True, "마이그레이션 014 적용 필요" rid = board["areas"][0]["rows"][0]["id"] cell = lambda m, body, who=ADMIN: req( # noqa: E731 "PUT", f"/project/api/goals/rows/{rid}/cells/{m}", who, json={"body": body}) # 상·하반기 글 칸(13·14), 범위 밖(15)은 400, 비관리자는 403 assert cell(13, "상반기 글").status_code == 200 and cell(14, "하반기 글").status_code == 200 assert cell(15, "x").status_code == 400 assert cell(13, "y", BOB).status_code == 403 for m, body in ((2, "이월"), (3, "삼월"), (5, "오월")): assert cell(m, body).status_code == 200 merge = lambda s, e: req( # noqa: E731 "POST", f"/project/api/goals/rows/{rid}/merge", ADMIN, json={"start": s, "end": e}) # 반기를 넘는 병합·한 칸 병합은 400 assert merge(5, 8).status_code == 400 and merge(4, 4).status_code == 400 r = merge(2, 3) assert r.status_code == 200 and r.json() == {"ok": True, "start": 2, "span": 2}, r.text cells = ST.get_goal_board(year=year)["areas"][0]["rows"][0]["cells"] assert cells[2] == "이월\n삼월" and 3 not in cells # 병합된 칸의 가운데 월에 늦게 온 저장은 거절(글은 시작 월에만) assert cell(3, "늦은 저장").status_code == 400 # 걸친 병합은 흡수: 3~5 → 2~5, 글은 월 순서대로 이어진다 r = merge(3, 5) assert r.json() == {"ok": True, "start": 2, "span": 4}, r.text row = ST.get_goal_board(year=year)["areas"][0]["rows"][0] assert row["merges"] == {2: 4} and row["cells"][2] == "이월\n삼월\n오월" and 5 not in row["cells"] assert row["cells"][13] == "상반기 글" and row["cells"][14] == "하반기 글" # 해제 — 글은 시작 월에 남음, 없는 병합 해제는 404 assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/2", ADMIN).status_code == 200 assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/2", ADMIN).status_code == 404 row = ST.get_goal_board(year=year)["areas"][0]["rows"][0] assert row["merges"] == {} and row["cells"][2] == "이월\n삼월\n오월" # 로아스 % 표기(입력에 % 가 있어도 숫자로 저장) r = req("PUT", f"/project/api/goals/{year}/metrics", ADMIN, json={"metric": "roas", "kind": "target", "month": 1, "value": "499%"}) assert r.status_code == 200 and r.json()["label"] == "499%" and r.json()["value"] == 499 r = req("PUT", f"/project/api/goals/{year}/metrics", ADMIN, json={"metric": "sales", "kind": "target", "month": 1, "value": "1,200"}) assert r.json()["label"] == "1,200" # 영역·줄 이름(그 자리 수정이 쓰는 API) — 영역 이름은 빈 값 400, 줄 이름은 빈 값 허용 aid = ST.get_goal_board(year=year)["areas"][0]["id"] assert req("PUT", f"/project/api/goals/areas/{aid}", ADMIN, json={"name": ""}).status_code == 400 assert req("PUT", f"/project/api/goals/areas/{aid}", ADMIN, json={"name": "상품2"}).status_code == 200 assert req("PUT", f"/project/api/goals/rows/{rid}", ADMIN, json={"label": ""}).status_code == 200 finally: ST.delete_goal_year(year=year) if __name__ == "__main__": if not ENABLED: print("SKIP: PROJECT_TEST_DB_URL(localhost) not set") sys.exit(0) n = 0 for name, fn in sorted(globals().items()): if name.startswith("test_") and callable(fn): fn() n += 1 print("ok", name) print(f"{n} tests passed") ST.close() _ = io, timedelta