888 lines
40 KiB
TypeScript
888 lines
40 KiB
TypeScript
/**
|
|
* commands/testcase/run.ts — 跑 form API 测试 (POST create / GET list / PUT update / DELETE)
|
|
* 真实业务数据模式 * - 默认 ON: --real-data 走字段语义化默认值 + 关联表真实 ID lookup
|
|
* - 默认 ON: --keep-data 保留数据供浏览器层 TC-B 验证 + 跨表 join 校验
|
|
* - 新增 Step 6: 跨表 join 校验 (--join-check 启用)
|
|
* - 新增 Step 7: 业务规则校验 (--business-rules 启用)
|
|
* - --no-real-data: 退回 test fixture 模式 (向后兼容
|
|
* 算法:
|
|
* 1. 从 form schema 读 fields + types (推断 sample data)
|
|
* 2. relationForm 字段从关联表 list 前 N 条拉真实 ID (而非跳过)
|
|
* 3. POST create 用真实业务数据 → 拿新 ID
|
|
* 4. GET info 验证数据回读
|
|
* 5. PUT update 修改一字段 → 验改后值
|
|
* 6. 跨表 join 校验: FK 字段能查到关联表记录
|
|
* 7. 业务规则校验: 字段值约束 (例: team_size >= 3)
|
|
* 8. (默认跳过) DELETE 清理, --keep-data 默认 ON 留数据
|
|
* 优势 vs 浏览器测试:
|
|
* - 速度: ~5s vs 30s+
|
|
* - 不需 token: 不调 screenshot, 不渲染页面
|
|
* - 真实业务数据: 默认走 --real-data, 用字段语义化值 + 关联表真实 ID
|
|
* - 局限: 不验浏览器 vmodel bind (tdd10 浏览器只 bind 2 字段 bug, 此工具查不出)
|
|
*/
|
|
import { Command } from 'commander'
|
|
import { JnpfClient } from '../../core/client.ts'
|
|
import { installHelpHookWithPatterns } from '../../core/help.ts'
|
|
import { log, printJson } from '../../core/log.ts'
|
|
import { setupOutputFilter, printCommandEnd } from '../_output_filter.ts' // v2.1+ (2026-07-21): 输出过滤 + CommandLog 落盘
|
|
|
|
interface RunOpts {
|
|
formId: string
|
|
output?: string
|
|
keepData?: boolean
|
|
json?: boolean
|
|
realData?: boolean
|
|
realFields?: string
|
|
relationFormLookup?: boolean
|
|
relationFormSample?: string
|
|
joinCheck?: boolean
|
|
joinRules?: string
|
|
businessRules?: string
|
|
verbose?: boolean
|
|
}
|
|
|
|
interface StepResult {
|
|
step: string
|
|
status: 'PASS' | 'FAIL' | 'SKIP'
|
|
duration: number
|
|
detail?: string
|
|
data?: unknown
|
|
}
|
|
|
|
interface SampleOptions {
|
|
realData: boolean
|
|
realFields?: Record<string, unknown>
|
|
relationFormLookup: boolean
|
|
relationFormSample: number
|
|
}
|
|
|
|
export function buildTestRunCommand(): Command {
|
|
const cmd = new Command('run')
|
|
.description('跑 form API 测试 (POST/GET/PUT/DELETE + 跨表 join + 业务规则, 默认走真实业务数据)')
|
|
.requiredOption('--formId <id>', '目标 form id')
|
|
.option('--output <file>', '输出报告文件路径 (默认 stdout)')
|
|
.option('--keep-data', '保留测试数据不删 (默认 ON, 留数据供 TC-B 浏览器验证)', true)
|
|
.option('--no-keep-data', '跑完立即 DELETE 清理 (test fixture 旧行为)')
|
|
// 真实业务数据模式 (替代 test fixture, 默认 ON)
|
|
.option('--real-data', '真实业务数据模式 (字段语义化默认值 + 关联表真实 ID lookup, 默认 ON)', true)
|
|
.option('--no-real-data', '关闭真实业务数据模式, 退回 test fixture (向后兼容 v0.11e)')
|
|
.option('--real-fields <json>', '自定义真实业务数据 JSON (优先级最高, 例: \'{"f_team_name":"数据先锋队"}\')')
|
|
// relationForm 自动 lookup 真实 ID
|
|
.option('--relation-form-lookup', 'relationForm 字段自动从关联表拉真实 ID (而非跳过, 默认 ON)', true)
|
|
.option('--no-relation-form-lookup', '关闭 relationForm 自动 lookup')
|
|
.option('--relation-form-sample <n>', '关联表拉前 N 条数据作为 sample (默认 1, 最大 5)', '1')
|
|
// 跨表 join 校验
|
|
.option('--join-check', 'POST 后跑跨表 join 校验, 验证外键字段可查到关联表记录')
|
|
.option('--join-rules <json>', 'join 规则 JSON (例: \'[{"fkField":"f_team_id","targetEnCode":"jxcj_team","checkField":"f_team_name"}]\')')
|
|
// 业务规则校验
|
|
.option('--business-rules <json>', '业务规则 JSON (例: \'[{"field":"f_team_size","rule":">=3","msg":"团队人数下限 3 人"}]\')')
|
|
.option('--verbose', '完整输出 (含 step machine、API 调用等过程日志)', false)
|
|
.option('--json', '原始 JSON 输出', false)
|
|
.action(async (opts: RunOpts) => {
|
|
// 输出过滤: 默认静默 (quiet mode), --verbose 走完整日志, --json 走原始 JSON
|
|
setupOutputFilter(opts)
|
|
const c = await JnpfClient.fromToken()
|
|
const startTime = Date.now()
|
|
const steps: StepResult[] = []
|
|
let testDataId: string | null = null
|
|
let sample: Record<string, unknown> = {}
|
|
|
|
// 解析可选 JSON
|
|
let realFieldsObj: Record<string, unknown> | undefined
|
|
if (opts.realFields) {
|
|
try {
|
|
realFieldsObj = JSON.parse(opts.realFields)
|
|
} catch (e) {
|
|
log.error(`--real-fields JSON 解析失败: ${(e as Error).message}`)
|
|
process.exit(1)
|
|
}
|
|
}
|
|
let joinRulesArr: Array<{ fkField: string; targetEnCode: string; checkField: string }> | undefined
|
|
if (opts.joinRules) {
|
|
try {
|
|
joinRulesArr = JSON.parse(opts.joinRules)
|
|
} catch (e) {
|
|
log.error(`--join-rules JSON 解析失败: ${(e as Error).message}`)
|
|
process.exit(1)
|
|
}
|
|
}
|
|
let businessRulesArr: Array<{ field: string; rule: string; msg?: string }> | undefined
|
|
if (opts.businessRules) {
|
|
try {
|
|
businessRulesArr = JSON.parse(opts.businessRules)
|
|
} catch (e) {
|
|
log.error(`--business-rules JSON 解析失败: ${(e as Error).message}`)
|
|
process.exit(1)
|
|
}
|
|
}
|
|
|
|
// 自动开启 join-check / business-rules (传了 rules 就跑)
|
|
const runJoinCheck = !!opts.joinCheck || !!joinRulesArr
|
|
const runBusinessRules = !!businessRulesArr
|
|
const relationSampleN = Math.min(Math.max(parseInt(opts.relationFormSample || '1', 10) || 1, 1), 5)
|
|
|
|
// Step 1: 拉 form schema 推导 sample data
|
|
const t0 = Date.now()
|
|
try {
|
|
const schemaR = (await c.get(`/visualdev/Base/${opts.formId}`)) as {
|
|
code: number
|
|
data: { formData: string; tables: string }
|
|
}
|
|
if (schemaR.code !== 200) throw new Error(`get schema failed: ${schemaR.code}`)
|
|
const formData = JSON.parse(schemaR.data.formData)
|
|
const fields = formData.fields || []
|
|
|
|
// 主子表自动 sample (testspace testjxcjp02ai 实战)
|
|
// 旧 (dacli-2026-06-29-04): 主子表检测到 tables.length > 1 时强制 exit(1), 逼用户传 --real-fields
|
|
// 根因: 当时 buildSampleData 对主子表只填主表前 2 字段, 不覆盖子表 children required 字段
|
|
// 新 (实测 testjxcjp02ai): buildSampleData 已通过 jnpfKey='table' 遍历 cfg.children 生成完整 childRow,
|
|
// POST /visualdev/OnlineDev/{formId} 返回 code=200 ("New created successfully")
|
|
// 去掉硬关卡, 主子表也走 buildSampleData 自动 sample; 保留软 warn + 子表名参考
|
|
// (用户想覆盖特定业务值仍可 --real-fields)
|
|
// 边界: web 端 Form.vue 提交时强制校验所有 required 字段 (主子表都验) — 不需在 dacli 侧重复
|
|
const tablesStr: string = schemaR.data.tables || '[]'
|
|
let tablesArr: any[] = []
|
|
try { tablesArr = JSON.parse(tablesStr) } catch { /* ignore */ }
|
|
const isMainSubTable = Array.isArray(tablesArr) && tablesArr.length > 1
|
|
if (isMainSubTable) {
|
|
log.warn(`⚠ 检测到主子表 (${tablesArr.length} 张), buildSampleData 自动覆盖主表 + 子表 children (P0-2 fix)`)
|
|
log.warn(` 子表 tableName 参考:`)
|
|
for (let i = 0; i < tablesArr.length; i++) {
|
|
const t = tablesArr[i]
|
|
const tName = t?.table || t?.tableName || `t${i}`
|
|
const role = t?.typeId === '1' ? '主表' : '子表'
|
|
log.warn(` - [${role}] ${tName} (typeId=${t?.typeId || '?'}, relationTable=${t?.relationTable || '?'})`)
|
|
}
|
|
log.warn(` 想覆盖特定业务值: --real-fields='{"main_field":"v","subTableField":[{"sub_field":"sv"}]}'`)
|
|
}
|
|
|
|
sample = await buildSampleData(fields, c, {
|
|
realData: !!opts.realData,
|
|
realFields: realFieldsObj,
|
|
relationFormLookup: !!opts.relationFormLookup,
|
|
relationFormSample: relationSampleN,
|
|
})
|
|
|
|
// — 注入唯一标记, 便于 POST 后通过 List 反查 ID
|
|
// 修复 永远注入 marker, 让 real-data 模式也能跑 join/rule.
|
|
// --no-keep-data 模式下测试数据自动 DELETE, --keep-data 模式 marker 保留 (可识别 + 手动清理).
|
|
// marker 格式: _T{ts_last8} (11 字符) 短而唯一, 不像 "_TEST_" 那样显眼
|
|
const testMarker = `_T${Date.now().toString().slice(-8)}`
|
|
{
|
|
let markerInjected = false
|
|
for (const k of Object.keys(sample)) {
|
|
if (typeof sample[k] === 'string' && !markerInjected) {
|
|
const old = sample[k] as string
|
|
sample[k] = `${testMarker}_${old}`.slice(0, 50)
|
|
markerInjected = true
|
|
break
|
|
}
|
|
}
|
|
}
|
|
steps.push({
|
|
step: '1. 拉 form schema + 推导 sample data',
|
|
status: 'PASS',
|
|
duration: Date.now() - t0,
|
|
detail: `${fields.length} fields, mode=${opts.realData ? 'real-data' : 'fixture'}, sample: ${JSON.stringify(sample).slice(0, 100)}`,
|
|
})
|
|
if (!opts.json) log.ok(`Step 1: schema 拉取 + sample 推导 PASS (${Date.now() - t0}ms)`)
|
|
|
|
// Step 2: POST create
|
|
const t1 = Date.now()
|
|
// datetime 字段自动转 Long 毫秒戳
|
|
// 根因: 后端 VisualdevModelDataServiceImpl.swapDatetime 强制 Long.parseLong(value),
|
|
// 传 ISO8601 字符串 ("00:00:00") 会抛 NumberFormatException
|
|
// → "System abnormality" (HTTP 400)
|
|
// 镜像: web 端 datePicker 默认值 = new Date().getTime() (Long)
|
|
// 修: POST 前扫描 fields 找 datePicker/timePicker, 字符串值自动转 Long
|
|
let datetimeConvertedCount = 0
|
|
for (const f of fields) {
|
|
const key = f?.__config__?.jnpfKey
|
|
const vmodel = f?.__vModel__
|
|
if (vmodel && (key === 'datePicker' || key === 'timePicker')) {
|
|
const val = sample[vmodel]
|
|
if (typeof val === 'string' && val.trim() !== '' && !/^-?\d+$/.test(val)) {
|
|
const ts = new Date(val).getTime()
|
|
if (!isNaN(ts)) {
|
|
sample[vmodel] = ts
|
|
datetimeConvertedCount++
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (datetimeConvertedCount > 0) {
|
|
log.info(` ↻ datetime 字段自动转 Long: ${datetimeConvertedCount} 项 (BS-New-3)`)
|
|
}
|
|
const createBody = { data: JSON.stringify(sample) }
|
|
const createR = (await c.postJson(`/visualdev/OnlineDev/${opts.formId}`, createBody)) as {
|
|
code: number
|
|
msg: string
|
|
data: { id?: string } | null
|
|
}
|
|
// JNPF POST /visualdev/OnlineDev/{id} 返回 data:null (无新 ID), 用唯一标识字段找
|
|
if (createR.code === 200) {
|
|
if (createR.data?.id) {
|
|
testDataId = createR.data.id
|
|
} else if (testMarker) {
|
|
// — 通过 List 反查 ID
|
|
// ⚠ B-14 (app batch2): JNPF List API + sidx='createTime' + sort='desc' → 返回 total=0 (空)
|
|
// 实测: 不传 sidx/sort 时 total 正确 (≥15), 传了就清零. JNPF 自身 bug.
|
|
// 不传 sidx/sort, 用 keyword 过滤 + 在结果里找 hit
|
|
const listBody: any = {
|
|
pageSize: 10,
|
|
currentPage: 1,
|
|
}
|
|
const firstStrKey = Object.keys(sample).find(k => typeof sample[k] === 'string')
|
|
if (firstStrKey) {
|
|
listBody.keyword = sample[firstStrKey]
|
|
}
|
|
const listR = (await c.postJson(`/visualdev/OnlineDev/${opts.formId}/List`, listBody)) as {
|
|
code: number
|
|
data: { list?: Array<Record<string, any>> } | null
|
|
}
|
|
if (listR.code === 200 && listR.data?.list?.length) {
|
|
const hit = listR.data.list.find((row: any) => {
|
|
return Object.values(row).some(v => typeof v === 'string' && v.includes(testMarker))
|
|
})
|
|
if (hit && hit.id) {
|
|
testDataId = String(hit.id)
|
|
} else if (listR.data.list[0].id) {
|
|
testDataId = String(listR.data.list[0].id)
|
|
}
|
|
}
|
|
}
|
|
steps.push({
|
|
step: '2. POST create (新增数据)',
|
|
status: 'PASS',
|
|
duration: Date.now() - t1,
|
|
detail: `msg="${createR.msg}"${testDataId ? ` id=${testDataId}` : opts.realData ? ' (POST OK, 跳过后续 GET/PUT/Join/Rule 验证)' : ' (JNPF POST 不返 id, 跳过后续步骤)'}`,
|
|
})
|
|
if (!opts.json) log.ok(`Step 2: POST create PASS (${Date.now() - t1}ms)${testDataId ? ` → id=${testDataId}` : ''}`)
|
|
} else {
|
|
steps.push({
|
|
step: '2. POST create (新增数据)',
|
|
status: 'FAIL',
|
|
duration: Date.now() - t1,
|
|
detail: `code=${createR.code}, msg="${createR.msg}"`,
|
|
})
|
|
if (!opts.json) log.error(`Step 2: POST create FAIL: ${createR.msg}`)
|
|
}
|
|
|
|
// Step 3: GET info 验证数据回读
|
|
if (testDataId) {
|
|
const t2 = Date.now()
|
|
const infoR = (await c.get(`/visualdev/OnlineDev/${opts.formId}/${testDataId}`)) as {
|
|
code: number
|
|
data: { data: string }
|
|
}
|
|
if (infoR.code === 200 && infoR.data?.data) {
|
|
steps.push({
|
|
step: '3. GET info (验证数据回读)',
|
|
status: 'PASS',
|
|
duration: Date.now() - t2,
|
|
detail: `data 长度 ${infoR.data.data.length} 字符`,
|
|
})
|
|
if (!opts.json) log.ok(`Step 3: GET info PASS (${Date.now() - t2}ms)`)
|
|
} else {
|
|
steps.push({
|
|
step: '3. GET info (验证数据回读)',
|
|
status: 'FAIL',
|
|
duration: Date.now() - t2,
|
|
detail: `code=${infoR.code}`,
|
|
})
|
|
if (!opts.json) log.error(`Step 3: GET info FAIL: code=${infoR.code}`)
|
|
}
|
|
}
|
|
|
|
// Step 4: PUT update (改一字段)
|
|
if (testDataId) {
|
|
const t3 = Date.now()
|
|
const updateR = await c.putJsonOnlineDevUpdate(
|
|
opts.formId,
|
|
testDataId,
|
|
{ ...sample, _test_updated: 'yes' }
|
|
) as { code: number; msg: string }
|
|
if (updateR.code === 200) {
|
|
steps.push({
|
|
step: '4. PUT update (修改数据)',
|
|
status: 'PASS',
|
|
duration: Date.now() - t3,
|
|
detail: `msg="${updateR.msg}"`,
|
|
})
|
|
if (!opts.json) log.ok(`Step 4: PUT update PASS (${Date.now() - t3}ms)`)
|
|
} else {
|
|
steps.push({
|
|
step: '4. PUT update (修改数据)',
|
|
status: 'FAIL',
|
|
duration: Date.now() - t3,
|
|
detail: `code=${updateR.code}, msg="${updateR.msg}"`,
|
|
})
|
|
if (!opts.json) log.error(`Step 4: PUT update FAIL: ${updateR.msg}`)
|
|
}
|
|
}
|
|
|
|
// Step 5: 跨表 join 校验 (新增 真实业务数据模式)
|
|
if (testDataId && runJoinCheck && joinRulesArr?.length) {
|
|
const t5 = Date.now()
|
|
try {
|
|
// 拿回最新数据 (含 relationForm lookup 的真实 ID)
|
|
const infoR = (await c.get(`/visualdev/OnlineDev/${opts.formId}/${testDataId}`)) as {
|
|
code: number
|
|
data: { data: string }
|
|
}
|
|
if (infoR.code !== 200 || !infoR.data?.data) {
|
|
throw new Error(`GET info failed: code=${infoR.code}`)
|
|
}
|
|
const currentData: Record<string, unknown> = JSON.parse(infoR.data.data)
|
|
const joinResults: Array<{ rule: string; ok: boolean; msg: string }> = []
|
|
for (const rule of joinRulesArr) {
|
|
const fkValue = currentData[rule.fkField]
|
|
if (!fkValue) {
|
|
joinResults.push({ rule: rule.fkField, ok: false, msg: `FK 字段 ${rule.fkField} 为空, 无法 join` })
|
|
continue
|
|
}
|
|
// 通过 modelId (enCode) 查关联表 List
|
|
const targetFormId = await getFormIdByEnCode(c, rule.targetEnCode)
|
|
if (!targetFormId) {
|
|
joinResults.push({ rule: rule.targetEnCode, ok: false, msg: `关联表 enCode=${rule.targetEnCode} 查不到 formId` })
|
|
continue
|
|
}
|
|
const targetListR = (await c.postJson(`/visualdev/OnlineDev/${targetFormId}/List`, {
|
|
pageSize: 10,
|
|
currentPage: 1,
|
|
keyword: String(fkValue),
|
|
})) as { code: number; data: { list?: Array<Record<string, any>> } | null }
|
|
if (targetListR.code !== 200 || !targetListR.data?.list?.length) {
|
|
joinResults.push({ rule: rule.targetEnCode, ok: false, msg: `关联表 ${rule.targetEnCode} 无匹配记录 (FK=${fkValue})` })
|
|
continue
|
|
}
|
|
// 验证目标记录的 checkField 有值 (说明 join 命中真实数据)
|
|
const hit = targetListR.data.list.find((row: any) => String(row.id) === String(fkValue) || String(row.f_id) === String(fkValue))
|
|
if (hit && hit[rule.checkField]) {
|
|
joinResults.push({ rule: rule.fkField, ok: true, msg: `${rule.fkField}=${fkValue} → ${rule.targetEnCode}.${rule.checkField}="${hit[rule.checkField]}"` })
|
|
} else if (targetListR.data.list[0]?.[rule.checkField]) {
|
|
joinResults.push({ rule: rule.fkField, ok: true, msg: `${rule.fkField}=${fkValue} → ${rule.targetEnCode} 模糊匹配, 首条 ${rule.checkField}="${targetListR.data.list[0][rule.checkField]}"` })
|
|
} else {
|
|
joinResults.push({ rule: rule.targetEnCode, ok: false, msg: `关联表 ${rule.targetEnCode} 命中但 ${rule.checkField} 字段空, join 校验失败` })
|
|
}
|
|
}
|
|
const failed = joinResults.filter(r => !r.ok)
|
|
steps.push({
|
|
step: '5. 跨表 join 校验 (FK → 关联表)',
|
|
status: failed.length === 0 ? 'PASS' : 'FAIL',
|
|
duration: Date.now() - t5,
|
|
detail: failed.length === 0
|
|
? `${joinResults.length} rules 全部 PASS: ${joinResults.map(r => r.msg).join('; ')}`
|
|
: `${failed.length}/${joinResults.length} FAIL: ${failed.map(r => r.msg).join('; ')}`,
|
|
})
|
|
if (failed.length === 0) {
|
|
if (!opts.json) log.ok(`Step 5: 跨表 join 校验 PASS (${Date.now() - t5}ms)`)
|
|
} else {
|
|
if (!opts.json) log.error(`Step 5: 跨表 join 校验 FAIL: ${failed.map(r => r.msg).join('; ')}`)
|
|
}
|
|
} catch (e) {
|
|
steps.push({
|
|
step: '5. 跨表 join 校验 (FK → 关联表)',
|
|
status: 'FAIL',
|
|
duration: Date.now() - t5,
|
|
detail: `异常: ${(e as Error).message}`,
|
|
})
|
|
if (!opts.json) log.error(`Step 5: 跨表 join 校验 FAIL: ${(e as Error).message}`)
|
|
}
|
|
} else if (testDataId && runJoinCheck && !joinRulesArr?.length) {
|
|
steps.push({
|
|
step: '5. 跨表 join 校验 (FK → 关联表)',
|
|
status: 'SKIP',
|
|
duration: 0,
|
|
detail: '--join-check 启用但未传 --join-rules',
|
|
})
|
|
}
|
|
|
|
// Step 6: 业务规则校验 (新增 真实业务数据模式)
|
|
if (testDataId && runBusinessRules && businessRulesArr?.length) {
|
|
const t6 = Date.now()
|
|
try {
|
|
const infoR = (await c.get(`/visualdev/OnlineDev/${opts.formId}/${testDataId}`)) as {
|
|
code: number
|
|
data: { data: string }
|
|
}
|
|
if (infoR.code !== 200 || !infoR.data?.data) {
|
|
throw new Error(`GET info failed: code=${infoR.code}`)
|
|
}
|
|
const currentData: Record<string, unknown> = JSON.parse(infoR.data.data)
|
|
const ruleResults: Array<{ rule: string; ok: boolean; msg: string }> = []
|
|
for (const rule of businessRulesArr) {
|
|
const fieldValue = currentData[rule.field]
|
|
const ok = evalBusinessRule(fieldValue, rule.rule)
|
|
ruleResults.push({
|
|
rule: `${rule.field} ${rule.rule}`,
|
|
ok,
|
|
msg: ok ? `${rule.field}=${fieldValue} ${rule.rule} ✓` : (rule.msg || `${rule.field}=${fieldValue} 不满足 ${rule.rule}`),
|
|
})
|
|
}
|
|
const failed = ruleResults.filter(r => !r.ok)
|
|
steps.push({
|
|
step: '6. 业务规则校验',
|
|
status: failed.length === 0 ? 'PASS' : 'FAIL',
|
|
duration: Date.now() - t6,
|
|
detail: failed.length === 0
|
|
? `${ruleResults.length} rules 全部 PASS: ${ruleResults.map(r => r.msg).join('; ')}`
|
|
: `${failed.length}/${ruleResults.length} FAIL: ${failed.map(r => r.msg).join('; ')}`,
|
|
})
|
|
if (failed.length === 0) {
|
|
if (!opts.json) log.ok(`Step 6: 业务规则校验 PASS (${Date.now() - t6}ms)`)
|
|
} else {
|
|
if (!opts.json) log.error(`Step 6: 业务规则校验 FAIL: ${failed.map(r => r.msg).join('; ')}`)
|
|
}
|
|
} catch (e) {
|
|
steps.push({
|
|
step: '6. 业务规则校验',
|
|
status: 'FAIL',
|
|
duration: Date.now() - t6,
|
|
detail: `异常: ${(e as Error).message}`,
|
|
})
|
|
if (!opts.json) log.error(`Step 6: 业务规则校验 FAIL: ${(e as Error).message}`)
|
|
}
|
|
} else if (testDataId && runBusinessRules && !businessRulesArr?.length) {
|
|
steps.push({
|
|
step: '6. 业务规则校验',
|
|
status: 'SKIP',
|
|
duration: 0,
|
|
detail: '--business-rules 未传, 跳过',
|
|
})
|
|
}
|
|
|
|
// Step 7: DELETE (清理, 除非 --keep-data)
|
|
if (testDataId && !opts.keepData) {
|
|
const t7 = Date.now()
|
|
const delR = await c.del(`/visualdev/OnlineDev/${opts.formId}/${testDataId}`) as {
|
|
code: number
|
|
msg: string
|
|
}
|
|
if (delR.code === 200) {
|
|
steps.push({
|
|
step: '7. DELETE (清理测试数据)',
|
|
status: 'PASS',
|
|
duration: Date.now() - t7,
|
|
detail: `id=${testDataId} deleted`,
|
|
})
|
|
if (!opts.json) log.ok(`Step 7: DELETE PASS (${Date.now() - t7}ms)`)
|
|
} else {
|
|
steps.push({
|
|
step: '7. DELETE (清理测试数据)',
|
|
status: 'FAIL',
|
|
duration: Date.now() - t7,
|
|
detail: `code=${delR.code}, msg="${delR.msg}"`,
|
|
})
|
|
if (!opts.json) log.warn(`Step 7: DELETE FAIL: ${delR.msg} (测试数据残留 id=${testDataId})`)
|
|
}
|
|
} else if (testDataId && opts.keepData) {
|
|
steps.push({
|
|
step: '7. DELETE (清理测试数据)',
|
|
status: 'SKIP',
|
|
duration: 0,
|
|
detail: `--keep-data 默认 ON, 保留 id=${testDataId} 供浏览器层 TC-B 验证`,
|
|
})
|
|
if (!opts.json) log.ok(`Step 7: SKIP (--keep-data 默认 ON, 保留数据 id=${testDataId})`)
|
|
}
|
|
} catch (e) {
|
|
steps.push({
|
|
step: 'ERR',
|
|
status: 'FAIL',
|
|
duration: 0,
|
|
detail: (e as Error).message,
|
|
})
|
|
if (!opts.json) log.error(`运行异常: ${(e as Error).message}`)
|
|
}
|
|
|
|
// 输出报告
|
|
const totalDuration = steps.reduce((s, x) => s + x.duration, 0)
|
|
const passCount = steps.filter(s => s.status === 'PASS').length
|
|
const failCount = steps.filter(s => s.status === 'FAIL').length
|
|
const skipCount = steps.filter(s => s.status === 'SKIP').length
|
|
|
|
const report = {
|
|
formId: opts.formId,
|
|
mode: opts.realData ? 'real-data' : 'fixture',
|
|
keepData: !!opts.keepData,
|
|
testDataId,
|
|
totalSteps: steps.length,
|
|
pass: passCount,
|
|
fail: failCount,
|
|
skip: skipCount,
|
|
totalDuration,
|
|
steps,
|
|
}
|
|
|
|
if (opts.json) {
|
|
printJson(report)
|
|
// v2.1+ (2026-07-21): --json 模式也落 CommandLog
|
|
printCommandEnd({
|
|
command: 'test run',
|
|
appCode: c.appCode,
|
|
result: failCount > 0 ? 'partial' : 'success',
|
|
error: failCount > 0 ? `${failCount} 个 step 失败` : undefined,
|
|
summary: { formId: opts.formId, pass: passCount, fail: failCount, skip: skipCount },
|
|
duration_ms: Date.now() - startTime,
|
|
verbose: opts.verbose,
|
|
json: opts.json,
|
|
})
|
|
return
|
|
}
|
|
|
|
const md = renderMarkdownReport(report)
|
|
if (opts.output) {
|
|
const fs = await import('node:fs/promises')
|
|
await fs.writeFile(opts.output, md, 'utf-8')
|
|
log.ok(`报告写入: ${opts.output}`)
|
|
} else {
|
|
console.log(md)
|
|
}
|
|
// v2.1+ (2026-07-21): 落 CommandLog (L3) — 测试报告天然适合历史查询
|
|
printCommandEnd({
|
|
command: 'test run',
|
|
appCode: c.appCode,
|
|
result: failCount > 0 ? 'partial' : 'success',
|
|
error: failCount > 0 ? `${failCount} 个 step 失败` : undefined,
|
|
summary: { formId: opts.formId, pass: passCount, fail: failCount, skip: skipCount },
|
|
duration_ms: Date.now() - startTime,
|
|
verbose: opts.verbose,
|
|
json: opts.json,
|
|
})
|
|
// 退出码: fail > 0 退出 1
|
|
if (failCount > 0) process.exit(1)
|
|
})
|
|
|
|
installHelpHookWithPatterns(cmd, 'test run', {
|
|
purpose: '跑 form API 测试 (POST/GET/PUT/DELETE + 跨表 join + 业务规则, 默认走真实业务数据)',
|
|
required: { '--formId': '目标 form id' },
|
|
optional: {
|
|
'--output': '输出报告文件路径 (默认 stdout)',
|
|
'--keep-data / --no-keep-data': '保留 / 删除测试数据 (默认 keep, 留数据供 TC-B 浏览器验证)',
|
|
'--real-data / --no-real-data': '真实业务数据 / test fixture 模式 (默认 real-data)',
|
|
'--real-fields <json>': '自定义真实业务数据 JSON (优先级最高; P0-2 fix 后主子表也走自动 sample, 无需强传)',
|
|
'--relation-form-lookup / --no-relation-form-lookup': 'relationForm 自动 lookup 关联表真实 ID (默认 ON)',
|
|
'--relation-form-sample <n>': '关联表拉前 N 条 (默认 1, 最大 5)',
|
|
'--join-check / --join-rules <json>': '跨表 join 校验 (FK → 关联表)',
|
|
'--business-rules <json>': '业务规则校验',
|
|
},
|
|
example: [
|
|
'dacli test run --formId=839877227762942789 # 默认 real-data + keep-data',
|
|
'dacli test run --formId=839877227762942789 --no-keep-data # 旧 fixture 模式 + 立即清理',
|
|
'dacli test run --formId=839877227762942789 --real-fields \'{"f_team_name":"数据先锋队"}\' # 自定义真实业务数据',
|
|
'dacli test run --formId=839877227762942789 --join-check --join-rules \'[{"fkField":"f_team_id","targetEnCode":"jxcj_team","checkField":"f_team_name"}]\'',
|
|
'dacli test run --formId=839877227762942789 --business-rules \'[{"field":"f_team_size","rule":">=3","msg":"团队人数下限 3 人"}]\'',
|
|
],
|
|
source: { api: 'GET/POST/PUT/DELETE /visualdev/OnlineDev/{formId}' },
|
|
notes: [
|
|
'**v0.11+ NEW** (2026-06-28 阶段 7.2): 升级到真实业务数据 CRUD 模式',
|
|
'**默认模式**: real-data (字段语义化默认值 + 关联表真实 ID lookup) + keep-data (留数据供 TC-B)',
|
|
'**7 步流程**: 拉 schema → POST create → GET info → PUT update → 跨表 join → 业务规则 → DELETE',
|
|
'**vs 浏览器测试**: 速度 5s vs 30s, 不需 token, 可重跑, 局限是查不出浏览器 vmodel bind bug',
|
|
'**vs test fixture (旧)**: real-data 用字段语义化值 + 关联表真实 ID, 不再是 t_<vmodel> 短前缀',
|
|
'**relationForm 自动 lookup**: 从关联表 List 前 N 条拉真实 ID (而非跳过), 修 BS-49/50 (关联字段空)',
|
|
'**跨表 join 校验**: FK 字段能查到关联表记录, 修 jxcj 跨表验证盲点',
|
|
'**业务规则校验**: 字段值约束 (例: team_size >= 3), 修 jxcj 业务规则盲点',
|
|
],
|
|
})
|
|
return cmd
|
|
}
|
|
|
|
/**
|
|
* 从 formData.fields 推导 sample data.
|
|
* 真实业务数据模式 * - 优先级 1: 用户传 --real-fields (最高优先级)
|
|
* - 优先级 2: 真实业务数据模式 (字段语义化默认值 + relationForm lookup)
|
|
* * varchar: `测试值_${vmodel}_${randomShort}` (避免 timestamp 后缀污染业务数据)
|
|
* * int: 100 (业务常用默认值)
|
|
* * decimal: 99.99
|
|
* * datetime: 当前 Date.now() (Long 时间戳, 与 web datePicker 一致)
|
|
* * select/radio/switch/checkbox: options[0].value
|
|
* * userSelect/organizeSelect/posSelect: '1' (admin)
|
|
* * relationForm: 从关联表 list 前 N 条拉真实 ID (而非跳过)
|
|
* - 优先级 3: test fixture 模式 (旧行为, --no-real-data 启用)
|
|
* * varchar: `t_${vmodel}` (短前缀 + 截断 20 字符)
|
|
* 规则 (沉淀自 tdd10 实战):
|
|
* - system fields → 跳过 (createUser/createTime/modifyUser/modifyTime/currOrganize/currPosition/billRule)
|
|
* - uploadImg/uploadFz/uploadFile → 跳过 (附件)
|
|
* - table 容器 → 填 1 行子表数据 (主子表 form 必须)
|
|
*/
|
|
async function buildSampleData(
|
|
fields: Array<{ __vModel__?: string; __config__?: { jnpfKey?: string; required?: boolean; options?: Array<{ value: string }>; modelId?: string; propsValue?: string; relationField?: string; children?: any[] } }>,
|
|
client: JnpfClient,
|
|
opts: SampleOptions,
|
|
): Promise<Record<string, unknown>> {
|
|
const sample: Record<string, unknown> = {}
|
|
|
|
// 优先级 1: 用户传 --real-fields 最高优先级
|
|
if (opts.realFields) {
|
|
Object.assign(sample, opts.realFields)
|
|
// relationForm 字段仍然要走 lookup (用户可能没填)
|
|
for (const f of fields) {
|
|
const vmodel = f.__vModel__
|
|
const cfg = f.__config__ || {}
|
|
const key = cfg.jnpfKey
|
|
if (!vmodel || !key) continue
|
|
if (key === 'relationForm' && opts.relationFormLookup && !sample[vmodel]) {
|
|
const realId = await lookupRelationFormId(client, cfg)
|
|
if (realId) sample[vmodel] = realId
|
|
}
|
|
}
|
|
return sample
|
|
}
|
|
|
|
const sysKeys = new Set(['createUser', 'createTime', 'modifyUser', 'modifyTime', 'currOrganize', 'currPosition', 'billRule'])
|
|
// 子表缓存 (避免同 enCode 多次查询)
|
|
const relationCache = new Map<string, string | null>()
|
|
// 字典缓存 (避免同 dictionaryType 多次查询)
|
|
const dictionaryCache = new Map<string, Array<Record<string, unknown>>>()
|
|
|
|
for (const f of fields) {
|
|
const vmodel = f.__vModel__
|
|
const cfg = f.__config__ || {}
|
|
const key = cfg.jnpfKey
|
|
if (!vmodel || !key) continue
|
|
if (sysKeys.has(key)) continue
|
|
if (['uploadImg', 'uploadFz', 'uploadFile'].includes(key)) continue
|
|
|
|
// relationForm 字段: 从关联表 list 前 N 条拉真实 ID
|
|
if (key === 'relationForm') {
|
|
if (opts.relationFormLookup) {
|
|
const cacheKey = cfg.modelId || cfg.propsValue || ''
|
|
let realId: string | null | undefined = relationCache.get(cacheKey)
|
|
if (realId === undefined) {
|
|
realId = await lookupRelationFormId(client, cfg, opts.relationFormSample)
|
|
relationCache.set(cacheKey, realId)
|
|
}
|
|
if (realId) {
|
|
sample[vmodel] = realId
|
|
continue
|
|
}
|
|
}
|
|
// 不 lookup 时跳过 (旧 fixture 行为)
|
|
continue
|
|
}
|
|
|
|
if (['input', 'textarea'].includes(key)) {
|
|
if (opts.realData) {
|
|
// 真实业务数据: 字段语义化值, 不加 timestamp 后缀
|
|
// 避免 varchar(20) 截断报错 (保留字段名前 15 字符)
|
|
const baseName = vmodel.replace(/^f_/, '').replace(/_/g, '').slice(0, 15)
|
|
const randomShort = Math.random().toString(36).slice(-4)
|
|
sample[vmodel] = `测试值_${baseName}_${randomShort}`.slice(0, 30)
|
|
} else {
|
|
// 旧 fixture 模式
|
|
sample[vmodel] = `t_${vmodel}`.slice(0, 20)
|
|
}
|
|
continue
|
|
}
|
|
if (['inputNumber', 'numInput', 'calculate'].includes(key)) {
|
|
sample[vmodel] = opts.realData ? 100 : 100
|
|
continue
|
|
}
|
|
if (['datePicker', 'timePicker'].includes(key)) {
|
|
// Long 时间戳 (与 web datePicker 默认值一致)
|
|
sample[vmodel] = Date.now()
|
|
continue
|
|
}
|
|
if (key === 'select') {
|
|
sample[vmodel] = await pickChoiceValue(client, dictionaryCache, cfg, vmodel)
|
|
continue
|
|
}
|
|
if (key === 'radio' || key === 'switch' || key === 'checkbox') {
|
|
sample[vmodel] = await pickChoiceValue(client, dictionaryCache, cfg, vmodel)
|
|
continue
|
|
}
|
|
if (key === 'userSelect' || key === 'organizeSelect' || key === 'posSelect') {
|
|
sample[vmodel] = opts.realData ? '管理员' : '1'
|
|
continue
|
|
}
|
|
// 主子表 form 的 table 容器: 填 1 行子表数据
|
|
if (key === 'table') {
|
|
const children = (cfg.children || [])
|
|
const childRow: Record<string, unknown> = {}
|
|
for (const c of children) {
|
|
const cCfg = c.__config__ || {}
|
|
const cKey = cCfg.jnpfKey
|
|
const cVmodel = c.__vModel__
|
|
if (!cVmodel) continue
|
|
if (['input', 'textarea'].includes(cKey)) {
|
|
childRow[cVmodel] = opts.realData
|
|
? `测试值_${cVmodel.replace(/^f_/, '').slice(0, 10)}_${Math.random().toString(36).slice(-3)}`.slice(0, 25)
|
|
: `t_${cVmodel}`.slice(0, 20)
|
|
} else if (['inputNumber', 'numInput', 'calculate'].includes(cKey)) {
|
|
childRow[cVmodel] = 100
|
|
} else if (['datePicker', 'timePicker'].includes(cKey)) {
|
|
childRow[cVmodel] = Date.now()
|
|
} else if (['select', 'radio', 'switch', 'checkbox'].includes(cKey)) {
|
|
childRow[cVmodel] = cCfg.options?.[0]?.value || '1'
|
|
} else {
|
|
childRow[cVmodel] = opts.realData
|
|
? `测试值_${cVmodel}`.slice(0, 20)
|
|
: `t_${cVmodel}`.slice(0, 20)
|
|
}
|
|
}
|
|
sample[vmodel] = [childRow]
|
|
continue
|
|
}
|
|
}
|
|
return sample
|
|
}
|
|
|
|
/**
|
|
* 从关联表 List 前 N 条拉真实 ID.
|
|
* @param client JnpfClient
|
|
* @param cfg relationForm 字段的 __config__ (含 modelId/propsValue/relationField)
|
|
* @param sampleN 取第 N 条 (1-based, 默认 1)
|
|
* @returns 真实 ID 字符串, 或 null (无数据/失败)
|
|
*/
|
|
async function lookupRelationFormId(
|
|
client: JnpfClient,
|
|
cfg: { modelId?: string; propsValue?: string; relationField?: string },
|
|
sampleN: number = 1,
|
|
): Promise<string | null> {
|
|
try {
|
|
const modelId = cfg.modelId || cfg.propsValue
|
|
if (!modelId) return null
|
|
const listR = (await client.postJson(`/visualdev/OnlineDev/${modelId}/List`, {
|
|
pageSize: Math.max(sampleN, 1),
|
|
currentPage: 1,
|
|
})) as { code: number; data: { list?: Array<Record<string, any>> } | null }
|
|
if (listR.code !== 200 || !listR.data?.list?.length) return null
|
|
const idx = Math.max(0, Math.min(sampleN - 1, listR.data.list.length - 1))
|
|
const row = listR.data.list[idx]
|
|
return row.id || row.f_id || null
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Pick a sample value for choice-style controls (select / radio / switch / checkbox).
|
|
* Priority:
|
|
* 1. JNPF dictionary binding (`dataType === 'dictionary'` + `dictionaryType` id) → first item's enCode
|
|
* 2. static options list → first option's value
|
|
* 3. fallback `'1'` (test fixture safety)
|
|
*/
|
|
export async function pickChoiceValue(
|
|
client: JnpfClient,
|
|
cache: Map<string, Array<Record<string, unknown>>>,
|
|
cfg: { options?: Array<{ value: string }>; dataType?: string; dictionaryType?: string; propsValue?: string },
|
|
vmodel: string,
|
|
): Promise<unknown> {
|
|
const optsCfg = cfg.options || []
|
|
const optValue = optsCfg[0]?.value
|
|
if (cfg.dataType === 'dictionary' && cfg.dictionaryType) {
|
|
let items = cache.get(cfg.dictionaryType)
|
|
if (!items) {
|
|
try {
|
|
const { initWebapi, loadDict } = await import('../../webapi/dict.ts')
|
|
await initWebapi(client)
|
|
const r = (await loadDict.getDictionaryDataSelector(cfg.dictionaryType)) as unknown
|
|
const raw = Array.isArray(r) ? r : (r as { data?: unknown })?.data
|
|
const flat: Array<Record<string, unknown>> = []
|
|
const walk = (nodes: unknown): void => {
|
|
for (const n of (Array.isArray(nodes) ? nodes : []) as Array<Record<string, unknown>>) {
|
|
if (typeof n?.enCode === 'string') flat.push(n)
|
|
if (Array.isArray(n?.children)) walk(n.children)
|
|
}
|
|
}
|
|
walk(raw)
|
|
items = flat
|
|
cache.set(cfg.dictionaryType, items)
|
|
} catch {
|
|
items = []
|
|
cache.set(cfg.dictionaryType, items)
|
|
}
|
|
}
|
|
const first = items.find((item) => item?.enCode)
|
|
if (first && typeof first.enCode === 'string') return first.enCode
|
|
}
|
|
if (typeof optValue === 'string' && optValue) return optValue
|
|
return '1'
|
|
}
|
|
|
|
/**
|
|
* 通过 enCode 查 formId (缓存于本次 run 周期内).
|
|
*/
|
|
const formIdCacheByEnCode = new Map<string, string | null>()
|
|
async function getFormIdByEnCode(client: JnpfClient, enCode: string): Promise<string | null> {
|
|
if (formIdCacheByEnCode.has(enCode)) return formIdCacheByEnCode.get(enCode)!
|
|
try {
|
|
const listR = (await client.get(`/visualdev/Base/list?keyword=${encodeURIComponent(enCode)}`)) as {
|
|
code: number
|
|
data: { list?: Array<{ id: string; enCode: string }> } | null
|
|
}
|
|
if (listR.code !== 200 || !listR.data?.list?.length) {
|
|
formIdCacheByEnCode.set(enCode, null)
|
|
return null
|
|
}
|
|
const hit = listR.data.list.find(f => f.enCode === enCode) || listR.data.list[0]
|
|
formIdCacheByEnCode.set(enCode, hit.id)
|
|
return hit.id
|
|
} catch {
|
|
formIdCacheByEnCode.set(enCode, null)
|
|
return null
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 业务规则求值器 (支持: >= <= > < == != + - * / 数字)
|
|
* 例: ">=3" 表示 fieldValue >= 3
|
|
* "<=100" 表示 fieldValue <= 100
|
|
* "==1" 表示 fieldValue == 1
|
|
* "!=0" 表示 fieldValue != 0
|
|
*/
|
|
function evalBusinessRule(fieldValue: unknown, rule: string): boolean {
|
|
const m = rule.match(/^(>=|<=|>|<|==|!=)\s*(.+)$/)
|
|
if (!m) return false
|
|
const op = m[1]
|
|
const target = Number(m[2])
|
|
const v = Number(fieldValue)
|
|
if (Number.isNaN(target) || Number.isNaN(v)) return false
|
|
switch (op) {
|
|
case '>=': return v >= target
|
|
case '<=': return v <= target
|
|
case '>': return v > target
|
|
case '<': return v < target
|
|
case '==': return v === target
|
|
case '!=': return v !== target
|
|
default: return false
|
|
}
|
|
}
|
|
|
|
function renderMarkdownReport(r: { formId: string; mode: string; keepData: boolean; testDataId: string | null; totalSteps: number; pass: number; fail: number; skip: number; totalDuration: number; steps: StepResult[] }): string {
|
|
const lines: string[] = []
|
|
lines.push(`# form API 测试报告 (v0.11+ 真实业务数据模式)`)
|
|
lines.push('')
|
|
lines.push(`- formId: \`${r.formId}\``)
|
|
lines.push(`- mode: **${r.mode}** (real-data: 字段语义化 + 关联表真实 ID; fixture: test fixture 短前缀)`)
|
|
lines.push(`- keep-data: **${r.keepData ? 'ON (数据保留供 TC-B)' : 'OFF (跑完 DELETE)'}**`)
|
|
lines.push(`- 测试数据 ID: \`${r.testDataId || '(无)'}\``)
|
|
lines.push(`- 通过: **${r.pass}/${r.totalSteps}**`)
|
|
lines.push(`- 失败: **${r.fail}**`)
|
|
lines.push(`- 跳过: **${r.skip}**`)
|
|
lines.push(`- 总耗时: ${r.totalDuration}ms`)
|
|
lines.push('')
|
|
lines.push(`| Step | Status | Duration | Detail |`)
|
|
lines.push(`|------|--------|----------|--------|`)
|
|
for (const s of r.steps) {
|
|
const icon = s.status === 'PASS' ? 'PASS' : s.status === 'FAIL' ? 'FAIL' : 'SKIP'
|
|
lines.push(`| ${s.step} | ${icon} | ${s.duration}ms | ${s.detail || ''} |`)
|
|
}
|
|
lines.push('')
|
|
lines.push(`## 通过条件`)
|
|
lines.push('')
|
|
lines.push(`- exit 0 (PASS): ${r.pass}/${r.totalSteps}`)
|
|
lines.push(`- exit 1 (FAIL): ${r.fail} 个失败`)
|
|
lines.push('')
|
|
if (r.keepData && r.testDataId) {
|
|
lines.push(`## 数据保留 (供浏览器层 TC-B 验证)`)
|
|
lines.push('')
|
|
lines.push(`- 测试数据保留 ID: \`${r.testDataId}\``)
|
|
lines.push(`- 浏览器访问: \`http://nginx/jnpf_app_developSystem/model/{enCode}?dataId=${r.testDataId}\``)
|
|
lines.push(`- 清理: \`dacli form delete-data <formId> <${r.testDataId}>\` 或浏览器端手动删除`)
|
|
lines.push('')
|
|
}
|
|
lines.push(`> 浏览器层验证 (新增按钮 + 截图 + UI 渲染 + 4 铁律) 需用 ssw-e2e-test 单独跑. \`dacli test run\` 仅验证 API 层 + 跨表 join + 业务规则.`)
|
|
return lines.join('\n')
|
|
} |