667 lines
26 KiB
TypeScript
667 lines
26 KiB
TypeScript
/**
|
|
* tests/unit/form_create_json_stdout.test.ts
|
|
*
|
|
* 命令级集成测试 (2026-07-22 eventhub blocker 阶段 5 修复):
|
|
*
|
|
* 修复前 bug:
|
|
* - form/create.ts:1446-1480 手工 CommandLog 块 (saveCommandLog + formatOneLineSummary
|
|
* + "✓ ..." + " 详情: dacli log last") 未判断 opts.json
|
|
* - 即便 action 主体已经 `if (opts.json) printJson({...})` 在 1418, 后续 1446-1480
|
|
* 的"详情"块又 process.stdout.write 拼了一份人类摘要
|
|
* - 运行时 stdout 是 JSON 后面跟 ✓ .../详情: dacli log last, JSON.parse 整段失败
|
|
*
|
|
* 修复后契约:
|
|
* - --json 路径: opts.json=true 时, 1446-1480 块应:
|
|
* * saveCommandLog 落 CommandLog (供 dacli log last 查询) — 保留
|
|
* * log.discard() 丢掉 buffered 过程日志 — 防止泄漏
|
|
* * 不输出人类摘要 (✓ ...) 与 "详情: dacli log last" — 关键契约
|
|
* - 非 --json: 行为保持不变 (default 摘要 + "详情", --verbose 走 log.info)
|
|
* - 整段 stdout 仅 1 行 JSON (含末尾 \n); JSON.parse 严格合法
|
|
*
|
|
* 测试策略:
|
|
* - mock JnpfClient + log + webapi.dataModel + webapi.visualDev + logfile
|
|
* - mock SSW 成功 (postJson /ssw/ai/infer-fields 返 200 + enCode/fullName/aiModelList)
|
|
* - mock create 成功 (loadVisualDev.create 返 200)
|
|
* - mock getVisualDevList 返 [{ id: 'form-id', enCode }]
|
|
* - mock release 成功 (loadVisualDev.release 不抛)
|
|
* - 收集 process.stdout.write 全段 → 验证只有 1 行 JSON
|
|
* - 反向断言: 不含 ✓, 不含 "详情: dacli log last", 不含 `printOneLineSummary` 内容
|
|
* - 二次断言非 json 行为: 不传 --json 时仍然打印人类摘要 (回归保险)
|
|
*
|
|
* 2026-07-22 eventhub blocker 阶段 6 (修复 2): --table 路径 tables/formData.tableName 契约
|
|
* 修复前 bug:
|
|
* - form create --table=eventaudit 走 --ai 路径 (经过 web buildFormData → opts.__aiBuildFormData)
|
|
* - create.ts:984 对无 --tables 永远 tables=[] 兜底, 后端 jnpf .../FlowFormDataUtil.java:831
|
|
* 查 typeId='1' 找主表 → 找不到 → 抛 MsgCode.COD001 ("集合条件过滤获得目标为空")
|
|
* - create.ts:730-733 把 formData.tableName 强制设为 opts.enCode (eventAudit) 而非现有物理表
|
|
* opts.table (eventaudit), 表名不一致
|
|
* 修复后契约:
|
|
* - opts.table 存在且无 opts.tables 时, 按 web formDesign Form.vue:285-305 item 构造单主表:
|
|
* { relationField:'', relationTable:'', table:opts.table, tableName:opts.table,
|
|
* tableField:'', typeId:'1', fields:dmFields }
|
|
* - formData.tableName 优先用 opts.table (绑现有物理表), --ai 路径保留 opts.enCode 派生
|
|
* - formData.fields[*].__config__.tableName 同理 (绑 opts.table)
|
|
*
|
|
* 关联:
|
|
* - docs/decisions/0016-eventhub-blocker-fixes-design.md §3.2 (JSON 输出契约)
|
|
* - tests/unit/dm_create_json_stdout.test.ts (dm 等价测试, 走 printCommandEnd 已修)
|
|
* - tests/unit/output_filter.test.ts (printCommandEnd 单测)
|
|
* - tests/unit/form_table_ssw_fail.test.ts (SSW 失败路径, 互补)
|
|
* - web/apps/.../formDesign/Form.vue:260-305 (onTableSelect 权威 item 构造)
|
|
*/
|
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
|
|
|
// 用 vi.hoisted 共享 mock state
|
|
const mocks = vi.hoisted(() => ({
|
|
fromToken: vi.fn(),
|
|
initDmWebapi: vi.fn(),
|
|
initVisualDevWebapi: vi.fn(),
|
|
getDataModelFieldList: vi.fn(),
|
|
getDataModelList: vi.fn(),
|
|
create: vi.fn(),
|
|
release: vi.fn(),
|
|
getVisualDevList: vi.fn(),
|
|
postJson: vi.fn(),
|
|
saveCommandLog: vi.fn(() => '/tmp/test-log.json'),
|
|
formatOneLineSummary: vi.fn(() => '✓ eventSignup (id=form-id1...) [0.5s]'),
|
|
// 收集 stdout
|
|
stdoutChunks: [] as string[],
|
|
stderrChunks: [] as string[],
|
|
exit: vi.fn(),
|
|
// 收集 log.* 调用
|
|
logInfo: [] as string[],
|
|
logOk: [] as string[],
|
|
logWarn: [] as string[],
|
|
logError: [] as string[],
|
|
logDim: [] as string[],
|
|
logRaw: [] as string[],
|
|
logDebug: [] as string[],
|
|
logFlush: 0,
|
|
logDiscard: 0,
|
|
validateFormCreate: vi.fn(() => ({
|
|
ok: true,
|
|
steps: [
|
|
{ ok: true, step: 0, stepName: '基础信息', errors: [] },
|
|
{ ok: true, step: 1, stepName: '表单字段', errors: [] },
|
|
{ ok: true, step: 2, stepName: '列表设计', errors: [] },
|
|
],
|
|
})),
|
|
}))
|
|
|
|
vi.mock('../../src/webapi/dict.ts', () => ({
|
|
initWebapi: vi.fn().mockResolvedValue(undefined),
|
|
loadDict: {
|
|
getDictionaryAll: vi.fn().mockResolvedValue({
|
|
data: {
|
|
list: [
|
|
{
|
|
id: 'business-type-id',
|
|
enCode: 'businessType',
|
|
dictionaryList: [
|
|
{ id: 'cat-test-id', enCode: 'testCat', fullName: '测试分类' },
|
|
],
|
|
children: [
|
|
{ id: 'cat-test-id', enCode: 'testCat', fullName: '测试分类' },
|
|
],
|
|
},
|
|
],
|
|
},
|
|
}),
|
|
},
|
|
}))
|
|
|
|
vi.mock('../../src/core/client.ts', () => ({
|
|
JnpfClient: {
|
|
fromToken: (...args: unknown[]) => mocks.fromToken(...args),
|
|
},
|
|
}))
|
|
|
|
vi.mock('../../src/core/log.ts', () => ({
|
|
log: {
|
|
setQuiet: vi.fn(),
|
|
setJsonMode: vi.fn(),
|
|
isJsonMode: vi.fn(),
|
|
isQuiet: vi.fn(() => true),
|
|
flush: vi.fn(() => { mocks.logFlush += 1 }),
|
|
discard: vi.fn(() => { mocks.logDiscard += 1 }),
|
|
info: (...args: unknown[]) => { mocks.logInfo.push(args.map(String).join(' ')) },
|
|
warn: (...args: unknown[]) => { mocks.logWarn.push(args.map(String).join(' ')) },
|
|
error: (...args: unknown[]) => { mocks.logError.push(args.map(String).join(' ')) },
|
|
ok: (...args: unknown[]) => { mocks.logOk.push(args.map(String).join(' ')) },
|
|
dim: (...args: unknown[]) => { mocks.logDim.push(args.map(String).join(' ')) },
|
|
raw: (...args: unknown[]) => { mocks.logRaw.push(args.map(String).join(' ')) },
|
|
debug: (...args: unknown[]) => { mocks.logDebug.push(args.map(String).join(' ')) },
|
|
},
|
|
printJson: vi.fn((v: unknown) => {
|
|
// 镜像 printJson: 直写 stdout 一行 JSON (末尾 \n)
|
|
process.stdout.write(JSON.stringify(v) + '\n')
|
|
}),
|
|
}))
|
|
|
|
vi.mock('../../src/core/logfile.ts', () => ({
|
|
saveCommandLog: mocks.saveCommandLog,
|
|
formatOneLineSummary: mocks.formatOneLineSummary,
|
|
// CommandLog / FixEntry types — 不参与运行, 但 import 路径需要覆盖
|
|
}))
|
|
|
|
vi.mock('../../src/webapi/dataModel.ts', () => ({
|
|
initWebapi: mocks.initDmWebapi,
|
|
loadDataModel: {
|
|
getDataModelFieldList: mocks.getDataModelFieldList,
|
|
getDataModelList: mocks.getDataModelList,
|
|
},
|
|
}))
|
|
|
|
vi.mock('../../src/webapi/visualDev.ts', () => ({
|
|
initWebapi: mocks.initVisualDevWebapi,
|
|
loadVisualDev: {
|
|
create: mocks.create,
|
|
release: mocks.release,
|
|
getVisualDevList: mocks.getVisualDevList,
|
|
},
|
|
}))
|
|
|
|
// Mock form/_validate.ts — step machine 校验 (避免真实校验 VS-CATEGORY/VS402)
|
|
vi.mock('../../src/commands/form/_validate.ts', () => ({
|
|
validateFormCreate: mocks.validateFormCreate,
|
|
}))
|
|
|
|
// Mock process.exit
|
|
vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
|
|
mocks.exit(code)
|
|
}) as never)
|
|
|
|
// 收集 stdout 全段
|
|
let originalWrite: typeof process.stdout.write
|
|
let originalErrWrite: typeof process.stderr.write
|
|
|
|
beforeEach(() => {
|
|
mocks.stdoutChunks = []
|
|
mocks.stderrChunks = []
|
|
mocks.exit.mockReset()
|
|
mocks.saveCommandLog.mockClear()
|
|
mocks.formatOneLineSummary.mockClear()
|
|
mocks.logInfo = []
|
|
mocks.logOk = []
|
|
mocks.logWarn = []
|
|
mocks.logError = []
|
|
mocks.logDim = []
|
|
mocks.logRaw = []
|
|
mocks.logDebug = []
|
|
mocks.logFlush = 0
|
|
mocks.logDiscard = 0
|
|
mocks.create.mockReset()
|
|
mocks.release.mockReset()
|
|
mocks.getVisualDevList.mockReset()
|
|
mocks.getDataModelFieldList.mockReset()
|
|
mocks.getDataModelList.mockReset()
|
|
mocks.initDmWebapi.mockReset()
|
|
mocks.initVisualDevWebapi.mockReset()
|
|
mocks.postJson.mockReset()
|
|
mocks.fromToken.mockReset()
|
|
|
|
originalWrite = process.stdout.write.bind(process.stdout)
|
|
originalErrWrite = process.stderr.write.bind(process.stderr)
|
|
process.stdout.write = ((chunk: string | Uint8Array): boolean => {
|
|
mocks.stdoutChunks.push(typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk))
|
|
return true
|
|
}) as typeof process.stdout.write
|
|
process.stderr.write = ((chunk: string | Uint8Array): boolean => {
|
|
mocks.stderrChunks.push(typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk))
|
|
return true
|
|
}) as typeof process.stderr.write
|
|
|
|
// 默认 SSW 成功: 返 enCode/fullName/aiModelList
|
|
// 注意: opts.table 路径走 postJson('/ssw/ai/infer-fields', ...)
|
|
mocks.postJson.mockImplementation(async (path: string, body: unknown) => {
|
|
if (typeof path === 'string' && path.includes('/ssw/ai/infer-fields')) {
|
|
return {
|
|
code: 200,
|
|
msg: 'ok',
|
|
data: {
|
|
enCode: 'eventSignup',
|
|
fullName: '活动报名',
|
|
aiModelList: [
|
|
{
|
|
fields: [
|
|
{
|
|
fieldName: 'f_name',
|
|
fieldComponent: 'input',
|
|
__list__: true,
|
|
__form__: true,
|
|
__query__: false,
|
|
},
|
|
],
|
|
},
|
|
],
|
|
},
|
|
}
|
|
}
|
|
return { code: 404, msg: 'not mocked', data: null }
|
|
})
|
|
|
|
// 默认 client: 提供 postJson (SSW 路径) + resolveDbLinkId
|
|
mocks.fromToken.mockResolvedValue({
|
|
appCode: 'eventhub',
|
|
dbLinkId: 'db-1',
|
|
baseUrl: 'http://test',
|
|
account: 'admin',
|
|
password: 'p',
|
|
postJson: (...args: unknown[]) => mocks.postJson(...args),
|
|
get: vi.fn(),
|
|
resolveDbLinkId: (v?: string) => v || 'db-1',
|
|
})
|
|
|
|
mocks.initDmWebapi.mockResolvedValue(undefined)
|
|
mocks.initVisualDevWebapi.mockResolvedValue(undefined)
|
|
mocks.getDataModelFieldList.mockResolvedValue([
|
|
{ field: 'f_name', fieldName: '名称', dataType: 'varchar', dataLength: '100' },
|
|
])
|
|
mocks.getDataModelList.mockResolvedValue({
|
|
data: { list: [{ table: 'event_signup', tableFieldList: [{}, {}] }] },
|
|
})
|
|
mocks.create.mockResolvedValue({ code: 200, msg: 'ok', data: { id: 'form-id-1' } })
|
|
mocks.getVisualDevList.mockResolvedValue({
|
|
list: [{ id: 'form-id-1', enCode: 'eventSignup' }],
|
|
})
|
|
mocks.release.mockResolvedValue({ code: 200, msg: 'ok', data: null })
|
|
})
|
|
|
|
afterEach(() => {
|
|
process.stdout.write = originalWrite
|
|
process.stderr.write = originalErrWrite
|
|
})
|
|
|
|
// 注意: import 必须在所有 vi.mock 之后 (hoisting 兼容性)
|
|
import { buildFormCreateCommand } from '../../src/commands/form/create.ts'
|
|
|
|
/**
|
|
* RED 阶段断言契约:
|
|
* - opts.json=true 时, stdout 仅含 1 行 JSON
|
|
* - saveCommandLog 仍被调用 (落 CommandLog, 供 dacli log last 查询)
|
|
* - log.discard() 仍被调用 (防 buffer 泄漏)
|
|
* - process.stdout.write 不应写出 ✓ ... 或 "详情: dacli log last"
|
|
*/
|
|
describe('form create --json: 成功路径 stdout 整段仅 1 行 JSON (eventhub blocker 阶段 5)', () => {
|
|
it('--table + --json: 走 SSW + create + release 成功, stdout 仅 1 行 JSON, 无 ✓ / "详情: dacli log last"', async () => {
|
|
const cmd = buildFormCreateCommand()
|
|
await cmd.parseAsync([
|
|
'node', 'test',
|
|
'--table', 'event_signup',
|
|
'--fullName', '活动报名',
|
|
'--enCode', 'eventSignup',
|
|
'--category', 'cat-test-id',
|
|
'--no-verify',
|
|
'--json',
|
|
])
|
|
|
|
// 1. 整段 stdout 必须能被 JSON.parse
|
|
const allStdout = mocks.stdoutChunks.join('')
|
|
expect(allStdout.length).toBeGreaterThan(0)
|
|
const trimmed = allStdout.trim()
|
|
|
|
// 严格合法 JSON (旧版会被 ✓ .../详情: dacli log last 污染, parse 失败)
|
|
const parsed = JSON.parse(trimmed)
|
|
// shape 校验: 应为 create 成功后 printJson 的 { id, enCode, type, webType }
|
|
expect(parsed).toEqual({
|
|
id: 'form-id-1',
|
|
enCode: 'eventSignup',
|
|
type: 1,
|
|
webType: 2,
|
|
})
|
|
|
|
// 2. 反向断言: stdout 不含人类摘要 / 详情提示
|
|
expect(allStdout).not.toMatch(/✓/)
|
|
expect(allStdout).not.toMatch(/详情: dacli log last/)
|
|
expect(allStdout).not.toMatch(/修正 \d+ 处/)
|
|
expect(allStdout).not.toMatch(/建议 \d+ 项/)
|
|
|
|
// 3. 整段 stdout split 后非空行恰好 1 行
|
|
const lines = allStdout.split('\n').filter((l) => l.trim().length > 0)
|
|
expect(lines.length).toBe(1)
|
|
expect(lines[0]).toBe(trimmed)
|
|
|
|
// 4. L3 CommandLog 仍落 (供 dacli log last 查询) — 不破坏 L3
|
|
expect(mocks.saveCommandLog).toHaveBeenCalledTimes(1)
|
|
const callArgs = mocks.saveCommandLog.mock.calls[0] as unknown as [string, { command: string; result: string }]
|
|
const [appCode, cmdLog] = callArgs
|
|
expect(appCode).toBe('eventhub')
|
|
expect(cmdLog.command).toBe('form create')
|
|
expect(cmdLog.result).toBe('success')
|
|
|
|
// 5. log.discard() 仍被调用 (防 buffer 泄漏, 见 _output_filter.ts:296 注释)
|
|
expect(mocks.logDiscard).toBeGreaterThanOrEqual(1)
|
|
|
|
// 6. formatOneLineSummary 在 json 路径不应走到 stdout
|
|
// (它被 saveCommandLog 内部可能用到, 但 process.stdout 不应有它)
|
|
// 因为 mock formatOneLineSummary 返回字符串含 ✓, 已被上面 expect 拦掉
|
|
})
|
|
|
|
it('非 --json: 默认摘要仍打印 (回归保险, opts.json=false 时不变)', async () => {
|
|
const cmd = buildFormCreateCommand()
|
|
await cmd.parseAsync([
|
|
'node', 'test',
|
|
'--table', 'event_signup',
|
|
'--fullName', '活动报名',
|
|
'--enCode', 'eventSignup',
|
|
'--no-verify',
|
|
// 注意: 不传 --json
|
|
])
|
|
|
|
const allStdout = mocks.stdoutChunks.join('')
|
|
// 回归保险: 默认 (quiet) 路径下应仍打印人类摘要
|
|
// saveCommandLog 仍被调用, 之后 process.stdout.write 拼 '✓ .../详情: dacli log last'
|
|
expect(mocks.saveCommandLog).toHaveBeenCalledTimes(1)
|
|
expect(allStdout).toMatch(/✓/)
|
|
expect(allStdout).toContain('详情: dacli log last')
|
|
// log.discard() 在默认路径也仍被调用
|
|
expect(mocks.logDiscard).toBeGreaterThanOrEqual(1)
|
|
// stdout 不是合法 JSON (因为有 ✓/详情混入)
|
|
expect(() => JSON.parse(allStdout.trim())).toThrow()
|
|
})
|
|
|
|
it('--json 路径不应触发 ctx.fail 或 process.exit(1) — 成功路径', async () => {
|
|
const cmd = buildFormCreateCommand()
|
|
await cmd.parseAsync([
|
|
'node', 'test',
|
|
'--table', 'event_signup',
|
|
'--fullName', '活动报名',
|
|
'--enCode', 'eventSignup',
|
|
'--no-verify',
|
|
'--json',
|
|
])
|
|
|
|
// 成功路径: ctx.fail 不应被调用 (即使 mock 整体 process.exit)
|
|
// form_table_ssw_fail 走 ctx.fail → process.exit(1); 本测试应相反
|
|
expect(mocks.exit).not.toHaveBeenCalledWith(1)
|
|
// 如果有 exit 调用, 应该是 0 (来自 commander 正常结束), 但我们 mock 了, 所以
|
|
// 这里只验证 exit(1) 没被调用
|
|
})
|
|
})
|
|
|
|
/**
|
|
* RED 阶段断言契约 (eventhub blocker 阶段 6 --table 路径 tables/formData.tableName 修复):
|
|
* - 模拟: opts.table='eventaudit' (现有物理表名, ≠ opts.enCode='eventAudit')
|
|
* - 触发: create 调用 + body capture
|
|
* - 断言:
|
|
* * JSON.parse(body.tables) === [{table:opts.table, tableName:opts.table, typeId:'1',
|
|
* relationField:'', relationTable:'', tableField:'', fields:dmFields}]
|
|
* * JSON.parse(body.formData).tableName === opts.table (不是 opts.enCode)
|
|
* * formData.fields[*].__config__.tableName === opts.table (绑物理表)
|
|
* - 反向: 用户显式 --tables 时不被覆盖
|
|
*/
|
|
describe('form create --table: tables payload + formData.tableName 契约 (eventhub blocker 阶段 6)', () => {
|
|
/**
|
|
* 帮助函数: 跑 cmd, 返回传给 loadVisualDev.create 的 body
|
|
*/
|
|
async function runAndCaptureBody(args: string[]): Promise<Record<string, unknown>> {
|
|
const cmd = buildFormCreateCommand()
|
|
await cmd.parseAsync(['node', 'test', ...args])
|
|
// loadVisualDev.create mock 返 {code:200, data:{id:'form-id-1'}}, 必被调用
|
|
expect(mocks.create).toHaveBeenCalledTimes(1)
|
|
return mocks.create.mock.calls[0][0] as Record<string, unknown>
|
|
}
|
|
|
|
it('--table + opts.table !== opts.enCode: tables 是单主表, typeId=1, table=opts.table, fields=dmFields', async () => {
|
|
// appCode 'eventhub', table 'eventaudit', enCode 'eventAudit' (刻意 ≠ table)
|
|
const body = await runAndCaptureBody([
|
|
'--table', 'eventaudit',
|
|
'--fullName', '活动审核',
|
|
'--enCode', 'eventAudit',
|
|
'--no-verify',
|
|
])
|
|
|
|
// body.tables 是字符串 (与 web Form.vue 一致)
|
|
expect(typeof body.tables).toBe('string')
|
|
const tables = JSON.parse(body.tables as string) as Array<Record<string, unknown>>
|
|
expect(Array.isArray(tables)).toBe(true)
|
|
expect(tables.length).toBe(1)
|
|
const main = tables[0] as any
|
|
expect(main.table).toBe('eventaudit') // opts.table
|
|
expect(main.tableName).toBe('eventaudit') // opts.table
|
|
expect(main.typeId).toBe('1') // 主表标识 (Form.vue:288 i==0 ? '1' : '0')
|
|
expect(main.relationField).toBe('') // Form.vue:271-279 全部空
|
|
expect(main.relationTable).toBe('') // i==0 时 relationTable='' (Form.vue:293)
|
|
expect(main.tableField).toBe('') // Form.vue:273/296
|
|
// fields 应等于 dm getDataModelFieldList 返的 list (原始 dm schema, 包含 f_id 等系统字段)
|
|
expect(Array.isArray(main.fields)).toBe(true)
|
|
expect(main.fields.length).toBeGreaterThan(0)
|
|
expect(main.fields[0]).toHaveProperty('field')
|
|
expect(main.fields[0]).toHaveProperty('fieldName')
|
|
})
|
|
|
|
it('--table 路径: formData.tableName === opts.table (绑物理表, 不是 opts.enCode)', async () => {
|
|
const body = await runAndCaptureBody([
|
|
'--table', 'eventaudit',
|
|
'--fullName', '活动审核',
|
|
'--enCode', 'eventAudit',
|
|
'--no-verify',
|
|
])
|
|
|
|
const formData = JSON.parse(body.formData as string) as Record<string, unknown>
|
|
// 关键契约: formData.tableName 必须用物理表名 (opts.table), 不用 enCode
|
|
expect(formData.tableName).toBe('eventaudit')
|
|
expect(formData.tableName).not.toBe('eventAudit') // 反向断言
|
|
})
|
|
|
|
it('--table 路径: formData.fields[*].__config__.tableName === opts.table', async () => {
|
|
const body = await runAndCaptureBody([
|
|
'--table', 'eventaudit',
|
|
'--fullName', '活动审核',
|
|
'--enCode', 'eventAudit',
|
|
'--no-verify',
|
|
])
|
|
|
|
const formData = JSON.parse(body.formData as string) as { fields?: Array<any> }
|
|
expect(Array.isArray(formData.fields)).toBe(true)
|
|
expect(formData.fields!.length).toBeGreaterThan(0)
|
|
// Debug: capture actual tableName values to understand what web buildFormData produces
|
|
const observed = formData.fields!
|
|
.filter((f: any) => f?.__config__)
|
|
.map((f: any) => f.__config__.tableName)
|
|
// web buildFormData defaults tableName to enCode; dacli needs to override to opts.table
|
|
// for --table path. Any non-eventaudit value means fix didn't take.
|
|
const distinct = [...new Set(observed)]
|
|
for (const val of distinct) {
|
|
expect(val).toBe('eventaudit')
|
|
}
|
|
})
|
|
|
|
it('--ai 路径 (无 --table): tables=[], formData.tableName === opts.enCode (不破坏原契约)', async () => {
|
|
// 走 --ai 路径: postJson /visualdev/ai/form (NCPF backend) 触发, 模拟 enCode/fullName/aiModelList
|
|
mocks.postJson.mockImplementation(async (path: string, _body: unknown) => {
|
|
// v0.22+: --ai 路径走 SSW /ssw/ai/build-form (旧 /visualdev/ai/form 已废弃, 保留兼容)
|
|
if (typeof path === 'string' && (path.includes('/ssw/ai/build-form') || path.includes('/visualdev/ai/form'))) {
|
|
return { code: 200, msg: 'ok', data: {
|
|
enCode: 'eventAudit', fullName: '活动审核',
|
|
aiModelList: [{ fields: [{
|
|
fieldName: 'f_name', fieldComponent: 'input',
|
|
__list__: true, __form__: true, __query__: false,
|
|
}] }],
|
|
} }
|
|
}
|
|
return { code: 404, msg: 'not mocked', data: null }
|
|
})
|
|
|
|
const body = await runAndCaptureBody([
|
|
// v0.23+: 短描述 (< 10 字符) 走默认 schema 不调 LLM; 用够长描述确保走真实 LLM 路径
|
|
'--ai', '活动审核管理:活动名称、报名开始时间、报名截止时间、参与人数、备注',
|
|
'--no-verify',
|
|
])
|
|
|
|
// --ai 路径无 --table: tables 应仍 [] (不影响)
|
|
const tables = JSON.parse(body.tables as string) as unknown[]
|
|
expect(tables).toEqual([])
|
|
|
|
// formData.tableName 应按 enCode 派生 (回归保险, --ai 不被破坏)
|
|
const formData = JSON.parse(body.formData as string) as Record<string, unknown>
|
|
expect(formData.tableName).toBe('eventAudit')
|
|
})
|
|
|
|
it('--table 路径: columnData.columnList[*].__config__.tableName === opts.table (HIGH1)', async () => {
|
|
const body = await runAndCaptureBody([
|
|
'--table', 'eventaudit',
|
|
'--fullName', '活动审核',
|
|
'--enCode', 'eventAudit',
|
|
'--no-verify',
|
|
])
|
|
|
|
const columnData = JSON.parse(body.columnData as string) as { columnList?: Array<any> }
|
|
expect(Array.isArray(columnData.columnList)).toBe(true)
|
|
expect(columnData.columnList!.length).toBeGreaterThan(0)
|
|
for (const entry of columnData.columnList!) {
|
|
if (!entry.__config__) continue
|
|
expect(entry.__config__.tableName).toBe('eventaudit')
|
|
}
|
|
})
|
|
|
|
it('--table 路径: columnData.searchList[*].__config__.tableName === opts.table (HIGH1)', async () => {
|
|
const body = await runAndCaptureBody([
|
|
'--table', 'eventaudit',
|
|
'--fullName', '活动审核',
|
|
'--enCode', 'eventAudit',
|
|
'--no-verify',
|
|
])
|
|
|
|
const columnData = JSON.parse(body.columnData as string) as { searchList?: Array<any> }
|
|
expect(Array.isArray(columnData.searchList)).toBe(true)
|
|
expect(columnData.searchList!.length).toBeGreaterThan(0)
|
|
for (const entry of columnData.searchList!) {
|
|
if (!entry.__config__) continue
|
|
expect(entry.__config__.tableName).toBe('eventaudit')
|
|
}
|
|
})
|
|
|
|
it('--table 路径: columnData.searchList[*] 保留 id/prop, 供 CodePreview 使用 (REGRESSION)', async () => {
|
|
const body = await runAndCaptureBody([
|
|
'--table', 'eventaudit',
|
|
'--fullName', '活动审核',
|
|
'--enCode', 'eventAudit',
|
|
'--no-verify',
|
|
])
|
|
|
|
const columnData = JSON.parse(body.columnData as string) as { searchList?: Array<any> }
|
|
expect(Array.isArray(columnData.searchList)).toBe(true)
|
|
expect(columnData.searchList!.length).toBeGreaterThan(0)
|
|
for (const entry of columnData.searchList!) {
|
|
expect(entry.id).toBeTruthy()
|
|
expect(entry.prop).toBe(entry.id)
|
|
}
|
|
})
|
|
|
|
it('--table 路径: appColumnData.columnList[*].__config__.tableName === opts.table (HIGH1)', async () => {
|
|
const body = await runAndCaptureBody([
|
|
'--table', 'eventaudit',
|
|
'--fullName', '活动审核',
|
|
'--enCode', 'eventAudit',
|
|
'--no-verify',
|
|
])
|
|
|
|
const appColumnData = JSON.parse(body.appColumnData as string) as { columnList?: Array<any> }
|
|
expect(Array.isArray(appColumnData.columnList)).toBe(true)
|
|
expect(appColumnData.columnList!.length).toBeGreaterThan(0)
|
|
for (const entry of appColumnData.columnList!) {
|
|
if (!entry.__config__) continue
|
|
expect(entry.__config__.tableName).toBe('eventaudit')
|
|
}
|
|
})
|
|
|
|
it('--table + --tables 互斥: 早期 ctx.fail, 不发 API (HIGH2)', async () => {
|
|
// 同时传 --table 和 --tables 应立刻 ctx.fail, 不调 loadVisualDev.create / SSW / dm
|
|
const cmd = buildFormCreateCommand()
|
|
await cmd.parseAsync([
|
|
'node', 'test',
|
|
'--table', 'eventaudit',
|
|
'--tables', JSON.stringify([{ table: 'eventaudit', tableName: '活动审核' }]),
|
|
'--fullName', '活动审核',
|
|
'--enCode', 'eventAudit',
|
|
'--no-verify',
|
|
])
|
|
|
|
// 关键契约: 不应触发任何 API (dm/SSW/visualdev.create/release)
|
|
expect(mocks.create).not.toHaveBeenCalled()
|
|
expect(mocks.release).not.toHaveBeenCalled()
|
|
expect(mocks.getDataModelFieldList).not.toHaveBeenCalled()
|
|
// postJson (SSW) 也不应被调用
|
|
expect(mocks.postJson).not.toHaveBeenCalled()
|
|
// 应有错误退出
|
|
expect(mocks.exit).toHaveBeenCalledWith(1)
|
|
})
|
|
})
|
|
|
|
describe('form create --ai + --table: final smartProps must survive table rebuild', () => {
|
|
it('preserves dictionaryType on the final generated select field', async () => {
|
|
mocks.getDataModelFieldList.mockResolvedValue([
|
|
{ field: 'f_topic_direction', fieldName: '赛题方向', dataType: 'varchar', dataLength: '50' },
|
|
])
|
|
mocks.postJson.mockImplementation(async (path: string) => {
|
|
if (path.includes('/ssw/ai/build-form') || path.includes('/visualdev/ai/form')) {
|
|
return {
|
|
code: 200,
|
|
msg: 'ok',
|
|
data: {
|
|
enCode: 'eventSignup',
|
|
fullName: '活动报名',
|
|
aiModelList: [{ isMain: true, fields: [{
|
|
fieldName: 'f_topic_direction',
|
|
fieldComponent: 'select',
|
|
__list__: true,
|
|
__form__: true,
|
|
__query__: true,
|
|
}] }],
|
|
},
|
|
}
|
|
}
|
|
if (path.includes('/ssw/ai/infer-fields')) {
|
|
return {
|
|
code: 200,
|
|
msg: 'ok',
|
|
data: {
|
|
enCode: 'eventSignup',
|
|
fullName: '活动报名',
|
|
aiModelList: [{ isMain: true, fields: [{
|
|
fieldName: 'f_topic_direction',
|
|
fieldComponent: 'select',
|
|
__list__: true,
|
|
__form__: true,
|
|
__query__: true,
|
|
}] }],
|
|
},
|
|
}
|
|
}
|
|
if (path.includes('/ssw/ai/infer-component-props')) {
|
|
return {
|
|
code: 200,
|
|
msg: 'ok',
|
|
data: {
|
|
props: [{
|
|
vModel: 'f_topic_direction',
|
|
dictionaryType: 'testCat',
|
|
reason: 'test dictionary inference',
|
|
}],
|
|
},
|
|
}
|
|
}
|
|
return { code: 404, msg: 'not mocked', data: null }
|
|
})
|
|
|
|
const cmd = buildFormCreateCommand()
|
|
await cmd.parseAsync([
|
|
'node', 'test',
|
|
'--ai', '活动报名',
|
|
'--table', 'event_signup',
|
|
'--fullName', '活动报名',
|
|
'--enCode', 'eventSignup',
|
|
'--category', 'cat-test-id',
|
|
'--no-verify',
|
|
'--json',
|
|
])
|
|
|
|
expect(mocks.create).toHaveBeenCalledTimes(1)
|
|
const body = mocks.create.mock.calls[0][0] as Record<string, unknown>
|
|
const formData = JSON.parse(body.formData as string) as { fields: Array<any> }
|
|
const field = formData.fields.find((item) => item.__vModel__ === 'f_topic_direction')
|
|
expect(field?.__config__?.dataType).toBe('dictionary')
|
|
expect(field?.__config__?.dictionaryType).toBe('cat-test-id')
|
|
})
|
|
}) |