import { describe, expect, it, spyOn, afterEach } from "bun:test"; import { handleWorkflowCommand } from "./workflow/index.js"; import * as helpers from "../helpers.js"; import type { CliRuntime } from "../types.js"; import type { CorpConfig } from "../../core/config/types.js"; const mockCorp: CorpConfig = { id: "test-corp", name: "测试企业", baseUrl: "https://app.ekuaibao.com", source: "openapi", credentials: { accessToken: "mock-token", corpId: "test-corp", staffId: "test-corp:STAFF_TEST", appKey: "test-key", appSecurity: "test-security", }, }; const mockRuntime: CliRuntime = { corpContext: { listCorps: () => [mockCorp], getCurrent: () => mockCorp, switchCorp: () => true, resolve: () => mockCorp, } as any, selectedCorp: mockCorp, jsonMode: false, outputOptions: {}, }; describe("CLI - workflow job 执行详情与异常精准透视", () => { let spies: ReturnType[] = []; afterEach(() => { for (const spy of spies) { spy.mockRestore(); } spies = []; }); it("fails when no corp is selected", async () => { const res = await handleWorkflowCommand( { area: "workflow", action: "job", args: ["job_123"], options: {}, raw: ["workflow", "job", "job_123"], }, { ...mockRuntime, selectedCorp: null } ); expect(res.exitCode).toBe(1); expect(res.stderr).toContain("未选中企业"); }); it("fails when no jobId is provided", async () => { const res = await handleWorkflowCommand( { area: "workflow", action: "job", args: [], options: {}, raw: ["workflow", "job"], }, mockRuntime ); expect(res.exitCode).toBe(1); expect(res.stderr).toContain("用法: hose-use workflow job "); }); it("handles workflow job --failed with deep error inspection and inputs/outputs", async () => { const mockPiperClient = { get: (url: string) => { let payload: any = {}; if (url.includes("/execution/level/failed")) { payload = { number: 1, size: 100, totalPages: 0, totalItems: 0, items: [] }; } else if (url.includes("/execution")) { payload = [ { id: "exec_1", name: "auto_approve", displayName: "资金调拨自动审批", type: "flow-approval", status: "FAILED", executionTime: 350, error: { message: "400: 无待办审批事项" }, inputs: { formId: "ZJ-20261014-001368", action: "agree" }, outputs: { code: 400, message: "无待办审批事项" }, }, ]; } else if (url.includes("/jobs/job_err")) { payload = { id: "job_err", pipelineId: "pipe_1", state: "FAILED", startTime: "2026-10-14 10:00:00", durationTime: 1200, }; } return new Response(JSON.stringify({ code: 200, data: payload }), { status: 200, headers: { "content-type": "application/json" }, }); }, }; spies.push( spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: { get: () => ({ json: async () => [{ id: "plat_1", active: true }] }), }, easoClient: mockPiperClient, } as any) ); spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockPiperClient as any)); // 文本输出测试 const res = await handleWorkflowCommand( { area: "workflow", action: "job", args: ["job_err"], options: { failed: true }, raw: ["workflow", "job", "job_err", "--failed"], }, mockRuntime ); expect(res.exitCode).toBe(0); expect(res.stdout).toContain("Job 异常/失败执行节点透视"); expect(res.stdout).toContain("资金调拨自动审批"); expect(res.stdout).toContain("400: 无待办审批事项"); expect(res.stdout).toContain("ZJ-20261014-001368"); // --json 模式测试 const jsonRes = await handleWorkflowCommand( { area: "workflow", action: "job", args: ["job_err"], options: { failed: true, json: true }, raw: ["workflow", "job", "job_err", "--failed", "--json"], }, { ...mockRuntime, jsonMode: true } ); expect(jsonRes.exitCode).toBe(0); const parsed = JSON.parse(jsonRes.stdout); expect(parsed.totalFailed).toBe(1); expect(parsed.failedNodes[0].id).toBe("exec_1"); expect(parsed.failedNodes[0].error.message).toBe("400: 无待办审批事项"); expect(parsed.failedNodes[0].inputs.formId).toBe("ZJ-20261014-001368"); }); it("handles workflow job --node= targeting specific execution node", async () => { const mockPiperClient = { get: (url: string) => { let payload: any = {}; if (url.includes("/execution")) { payload = [ { id: "node_code", name: "codeRunner_1", displayName: "MVEL计算节点", type: "code", status: "COMPLETED", executionTime: 85, inputs: { expression: "pvTotal * dailyRate" }, outputs: { result: 78787.55 }, }, ]; } return new Response(JSON.stringify({ code: 200, data: payload }), { status: 200, headers: { "content-type": "application/json" }, }); }, }; spies.push( spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: { get: () => ({ json: async () => [{ id: "plat_1", active: true }] }), }, easoClient: mockPiperClient, } as any) ); spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockPiperClient as any)); const res = await handleWorkflowCommand( { area: "workflow", action: "job", args: ["job_single"], options: { node: "MVEL计算" }, raw: ["workflow", "job", "job_single", "--node=MVEL计算"], }, mockRuntime ); expect(res.exitCode).toBe(0); expect(res.stdout).toContain("工作流节点执行详情 [node_code]"); expect(res.stdout).toContain("MVEL计算节点"); expect(res.stdout).toContain("pvTotal * dailyRate"); expect(res.stdout).toContain("78787.55"); // 节点不存在时的错误提示拦截 const notFoundRes = await handleWorkflowCommand( { area: "workflow", action: "job", args: ["job_single"], options: { node: "不存在的节点" }, raw: ["workflow", "job", "job_single", "--node=不存在的节点"], }, mockRuntime ); expect(notFoundRes.exitCode).toBe(1); expect(notFoundRes.stderr).toContain("未在 Job [job_single] 的执行树中找到匹配 \"不存在的节点\" 的节点"); }); it("handles workflow diff comparing code and node changes", async () => { const snap1 = { id: "snap_v1", pipelineId: "pipe_1", version: "1.0.1", updateTime: "2026-10-13 14:00:00", staffName: "张三", tasks: [ { name: "fetch_contract", type: "ekuaibao-datalink-filter", displayName: "获取合同台账", groupName: "action", orderIndex: 0, levelIndex: [0], status: "ENABLE", combineFilters: { condition: "AND", filters: [{ key: "state", compare: "EQUAL", value: "OPEN" }] }, }, { name: "mvel_calc", type: "code", displayName: "MVEL计算节点", groupName: "action", orderIndex: 1, levelIndex: [1], status: "ENABLE", code: "double dailyRate = 0.05;\nreturn pvTotal * dailyRate;", }, ], }; const snap2 = { id: "snap_v2", pipelineId: "pipe_1", version: "1.0.2", updateTime: "2026-10-14 09:30:00", staffName: "李四", tasks: [ { name: "fetch_contract", type: "ekuaibao-datalink-filter", displayName: "获取合同台账", groupName: "action", orderIndex: 0, levelIndex: [0], status: "ENABLE", combineFilters: { condition: "AND", filters: [{ key: "state", compare: "EQUAL", value: "APPROVING" }] }, }, { name: "mvel_calc", type: "code", displayName: "MVEL计算节点", groupName: "action", orderIndex: 1, levelIndex: [1], status: "ENABLE", code: "double dailyRate = 0.05;\nif (pvTotal <= 0) throw new RuntimeException('金额非法');\nreturn pvTotal * dailyRate;", }, { name: "notify_audit", type: "webhook", displayName: "审计通知", groupName: "action", orderIndex: 2, levelIndex: [2], status: "ENABLE", }, ], }; const mockPiperClient = { get: (url: string) => { let payload: any = {}; if (url.includes("snap_v1")) payload = snap1; else if (url.includes("snap_v2")) payload = snap2; return new Response(JSON.stringify({ code: 200, data: payload }), { status: 200, headers: { "content-type": "application/json" }, }); }, }; spies.push( spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: { get: () => ({ json: async () => [{ id: "plat_1", active: true }] }) }, easoClient: mockPiperClient, } as any) ); spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockPiperClient as any)); // 1. 文本输出模式 const res = await handleWorkflowCommand( { area: "workflow", action: "diff", args: ["snap_v1", "snap_v2"], options: {}, raw: ["workflow", "diff", "snap_v1", "snap_v2"], }, mockRuntime ); expect(res.exitCode).toBe(0); expect(res.stdout).toContain("工作流快照比对 [1.0.1 -> 1.0.2]"); expect(res.stdout).toContain("新增节点 (1 个)"); expect(res.stdout).toContain("notify_audit"); expect(res.stdout).toContain("mvel_calc"); expect(res.stdout).toContain("金额非法"); expect(res.stdout).toContain("过滤/触发条件变动"); // 2. JSON 模式 const jsonRes = await handleWorkflowCommand( { area: "workflow", action: "diff", args: ["snap_v1", "snap_v2"], options: { json: true }, raw: ["workflow", "diff", "snap_v1", "snap_v2", "--json"], }, { ...mockRuntime, jsonMode: true } ); expect(jsonRes.exitCode).toBe(0); const parsed = JSON.parse(jsonRes.stdout); expect(parsed.addedTasks).toContain("notify_audit"); expect(parsed.modifiedTasks.find((t: any) => t.taskName === "mvel_calc")).toBeDefined(); // 3. 缺少参数 const errRes = await handleWorkflowCommand( { area: "workflow", action: "diff", args: ["snap_v1"], options: {}, raw: ["workflow", "diff", "snap_v1"], }, mockRuntime ); expect(errRes.exitCode).toBe(1); expect(errRes.stderr).toContain("用法: hose-use workflow diff"); }); it("handles workflow diff-job comparing execution branch and error divergence", async () => { const jobA = { id: "job_success", pipelineId: "pipe_1", state: "COMPLETED", startTime: "2026-10-14 10:00:00", durationTime: 450, hasError: false, errorTaskCount: 0, }; const treeA = [ { id: "ex_1", name: "get_bill", displayName: "获取单据", type: "flow-detail", status: "COMPLETED", executionTime: 120, inputs: { billCode: "ZJ-20261014-001" }, outputs: { state: "APPROVING" }, }, { id: "ex_2", name: "auto_approve", displayName: "自动审批", type: "flow-approval", status: "COMPLETED", executionTime: 330, inputs: { action: "agree" }, outputs: { code: 200, success: true }, }, ]; const jobB = { id: "job_failed", pipelineId: "pipe_1", state: "FAILED", startTime: "2026-10-14 11:00:00", durationTime: 320, hasError: true, errorTaskCount: 1, }; const treeB = [ { id: "ex_1b", name: "get_bill", displayName: "获取单据", type: "flow-detail", status: "COMPLETED", executionTime: 100, inputs: { billCode: "ZJ-20261014-002" }, outputs: { state: "PAYING" }, }, { id: "ex_2b", name: "auto_approve", displayName: "自动审批", type: "flow-approval", status: "FAILED", executionTime: 220, error: { message: "400: 无待办审批事项" }, inputs: { action: "agree" }, outputs: { code: 400, message: "无待办审批事项" }, }, ]; const mockPiperClient = { get: (url: string) => { let payload: any = {}; if (url.includes("job_success/execution")) payload = treeA; else if (url.includes("job_failed/execution")) payload = treeB; else if (url.includes("job_success")) payload = jobA; else if (url.includes("job_failed")) payload = jobB; return new Response(JSON.stringify({ code: 200, data: payload }), { status: 200, headers: { "content-type": "application/json" }, }); }, }; spies.push( spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: { get: () => ({ json: async () => [{ id: "plat_1", active: true }] }) }, easoClient: mockPiperClient, } as any) ); spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockPiperClient as any)); // 1. 文本输出模式 const res = await handleWorkflowCommand( { area: "workflow", action: "diff-job", args: ["job_success", "job_failed"], options: {}, raw: ["workflow", "diff-job", "job_success", "job_failed"], }, mockRuntime ); expect(res.exitCode).toBe(0); expect(res.stdout).toContain("工作流 Job 执行比对 [job_success vs job_failed]"); expect(res.stdout).toContain("auto_approve"); expect(res.stdout).toContain("400: 无待办审批事项"); expect(res.stdout).toContain("ZJ-20261014-001"); expect(res.stdout).toContain("ZJ-20261014-002"); // 2. JSON 模式 const jsonRes = await handleWorkflowCommand( { area: "workflow", action: "diff-job", args: ["job_success", "job_failed"], options: { json: true }, raw: ["workflow", "diff-job", "job_success", "job_failed", "--json"], }, { ...mockRuntime, jsonMode: true } ); expect(jsonRes.exitCode).toBe(0); const parsed = JSON.parse(jsonRes.stdout); expect(parsed.jobA.id).toBe("job_success"); expect(parsed.jobB.id).toBe("job_failed"); expect(parsed.summary.statusDiffCount).toBe(1); expect(parsed.nodes.find((n: any) => n.taskName === "auto_approve").statusB).toBe("FAILED"); }); it("handles workflow test without pipelineId", async () => { const res = await handleWorkflowCommand( { area: "workflow", action: "test", args: [], options: {}, raw: ["workflow", "test"], }, mockRuntime ); expect(res.exitCode).toBe(1); expect(res.stderr).toContain("用法: hose-use workflow test"); }); it("handles workflow test without --flow by listing candidate sources", async () => { const mockClient = { post: (url: string) => ({ json: async () => ({ code: 200, data: { type: "flowForm", total: 1, label: "我的单据", items: [ { id: "ZJ-20261015-001387", title: "资金调拨测试单", flowState: "审批中" }, ], fields: [ { key: "id", label: "单号" }, { key: "title", label: "标题" }, ], }, }), }), get: (url: string) => { if (url.includes("platform")) { return { json: async () => ({ items: [] }) }; } return { json: async () => ({ code: 200, data: [] }) }; }, }; spies.push( spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: mockClient as any, easoClient: mockClient as any, corp: mockCorp, } as any) ); spies.push( spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any) ); const res = await handleWorkflowCommand( { area: "workflow", action: "test", args: ["wf_test_1"], options: { platformId: "p1" }, raw: ["workflow", "test", "wf_test_1", "--platform-id=p1"], }, mockRuntime ); expect(res.exitCode).toBe(1); expect(res.stdout).toContain("未指定测试单号"); expect(res.stdout).toContain("ZJ-20261015-001387"); expect(res.stdout).toContain("资金调拨测试单"); }); it("handles workflow test end-to-end with --flow parameter", async () => { const mockClient = { post: (url: string) => { if (url.includes("debugSource")) { return { json: async () => ({ code: 200, data: { type: "flowForm", total: 1, items: [{ id: "ZJ-20261015-001387", title: "资金调拨", flowState: "审批中" }], }, }), }; } if (url.includes("api/easo/jobs")) { return { json: async () => ({ code: 200, data: "job_debug_888", }), }; } return { json: async () => ({ code: 200, data: null }) }; }, get: (url: string) => { if (url.includes("execution")) { return { json: async () => ({ code: 200, data: [ { id: "e1", name: "trigger_1", label: "触发器", type: "ekuaibao-flowform-trigger", status: "COMPLETED", executionTime: 10, }, { id: "e2", name: "control_1", label: "条件节点", type: "condition", status: "COMPLETED", executionTime: 5, tasks: [{ name: "action_auto", label: "自动审批", type: "http" }], }, { id: "e3", name: "action_stop", label: "终止节点", type: "stop", status: "COMPLETED", executionTime: 2, }, ], }), }; } if (url.includes("api/easo/pipelines/")) { return { json: async () => ({ code: 200, data: { id: "wf_test_1", label: "测试工作流", state: 0, }, }), }; } return { json: async () => ({ code: 200, data: { id: "job_debug_888", pipelineId: "wf_test_1", status: "COMPLETED", runType: "DEBUG", durationTime: 17, }, }), }; }, }; spies.push( spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: mockClient as any, easoClient: mockClient as any, corp: mockCorp, } as any) ); spies.push( spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any) ); const res = await handleWorkflowCommand( { area: "workflow", action: "test", args: ["wf_test_1"], options: { flow: "ZJ-20261015-001387", platformId: "p1" }, raw: ["workflow", "test", "wf_test_1", "--flow=ZJ-20261015-001387", "--platform-id=p1"], }, mockRuntime ); expect(res.exitCode).toBe(0); expect(res.stdout).toContain("工作流自动化调测报告 [wf_test_1]"); expect(res.stdout).toContain("job_debug_888"); expect(res.stdout).toContain("ZJ-20261015-001387"); expect(res.stdout).toContain("control_1"); }); it("blocks workflow test when pipeline is enabled in production without --force", async () => { const mockClient = { get: (url: string) => { if (url.includes("api/easo/pipelines/")) { return { json: async () => ({ code: 200, data: { id: "wf_prod_1", label: "生产自动审批工作流", state: 1, // 生产启用中 }, }), }; } return { json: async () => ({ code: 200, data: null }) }; }, post: () => ({ json: async () => ({ code: 200, data: null }) }), }; spies.push( spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: mockClient as any, easoClient: mockClient as any, corp: mockCorp, } as any) ); spies.push( spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any) ); const res = await handleWorkflowCommand( { area: "workflow", action: "test", args: ["wf_prod_1"], options: { flow: "ZJ-20261015-001387", platformId: "p1" }, raw: ["workflow", "test", "wf_prod_1", "--flow=ZJ-20261015-001387", "--platform-id=p1"], }, mockRuntime ); expect(res.exitCode).toBe(1); expect(res.stderr).toContain("安全防御拦截"); expect(res.stderr).toContain("生产启用中"); expect(res.stderr).toContain("--force"); }); it("allows workflow test when pipeline is enabled in production with --force", async () => { const mockClient = { get: (url: string) => { if (url.includes("api/easo/pipelines/")) { return { json: async () => ({ code: 200, data: { id: "wf_prod_1", label: "生产自动审批工作流", state: 1, }, }), }; } if (url.includes("execution")) { return { json: async () => ({ code: 200, data: [ { id: "e1", name: "trigger_1", label: "触发器", type: "ekuaibao-flowform-trigger", status: "COMPLETED", }, ], }), }; } return { json: async () => ({ code: 200, data: { id: "job_force_999", pipelineId: "wf_prod_1", status: "COMPLETED", runType: "DEBUG", }, }), }; }, post: () => ({ json: async () => ({ code: 200, data: "job_force_999" }) }), }; spies.push( spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: mockClient as any, easoClient: mockClient as any, corp: mockCorp, } as any) ); spies.push( spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any) ); const res = await handleWorkflowCommand( { area: "workflow", action: "test", args: ["wf_prod_1"], options: { flow: "ZJ-20261015-001387", force: true, platformId: "p1" }, raw: ["workflow", "test", "wf_prod_1", "--flow=ZJ-20261015-001387", "--force", "--platform-id=p1"], }, mockRuntime ); expect(res.exitCode).toBe(0); expect(res.stdout).toContain("生产调试警示"); expect(res.stdout).toContain("job_force_999"); }); });