feat(v0.11+): dacli test generate (覆盖 API 测不到的 vmodel bind bug)
用户拍板 (2026-06-25): 'dacli test 不能覆盖的场景, 研究一下能不能尽可能覆盖' 新增 src/commands/test/generate.ts: 生成浏览器 E2E playwright bash 脚本 - 读 form schema 推导必填字段 (v0.11+ 防御: 填所有 user field, 不仅 required — dacli form create v0.11+ 会丢 required=true 属性 D-13 buildFormData 简化导致) - 3 策略填充: input/textarea, userSelect (dropdown), datePicker - 自动登录 + goto + click 新增 + fill + save + 等行数变化 + 验证 - 输出可执行 chmod +x 脚本, 用户跑 `bash <script>` 即可 - 替代旧 gen.ts stub (P1 stub, 重写为实用工具) 覆盖扩展: - 之前 test 只测 API 层 (run + check) - 现在 generate 准备浏览器层 (用户手动跑, 覆盖 vmodel bind 渲染) - 3 子命令完整覆盖尽可能多场景: run(API) + check(schema) + generate(浏览器) 设计原则 (沉淀自 tdd10): - 浏览器层 E2E 仍是可选 (v0.11+ 保留 ssw-e2e-test), 但 generate 让 AI 一键生成 - dacli test 不知道 browser eval 的语法细节 (page 在 global), 所以脚本是 AI 起点, 用户需微调 - 输出后用户加 1-2 行 fix 即用 (v0.11+ 主功能已就绪) 替换 src/commands/test/gen.ts (旧 P1 stub) → 新 generate.ts .gitignore: 加 .playwright-cli/ (playwright CLI 缓存不入 git)
This commit is contained in:
1 parent
56879227ab
commit
7d50bb4572
4 files changed
+251
-74
No files matched your search
@@ -16,3 +16,4 @@ src/data/*.json
|
||||
|
||||
# dacli codegen 输出 (form codegen --out 默认 ./generated/, 不入库)
|
||||
generated/
|
||||
.playwright-cli/
|
||||
@@ -1,60 +0,0 @@
|
||||
/**
|
||||
* commands/testcase/gen.ts — 生成测试脚本 (P1, 暂 stub)
|
||||
*
|
||||
* 设计: 从 form schema 生成可重用的 shell/curl 脚本, 用户可手动执行.
|
||||
* 当前为 stub, 仅 print "TODO" + 列出设计. 后续实现:
|
||||
* 1. 读 formData.fields + tables
|
||||
* 2. 推导 sample data (复用 run.ts 的 buildSampleData)
|
||||
* 3. 输出 shell 脚本 (.sh):
|
||||
* - POST create + capture id
|
||||
* - GET info + jq assert
|
||||
* - PUT update + jq assert
|
||||
* - DELETE cleanup
|
||||
* 4. 输出 pytest/python 脚本 (.py) 备用
|
||||
*/
|
||||
import { Command } from 'commander'
|
||||
import { installAiHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
|
||||
interface GenOpts {
|
||||
formId: string
|
||||
output?: string
|
||||
format?: 'sh' | 'py'
|
||||
}
|
||||
|
||||
export function buildTestGenCommand(): Command {
|
||||
const cmd = new Command('gen')
|
||||
.description('从 form schema 生成可重用的测试脚本 (P1 stub)')
|
||||
.requiredOption('--formId <id>', '目标 form id')
|
||||
.option('--output <file>', '输出脚本路径 (默认 stdout)')
|
||||
.option('--format <sh|py>', '输出格式 (默认 sh)', 'sh')
|
||||
.action(async (opts: GenOpts) => {
|
||||
log.warn('testcase gen 暂为 stub (P1, 设计中).')
|
||||
log.info('计划:')
|
||||
log.info(' 1. 读 form schema 推导 sample data')
|
||||
log.info(' 2. 输出 shell 脚本 (POST/GET/PUT/DELETE + jq assert)')
|
||||
log.info(' 3. 或输出 python 脚本 (pytest 兼容)')
|
||||
log.info('参考: testcase/run.ts 已实现核心逻辑, 可复用 buildSampleData()')
|
||||
log.info('')
|
||||
log.info(`参数: formId=${opts.formId} format=${opts.format} output=${opts.output || 'stdout'}`)
|
||||
})
|
||||
|
||||
installAiHelpHook(cmd, {
|
||||
purpose: '从 form schema 生成可重用的测试脚本 (P1 stub, 设计中)',
|
||||
required: { '--formId': '目标 form id' },
|
||||
optional: {
|
||||
'--output': '输出脚本路径',
|
||||
'--format': 'sh / py',
|
||||
},
|
||||
example: [
|
||||
'dacli testcase gen --formId=839877227762942789',
|
||||
'dacli testcase gen --formId=839877227762942789 --output=/tmp/test.sh --format=sh',
|
||||
],
|
||||
source: { api: '读取 form schema → 输出可执行 shell/python 脚本' },
|
||||
notes: [
|
||||
'**P1 stub** (2026-06-25): 复用 `dacli testcase run` 的 buildSampleData 逻辑',
|
||||
'**vs testcase/run**: run 是直接调 API + 报告. gen 是生成可复用脚本 (用户保存 + CI 集成)',
|
||||
],
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
/**
|
||||
* commands/test/generate.ts — 生成浏览器 E2E 脚本 (覆盖 API 测不到的 vmodel bind)
|
||||
*
|
||||
* 思路:
|
||||
* - 读 form schema (formData + tables)
|
||||
* - 推导必填字段 + sample data (复用 buildSampleData)
|
||||
* - 输出 playwright bash 脚本:
|
||||
* 1. login
|
||||
* 2. goto /jnpf_app_{appCode}/model/{enCode}
|
||||
* 3. click 新增
|
||||
* 4. fillByLabel 每个必填字段
|
||||
* 5. saveModal
|
||||
* 6. waitRowCountChange (+1)
|
||||
* 7. 验证: list 含新数据
|
||||
* - 输出后用户运行 `playwright -s=tddXX -e <script>` 即可
|
||||
*
|
||||
* 沉淀自 tdd10 实战: dacli API 测只验 API 层, 浏览器 vmodel bind 漏数据问题
|
||||
* 必须用真实浏览器 E2E 才能查. 此命令一键生成测试脚本.
|
||||
*/
|
||||
import { Command } from 'commander'
|
||||
import { JnpfClient } from '../../core/client.ts'
|
||||
import { installAiHelpHook } from '../../core/help.ts'
|
||||
import { log } from '../../core/log.ts'
|
||||
import * as fs from 'node:fs/promises'
|
||||
|
||||
interface GenOpts {
|
||||
formId: string
|
||||
output?: string
|
||||
appCode?: string
|
||||
}
|
||||
|
||||
export function buildTestGenerateCommand(): Command {
|
||||
const cmd = new Command('generate')
|
||||
.description('生成浏览器 E2E 脚本 (覆盖 API 测不到的 vmodel bind / 渲染问题)')
|
||||
.requiredOption('--formId <id>', '目标 form id')
|
||||
.option('--output <file>', '输出脚本路径 (默认 stdout)')
|
||||
.option('--appCode <code>', '应用编码 (默认从 token.json 读)')
|
||||
.action(async (opts: GenOpts) => {
|
||||
const c = await JnpfClient.fromToken()
|
||||
const appCode = opts.appCode || (await import('../../core/config.ts')).loadToken()?.appCode || 'tddXX'
|
||||
|
||||
const schemaR = (await c.get(`/visualdev/Base/${opts.formId}`)) as {
|
||||
code: number
|
||||
data: { enCode: string; fullName: string; formData: string }
|
||||
}
|
||||
if (schemaR.code !== 200) {
|
||||
log.error(`拉 form 失败: ${schemaR.code}`)
|
||||
process.exit(1)
|
||||
}
|
||||
const enCode = schemaR.data.enCode
|
||||
const formData = JSON.parse(schemaR.data.formData || '{}')
|
||||
const fields = formData.fields || []
|
||||
// ⚠️ dacli form create v0.11+ 会丢 required=true 属性 (D-13 buildFormData 简化)
|
||||
// 防御: 填所有 user field, 不仅 required. 防止漏数据 bug.
|
||||
const targetFields = fields.filter((f: { __vModel__?: string; __config__?: { jnpfKey?: string; required?: boolean } }) => {
|
||||
const key = f.__config__?.jnpfKey
|
||||
if (!key) return false
|
||||
if (['createUser', 'createTime', 'modifyUser', 'modifyTime', 'currOrganize', 'currPosition', 'billRule'].includes(key)) return false
|
||||
if (['uploadImg', 'uploadFz', 'uploadFile'].includes(key)) return false
|
||||
return true
|
||||
})
|
||||
|
||||
// 推导必填字段 sample
|
||||
const sample = buildSampleData(fields)
|
||||
|
||||
const script = renderBashScript({
|
||||
formId: opts.formId,
|
||||
appCode,
|
||||
enCode,
|
||||
targetFields: targetFields.map((f: { __config__?: { label?: string }; __vModel__?: string }) => ({
|
||||
label: f.__config__?.label || 'unknown',
|
||||
vmodel: f.__vModel__ || '',
|
||||
sample: sample[f.__vModel__ || ''] || 'test_value',
|
||||
})),
|
||||
})
|
||||
|
||||
if (opts.output) {
|
||||
await fs.writeFile(opts.output, script, 'utf-8')
|
||||
await fs.chmod(opts.output, 0o755)
|
||||
log.ok(`脚本生成: ${opts.output} (${targetFields.length} 字段, ${script.length} 字节)`)
|
||||
} else {
|
||||
console.log(script)
|
||||
}
|
||||
})
|
||||
|
||||
installAiHelpHook(cmd, {
|
||||
purpose: '生成浏览器 E2E 脚本 (playwright bash, 覆盖 vmodel bind bug)',
|
||||
required: { '--formId': '目标 form id' },
|
||||
optional: {
|
||||
'--output': '输出脚本路径 (默认 stdout)',
|
||||
'--appCode': '应用编码 (默认从 token.json 读)',
|
||||
},
|
||||
example: [
|
||||
'dacli test generate --formId=839877227762942789 --output=/tmp/tdd10-e2e.sh',
|
||||
'dacli test generate --formId=839877227762942789 --appCode=tdd10 --output=/tmp/tdd10-e2e.sh',
|
||||
'sh /tmp/tdd10-e2e.sh # run',
|
||||
],
|
||||
source: { api: 'playwright -s={session} open http://... + eval 序列' },
|
||||
notes: [
|
||||
'**v0.11+ NEW** (2026-06-25): 沉淀自 tdd10 — 浏览器只 bind 2 字段 bug',
|
||||
'**为何需要**: `dacli test run` 测 API 层, 但 JNPF runtime 的 vmodel bind (OnlineSwapDataUtils.swapDatetime:435) 是浏览器层行为, 需真实浏览器',
|
||||
'**生成后**: `playwright -s=tddXX -f <script>` 或 `bash <script>` (内置 eval 序列)',
|
||||
'**vs test/run**: run 调 API, generate 准备浏览器测试. 两者互补.',
|
||||
],
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
function buildSampleData(fields: Array<{ __vModel__?: string; __config__?: { jnpfKey?: string; options?: Array<{ value: string }> } }>): Record<string, unknown> {
|
||||
const sample: Record<string, unknown> = {}
|
||||
const sysKeys = new Set(['createUser', 'createTime', 'modifyUser', 'modifyTime', 'currOrganize', 'currPosition', 'billRule'])
|
||||
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
|
||||
if (['input', 'textarea'].includes(key)) {
|
||||
sample[vmodel] = `test_${vmodel}_${Date.now().toString().slice(-6)}`
|
||||
continue
|
||||
}
|
||||
if (['inputNumber', 'numInput', 'calculate'].includes(key)) {
|
||||
sample[vmodel] = 100
|
||||
continue
|
||||
}
|
||||
if (['datePicker', 'timePicker'].includes(key)) {
|
||||
sample[vmodel] = new Date().toISOString().slice(0, 10)
|
||||
continue
|
||||
}
|
||||
if (key === 'select') {
|
||||
const opts = cfg.options || []
|
||||
sample[vmodel] = opts[0]?.value || '1'
|
||||
continue
|
||||
}
|
||||
if (key === 'userSelect' || key === 'organizeSelect' || key === 'posSelect') {
|
||||
sample[vmodel] = '管理员'
|
||||
continue
|
||||
}
|
||||
}
|
||||
return sample
|
||||
}
|
||||
|
||||
function renderBashScript(p: {
|
||||
formId: string
|
||||
appCode: string
|
||||
enCode: string
|
||||
targetFields: Array<{ label: string; vmodel: string; sample: unknown }>
|
||||
}): string {
|
||||
const fills = p.targetFields
|
||||
.map(f => {
|
||||
return `playwright -s=\$SESSION eval "async () => {
|
||||
const label = page.locator('text=\\"${f.label}\\"').first();
|
||||
const formItem = label.locator('xpath=ancestor::div[contains(@class, \\"ant-form-item\\")]');
|
||||
let inp = formItem.locator('input, textarea').first();
|
||||
if (await inp.count() > 0) { await inp.fill('${f.sample}'); return; }
|
||||
const select = formItem.locator('.ant-select').first();
|
||||
if (await select.count() > 0) {
|
||||
await select.click();
|
||||
await page.waitForTimeout(500);
|
||||
const opt = page.locator('.ant-select-item-option').first();
|
||||
if (await opt.count() > 0) await opt.click();
|
||||
return;
|
||||
}
|
||||
const date = formItem.locator('.ant-picker input').first();
|
||||
if (await date.count() > 0) { await date.fill('${f.sample}'); return; }
|
||||
console.warn('未找到字段: ${f.label} (vmodel=${f.vmodel})');
|
||||
}"`
|
||||
})
|
||||
.join('\n\n')
|
||||
|
||||
return `#!/bin/bash
|
||||
# Auto-generated by dacli test generate --formId=${p.formId}
|
||||
# 跑前: 1) dacli app login --appCode=${p.appCode} 2) playwright install chromium
|
||||
set -e
|
||||
|
||||
SESSION="tddXX"
|
||||
APP_CODE="${p.appCode}"
|
||||
ENCODE="${p.enCode}"
|
||||
FORM_ID="${p.formId}"
|
||||
URL="http://nginx/jnpf_app_\${APP_CODE}/model/\${ENCODE}"
|
||||
|
||||
# 1. 打开浏览器
|
||||
playwright -s=\$SESSION open "\$URL"
|
||||
|
||||
# 2. 登录 (如未登录)
|
||||
playwright -s=\$SESSION eval "async () => {
|
||||
if (page.url().includes('/login')) {
|
||||
await page.fill('input[placeholder=\\"请输入账号\\"]', 'admin');
|
||||
await page.fill('input[placeholder=\\"请输入密码\\"]', '123456');
|
||||
await page.locator('button:has-text(\\"登 录\\")').first().click();
|
||||
await page.waitForURL(/\\\\/home/, { timeout: 10000 });
|
||||
}
|
||||
}"
|
||||
|
||||
# 3. 等列表加载
|
||||
sleep 2
|
||||
|
||||
# 4. 记初始行数
|
||||
INITIAL=\$(playwright -s=\$SESSION eval "() => document.querySelectorAll('.vxe-body--row').length" 2>/dev/null || echo 0)
|
||||
|
||||
# 5. 点击新增
|
||||
playwright -s=\$SESSION eval "async () => {
|
||||
const btn = page.locator('button:has-text(\\"新增\\")').first();
|
||||
if (await btn.count() === 0) throw new Error('新增按钮未找到 (BS-52 FAIL)');
|
||||
await btn.click();
|
||||
await page.waitForSelector('.ant-modal', { timeout: 5000 });
|
||||
}"
|
||||
|
||||
# 6. 填必填字段
|
||||
${fills}
|
||||
|
||||
# 7. 保存
|
||||
playwright -s=\$SESSION eval "
|
||||
const btn = page.locator('.ant-modal button:has-text(\\"确定\\")').first();
|
||||
if (await btn.count() === 0) throw new Error('保存按钮未找到');
|
||||
await btn.click();
|
||||
await page.waitForSelector('.ant-modal', { state: 'hidden', timeout: 10000 });
|
||||
"
|
||||
|
||||
# 8. 等行数变化
|
||||
sleep 2
|
||||
NEW=\$(playwright -s=\$SESSION eval "() => document.querySelectorAll('.vxe-body--row').length" 2>/dev/null || echo 0)
|
||||
|
||||
# 9. 验证
|
||||
if [ "\$NEW" -gt "\$INITIAL" ]; then
|
||||
echo "✓ 浏览器 E2E PASS: 行数 \$INITIAL → \$NEW"
|
||||
else
|
||||
echo "✗ 浏览器 E2E FAIL: 行数没增加 (\$INITIAL → \$NEW). 可能 vmodel bind bug."
|
||||
echo "→ 查后端日志: dacli log exception --keyword=\$ENCODE --limit=5"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 10. 清理
|
||||
playwright -s=\$SESSION close
|
||||
`
|
||||
}
|
||||
+13
-14
@@ -1,30 +1,29 @@
|
||||
/**
|
||||
* commands/test/index.ts — test 父命令 (v0.11+ 新命名, 替代 testcase)
|
||||
*
|
||||
* 命名说明:
|
||||
* - 主命令: `dacli test` (短, 对齐 npm/pytest 惯例)
|
||||
* - Alias: `dacli testcase` 保留兼容 (早期 v0.11+ 命名为 testcase, 后简化)
|
||||
* 命名: 主命令 `dacli test` (短, 对齐 npm/pytest 惯例). 早期 v0.11+ 命名 testcase, 用户拍板简化为 test.
|
||||
*
|
||||
* 核心思路:
|
||||
* 从 form schema 自动生成 API 测试脚本 (POST create / GET list / PUT update / DELETE),
|
||||
* 跑测试 + BS-52 自检 + 输出 report.md. 替代浏览器层测试的 API 部分.
|
||||
* 3 子命令覆盖:
|
||||
* - run 跑 form API 测试 (POST/GET/PUT/DELETE, ~5s, 不需浏览器)
|
||||
* - check schema BS-52 + 6 盲点自检 (~1s, 不调 API)
|
||||
* - generate 生成浏览器 E2E 脚本 (playwright bash, 覆盖 vmodel bind bug)
|
||||
*
|
||||
* 设计原则 (用户拍板 2026-06-25):
|
||||
* - 读取 web/** 渲染源码 + form schema → 推导出 sample data + API 序列
|
||||
* - 不需浏览器, 跑得快 (curl 直调 JNPF REST)
|
||||
* - 浏览器层 E2E 仍保留作为可选 visual regression (用户手动跑)
|
||||
* - 输出可重跑 (幂等): delete + create 测试每次都从 0 开始
|
||||
* 覆盖 vs 浏览器测试 (v0.11+ 闭环):
|
||||
* - API 层: run 完全覆盖 (POST/GET/PUT/DELETE)
|
||||
* - Schema 层: check 覆盖 (BS-52, 6 盲点)
|
||||
* - 浏览器层: generate 生成脚本, 用户手动跑
|
||||
* - 浏览器层手动: 仍保留 ssw-e2e-test 作为 visual regression
|
||||
*/
|
||||
import { Command } from 'commander'
|
||||
import { buildTestRunCommand } from './run.ts'
|
||||
import { buildTestGenCommand } from './gen.ts'
|
||||
import { buildTestGenerateCommand } from './generate.ts'
|
||||
import { buildTestCheckCommand } from './check.ts'
|
||||
|
||||
export function buildTestCommand(): Command {
|
||||
const cmd = new Command('test')
|
||||
.description('API 测试能力 (v0.11+ NEW) — 从 form schema 自动生成 + 跑 API 测试 + BS-52 自检, 不需浏览器')
|
||||
.description('API 测试能力 (v0.11+ NEW) — run API 测试 + check schema 自检 + generate 浏览器脚本, 3 子命令覆盖尽可能多的测试场景')
|
||||
cmd.addCommand(buildTestRunCommand())
|
||||
cmd.addCommand(buildTestGenCommand())
|
||||
cmd.addCommand(buildTestGenerateCommand())
|
||||
cmd.addCommand(buildTestCheckCommand())
|
||||
return cmd
|
||||
}
|
||||
Reference in new issue
Block a user