droboticflow/tests/browser/review-session.mjs

132 lines
5.8 KiB
JavaScript

// Real application + local snapshot API: never mocks review-session responses.
// Fixtures are prepared separately under the ignored verification directory.
import { chromium } from "playwright";
import assert from "node:assert/strict";
import fs from "node:fs/promises";
const dir = process.env.REVIEW_SESSION_FIXTURES || "local-data/verification/review-focused-20260922";
const base = process.env.REVIEW_SESSION_URL || "http://review-session.test:5178";
const hostname = new URL(base).hostname;
const index = JSON.parse(await fs.readFile(`${dir}/fixture-index.json`, "utf8"));
const browser = await chromium.launch({
executablePath: process.env.BROWSER_EXECUTABLE || "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
headless: true,
args: [`--host-resolver-rules=MAP ${hostname} 127.0.0.1`, "--no-proxy-server"],
});
const report = [];
try {
for (const mode of process.env.REVIEW_SESSION_MODE ? [process.env.REVIEW_SESSION_MODE] : ["quality", "acceptance"]) {
const auth = JSON.parse(
await fs.readFile(`${dir}/fixture-${mode === "quality" ? "qc" : "acceptance"}-auth.json`, "utf8"),
);
auth.cookies = auth.cookies.map((cookie) => ({ ...cookie, domain: hostname }));
const context = await browser.newContext({ storageState: auth, viewport: { width: 1600, height: 1000 } });
const errors = [];
const a = await context.newPage(),
b = await context.newPage();
for (const page of [a, b]) {
page.setDefaultTimeout(20000);
page.on("pageerror", (e) => errors.push(e.message));
}
const fixture = index[mode][0];
const url = `${base}/plugins/annotation-qa/workflows/all/${mode}?projectId=${index.projectId}${fixture.taskId ? `&taskId=${fixture.taskId}` : ""}`;
const open = async (page) => {
await page.goto(url);
await page.getByRole("button", { name: /^我的任务/ }).click();
if (mode === "acceptance")
await page
.getByTestId("acceptance-task-card")
.first()
.getByRole("button", { name: /^预览 / })
.click()
.catch(async (cause) => {
console.log((await page.locator("body").innerText()).slice(-7000));
throw cause;
});
await page
.getByRole("status")
.filter({ hasText: /本页可编辑审查意见|本页只读/ })
.waitFor();
};
let firstSession;
a.on("response", async (response) => {
if (
response.url().endsWith("/review-session") &&
["acquire", "takeover"].includes(response.request().postDataJSON()?.action) &&
response.ok()
)
firstSession = { ...(await response.json()), pageId: response.request().postDataJSON().pageId };
});
await open(a);
if (await a.getByRole("button", { name: "在本页接管审查", exact: true }).count())
await a.getByRole("button", { name: "在本页接管审查", exact: true }).click();
await a.getByText("本页可编辑审查意见", { exact: true }).waitFor();
assert.equal(await a.evaluate(() => window.isSecureContext), false, "test must use actual ordinary HTTP");
assert.equal(await a.evaluate(() => typeof navigator.locks), "undefined", "HTTP must not have Web Locks");
await open(b);
await b.getByText("本页只读,可接管后编辑审查意见。", { exact: true }).waitFor();
const label = mode === "quality" ? "审核通过" : "验收通过";
assert.equal(
(await b.getByRole("button", { name: label, exact: true }).count()) > 0 &&
(await b.getByRole("button", { name: label, exact: true }).isEnabled()),
false,
"second page decision must be disabled",
);
await b.getByRole("button", { name: "在本页接管审查", exact: true }).click();
await b.getByText("本页可编辑审查意见", { exact: true }).waitFor();
const endpoint =
mode === "quality"
? `/api/plugins/annotation-qa/tasks/${fixture.taskId}/reviews`
: `/api/human-items/${fixture.humanItemId}/decisions`;
const results = await a.evaluate(
async ({ endpoint, session }) => {
const csrfCookie = document.cookie.split("; ").find((entry) => entry.startsWith("droboticflow_csrf="));
const csrf = csrfCookie ? decodeURIComponent(csrfCookie.split("=").slice(1).join("=")) : "";
const codes = [];
for (const leaseHeaders of [
{},
{ "X-Review-Page": session.pageId, "X-Review-Generation": String(session.generation) },
]) {
const response = await fetch(endpoint, {
method: "POST",
headers: { "Content-Type": "application/json", "X-Droboticflow-CSRF-Token": csrf, ...leaseHeaders },
body: JSON.stringify({ stage: "quality", decision: "approved", version: 1 }),
});
codes.push({ status: response.status, body: await response.json() });
}
return codes;
},
{ endpoint, session: firstSession },
);
assert.deepEqual(
results.map((r) => [r.status, r.body.code]),
[
[409, "review_session_lost"],
[409, "review_session_lost"],
],
);
await a
.getByRole("status")
.filter({ hasText: /失去编辑权/ })
.waitFor();
assert.equal(
(await a.getByRole("button", { name: label, exact: true }).count()) > 0 &&
(await a.getByRole("button", { name: label, exact: true }).isEnabled()),
false,
);
await b.screenshot({ path: `${dir}/session-${mode}-takeover.png`, fullPage: true });
assert.deepEqual(errors, []);
report.push({
mode,
ordinaryHTTP: true,
webLocks: false,
takeover: true,
oldPageAndMissingHeadersRejected: results.map((r) => r.status),
});
await context.close();
}
await fs.writeFile(`${dir}/review-session-browser.json`, JSON.stringify(report, null, 2));
console.log(JSON.stringify(report));
} finally {
await browser.close();
}