fix(project): review fixes — access leaks, open paths, save safety, concurrency
- Subproject tasks via parent /tasks are re-filtered by current access (FULL/READ kept)
- PUT /api/projects/order: every id must be manageable; bad/duplicate ids -> 400, all-or-nothing
- Inbox, web alert popup, PC notifier open tasks via /project/t/{id}; embed=1 survives redirect;
old /p/{home}?task= redirects READ users to the linked project
- Project page / snapshot / workload include the opened archived or sub project only
- Alerts: DB-side filters + oldest-first paging (no 50-row cut); badges counted without caps;
my tasks keep every open task (completed capped)
- Meeting results: next-week meeting open, or own meeting open when no next meeting;
header edits + result checks under row locks (FOR UPDATE / FOR SHARE)
- Inbox panel waits for the task window save (same retry/discard flow) before switching/closing;
read failures stay unread
- Attachment upload removes only its own file on DB failure
- New project modal: create once, retry only failed member assignments
- update_task / update_project: locked-row validation in one transaction; completion hints from real transition
- Creator added as explicit member when another owner is chosen
- _once lock lifetime managed by refcount (no leak on failure)
- Section default assignee must still be a registered project user; follower add uses can_assign
- Docs (PROJECT_MODULE 6-15, help), tests (DB-less, real PostgreSQL, jsdom, Chrome)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -60,3 +60,16 @@ python -m unittest discover -s tests -p test_project_meeting_cells.py
|
||||
`PROJECT_TEST_DB_URL`에 기존 로컬 테스트 DB를 지정해야 하며, 미설정 또는 로컬 주소가 아니면 건너뛴다.
|
||||
회의록 셀 테스트는 DB 연결을 대신하는 트랜잭션 모형으로 실제 저장소 메서드·API 권한/충돌·이동/병합 롤백·
|
||||
019 미적용·병합 행 작업 보호·서식 보존·안전한 템플릿 출력을 검증한다. 실제 PostgreSQL 잠금 동작 검증은 별도다.
|
||||
|
||||
# 프로젝트 화면·수신함 UI 테스트 (jsdom + 실제 Chrome)
|
||||
|
||||
`project.html`·`inbox.html` + `static/project.js` — 작업 창 저장/실패/동기화, 전체 보기의 연결된(읽기 전용) 작업,
|
||||
수신함 오른쪽 작업 창(저장 대기 뒤 바꾸기·계속 편집·A→B→A·저장 중 Esc·읽음 실패), 새 프로젝트 창(생성/멤버 배정 결과 분리·
|
||||
실패한 멤버만 다시 배정·연타)을 가짜 서버로 검증한다.
|
||||
|
||||
```powershell
|
||||
python tests/js/render_project.py # → tests/js/.out/project_*.html · inbox_render.html
|
||||
node tests/js/project_ui.test.js # jsdom
|
||||
$env:PJ_TEST_BROWSER = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
|
||||
node tests/js/inbox_panel.browser.test.js # Playwright: iframe 리다이렉트 뒤 embed·저장 실패 확인창·A→B→A·iframe 안 Esc·읽음 실패
|
||||
```
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
// 실제 브라우저 — 수신함 오른쪽 작업 창(iframe)이 다른 줄로 바뀌거나 닫히기 전에 작업 창의 저장을 기다리는지,
|
||||
// 저장 실패면 작업 창과 같은 "버리고 넘어가기 / 계속 편집"을 묻는지, 공유 링크 리다이렉트 뒤에도 embed 인지,
|
||||
// iframe 안 Esc·빠른 A→B→A·읽음 실패를 확인한다. 서버는 가짜(이 파일의 http 서버), 화면은 실제 템플릿 렌더 결과.
|
||||
// python tests/js/render_project.py
|
||||
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/inbox_panel.browser.test.js
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs"), path = require("node:path"), http = require("node:http");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.resolve(__dirname, "../.."), OUT = path.join(__dirname, ".out"), STATIC = path.join(ROOT, "app/static");
|
||||
|
||||
const detail = (id, title) => ({ id, title, project_id: 1, stage_id: 11, description: "", priority: "normal",
|
||||
assignee_email: "", subtasks: [], links: [], followers: [], access: "full", completed_at: null });
|
||||
let putStatus = 200, holdPut = false, releasePut = null, failNotiRead = false;
|
||||
const puts = [], reads = [];
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
const json = (code, body) => { res.statusCode = code; res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify(body)); };
|
||||
if (url.pathname === "/project/inbox") { res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(fs.readFileSync(path.join(OUT, "inbox_render.html"))); return; }
|
||||
const tm = /^\/project\/t\/(\d+)$/.exec(url.pathname);
|
||||
if (tm) { // 공유 링크 — 서버(router.task_permalink)처럼 embed 를 이어서 보낸다
|
||||
res.statusCode = 303;
|
||||
res.setHeader("Location", `/project/p/1?task=${tm[1]}${url.searchParams.get("embed") === "1" ? "&embed=1" : ""}`);
|
||||
res.end(); return;
|
||||
}
|
||||
if (url.pathname === "/project/p/1") { res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(fs.readFileSync(path.join(OUT, "project_render.html"))); return; }
|
||||
if (url.pathname.startsWith("/project/api/")) {
|
||||
let raw = ""; for await (const c of req) raw += c;
|
||||
const body = raw ? JSON.parse(raw) : null;
|
||||
const task = /^\/project\/api\/tasks\/(\d+)$/.exec(url.pathname);
|
||||
if (task && req.method === "GET") return json(200, { task: detail(+task[1], "작업 " + task[1]) });
|
||||
if (task && req.method === "PUT") {
|
||||
puts.push({ id: +task[1], body });
|
||||
if (holdPut) await new Promise(r => { releasePut = r; });
|
||||
return putStatus >= 400 ? json(putStatus, { detail: "서버 오류" }) : json(200, { task: Object.assign(detail(+task[1], "작업"), body) });
|
||||
}
|
||||
if (url.pathname === "/project/api/mentions/read") { reads.push("m" + (body && body.task_id)); return json(200, { ok: true, marked: 1 }); }
|
||||
const nr = /^\/project\/api\/notifications\/(\d+)\/read$/.exec(url.pathname);
|
||||
if (nr) { reads.push("n" + nr[1]); return failNotiRead ? json(500, { detail: "db" }) : json(200, { ok: true }); }
|
||||
if (url.pathname.endsWith("/comments")) return json(200, { comments: [], events: [], features: {} });
|
||||
if (url.pathname.endsWith("/attachments")) return json(200, { attachments: [] });
|
||||
if (url.pathname.endsWith("/members")) return json(200, { members: [{ user_email: "me@test.local" }] });
|
||||
if (url.pathname.endsWith("/live-version")) return json(200, { ts: "v1" });
|
||||
if (url.pathname.endsWith("/alerts")) return json(200, { me: "me@test.local", latest_id: 0, alerts: [] });
|
||||
return json(200, {});
|
||||
}
|
||||
if (url.pathname.startsWith("/static/")) {
|
||||
const file = path.join(STATIC, decodeURIComponent(url.pathname.slice("/static/".length)));
|
||||
if (file.startsWith(STATIC) && fs.existsSync(file)) {
|
||||
res.setHeader("Content-Type", file.endsWith(".js") ? "text/javascript" : file.endsWith(".css") ? "text/css" : "application/octet-stream");
|
||||
res.end(fs.readFileSync(file)); return;
|
||||
}
|
||||
}
|
||||
res.statusCode = 404; res.end("");
|
||||
});
|
||||
|
||||
(async function () {
|
||||
await new Promise(r => server.listen(0, "127.0.0.1", r));
|
||||
const base = "http://127.0.0.1:" + server.address().port;
|
||||
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
|
||||
const page = await browser.newPage({ viewport: { width: 1920, height: 1080 } }); // 작업 창이 왼쪽 목록을 가리지 않는 보통 PC 화면
|
||||
const dialogs = [];
|
||||
let dialogAnswer = false;
|
||||
page.on("dialog", async d => { dialogs.push(d.type() + ":" + d.message().slice(0, 20)); if (dialogAnswer) await d.accept(); else await d.dismiss(); });
|
||||
const pass = [];
|
||||
const ok = (name, cond, extra) => { assert.ok(cond, name + (extra === undefined ? "" : " → " + JSON.stringify(extra))); pass.push(name); console.log("PASS " + name); };
|
||||
try {
|
||||
await page.goto(base + "/project/inbox");
|
||||
const frameOf = () => page.frames().find(f => f !== page.mainFrame());
|
||||
const frameUrl = () => (frameOf() ? frameOf().url() : "");
|
||||
const waitModal = async () => {
|
||||
await page.waitForFunction(() => { const f = document.querySelector(".pj-inbox-panel iframe"); const d = f && f.contentDocument;
|
||||
const m = d && d.getElementById("pj-modal-task"); return !!(m && !m.hidden && d.getElementById("pj-t-id").value); });
|
||||
};
|
||||
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="101"]');
|
||||
await waitModal();
|
||||
ok("공유 링크 리다이렉트 뒤에도 embed 화면(작업 창만)", /\/project\/p\/1\?/.test(frameUrl()) && /embed=1/.test(frameUrl()) &&
|
||||
await frameOf().evaluate(() => document.documentElement.classList.contains("pj-embed")), frameUrl());
|
||||
ok("같은 작업의 태그·알림을 함께 확인", reads.includes("m101") && reads.includes("n901"), reads);
|
||||
|
||||
// ① 저장 실패 → 다른 줄 → 묻기 → 계속 편집: 창·입력 그대로
|
||||
putStatus = 500;
|
||||
const fr = frameOf();
|
||||
await fr.fill("#pj-t-title", "작업 101 고침");
|
||||
await fr.evaluate(() => document.getElementById("pj-t-title").blur());
|
||||
await page.waitForTimeout(150);
|
||||
dialogAnswer = false;
|
||||
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
|
||||
await page.waitForTimeout(400);
|
||||
ok("저장 실패면 바꾸기 전에 묻고(작업 창과 같은 확인), 계속 편집이면 그대로", dialogs.length === 1 && /\?task=|\/p\/1/.test(frameUrl()) &&
|
||||
await fr.evaluate(() => document.getElementById("pj-t-title").value) === "작업 101 고침" &&
|
||||
!reads.includes("m102"), { dialogs, url: frameUrl(), reads });
|
||||
|
||||
// ② 저장 대기 중 A→B→A — 확인 뒤 A 그대로, 새 줄 안 열림
|
||||
putStatus = 200; holdPut = true;
|
||||
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
|
||||
await page.waitForTimeout(150);
|
||||
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="101"]');
|
||||
await page.waitForTimeout(100);
|
||||
ok("저장이 끝나기 전엔 창을 바꾸지 않는다", frameOf() === fr && releasePut !== null);
|
||||
holdPut = false; releasePut(); releasePut = null;
|
||||
await page.waitForTimeout(500);
|
||||
ok("A→B→A 빨리 — 저장 성공 뒤 A 작업 창 그대로(다시 읽지 않음)", frameOf() === fr &&
|
||||
await fr.evaluate(() => document.getElementById("pj-t-id").value) === "101" && puts[puts.length - 1].body.title === "작업 101 고침" &&
|
||||
!reads.includes("m102"), { puts: puts.length, reads });
|
||||
|
||||
// ③ 저장 성공 상태에서 B → 바로 바뀌고 이탈 경고 없음
|
||||
const before = dialogs.length;
|
||||
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
|
||||
await waitModal();
|
||||
await page.waitForFunction(() => document.querySelector(".pj-inbox-panel iframe").contentDocument.getElementById("pj-t-id").value === "102");
|
||||
ok("저장된 상태면 묻지 않고 B 로(beforeunload 경고도 없음)", dialogs.length === before && reads.includes("m102"), dialogs);
|
||||
|
||||
// ④ iframe 안 포커스에서 Esc — 작업 창이 닫히며 패널도 닫힘, 확인한 줄은 목록에서 빠짐
|
||||
const fr2 = frameOf();
|
||||
await fr2.focus("#pj-t-title");
|
||||
await page.keyboard.press("Escape");
|
||||
await page.waitForFunction(() => !document.querySelector(".pj-inbox-panel").classList.contains("is-open"));
|
||||
await page.waitForTimeout(400);
|
||||
ok("iframe 안에서 Esc → 패널 닫힘, 확인한 태그 줄은 빠짐", await page.evaluate(() =>
|
||||
!document.querySelector('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]')));
|
||||
|
||||
// ⑤ 읽음 실패한 알림 줄은 남는다
|
||||
failNotiRead = true;
|
||||
await page.click('#pj-inbox .pj-inbox-item[data-id="903"]', { button: "right" });
|
||||
await page.click(".pj-ctxmenu button, .pj-ctxmenu [role=menuitem], .pj-ctxmenu li");
|
||||
await page.waitForTimeout(400);
|
||||
ok("읽음 처리 실패 — 줄이 남고 굵게(읽지 않음)", await page.evaluate(() => {
|
||||
const li = document.querySelector('#pj-inbox .pj-inbox-item[data-id="903"]'); return !!li && li.classList.contains("is-unread"); }));
|
||||
console.log("\nALL PASS (" + pass.length + ")");
|
||||
} finally {
|
||||
await browser.close();
|
||||
server.close();
|
||||
}
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
@@ -16,6 +16,7 @@ const WATCHDOG = setTimeout(function () { console.log("TIMEOUT — 어딘가에
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const html = fs.readFileSync(path.join(__dirname, ".out", "project_render.html"), "utf8");
|
||||
const adminHtml = fs.readFileSync(path.join(__dirname, ".out", "project_admin_render.html"), "utf8");
|
||||
const inboxHtml = fs.readFileSync(path.join(__dirname, ".out", "inbox_render.html"), "utf8");
|
||||
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
|
||||
|
||||
const fails = [];
|
||||
@@ -779,6 +780,124 @@ function titleVal(d) { return d.getElementById("pj-t-title").value; }
|
||||
const shown = Array.from(d.querySelectorAll(".pj-tmember")).map(function (n) { return n.dataset.email; });
|
||||
check("[멤버 배정·제외] 머리 멤버 아이콘 갱신", shown.indexOf("bob@test.local") < 0 && shown.indexOf("carol@test.local") >= 0, shown);
|
||||
}
|
||||
// ── [검토 A] 전체 보기 — 원 소속을 볼 수 없는 연결된 작업(301, 읽기 전용)도 한 번 나온다 ──
|
||||
{
|
||||
const env = makeEnv(adminHtml); baseRoutes(env);
|
||||
await boot(env);
|
||||
const d = env.d;
|
||||
d.getElementById("pj-side-allview").click(); await settle();
|
||||
const cards = function (id) { return d.querySelectorAll('.pj-card[data-task-id="' + id + '"]').length; };
|
||||
check("[전체 보기] 연결된 작업(원 소속 못 봄)도 한 장, 원 소속 작업은 그대로 한 장", cards(301) === 1 && cards(101) === 1 && cards(103) === 1,
|
||||
[cards(301), cards(101), cards(103)]);
|
||||
}
|
||||
// ── [검토 7] 수신함 iframe 안쪽 — __pjEmbedSettle 이 작업 창 닫기와 같은 저장 절차를 탄다 ──
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
env.d.documentElement.classList.add("pj-embed");
|
||||
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 = "작업 A3"; ta.dispatchEvent(new env.w.Event("blur")); await settle();
|
||||
env.setConfirm(false); // 계속 편집
|
||||
const ok1 = await env.w.__pjEmbedSettle(); await settle();
|
||||
check("[수신함 iframe] 저장 실패 → 다시 시도 후 묻고, 계속 편집이면 false·입력 유지",
|
||||
ok1 === false && !modal.hidden && titleVal(d) === "작업 A3" && env.confirms === 1 && puts.length >= 2, [ok1, env.confirms, puts.length]);
|
||||
putStatus = 200;
|
||||
const ok2 = await env.w.__pjEmbedSettle(); await settle();
|
||||
check("[수신함 iframe] 다시 — 재시도 성공이면 true(묻지 않음)", ok2 === true && env.confirms === 1 && puts[puts.length - 1].title === "작업 A3",
|
||||
[ok2, env.confirms]);
|
||||
}
|
||||
// ── [검토 7] 수신함 작업 창 — 바꾸기·닫기 전 저장 대기, 계속 편집이면 그대로, A→B→A, 저장 중 Esc, 읽음 실패 ──
|
||||
{
|
||||
const env = makeEnv(inboxHtml); baseRoutes(env);
|
||||
const reads = [];
|
||||
env.route("POST", /\/project\/api\/mentions\/read$/, function (u, b) { reads.push("m" + (b && b.task_id)); return { body: { ok: true, marked: 1 } }; });
|
||||
let failNoti = true;
|
||||
env.route("POST", /\/project\/api\/notifications\/\d+\/read$/, function (u) {
|
||||
reads.push("n" + u.split("/")[4]);
|
||||
return failNoti ? { status: 500, body: { detail: "db" } } : { body: { ok: true } };
|
||||
});
|
||||
await boot(env);
|
||||
const d = env.d;
|
||||
const A = d.querySelector('#pj-mention-tasks .pj-inbox-item[data-task-id="101"]');
|
||||
const B = d.querySelector('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
|
||||
const N901 = d.querySelector('#pj-inbox .pj-inbox-item[data-id="901"]');
|
||||
const frame = function () { const p = d.body.querySelector(".pj-inbox-panel"); return p && p.querySelector("iframe"); };
|
||||
const src = function () { return frame() ? frame().getAttribute("src") : ""; };
|
||||
A.click(); await settle();
|
||||
check("[수신함] 줄 → 오른쪽 작업 창 = 공유 링크 + embed", src() === "/project/t/101?embed=1", src());
|
||||
check("[수신함] 같은 작업의 태그·알림을 함께 확인", reads.indexOf("m101") >= 0 && reads.indexOf("n901") >= 0, reads);
|
||||
await settle();
|
||||
check("[수신함] 알림 읽음 실패 — 굵게(읽지 않음) 그대로", N901.classList.contains("is-unread"));
|
||||
let gate = deferred(), settles = 0;
|
||||
frame().contentWindow.__pjEmbedSettle = function () { settles++; return gate.promise; };
|
||||
B.click(); await settle();
|
||||
check("[수신함] 작업 창 저장 확인 중엔 바꾸지 않음", src() === "/project/t/101?embed=1" && settles === 1, [src(), settles]);
|
||||
A.click(); await settle(); // A→B→A 빨리
|
||||
gate.resolve(true); await settle();
|
||||
check("[수신함] A→B→A — 확인 뒤 A 그대로, B 는 열거나 확인하지 않음",
|
||||
src() === "/project/t/101?embed=1" && reads.indexOf("m102") < 0 && B.classList.contains("is-unread") && settles === 1, [src(), reads, settles]);
|
||||
gate = deferred();
|
||||
B.click(); await settle(); gate.resolve(false); await settle();
|
||||
check("[수신함] 계속 편집 — 창·선택 그대로, 새 줄 확인 안 함",
|
||||
src() === "/project/t/101?embed=1" && A.classList.contains("is-selected") && !B.classList.contains("is-selected") && reads.indexOf("m102") < 0);
|
||||
gate = deferred(); settles = 0;
|
||||
const esc = function () { d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); };
|
||||
esc(); await settle(); esc(); await settle();
|
||||
const panelEl = d.body.querySelector(".pj-inbox-panel");
|
||||
check("[수신함] 저장 중 Esc(두 번) — 확인 하나만, 끝나기 전엔 열린 채", panelEl.classList.contains("is-open") && settles === 1, settles);
|
||||
gate.resolve(true); await settle();
|
||||
check("[수신함] 저장이 끝나면 닫힘", !panelEl.classList.contains("is-open"));
|
||||
await wait(260); await settle();
|
||||
check("[수신함] 확인된 태그 줄은 빠지고, 읽음 실패한 알림 줄은 남는다", !A.isConnected && N901.isConnected, [A.isConnected, N901.isConnected]);
|
||||
failNoti = false;
|
||||
B.click(); await settle(); await settle();
|
||||
check("[수신함] 닫힌 뒤 다른 줄 — 바로 열림", src() === "/project/t/102?embed=1", src());
|
||||
}
|
||||
// ── [검토 9] 새 프로젝트 — 생성과 멤버 배정 결과를 따로, 실패한 멤버만 다시, 연타해도 한 번 생성 ──
|
||||
{
|
||||
const env = makeEnv(adminHtml); baseRoutes(env);
|
||||
env.route("GET", /\/project\/api\/assignable-users$/, function () { return { body: { users: [
|
||||
{ email: "bob@test.local", id: "bob", name: "Bob", avatar: "" },
|
||||
{ email: "carol@test.local", id: "carol", name: "Carol", avatar: "" }] } }; });
|
||||
let creates = 0, failCarol = true;
|
||||
const memberCalls = [];
|
||||
const createGate = deferred();
|
||||
env.route("POST", /\/project\/api\/projects$/, async function () {
|
||||
creates++;
|
||||
await createGate.promise;
|
||||
return { status: 201, body: { project: { id: 9, name: "새 프로젝트" } } };
|
||||
});
|
||||
env.route("POST", /\/project\/api\/projects\/9\/members$/, function (u, b) {
|
||||
memberCalls.push(b.user_email);
|
||||
return failCarol && b.user_email === "carol@test.local" ? { status: 400, body: { detail: "배정 불가" } } : { status: 201, body: { member: {} } };
|
||||
});
|
||||
await boot(env);
|
||||
const d = env.d;
|
||||
d.getElementById("pj-new-project-side").click(); await settle();
|
||||
d.getElementById("pj-f-name").value = "새 프로젝트";
|
||||
d.querySelectorAll("#pj-f-members input[type=checkbox]").forEach(function (c) { c.checked = true; });
|
||||
const save = d.getElementById("pj-save-project");
|
||||
save.click(); save.click(); await settle(); // 연타
|
||||
createGate.resolve(); await settle(); await settle();
|
||||
const modal = d.getElementById("pj-modal-project");
|
||||
const msg = d.getElementById("pj-f-project-msg");
|
||||
const carol = d.querySelector('#pj-f-members input[value="carol@test.local"]').closest(".pj-member-pick");
|
||||
check("[새 프로젝트] 연타해도 한 번만 생성", creates === 1, creates);
|
||||
check("[새 프로젝트] 배정 실패 — 창 유지, 생성됨·실패 멤버 안내, 실패 표시",
|
||||
!modal.hidden && !msg.hidden && /만들어졌습니다/.test(msg.textContent) && /배정 불가/.test(msg.textContent) &&
|
||||
carol.classList.contains("is-failed") && /다시 배정/.test(save.textContent), [modal.hidden, msg.textContent, save.textContent]);
|
||||
failCarol = false;
|
||||
save.click(); await settle(); await settle();
|
||||
check("[새 프로젝트] 다시 배정 — 실패한 멤버만, 프로젝트는 다시 만들지 않음, 끝나면 닫힘",
|
||||
creates === 1 && JSON.stringify(memberCalls) === JSON.stringify(["bob@test.local", "carol@test.local", "carol@test.local"]) && modal.hidden,
|
||||
[creates, memberCalls, modal.hidden]);
|
||||
}
|
||||
clearTimeout(WATCHDOG);
|
||||
console.log(fails.length ? "\nFAILED: " + fails.join(", ") : "\nALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
|
||||
@@ -52,6 +52,31 @@ def main() -> None:
|
||||
env.globals["pj_kr_holidays"] = {}
|
||||
for name, admin in (("project_render.html", False), ("project_admin_render.html", True)):
|
||||
render_one(env, name, admin)
|
||||
render_inbox(env)
|
||||
|
||||
|
||||
def render_inbox(env) -> None:
|
||||
"""수신함(project/inbox.html) — 태그한 작업 101·102, 알림(작업 101·102·프로젝트만)."""
|
||||
def mt(tid: int, title: str) -> dict:
|
||||
return {"id": tid, "title": title, "project_id": 1, "project_name": "P1", "project_color": "#4573d2",
|
||||
"unread_mentions": 1, "stage_name": "할 일", "due_label": "", "mention_actor": "bob@test.local",
|
||||
"completed_at": None}
|
||||
|
||||
def nt(nid: int, ntype: str, title: str, task_id: int | None) -> dict:
|
||||
return {"id": nid, "type": ntype, "title": title, "body": "P1", "task_id": task_id, "project_id": 1,
|
||||
"is_read": False, "actor_email": "bob@test.local", "created_at": "2026-10-12T09:00:00+09:00"}
|
||||
|
||||
html = env.get_template("project/inbox.html").render(
|
||||
user={"email": ME, "is_super_admin": False}, is_admin=False, pj_pro=False, pj_admin=False,
|
||||
nav_projects=PROJECTS, goal_years=[2026], my_open_total=0, mention_unread=2,
|
||||
color_palette=["#4573d2"], project_icons=["folder"], project_asana_icons=[],
|
||||
mentioned_tasks=[mt(101, "작업 A"), mt(102, "작업 B")],
|
||||
notifications=[nt(901, "assigned", "작업 배정: 작업 A", 101), nt(902, "comment", "새 댓글: 작업 B", 102),
|
||||
nt(903, "completed", "프로젝트 알림", None)],
|
||||
)
|
||||
path = os.path.join(OUT_DIR, "inbox_render.html")
|
||||
io.open(path, "w", encoding="utf-8", newline="\n").write(html)
|
||||
print("rendered:", path)
|
||||
|
||||
|
||||
def render_one(env, name: str, admin: bool) -> None:
|
||||
|
||||
@@ -18,13 +18,24 @@ ROWS = [ # 최신순(list_notifications 와 같게)
|
||||
|
||||
|
||||
class FakeStore:
|
||||
"""list_notifications(최신순) + list_unread_after(DB 쪽 조건·오래된 것부터) — db.py 와 같은 의미."""
|
||||
desktop = False
|
||||
|
||||
def __init__(self, rows=None):
|
||||
self.rows = list(ROWS if rows is None else rows)
|
||||
self.pages = 0
|
||||
|
||||
def notifier_active(self, email):
|
||||
return self.desktop
|
||||
|
||||
def list_notifications(self, recipient_email, unread_only=False, limit=100):
|
||||
rows = [r for r in ROWS if not unread_only or not r["is_read"]]
|
||||
rows = sorted((r for r in self.rows if not unread_only or not r["is_read"]), key=lambda r: -r["id"])
|
||||
return rows[:limit]
|
||||
|
||||
def list_unread_after(self, recipient_email, after_id, types, limit=200):
|
||||
self.pages += 1
|
||||
rows = sorted((r for r in self.rows if not r["is_read"] and r["id"] > after_id and r["type"] in types),
|
||||
key=lambda r: r["id"])
|
||||
return rows[:limit]
|
||||
|
||||
|
||||
@@ -34,12 +45,13 @@ class AlertsApiTests(unittest.TestCase):
|
||||
app.include_router(api.router)
|
||||
self.client = TestClient(app)
|
||||
|
||||
def get(self, qs="", desktop=False):
|
||||
st = FakeStore()
|
||||
def get(self, qs="", desktop=False, st=None, visible=None):
|
||||
st = st or FakeStore()
|
||||
st.desktop = desktop
|
||||
vis = visible or (lambda st, user, items: items)
|
||||
with patch.object(api, "_require_user", return_value={"email": "Me@Test.local"}), \
|
||||
patch.object(api, "_db_or_503", return_value=st), \
|
||||
patch.object(api, "_visible_notifications", side_effect=lambda st, user, items: items):
|
||||
patch.object(api, "_visible_notifications", side_effect=vis):
|
||||
return self.client.get("/project/api/notifications/alerts" + qs).json()
|
||||
|
||||
def test_without_after_returns_only_baseline(self):
|
||||
@@ -52,6 +64,13 @@ class AlertsApiTests(unittest.TestCase):
|
||||
self.assertEqual(out["alerts"][1]["type"], "mention")
|
||||
self.assertNotIn("desktop", out)
|
||||
|
||||
def test_alert_links_use_task_permalink(self):
|
||||
# 작업 알림은 /project/t/{id} — 연결된 프로젝트에서만 읽을 수 있는 사람도 403 없이 열린다
|
||||
out = self.get("?after=5")
|
||||
self.assertEqual([a["href"] for a in out["alerts"]], ["/project/t/3", "/project/t/1"])
|
||||
st = FakeStore([{"id": 3, "type": "mention", "is_read": False, "task_id": None, "project_id": 4}])
|
||||
self.assertEqual(self.get("?after=0", st=st)["alerts"][0]["href"], "/project/p/4")
|
||||
|
||||
def test_pc_notifier_running_silences_web_popup(self):
|
||||
out = self.get("?after=5", desktop=True)
|
||||
self.assertEqual((out["alerts"], out["latest_id"], out["desktop"]), ([], 9, True))
|
||||
@@ -60,12 +79,39 @@ class AlertsApiTests(unittest.TestCase):
|
||||
class Broken(FakeStore):
|
||||
def notifier_active(self, email):
|
||||
raise RuntimeError("db down")
|
||||
with patch.object(api, "_require_user", return_value={"email": "me@test.local"}), \
|
||||
patch.object(api, "_db_or_503", return_value=Broken()), \
|
||||
patch.object(api, "_visible_notifications", side_effect=lambda st, user, items: items):
|
||||
out = self.client.get("/project/api/notifications/alerts?after=5").json()
|
||||
out = self.get("?after=5", st=Broken())
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [6, 8])
|
||||
|
||||
# ── 예전엔 최신 50건을 자른 뒤 걸러서 빠지던 경우들 ──
|
||||
def test_assignment_behind_fifty_comment_alerts_is_not_lost(self):
|
||||
rows = [{"id": 1, "type": "assigned", "title": "배정", "is_read": False, "task_id": 1, "project_id": 1}]
|
||||
rows += [{"id": 100 + i, "type": "comment", "title": "댓글", "is_read": False, "task_id": 1, "project_id": 1}
|
||||
for i in range(50)]
|
||||
out = self.get("?after=0", st=FakeStore(rows))
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [1])
|
||||
|
||||
def test_more_than_sixty_assignments_page_oldest_first(self):
|
||||
rows = [{"id": i, "type": "assigned", "title": f"배정{i}", "is_read": False, "task_id": i, "project_id": 1}
|
||||
for i in range(1, 66)]
|
||||
st = FakeStore(rows)
|
||||
out = self.get("?after=0", st=st)
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], list(range(1, 11))) # 오래된 것부터 10건
|
||||
out = self.get("?after=10", st=st) # 닫으면 그 뒤 것(화면이 본 것=10 으로 다시 묻는다)
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], list(range(11, 21)))
|
||||
out = self.get("?after=60", st=st)
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [61, 62, 63, 64, 65])
|
||||
|
||||
def test_invisible_alerts_ahead_do_not_hide_visible_ones(self):
|
||||
# 앞쪽 450건은 지금 볼 수 없는 작업(권한 회수) — 페이지를 넘겨 그 뒤의 볼 수 있는 알림을 찾는다
|
||||
rows = [{"id": i, "type": "mention", "title": "x", "is_read": False, "task_id": 9, "project_id": 9}
|
||||
for i in range(1, 451)]
|
||||
rows.append({"id": 500, "type": "mention", "title": "보임", "is_read": False, "task_id": 1, "project_id": 1})
|
||||
st = FakeStore(rows)
|
||||
out = self.get("?after=0", st=st,
|
||||
visible=lambda st, user, items: [n for n in items if n["project_id"] == 1])
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [500])
|
||||
self.assertEqual(st.pages, 3) # 200·200·51 — 끝까지 읽고 멈춘다
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -17,6 +17,11 @@ class FakeStore:
|
||||
def list_projects(self, include_archived, member_email):
|
||||
return [{"id": 1, "parent_id": None}, {"id": 2, "parent_id": None}, {"id": 5, "parent_id": 1}]
|
||||
|
||||
def get_project(self, project_id):
|
||||
# 7 = 보관된 프로젝트(활성 목록에 없음), 5 = 서브프로젝트
|
||||
return {"id": project_id, "parent_id": 1 if project_id == 5 else None,
|
||||
"status": "archived" if project_id == 7 else "active"}
|
||||
|
||||
def list_tasks_for_projects(self, project_ids):
|
||||
self.asked_projects = project_ids
|
||||
return [{"id": 10 * pid} for pid in project_ids]
|
||||
@@ -33,12 +38,12 @@ class SubtaskSummaryTests(unittest.TestCase):
|
||||
self.client = TestClient(app)
|
||||
self.st = FakeStore()
|
||||
|
||||
def call(self, scope):
|
||||
def call(self, scope, pid=1):
|
||||
with patch.object(api, "_require_user", return_value={"email": "me@test", "role": "pro"}), \
|
||||
patch.object(api, "_db_or_503", return_value=self.st), \
|
||||
patch.object(api, "_require_manage", return_value=None), \
|
||||
patch.object(api, "_accessible_project_ids", return_value=None):
|
||||
return self.client.get(f"/project/api/projects/1/subtasks-summary?scope={scope}")
|
||||
return self.client.get(f"/project/api/projects/{pid}/subtasks-summary?scope={scope}")
|
||||
|
||||
def test_project_scope_uses_only_this_project(self):
|
||||
r = self.call("project")
|
||||
@@ -51,6 +56,13 @@ class SubtaskSummaryTests(unittest.TestCase):
|
||||
self.call("all")
|
||||
self.assertEqual(self.st.asked_projects, [1, 2]) # 서브프로젝트(5) 제외 — 스냅샷과 같은 범위
|
||||
|
||||
def test_all_scope_adds_open_archived_or_subproject_only(self):
|
||||
# 지금 연 프로젝트가 보관(7)·서브프로젝트(5)면 그 하나만 더한다(다른 보관 프로젝트는 읽지 않는다)
|
||||
self.call("all", pid=7)
|
||||
self.assertEqual(self.st.asked_projects, [1, 2, 7])
|
||||
self.call("all", pid=5)
|
||||
self.assertEqual(self.st.asked_projects, [1, 2, 5])
|
||||
|
||||
def test_no_access_is_rejected(self):
|
||||
with patch.object(api, "_require_user", return_value={"email": "me@test", "role": "pro"}), \
|
||||
patch.object(api, "_db_or_503", return_value=self.st), \
|
||||
|
||||
@@ -11,7 +11,7 @@ from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.project import store
|
||||
from app.modules.project.db import ProjectStore
|
||||
from tests.test_project_meeting_cells import Connection
|
||||
from tests.test_project_meeting_cells import Connection, Result
|
||||
|
||||
api = importlib.import_module("app.modules.project.router")
|
||||
|
||||
@@ -20,11 +20,22 @@ class LockConnection(Connection):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.completed = set() # 완료된 주차 시작일
|
||||
# 있는 회의록 — 9/28 주차(9/28~9/30)와 바로 다음 주차(10/1, 목요일 시작 — 달이 바뀐다)
|
||||
self.meetings = {date(2026, 9, 28), date(2026, 10, 1)}
|
||||
self.shared = [] # FOR SHARE 로 잠근 주차(다음 회의록)
|
||||
|
||||
def execute(self, sql, params=()):
|
||||
if sql.startswith("SELECT completed_at FROM goal_meetings WHERE week_start = %s"):
|
||||
from tests.test_project_meeting_cells import Result
|
||||
if sql.endswith("FOR SHARE"):
|
||||
assert self.depth > 0, "다음 회의록 잠금은 트랜잭션 안에서"
|
||||
self.shared.append(params[0])
|
||||
if params[0] not in self.meetings:
|
||||
return Result([])
|
||||
return Result([{"completed_at": "done" if params[0] in self.completed else None}])
|
||||
if sql.startswith("UPDATE goal_meetings SET"):
|
||||
assert self.locked and self.depth > 0, "머리 변경은 회의록 행을 잠근 트랜잭션 안에서"
|
||||
self.calls.append((sql, params))
|
||||
return Result([{"week_start": params[-1]}])
|
||||
return super().execute(sql, params)
|
||||
|
||||
|
||||
@@ -55,10 +66,35 @@ class MeetingLockTests(unittest.TestCase):
|
||||
self.conn.completed.add(date(2026, 9, 28))
|
||||
out = self.st.update_meeting_item(item_id=1, fields={"result_note": "잘 됨", "result_amount": "100"})
|
||||
self.assertEqual((out["result_note"], out["result_amount"]), ("잘 됨", 100))
|
||||
self.assertEqual(self.conn.shared, [date(2026, 10, 1)]) # 달이 바뀐 다음 주차(목요일 시작)를 잠그고 확인
|
||||
self.conn.completed.add(date(2026, 10, 1))
|
||||
with self.assertRaises(store.MeetingLocked):
|
||||
self.st.update_meeting_item(item_id=1, fields={"result_note": "늦게"})
|
||||
|
||||
def test_completed_week_without_next_meeting_is_locked(self):
|
||||
# 예전엔 다음 주차 회의록이 없으면 완료된 회의록의 결과도 고칠 수 있었다
|
||||
self.conn.meetings.discard(date(2026, 10, 1))
|
||||
self.conn.completed.add(date(2026, 9, 28))
|
||||
with self.assertRaises(store.MeetingLocked):
|
||||
self.st.update_meeting_item(item_id=1, fields={"result_note": "다음 회의 전"})
|
||||
self.assertEqual(self.conn.rows[1]["result_note"], "")
|
||||
|
||||
def test_open_week_without_next_meeting_accepts_result(self):
|
||||
self.conn.meetings.discard(date(2026, 10, 1))
|
||||
out = self.st.update_meeting_item(item_id=1, fields={"result_note": "이번 주 결과"})
|
||||
self.assertEqual(out["result_note"], "이번 주 결과")
|
||||
|
||||
def test_header_update_checks_lock_inside_row_lock(self):
|
||||
self.st.update_meeting(week_start=date(2026, 9, 28), fields={"notes": "메모"})
|
||||
sqls = [s for s, _ in self.conn.calls]
|
||||
lock = next(i for i, s in enumerate(sqls) if s.startswith("SELECT week_start FROM goal_meetings") and "FOR UPDATE" in s)
|
||||
upd = next(i for i, s in enumerate(sqls) if s.startswith("UPDATE goal_meetings SET"))
|
||||
self.assertLess(lock, upd)
|
||||
self.conn.completed.add(date(2026, 9, 28))
|
||||
with self.assertRaises(store.MeetingLocked):
|
||||
self.st.update_meeting(week_start=date(2026, 9, 28), fields={"notes": "잠김"})
|
||||
self.assertEqual(sum(1 for s, _ in self.conn.calls if s.startswith("UPDATE goal_meetings SET")), 1)
|
||||
|
||||
def test_anyone_edits_but_only_admin_completes(self):
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
|
||||
@@ -346,7 +346,7 @@ def test_file_comment_atomic_and_idempotent():
|
||||
# [04] 날짜 범위
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def test_date_range_validation():
|
||||
p = _project("P-date", ADMIN, (BOB,))
|
||||
p = _project("P-date", ADMIN, (BOB, PRO))
|
||||
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
|
||||
@@ -359,11 +359,11 @@ def test_date_range_validation():
|
||||
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
|
||||
# 프로젝트도 같은 규칙(부분 수정 포함)
|
||||
# 프로젝트도 같은 규칙(부분 수정 포함) — 프로젝트 수정은 Pro user 이상 멤버(2026-10-12)
|
||||
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("PUT", pu, PRO, json={"start_date": "2026-11-01", "due_date": "2026-10-01"}).status_code == 400
|
||||
assert req("PUT", pu, PRO, json={"due_date": "2026-10-01"}).status_code == 200
|
||||
assert req("PUT", pu, PRO, json={"start_date": "2026-11-01"}).status_code == 400
|
||||
assert req("POST", "/project/api/projects", PRO, json={"name": "d", "start_date": "2026-11-02", "due_date": "2026-11-01"}).status_code == 400
|
||||
|
||||
|
||||
@@ -1031,6 +1031,141 @@ def test_meeting_perf_unknown_vs_zero():
|
||||
_drop_meetings([w, w - timedelta(days=7)])
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# [검토 2026-10-12] 실제 DB — 동시성·조회 범위·알림 페이지·배지·회의록 결과 잠금
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _race(fns):
|
||||
"""함수들을 최대한 같은 순간에 돌리고 (결과 또는 예외) 목록."""
|
||||
gate = threading.Barrier(len(fns))
|
||||
out: list = [None] * len(fns)
|
||||
|
||||
def run(i, fn):
|
||||
gate.wait()
|
||||
try:
|
||||
out[i] = fn()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
out[i] = exc
|
||||
ths = [threading.Thread(target=run, args=(i, f)) for i, f in enumerate(fns)]
|
||||
[t.start() for t in ths]
|
||||
[t.join() for t in ths]
|
||||
return out
|
||||
|
||||
|
||||
def test_review_task_dates_never_invert_under_race():
|
||||
p = _project("P-race", ADMIN, (BOB,))
|
||||
s = _stage(p["id"], by=ADMIN)
|
||||
for _ in range(10):
|
||||
t = ST.create_task(project_id=p["id"], title="race", stage_id=s["id"],
|
||||
start_date="2026-10-10", due_date="2026-10-20", created_by=BOB)
|
||||
_race([lambda: ST.update_task(task_id=t["id"], fields={"start_date": "2026-10-18"}),
|
||||
lambda: ST.update_task(task_id=t["id"], fields={"due_date": "2026-10-12"})])
|
||||
got = ST.get_task(task_id=t["id"])
|
||||
assert got["start_date"] <= got["due_date"], got # 한쪽은 지금 값으로 검사돼 거절된다
|
||||
# 프로젝트도 같은 규칙
|
||||
for _ in range(5):
|
||||
q = ST.create_project(name=f"race-{uuid.uuid4().hex[:4]}", owner_email=ADMIN, created_by=ADMIN,
|
||||
start_date="2026-10-10", due_date="2026-10-20")
|
||||
_race([lambda: ST.update_project(project_id=q["id"], fields={"start_date": "2026-10-18"}),
|
||||
lambda: ST.update_project(project_id=q["id"], fields={"due_date": "2026-10-12"})])
|
||||
got = ST.get_project(project_id=q["id"])
|
||||
assert got["start_date"] <= got["due_date"], got
|
||||
|
||||
|
||||
def test_review_concurrent_completion_logs_once():
|
||||
p = _project("P-done-race", ADMIN, (BOB,))
|
||||
s = _stage(p["id"], by=ADMIN)
|
||||
t = ST.create_task(project_id=p["id"], title="once", stage_id=s["id"], created_by=BOB)
|
||||
outs = _race([lambda: ST.update_task(task_id=t["id"], fields={"completed": True}, actor=BOB) for _ in range(4)])
|
||||
assert sum(1 for o in outs if isinstance(o, dict) and o["_newly_completed"]) == 1, outs
|
||||
assert _count("SELECT COUNT(*) AS n FROM project_activity WHERE task_id = %s AND action = 'completed'", t["id"]) == 1
|
||||
|
||||
|
||||
def test_review_subproject_tasks_and_archived_scope():
|
||||
parent = _project("P-parent", ADMIN, (BOB, CAROL))
|
||||
child = ST.create_project(name=f"child-{uuid.uuid4().hex[:4]}", parent_id=parent["id"], owner_email=ADMIN, created_by=ADMIN)
|
||||
ST.add_member(project_id=child["id"], user_email=CAROL)
|
||||
tp = ST.create_task(project_id=parent["id"], title="부모", created_by=ADMIN)
|
||||
tc = ST.create_task(project_id=child["id"], title="자식", created_by=ADMIN)
|
||||
ids = lambda who: sorted(t["id"] for t in req("GET", f"/project/api/projects/{parent['id']}/tasks", who).json()["tasks"])
|
||||
assert ids(BOB) == [tp["id"]] # 부모 멤버·자식 비멤버 — 자식 작업 안 보임
|
||||
assert ids(CAROL) == sorted([tp["id"], tc["id"]])
|
||||
assert req("GET", f"/project/api/projects/{parent['id']}/tasks", ADMIN).status_code == 200 # ADMIN = owner
|
||||
# 보관된 프로젝트를 열어도 자기 작업은 받는다(스냅샷)
|
||||
arch = _project("P-arch", BOB)
|
||||
ta = ST.create_task(project_id=arch["id"], title="보관 작업", created_by=BOB)
|
||||
ST.update_project(project_id=arch["id"], fields={"status": "archived"})
|
||||
snap = req("GET", f"/project/api/projects/{arch['id']}/snapshot?scope=all", BOB).json()
|
||||
assert ta["id"] in [t["id"] for t in snap["tasks"]]
|
||||
assert [x["id"] for x in snap["projects"] if x.get("view_only")] == [arch["id"]]
|
||||
|
||||
|
||||
def test_review_alert_paging_and_badges():
|
||||
me = USERS.add(f"alert-{uuid.uuid4().hex[:6]}@test.local")
|
||||
p = _project("P-alert", ADMIN, (me,))
|
||||
t = ST.create_task(project_id=p["id"], title="x", created_by=ADMIN)
|
||||
ST.add_notification(recipient_email=me, actor_email=ADMIN, project_id=p["id"], task_id=t["id"], type="assigned", title="배정")
|
||||
for _ in range(55):
|
||||
ST.add_notification(recipient_email=me, actor_email=ADMIN, project_id=p["id"], task_id=t["id"], type="comment", title="댓글")
|
||||
out = req("GET", "/project/api/notifications/alerts?after=0", me).json()
|
||||
assert [a["type"] for a in out["alerts"]] == ["assigned"] and out["alerts"][0]["href"] == f"/project/t/{t['id']}"
|
||||
assert req("GET", "/project/api/notifications/unread-count", me).json()["unread"] == 56
|
||||
# 권한을 잃은 프로젝트의 알림은 배지에서 빠진다(기록은 그대로)
|
||||
ST.remove_member(project_id=p["id"], user_email=me)
|
||||
assert req("GET", "/project/api/notifications/unread-count", me).json()["unread"] == 0
|
||||
# 내 작업 배지·목록 — 미완료는 전부, 완료는 최근 것만
|
||||
q = _project("P-my", ADMIN, (me,))
|
||||
open_ids = [ST.create_task(project_id=q["id"], title=f"o{i}", assignee_email=me, created_by=ADMIN)["id"] for i in range(3)]
|
||||
done_ids = []
|
||||
for i in range(3):
|
||||
d = ST.create_task(project_id=q["id"], title=f"d{i}", assignee_email=me, created_by=ADMIN)
|
||||
ST.update_task(task_id=d["id"], fields={"completed": True})
|
||||
done_ids.append(d["id"])
|
||||
rows = ST.list_my_tasks(assignee_email=me, completed_limit=1)
|
||||
assert sorted(r["id"] for r in rows if not r["completed_at"]) == sorted(open_ids)
|
||||
assert [r["id"] for r in rows if r["completed_at"]] == [done_ids[-1]]
|
||||
assert req("GET", "/project/api/my-tasks/open-count", me).json()["open"] == 3
|
||||
ST.add_mentions(task_id=open_ids[0], emails=[me], actor_email=ADMIN)
|
||||
assert req("GET", "/project/api/mentions/unread-count", me).json()["unread"] == 1
|
||||
|
||||
|
||||
def test_review_reorder_and_creator_membership():
|
||||
mine = _project("P-ord", PRO)
|
||||
other = _project("P-ord-other", ADMIN)
|
||||
assert req("PUT", "/project/api/projects/order", PRO, json={"ordered_ids": [mine["id"], other["id"]]}).status_code == 403
|
||||
assert req("PUT", "/project/api/projects/order", PRO, json={"ordered_ids": [mine["id"], mine["id"]]}).status_code == 400
|
||||
assert req("PUT", "/project/api/projects/order", PRO, json={"ordered_ids": [mine["id"]]}).status_code == 200
|
||||
r = req("POST", "/project/api/projects", PRO, json={"name": f"own-{RUN}", "owner_email": ALICE})
|
||||
assert r.status_code == 201, r.text
|
||||
pid = r.json()["project"]["id"]
|
||||
assert ST.get_project(project_id=pid)["owner_email"] == ALICE
|
||||
assert req("GET", f"/project/p/{pid}", PRO).status_code == 200 # 만든 직후 자기 프로젝트를 연다(멤버 행)
|
||||
ST.remove_member(project_id=pid, user_email=PRO)
|
||||
assert req("GET", f"/project/p/{pid}", PRO).status_code == 403 # created_by 로는 권한이 남지 않는다
|
||||
|
||||
|
||||
def test_review_meeting_result_lock_rules():
|
||||
from app.modules.project import store
|
||||
|
||||
w2 = date(2031, 10, 1) # 수요일 시작 1주차(달 경계)
|
||||
w1 = store.prev_week_period(w2)[0] # 9월 마지막 주차
|
||||
_drop_meetings([w1, w2])
|
||||
try:
|
||||
_create_meeting(w1)
|
||||
item = ST.get_meeting(week_start=w1)["items"][0]["id"]
|
||||
put = lambda body: req("PUT", f"/project/api/goals/meeting-items/{item}", BOB, json=body).status_code
|
||||
ST.set_meeting_completed(week_start=w1, done=True, by=ADMIN)
|
||||
assert put({"result_note": "다음 회의 전"}) == 409 # 다음 주차 회의록이 없으면 그 주가 완료되면 잠김
|
||||
_create_meeting(w2)
|
||||
assert put({"result_note": "다음 회의에서"}) == 200 # 다음 주차 회의록이 열려 있으면 결과는 적을 수 있다
|
||||
assert put({"content": "내용"}) == 409 # 주요 업무는 그 주 완료로 잠김(잠금 차이 보존)
|
||||
ST.set_meeting_completed(week_start=w2, done=True, by=ADMIN)
|
||||
assert put({"result_note": "늦게"}) == 409
|
||||
r = req("PUT", f"/project/api/goals/meetings/{w2}", BOB, json={"notes": "잠김"})
|
||||
assert r.status_code == 409, r.text # 완료된 회의록 머리도
|
||||
finally:
|
||||
_drop_meetings([w1, w2])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if not ENABLED:
|
||||
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")
|
||||
|
||||
@@ -24,6 +24,10 @@ class FakeStore:
|
||||
def list_notifications(self, recipient_email, unread_only=False, limit=100):
|
||||
return ROWS[:limit]
|
||||
|
||||
def list_unread_after(self, recipient_email, after_id, types, limit=200):
|
||||
return sorted((r for r in ROWS if not r["is_read"] and r["id"] > after_id and r["type"] in types),
|
||||
key=lambda r: r["id"])[:limit]
|
||||
|
||||
def mark_read(self, notification_id, recipient_email):
|
||||
self.read.append((notification_id, recipient_email))
|
||||
|
||||
@@ -86,6 +90,8 @@ class NotifierApiTests(unittest.TestCase):
|
||||
out = res.json()
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [6, 8])
|
||||
self.assertEqual((out["me"], out["latest_id"], out["name"]), ("me@test.local", 8, "나"))
|
||||
# PC 알림 [열기] 도 웹과 같은 주소(작업 공유 링크) — 서버가 지금 권한으로 열 프로젝트를 고른다
|
||||
self.assertEqual([a["href"] for a in out["alerts"]], ["/project/t/3", "/project/t/1"])
|
||||
|
||||
def test_alerts_rejects_missing_or_unknown_token(self):
|
||||
self.assertEqual(self.client.get("/project/api/notifier/alerts").status_code, 401)
|
||||
|
||||
@@ -0,0 +1,478 @@
|
||||
"""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.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([])
|
||||
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))
|
||||
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()
|
||||
@@ -27,6 +27,10 @@ class FakeStore(MagicMock):
|
||||
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 [{"id": pid, "parent_id": None} for pid, ms in self.MEMBERS.items()
|
||||
if member_email is None or member_email in ms]
|
||||
|
||||
def get_project(self, project_id):
|
||||
return {"id": project_id, "name": "P1", "owner_email": "admin@test.local", "created_by": "admin@test.local"}
|
||||
|
||||
@@ -145,6 +149,8 @@ class RoleApiTests(unittest.TestCase):
|
||||
body = {"ordered_ids": [1]}
|
||||
self.assertEqual(self.call(USER, "PUT", "/project/api/projects/order", json=body).status_code, 403)
|
||||
self.assertEqual(self.call(PRO, "PUT", "/project/api/projects/order", json=body).status_code, 200)
|
||||
# Pro user 라도 멤버가 아닌 프로젝트는 순서를 못 바꾼다(검토 2026-10-12)
|
||||
self.assertEqual(self.call(OUTSIDER_PRO, "PUT", "/project/api/projects/order", json=body).status_code, 403)
|
||||
|
||||
def test_section_delete_admin_any_others_creator(self):
|
||||
self.assertEqual(self.call(PRO, "DELETE", "/project/api/projects/1/stages/5").status_code, 403)
|
||||
@@ -173,8 +179,7 @@ class RoleApiTests(unittest.TestCase):
|
||||
self.assertEqual(self.call(PRO, "GET", "/project/api/projects/1/subtasks-summary").status_code, 200)
|
||||
|
||||
def test_trash_restore_pro(self):
|
||||
self.st.list_trash.return_value = [{"id": 4, "project_id": 1}]
|
||||
self.st.list_projects.return_value = [{"id": 1}]
|
||||
self.st.list_trash.return_value = [{"id": 4, "project_id": 1}] # 프로젝트 1 = PRO 가 멤버(list_projects)
|
||||
self.st.restore_trash.return_value = {"restored": 1}
|
||||
self.assertEqual(self.call(USER, "POST", "/project/api/trash/4/restore").status_code, 403)
|
||||
self.assertEqual(self.call(PRO, "POST", "/project/api/trash/4/restore").status_code, 200)
|
||||
|
||||
Reference in New Issue
Block a user