228 lines
9.0 KiB
JavaScript
228 lines
9.0 KiB
JavaScript
import { chromium, request } from "playwright";
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = path.dirname(__filename);
|
|
|
|
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
const runId = `slice7-demo-${Date.now()}`;
|
|
const webBase = process.env.SLICE7_WEB_URL || "http://localhost:3000";
|
|
const apiBase = process.env.SLICE7_API_URL || "http://127.0.0.1:8010/api/v1";
|
|
const healthUrl = process.env.SLICE7_HEALTH_URL || "http://127.0.0.1:8010/health";
|
|
const sharedAiHealthUrl = process.env.SLICE7_SHARED_AI_HEALTH_URL || "http://127.0.0.1:18011/health";
|
|
const adminPassword = process.env.AI_CONTRACT_ADMIN_PASSWORD || "123456";
|
|
const artifactDir =
|
|
process.env.SLICE7_ARTIFACT_DIR ||
|
|
path.resolve(__dirname, "..", "..", "project-docs", "qa-artifacts", "slice7-demo-assets-closed-loop", stamp);
|
|
|
|
fs.mkdirSync(artifactDir, { recursive: true });
|
|
|
|
const results = [];
|
|
const state = {
|
|
api: null,
|
|
browser: null,
|
|
contexts: [],
|
|
admin: null,
|
|
};
|
|
|
|
function apiUrl(route) {
|
|
return `${apiBase.replace(/\/$/, "")}${route}`;
|
|
}
|
|
|
|
function screenshotPath(name) {
|
|
return path.join(artifactDir, `${name}.png`);
|
|
}
|
|
|
|
function assert(condition, message, details = undefined) {
|
|
if (!condition) {
|
|
const error = new Error(message);
|
|
error.details = details;
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async function step(id, title, fn) {
|
|
const startedAt = new Date().toISOString();
|
|
const started = Date.now();
|
|
try {
|
|
const details = await fn();
|
|
const item = { id, title, status: "PASS", duration_ms: Date.now() - started, started_at: startedAt, details: details || {} };
|
|
results.push(item);
|
|
console.log(`PASS ${id} ${title}`);
|
|
return item;
|
|
} catch (error) {
|
|
const item = {
|
|
id,
|
|
title,
|
|
status: "FAIL",
|
|
duration_ms: Date.now() - started,
|
|
started_at: startedAt,
|
|
error: error.message,
|
|
details: error.details || {},
|
|
};
|
|
results.push(item);
|
|
console.error(`FAIL ${id} ${title}: ${error.message}`);
|
|
return item;
|
|
}
|
|
}
|
|
|
|
async function apiRequest(method, route, options = {}) {
|
|
const headers = {
|
|
...(options.authToken ? { Authorization: `Bearer ${options.authToken}` } : {}),
|
|
...(options.headers || {}),
|
|
};
|
|
const response = await state.api[method](apiUrl(route), { ...options, headers });
|
|
const text = await response.text();
|
|
let body = null;
|
|
if (text) {
|
|
try {
|
|
body = JSON.parse(text);
|
|
} catch {
|
|
body = text;
|
|
}
|
|
}
|
|
return { response, body, text };
|
|
}
|
|
|
|
function expectOk(payload, label) {
|
|
assert(payload.response.status() >= 200 && payload.response.status() < 300, `${label} HTTP ${payload.response.status()}`, {
|
|
body: payload.body,
|
|
});
|
|
if (payload.body && typeof payload.body === "object" && "code" in payload.body) {
|
|
assert(payload.body.code === 0, `${label} API code ${payload.body.code}`, { body: payload.body });
|
|
}
|
|
}
|
|
|
|
async function login(account, password) {
|
|
const payload = await apiRequest("post", "/auth/login", { data: { account, password } });
|
|
expectOk(payload, `login ${account}`);
|
|
return payload.body.data;
|
|
}
|
|
|
|
async function attachApiProxy(context) {
|
|
await context.route("**/api/v1/**", async (route) => {
|
|
const browserRequest = route.request();
|
|
const browserUrl = new URL(browserRequest.url());
|
|
const targetUrl = apiUrl(browserUrl.pathname.replace(/^\/api\/v1/, "") + browserUrl.search);
|
|
const headers = { ...browserRequest.headers() };
|
|
delete headers.host;
|
|
|
|
const response = await state.api.fetch(targetUrl, {
|
|
method: browserRequest.method(),
|
|
headers,
|
|
data: browserRequest.postDataBuffer() ?? undefined,
|
|
});
|
|
await route.fulfill({ response });
|
|
});
|
|
}
|
|
|
|
async function createAuthenticatedContext(userSession) {
|
|
const context = await state.browser.newContext({ viewport: { width: 1440, height: 1100 } });
|
|
await context.addInitScript(
|
|
({ token, user }) => {
|
|
window.localStorage.setItem("access_token", token);
|
|
window.localStorage.setItem("auth-store", JSON.stringify({ state: { accessToken: token, currentUser: user }, version: 0 }));
|
|
},
|
|
{ token: userSession.access_token, user: userSession.user },
|
|
);
|
|
await attachApiProxy(context);
|
|
state.contexts.push(context);
|
|
return context;
|
|
}
|
|
|
|
async function run() {
|
|
state.api = await request.newContext();
|
|
state.browser = await chromium.launch({ headless: true });
|
|
|
|
await step("ENV-001", "frontend, backend, and shared-ai health", async () => {
|
|
const [frontend, backendHealth, sharedAiHealth] = await Promise.all([
|
|
state.api.get(`${webBase}/`),
|
|
state.api.get(healthUrl),
|
|
state.api.get(sharedAiHealthUrl),
|
|
]);
|
|
assert(frontend.status() === 200, `frontend / status ${frontend.status()}`);
|
|
assert(backendHealth.status() === 200, `backend /health status ${backendHealth.status()}`);
|
|
assert(sharedAiHealth.status() === 200, `shared-ai stub /health status ${sharedAiHealth.status()}`);
|
|
return { webBase, apiBase, healthUrl, sharedAiHealthUrl, artifactDir };
|
|
});
|
|
|
|
await step("AUTH-001", "default admin seed and login", async () => {
|
|
const seed = await apiRequest("post", "/auth/seed-admin");
|
|
expectOk(seed, "seed default admin");
|
|
state.admin = await login("admin@example.com", adminPassword);
|
|
assert(state.admin.user.role === "admin", "admin role mismatch", state.admin.user);
|
|
return { user: state.admin.user.username, role: state.admin.user.role };
|
|
});
|
|
|
|
await step("SEED-001", "admin seeds fixed demo assets", async () => {
|
|
const payload = await apiRequest("post", "/system/pilot-demo-assets/seed", { authToken: state.admin.access_token });
|
|
expectOk(payload, "seed pilot demo assets");
|
|
const data = payload.body.data;
|
|
assert(data.templates.total >= 3, "default template count should be at least 3", data.templates);
|
|
assert(data.knowledge.status === "ready", "demo knowledge should be ready", data.knowledge);
|
|
assert(data.knowledge.knowledge_base.name === "AI合同试点演示知识库", "demo knowledge base name mismatch", data.knowledge);
|
|
assert(data.knowledge.document.status === "indexed", "demo knowledge document should be indexed", data.knowledge.document);
|
|
assert(data.demo_accounts.roles.includes("legal") && data.demo_accounts.roles.includes("business"), "demo roles missing", data.demo_accounts);
|
|
return {
|
|
templates_total: data.templates.total,
|
|
knowledge_base_id: data.knowledge.knowledge_base.id,
|
|
document_id: data.knowledge.document.id,
|
|
};
|
|
});
|
|
|
|
await step("ASSET-001", "templates and knowledge base are visible through management APIs", async () => {
|
|
const [templates, knowledgeBases] = await Promise.all([
|
|
apiRequest("get", "/templates?page=1&page_size=20", { authToken: state.admin.access_token }),
|
|
apiRequest("get", "/knowledge-bases?page=1&page_size=20", { authToken: state.admin.access_token }),
|
|
]);
|
|
expectOk(templates, "template list");
|
|
expectOk(knowledgeBases, "knowledge base list");
|
|
assert(templates.body.data.total >= 3, "seeded templates missing from template list", templates.body.data);
|
|
const demoKb = knowledgeBases.body.data.items.find((item) => item.name === "AI合同试点演示知识库");
|
|
assert(demoKb, "seeded demo knowledge base missing", knowledgeBases.body.data);
|
|
assert(demoKb.document_count >= 1, "demo knowledge base should include a document", demoKb);
|
|
return { templates_total: templates.body.data.total, demo_knowledge_base_id: demoKb.id };
|
|
});
|
|
|
|
await step("BROWSER-001", "pilot readiness page can seed demo assets from UI", async () => {
|
|
const context = await createAuthenticatedContext(state.admin);
|
|
const page = await context.newPage();
|
|
await page.goto(`${webBase}/pilot-readiness`, { waitUntil: "domcontentloaded" });
|
|
await page.getByTestId("seed-pilot-demo-assets").click();
|
|
await page.getByTestId("pilot-demo-assets-result").waitFor({ state: "visible", timeout: 12000 });
|
|
await page.screenshot({ path: screenshotPath("pilot-readiness-demo-assets"), fullPage: true });
|
|
const resultText = await page.getByTestId("pilot-demo-assets-result").innerText();
|
|
assert(resultText.includes("AI合同试点演示知识库"), "UI seed result missing demo knowledge base", resultText);
|
|
assert(resultText.includes("pilot-contract-review-playbook.txt"), "UI seed result missing demo document", resultText);
|
|
return { screenshot: "pilot-readiness-demo-assets.png" };
|
|
});
|
|
}
|
|
|
|
try {
|
|
await run();
|
|
} finally {
|
|
for (const context of state.contexts) {
|
|
await context.close().catch(() => {});
|
|
}
|
|
if (state.browser) {
|
|
await state.browser.close().catch(() => {});
|
|
}
|
|
if (state.api) {
|
|
await state.api.dispose().catch(() => {});
|
|
}
|
|
const summary = {
|
|
run_id: runId,
|
|
artifact_dir: artifactDir,
|
|
passed: results.filter((item) => item.status === "PASS").length,
|
|
failed: results.filter((item) => item.status === "FAIL").length,
|
|
results,
|
|
};
|
|
fs.writeFileSync(path.join(artifactDir, "summary.json"), `${JSON.stringify(summary, null, 2)}\n`, "utf8");
|
|
console.log(`Wrote ${path.join(artifactDir, "summary.json")}`);
|
|
if (summary.failed > 0) {
|
|
process.exitCode = 1;
|
|
}
|
|
}
|