- e2e: fix 9 failing cases (contract/hosting/delivery/usage/security); add dsl.createSandboxTask() self-provision helper; cli/runner now default headless, --ob opens visible browser - backend: tdc/tds controller adjustments (delivery, hosting, contract, chain-evidence, catalog, product, policy-conflict, etc.) - web: ssw views/components adjustments (contract, product, hosting, connector) - docs: AGENTS.md, e2e README; .gitignore; project memory update Excludes docs/e2e/results artifacts (screenshots + results.json).
715 lines
28 KiB
JavaScript
715 lines
28 KiB
JavaScript
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'
|
||
|
||
/**
|
||
* 用例 DSL —— 344 条脚本共用的动作与断言。
|
||
*
|
||
* 页面这边有个很大的便利:TDS/TDC 绝大多数管理页都由 web/src/components/ssw/common/CrudPage.vue
|
||
* 渲染,DOM 是统一的(新建按钮 / 抽屉表单 / 行内链接按钮 / prompt 弹窗 / 关键字搜索)。
|
||
* 所以这里的选择器按那份组件的结构来写,一次写对,全站通用。
|
||
*
|
||
* 注意:项目没有给 ant-design-vue 配中文 locale,Modal/Popconfirm 的确认按钮文案是
|
||
* 组件库默认英文(OK/Cancel)。因此凡是组件库自带的按钮一律按 .ant-btn-primary 类名点,
|
||
* 不去赌文案;只有业务自己写死的中文(新建/保存/查询/删除…)才按文本定位。
|
||
*/
|
||
|
||
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
|
||
}
|
||
|
||
/** 走真实登录页(身份认证类用例要的就是这条链路) */
|
||
async loginUI(account = ACCOUNT, password = PASSWORD) {
|
||
await this.page.goto(`${FE_BASE}/login`, { waitUntil: 'domcontentloaded' })
|
||
await this.page.locator('.login-card input').first().fill(account)
|
||
await this.page.locator('.login-card input[type="password"]').fill(password)
|
||
await this.page.getByRole('button', { name: btnName('登录') }).click()
|
||
}
|
||
|
||
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(300)
|
||
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()
|
||
}
|
||
this.log(` 已打开 ${route}`)
|
||
}
|
||
|
||
async waitIdle(ms = 600) {
|
||
await this.page.waitForLoadState('networkidle', { timeout: 15_000 }).catch(() => {})
|
||
await this.page.waitForTimeout(ms)
|
||
}
|
||
|
||
/** 页面标题(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 input.fill(keyword)
|
||
await this.page.getByRole('button', { name: btnName('查询') }).click()
|
||
await this.waitIdle()
|
||
this.log(` 已按关键字「${keyword}」查询`)
|
||
}
|
||
|
||
async resetQuery() {
|
||
await this.page.getByRole('button', { name: btnName('重置') }).click()
|
||
await this.waitIdle()
|
||
}
|
||
|
||
async refresh() {
|
||
await this.page.getByRole('button', { name: btnName('刷新') }).click()
|
||
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 item.locator('.ant-select').click()
|
||
await this.page.locator('.ant-select-dropdown:visible .ant-select-item-option').filter({ hasText: optionText }).first().click()
|
||
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
|
||
}
|
||
// 组件在只有一个空间时会自动选中,已经有值就不用再点
|
||
const current = (await picker.locator('.ant-select-selection-item').innerText().catch(() => '')).trim()
|
||
if (current && !name) {
|
||
this.log(` 所属空间已选中「${current}」`)
|
||
return current
|
||
}
|
||
await picker.click()
|
||
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 opt.click()
|
||
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 this.page.getByRole('button', { name: btnName('新建') }).click()
|
||
await this.page.locator('.ant-drawer-content').waitFor({ state: 'visible', timeout: ACTION_TIMEOUT })
|
||
await this.page.waitForTimeout(250)
|
||
}
|
||
|
||
async openEdit(rowText) {
|
||
await this.row(rowText).getByRole('button', { name: btnName('编辑') }).click()
|
||
await this.page.locator('.ant-drawer-content').waitFor({ state: 'visible', timeout: ACTION_TIMEOUT })
|
||
await this.page.waitForTimeout(250)
|
||
}
|
||
|
||
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 select.click()
|
||
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(150)
|
||
return opts
|
||
}
|
||
|
||
/** 点下拉项。虚拟列表重排会让节点瞬间 detach,撞上就重试一次 */
|
||
async clickOption(opt) {
|
||
try {
|
||
await opt.click({ timeout: Math.max(3000, ACTION_TIMEOUT / 3) })
|
||
} catch (e) {
|
||
await this.page.waitForTimeout(250)
|
||
await opt.click({ timeout: Math.max(3000, ACTION_TIMEOUT / 3) })
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 按索引选下拉项,返回选中的文案。
|
||
* 用于「必须选到两个不同的引用对象」这类场景(如合约的提供方/使用方连接器)——
|
||
* 用例事先并不知道下拉里到底会有哪些选项,按名字猜不如按位置取。
|
||
*/
|
||
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 item.locator('.ant-input-number-input').fill(String(value))
|
||
return
|
||
}
|
||
if (await item.locator('textarea').count()) {
|
||
await item.locator('textarea').fill(String(value))
|
||
return
|
||
}
|
||
await item.locator('input').first().fill(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 box.fill('')
|
||
}
|
||
|
||
async save() {
|
||
await this.drawer().getByRole('button', { name: btnName('保存') }).click()
|
||
await this.page.waitForTimeout(400)
|
||
}
|
||
|
||
async cancelDrawer() {
|
||
await this.drawer().getByRole('button', { name: btnName('取消') }).click()
|
||
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 btn = this.row(rowText).getByRole('button', { name: btnName(actionLabel) })
|
||
await btn.waitFor({ state: 'visible', timeout: ACTION_TIMEOUT })
|
||
await btn.click()
|
||
await this.page.waitForTimeout(300)
|
||
}
|
||
|
||
async hasRowAction(rowText, actionLabel) {
|
||
return (await this.row(rowText).getByRole('button', { name: btnName(actionLabel) }).count()) > 0
|
||
}
|
||
|
||
/** prompt 弹窗填值并确认;组件库自带按钮按 class 点,避开中英文文案差异 */
|
||
async promptOk(value) {
|
||
const modal = this.page.locator('.ant-modal-wrap:visible .ant-modal').last()
|
||
await modal.waitFor({ state: 'visible', timeout: ACTION_TIMEOUT })
|
||
if (await modal.locator('.ant-select').count()) {
|
||
await modal.locator('.ant-select').click()
|
||
await this.page.locator('.ant-select-dropdown:visible .ant-select-item-option').filter({ hasText: String(value) }).first().click()
|
||
} else if (value !== undefined && value !== null) {
|
||
await modal.locator('textarea').fill(String(value))
|
||
}
|
||
await modal.locator('.ant-modal-footer .ant-btn-primary').click()
|
||
await this.page.waitForTimeout(400)
|
||
}
|
||
|
||
async promptCancel() {
|
||
const modal = this.page.locator('.ant-modal-wrap:visible .ant-modal').last()
|
||
await modal.locator('.ant-modal-footer .ant-btn:not(.ant-btn-primary)').first().click()
|
||
await this.page.waitForTimeout(200)
|
||
}
|
||
|
||
async promptIsOpen() {
|
||
return (await this.page.locator('.ant-modal-wrap: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 this.row(rowText).getByRole('button', { name: btnName('删除') }).click()
|
||
const confirm = this.page.locator('.ant-popconfirm:visible').last()
|
||
await confirm.waitFor({ state: 'visible', timeout: ACTION_TIMEOUT })
|
||
await confirm.locator('.ant-btn-primary').click()
|
||
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 })
|
||
const file = `${this.meta.tc}__${String(this.shots.length + 1).padStart(2, '0')}-${name}.png`
|
||
const full = path.join(SHOTS_DIR, file)
|
||
try {
|
||
// 视口变更 / 异常跳转让 page 可能已关:拿不到也别让用例崩
|
||
if (this.page.isClosed()) throw new Error('page closed')
|
||
await this.page.screenshot({ path: full, fullPage: false, timeout: 5000 })
|
||
this.shots.push(file)
|
||
this.log(` 📸 ${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) : ''})`
|
||
)
|
||
}
|
||
}
|