From 6c69dd78ded8e71e3d81a7aab0a4155a7e0c843a Mon Sep 17 00:00:00 2001 From: yunyingk Date: Sun, 13 Sep 2026 22:08:26 +0800 Subject: [PATCH] Isolate regression test CLI unit tests with mock environment --- src/cli/commands/test.test.ts | 202 ++++++++++++++++++++++++++++++++-- 1 file changed, 195 insertions(+), 7 deletions(-) diff --git a/src/cli/commands/test.test.ts b/src/cli/commands/test.test.ts index 87cf986..7b563a7 100644 --- a/src/cli/commands/test.test.ts +++ b/src/cli/commands/test.test.ts @@ -1,22 +1,207 @@ -import { describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { CorpConfig } from "../../core/config/types.js"; import { runCli } from "../runner.js"; +const ORIGINAL_ENV = { + enterprises: process.env.SEAL_USE_ENTERPRISES_DIR, + config: process.env.SEAL_USE_CONFIG_FILE, + tokenStore: process.env.SEAL_USE_TOKEN_STORE +}; +const ORIGINAL_FETCH = globalThis.fetch; +const tempDirs: string[] = []; + +afterEach(() => { + restoreEnv("SEAL_USE_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises); + restoreEnv("SEAL_USE_CONFIG_FILE", ORIGINAL_ENV.config); + restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore); + globalThis.fetch = ORIGINAL_FETCH; + + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +function restoreEnv(name: string, value: string | undefined) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; +} + +const mockApprovalRuns = [ + { + id: "run-001", + status: "completed", + sourceSystem: "hosecloud", + sourceDocumentSN: "BX9990001", + sourceDocumentId: "DOC-999", + createdAt: 1789115000000, + result: { decision: "APPROVE", summary: "合规通过" }, + document: { + id: "DOC-999", + sn: "BX9990001", + fields: [ + { key: "cost_type", label: "费用类型", type: "TEXT", value: "打车" }, + { key: "amount", label: "金额", type: "AMOUNT", value: { amount: 120 } } + ] + } + }, + { + id: "run-002", + status: "completed", + sourceSystem: "hosecloud", + sourceDocumentSN: "BX9990002", + sourceDocumentId: "DOC-998", + createdAt: 1789115100000, + result: { decision: "REJECT", summary: "超标" }, + document: { + id: "DOC-998", + sn: "BX9990002", + fields: [ + { key: "cost_type", label: "费用类型", type: "TEXT", value: "住宿" }, + { key: "amount", label: "金额", type: "AMOUNT", value: { amount: 800 } } + ] + } + } +]; + +function setupTestEnv() { + const root = mkdtempSync(join(tmpdir(), "seal-use-test-cli-")); + const enterprises = join(root, "enterprises"); + mkdirSync(enterprises, { recursive: true }); + tempDirs.push(root); + + process.env.SEAL_USE_ENTERPRISES_DIR = enterprises; + process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json"); + process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json"); + + const prodCorp: CorpConfig = { + id: "corp-prod", + name: "生产企业", + environment: "production", + testCorpId: "corp-test", + seal: { + url: "https://acme-prod.sealai.cc", + endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } + }, + source: { + type: "seal", + token: "prod-token", + sealUrl: "https://acme-prod.sealai.cc", + expiresIn: 3600, + staffId: "seal" + }, + auth: { refreshTtl: 300 } + }; + + const testCorp: CorpConfig = { + id: "corp-test", + name: "测试靶场企业", + environment: "test", + prodCorpId: "corp-prod", + seal: { + url: "https://acme-test.sealai.cc", + endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } + }, + source: { + type: "seal", + token: "test-token", + sealUrl: "https://acme-test.sealai.cc", + expiresIn: 3600, + staffId: "seal" + }, + auth: { refreshTtl: 300 } + }; + + const unpairedCorp: CorpConfig = { + id: "corp-unpaired", + name: "未配对企业", + environment: "production", + seal: { + url: "https://acme-unpaired.sealai.cc", + endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } + }, + source: { + type: "seal", + token: "unpaired-token", + sealUrl: "https://acme-unpaired.sealai.cc", + expiresIn: 3600, + staffId: "seal" + }, + auth: { refreshTtl: 300 } + }; + + writeFileSync(join(enterprises, "corp-prod.json"), JSON.stringify(prodCorp, null, 2)); + writeFileSync(join(enterprises, "corp-test.json"), JSON.stringify(testCorp, null, 2)); + writeFileSync(join(enterprises, "corp-unpaired.json"), JSON.stringify(unpairedCorp, null, 2)); + + writeFileSync( + join(root, "config.json"), + JSON.stringify({ defaultCorpId: "corp-prod", stateful: true }, null, 2) + ); + + return { root, enterprises, prodCorp, testCorp, unpairedCorp }; +} + +function mockApiFetch() { + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + + if (url.includes("/api/v1/billing/status")) { + return new Response( + JSON.stringify({ + data: { + features: [ + { + code: "ai-approval", + balance: 5000, + deductionAmount: 100 + } + ] + } + }), + { status: 200, headers: { "Content-Type": "application/json" } } + ); + } + + if (url.includes("/api/v1/approvals")) { + return new Response( + JSON.stringify({ + data: { + records: mockApprovalRuns, + total: mockApprovalRuns.length + } + }), + { status: 200, headers: { "Content-Type": "application/json" } } + ); + } + + return new Response("Not found", { status: 404 }); + }) as any; +} + describe("seal-use test regression CLI", () => { test("fails with exit code 2 when unknown subaction is requested", async () => { + setupTestEnv(); const result = await runCli(["test", "invalid-action"]); expect(result.exitCode).toBe(2); expect(result.stderr).toContain("未知的 test 子命令"); }); test("rejects when production enterprise has no bound test enterprise", async () => { - const result = await runCli(["test", "regression", "--corp", "ID01Nl1kQVYbKL"]); + setupTestEnv(); + const result = await runCli(["test", "regression", "--corp", "corp-unpaired"]); expect(result.exitCode).toBe(2); expect(result.stderr).toContain("未绑定测试靶场企业"); expect(result.stderr).toContain("硬性规定:回归测试严禁在生产环境直接运行"); }); test("executes dry-run regression preview on paired test enterprise", async () => { - const result = await runCli(["test", "regression", "--corp", "xiezihao", "--samples", "2", "--dry-run"]); + setupTestEnv(); + mockApiFetch(); + + const result = await runCli(["test", "regression", "--corp", "corp-test", "--samples", "2", "--dry-run"]); expect(result.exitCode).toBe(0); const payload = JSON.parse(result.stdout); @@ -24,8 +209,8 @@ describe("seal-use test regression CLI", () => { expect(payload.verdict).toBe("DRY_RUN"); expect(payload.safeToPublish).toBe(true); expect(payload.metrics.sampleCount).toBe(2); - expect(payload.sourceCorp.id).toBe("LyG3iezucw03fs"); - expect(payload.targetCorp.id).toBe("xiezihao"); + expect(payload.sourceCorp.id).toBe("corp-prod"); + expect(payload.targetCorp.id).toBe("corp-test"); expect(payload.records.length).toBe(2); expect(result.stderr).toContain("规则回归测试矩阵"); @@ -33,11 +218,14 @@ describe("seal-use test regression CLI", () => { }); test("corps regression alias routes to test regression command", async () => { - const result = await runCli(["corps", "regression", "--corp", "xiezihao", "--samples", "2", "--dry-run"]); + setupTestEnv(); + mockApiFetch(); + + const result = await runCli(["corps", "regression", "--corp", "corp-test", "--samples", "2", "--dry-run"]); expect(result.exitCode).toBe(0); const payload = JSON.parse(result.stdout); expect(payload.verdict).toBe("DRY_RUN"); - expect(payload.targetCorp.id).toBe("xiezihao"); + expect(payload.targetCorp.id).toBe("corp-test"); }); });