f36f7d3ad4
- 협업자 = 담당자 외의 멤버: add_followers 가 담당자를 거르고, 담당자 지정 시 같은 트랜잭션에서 협업자에서 뺌, 담당자 협업자 추가는 400 - 마이그레이션 028: 이미 겹친 task_followers 행 정리(스키마 변경 없음, 멱등) - 업무 창 세부 업무 추가 칸: 담당자·협업자·마감일을 동그라미 아이콘 버튼으로, 제목 칸을 넓게 - 내 업무 화면: 줄 클릭 시 화면 이동 없이 오른쪽 업무 창(iframe), 닫으면 목록 다시 받기 - 대시보드 "미완료 업무 합계(섹션별)" 카드 삭제 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
487 lines
24 KiB
Python
487 lines
24 KiB
Python
"""2026-10-12 검토 반영 회귀 테스트 — 권한·링크·조회 범위·저장 실패·동시성·중복 방지. DB 없이 가짜 저장소로.
|
|
|
|
실제 PostgreSQL 이 있어야 확인되는 동시성(두 요청이 정말 동시에 행을 잠그는 경우)은
|
|
tests/test_project_module.py 의 test_review_* 가 맡는다(로컬 테스트 DB 전용).
|
|
"""
|
|
import importlib
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import types
|
|
import unittest
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.responses import HTMLResponse
|
|
from fastapi.testclient import TestClient
|
|
|
|
from app.modules.project import access, store
|
|
from app.modules.project.db import ProjectStore
|
|
from app.store import SUPER_ADMIN_EMAIL
|
|
|
|
api = importlib.import_module("app.modules.project.router")
|
|
|
|
PM = {"email": "pm@test.local", "role": "pro"} # 부모(1)·보관(4) 멤버, 자식(2) 비멤버
|
|
BOTH = {"email": "both@test.local", "role": "user"} # 부모·자식 멤버
|
|
CHILD = {"email": "child@test.local", "role": "user"} # 자식만
|
|
ADMIN = {"email": "admin@test.local", "role": "admin"} # 어디에도 멤버 아님
|
|
SUPER = {"email": SUPER_ADMIN_EMAIL, "role": "admin"}
|
|
READER = {"email": "reader@test.local", "role": "pro"} # 부모(1)·연결 대상(3) 멤버 — 자식 작업 20 은 3 에 연결돼 READ
|
|
|
|
|
|
class Store(MagicMock):
|
|
"""프로젝트 1(부모) ─ 2(서브), 3(다른 프로젝트), 4(보관). 작업 10∈1, 20∈2(3 에 연결), 21∈2."""
|
|
|
|
PROJECTS = {
|
|
1: {"id": 1, "parent_id": None, "name": "부모", "owner_email": "", "status": "active", "created_by": ""},
|
|
2: {"id": 2, "parent_id": 1, "name": "자식", "owner_email": "", "status": "active", "created_by": ""},
|
|
3: {"id": 3, "parent_id": None, "name": "연결", "owner_email": "", "status": "active", "created_by": ""},
|
|
4: {"id": 4, "parent_id": None, "name": "보관", "owner_email": "", "status": "archived", "created_by": ""},
|
|
}
|
|
MEMBERS = {1: {"pm@test.local", "both@test.local", "reader@test.local"},
|
|
2: {"both@test.local", "child@test.local"},
|
|
3: {"reader@test.local"},
|
|
4: {"pm@test.local"}}
|
|
TASKS = {10: {"id": 10, "project_id": 1, "title": "부모 작업", "parent_task_id": None},
|
|
20: {"id": 20, "project_id": 2, "title": "자식 작업(연결)", "parent_task_id": None},
|
|
21: {"id": 21, "project_id": 2, "title": "자식 작업", "parent_task_id": None},
|
|
40: {"id": 40, "project_id": 4, "title": "보관 작업", "parent_task_id": None}}
|
|
LINKS = {20: {3}}
|
|
|
|
def is_member(self, project_id, user_email):
|
|
return user_email in self.MEMBERS.get(int(project_id), set())
|
|
|
|
def list_projects(self, include_archived=False, member_email=None):
|
|
return [dict(p) for pid, p in self.PROJECTS.items()
|
|
if (include_archived or p["status"] != "archived")
|
|
and (member_email is None or member_email in self.MEMBERS.get(pid, set()))]
|
|
|
|
def get_project(self, project_id):
|
|
p = self.PROJECTS.get(int(project_id))
|
|
return dict(p) if p else None
|
|
|
|
def get_task(self, task_id):
|
|
t = self.TASKS.get(int(task_id))
|
|
return dict(t) if t else None
|
|
|
|
def task_link_scope(self, task_ids):
|
|
return {int(t): set(self.LINKS[int(t)]) for t in task_ids if int(t) in self.LINKS}
|
|
|
|
def list_tasks(self, project_id=None, include_subprojects=False, limit=1000, **kw):
|
|
tree = {int(project_id)}
|
|
if include_subprojects:
|
|
tree |= {pid for pid, p in self.PROJECTS.items() if p["parent_id"] in tree}
|
|
return [dict(t) for t in self.TASKS.values() if t["project_id"] in tree]
|
|
|
|
def list_tasks_for_projects(self, project_ids, **kw):
|
|
self.asked_task_projects = list(project_ids)
|
|
out = []
|
|
for pid in project_ids:
|
|
out += [{**t, "context_project_id": pid} for t in self.TASKS.values() if t["project_id"] == pid]
|
|
out += [{**self.TASKS[tid], "context_project_id": pid} for tid, ps in self.LINKS.items() if pid in ps]
|
|
return out
|
|
|
|
def list_stages_for_projects(self, project_ids):
|
|
return {int(i): [] for i in project_ids}
|
|
|
|
def list_stages(self, project_id):
|
|
return []
|
|
|
|
def list_members(self, project_id):
|
|
return [{"user_email": e} for e in sorted(self.MEMBERS.get(int(project_id), set()))]
|
|
|
|
|
|
def client_for(st, data_dir=None):
|
|
app = FastAPI()
|
|
app.include_router(api.router)
|
|
app.state.project_store = st
|
|
app.state.data_dir = data_dir or tempfile.mkdtemp(prefix="pj-review-")
|
|
return TestClient(app, raise_server_exceptions=False)
|
|
|
|
|
|
class Base(unittest.TestCase):
|
|
def setUp(self):
|
|
self.st = Store()
|
|
for p in (patch.object(access, "can_use_module", side_effect=lambda u: bool(u)),):
|
|
p.start()
|
|
self.addCleanup(p.stop)
|
|
self.client = client_for(self.st)
|
|
|
|
def call(self, who, method, url, **kw):
|
|
with patch.object(api, "_require_user", return_value=who), patch.object(api, "_db_or_503", return_value=self.st):
|
|
return self.client.request(method, url, **kw)
|
|
|
|
|
|
# ── [1] 부모 프로젝트 조회로 서브프로젝트 작업이 새지 않는다 ─────────────
|
|
class SubprojectTasksTests(Base):
|
|
def ids(self, who, pid=1):
|
|
r = self.call(who, "GET", f"/project/api/projects/{pid}/tasks")
|
|
return r.status_code, sorted(t["id"] for t in r.json().get("tasks", [])) if r.status_code == 200 else None
|
|
|
|
def test_parent_member_without_child_membership(self):
|
|
self.assertEqual(self.ids(PM), (200, [10]))
|
|
|
|
def test_member_of_both_and_child_member(self):
|
|
self.assertEqual(self.ids(BOTH), (200, [10, 20, 21]))
|
|
self.assertEqual(self.ids(CHILD)[0], 403) # 부모 화면은 못 연다
|
|
self.assertEqual(self.ids(CHILD, pid=2), (200, [20, 21]))
|
|
|
|
def test_non_member_admin_and_super(self):
|
|
self.assertEqual(self.ids(ADMIN)[0], 403)
|
|
self.assertEqual(self.ids(SUPER), (200, [10, 20, 21]))
|
|
|
|
def test_linked_read_task_stays_visible(self):
|
|
# READER 는 자식(2) 멤버가 아니지만 작업 20 이 자기 프로젝트(3)에 연결돼 읽기 권한(READ)
|
|
self.assertEqual(self.ids(READER), (200, [10, 20]))
|
|
self.assertEqual(access.task_access(self.st, READER, self.st.get_task(20)), access.READ)
|
|
|
|
|
|
# ── [2] 사이드바 순서 API — 보낸 id 전부 관리 권한, 이상한 값은 400 ──────────
|
|
class ReorderTests(Base):
|
|
def put(self, who, body):
|
|
self.st.reorder_projects.reset_mock()
|
|
return self.call(who, "PUT", "/project/api/projects/order", json=body).status_code
|
|
|
|
def test_only_manageable_projects(self):
|
|
self.assertEqual(self.put(PM, {"ordered_ids": [4, 1]}), 200)
|
|
self.st.reorder_projects.assert_called_once_with(ordered_ids=[4, 1])
|
|
self.assertEqual(self.put(PM, {"ordered_ids": [1, 3]}), 403) # 3 은 멤버 아님
|
|
self.st.reorder_projects.assert_not_called() # 일부만 바뀌지 않는다
|
|
self.assertEqual(self.put(PM, {"ordered_ids": [999]}), 403) # 없는 id 도 같은 403
|
|
self.assertEqual(self.put(ADMIN, {"ordered_ids": [1]}), 403) # 비멤버 Admin
|
|
self.assertEqual(self.put(SUPER, {"ordered_ids": [3, 1]}), 200)
|
|
self.assertEqual(self.put(SUPER, {"ordered_ids": [999]}), 403)
|
|
self.assertEqual(self.put(BOTH, {"ordered_ids": [1]}), 403) # User 는 등급에서 막힘
|
|
|
|
def test_bad_payloads_are_400(self):
|
|
for body in ({}, {"ordered_ids": []}, {"ordered_ids": "1,2"}, {"ordered_ids": [1, 1]},
|
|
{"ordered_ids": [True]}, {"ordered_ids": ["a"]}, {"ordered_ids": [1.5]},
|
|
{"ordered_ids": [0]}, {"ordered_ids": [None]}):
|
|
with self.subTest(body=body):
|
|
self.assertEqual(self.put(PM, body), 400)
|
|
self.st.reorder_projects.assert_not_called()
|
|
|
|
|
|
# ── [3][4] 작업 열기 경로·보관/서브프로젝트 화면 ─────────────────────────
|
|
class FakeMain(types.ModuleType):
|
|
def __init__(self, who):
|
|
super().__init__("app.main")
|
|
self.who = who
|
|
self.ctx = None
|
|
self.user_store = SimpleNamespace(list_all=lambda: [], get=lambda e: None)
|
|
|
|
def get_current_user_record(self, request):
|
|
return self.who
|
|
|
|
def build_erp_nav(self, user, active=""):
|
|
return []
|
|
|
|
def render_template(self, request, name, ctx, status_code=200):
|
|
self.ctx = ctx
|
|
return HTMLResponse(f"{name}|{ctx.get('reason', '')}", status_code=status_code)
|
|
|
|
|
|
class OpenPathTests(Base):
|
|
def get(self, who, url):
|
|
fake = FakeMain(who)
|
|
with patch.dict(sys.modules, {"app.main": fake}), patch("app.store.has_module", return_value=True):
|
|
r = self.call(who, "GET", url, follow_redirects=False)
|
|
return r, fake
|
|
|
|
def test_permalink_opens_linked_project_for_read_user_and_keeps_embed(self):
|
|
r, _ = self.get(READER, "/project/t/20?embed=1")
|
|
self.assertEqual((r.status_code, r.headers["location"]), (303, "/project/p/3?task=20&embed=1"))
|
|
r, _ = self.get(PM, "/project/t/10")
|
|
self.assertEqual(r.headers["location"], "/project/p/1?task=10")
|
|
r, _ = self.get(ADMIN, "/project/t/20")
|
|
self.assertEqual(r.status_code, 403)
|
|
|
|
def test_old_home_project_url_redirects_read_user(self):
|
|
# 옛 PC 알림 프로그램·북마크(/p/{원 소속}?task=) — 403 대신 읽을 수 있는 연결된 프로젝트로
|
|
r, _ = self.get(READER, "/project/p/2?task=20&embed=1")
|
|
self.assertEqual((r.status_code, r.headers["location"]), (303, "/project/p/3?task=20&embed=1"))
|
|
r, _ = self.get(ADMIN, "/project/p/2?task=20")
|
|
self.assertEqual(r.status_code, 403)
|
|
r, _ = self.get(READER, "/project/p/2")
|
|
self.assertEqual(r.status_code, 403)
|
|
|
|
def test_archived_project_page_reads_its_own_tasks_only(self):
|
|
r, fake = self.get(PM, "/project/p/4")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(self.st.asked_task_projects, [1, 4]) # 활성 최상위(1) + 지금 연 보관 프로젝트(4)만
|
|
self.assertIn(40, [t["id"] for t in fake.ctx["tasks"]])
|
|
metas = {p["id"]: p for p in fake.ctx["projects_meta"]}
|
|
self.assertTrue(metas[4]["view_only"]) # 화면용 — 사이드바 목록에는 없다
|
|
self.assertNotIn(4, [p["id"] for p in fake.ctx["nav_projects"]])
|
|
|
|
def test_snapshot_matches_first_page_scope(self):
|
|
r = self.call(PM, "GET", "/project/api/projects/4/snapshot?scope=all")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
out = r.json()
|
|
self.assertEqual(self.st.asked_task_projects, [1, 4])
|
|
self.assertIn(40, [t["id"] for t in out["tasks"]])
|
|
self.assertEqual([p["id"] for p in out["projects"] if p.get("view_only")], [4])
|
|
|
|
def test_subproject_page_includes_its_tasks(self):
|
|
r, fake = self.get(BOTH, "/project/p/2")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(self.st.asked_task_projects, [1, 2]) # 최상위 멤버 프로젝트(1) + 지금 연 서브프로젝트(2)
|
|
self.assertEqual(sorted(t["id"] for t in fake.ctx["tasks"] if t["context_project_id"] == 2), [20, 21])
|
|
|
|
|
|
# ── [8] 일반 첨부 — DB 저장 실패면 이 요청이 쓴 파일만 지운다 ─────────────
|
|
class AttachmentCleanupTests(Base):
|
|
def test_db_failure_removes_only_new_file(self):
|
|
data_dir = tempfile.mkdtemp(prefix="pj-att-")
|
|
self.client = client_for(self.st, data_dir)
|
|
old = Path(data_dir) / "project" / "10"
|
|
old.mkdir(parents=True)
|
|
(old / "existing.bin").write_bytes(b"keep")
|
|
self.st.add_attachment.side_effect = RuntimeError("db down")
|
|
r = self.call(PM, "POST", "/project/api/tasks/10/attachments", files={"file": ("a.txt", b"hello", "text/plain")})
|
|
self.assertEqual(r.status_code, 500)
|
|
self.assertEqual(sorted(p.name for p in old.iterdir()), ["existing.bin"])
|
|
self.st.add_attachment.side_effect = None
|
|
self.st.add_attachment.return_value = {"id": 1}
|
|
r = self.call(PM, "POST", "/project/api/tasks/10/attachments", files={"file": ("a.txt", b"hello", "text/plain")})
|
|
self.assertEqual(r.status_code, 201)
|
|
self.assertEqual(len(list(old.iterdir())), 2)
|
|
# 빈 파일·권한은 그대로
|
|
self.assertEqual(self.call(PM, "POST", "/project/api/tasks/10/attachments",
|
|
files={"file": ("e.txt", b"", "text/plain")}).status_code, 400)
|
|
self.assertEqual(self.call(CHILD, "POST", "/project/api/tasks/10/attachments",
|
|
files={"file": ("a.txt", b"x", "text/plain")}).status_code, 403)
|
|
|
|
|
|
# ── [10] 배지 개수 — 제한 없이, 지금 권한으로 ─────────────────────────────
|
|
class BadgeCountTests(Base):
|
|
def test_my_open_count_is_exact_past_old_limit(self):
|
|
self.st.list_my_open_refs.return_value = (
|
|
[{"id": i, "project_id": 1} for i in range(1, 1501)] + [{"id": 5000 + i, "project_id": 2} for i in range(10)])
|
|
self.assertEqual(api._my_open_count(self.st, PM), 1500) # 2(비멤버)의 10건은 빼고
|
|
self.assertEqual(api._my_open_count(self.st, BOTH), 1510)
|
|
|
|
def test_unread_notification_count_is_exact(self):
|
|
self.st.list_unread_refs.return_value = (
|
|
[{"id": i, "project_id": 1, "task_id": 10} for i in range(700)] + [{"id": 900, "project_id": 2, "task_id": 21}])
|
|
self.assertEqual(api._notification_unread(self.st, PM), 700)
|
|
self.assertEqual(api._notification_unread(self.st, BOTH), 701)
|
|
|
|
def test_unread_mentions_count_filters_by_current_access(self):
|
|
self.st.list_unread_mention_refs.return_value = [
|
|
{"id": 10, "project_id": 1, "unread_mentions": 3}, {"id": 21, "project_id": 2, "unread_mentions": 4}]
|
|
self.assertEqual(api._safe_mention_unread(self.st, PM), 3)
|
|
self.assertEqual(api._safe_mention_unread(self.st, BOTH), 7)
|
|
|
|
|
|
# ── [13] 남을 소유자로 지정해 만들면 만든 사람은 명시적 멤버로 ───────────────
|
|
class CreatorMemberTests(Base):
|
|
def test_creator_added_as_member_only_when_owner_is_someone_else(self):
|
|
self.st.create_project.return_value = {"id": 9, "name": "n"}
|
|
with patch.object(api, "_check_owner_candidate"):
|
|
self.call(PM, "POST", "/project/api/projects", json={"name": "n", "owner_email": "other@test.local"})
|
|
kw = self.st.create_project.call_args.kwargs
|
|
self.assertEqual((kw["owner_email"], kw["member_emails"]), ("other@test.local", ["pm@test.local"]))
|
|
self.call(PM, "POST", "/project/api/projects", json={"name": "n"})
|
|
kw = self.st.create_project.call_args.kwargs
|
|
self.assertEqual((kw["owner_email"], kw["member_emails"]), ("pm@test.local", []))
|
|
|
|
|
|
# ── [14] 중복 방지 키 — 실패·성공·동시 요청에서 잠금이 남지 않는다 ───────────
|
|
class OnceTests(unittest.TestCase):
|
|
USER = {"email": "me@test.local"}
|
|
|
|
def setUp(self):
|
|
api._once_results.clear()
|
|
api._once_key_locks.clear()
|
|
|
|
def test_failure_releases_lock_and_retry_runs_again(self):
|
|
calls = []
|
|
|
|
def boom():
|
|
calls.append(1)
|
|
raise RuntimeError("x")
|
|
with self.assertRaises(RuntimeError):
|
|
api._once(self.USER, 1, "tok", boom)
|
|
self.assertEqual(api._once_key_locks, {}) # 실패한 키의 잠금이 남지 않는다
|
|
out = api._once(self.USER, 1, "tok", lambda: {"ok": 1})
|
|
self.assertEqual((out, len(calls)), ({"ok": 1}, 1))
|
|
self.assertEqual(api._once(self.USER, 1, "tok", lambda: {"ok": 2}), {"ok": 1, "duplicate": True}) # 응답 유실 후 재전송
|
|
self.assertEqual(api._once_key_locks, {})
|
|
|
|
def test_concurrent_same_token_runs_once(self):
|
|
started, release, runs, outs = threading.Event(), threading.Event(), [], []
|
|
|
|
def slow():
|
|
runs.append(1)
|
|
started.set()
|
|
release.wait(2)
|
|
return {"id": 7}
|
|
th = [threading.Thread(target=lambda: outs.append(api._once(self.USER, 1, "same", slow))) for _ in range(5)]
|
|
th[0].start()
|
|
started.wait(2)
|
|
for t in th[1:]:
|
|
t.start()
|
|
time.sleep(0.05)
|
|
self.assertEqual(api._once_key_locks[("me@test.local", 1, "same")][1], 5) # 기다리는 요청이 있는 동안 유지
|
|
release.set()
|
|
for t in th:
|
|
t.join(2)
|
|
self.assertEqual(len(runs), 1)
|
|
self.assertEqual(sorted(bool(o.get("duplicate")) for o in outs), [False, True, True, True, True])
|
|
self.assertEqual(api._once_key_locks, {})
|
|
|
|
def test_expired_results_are_purged(self):
|
|
api._once(self.USER, 1, "old", lambda: {"ok": 1})
|
|
with patch.object(api.time, "monotonic", return_value=time.monotonic() + api._ONCE_TTL_SEC + 1):
|
|
api._once(self.USER, 1, "new", lambda: {"ok": 2})
|
|
self.assertNotIn(("me@test.local", 1, "old"), api._once_results)
|
|
|
|
|
|
# ── [B] 섹션 기본 담당자 — 지금 권한(등록·project 권한)도 통과해야 자동 배정 ──────
|
|
class _Res:
|
|
def __init__(self, rows):
|
|
self.rows = list(rows)
|
|
|
|
def fetchone(self):
|
|
return self.rows[0] if self.rows else None
|
|
|
|
def fetchall(self):
|
|
return self.rows
|
|
|
|
|
|
class StageDefaultAssigneeTests(unittest.TestCase):
|
|
def conn(self):
|
|
def execute(sql, params=()):
|
|
if "to_jsonb(s)" in sql:
|
|
return _Res([{"e": "Gone@Test.local"}])
|
|
if "FROM project_members" in sql:
|
|
return _Res([{"user_name": "Gone"}])
|
|
raise AssertionError(sql)
|
|
return SimpleNamespace(execute=execute)
|
|
|
|
def test_revoked_or_deleted_user_is_not_auto_assigned(self):
|
|
self.assertEqual(ProjectStore._stage_default_assignee(self.conn(), 5, 1), ("gone@test.local", "Gone"))
|
|
self.assertEqual(ProjectStore._stage_default_assignee(self.conn(), 5, 1, allowed=lambda e: False), ("", ""))
|
|
self.assertEqual(ProjectStore._stage_default_assignee(self.conn(), 5, 1, allowed=lambda e: True),
|
|
("gone@test.local", "Gone"))
|
|
|
|
def test_router_check_uses_user_registry_and_module(self):
|
|
with patch.object(access, "default_user_lookup", return_value=None):
|
|
self.assertFalse(api._registered_project_user("x@test.local"))
|
|
with patch.object(access, "default_user_lookup", return_value={"email": "x@test.local"}), \
|
|
patch.object(access, "can_use_module", return_value=False):
|
|
self.assertFalse(api._registered_project_user("x@test.local"))
|
|
with patch.object(access, "default_user_lookup", return_value={"email": "x@test.local"}), \
|
|
patch.object(access, "can_use_module", return_value=True):
|
|
self.assertTrue(api._registered_project_user("x@test.local"))
|
|
|
|
|
|
# ── [11] 작업 수정 — 잠근 행으로 검사, 같은 연결, 실제 전환 기준 알림 힌트 ────────
|
|
class TaskConn:
|
|
"""tasks 한 행 + 섹션. FOR UPDATE 로 읽힌 '지금 값'이 검사·알림 기준이어야 한다."""
|
|
|
|
def __init__(self, row):
|
|
self.row = dict(row)
|
|
self.depth, self.locked, self.updates, self.logs = 0, False, [], []
|
|
self.unfollowed = [] # 담당자가 되면 협업자에서 뺀다(2026-10-13) — 같은 트랜잭션·잠근 행에서
|
|
self.stages = {11: {"project_id": 1, "is_done_stage": False, "dae": "dae@test.local"},
|
|
12: {"project_id": 1, "is_done_stage": True, "dae": ""}}
|
|
|
|
@contextmanager
|
|
def transaction(self):
|
|
self.depth += 1
|
|
try:
|
|
yield
|
|
finally:
|
|
self.depth -= 1
|
|
self.locked = False
|
|
|
|
def execute(self, sql, params=()):
|
|
if sql.startswith("SELECT * FROM tasks WHERE id = %s FOR UPDATE"):
|
|
assert self.depth > 0
|
|
self.locked = True
|
|
return _Res([dict(self.row)])
|
|
if sql.startswith("SELECT 1 FROM project_stages WHERE id = %s AND project_id = %s"):
|
|
s = self.stages.get(params[0])
|
|
return _Res([{"?": 1}] if s and s["project_id"] == params[1] else [])
|
|
if "to_jsonb(s)" in sql:
|
|
return _Res([{"e": self.stages[params[0]]["dae"]}])
|
|
if "FROM project_members" in sql:
|
|
return _Res([{"user_name": "Dae"}])
|
|
if sql.startswith("SELECT is_done_stage FROM project_stages"):
|
|
return _Res([{"is_done_stage": self.stages[params[0]]["is_done_stage"]}])
|
|
if sql.startswith("UPDATE tasks SET"):
|
|
assert self.locked, "변경은 잠근 행에"
|
|
self.updates.append((sql, params))
|
|
return _Res([])
|
|
if sql.startswith("INSERT INTO project_activity"):
|
|
self.logs.append(params)
|
|
return _Res([])
|
|
if sql.startswith("SELECT to_regclass"):
|
|
return _Res([{"r": params[0]}])
|
|
if sql.startswith("DELETE FROM task_followers"):
|
|
assert self.locked, "협업자 정리도 잠근 행의 트랜잭션에서"
|
|
self.unfollowed.append(params[1])
|
|
return _Res([])
|
|
raise AssertionError(sql)
|
|
|
|
|
|
class UpdateTaskConcurrencyTests(unittest.TestCase):
|
|
def make(self, row, stale=None):
|
|
self.conn = TaskConn(row)
|
|
self.borrows = 0
|
|
|
|
@contextmanager
|
|
def connection():
|
|
self.borrows += 1
|
|
yield self.conn
|
|
|
|
st = ProjectStore.__new__(ProjectStore)
|
|
st._pool = SimpleNamespace(connection=connection)
|
|
# 잠그기 전 다른 연결로 읽은 옛 값(예전 코드가 검사에 쓰던 값) — 이제는 결과 표시에만 쓰인다
|
|
st.get_task = lambda task_id: {**(stale or self.conn.row), "id": task_id}
|
|
return st
|
|
|
|
BASE = {"id": 7, "project_id": 1, "stage_id": 11, "title": "t", "assignee_email": "", "completed_at": None,
|
|
"start_date": "2026-10-10", "due_date": "2026-10-20", "start_time": None, "due_time": None}
|
|
|
|
def test_date_check_uses_locked_current_row(self):
|
|
# A 가 시작일을 10/18 로 이미 바꿨다(잠근 행) — B 의 마감일 10/12 는 옛 값(10/10)으론 통과했지만 이제 거절
|
|
st = self.make({**self.BASE, "start_date": "2026-10-18"}, stale=self.BASE)
|
|
with self.assertRaises(ValueError):
|
|
st.update_task(task_id=7, fields={"due_date": "2026-10-12"})
|
|
self.assertEqual(self.conn.updates, [])
|
|
st.update_task(task_id=7, fields={"due_date": "2026-10-25"})
|
|
self.assertEqual(len(self.conn.updates), 1)
|
|
self.assertEqual(self.borrows, 2) # 요청마다 연결 하나(get_task 대역 제외) — 트랜잭션 안에서 다시 빌리지 않는다
|
|
|
|
def test_second_completion_is_not_a_new_transition(self):
|
|
st = self.make({**self.BASE, "completed_at": "2026-10-11T10:00:00+09:00"})
|
|
out = st.update_task(task_id=7, fields={"completed": True}, actor="b@test.local")
|
|
self.assertFalse(out["_newly_completed"])
|
|
self.assertEqual((self.conn.updates, self.conn.logs), ([], []))
|
|
|
|
def test_stage_move_default_assignee_and_done_in_same_connection(self):
|
|
st = self.make({**self.BASE, "stage_id": 12})
|
|
asked = []
|
|
out = st.update_task(task_id=7, fields={"stage_id": 11}, actor="a@test.local",
|
|
assignee_allowed=lambda e: asked.append(e) or True)
|
|
self.assertEqual((asked, out["_newly_assigned"], self.borrows), (["dae@test.local"], "dae@test.local", 1))
|
|
self.assertEqual(self.conn.unfollowed, ["dae@test.local"]) # 새 담당자는 협업자에서 빠진다
|
|
st = self.make({**self.BASE, "stage_id": 12})
|
|
out = st.update_task(task_id=7, fields={"stage_id": 11}, assignee_allowed=lambda e: False)
|
|
self.assertIsNone(out["_newly_assigned"]) # 권한을 잃은 기본 담당자는 자동 배정·배정 알림 없음
|
|
st = self.make(self.BASE)
|
|
out = st.update_task(task_id=7, fields={"stage_id": 12})
|
|
self.assertTrue(out["_newly_completed"])
|
|
self.assertEqual(len(self.conn.logs), 1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|