Files
hose-use/src/domains/platform/workflow/analysis/index.test.ts
T
gitea cedc4249e5 test(workflow): 补齐条件比较符、节点类型与错误指纹的测试覆盖
- 新增 branch/evaluate-rule.test.ts:覆盖 eq/neq、empty/not_empty、in/not_in、
  include/not_include、gt/gte/lt/lte 全部比较符,含无法确定(返回 null)的边界,
  以及 @{value(...)} / @{choose(...)} 描述符解析。此前只有 eq 与 gt 有用例。
- 新增未知节点类型与权限证据边界用例:UNKNOWN_TASK_TYPE 硬软门禁、
  以及拿不到开通清单(availableNodeTypes 为空)时既不谎报通过也不误报缺失。

错误指纹:
- alert observe() 原先在 SQLite 事务提交后直接 writeFileSync,
  落盘失败会把整轮巡检打成失败;而此刻指纹其实已经写入,
  下一轮会被当成「未观察过」从而重复提醒。改为捕获异常并以 exportError 返回,
  SQLite 仍作为唯一事实来源。
- 新增 alert/index.test.ts,并把原先写在 state/index.test.ts 里的告警用例迁移回来,
  修正模块归属错位。

覆盖 1004 个用例,`bun run check` 无错误。
2026-11-01 22:09:18 +08:00

555 lines
19 KiB
TypeScript

import { describe, expect, it } from "bun:test";
import { analyzeWorkflow } from "./index.js";
import { PlatformSchema } from "../../applications/types.js";
describe("Workflow static analysis", () => {
it("accepts nullable app center metadata", () => {
const platform = PlatformSchema.parse({ id: "app-1", name: "测试应用", corporationId: "corp-1", adminIds: null, importMethod: null });
expect(platform.adminIds).toEqual([]);
expect(platform.importMethod).toEqual([]);
});
it("builds a recursive AST and extracts code references", () => {
const result = analyzeWorkflow({ id: "wf-1", label: "审批", state: 1, version: "3", tasks: [{ name: "条件", type: "condition", label: "条件", groupName: "", orderIndex: 0, levelIndex: [0], status: "", tasks: [{ name: "脚本", type: "code-js2", label: "脚本", groupName: "", orderIndex: 1, levelIndex: [0, 0], status: "", code: "return {{bill.amount}} + ctx.user.id;" }] }] } as any);
expect(result.ast[0]?.children[0]?.path).toBe("0.0"); expect(result.dependencies[0]?.references).toEqual(["bill.amount", "user.id"]); expect(result.diagnostics).toHaveLength(0);
});
it("reports empty scripts, branches, and disabled workflow state", () => {
const result = analyzeWorkflow({ id: "wf-2", label: "异常", state: 0, version: "", tasks: [{ name: "脚本", type: "code", label: "", groupName: "", orderIndex: 0, levelIndex: [0], status: "", code: "" }, { name: "条件", type: "condition", label: "", groupName: "", orderIndex: 1, levelIndex: [1], status: "", tasks: [] }] } as any);
expect(result.diagnostics.map((item) => item.code)).toEqual(["WORKFLOW_DISABLED", "EMPTY_CODE", "EMPTY_BRANCH"]);
});
it("detects BROKEN_LOOP_ITEM_REFERENCE and BROKEN_CHOOSE_REFERENCE", () => {
const wf = {
id: "wf-broken",
label: "循环变量破坏",
state: 1,
version: "1",
tasks: [
{
name: "control_loop",
type: "every",
label: "循环",
tasks: [
{
name: "action_create",
type: "ekuaibao-datalink-create",
fields: [
{
key: "E_field_1",
value: "@{choose('{\"key\":\"control_loop.$item\",\"properties\":[{\"key\":\"E_field_1\"}]}')}",
},
{
key: "E_field_2",
value: "@{choose('{\"key\":\"non_existent_node\",\"properties\":[{\"key\":\"E_field_2\"}]}')}",
},
],
},
],
},
],
};
const result = analyzeWorkflow(wf as any);
const codes = result.diagnostics.map((d) => d.code);
expect(codes).toContain("BROKEN_LOOP_ITEM_REFERENCE");
expect(codes).toContain("BROKEN_CHOOSE_REFERENCE");
});
it("detects UNSAFE_SKIP_WITHOUT_STATUS_GUARD and LINKAGE_PRIORITY_OVERRIDE", () => {
const wf = {
id: "886351399301758976",
label: "【生产】每30分钟创建采购申请单",
state: 1,
version: "10",
tasks: [
{
name: "every_0",
type: "every",
label: "循环每条支付计划",
groupName: "control",
orderIndex: 1,
levelIndex: [0],
status: "",
tasks: [
{
name: "ekuaibao_flow_create_task_0",
type: "flow-create-task",
label: "创建预付申请单",
groupName: "ekuaibao",
orderIndex: 0,
levelIndex: [0, 0],
status: "",
onError: { defaultAction: "SKIP" },
inputs: {
specificationId: "ID01TxgE3fhD6n",
form: {
u_关联合同流程: "{{every_0.item.E_contract}}",
u_我方签约主体: "{{every_0.item.E_company}}",
},
},
},
{
name: "ekuaibao_datalink_edit_0",
type: "ekuaibao-datalink-edit",
label: "更新支付计划状态为创建成功",
groupName: "ekuaibao",
orderIndex: 1,
levelIndex: [0, 1],
status: "",
inputs: {
dataLinkId: "{{every_0.item.id}}",
form: {
状态: "创建成功",
},
},
},
],
},
],
};
const specifications = {
ID01TxgE3fhD6n: {
id: "ID01TxgE3fhD6n",
name: "预付申请单",
form: [
{
id: "f1",
name: "u_关联合同流程",
label: "关联合同流程",
type: "dataLink",
optional: false,
entityId: "e23d0d5451b1ccabfd7a",
assignmentRule: "ID01TRWvYFAulh",
isLinkageAssignment: false,
priorityList: [
{ type: "LINKAGE_ASSIGNMENT", priority: 10 },
{ type: "MANUALLY_FILL_IN", priority: 5 },
],
},
{
id: "f2",
name: "u_我方签约主体",
label: "我方签约主体",
type: "dimension",
optional: false,
isLinkageAssignment: true,
priorityList: [
{ type: "LINKAGE_ASSIGNMENT", priority: 10 },
{ type: "MANUALLY_FILL_IN", priority: 5 },
],
},
],
},
};
const result = analyzeWorkflow(wf as any, { specifications: specifications as any });
const codes = result.diagnostics.map((d) => d.code);
expect(codes).toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
expect(codes).toContain("LINKAGE_PRIORITY_OVERRIDE");
});
it("detects DEADLOCK_TRIGGER_STATE_FILTER when trigger specifies state APPROVING", () => {
const wf = {
id: "wf-trigger-deadlock",
label: "资金调拨自动审批",
state: 1,
version: "1",
tasks: [
{
name: "trigger_1",
type: "ekuaibao-flowform-trigger",
label: "单据审批事件触发器",
combineFilters: {
filters: [
{
filters: [
{ key: "formSpecification", value: "ID01RUq5zrhZTh", compare: "eq" },
{ key: "state", value: "APPROVING", compare: "eq" },
],
condition: "and",
},
],
condition: "or",
},
},
],
};
const result = analyzeWorkflow(wf as any);
const codes = result.diagnostics.map((d) => d.code);
expect(codes).toContain("DEADLOCK_TRIGGER_STATE_FILTER");
expect(result.diagnostics.find((d) => d.code === "DEADLOCK_TRIGGER_STATE_FILTER")?.severity).toBe("error");
});
it("detects MISSING_BACKLOG_DATA_BRACKETS on backlog openapi http task", () => {
const wf = {
id: "wf-http-no-brackets",
label: "自动审批",
state: 1,
version: "1",
tasks: [
{
name: "action_1",
type: "http",
label: "审批接口调用",
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/ID01X4mbLfjvpt",
},
],
};
const result = analyzeWorkflow(wf as any);
const codes = result.diagnostics.map((d) => d.code);
expect(codes).toContain("MISSING_BACKLOG_DATA_BRACKETS");
expect(result.diagnostics.find((d) => d.code === "MISSING_BACKLOG_DATA_BRACKETS")?.severity).toBe("warning");
});
it("detects PERMISSION_MISSING_NODE when workflow uses nodes not granted to the enterprise", () => {
const wf = {
id: "wf-missing-perm",
label: "新代码节点测试",
state: 1,
version: "1",
tasks: [
{
name: "action_1",
type: "code-js2",
label: "新版JS节点",
code: "return 1;",
},
],
};
// 假设企业只开通了 code 和 http,没有开通 code-js2
const result = analyzeWorkflow(wf as any, {
availableNodeTypes: ["code", "http"],
});
const missingNodeDiag = result.diagnostics.find(
(d) => d.code === "PERMISSION_MISSING_NODE"
);
expect(missingNodeDiag).toBeDefined();
expect(missingNodeDiag?.severity).toBe("error");
expect(missingNodeDiag?.message).toContain("code-js2");
});
it("detects MISPLACED_FORMULA_IN_DATALINK_MAPPING when formulas are placed in DataLink fields", () => {
const wf = {
id: "wf-datalink-formula",
label: "台账摊销工作流",
state: 1,
version: "1",
tasks: [
{
name: "action_create",
type: "ekuaibao-datalink-create",
label: "新增摊销台账",
mapping: [
{
key: "amortizationMonth",
type: "date",
value: "AddMonths(date, 1)",
},
],
},
],
};
const result = analyzeWorkflow(wf as any);
const formulaDiag = result.diagnostics.find(
(d) => d.code === "MISPLACED_FORMULA_IN_DATALINK_MAPPING"
);
expect(formulaDiag).toBeDefined();
expect(formulaDiag?.severity).toBe("error");
expect(formulaDiag?.message).toContain("AddMonths");
expect(formulaDiag?.message).toContain("代码节点");
});
it("calculates summary metrics and classifies diagnostics into hard_block and soft_advice", () => {
const wf = {
id: "wf-summary-test",
label: "门禁分类测试",
state: 0, // -> warning (soft_advice): WORKFLOW_DISABLED
version: "1",
tasks: [
{
name: "empty_code_node",
type: "code",
label: "空代码",
code: "", // -> error (hard_block): EMPTY_CODE
},
{
name: "empty_branch_node",
type: "condition",
label: "空分支",
tasks: [], // -> warning (soft_advice): EMPTY_BRANCH
},
],
};
const result = analyzeWorkflow(wf as any);
expect(result.summary).toBeDefined();
expect(result.summary.total).toBe(3);
expect(result.summary.hardBlocks).toBe(1);
expect(result.summary.softAdvices).toBe(2);
expect(result.summary.passed).toBe(false);
const emptyCode = result.diagnostics.find((d) => d.code === "EMPTY_CODE");
expect(emptyCode?.category).toBe("hard_block");
expect(emptyCode?.severity).toBe("error");
const disabled = result.diagnostics.find((d) => d.code === "WORKFLOW_DISABLED");
expect(disabled?.category).toBe("soft_advice");
expect(disabled?.severity).toBe("warning");
const emptyBranch = result.diagnostics.find((d) => d.code === "EMPTY_BRANCH");
expect(emptyBranch?.category).toBe("soft_advice");
expect(emptyBranch?.severity).toBe("warning");
});
it("detects DOCS_DOMAIN_USED as a hard block when docs.ekuaibao.com is used in HTTP tasks", () => {
const wf = {
id: "wf-docs-domain",
label: "测试域名诊断",
state: 1,
version: "1",
tasks: [
{
name: "action_approve_wrong",
type: "http",
label: "审批节点",
url: "https://docs.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]",
},
],
};
const result = analyzeWorkflow(wf as any);
const diag = result.diagnostics.find((d) => d.code === "DOCS_DOMAIN_USED");
expect(diag).toBeDefined();
expect(diag?.category).toBe("hard_block");
expect(diag?.severity).toBe("error");
expect(diag?.message).toContain("docs.ekuaibao.com");
expect(diag?.message).toContain("app.ekuaibao.com");
expect(result.summary.hardBlocks).toBeGreaterThanOrEqual(1);
expect(result.summary.passed).toBe(false);
});
it("detects UNLICENSED_POWER_CODE when enterprise has not opened powerCode application", () => {
const wf = {
id: "wf-power-code",
label: "测试权限诊断",
state: 1,
version: "1",
tasks: [
{
name: "action_audit",
type: "http",
label: "调用单据审批",
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]?powerCode=TICKET_AUDIT_switch",
},
],
};
// openedPowerCodes does NOT include ticket_audit_switch
const result = analyzeWorkflow(wf as any, {
openedPowerCodes: ["staff_sync_switch"],
});
const diag = result.diagnostics.find((d) => d.code === "UNLICENSED_POWER_CODE");
expect(diag).toBeDefined();
expect(diag?.category).toBe("hard_block");
expect(diag?.severity).toBe("error");
expect(diag?.message).toContain("TICKET_AUDIT_switch");
expect(diag?.message).toContain("403 Forbidden");
expect(result.summary.passed).toBe(false);
});
it("passes UNLICENSED_POWER_CODE when enterprise has opened powerCode application", () => {
const wf = {
id: "wf-power-code-ok",
label: "已开通应用流程",
state: 1,
version: "1",
tasks: [
{
name: "action_audit",
type: "http",
label: "调用单据审批",
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]?powerCode=TICKET_AUDIT_switch",
},
],
};
const result = analyzeWorkflow(wf as any, {
openedPowerCodes: ["ticket_audit_switch"],
});
const hardBlock = result.diagnostics.find((d) => d.code === "UNLICENSED_POWER_CODE");
expect(hardBlock).toBeUndefined();
});
it("provides POWER_CODE_DEPENDENCY soft advice when openedPowerCodes is not provided", () => {
const wf = {
id: "wf-power-code-offline",
label: "离线分析流程",
state: 1,
version: "1",
tasks: [
{
name: "action_audit",
type: "http",
label: "调用单据审批",
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]?powerCode=TICKET_AUDIT_switch",
},
],
};
const result = analyzeWorkflow(wf as any);
const diag = result.diagnostics.find((d) => d.code === "POWER_CODE_DEPENDENCY");
expect(diag).toBeDefined();
expect(diag?.category).toBe("soft_advice");
expect(diag?.severity).toBe("warning");
});
it("diagnoses malformed powerCode encoding and continues checking later nodes", () => {
const wf = {
id: "wf-invalid-power-code-encoding",
label: "权限代码编码异常",
state: 1,
version: "1",
tasks: [
{
name: "action_invalid",
type: "http",
label: "无效权限代码",
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]?powerCode=bad%value",
},
{
name: "action_encoded",
type: "http",
label: "编码权限代码",
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/[{flowId}]?powerCode=custom%20power",
},
],
};
const result = analyzeWorkflow(wf as any);
const invalidEncoding = result.diagnostics.find((d) => d.code === "INVALID_POWER_CODE_ENCODING");
const dependency = result.diagnostics.find((d) => d.code === "POWER_CODE_DEPENDENCY");
expect(invalidEncoding?.severity).toBe("error");
expect(invalidEncoding?.category).toBe("hard_block");
expect(invalidEncoding?.path).toBe("0");
expect(invalidEncoding?.message).toContain("无效的百分号转义");
expect(dependency?.path).toBe("1");
expect(dependency?.message).toContain("custom power");
expect(result.summary.hardBlocks).toBe(1);
expect(result.summary.softAdvices).toBe(1);
});
describe("状态守卫判定", () => {
/** 构造「循环内建单(SKIP) + 条件节点 + 台账更新」的最小工作流。 */
const buildSkipWorkflow = (guardValue: string) => ({
id: "wf-guard",
label: "状态守卫校验",
state: 1,
version: "1",
tasks: [
{
name: "every_0",
type: "every",
label: "依次执行",
groupName: "control",
orderIndex: 0,
levelIndex: [0],
status: "",
tasks: [
{
name: "create_task_0",
type: "flow-create-task",
label: "创建单据",
groupName: "ekuaibao",
orderIndex: 0,
levelIndex: [0, 0],
status: "",
onError: { defaultAction: "SKIP" },
},
{
name: "condition_0",
type: "condition",
label: "是否创建成功",
groupName: "control",
orderIndex: 1,
levelIndex: [0, 1],
status: "",
combineFilters: {
condition: "and",
filters: [
{ key: guardValue, compare: "eq", value: "SUCCESS" },
],
},
// 状态守卫的典型写法:把台账更新放进条件分支内部
tasks: [
{
name: "datalink_edit_0",
type: "ekuaibao-datalink-edit",
label: "更新台账",
groupName: "ekuaibao",
orderIndex: 0,
levelIndex: [0, 1, 0],
status: "",
},
],
},
],
},
],
});
const guardCodes = (guardValue: string) =>
analyzeWorkflow(buildSkipWorkflow(guardValue) as any).diagnostics.map((d) => d.code);
it("把 ${节点名}.$status 判定为已守卫", () => {
expect(guardCodes("${create_task_0.$status}")).not.toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
});
it("把裸写 节点名.status 也判定为已守卫", () => {
expect(guardCodes("create_task_0.status")).not.toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
});
it("不因为节点名子串而误判为已守卫", () => {
// create_task_0 是另一个节点的名字前缀时,不能当成对 create_task_0 的守卫
expect(guardCodes("${create_task_0_extended.$status}")).toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
});
it("无关引用与注释文本不构成守卫", () => {
expect(guardCodes("${every_0.item.id}")).toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
});
});
describe("未知节点类型与权限证据边界", () => {
const build = (type: string) => ({
id: "wf-node-type",
label: "节点类型校验",
state: 1,
version: "1",
tasks: [
{
name: "task_0",
type,
label: "被测节点",
groupName: "action",
orderIndex: 0,
levelIndex: [0],
status: "",
},
],
});
it("对未收录的节点类型给出软建议", () => {
const codes = analyzeWorkflow(build("brand-new-node") as any).diagnostics.map((d) => d.code);
expect(codes).toContain("UNKNOWN_TASK_TYPE");
});
it("已收录的节点类型不产生该建议", () => {
const codes = analyzeWorkflow(build("http") as any).diagnostics.map((d) => d.code);
expect(codes).not.toContain("UNKNOWN_TASK_TYPE");
});
it("拿不到开通清单时既不谎报通过也不误报缺失", () => {
const codes = analyzeWorkflow(build("code-js2") as any, { availableNodeTypes: [] })
.diagnostics.map((d) => d.code);
expect(codes).not.toContain("PERMISSION_MISSING_NODE");
});
});
});