import { afterEach, expect, test } from "bun:test"; import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { handleWhoami } from "./whoami.js"; import { saveCorpConfig } from "../../../core/config/loader.js"; import { CorpConfigSchema } from "../../../core/config/types.js"; import { CorpContext } from "../../../core/config/manager.js"; import { parseArgs } from "../../parser.js"; import type { CliRuntime } from "../../types.js"; const originalFetch = globalThis.fetch; const originalEnv = { ...process.env }; const directories: string[] = []; afterEach(() => { globalThis.fetch = originalFetch; process.env = { ...originalEnv }; for (const dir of directories.splice(0)) rmSync(dir, { recursive: true, force: true }); }); function fixture() { const dir = mkdtempSync(join(tmpdir(), "hose-whoami-scope-")); directories.push(dir); process.env.HOSE_ENTERPRISES_DIR = dir; process.env.HOSE_USER_ENTERPRISES_DIR = dir; process.env.HOSE_CONFIG_FILE = join(dir, "config.json"); const corps = ["one", "two"].map(id => CorpConfigSchema.parse({ id, name: id, source: "manual", baseUrl: "https://tenant.invalid", credentials: { accessToken: "fake", corpId: id, staffId: `staff-${id}` } })); for (const corp of corps) saveCorpConfig(corp, dir); const requests: string[] = []; globalThis.fetch = (async (input: Request) => { requests.push(new URL(input.url).searchParams.get("corpId")!); return Response.json({ value: { staff: { name: "Test Staff" } } }); }) as unknown as typeof fetch; const runtime: CliRuntime = { corpContext: new CorpContext(corps, { stateful: false }), selectedCorp: corps[0]!, jsonMode: true }; return { runtime, requests }; } test("显式企业只查询该企业;不带企业时保留全企业身份查看", async () => { const f = fixture(); const selected = await handleWhoami(parseArgs(["corps", "whoami", "--corp=one", "--json"]), f.runtime); expect(f.requests).toEqual(["one"]); expect(JSON.parse(selected.stdout).corporations.map((c: { id: string }) => c.id)).toEqual(["one"]); f.requests.length = 0; await handleWhoami(parseArgs(["corps", "whoami", "--json"]), f.runtime); expect(f.requests.sort()).toEqual(["one", "two"]); }); test("无效企业不退回全量查询;离线模式不请求网络", async () => { const f = fixture(); await expect(handleWhoami(parseArgs(["corps", "whoami", "--corp=missing"]), { ...f.runtime, selectedCorp: null })).rejects.toThrow("未找到企业"); const result = await handleWhoami(parseArgs(["corps", "whoami", "--corp=one", "--offline", "--json"]), f.runtime); expect(JSON.parse(result.stdout).corporations).toHaveLength(1); expect(f.requests).toEqual([]); });