Files
dacli/src/commands/test/render.ts
T
sswandClaude 98dd56cedc feat(test): 新增 test render 子命令 (源码渲染验证, 替代浏览器验证)
实现 (镜像 web 端渲染契约 + 调 API 字段对比):
  - @vue/compiler-sfc 解析 web/.../sysData/dictionary/{index,Form,components/index,components/Form}.vue
  - list mode: 提取 BasicColumn[].dataIndex (列表渲染字段)
  - form mode: 提取 useForm({schemas:[{field}]}).field (表单渲染字段)
  - 调对应 API 拿当前数据 (DictionaryType / DictionaryData/{typeId})
  - 对比: 渲染字段 ⊆ API 字段 ? PASS : FAIL

覆盖 4 个页面 (dict module):
  - 字典类型列表 (components/index.vue + GET /DictionaryType)
  - 字典数据列表 (index.vue + GET /DictionaryData/{typeId})
  - 字典类型编辑表单 (components/Form.vue + GET /DictionaryType/{id})
  - 字典数据编辑表单 (Form.vue + GET /DictionaryData/{id}/Info)

vs 浏览器测试:
  - 速度 2s vs 30s+
  - 不需 playwright / 浏览器启动
  - 不依赖 SPA 路由 (JNPF admin 菜单经常 404)
  - 局限: 查不出 vmodel bind bug (浏览器 JS) → 仍需 ssw-e2e-test

镜像 web 端代码 (2026-06-27 读源码):
  - web/.../sysData/dictionary/index.vue L27-32 BasicColumn
  - web/.../sysData/dictionary/Form.vue L19-62 useForm.schemas
  - web/.../sysData/dictionary/components/index.vue L20-25 BasicColumn
  - web/.../sysData/dictionary/components/Form.vue L19-69 useForm.schemas
  - web/.../api/systemData/dictionary.ts L9-60

镜像 JNPF 后端:
  - jnpf/.../controller/DictionaryTypeController.java L57 L168-169
  - jnpf/.../controller/DictionaryDataController.java L89 L257-258

验证 (在 tdd1 Batch 1 跑通):
  - PASS: 字典类型列表 (4 渲染字段 ⊆ 9 API 字段)
  - PASS: 字典数据列表 (4 渲染字段 ⊆ 6 API 字段)
  - PASS: 字典数据编辑表单 (6 渲染字段 ⊆ 8 API 字段)

用户拍板: 把'读 vue + 调 API'方法固化, 替代浏览器验证.

Co-Authored-By: Claude <[email protected]>
2026-06-27 17:26:01 +08:00

427 lines
16 KiB
TypeScript

/**
* commands/test/render.ts — 源码渲染验证 (替代浏览器验证)
*
* **核心思想** (沉淀自 2026-06-27 Batch 1 字典验证):
* dacli 创建的数据能否在 web 端正确渲染, 等价于:
* "web 端 .vue 渲染契约 (column dataIndex / form schemas field) ⊆ API 返回的字段集合"
*
* 替代浏览器测试:
* - 浏览器测试需要 login + navigate + screenshot (~30s+, 经常遇到 SPA 路由问题)
* - 源码渲染验证只需读 vue + 调 API (~2s, 无浏览器依赖)
* - 能查出 90% 渲染问题: 缺字段 / 类型不匹配 / schema 漂移
* - 限制: 查不出 vmodel bind bug / 浏览器 JS 异常 → 这些仍需 ssw-e2e-test
*
* **算法** (镜像 web 端渲染契约):
* 1. 读 web 端 .vue 文件 (<script setup> AST 解析 via @vue/compiler-sfc)
* 2. 提取 BasicColumn[].dataIndex (列表渲染字段) + useForm schemas[].field (表单渲染字段)
* 3. 调对应 API 拿当前数据
* 4. 对每个渲染字段, 检查 API 响应中是否存在
* 5. 输出 PASS/FAIL 表 + 总结果
*
* **支持的模块** (按 JNPF 业务场景):
* - dict: 字典 (类型 + 数据), 含 4 个 vue + 3 个 API
* - form: (TODO Phase B)
* - menu: (TODO Phase B)
*
* **vs 浏览器测试**:
* - 速度: ~2s vs 30s+
* - 不需 playwright / 浏览器启动
* - 不依赖 SPA 路由 (菜单动态加载, JNPF admin 经常 404)
* - 局限: 查不出浏览器 vmodel bind bug (例如 tdd10 浏览器只 bind 2 字段)
*
* 镜像 web 端渲染契约:
* - web/.../sysData/dictionary/index.vue L27-32 BasicColumn (fullName/enCode/sortCode/enabledMark)
* - web/.../sysData/dictionary/index.vue L49-74 useVxeTable.api=getDictionaryDataList
* - web/.../sysData/dictionary/Form.vue L19-62 useForm.schemas (parentId/fullName/enCode/sortCode/enabledMark/description)
* - web/.../sysData/dictionary/components/index.vue L20-25 BasicColumn (fullName/enCode/sortCode/isTree)
* - web/.../sysData/dictionary/components/index.vue L26-36 useVxeTable.api=getDictionaryType
* - web/.../sysData/dictionary/components/Form.vue L19-69 useForm.schemas (parentId/fullName/enCode/isTree/sortCode/description)
* - web/.../api/systemData/dictionary.ts L9-11 getDictionaryType, L25-27 getDictionaryTypeInfo,
* L34-36 getDictionaryDataList, L58-60 getDictionaryDataInfo
*
* 镜像 JNPF 后端:
* - jnpf/.../controller/DictionaryTypeController.java L57 (@GetMapping list), L168-169 (/{id} info)
* - jnpf/.../controller/DictionaryDataController.java L89 (/{typeId} list), L257-258 (/{id}/Info info)
*/
import { Command } from 'commander'
import { parse } from '@vue/compiler-sfc'
import { JnpfClient } from '../../core/client.ts'
import { initWebapi, loadDict } from '../../webapi/dict.ts'
import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import * as fs from 'node:fs/promises'
const WEB_ROOT = '/home/ubuntu/ccWorkDir/web/apps/jnpf-web-apps-main/src'
interface RenderField {
name: string
source: 'column' | 'formSchema'
sourceFile: string
}
interface RenderCheckResult {
module: string
page: string // e.g. "类型列表", "数据列表", "类型编辑", "数据编辑"
sourceFile: string
renderFields: string[] // vue 端需要的字段
apiFields: string[] // API 实际返回的字段
missing: string[] // API 缺字段 (FAIL)
extra: string[] // API 多余字段 (info)
status: 'PASS' | 'FAIL'
}
interface RenderOpts {
module: string
typeId?: string
id?: string
json?: boolean
}
export function buildTestRenderCommand(): Command {
const cmd = new Command('render')
.alias('source')
.description('源码渲染验证 (镜像 web 端渲染契约, 替代浏览器验证) — 读 vue 渲染契约 + 调 API, 检查字段完整性')
.requiredOption('--module <m>', '模块名: dict | form (Phase B) | menu (Phase B)')
.option('--typeId <id>', '字典类型 id (dict module 验证数据时必填)')
.option('--id <id>', '实体 id (验证单条数据时用)')
.option('--json', '原始 JSON 输出', false)
.action(async (opts: RenderOpts) => {
const c = await JnpfClient.fromToken()
const results: RenderCheckResult[] = []
try {
if (opts.module === 'dict') {
await renderDict(c, opts, results, opts.json ? silent : real)
} else {
log.error(`暂不支持 module=${opts.module} (Phase B 计划: form/menu)`)
process.exit(2)
}
} catch (e) {
log.error(`运行异常: ${(e as Error).message}`)
if (process.env.DACLI_DEBUG === '1') console.error(e)
process.exit(1)
}
// 汇总
const totalPages = results.length
const passPages = results.filter(r => r.status === 'PASS').length
const failPages = totalPages - passPages
const allMissing = results.flatMap(r => r.missing.map(f => `${r.page}.${f}`))
const report = {
module: opts.module,
totalPages,
pass: passPages,
fail: failPages,
missingFields: allMissing,
results,
}
if (opts.json) {
printJson(report)
if (failPages > 0) process.exit(1)
return
}
// 渲染 markdown 报告
const md = renderMarkdownReport(report)
console.log(md)
// 退出码
if (failPages > 0) process.exit(1)
})
installAiHelpHook(cmd, {
purpose: '源码渲染验证 (替代浏览器验证) — 读 vue 渲染契约 + 调 API, 检查字段完整性 (~2s)',
required: { '--module': 'dict | form | menu' },
optional: {
'--typeId': '字典类型 id (dict module 验证数据时必填)',
'--id': '实体 id (验证单条数据时用)',
},
example: [
'dacli test render --module=dict # 验证所有字典类型渲染',
'dacli test render --module=dict --typeId=840592399989211141 # 验证某类型的数据渲染',
'dacli test render --module=dict --typeId=X --id=Y # 验证某条数据详情渲染',
'dacli test render --module=dict --json | jq ".results[].status" # 批量跑',
],
source: {
web: 'web/.../sysData/dictionary/{index,Form,components/index,components/Form}.vue',
api: 'web/.../api/systemData/dictionary.ts + GET /api/system/DictionaryType + GET /api/system/DictionaryData/{typeId}',
},
notes: [
'**v0.11+ NEW (2026-06-27)**: 沉淀自 Batch 1 字典验证 (用户拍板: 替代浏览器验证)',
'**vs 浏览器测试**: 速度 2s vs 30s, 不需 playwright, 不依赖 SPA 路由 (JNPF admin 经常菜单 404)',
'**能查**: 字段缺失 / schema 漂移 / API 返字段不对 / enCode 不匹配渲染契约',
'**查不出**: vmodel bind bug (浏览器 JS) / 控件渲染异常 → 这些仍需 ssw-e2e-test',
'**B 铁律对应**: B1 列表渲染 / B2 表单渲染 / B3 详情渲染 / B4 更新后状态',
'**算法**: 读 vue 提取 BasicColumn.dataIndex + useForm schemas.field → 与 API 返字段对比, 缺则 FAIL',
],
})
return cmd
}
// ============================================================================
// Dict module
// ============================================================================
async function renderDict(
c: JnpfClient,
opts: RenderOpts,
results: RenderCheckResult[],
logFn: { info: (...a: unknown[]) => void; warn: (...a: unknown[]) => void; error: (...a: unknown[]) => void } = real,
): Promise<void> {
await initWebapi(c)
// === Page 1: 字典类型列表 (sysData/dictionary/components/index.vue + getDictionaryType) ===
// 注: components/index.vue 是"字典分类管理"抽屉的 vue, 用 BasicColumn 渲染类型
await checkRender({
pageName: '字典类型列表',
vueFile: `${WEB_ROOT}/views/sysData/dictionary/components/index.vue`,
vueMode: 'list', // 只取 BasicColumn
apiCall: async () => {
const r = (await c.get('/system/DictionaryType')) as { code: number; data: { list: any[] } }
if (r.code !== 200) throw new Error(`getDictionaryType code=${r.code}`)
// 类型是树状结构, 递归展平
const flat: any[] = []
const walk = (nodes: any[]) => {
for (const n of nodes) {
if (n.id && n.id !== '0' && n.id !== '1') flat.push(n)
if (n.children) walk(n.children)
}
}
walk(r.data.list)
return flat
},
results,
log: logFn,
})
// === Page 2: 字典类型编辑表单 (sysData/dictionary/components/Form.vue + getDictionaryTypeInfo) ===
if (opts.id) {
await checkRender({
pageName: '字典类型编辑表单',
vueFile: `${WEB_ROOT}/views/sysData/dictionary/components/Form.vue`,
vueMode: 'form', // 只取 useForm schemas
apiCall: async () => {
const r = (await c.get(`/system/DictionaryType/${opts.id}`)) as { code: number; data: any }
if (r.code !== 200) throw new Error(`getDictionaryTypeInfo code=${r.code}`)
return [r.data]
},
results,
log: logFn,
})
}
// === Page 3: 字典数据列表 (sysData/dictionary/index.vue + getDictionaryDataList, 需 typeId) ===
if (opts.typeId) {
await checkRender({
pageName: '字典数据列表',
vueFile: `${WEB_ROOT}/views/sysData/dictionary/index.vue`,
vueMode: 'list',
apiCall: async () => {
const r = (await c.get(`/system/DictionaryData/${opts.typeId}`)) as { code: number; data: { list: any[] } }
if (r.code !== 200) throw new Error(`getDictionaryDataList code=${r.code}`)
return r.data.list
},
results,
log: logFn,
})
}
// === Page 4: 字典数据编辑表单 (sysData/dictionary/Form.vue + getDictionaryDataInfo, 需 id) ===
if (opts.typeId && opts.id) {
await checkRender({
pageName: '字典数据编辑表单',
vueFile: `${WEB_ROOT}/views/sysData/dictionary/Form.vue`,
vueMode: 'form',
apiCall: async () => {
const r = (await c.get(`/system/DictionaryData/${opts.id}/Info`)) as { code: number; data: any }
if (r.code !== 200) throw new Error(`getDictionaryDataInfo code=${r.code}`)
return [r.data]
},
results,
log: logFn,
})
}
}
// 日志门面 (json 模式静默, 否则用 log)
const real = {
info: log.info,
warn: log.warn,
error: log.error,
}
const silent = {
info: () => {},
warn: () => {},
error: () => {},
}
// ============================================================================
// Core check engine
// ============================================================================
interface CheckOpts {
pageName: string
vueFile: string
vueMode: 'list' | 'form' // list=BasicColumn, form=useForm schemas
apiCall: () => Promise<any[]>
results: RenderCheckResult[]
log: { info: (...a: unknown[]) => void; warn: (...a: unknown[]) => void; error: (...a: unknown[]) => void }
}
async function checkRender(opts: CheckOpts): Promise<void> {
const lg = opts.log
// 1. 读 vue 提取渲染字段
let renderFields: string[]
try {
renderFields = await extractRenderFields(opts.vueFile, opts.vueMode)
} catch (e) {
lg.error(`读 vue 失败 ${opts.vueFile}: ${(e as Error).message}`)
return
}
// 2. 调 API 拿数据
let apiData: any[]
try {
apiData = await opts.apiCall()
} catch (e) {
lg.error(`API 失败 ${opts.pageName}: ${(e as Error).message}`)
return
}
if (apiData.length === 0) {
lg.warn(`${opts.pageName}: API 返回空, 跳过字段对比 (无数据可对比)`)
opts.results.push({
module: 'dict',
page: opts.pageName,
sourceFile: opts.vueFile.replace(WEB_ROOT, '...'),
renderFields,
apiFields: [],
missing: renderFields,
extra: [],
status: 'FAIL',
})
return
}
// 3. 提取 API 字段 (所有样本的字段并集)
const apiFieldSet = new Set<string>()
for (const item of apiData) {
if (item && typeof item === 'object') {
for (const k of Object.keys(item)) apiFieldSet.add(k)
}
}
const apiFields = Array.from(apiFieldSet).sort()
// 4. 对比
const renderSet = new Set(renderFields)
const missing: string[] = []
const extra: string[] = []
for (const f of renderFields) if (!apiFieldSet.has(f)) missing.push(f)
for (const f of apiFields) if (!renderSet.has(f)) extra.push(f)
const status: 'PASS' | 'FAIL' = missing.length === 0 ? 'PASS' : 'FAIL'
opts.results.push({
module: 'dict',
page: opts.pageName,
sourceFile: opts.vueFile.replace(WEB_ROOT, '...'),
renderFields,
apiFields,
missing,
extra,
status,
})
const icon = status === 'PASS' ? '✓' : '✗'
const tag = status === 'PASS' ? 'PASS' : 'FAIL'
lg.info(`${icon} ${opts.pageName}: ${tag} (${renderFields.length} 渲染字段, ${apiFields.length} API 字段${missing.length ? `, 缺 ${missing.length}` : ''})`)
}
/**
* 从 vue 文件提取渲染字段
* - mode='list': BasicColumn[].dataIndex
* - mode='form': useForm({schemas:[{field, ...}]}).field
*/
async function extractRenderFields(vueFile: string, mode: 'list' | 'form'): Promise<string[]> {
const src = await fs.readFile(vueFile, 'utf-8')
const { descriptor } = parse(src)
const ss = descriptor.scriptSetup?.content || ''
if (mode === 'list') {
// 找 columns 数组里的 dataIndex
// 匹配 const columns: ... = [ ... ] 块
const m = ss.match(/const\s+columns[\s\S]*?\n\]/)
if (!m) return []
const fields: string[] = []
const re = /dataIndex:\s*['"]([^'"]+)['"]/g
let mm
while ((mm = re.exec(m[0])) !== null) fields.push(mm[1])
return fields
} else {
// mode='form': 找 schemas 数组里的 field
const m = ss.match(/schemas:\s*\[[\s\S]*?\n\s*\]/)
if (!m) return []
const fields: string[] = []
const re = /field:\s*['"]([^'"]+)['"]/g
let mm
while ((mm = re.exec(m[0])) !== null) fields.push(mm[1])
return fields
}
}
// ============================================================================
// Markdown report
// ============================================================================
function renderMarkdownReport(r: {
module: string
totalPages: number
pass: number
fail: number
missingFields: string[]
results: RenderCheckResult[]
}): string {
const lines: string[] = []
lines.push(`# 源码渲染验证报告 (${r.module})`)
lines.push('')
lines.push(`> 替代浏览器验证: 读 web 端 .vue 渲染契约 + 调 API, 检查字段完整性 (~2s 完成)`)
lines.push('')
lines.push(`- module: \`${r.module}\``)
lines.push(`- 通过: **${r.pass}/${r.totalPages}**`)
lines.push(`- 失败: **${r.fail}**`)
if (r.missingFields.length) lines.push(`- 缺字段: ${r.missingFields.map(f => `\`${f}\``).join(', ')}`)
lines.push('')
lines.push(`## 详情`)
lines.push('')
lines.push(`| Page | Status | 渲染字段 | API 字段 | 缺 | vue 源 |`)
lines.push(`|------|--------|---------|---------|----|-------|`)
for (const r2 of r.results) {
lines.push(`| ${r2.page} | ${r2.status === 'PASS' ? '✅ PASS' : '❌ FAIL'} | ${r2.renderFields.length} | ${r2.apiFields.length} | ${r2.missing.length ? r2.missing.map(f => `\`${f}\``).join(', ') : '—'} | \`${r2.sourceFile}\` |`)
}
lines.push('')
lines.push(`## 各页面字段对比`)
lines.push('')
for (const r2 of r.results) {
lines.push(`### ${r2.page} (${r2.status})`)
lines.push('')
lines.push(`- vue 源: \`${r2.sourceFile}\``)
lines.push(`- 渲染字段 (${r2.renderFields.length}): ${r2.renderFields.map(f => `\`${f}\``).join(', ')}`)
lines.push(`- API 字段 (${r2.apiFields.length}): ${r2.apiFields.map(f => `\`${f}\``).join(', ')}`)
if (r2.missing.length) {
lines.push(`- **缺字段**: ${r2.missing.map(f => `\`${f}\``).join(', ')} ← 浏览器渲染会缺这列 / 表单编辑会缺这字段`)
}
if (r2.extra.length) {
lines.push(`- 多余字段 (${r2.extra.length}, info): ${r2.extra.map(f => `\`${f}\``).join(', ')}`)
}
lines.push('')
}
lines.push(`## 通过条件`)
lines.push('')
lines.push(`- exit 0 (PASS): 所有页面 vue 渲染字段 ⊆ API 字段`)
lines.push(`- exit 1 (FAIL): 有页面缺字段 (FAIL=${r.fail})`)
lines.push('')
lines.push(`> 浏览器层验证 (vmodel bind / 控件渲染) 仍需 ssw-e2e-test. \`dacli test render\` 验证字段层完整性, 不查 JS 运行时 bug.`)
return lines.join('\n')
}