Files
dacli/tests/unit/workflow/create_stale_retry.test.ts
T

156 lines
6.4 KiB
TypeScript

/**
* Workflow stale pre-validate cleanup + retry (BS-新43b) unit test
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
// Use vi.hoisted to share mock state across vi.mock factory (hoisted) and tests
const mocks = vi.hoisted(() => ({
mockPostJson: vi.fn(),
mockGet: vi.fn(),
mockDelFlow: vi.fn(),
mockExit: vi.fn(),
}))
vi.mock('../../../src/core/client.ts', () => ({
JnpfClient: {
fromToken: vi.fn(async () => ({
postJson: mocks.mockPostJson,
get: mocks.mockGet,
appCode: 'ts2',
baseUrl: 'http://127.0.0.1:30000',
})),
},
}))
vi.mock('../../../src/webapi/workflow.ts', () => ({
initWebapi: vi.fn(async () => {}),
loadWorkflow: { delFlow: mocks.mockDelFlow },
}))
vi.mock('../../../src/core/log.ts', async () => {
// mock 必须覆盖 log 对象全部 9 个方法, 否则 commands/workflow/_output.ts
// 里的 setupOutputFilter (log.setQuiet) / printCommandEnd (log.flush/discard)
// 会 'log.setQuiet is not a function' 抛错 (2026-07-20 复盘发现).
return {
log: {
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
ok: vi.fn(),
setQuiet: vi.fn(),
isQuiet: vi.fn(),
flush: vi.fn(),
discard: vi.fn(),
dim: vi.fn(),
raw: vi.fn(),
debug: vi.fn(),
},
printJson: vi.fn(),
}
})
vi.mock('../../../src/commands/_error_codes.ts', () => ({
enhanceFromBackend: vi.fn(() => ({ bs: 'BS-新43b', message: 'stale' })),
formatErrorLine: vi.fn(() => 'formatted'),
}))
vi.mock('../../../src/commands/workflow/_validate.ts', async () => {
const actual = await vi.importActual<any>('../../../src/commands/workflow/_validate.ts')
return {
...actual,
runWorkflowStepMachine: vi.fn(async () => {}),
detectTrivialFlowXml: vi.fn(() => false),
validateWorkflowCreate: vi.fn(() => ({ ok: true, step: 2, stepName: 'all', errors: [] })),
}
})
vi.spyOn(process, 'exit').mockImplementation(mocks.mockExit as any)
import { buildWorkflowCreateCommand } from '../../../src/commands/workflow/create.ts'
const flowXml = '<?xml version="1.0"?><bpmn2:definitions xmlns:bpmn2="http://www.omg.org/spec/BPMN/20100524/MODEL"><bpmn2:process id="p1"><bpmn2:startEvent id="s1"/><bpmn2:endEvent id="e1"/></bpmn2:process></bpmn2:definitions>'
describe('Workflow create — BS-新43b stale pre-validate cleanup + retry', () => {
beforeEach(() => {
// 注意: 不要 vi.clearAllMocks() — 会清掉 Once queue. 只清 calls/results.
mocks.mockPostJson.mockClear()
mocks.mockGet.mockClear()
mocks.mockDelFlow.mockClear()
mocks.mockExit.mockReset()
// 默认 postJson 返回合理响应 (防止后续 step 4-6 调 save/buildFlowNodes 等挂掉)
mocks.mockPostJson.mockResolvedValue({ code: 200, msg: 'ok', data: {} })
// 默认 get: validateWorkflowCreate 唯一性检查需要空列表, step 3 Version 需要非空
mocks.mockGet.mockImplementation(async (url: string) => {
if (url.includes('/Version/')) {
return { data: [{ id: 'ver-default', state: 1 }] }
}
return { data: [] }
})
})
it('stale keyword 触发 cleanup + retry ONCE', async () => {
let createCalled = 0
mocks.mockPostJson.mockImplementation(async (url: string) => {
console.log('DEBUG postJson called with url:', url, 'createCalled:', createCalled)
if (url === '/workflow/template') {
createCalled += 1
if (createCalled === 1) return { code: 400, msg: '编码已存在 SU001 预校验', data: null }
return { code: 200, msg: 'ok', data: { id: 'new-template-id' } }
}
return { code: 200, msg: 'ok', data: {} }
})
mocks.mockGet.mockImplementation(async (url: string, params?: any) => {
console.log('DEBUG get called:', url, params)
if (params?.keyword === 'r17test') return { data: { list: [{ id: 'stale-1' }, { id: 'stale-2' }] } }
if (url.includes('/Version/')) return { data: [{ id: 'ver-default', state: 1 }] }
return { data: [] }
})
mocks.mockDelFlow.mockImplementation(async (id: string) => {
console.log('DEBUG delFlow called with:', id)
return { code: 200 }
})
const cmd = buildWorkflowCreateCommand()
await cmd.parseAsync(['node', 'test', '--enCode', 'r17test', '--fullName', 'r17 test',
'--category', 'be6b516477ed41dab4d0777336e58ddf', '--flowXml', flowXml])
// debug: list all postJson calls
console.log('DEBUG postJson calls:', mocks.mockPostJson.mock.calls.map((c: any) => c[0]))
console.log('DEBUG delFlow calls:', mocks.mockDelFlow.mock.calls)
// create + retry + save = 3 calls (stale retry 后继续 step 5 buildFlowNodes + step 6 save)
expect(mocks.mockPostJson.mock.calls.length).toBeGreaterThanOrEqual(2)
// 第一次: 创建 (stale fail), 第二次: retry
expect(mocks.mockPostJson.mock.calls[0][0]).toBe('/workflow/template')
expect(mocks.mockPostJson.mock.calls[1][0]).toBe('/workflow/template')
expect(mocks.mockGet).toHaveBeenCalledWith('/workflow/template', expect.objectContaining({ keyword: 'r17test' }))
expect(mocks.mockDelFlow).toHaveBeenCalledTimes(2)
expect(mocks.mockDelFlow).toHaveBeenCalledWith('stale-1')
expect(mocks.mockDelFlow).toHaveBeenCalledWith('stale-2')
expect(mocks.mockExit).not.toHaveBeenCalledWith(1)
})
it('non-stale error 不触发 retry (直接 exit)', async () => {
mocks.mockPostJson.mockResolvedValueOnce({ code: 500, msg: 'internal error', data: null })
const cmd = buildWorkflowCreateCommand()
await cmd.parseAsync(['node', 'test', '--enCode', 'r17test2', '--fullName', 'r17 test 2',
'--category', 'be6b516477ed41dab4d0777336e58ddf', '--flowXml', flowXml])
expect(mocks.mockPostJson.mock.calls[0][0]).toBe('/workflow/template')
expect(mocks.mockDelFlow).not.toHaveBeenCalled()
expect(mocks.mockExit).toHaveBeenCalledWith(1)
})
it('stale detected but no stale id → cleanup 失败 → exit 1', async () => {
mocks.mockPostJson.mockResolvedValueOnce({ code: 400, msg: '已存在', data: null })
mocks.mockGet.mockResolvedValueOnce({ data: { list: [] } })
const cmd = buildWorkflowCreateCommand()
await cmd.parseAsync(['node', 'test', '--enCode', 'r17test3', '--fullName', 'r17 test 3',
'--category', 'be6b516477ed41dab4d0777336e58ddf', '--flowXml', flowXml])
expect(mocks.mockPostJson.mock.calls[0][0]).toBe('/workflow/template')
expect(mocks.mockDelFlow).not.toHaveBeenCalled()
expect(mocks.mockExit).toHaveBeenCalledWith(1)
})
})