Files
story/test/e2e/visual-family-invitation-device-controls.mjs
T

108 lines
7.4 KiB
JavaScript

import { createRequire } from "node:module";
import { createHash, randomUUID } from "node:crypto";
import { execFileSync } from "node:child_process";
import { mkdir } from "node:fs/promises";
import { fileURLToPath } from "node:url";
const require = createRequire(process.env.PLAYWRIGHT_REQUIRE_FROM ?? import.meta.url);
const { chromium } = require("playwright");
const outputDirectory = new URL("./screenshots/", import.meta.url);
const webURL = process.env.VISUAL_WEB_URL ?? "http://localhost:3100";
const webHostPattern = new RegExp(new URL(webURL).host.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
const oidcURLPattern = new RegExp(process.env.VISUAL_OIDC_URL_PATTERN ?? "localhost:58180");
const username = process.env.VISUAL_USERNAME ?? "owner";
const password = process.env.VISUAL_PASSWORD ?? "LocalOnly123!";
const invitationInternalID = randomUUID();
const invitationPublicID = randomUUID();
const marker = invitationPublicID.slice(0, 8);
const invitationHint = `页面邀请撤销夹具-${marker}`;
const tokenDigest = createHash("sha256").update(`visual-invitation-${invitationPublicID}`).digest("hex");
const deviceID = "10000000-0000-0000-0000-000000000511";
await mkdir(outputDirectory, { recursive: true });
function psql(statement) {
return execFileSync("docker", ["compose", "exec", "-T", "postgres", "psql", "-v", "ON_ERROR_STOP=1", "-U", "voice", "-d", "voice_platform", "-Atc", statement], {
cwd: process.cwd(), encoding: "utf8", stdio: ["ignore", "pipe", "pipe"]
}).trim();
}
function cleanup() {
psql(`DELETE FROM member_invitation WHERE id='${invitationInternalID}'::uuid;`);
}
psql(`INSERT INTO member_invitation(id,public_id,tenant_id,household_id,invitee_hint,token_digest,role,expires_at,created_by)
VALUES('${invitationInternalID}'::uuid,'${invitationPublicID}'::uuid,'10000000-0000-0000-0000-000000000001'::uuid,(SELECT id FROM household WHERE public_id='10000000-0000-0000-0000-000000000211'::uuid),'${invitationHint}','${tokenDigest}','viewer',now()+interval '1 day','10000000-0000-0000-0000-000000000101'::uuid);`);
const diagnosticCountBefore = Number(psql(`SELECT count(*) FROM device_command WHERE device_id=(SELECT id FROM device WHERE public_id='${deviceID}'::uuid) AND command_type='diagnostics';`));
const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROME_PATH ?? "C:/Program Files/Google/Chrome/Application/chrome.exe" });
const page = await browser.newPage({ viewport: { width: 1440, height: 1050 }, deviceScaleFactor: 1 });
const consoleErrors = [];
const failedRequests = [];
const mutations = [];
page.on("console", (message) => { if (message.type() === "error") consoleErrors.push(message.text()); });
page.on("request", (request) => {
if (request.method() === "POST" && (/\/api\/v1\/households\/[^/]+\/invitations\/[^/]+\/revoke$/.test(request.url()) || /\/api\/v1\/devices\/[^/]+\/commands$/.test(request.url()))) mutations.push(`${request.method()} ${request.url()}`);
});
page.on("requestfailed", (request) => {
const failure = request.failure()?.errorText ?? "failed";
const requestURL = new URL(request.url());
if (request.method() === "GET" && requestURL.pathname === "/api/v1/events" && failure.includes("ERR_ABORTED")) return;
failedRequests.push(`${request.method()} ${request.url()} ${failure}`);
});
try {
await page.goto(webURL, { waitUntil: "networkidle" });
await page.getByRole("button", { name: "登录研发环境" }).click();
await page.waitForURL(oidcURLPattern);
await page.locator("#username").fill(username);
await page.locator("#password").fill(password);
await page.locator("#kc-login").click();
await page.waitForURL(webHostPattern, { timeout: 15000 });
await page.getByRole("heading", { name: "家庭业务工作台" }).waitFor();
await page.getByRole("button", { name: "家庭成员" }).click();
const invitationRow = page.locator(".member-row").filter({ hasText: invitationHint });
await invitationRow.waitFor();
await invitationRow.getByRole("button", { name: "撤销" }).click();
let form = page.getByRole("form", { name: "家庭业务受控操作" });
await form.waitFor();
let text = await form.textContent();
const invitationTargetBound = text?.includes(invitationPublicID) === true && text?.includes(invitationHint) === true && text?.includes("查看者") === true && text?.includes("原一次性凭据立即失效") === true;
let action = form.getByRole("button", { name: "确认撤销邀请" });
const invitationNeedsAcknowledgement = await action.isDisabled();
await form.getByLabel(/我确认该待接受邀请的一次性凭据将立即失效/).check();
const invitationEnabled = await action.isEnabled();
await form.getByRole("button", { name: "取消" }).click();
const invitationCancelClosed = await form.count() === 0;
await page.getByRole("button", { name: "设备管理" }).click();
const deviceCard = page.locator(".device-card").filter({ hasText: "simulated-terminal" });
await deviceCard.waitFor();
await deviceCard.getByRole("button", { name: "下发设备诊断" }).click();
form = page.getByRole("form", { name: "家庭业务受控操作" });
await form.waitFor();
text = await form.textContent();
const deviceTargetBound = text?.includes(deviceID) === true && text?.includes("测试长者") === true && text?.includes("sim-rev-a / 0.1.0-sim") === true && text?.includes("期望配置 v1") === true && text?.includes("音频、网络和存储") === true;
action = form.getByRole("button", { name: "确认下发诊断" });
const deviceNeedsAcknowledgement = await action.isDisabled();
await form.getByLabel(/我确认向该设备下发音频、网络和存储三项诊断命令/).check();
const deviceEnabled = await action.isEnabled();
await form.screenshot({ path: fileURLToPath(new URL("family-device-diagnostics-control.png", outputDirectory)) });
await form.getByRole("button", { name: "取消" }).click();
const deviceCancelClosed = await form.count() === 0;
const invitationUnchanged = psql(`SELECT (revoked_at IS NULL AND used_at IS NULL)::text FROM member_invitation WHERE id='${invitationInternalID}'::uuid;`) === "true";
const diagnosticCountAfter = Number(psql(`SELECT count(*) FROM device_command WHERE device_id=(SELECT id FROM device WHERE public_id='${deviceID}'::uuid) AND command_type='diagnostics';`));
const deviceCommandsUnchanged = diagnosticCountAfter === diagnosticCountBefore;
const overflow = await page.evaluate(() => [...document.querySelectorAll("body *")]
.filter((element) => element instanceof HTMLElement && element.scrollWidth > element.clientWidth + 2 && getComputedStyle(element).overflowX === "visible")
.slice(0, 20)
.map((element) => `${element.tagName}.${element.className}: ${element.clientWidth}/${element.scrollWidth}`));
const result = { invitationTargetBound, invitationNeedsAcknowledgement, invitationEnabled, invitationCancelClosed, deviceTargetBound, deviceNeedsAcknowledgement, deviceEnabled, deviceCancelClosed, invitationUnchanged, deviceCommandsUnchanged, mutations, overflow, consoleErrors, failedRequests };
console.log(JSON.stringify(result, null, 2));
if (Object.entries(result).some(([key, value]) => !["mutations", "overflow", "consoleErrors", "failedRequests"].includes(key) && value !== true) || mutations.length || overflow.length || consoleErrors.length || failedRequests.length) throw new Error("Family invitation and device control visual smoke failed");
} finally {
await browser.close();
cleanup();
}