fix(project): 권한 우회·작업 혼선·저장 유실 등 16개 항목 수정 — 지금 권한 기준·읽기 전용 연결 작업·원자적 파일 댓글
권한(서버) - 공통 권한 모듈 access.py: 모든 판단을 "지금" 권한으로 — 내 작업·수신함·알림·멘션·검색·상세·공유 링크· 댓글·첨부·알림/메일 수신자에서 권한을 잃은 사람 제외(기록은 이력으로 보존) - 소유자 변경·남을 소유자로 지정한 생성은 관리자만, 새 소유자는 권한 있는 등록 사용자 - 삭제는 생성자 규칙 + 지금 권한(멤버에서 빠진 생성자 거절), 댓글 수정·삭제도 지금 권한 - @태그는 볼 수 있는 사람만(mention_skipped), 태그 후보 all-users?task_id=, 새 담당자 권한 검사 - 연결(멀티호밍) 작업은 연결된 프로젝트 멤버에게 읽기 전용(task_link_scope), 볼 수 없는 연결 프로젝트 숨김 저장·동기화(화면) - 작업 창 세대(taskGen)·블록 ctxSeq 로 늦은 A 응답이 B 를 덮지 않게(A→B, A→B→A, 이미지 업로드 중 전환) - 자동 저장 성공/실패 반환, 실패 칸 재시도, 닫기·전환 전 저장 확인(버리기/계속 편집), 미저장 이탈 경고 - 실시간 동기화 observed/applied 분리·실패 재시도·겹침 방지, snapshot?scope=all 로 전체 범위 반영·권한 회수 안내 - 한국시간 기준 오늘(kstTodayIso), 한글 조합 중 Enter 는 제출하지 않음, 댓글 연타·재전송 중복 방지(client_token) 기타 - 파일 댓글은 본문+파일 한 트랜잭션(POST /comments/files), 실패 파일 표시·유지, 작업 창 댓글에 첨부 표시 - 날짜 범위 검증(부분 수정은 최종 상태), 완료 섹션에 바로 만든 작업 완료 처리·알림 - 마감 알림 발송 기록+수신함 알림 원자적(실패 시 재시도), 권한 없는 수신자 제외 - 테스트: tests/test_project_module.py(로컬 PostgreSQL 11개), tests/js/project_ui.test.js(jsdom 51개) - 문서(PROJECT_MODULE 6-10·도움말·CLAUDE.md), project.js/css 캐시 버전 20260930g, 새 마이그레이션·환경변수 없음 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,425 @@
|
||||
// 프로젝트 관리 화면(project/project.html + static/project.js) UI 회귀 테스트 — jsdom.
|
||||
// 서버 응답은 가짜(fetch 대체)로, 지연·실패·순서 역전을 직접 만든다. 실제 브라우저 레이아웃·입력기는 아니다.
|
||||
//
|
||||
// python tests/js/render_project.py # 템플릿 렌더 → tests/js/.out/project_render.html
|
||||
// npm install jsdom # (최초 1회)
|
||||
// TZ=America/Los_Angeles node tests/js/project_ui.test.js # 해외 시간대 브라우저 흉내
|
||||
//
|
||||
// 성공하면 마지막 줄 ALL PASS, 실패하면 항목명과 종료코드 1.
|
||||
// Git Bash 는 윈도우 프로그램에 TZ 를 넘기지 않아 PJ_TEST_TZ 로도 받는다(날짜 객체를 만들기 전에 설정).
|
||||
if (process.env.PJ_TEST_TZ) process.env.TZ = process.env.PJ_TEST_TZ;
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { JSDOM } = require("jsdom");
|
||||
const WATCHDOG = setTimeout(function () { console.log("TIMEOUT — 어딘가에서 멈춤"); process.exit(2); }, 90000);
|
||||
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const html = fs.readFileSync(path.join(__dirname, ".out", "project_render.html"), "utf8");
|
||||
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
|
||||
|
||||
const fails = [];
|
||||
function check(name, cond, extra) {
|
||||
if (cond) console.log("PASS " + name);
|
||||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||||
}
|
||||
|
||||
function deferred() {
|
||||
let resolve, reject;
|
||||
const p = new Promise(function (a, b) { resolve = a; reject = b; });
|
||||
return { promise: p, resolve: resolve, reject: reject };
|
||||
}
|
||||
|
||||
function makeEnv() {
|
||||
const dom = new JSDOM(html, { runScripts: "dangerously", pretendToBeVisual: true, url: "http://localhost/project/p/1" });
|
||||
const w = dom.window, d = w.document;
|
||||
w.__PJ_TEST__ = true;
|
||||
w.HTMLCanvasElement.prototype.getContext = function () { return null; };
|
||||
w.URL.createObjectURL = function () { return "blob:x"; };
|
||||
w.URL.revokeObjectURL = function () {};
|
||||
w.Image = function () { const self = this; Object.defineProperty(self, "src", { set: function () { setTimeout(function () { if (self.onerror) self.onerror(); }, 0); } }); };
|
||||
w.console.error = function () {};
|
||||
let confirmAnswer = false;
|
||||
w.erpConfirm = function () { env.confirms++; return Promise.resolve(confirmAnswer); };
|
||||
w.erpAlert = function (m) { env.alerts.push(m); };
|
||||
w.alert = function (m) { env.alerts.push(m); };
|
||||
// 8초 이상 타이머(실시간 새로고침)는 붙잡아 두고 테스트가 직접 돌린다.
|
||||
const realSetTimeout = w.setTimeout.bind(w);
|
||||
const slow = [];
|
||||
w.setTimeout = function (fn, ms) {
|
||||
if (ms >= 8000) { slow.push({ fn: fn, ms: ms }); return 999000 + slow.length; }
|
||||
return realSetTimeout(fn, ms);
|
||||
};
|
||||
const env = {
|
||||
w: w, d: d, calls: [], routes: [], slow: slow, confirms: 0, alerts: [],
|
||||
setConfirm: function (v) { confirmAnswer = v; },
|
||||
route: function (method, re, fn) { env.routes.unshift({ method: method, re: re, fn: fn }); },
|
||||
runSlow: async function () { const t = slow.shift(); if (t) { t.fn(); await settle(); } return t; },
|
||||
};
|
||||
w.fetch = async function (url, opts) {
|
||||
const method = (opts && opts.method) || "GET";
|
||||
let body = opts && opts.body;
|
||||
if (typeof body === "string") { try { body = JSON.parse(body); } catch (_) {} }
|
||||
env.calls.push({ method: method, url: String(url), body: body });
|
||||
if (process.env.PJ_TEST_TRACE && method === "PUT") console.log(" TRACE PUT", url, new Error().stack.split("\n").slice(2, 7).join(" | "));
|
||||
for (const r of env.routes) {
|
||||
if (r.method === method && r.re.test(String(url))) {
|
||||
const out = await r.fn(String(url), body);
|
||||
if (out === "NETWORK") throw new TypeError("Failed to fetch");
|
||||
const status = out.status || 200;
|
||||
return { ok: status < 400, status: status, statusText: "x", json: async function () { return out.body; } };
|
||||
}
|
||||
}
|
||||
return { ok: true, status: 200, statusText: "OK", json: async function () { return {}; } };
|
||||
};
|
||||
return env;
|
||||
}
|
||||
|
||||
function settle(n) {
|
||||
return new Promise(function (r) { let i = 0; (function spin() { if (i++ >= (n || 30)) return r(); setImmediate(spin); })(); });
|
||||
}
|
||||
|
||||
function detail(id, title, extra) {
|
||||
return Object.assign({ id: id, title: title, project_id: 1, stage_id: 11, description: "", priority: "normal",
|
||||
assignee_email: "", subtasks: [], links: [], followers: [], access: "full", completed_at: null }, extra || {});
|
||||
}
|
||||
|
||||
function baseRoutes(env) {
|
||||
env.route("GET", /\/project\/api\/tasks\/\d+\/attachments/, function () { return { body: { attachments: [] } }; });
|
||||
env.route("GET", /\/project\/api\/tasks\/\d+\/comments/, function () { return { body: { comments: [], events: [], features: {} } }; });
|
||||
env.route("GET", /\/project\/api\/projects\/\d+\/members/, function () { return { body: { members: [{ user_email: "me@test.local" }] } }; });
|
||||
env.route("GET", /\/project\/api\/projects$/, function () { return { body: { projects: [] } }; });
|
||||
env.route("GET", /\/project\/api\/all-users/, function () { return { body: { users: [] } }; });
|
||||
env.route("GET", /\/project\/api\/live-version/, function () { return { body: { ts: "v1" } }; });
|
||||
env.route("GET", /\/project\/api\/tasks\/101$/, function () { return { body: { task: detail(101, "작업 A") } }; });
|
||||
env.route("GET", /\/project\/api\/tasks\/102$/, function () { return { body: { task: detail(102, "작업 B") } }; });
|
||||
}
|
||||
|
||||
async function boot(env) {
|
||||
// jsdom 이 문서를 다 읽고 DOMContentLoaded 를 보낸 뒤에 넣는다 — 먼저 넣으면 초기화가 두 번 돈다.
|
||||
if (env.d.readyState === "loading") {
|
||||
await new Promise(function (r) { env.d.addEventListener("DOMContentLoaded", r); });
|
||||
}
|
||||
// jsdom 의 <select>·일부 입력은 내부 Proxy 라 value 를 재정의(enhance*)하면 쓰기가 막힌다(실제 브라우저는
|
||||
// 문제없음, 기존 코드 그대로). 테스트에서는 버튼 보강을 건너뛰고 원래 입력칸으로 시험한다.
|
||||
env.d.querySelectorAll("select").forEach(function (s) { s.dataset.pjEnhanced = "1"; });
|
||||
env.d.querySelectorAll("input[type=date]").forEach(function (i) { i.dataset.pjDate = "1"; });
|
||||
env.w.eval(JS);
|
||||
env.d.dispatchEvent(new env.w.Event("DOMContentLoaded"));
|
||||
await settle();
|
||||
return env.w.__pjProject;
|
||||
}
|
||||
|
||||
function taskOf(P, id) { return P.state().tasks.find(function (t) { return t.id === id && t.context_project_id === 1; }); }
|
||||
function subsText(d) { // 하위 작업 제목은 입력칸 값이다
|
||||
return Array.from(d.querySelectorAll("#pj-subtask-list .pj-subtask-title")).map(function (i) { return i.value; }).join("|") ||
|
||||
d.getElementById("pj-subtask-list").textContent;
|
||||
}
|
||||
function wait(ms) { return new Promise(function (r) { setTimeout(r, ms); }); } // 창 닫기 애니메이션(0.32초) 대기
|
||||
function titleVal(d) { return d.getElementById("pj-t-title").value; }
|
||||
|
||||
(async function () {
|
||||
// ── [05] 한국시간 기준 오늘 ─────────────────────────────
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env); await boot(env);
|
||||
const H = env.w.__pjHelpers;
|
||||
const kst = function (y, m, d, hh, mm) { return Date.UTC(y, m - 1, d, hh - 9, mm); };
|
||||
check("[05] KST 00:00 → 그날", H.kstTodayIso(kst(2026, 9, 30, 0, 0)) === "2026-09-30");
|
||||
check("[05] KST 08:59(UTC 전날) → 그날", H.kstTodayIso(kst(2026, 9, 30, 8, 59)) === "2026-09-30");
|
||||
check("[05] KST 09:00 → 그날", H.kstTodayIso(kst(2026, 9, 30, 9, 0)) === "2026-09-30");
|
||||
check("[05] KST 23:59 → 그날", H.kstTodayIso(kst(2026, 9, 30, 23, 59)) === "2026-09-30");
|
||||
const realNow = env.w.Date.now;
|
||||
env.w.Date.now = function () { return kst(2026, 9, 30, 8, 30); };
|
||||
const y = H.dueInfo("2026-09-29", false), t = H.dueInfo("2026-09-30", false);
|
||||
check("[05] 해외 시간대(" + (process.env.TZ || "기본") + ")·한국 오전에도 전날 마감=지남", y.cls === "is-overdue" && y.text === "어제", y);
|
||||
check("[05] 오늘 마감은 지남이 아님", t.cls === "is-soon" && t.text === "오늘", t);
|
||||
env.w.Date.now = realNow;
|
||||
}
|
||||
|
||||
// ── [09] A→B 전환 중 늦은 A 응답이 B 를 덮지 않는다 ───────────
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const dA = deferred();
|
||||
env.route("GET", /\/project\/api\/tasks\/101$/, function () { return dA.promise; });
|
||||
env.route("GET", /\/project\/api\/tasks\/102$/, function () { return { body: { task: detail(102, "작업 B", { subtasks: [{ id: 902, title: "B-sub", project_id: 1 }] }) } }; });
|
||||
const P = await boot(env); const d = env.d;
|
||||
await P.openTaskModal(taskOf(P, 101));
|
||||
await P.openTaskModal(taskOf(P, 102));
|
||||
await settle();
|
||||
dA.resolve({ body: { task: detail(101, "작업 A", { subtasks: [{ id: 901, title: "A-sub", project_id: 1 }] }) } });
|
||||
await settle();
|
||||
check("[09] 늦은 A 상세가 B 의 하위 작업 목록을 덮지 않음", subsText(d).includes("B-sub") && !subsText(d).includes("A-sub"), subsText(d));
|
||||
env.route("POST", /\/project\/api\/projects\/1\/tasks$/, function (u, b) { return { status: 201, body: { task: detail(903, b.title, { parent_task_id: b.parent_task_id }) } }; });
|
||||
d.getElementById("pj-subtask-input").value = "새 하위";
|
||||
d.getElementById("pj-subtask-add").click();
|
||||
await settle();
|
||||
const post = env.calls.filter(function (c) { return c.method === "POST" && /projects\/1\/tasks$/.test(c.url); }).pop();
|
||||
check("[09] B 화면에서 추가한 하위 작업은 B 에 붙음", post && post.body.parent_task_id === 102, post && post.body);
|
||||
}
|
||||
// A→B→A — 같은 작업을 다시 열어도 이전 요청은 버린다
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const dOld = deferred(); let n = 0;
|
||||
env.route("GET", /\/project\/api\/tasks\/101$/, function () {
|
||||
n++;
|
||||
if (n === 1) return dOld.promise;
|
||||
return { body: { task: detail(101, "작업 A", { subtasks: [{ id: 911, title: "A-new", project_id: 1 }] }) } };
|
||||
});
|
||||
const P = await boot(env); const d = env.d;
|
||||
await P.openTaskModal(taskOf(P, 101));
|
||||
await P.openTaskModal(taskOf(P, 102));
|
||||
await P.openTaskModal(taskOf(P, 101));
|
||||
await settle();
|
||||
dOld.resolve({ body: { task: detail(101, "작업 A", { subtasks: [{ id: 910, title: "A-old", project_id: 1 }] }) } });
|
||||
await settle();
|
||||
check("[09] A→B→A 에서 첫 A 의 늦은 응답은 버림", subsText(d).includes("A-new") && !subsText(d).includes("A-old"), subsText(d));
|
||||
}
|
||||
// 이미지 업로드 중 A→B 전환 — 업로드가 끝나 A 설명에 들어가고 저장된 뒤에 B 가 열린다
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const up = deferred();
|
||||
env.route("POST", /\/project\/api\/tasks\/101\/attachments$/, function () { return up.promise; });
|
||||
env.route("PUT", /\/project\/api\/tasks\/101$/, function (u, b) { return { body: { task: Object.assign(detail(101, "작업 A"), b) } }; });
|
||||
const P = await boot(env); const d = env.d;
|
||||
await P.openTaskModal(taskOf(P, 101));
|
||||
await settle();
|
||||
const box = d.getElementById("pj-t-desc");
|
||||
const file = new env.w.File(["x"], "a.png", { type: "image/png" });
|
||||
const ev = new env.w.Event("paste", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(ev, "clipboardData", { value: { items: [{ type: "image/png", getAsFile: function () { return file; } }], getData: function () { return ""; } } });
|
||||
box.dispatchEvent(ev);
|
||||
await settle();
|
||||
const switching = P.openTaskModal(taskOf(P, 102));
|
||||
await settle();
|
||||
check("[09] 업로드 중에는 B 로 넘어가지 않고 기다림", d.getElementById("pj-t-id").value === "101");
|
||||
up.resolve({ status: 201, body: { attachment: { id: 55 } } });
|
||||
await switching; await settle();
|
||||
const put = env.calls.filter(function (c) { return c.method === "PUT" && /tasks\/101$/.test(c.url) && c.body.description; }).pop();
|
||||
check("[09] 업로드된 이미지는 A 설명에 넣어 A 에 저장", !!put && put.body.description.includes("/attachments/55/inline"), put && put.body);
|
||||
check("[09] 그 다음 B 가 열리고 B 설명엔 이미지 없음", d.getElementById("pj-t-id").value === "102" && !box.innerHTML.includes("/attachments/55/"));
|
||||
}
|
||||
|
||||
// ── [10] 저장 실패 후 닫기 — 유실 없이 재시도/버리기 선택 ─────────
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
let putStatus = 500; const puts = [];
|
||||
env.route("PUT", /\/project\/api\/tasks\/101$/, function (u, b) {
|
||||
puts.push(b);
|
||||
return putStatus >= 400 ? { status: putStatus, body: { detail: "서버 오류" } } : { body: { task: Object.assign(detail(101, "작업 A"), b) } };
|
||||
});
|
||||
const P = await boot(env); const d = env.d; const modal = d.getElementById("pj-modal-task");
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
const ta = d.getElementById("pj-t-title");
|
||||
ta.value = "작업 A2"; ta.dispatchEvent(new env.w.Event("blur")); await settle();
|
||||
check("[10] 실패한 칸 기록 + '저장 실패 · 다시 시도' 표시", P.state().failed.includes("title") && d.getElementById("pj-autosave-state").textContent.includes("저장 실패"), P.state().failed);
|
||||
check("[10] 저장 안 된 상태면 페이지 이탈 경고 대상", P.state().unsaved === true);
|
||||
env.setConfirm(false); // 계속 편집
|
||||
await P.attemptClose(); await settle();
|
||||
check("[10] 닫기 때 재시도해도 실패 → 묻고, '계속 편집'이면 창·입력 유지", !modal.hidden && titleVal(d) === "작업 A2" && env.confirms === 1);
|
||||
putStatus = 200;
|
||||
await P.attemptClose(); await settle(); await wait(400);
|
||||
check("[10] 다시 닫기 → 재시도 성공 후 닫힘", modal.hidden && puts[puts.length - 1].title === "작업 A2", { hidden: modal.hidden, last: puts[puts.length - 1] });
|
||||
check("[10] 저장된 상태에서는 이탈 경고 없음", P.state().unsaved === false);
|
||||
}
|
||||
{
|
||||
// 403·지연 + Escape + 버리기, A 실패가 B 상태를 오염시키지 않음
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const dPut = deferred();
|
||||
env.route("PUT", /\/project\/api\/tasks\/101$/, function () { return dPut.promise; });
|
||||
const P = await boot(env); const d = env.d; const modal = d.getElementById("pj-modal-task");
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
d.getElementById("pj-t-priority").value = "high";
|
||||
d.getElementById("pj-t-priority").dispatchEvent(new env.w.Event("change")); await settle();
|
||||
d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); await settle();
|
||||
check("[10] 저장 중 Esc → 저장이 끝날 때까지 창 유지", !modal.hidden);
|
||||
env.setConfirm(true); // 버리고 넘어가기
|
||||
const opening = P.openTaskModal(taskOf(P, 102)); await settle();
|
||||
dPut.resolve({ status: 403, body: { detail: "권한 없음" } });
|
||||
await opening; await settle();
|
||||
check("[10] 403 실패 → 버리기 선택 후 B 열림", d.getElementById("pj-t-id").value === "102" && !modal.hidden);
|
||||
check("[10] A 의 실패가 B 상태를 오염시키지 않음", P.state().failed.length === 0 && d.getElementById("pj-autosave-state").textContent === "", P.state().failed);
|
||||
}
|
||||
{
|
||||
// 네트워크 단절 → 계속 편집, 복구 후 표시줄 클릭으로 재시도
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
let net = false; const puts = [];
|
||||
env.route("PUT", /\/project\/api\/tasks\/101$/, function (u, b) { puts.push(b); return net ? { body: { task: Object.assign(detail(101, "작업 A"), b) } } : "NETWORK"; });
|
||||
const P = await boot(env); const d = env.d;
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
d.getElementById("pj-t-due").value = "2026-10-10";
|
||||
d.getElementById("pj-t-due").dispatchEvent(new env.w.Event("change")); await settle();
|
||||
check("[10] 네트워크 오류 → 마감일 칸 실패로 남음", P.state().failed.includes("due"));
|
||||
net = true;
|
||||
const stEl = d.getElementById("pj-autosave-state");
|
||||
const stBefore = stEl.dataset.state;
|
||||
stEl.click(); await settle();
|
||||
check("[10] '다시 시도' → 같은 값으로 재전송 성공", P.state().failed.length === 0 && puts[puts.length - 1].due_date === "2026-10-10",
|
||||
{ stBefore: stBefore, failed: P.state().failed, puts: puts });
|
||||
}
|
||||
|
||||
// ── [16] 한글 조합 Enter ─────────────────────────────────
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const dPost = deferred();
|
||||
env.route("POST", /\/project\/api\/tasks\/101\/comments$/, function () { return dPost.promise; });
|
||||
const P = await boot(env); const d = env.d;
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
const inp = d.getElementById("pj-comment-input");
|
||||
inp.value = "안녕하세요";
|
||||
inp.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Enter", isComposing: true, bubbles: true, cancelable: true }));
|
||||
const ev229 = new env.w.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true });
|
||||
Object.defineProperty(ev229, "keyCode", { value: 229 });
|
||||
inp.dispatchEvent(ev229);
|
||||
await settle();
|
||||
const posts = function () { return env.calls.filter(function (c) { return c.method === "POST" && /101\/comments$/.test(c.url); }); };
|
||||
check("[16] 조합 중 Enter(isComposing·229)는 댓글 전송 안 함", posts().length === 0);
|
||||
inp.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
|
||||
inp.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
|
||||
await settle();
|
||||
check("[16] 조합이 끝난 Enter 연타 → 한 번만 전송", posts().length === 1 && posts()[0].body.client_token, posts().length);
|
||||
dPost.resolve({ status: 201, body: { comment: { id: 1, body: "안녕하세요" }, mention_skipped: [] } }); await settle();
|
||||
const sub = d.getElementById("pj-subtask-input");
|
||||
await settle(); sub.value = "하위";
|
||||
sub.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Enter", isComposing: true, bubbles: true, cancelable: true })); await settle();
|
||||
check("[16] 하위 작업 칸도 조합 중 Enter 는 추가 안 함", !env.calls.some(function (c) { return c.method === "POST" && /projects\/1\/tasks$/.test(c.url); }));
|
||||
const cm = d.getElementById("pj-cm-input");
|
||||
env.w.__pjChat.open(101); await settle();
|
||||
cm.value = "채팅";
|
||||
cm.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Enter", isComposing: true, bubbles: true, cancelable: true })); await settle();
|
||||
check("[16] 댓글 대화창도 조합 중 Enter 는 전송 안 함", posts().length === 1);
|
||||
}
|
||||
|
||||
// ── [03] 파일 댓글 — 실패 파일 표시·유지, 성공 시 비움 ───────────
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
let mode = "fail";
|
||||
env.route("POST", /\/project\/api\/tasks\/101\/comments\/files$/, function () {
|
||||
if (mode === "fail") return { status: 400, body: { detail: { message: "보낼 수 없는 파일이 있어 댓글을 등록하지 않았습니다.", failed: [{ index: "1", name: "b.png", reason: "빈 파일" }] } } };
|
||||
if (mode === "net") return "NETWORK";
|
||||
return { status: 201, body: { comment: { id: 5, body: "" }, attachments: [], mention_skipped: [] } };
|
||||
});
|
||||
const P = await boot(env); const d = env.d;
|
||||
env.w.__pjChat.open(101); await settle();
|
||||
const cm = d.getElementById("pj-cm-input");
|
||||
function pasteImg(name, content) {
|
||||
const f = new env.w.File(content, name, { type: "image/png" });
|
||||
const ev = new env.w.Event("paste", { bubbles: true, cancelable: true });
|
||||
Object.defineProperty(ev, "clipboardData", { value: { items: [{ type: "image/png", getAsFile: function () { return f; } }], getData: function () { return ""; } } });
|
||||
cm.dispatchEvent(ev);
|
||||
}
|
||||
pasteImg("a.png", ["aaa"]); pasteImg("b.png", []);
|
||||
await settle();
|
||||
d.getElementById("pj-cm-send").click(); await settle();
|
||||
const chips = function () { return Array.from(d.querySelectorAll("#pj-cm-pending .pj-chat-pending-chip")); };
|
||||
check("[03] 서버가 거절한 파일만 빨간 표시, 두 파일 모두 남음", chips().length === 2 && chips()[1].classList.contains("is-failed") && !chips()[0].classList.contains("is-failed"));
|
||||
const sent = env.calls.filter(function (c) { return /comments\/files$/.test(c.url); });
|
||||
check("[03] 파일은 본문과 한 요청으로(빈 댓글을 먼저 만들지 않음)", sent.length === 1 && !env.calls.some(function (c) { return c.method === "POST" && /101\/comments$/.test(c.url); }));
|
||||
mode = "net";
|
||||
d.getElementById("pj-cm-send").click(); await settle();
|
||||
check("[03] 네트워크 오류 → 파일·입력 유지", chips().length === 2);
|
||||
const tok1 = env.calls.filter(function (c) { return /comments\/files$/.test(c.url); }).pop().body.get("client_token");
|
||||
mode = "ok";
|
||||
d.getElementById("pj-cm-send").click(); await settle();
|
||||
const tok2 = env.calls.filter(function (c) { return /comments\/files$/.test(c.url); }).pop().body.get("client_token");
|
||||
check("[03] 응답을 못 받은 재전송은 같은 client_token(서버가 한 번만 만듦)", tok1 && tok1 === tok2);
|
||||
check("[03] 성공하면 대기 파일 비움", chips().length === 0);
|
||||
}
|
||||
|
||||
// ── [14] 작업 창 댓글에 파일 표시 ─────────────────────────
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
env.route("GET", /\/project\/api\/tasks\/101\/comments/, function () {
|
||||
return { body: { comments: [{ id: 7, body: "", author_email: "me@test.local", created_at: "2026-09-30T10:00" },
|
||||
{ id: 8, body: "답글", parent_id: 7, author_email: "me@test.local", created_at: "2026-09-30T10:01" }],
|
||||
events: [], features: { replies: true } } };
|
||||
});
|
||||
env.route("GET", /\/project\/api\/tasks\/101\/attachments/, function () {
|
||||
return { body: { attachments: [{ id: 70, comment_id: 7, filename: "<b>x</b>.pdf", content_type: "application/pdf", size_bytes: 10 },
|
||||
{ id: 71, comment_id: 8, filename: "r.png", content_type: "image/png", size_bytes: 10 },
|
||||
{ id: 72, comment_id: null, filename: "plain.txt", content_type: "text/plain", size_bytes: 10 }] } };
|
||||
});
|
||||
const P = await boot(env); const d = env.d;
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
const list = d.getElementById("pj-comment-list");
|
||||
check("[14] 파일만 있는 댓글에 파일 표시", list.querySelector('a[href="/project/api/attachments/70/download"]') !== null);
|
||||
check("[14] 파일명은 이스케이프(태그로 해석 안 됨)", !list.querySelector(".pj-comment-atts b") && list.textContent.includes("<b>x</b>.pdf"));
|
||||
check("[14] 답글의 파일은 답글에", !!list.querySelector(".pj-comment-item.is-reply img[src='/project/api/attachments/71/inline']"));
|
||||
check("[14] 댓글 아닌 첨부는 댓글에 안 섞임", !list.innerHTML.includes("attachments/72/"));
|
||||
check("[14] 첨부 목록에 '댓글' 표시", d.getElementById("pj-attach-list").textContent.includes("댓글"));
|
||||
}
|
||||
|
||||
// ── [12] 연결된 작업은 읽기 전용 ─────────────────────────
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
env.route("GET", /\/project\/api\/tasks\/301$/, function () {
|
||||
return { body: { task: detail(301, "연결된 작업", { project_id: 3, project_name: "비밀", access: "read", followers: null, subtasks: [{ id: 3011, title: "읽기 하위", project_id: 3 }] }) } };
|
||||
});
|
||||
const P = await boot(env); const d = env.d;
|
||||
const linked = P.state().tasks.find(function (t) { return t.id === 301; });
|
||||
await P.openTaskModal(linked); await settle();
|
||||
check("[12] 제목·담당자 편집 불가", d.getElementById("pj-t-title").readOnly && d.getElementById("pj-t-assignee").disabled);
|
||||
check("[12] 읽기 전용 안내 표시", !d.getElementById("pj-t-readonly").hidden);
|
||||
check("[12] 댓글 입력·완료·삭제 숨김", d.getElementById("pj-comment-dock").hidden && d.getElementById("pj-toggle-complete").hidden && d.getElementById("pj-delete-task").hidden);
|
||||
check("[12] 하위 작업 추가 칸 숨김, 목록은 보임", d.querySelector(".pj-subtask-form").hidden && subsText(d).includes("읽기 하위"));
|
||||
d.getElementById("pj-t-title").value = "바꿈";
|
||||
d.getElementById("pj-t-title").dispatchEvent(new env.w.Event("blur")); await settle();
|
||||
const puts12 = env.calls.filter(function (c) { return c.method === "PUT"; });
|
||||
check("[12] 읽기 전용이면 저장 요청을 보내지 않음(뒤늦은 403 없음)", puts12.length === 0, puts12);
|
||||
}
|
||||
|
||||
// ── [13][01] 실시간 동기화 — 실패 후 같은 버전 재시도, 전체 범위 반영, 권한 회수 ──
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
let ver = "v1", snapMode = "fail";
|
||||
const dSnap = deferred();
|
||||
env.route("GET", /\/project\/api\/live-version/, function () { return { body: { ts: ver } }; });
|
||||
env.route("GET", /\/snapshot\?scope=all/, function () {
|
||||
if (snapMode === "fail") return { status: 500, body: { detail: "잠시 오류" } };
|
||||
if (snapMode === "slow") return dSnap.promise;
|
||||
if (snapMode === "gone") return { status: 403, body: { detail: "권한 없음" } };
|
||||
return { body: { scope: "all", project: { id: 1, name: "P1" },
|
||||
projects: [{ id: 1, name: "P1", color: "#4573d2", status: "active" }],
|
||||
tasks: [{ id: 101, title: "작업 A(새 제목)", project_id: 1, context_project_id: 1, stage_id: 11, stage_name: "할 일" },
|
||||
{ id: 150, title: "다른 사람이 만든 작업", project_id: 1, context_project_id: 1, stage_id: 13, stage_name: "검토" }],
|
||||
stages_by_project: { "1": [{ id: 11, project_id: 1, name: "할 일" }, { id: 13, project_id: 1, name: "검토" }] },
|
||||
stages: [{ id: 11, project_id: 1, name: "할 일" }, { id: 13, project_id: 1, name: "검토" }],
|
||||
members: [{ user_email: "me@test.local" }] } };
|
||||
});
|
||||
const P = await boot(env); const d = env.d;
|
||||
const st = function () { return env.w.pjLiveRefreshState(); };
|
||||
const poll = function () { return env.w.__pjLivePoll(); };
|
||||
const nextDelay = function () { const t = env.slow.filter(function (s) { return s.fn === env.w.__pjLivePoll; }).pop(); return t && t.ms; };
|
||||
check("[13] 처음 본 버전 = 반영된 버전", st().observed === "v1" && st().applied === "v1");
|
||||
ver = "v2";
|
||||
await poll(); await settle();
|
||||
check("[13] 스냅샷 실패 → 반영 버전은 그대로(v1), 실패 1", st().observed === "v2" && st().applied === "v1" && st().failures === 1, st());
|
||||
check("[13] 실패 뒤 다음 확인은 늘어난 간격(16초)", nextDelay() === 16000, nextDelay());
|
||||
snapMode = "ok";
|
||||
await poll(); await settle();
|
||||
check("[13] 같은 버전 다음 요청 성공 → v2 반영", st().applied === "v2" && st().failures === 0, st());
|
||||
const s = P.state();
|
||||
check("[01] 다른 프로젝트(P2) 작업·사이드바 항목 제거(권한 회수)", !s.tasks.some(function (t) { return t.project_id === 2; }) && !s.projectsMeta.some(function (p) { return p.id === 2; }));
|
||||
check("[01] 새 작업·새 섹션 반영", s.tasks.some(function (t) { return t.id === 150; }) && s.boardStages.includes("검토"));
|
||||
check("[01] 제목 변경 반영", s.tasks.find(function (t) { return t.id === 101; }).title === "작업 A(새 제목)");
|
||||
// 동기화 중 버전이 또 바뀌면 끝난 뒤 한 번 더
|
||||
snapMode = "slow"; ver = "v3";
|
||||
const firstPoll = poll();
|
||||
await settle();
|
||||
ver = "v4";
|
||||
const snapsBefore = env.calls.filter(function (c) { return /snapshot/.test(c.url); }).length;
|
||||
await poll(); // 동기화가 도는 중에 또 확인 — 겹쳐 받지 않는다
|
||||
const snapsDuring = env.calls.filter(function (c) { return /snapshot/.test(c.url); }).length;
|
||||
dSnap.resolve({ body: { tasks: [], projects: [{ id: 1, name: "P1", status: "active" }], stages_by_project: {}, stages: [], members: [] } });
|
||||
await firstPoll; await settle();
|
||||
check("[13] 동기화 중 새 버전(v4) — 겹쳐 돌지 않고 반영 버전은 v3", st().applied === "v3" && st().observed === "v4" && snapsDuring === snapsBefore, { st: st(), snapsBefore: snapsBefore, snapsDuring: snapsDuring });
|
||||
snapMode = "ok";
|
||||
await poll(); await settle();
|
||||
check("[13] 다음 주기에 v4 반영", st().applied === "v4", st());
|
||||
snapMode = "gone"; ver = "v5";
|
||||
await poll(); await settle();
|
||||
check("[01][02] 이 프로젝트 권한 회수 → 작업 비우고 안내", !!d.querySelector(".pj-access-lost") && P.state().tasks.length === 0);
|
||||
}
|
||||
|
||||
clearTimeout(WATCHDOG);
|
||||
console.log(fails.length ? "\nFAILED: " + fails.join(", ") : "\nALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
})().catch(function (e) { console.error(e); process.exit(1); });
|
||||
@@ -0,0 +1,71 @@
|
||||
"""project/project.html 을 테스트용 HTML 로 렌더한다(erp_base.html 은 최소 스텁, 가상의 데이터).
|
||||
|
||||
python tests/js/render_project.py # → tests/js/.out/project_render.html
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
|
||||
import jinja2
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
|
||||
|
||||
BASE_STUB = ("{% block head_extra %}{% endblock %}<body>{% block topbar_actions %}{% endblock %}"
|
||||
"<main class='erp-page'>{% block content %}{% endblock %}</main></body>")
|
||||
|
||||
ME = "me@test.local"
|
||||
STAGES = {
|
||||
1: [{"id": 11, "project_id": 1, "name": "할 일", "is_done_stage": False, "sort_order": 0, "color": None,
|
||||
"created_by": ME, "default_assignee_email": ""},
|
||||
{"id": 12, "project_id": 1, "name": "완료", "is_done_stage": True, "sort_order": 1, "color": None,
|
||||
"created_by": ME, "default_assignee_email": ""}],
|
||||
2: [{"id": 21, "project_id": 2, "name": "할 일", "is_done_stage": False, "sort_order": 0, "color": None,
|
||||
"created_by": ME, "default_assignee_email": ""}],
|
||||
}
|
||||
|
||||
|
||||
def task(tid: int, title: str, pid: int, stage: int, *, ctx: int | None = None, linked: bool = False) -> dict:
|
||||
return {"id": tid, "title": title, "project_id": pid, "context_project_id": ctx or pid, "is_linked": linked,
|
||||
"stage_id": stage, "home_stage_id": stage, "stage_name": "할 일", "is_done_stage": False,
|
||||
"description": "", "assignee_email": "", "assignee_name": "", "priority": "normal",
|
||||
"start_date": None, "due_date": None, "completed_at": None, "created_by": ME,
|
||||
"parent_task_id": None, "comment_count": 0, "subtask_count": 0, "subtask_done": 0,
|
||||
"project_name": {1: "P1", 2: "P2", 3: "비밀"}[pid], "project_color": "#4573d2", "sort_order": tid}
|
||||
|
||||
|
||||
TASKS = [task(101, "작업 A", 1, 11), task(102, "작업 B", 1, 11), task(103, "작업 C", 2, 21),
|
||||
task(301, "연결된 작업", 3, 99, ctx=1, linked=True)]
|
||||
PROJECTS = [{"id": 1, "name": "P1", "color": "#4573d2", "icon": "", "start_date": None, "due_date": None,
|
||||
"created_by": ME, "description": "", "status": "active"},
|
||||
{"id": 2, "name": "P2", "color": "#f06a6a", "icon": "", "start_date": None, "due_date": None,
|
||||
"created_by": ME, "description": "", "status": "active"}]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
env = jinja2.Environment(loader=jinja2.ChoiceLoader([
|
||||
jinja2.DictLoader({"erp_base.html": BASE_STUB}),
|
||||
jinja2.FileSystemLoader(os.path.join(ROOT, "app", "modules", "project", "templates")),
|
||||
]))
|
||||
env.globals["pj_kr_holidays"] = {}
|
||||
html = env.get_template("project/project.html").render(
|
||||
user={"email": ME, "is_super_admin": False}, is_admin=False, can_manage=True,
|
||||
project=PROJECTS[0], current_project_id=1, stages=STAGES[1], tasks=TASKS,
|
||||
members=[{"user_email": ME, "role": "member"}, {"user_email": "bob@test.local", "role": "member"}],
|
||||
projects_meta=PROJECTS, nav_projects=PROJECTS, stages_by_project=STAGES, board_stage_names=["할 일", "완료"],
|
||||
avatars={}, priority_labels={"low": "낮음", "normal": "보통", "high": "높음"},
|
||||
color_palette=["#4573d2"], project_icons=["folder"], stage_color_palette=["#c7c4c4"],
|
||||
today="2026-09-30", holidays={}, year=2026, month=9, prev_y=2026, prev_m=8, next_y=2026, next_m=10,
|
||||
weekdays=["일", "월", "화", "수", "목", "금", "토"], weeks=[], goal_years=[2026],
|
||||
my_open_total=0, mention_unread=0,
|
||||
)
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
path = os.path.join(OUT_DIR, "project_render.html")
|
||||
io.open(path, "w", encoding="utf-8", newline="\n").write(html)
|
||||
print("rendered:", path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,471 @@
|
||||
"""프로젝트 관리 모듈 — 권한·저장·댓글 첨부·알림 회귀 테스트 (실제 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'<span class="pj-mention" data-email="{ALICE}">@a</span>'}).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'<span class="pj-mention" data-email="{e}">@x</span>' 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)
|
||||
|
||||
|
||||
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
|
||||
Reference in New Issue
Block a user