Files
dacli/tests/unit/dm_create_json.test.ts
sushub f403a7e80e import: ssw/dacli@eea0ebc (2026-08-12) 起点版本
本仓 2026-08-12 从 ssw main (192.168.1.18:13300/ssw/ssw-mvp) 的
dacli/ subpath 抽取,作为独立仓托管到 gitea:3000/ssw/dacli.git。

- 工作树为 ssw main dacli subpath 最新版 (110 commit, 08-12)
- 历史未带 ssw main 整体历史(避免大仓污染)
- 此为新仓基线 commit,未来以本仓历史为主
2026-08-12 15:58:06 +08:00

254 lines
9.9 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* tests/unit/dm_create_json.test.ts
*
* 覆盖 src/commands/dm/_result.ts buildDmCreateResult + printDmCreateJsonResult
* (2026-07-22 eventhub 阻断修复)
*
* 修复前 root cause (debug.md §2.1):
* - dm create --json 在 `event_info` 场景失败时, 旧逻辑 printJson(r) 输出整个
* response envelope + 上层 info 日志混杂, 实际 stdout 出现 `null` (因后端 data 为空).
* - 实际生产中 AI 拿到 undefined 字段, JSON.parse 失败导致脚本退出码 0 (log 路径) 而
* 不是 exit 1.
*
* 修复后契约:
* - 成功: 即使后端 data 为空, 也输出去归一化的 {ok:true, table, tableName}
* - 失败 (后端非200): {ok:false, table, error, code?}
* - 失败 (catch): {ok:false, table, error, code:'EXC'}
* - 输出经 JSON.parse 严格合法; 禁止字面量 'undefined'
* - 失败时 exit code 非零 (调用方负责, 这里只验 stdout shape)
*
* 详见 docs/decisions/0016-eventhub-blocker-fixes-design.md §3.2
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import {
buildDmCreateResult,
printDmCreateJsonResult,
type DmCreateResult,
type BackendResponseLite,
} from '../../src/commands/dm/_result.ts'
describe('buildDmCreateResult.success — 成功路径 (event_signup 案例)', () => {
it('snake_case 表名 + 中文名 → 标准 success shape', () => {
const r = buildDmCreateResult.success({
table: 'event_signup',
tableName: '活动报名表',
})
expect(r.ok).toBe(true)
expect(r.table).toBe('event_signup')
expect(r.tableName).toBe('活动报名表')
// 不输出 undefined 字段
expect(JSON.stringify(r)).not.toContain('undefined')
})
it('后端 data 为空也能产出合法 success result (修复前 root cause)', () => {
// 模拟后端返 { code: 200 } 但 data: null — 旧 printJson(r.data) 会输出 'null'
// 现在 buildSuccess 用本地输入, 后端 data 缺失不阻断
const r = buildDmCreateResult.success({
table: 'event_signup',
tableName: '活动报名表',
})
expect(r.ok).toBe(true)
expect(r.table).toBe('event_signup')
// 输出能 JSON.parse
expect(() => JSON.parse(JSON.stringify(r))).not.toThrow()
const parsed = JSON.parse(JSON.stringify(r))
expect(parsed.ok).toBe(true)
expect(parsed.table).toBe('event_signup')
})
it('空 string 输入 → 空字符串保留 (不抛)', () => {
const r = buildDmCreateResult.success({ table: '', tableName: '' })
expect(r.table).toBe('')
expect(r.tableName).toBe('')
expect(JSON.stringify(r)).toBe('{"ok":true,"table":"","tableName":""}')
})
})
describe('buildDmCreateResult.failureFromBackend — 后端非 200 路径', () => {
it('后端 code=500 + msg="Duplicate column name \'f_description\'" → failure shape', () => {
const r = buildDmCreateResult.failureFromBackend({
table: 'event_signup',
response: { code: 500, msg: "Duplicate column name 'f_description'" },
})
expect(r.ok).toBe(false)
expect(r.table).toBe('event_signup')
expect(r.error).toBe("Duplicate column name 'f_description'")
expect(r.code).toBe(500)
expect(JSON.parse(JSON.stringify(r))).toEqual({
ok: false,
table: 'event_signup',
error: "Duplicate column name 'f_description'",
code: 500,
})
})
it('后端只返 msg 无 code → failure shape 不含 code 字段', () => {
const r = buildDmCreateResult.failureFromBackend({
table: 'event_info',
response: { msg: 'TABLE_NAME_CONFLICT' },
})
expect(r.ok).toBe(false)
expect(r.error).toBe('TABLE_NAME_CONFLICT')
// code 字段不存在 (JSON.stringify 自动省略 undefined, 但 ts 类型允许 undefined)
expect('code' in r).toBe(false)
// stdout 不含 'undefined'
expect(JSON.stringify(r)).not.toContain('undefined')
expect(JSON.stringify(r)).toBe('{"ok":false,"table":"event_info","error":"TABLE_NAME_CONFLICT"}')
})
it('后端返空响应 (无 code 无 msg) → fallback error 文案', () => {
const r = buildDmCreateResult.failureFromBackend({
table: 'event_info',
response: {},
})
expect(r.ok).toBe(false)
expect(r.table).toBe('event_info')
expect(r.error).toBe('dm create failed')
// 无 code 字段
expect('code' in r).toBe(false)
})
it('后端响应 null/undefined → 不抛, fallback error', () => {
const r1 = buildDmCreateResult.failureFromBackend({ table: 'a', response: null })
const r2 = buildDmCreateResult.failureFromBackend({ table: 'a', response: undefined })
expect(r1.error).toBe('dm create failed')
expect(r2.error).toBe('dm create failed')
})
it('后端 string code (非 number) 也接受', () => {
const r = buildDmCreateResult.failureFromBackend({
table: 'event_info',
response: { code: 'EXIST001' as unknown as number, msg: 'table exists' },
})
// 后端是 number 但强制 string 走, 兜底保留 string code (防御 runtime 类型漂移)
expect(r.code).toBe('EXIST001')
})
})
describe('buildDmCreateResult.failureFromException — catch 路径', () => {
it('Error 对象 → exception shape', () => {
const r = buildDmCreateResult.failureFromException({
table: 'event_signup',
error: new Error('JSON parse failure at field 0'),
})
expect(r.ok).toBe(false)
expect(r.table).toBe('event_signup')
expect(r.error).toBe('JSON parse failure at field 0')
expect(r.code).toBe('EXC')
})
it('string 异常 → 转 string', () => {
const r = buildDmCreateResult.failureFromException({
table: 'event_signup',
error: 'unexpected end of JSON input',
})
expect(r.error).toBe('unexpected end of JSON input')
expect(r.code).toBe('EXC')
})
it('undefined 异常 → fallback 文案', () => {
const r = buildDmCreateResult.failureFromException({
table: 'event_signup',
error: undefined,
})
expect(r.error).toBe('dm create exception')
expect(r.code).toBe('EXC')
})
it('错误信息裁剪到 200 字符 (过长不爆 stdout)', () => {
const longMsg = 'a'.repeat(500)
const r = buildDmCreateResult.failureFromException({
table: 'event_signup',
error: new Error(longMsg),
})
expect(r.error.length).toBeLessThanOrEqual(200)
expect(r.error).toBe(longMsg.slice(0, 200))
})
})
describe('JSON 可解析性 (AI / pipe 消费方验证)', () => {
// 全 5 个 shape 都要 JSON.parse 成功
const samples: Array<{ name: string; result: DmCreateResult }> = [
{ name: 'success', result: buildDmCreateResult.success({ table: 'a', tableName: 'b' }) },
{ name: 'failure with code', result: buildDmCreateResult.failureFromBackend({ table: 'a', response: { code: 400, msg: 'bad' } }) },
{ name: 'failure without code', result: buildDmCreateResult.failureFromBackend({ table: 'a', response: { msg: 'bad' } }) },
{ name: 'failure empty response', result: buildDmCreateResult.failureFromBackend({ table: 'a', response: {} }) },
{ name: 'failure exception', result: buildDmCreateResult.failureFromException({ table: 'a', error: new Error('boom') }) },
]
samples.forEach(({ name, result }) => {
it(`${name}: JSON.parse(stdout) 严格合法`, () => {
const str = JSON.stringify(result)
// 不含字面 undefined
expect(str).not.toContain('undefined')
// JSON.parse 成功
const parsed = JSON.parse(str)
// shape 校验: 必有 ok/table/error(success)/error+code(failure)
expect(typeof parsed.ok).toBe('boolean')
expect(typeof parsed.table).toBe('string')
if (result.ok === true) {
expect(parsed.tableName).toBeDefined()
} else {
expect(typeof parsed.error).toBe('string')
if ((result as { code?: unknown }).code !== undefined) {
expect(parsed.code).toBeDefined()
}
}
})
})
})
describe('printDmCreateJsonResult — 直出 stdout (跳过 log 噪音)', () => {
// writeSpy: 收集 stdout.write 收到的字符串. 用 any 避开 vitest's strict mock 类型
// (跟 tests/unit/output_filter.test.ts:362 同样的模式; tsc strict 报同一类 warn, 但运行时通过)
let writes: string[]
let originalWrite: typeof process.stdout.write
beforeEach(() => {
writes = []
originalWrite = process.stdout.write.bind(process.stdout)
// 与 output_filter.test.ts:362 同样模式: 替换 process.stdout.write 收集 buffer.
// 注: vi.spyOn 严格 mock 类型在 strict 模式下不兼容, 用直接赋值.
process.stdout.write = ((chunk: string | Uint8Array) => {
writes.push(typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk))
return true
}) as typeof process.stdout.write
})
afterEach(() => {
process.stdout.write = originalWrite
})
it('success result → stdout 单行 JSON + 换行', () => {
const r = buildDmCreateResult.success({ table: 'event_signup', tableName: '活动报名表' })
printDmCreateJsonResult(r)
expect(writes).toHaveLength(1)
expect(writes[0]).toBe(JSON.stringify(r) + '\n')
// 可解析
expect(() => JSON.parse(writes[0].trim())).not.toThrow()
})
it('failure result → stdout 单行 JSON + 换行', () => {
const r = buildDmCreateResult.failureFromBackend({
table: 'event_info',
response: { code: 500, msg: 'server error' },
})
printDmCreateJsonResult(r)
expect(writes).toHaveLength(1)
expect(writes[0]).toBe(JSON.stringify(r) + '\n')
expect(writes[0]).not.toContain('undefined')
const parsed = JSON.parse(writes[0].trim())
expect(parsed.ok).toBe(false)
expect(parsed.code).toBe(500)
})
it('print 后 stdout 不含 log 装饰符 (无 emoji/中文/ANSI)', () => {
const r = buildDmCreateResult.success({ table: 'event_signup', tableName: '活动报名表' })
printDmCreateJsonResult(r)
const out = writes[0]
// stdout 是 raw JSON, 不应走 log.info (会加 ℹ 装饰)
expect(out).not.toMatch(/[ℹ✓✗⚠]/) // log.ts emoji
expect(out).not.toMatch(/\x1b\[/) // ANSI color
})
})