import fs from 'node:fs' import path from 'node:path' import { ACCOUNT, ACTION_TIMEOUT, BE_BASE, FE_BASE, PASSWORD, SHOTS_DIR, TOKEN_KEY } from './config.mjs' import { encryptPassword } from './cipher.mjs' import { humanClick, humanFill, humanHover, humanPress, humanScrollTo, humanViewportFlicker, jitter } from './human.mjs' /** * 用例 DSL —— 344 条脚本共用的动作与断言。 * * 页面这边有个很大的便利:TDS/TDC 绝大多数管理页都由 web/src/components/ssw/common/CrudPage.vue * 渲染,DOM 是统一的(新建按钮 / 抽屉表单 / 行内链接按钮 / prompt 弹窗 / 关键字搜索)。 * 所以这里的选择器按那份组件的结构来写,一次写对,全站通用。 * * 注意:项目没有给 ant-design-vue 配中文 locale,Modal/Popconfirm 的确认按钮文案是 * 组件库默认英文(OK/Cancel)。因此凡是组件库自带的按钮一律按 .ant-btn-primary 类名点, * 不去赌文案;只有业务自己写死的中文(新建/保存/查询/删除…)才按文本定位。 * * 所有浏览器操作(click/fill/hover/scroll)默认走「人类行为模拟」(lib/human.mjs): * 鼠标移动走贝塞尔曲线 + 悬停停顿 + 字符级键入 + 操作间随机抖动; * 只有 URL 跳转、addInitScript 注入、网络 API 调用保持程序式(这些必须程序化)。 */ export class SkipError extends Error { constructor(msg) { super(msg) this.name = 'SkipError' this.isSkip = true } } export class ManualError extends Error { constructor(msg) { super(msg) this.name = 'ManualError' this.isManual = true } } export class AssertError extends Error { constructor(msg) { super(msg) this.name = 'AssertError' } } /** * 按钮文案匹配 —— Ant Design 会给「恰好两个汉字」的按钮中间插一个空格 * (`新建` 实际渲染成 `新 建`),但 type="link" / "text" 的按钮又不插 * (所以 `编辑`/`删除` 保持原样)。两种都要能点中,统一按「忽略空白」匹配。 */ export function btnName(label) { const body = [...label].map((ch) => ch.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('\\s*') return new RegExp(`^\\s*${body}\\s*$`) } /** * 后端统一返回 `{ code, msg, data }`。脚本里两种写法都常见: * - 读信封:`r.code` / `r.msg` / `r.data` * - 直接读数据:`r.id` / `r.account` / `r.userId`(把 `r` 当成 data 本体) * 这里用 Proxy 让两者都成立:顶层字段优先走信封,查不到时回落到 `data` 上的字段。 * 这样历史脚本「忘了写 .data」的写法也能跑,不必逐条改;真正的产品缺陷(data 里也没有该字段)仍会如实报 undefined。 */ export function wrapEnvelope(json) { if (json == null || typeof json !== 'object') return json const data = json.data const isObj = data != null && typeof data === 'object' return new Proxy(json, { get(target, prop, receiver) { if (prop === 'toJSON') return () => target if (typeof prop === 'symbol') return Reflect.get(target, prop, receiver) if (prop in target) return target[prop] if (isObj && prop in data) return data[prop] return undefined }, has(target, prop) { if (prop in target) return true if (isObj && prop in data) return true return false }, ownKeys(target) { const base = Reflect.ownKeys(target) const extra = isObj ? Reflect.ownKeys(data).filter((k) => !(k in target)) : [] return [...new Set([...base, ...extra])] }, getOwnPropertyDescriptor(target, prop) { if (prop in target) return Reflect.getOwnPropertyDescriptor(target, prop) if (isObj && prop in data) return Reflect.getOwnPropertyDescriptor(data, prop) return undefined } }) } let tokenCache = { token: null, at: 0 } /** 直接调后端拿 token —— 加密算法与前端 cipher.ts 等价 */ export async function apiLogin(account = ACCOUNT, password = PASSWORD, force = false) { if (!force && tokenCache.token && Date.now() - tokenCache.at < 30 * 60 * 1000) return tokenCache.token const body = new URLSearchParams({ account, password: encryptPassword(password), grant_type: 'password' }) const res = await fetch(`${BE_BASE}/api/oauth/Login`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'App-Code': 'sswflow', 'Jnpf-Origin': 'pc', 'Vue-Version': '3' }, body }) const json = await res.json().catch(() => ({})) if (json.code !== 200 || !json.data?.token) { throw new Error(`登录失败:code=${json.code} msg=${json.msg || res.status}`) } const token = json.data.token.startsWith('bearer ') ? json.data.token : `bearer ${json.data.token}` if (account === ACCOUNT) tokenCache = { token, at: Date.now() } return token } export function resetTokenCache() { tokenCache = { token: null, at: 0 } } /** * 一条用例的执行上下文。脚本里拿到的 `t` 就是它。 */ export class TestCtx { constructor({ page, context, meta, runId, log }) { this.page = page this.context = context this.meta = meta this.runId = runId this._log = log this.shots = [] this.consoleErrors = [] this.token = null this.steps = [] page.on('console', (m) => { if (m.type() === 'error') { const txt = m.text() // 资源 404 / favicon 之类噪声不算前端异常 if (!/favicon|net::ERR_|Failed to load resource/i.test(txt)) this.consoleErrors.push(txt) } }) page.on('pageerror', (e) => this.consoleErrors.push(`pageerror: ${e.message}`)) } log(msg) { this._log(msg) } /** 带日志的步骤分组,失败时能一眼看出卡在第几步 */ async step(name, fn) { const t0 = Date.now() this.log(`▸ ${name}`) try { const r = await fn() this.steps.push({ name, ok: true, ms: Date.now() - t0 }) return r } catch (e) { this.steps.push({ name, ok: false, ms: Date.now() - t0, err: e.message }) throw e } } assert(cond, msg) { if (!cond) throw new AssertError(msg) this.log(` ✓ ${msg}`) return true } skip(reason) { throw new SkipError(reason) } /** 无法用浏览器自动化的用例(扫描器、断电、纸质文档核对…),标记为人工核对并给出指引 */ manual(reason) { throw new ManualError(reason) } /** 生成本轮唯一的业务标识,避免反复跑用例把库里塞满同名数据 */ uid(prefix = 'E2E') { return `${prefix}-${this.runId}` } // ---------- 登录 / 导航 ---------- /** 快速登录:后端换 token 后直接注入 localStorage,省掉每条用例重复走登录页 */ async login(account = ACCOUNT, password = PASSWORD) { const token = await apiLogin(account, password) this.token = token await this.context.addInitScript( ([k, v]) => { localStorage.setItem(k, v) localStorage.setItem(`${k}_expire`, String(Date.now() + 7200 * 1000)) }, [TOKEN_KEY, token] ) // 已经打开过页面的话,当前页也补一份,免得还停留在未登录态 if (!this.page.url().startsWith('about:')) { await this.page.evaluate( ([k, v]) => { localStorage.setItem(k, v) localStorage.setItem(`${k}_expire`, String(Date.now() + 7200 * 1000)) }, [TOKEN_KEY, token] ) } this.log(` 已登录 ${account}`) return token } /** * 清登录态:localStorage + sessionStorage + cookies 全部清空。 * 切用户场景专用:单 context 单 window 模式下,每个节点切 lane 前调用一次。 * 然后调用 login(newAccount) 即可登入新账号。 */ async clearLogin() { try { await this.page.evaluate(() => { try { localStorage.clear() } catch {} try { sessionStorage.clear() } catch {} }) } catch {} try { await this.context.clearCookies() } catch {} } /** 走真实登录页(身份认证类用例要的就是这条链路) */ async loginUI(account = ACCOUNT, password = PASSWORD) { await this.page.goto(`${FE_BASE}/login`, { waitUntil: 'domcontentloaded' }) await humanViewportFlicker(this.page) // 用户名:先清空再字符级键入 await humanFill(this.page, this.page.locator('.login-card input').first(), account) // 密码:tab 切到下一字段 → 字符级键入 await humanPress(this.page, 'Tab') await humanFill(this.page, this.page.locator('.login-card input[type="password"]'), password) // 登录按钮 await humanClick(this.page, this.page.getByRole('button', { name: btnName('登录') })) } async logout() { // 页面还没导航(about:blank)时 localStorage 访问会抛 SecurityError, // 而全新 context 本就没有 token,直接跳过即可。 if (!this.page.url().startsWith('about:')) { await this.page.evaluate((k) => { localStorage.removeItem(k) localStorage.removeItem(`${k}_expire`) }, TOKEN_KEY) } } async goto(route, { waitTable = true } = {}) { const url = route.startsWith('http') ? route : `${FE_BASE}${route}` await this.page.goto(url, { waitUntil: 'domcontentloaded' }) // 导航后的短暂停顿(真人等待页面响应) await this.page.waitForTimeout(jitter(200, 400)) if (waitTable) { // 表格页等首屏加载完;不是表格页就算了,不阻塞 await this.page .locator('.ant-table, .crud-page, .ant-card, .ant-tabs') .first() .waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) .catch(() => {}) await this.waitIdle() } // 页面打开后视口自然微动("看屏幕") await humanViewportFlicker(this.page, { intensity: 'low' }) this.log(` 已打开 ${route}`) } async waitIdle(ms = 600) { await this.page.waitForLoadState('networkidle', { timeout: 15_000 }).catch(() => {}) await this.page.waitForTimeout(jitter(ms, ms + 200)) // 偶尔触发视口微动(模拟"查看结果") if (Math.random() < 0.25) await humanViewportFlicker(this.page, { intensity: 'low' }) } /** 页面标题(CrudPage 的 .page-title) */ async pageTitle() { const el = this.page.locator('.page-title').first() return (await el.count()) ? (await el.innerText()).trim() : (await this.page.title()).trim() } async expectTitle(text) { const got = await this.pageTitle() this.assert(got.includes(text), `页面标题包含「${text}」(实际「${got}」)`) } async expectVisible(selectorOrText, desc) { // 既支持「选择器」也支持「文本」: // - 以 . # [ 开头 → 选择器 // - 以标签名(button/a/div…)开头且含 : > 空格(后代/伪类)→ 选择器 // - 否则当作页面文本匹配 const isSelector = selectorOrText.startsWith('.') || selectorOrText.startsWith('#') || selectorOrText.startsWith('[') || /^[a-zA-Z][\w-]*[ :>]/.test(selectorOrText) const loc = isSelector ? this.page.locator(selectorOrText) : this.page.getByText(selectorOrText, { exact: false }) await loc.first().waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) this.assert(true, desc || `可见:${selectorOrText}`) } // ---------- 表格 ---------- table() { return this.page.locator('.ant-table').first() } rows() { return this.page.locator('.ant-table-tbody tr.ant-table-row') } async rowCount() { await this.page.waitForTimeout(200) return await this.rows().count() } row(text) { return this.page.locator(`.ant-table-tbody tr.ant-table-row:has-text(${JSON.stringify(text)})`).first() } async expectRow(text) { await this.row(text).waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) this.assert(true, `列表中存在「${text}」`) } async expectNoRow(text) { const n = await this.page.locator(`.ant-table-tbody tr.ant-table-row:has-text(${JSON.stringify(text)})`).count() this.assert(n === 0, `列表中不存在「${text}」`) } /** 读整表为二维数组,用于「列表与详情一致」这类断言 */ async readTable() { return await this.page.$$eval('.ant-table-tbody tr.ant-table-row', (trs) => trs.map((tr) => [...tr.querySelectorAll('td')].map((td) => td.innerText.trim())) ) } async search(keyword) { const input = this.page.getByPlaceholder('关键字搜索') await humanFill(this.page, input, keyword) await humanClick(this.page, this.page.getByRole('button', { name: btnName('查询') })) await this.waitIdle() this.log(` 已按关键字「${keyword}」查询`) } async resetQuery() { await humanClick(this.page, this.page.getByRole('button', { name: btnName('重置') })) await this.waitIdle() } async refresh() { await humanClick(this.page, this.page.getByRole('button', { name: btnName('刷新') })) await this.waitIdle() } /** 顶部筛选下拉(CrudPage filters) */ async selectFilter(label, optionText) { const item = this.page.locator(`.filter-bar .ant-form-item:has(label:text-is(${JSON.stringify(label)}))`).first() await humanClick(this.page, item.locator('.ant-select')) await this.page.locator('.ant-select-dropdown:visible .ant-select-item-option').filter({ hasText: optionText }).first().waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) await humanClick(this.page, this.page.locator('.ant-select-dropdown:visible .ant-select-item-option').filter({ hasText: optionText }).first()) await this.waitIdle() this.log(` 筛选 ${label} = ${optionText}`) } // ---------- 新建 / 编辑抽屉 ---------- /** * 选顶部的「所属空间」(SpacePicker,placeholder=全部空间)。 * TDS 大部分业务对象都挂在空间下,不选空间直接新建会被后端挡回 * 「所属空间不能为空」——所以正向用例开头基本都要先来一发。 * 返回选中的空间显示名。 */ async pickSpace(name) { // SpacePicker 渲染在 CrudPage 的 head-extra 插槽里,就是页头里的第一个下拉。 // 不按 placeholder 找:antd 的 placeholder 是独立的 span,选中后就没了。 const picker = this.page.locator('.page-head .ant-select').first() if (!(await picker.count())) { this.log(' 本页没有空间选择器,跳过选空间') return null } // 组件在只有一个空间时会自动选中,已经有值就不用再点。 // 注意:未选中态下 .ant-select-selection-item 不存在,Playwright 默认 strict 模式会等 30s 才返回, // 之前用 .catch(()=>'') 兜底但 innerText() 内部仍会卡 20s。必须先 count() 探测。 const selItem = picker.locator('.ant-select-selection-item') const hasSel = await selItem.count() if (hasSel > 0) { const current = (await selItem.innerText()).trim() if (current && !name) { this.log(` 所属空间已选中「${current}」`) return current } } await humanClick(this.page, picker) const dd = this.page.locator('.ant-select-dropdown:visible .ant-select-item-option') await dd.first().waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) const opt = name ? dd.filter({ hasText: name }).first() : dd.first() const label = (await opt.innerText()).trim() await humanClick(this.page, opt) await this.waitIdle() this.log(` 已选择所属空间「${label}」`) return label } /** * 选空间并返回真实 spaceId。 * * SpacePicker 的 option `label` 是 `名称(编码)`、`value` 才是 id,但 DOM 里只看得到 label。 * 用例如果直接读 `.page-head .ant-select-selection-item` 的文案当 spaceId 去 POST 建数据, * 后端 beforeSave 只校验非空所以会建成功,可数据实际挂在一个**不存在的空间**上, * 页面按当前空间过滤时就再也查不到自己刚建的那条,表现为「查询超时找不到行」。 * 需要真实 id 的用例一律用这个方法,别自己从 DOM 抠。 */ async pickSpaceRef(name) { const label = await this.pickSpace(name) if (!label) return null const spaces = await this.apiList('/api/ssw/tds/Space', { pageSize: 200 }) const hit = spaces.find((s) => `${s.name}(${s.spaceCode})` === label) || spaces.find((s) => s.spaceCode && label.includes(s.spaceCode)) || spaces.find((s) => s.name && label.includes(s.name)) if (!hit) { this.log(` ⚠ 空间「${label}」在接口列表里找不到对应记录,无法解析 spaceId`) return null } return { id: hit.id, name: hit.name, spaceCode: hit.spaceCode, label } } async openCreate() { await humanClick(this.page, this.page.getByRole('button', { name: btnName('新建') })) await this.page.locator('.ant-drawer-content').waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) await this.page.waitForTimeout(jitter(250, 400)) } async openEdit(rowText) { await humanClick(this.page, this.row(rowText).getByRole('button', { name: btnName('编辑') })) await this.page.locator('.ant-drawer-content').waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) await this.page.waitForTimeout(jitter(250, 400)) } drawer() { return this.page.locator('.ant-drawer-content').last() } /** * 打开某个表单项的下拉,返回它专属的选项 locator。 * * 不能用 `.ant-select-dropdown:visible` —— 表单里有多个 select 时, * 上一个下拉的关闭是带淡出动画的,新下拉打开的瞬间会同时匹配到两个, * `.first()` 极可能落在正在消失的那个上,于是「element is not visible」死等超时。 * ant-design-vue 会给每个 select 的 combobox 输入框挂 aria-controls 指向自己的 * 选项列表 id,按它精确定位才稳。 */ async openSelect(item) { const select = item.locator('.ant-select').first() await humanClick(this.page, select) const listId = await item.locator('input[role="combobox"]').first().getAttribute('aria-controls').catch(() => null) const dd = listId ? this.page.locator(`.ant-select-dropdown:has(#${listId})`) : this.page.locator('.ant-select-dropdown:visible') const opts = dd.locator('.ant-select-item-option') await opts.first().waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) // 下拉用的是 rc-virtual-list,首帧渲染完还会按实际高度重排一次, // 紧接着点会撞上「element was detached from the DOM」,等它稳一下。 await this.page.waitForTimeout(jitter(150, 250)) return opts } /** 点下拉项。虚拟列表重排会让节点瞬间 detach,撞上就重试一次 */ async clickOption(opt) { try { await humanClick(this.page, opt, { hoverMs: [80, 220] }) } catch (e) { await this.page.waitForTimeout(jitter(250, 400)) await humanClick(this.page, opt, { hoverMs: [80, 220] }) } } /** * 按索引选下拉项,返回选中的文案。 * 用于「必须选到两个不同的引用对象」这类场景(如合约的提供方/使用方连接器)—— * 用例事先并不知道下拉里到底会有哪些选项,按名字猜不如按位置取。 */ async pickOption(label, index = 0) { const item = this.drawer().locator(`.ant-form-item:has(label:text-is(${JSON.stringify(label)}))`).first() await item.waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) const opts = await this.openSelect(item) const total = await opts.count() if (index >= total) throw new Error(`「${label}」下拉只有 ${total} 个选项,取不到第 ${index + 1} 个`) const opt = opts.nth(index) const text = (await opt.innerText()).trim() await this.clickOption(opt) await item.locator('.ant-form-item-label, .ant-select').first().click().catch(() => {}) this.log(` 「${label}」选中「${text}」`) return text } /** 按表单项标签定位控件,自动识别 input / textarea / number / select */ async fillField(label, value) { const item = this.drawer().locator(`.ant-form-item:has(label:text-is(${JSON.stringify(label)}))`).first() await item.waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) if (await item.locator('.ant-select').count()) { const opts = await this.openSelect(item) const hit = opts.filter({ hasText: String(value) }) if (await hit.count()) await this.clickOption(hit.first()) else await this.clickOption(opts.first()) // 不直接按 Escape:ant-design-vue Drawer 默认也会监听 Escape 关闭抽屉。 // 点选项本身会关闭下拉,再点一下表单项容器让焦点安全转移即可。 await item.locator('.ant-form-item-label, .ant-select').first().click().catch(() => {}) return } if (await item.locator('.ant-input-number-input').count()) { await humanFill(this.page, item.locator('.ant-input-number-input'), String(value)) return } if (await item.locator('textarea').count()) { await humanFill(this.page, item.locator('textarea'), String(value)) return } await humanFill(this.page, item.locator('input').first(), String(value)) } async fillForm(obj) { for (const [label, value] of Object.entries(obj)) { if (value === undefined || value === null) continue await this.fillField(label, value) } } async clearField(label) { const item = this.drawer().locator(`.ant-form-item:has(label:text-is(${JSON.stringify(label)}))`).first() const box = item.locator('input, textarea').first() if (await box.count()) await humanFill(this.page, box, '') } async save() { await humanClick(this.page, this.drawer().getByRole('button', { name: btnName('保存') })) await this.page.waitForTimeout(jitter(400, 600)) } async cancelDrawer() { await humanClick(this.page, this.drawer().getByRole('button', { name: btnName('取消') })) await this.page.locator('.ant-drawer-content').waitFor({ state: 'hidden', timeout: ACTION_TIMEOUT }).catch(() => {}) } /** 新建一条并断言成功(正向用例主力) */ async create(fields, { expectToast = '新增成功' } = {}) { await this.openCreate() await this.fillForm(fields) await this.save() if (expectToast) await this.expectToast(expectToast) await this.waitIdle() } // ---------- 行内动作 ---------- /** 点某行的链接按钮(提供方签署 / 上链存证 / 终止 …) */ async rowAction(rowText, actionLabel) { const row = this.row(rowText) await row.waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) const btn = row.getByRole('button', { name: btnName(actionLabel) }).first() await btn.waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) await humanClick(this.page, btn) // 等待 modal/popover/drawer 出现的初始动画(避免 promptOk / 后续逻辑等不到) await this.page.waitForTimeout(jitter(400, 700)) } async hasRowAction(rowText, actionLabel) { return (await this.row(rowText).getByRole('button', { name: btnName(actionLabel) }).count()) > 0 } /** 锁定当前页可见的「弹窗 / 抽屉 / 浮层」容器。 * ant-design-vue 不同版本渲染差异大:v3 标准 a-modal 是 .ant-modal-wrap > .ant-modal, * 但 jweb 用的版本把 modal 内部用 ant-tabs 组件包了一层,根容器变成 .ant-tabs-root; * 抽屉(Drawer)又是 .ant-drawer。这里统一收口。 * 返回的 locator 直接当 modal 容器用:locator('.ant-btn-primary') / locator('textarea') 等。 */ _visibleDialog() { // 优先级:标准 modal > ant-tabs-root(jweb modal) > drawer > 自定义 .ant-popover const sels = [ '.ant-modal-wrap:visible .ant-modal:not(.ant-modal-confirm)', '.ant-modal-wrap:visible .ant-tabs-root', '.ant-drawer-content-wrapper:visible .ant-drawer-body', '.ant-popover:visible .ant-popover-inner' ] for (const s of sels) { const n = this.page.locator(s) if (n.length) return n.last() } return this.page.locator('body') } /** prompt 弹窗填值并确认;组件库自带按钮按 class 点,避开中英文文案差异 * value 用法: * - null / undefined / '':保留 modal 默认值(不点 select、不填 textarea),直接确认 * - 'xxx':先在 select 里匹配(同时按文本与 value 属性匹配,兼容中英文),再把同一值填到 textarea(若有) * - { select: 'SANDBOX', textarea: '留言...' }:分别指定 select 选项 + textarea 文案 */ async promptOk(value) { const dialog = this._visibleDialog() await dialog.waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) // 解析 value:支持对象 / 单值 const opts = (value && typeof value === 'object') ? value : { select: value, textarea: value } // 处理顺序:先填 select(如果有 + 显式指定),再填 textarea(如果有) const wantSelect = opts.select !== null && opts.select !== undefined && opts.select !== '' if (wantSelect && await dialog.locator('.ant-select').count()) { await humanClick(this.page, dialog.locator('.ant-select').first()) // antd 渲染时 option 的 label 是 label 文本,value 落在 li[data-value] / .ant-select-item-option-value 上 const dropdown = this.page.locator('.ant-select-dropdown:visible').last() await dropdown.waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) const want = String(opts.select) // 先按 li title / 文本匹配(中文 label),再回退按 data-value 匹配(英文 value) let opt = dropdown.locator('.ant-select-item-option').filter({ hasText: want }).first() if (!(await opt.count())) { opt = dropdown.locator(`.ant-select-item-option[data-value="${want.replace(/"/g, '\\"')}"]`).first() } await opt.waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) await humanClick(this.page, opt) // antd select 选中后自动收起 dropdown,等其稳一下再 fill textarea(避免遮盖) await this.page.waitForTimeout(jitter(150, 280)) } const wantText = opts.textarea if (wantText !== undefined && wantText !== null && wantText !== '' && await dialog.locator('textarea').count()) { await humanFill(this.page, dialog.locator('textarea').first(), String(wantText)) } await humanClick(this.page, dialog.locator('.ant-btn-primary').last()) await this.page.waitForTimeout(jitter(400, 600)) } async promptCancel() { const dialog = this._visibleDialog() await humanClick(this.page, dialog.locator('.ant-btn:not(.ant-btn-primary)').first()) await this.page.waitForTimeout(jitter(200, 350)) } async promptIsOpen() { // 兼容 jweb 的 ant-tabs-root modal + 标准 ant-modal + drawer return (await this.page.locator('.ant-modal-wrap:visible, .ant-drawer-content-wrapper:visible').count()) > 0 } /** 行内动作 + prompt 一步到位 */ async doAction(rowText, actionLabel, promptValue) { await this.rowAction(rowText, actionLabel) if (await this.promptIsOpen()) await this.promptOk(promptValue) await this.waitIdle() } async remove(rowText) { await humanClick(this.page, this.row(rowText).getByRole('button', { name: btnName('删除') })) const confirm = this.page.locator('.ant-popconfirm:visible').last() await confirm.waitFor({ state: 'visible', timeout: ACTION_TIMEOUT }) await humanClick(this.page, confirm.locator('.ant-btn-primary')) await this.waitIdle() } // ---------- 提示 ---------- /** ant-design-vue 的全局提示 3 秒自动消失,这里轮询抓取,别用固定等待 */ async toastText(timeout = 6000) { const t0 = Date.now() while (Date.now() - t0 < timeout) { const n = this.page.locator('.ant-message-notice-content') if (await n.count()) { const txt = (await n.last().innerText()).trim() if (txt) return txt } await this.page.waitForTimeout(120) } return '' } async expectToast(expect, { type } = {}) { const txt = await this.toastText() this.assert(txt.includes(expect), `出现提示「${expect}」(实际「${txt || '无提示'}」)`) if (type) { const cls = await this.page.locator('.ant-message-notice-content').last().innerHTML() this.assert(cls.includes(`anticon-${type}`) || cls.includes(type), `提示类型为 ${type}`) } return txt } /** 反向用例:期望出现拒绝/校验类提示,且不是成功提示 */ async expectReject(keyword) { const txt = await this.toastText() this.assert(!!txt, `系统给出了提示(实际「${txt}」)`) this.assert(!/成功/.test(txt), `未出现成功提示,操作被拒绝(实际「${txt}」)`) if (keyword) this.assert(txt.includes(keyword), `提示包含「${keyword}」`) return txt } async expectNoToast(ms = 1500) { await this.page.waitForTimeout(ms) const n = await this.page.locator('.ant-message-notice-content').count() this.assert(n === 0, '没有出现任何提示') } // ---------- 后端接口 ---------- /** 直接打后端,用于「界面之外还要落库/落链」这类断言 */ async api(method, url, body, { raw = false, token } = {}) { const t = token ?? this.token ?? (await this.login()) const full = url.startsWith('http') ? url : `${BE_BASE}${url.startsWith('/api') ? '' : '/api'}${url}` // GET / HEAD 不允许 body;脚本可能误传,DSL 兜底不让整批崩 const upper = method.toUpperCase() const safeBody = (upper === 'GET' || upper === 'HEAD') ? undefined : body const res = await fetch(full, { method: upper, headers: { Authorization: t, 'App-Code': 'sswflow', 'Jnpf-Origin': 'pc', 'Vue-Version': '3', ...(safeBody ? { 'Content-Type': 'application/json' } : {}) }, ...(safeBody ? { body: JSON.stringify(safeBody) } : {}) }) const json = await res.json().catch(() => ({})) if (raw) return { status: res.status, json } return wrapEnvelope(json) } /** 分页列表接口的通用取数 */ async apiList(url, query = {}) { const qs = new URLSearchParams({ currentPage: 1, pageSize: 20, ...query }).toString() const r = await this.api('GET', `${url}?${qs}`) const d = r?.data ?? r return d?.list ?? d?.records ?? (Array.isArray(d) ? d : []) } /** 自举:创建一条全新的 SANDBOX 交付任务(status/runStatus=PENDING_DELIVER,无程序) * 用于 DELIVERY/USAGE 用例在无「干净可上传」共享任务时可独立跑通。 * 探针已验证:POST 后 status=runStatus=PENDING_DELIVER、programUri=null,UploadProgram 返回 200。 * 返回 { id, contractCode, productName } 或 null(失败/无前置数据时)。 */ async createSandboxTask() { try { const contracts = (await this.apiList('/api/ssw/tds/Contract', { pageSize: 50 })).filter((c) => c.status === '02') const prods = await this.apiList('/api/ssw/tds/DataProduct', { pageSize: 50 }) if (!contracts.length || !prods.length) return null const c = contracts[0] const p = prods[0] // 自带唯一 taskNo(beforeSave 仅在缺省时生成 DT+时间戳;自带则沿用,且需全局唯一) const taskNo = 'DT-E2E-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6) const r = await this.api('POST', '/api/ssw/tdc/DeliveryTask', { taskNo, contractId: c.id, contractCode: c.contractCode, productId: p.id, productName: p.name || p.productName, deliveryType: 'SANDBOX', // beforeSave 仅在缺省时设 status=PENDING,这里自带 PENDING_DELIVER 让用例 filter 命中; // runStatus 也自带(beforeSave 不设),否则 UploadProgram 会因 runStatus!=PENDING_DELIVER 被拒 status: 'PENDING_DELIVER', runStatus: 'PENDING_DELIVER', triggerType: 'MANUAL' }) if (r.code !== 200 || !r.data) return null const id = typeof r.data === 'string' ? r.data : r.data?.id if (!id) return null return { id, taskNo, contractCode: c.contractCode, productName: p.name || p.productName } } catch (e) { return null } } // ---------- 证据 ---------- async shot(name) { fs.mkdirSync(SHOTS_DIR, { recursive: true }) // 关键动作截图统一命名 <用例号>-<序号>.jpg,如 TC-FLOW-001-001.jpg const file = `${this.meta.tc}-${String(this.shots.length + 1).padStart(3, '0')}.jpg` const full = path.join(SHOTS_DIR, file) try { // 视口变更 / 异常跳转让 page 可能已关:拿不到也别让用例崩 if (this.page.isClosed()) throw new Error('page closed') await this.page.screenshot({ path: full, type: 'jpeg', quality: 82, fullPage: false, timeout: 5000 }) this.shots.push(file) this.log(` 📸 ${file}${name ? ' · ' + name : ''}`) return file } catch (e) { this.log(` 📸(${name} 截图失败:${e.message.slice(0, 60)})`) return null } } /** 无前端报错 —— 可靠性/易用性类用例的通用断言 */ expectConsoleClean() { this.assert( this.consoleErrors.length === 0, `无前端控制台错误(实际 ${this.consoleErrors.length} 条${this.consoleErrors[0] ? ':' + this.consoleErrors[0].slice(0, 120) : ''})` ) } // ==================================================================== // 真实链路 / 真实计算引擎标记断言(TC-FLOW-001~005 共用) // -------------------------------------------------------------------- // 把"沙箱执行/隐私计算是不是真的走了 Nax→K8s→TEE 还是退到本地模拟" // 以及"FISCO 上链区块号、TEE 远程证明、KBS 密文路径"这些**真实物理证据** // 解析成结构化断言,而不是只验一个宽泛的正则。 // ==================================================================== /** * 解析 runLog 中的引擎回退链标记:[K8S] / [NAX] / [模拟] 出现位置 + 顺序。 * 返回 { k8s, nax, simulator, chain } —— chain 是按时间顺序的命中列表(去重保序)。 * 引擎先后顺序:真 K8s > Nax > 本地模拟;都未命中视为「无引擎标记」(用例应警觉)。 */ parseEngineChain(runLog) { const s = String(runLog || '') const re = /\[(K8S(?:[^\]]*)?|NAX(?:[^\]]*)?|模拟[^\]]*?)\]/g const chain = [] let m while ((m = re.exec(s)) !== null) { const tag = m[1] if (!chain.includes(tag)) chain.push(tag) } const k8s = chain.find((t) => /^K8S/.test(t)) || null const nax = chain.find((t) => /^NAX/.test(t)) || null const simulator = chain.find((t) => /^模拟/.test(t)) || null return { k8s, nax, simulator, chain } } /** * 断言 runLog 命中「真引擎」至少一次(K8S 或 NAX,**不接受纯模拟**)。 * 如果走 NAX 也能算「真实计算」—— Nax 真起 Python 子进程跑 pandas/numpy。 * 用例如果强制要求真 K8s,可传 { requireK8s: true }。 */ assertRealEngineEngaged(runLog, opts = {}) { const { requireK8s = false, allowSimulator = true, label = '本次执行' } = opts const parsed = this.parseEngineChain(runLog) const summary = `引擎回退链=[${parsed.chain.join(' → ') || '无标记'}]` if (requireK8s) { this.assert(!!parsed.k8s, `${label}走真 K8S 引擎(${summary})`) } else if (parsed.k8s || parsed.nax) { this.assert(true, `${label}命中真实计算引擎(${summary})`) } else if (parsed.simulator && allowSimulator) { this.assert(true, `${label}走本地模拟回退(${summary})—— 接受为有效执行`) } else { this.assert(false, `${label}未命中任何引擎标记(${summary}),结果不可信`) } return parsed } /** * 解析 runLog 中的 FISCO 存证区块号。格式:「上链 block=#N tx=0x...」或类似。 * 真上链:blockHeight > 0;fallback LOCAL/PENDING/FAIL:blockHeight=0 或缺失。 * 返回 { blockHeight, txHash, status, raw }。 */ parseChainEvidence(runLog) { const s = String(runLog || '') const m = s.match(/block=#(\d+)|block[=#:]+\s*(\d+)|区块[=#:]*\s*(\d+)/i) const tx = s.match(/tx[=#:]*\s*(0x[0-9a-fA-F]{64})/) const status = s.match(/存证\s*([A-Z]{2,})/) || s.match(/on-chain\s*([A-Z]{2,})/i) return { blockHeight: m ? Number(m[1] || m[2] || m[3]) : 0, txHash: tx ? tx[1] : null, status: status ? status[1] : null, raw: m ? m[0] : null } } /** * 断言 FISCO 真上链:返回 blockHeight > 0;fallback 状态(LOCAL/PENDING/FAIL)单独识别。 * - { requireOnChain: true }:必须是真链(blockHeight > 0)—— 适合「上链存证」步骤 * - 默认允许 fallback:本地缓存 + 异步上链,结果落 LOCAL/PENDING/FAIL 都不阻断主流程 */ assertChainEvidence(runLog, opts = {}) { const { requireOnChain = false, label = '本次存证' } = opts const ev = this.parseChainEvidence(runLog) if (requireOnChain) { this.assert(ev.blockHeight > 0 || !!ev.txHash, `${label}已上链(blockHeight=${ev.blockHeight} tx=${(ev.txHash || '').slice(0, 12)}...)`) } else { const ok = ev.blockHeight > 0 || ['LOCAL', 'PENDING'].includes(ev.status || '') this.assert(ok, `${label}落账(blockHeight=${ev.blockHeight} status=${ev.status || '未知'})`) } return ev } /** * 读 TEE 结构化证据(解析 runLog 中的 [TEE_EVIDENCE_JSON] 块或调后端 /TeeEvidence)。 * 后端路径二选一:runLog 自带(K8sSandboxClient.appendTeeEvidence 写入)→ 直接解析; * 否则调 /api/ssw/tdc/{Sandbox,Privacy}/{id}/TeeEvidence。 * 返回 { teeType, attestationGated, resultSealed, kbc, guestKernel, * measurementSha256, signatureNonZeroBytes, runtimeClass, kbsEngaged, fatal }。 */ async fetchTeeEvidence(taskId, runLog) { // 先试 runLog 内嵌 if (runLog && runLog.includes('[TEE_EVIDENCE_JSON]')) { const i = runLog.indexOf('[TEE_EVIDENCE_JSON]') const json = runLog.substring(i + '[TEE_EVIDENCE_JSON]'.length()).trim() try { return JSON.parse(json) } catch { /* fall through to API */ } } // 落不到 runLog 就调后端(Sandbox 与 Privacy 各试一次) for (const path of [`/api/ssw/tdc/Sandbox/${taskId}/TeeEvidence`, `/api/ssw/tdc/Privacy/${taskId}/TeeEvidence`]) { const r = await this.api('GET', path) if (r.code === 200 && r.data) return r.data } return null } /** * 断言 TEE 执行证据:远程证明门控 + 结果加密 + measurement 真存在。 * 默认要求 attestationGated=true 且 resultSealed=true(链路必须密态门控)。 * 如果是真 TEE,应还有 measurementSha256(64 hex);fallback 到本地模拟也允许通过。 */ async assertTeeEvidence(taskId, runLog, opts = {}) { const { requireGated = true, requireSealed = true, requireMeasurement = false, label = '本次 TEE 执行' } = opts const ev = await this.fetchTeeEvidence(taskId, runLog) if (!ev) { this.assert(false, `${label}未产出 TEE 证据块(runLog 无 [TEE_EVIDENCE_JSON]、/TeeEvidence 不可读)`) return null } const teeType = ev.teeType || ev.tee || 'unknown' this.assert(true, `${label}证据结构化:teeType=${teeType} attestationGated=${ev.attestationGated} resultSealed=${ev.resultSealed} kbc=${ev.kbc || 'n/a'} guestKernel=${ev.guestKernel || 'n/a'}`) if (requireGated) this.assert(ev.attestationGated === true, `${label}远程证明门控开启(attestationGated=true)`) if (requireSealed) this.assert(ev.resultSealed === true, `${label}结果密文封装(resultSealed=true,AES-256-GCM)`) if (requireMeasurement) { const m = ev.measurementSha256 this.assert(typeof m === 'string' && m.length === 64, `${label}有真实 measurement(SHA-256 64位 hex,实际=${(m || '').slice(0, 16)}...)`) } if (ev.fatal) { this.assert(false, `${label}TEE 失败 fatal=${ev.fatal}——fail-closed 起作用但任务不应仍报 SUCCESS`) } return ev } /** * 计算一段字符串的真实 SHA-256(hex, 64 字符)。 * 用于把合约摘要、算法代码摘要、销毁前的产物摘要等业务对象的"指纹"算出来, * 而不是用随机 fakeHash 假装存证;后者过不了「链上数据必须可重现」的反向审计。 */ sha256Hex(text) { // 同步实现;不引 crypto 依赖;用 Node 内置 // 通过动态 import 替代 require(ESM 环境) return import('node:crypto').then(({ createHash }) => createHash('sha256').update(String(text), 'utf8').digest('hex')) } /** * 把"执行耗时(ms)"切成可断言的档位,验证沙箱/隐私计算走的是真实路径不是秒回。 * - missing/undefined:实体若不携带 costMs 字段(如 DeliveryTask),只 log 不阻断(接口尚无此指标) * - tooFast(< minMs):< 50ms 几乎确定是 stub/缓存(除非仅静态校验) * - tooSlow(> maxMs):> maxMs 视为超时嫌疑(结合 runStatus 一起判断) */ assertExecCost(costMs, opts = {}) { const { minMs = 50, maxMs = 600000, label = '本次执行', required = false } = opts const n = Number(costMs) if (!Number.isFinite(n) || n < 0 || costMs === undefined || costMs === null) { if (required) { this.assert(false, `${label}必须带 costMs(实际 ${costMs})`) } else { this.log(` (${label}无 costMs 字段(实际 ${costMs}),该实体尚未记录执行耗时,跳过区间校验)`) } return n || 0 } if (n > 0 && n < minMs) { this.log(` ⚠ ${label}耗时仅 ${n}ms(< ${minMs}ms),疑似本地 stub`) } else if (n > maxMs) { this.log(` ⚠ ${label}耗时 ${n}ms(> ${maxMs}ms),需关注是否触发超时回退`) } else if (n === 0) { this.log(` (${label}costMs=0,可能尚未记录耗时)`) } else { this.assert(true, `${label}耗时 ${n}ms 在合理区间 [${minMs}, ${maxMs}]`) } return n } }