import { describe, expect, test } from "bun:test"; import { authStateFrom, bytedcliBin, lastJson, profileFor } from "../src/bits_cli"; import { BitsCasesError, fetchBitsCases } from "../src/bits_cases"; /** * 控制面替建单人读 Bits 测试计划(bits_cli.ts):按人隔离的 profile、授权身份核对、 * 从 bytedcli 输出里取结果;以及失败怎么翻译成表单能分辨的状态码(bits_cases.ts)。 */ describe("bytedcli 授权状态", () => { const status = (identity: Record | null, st = "ready") => ({ status: "success", data: { bytecloud_auth: { status: st, identity, refreshTokenExpiresAt: "2026-10-21T00:00:00Z" } }, }); test("授权身份就是建单人 → authorized", () => { expect(authStateFrom(status({ username: "qa", email: "QA@example.com" }), "qa@example.com")) .toEqual({ state: "authorized", account: "QA@example.com", refreshExpiresAt: "2026-10-21T00:00:00Z" }); }); test("授权到了别人的账号上 → mismatch,不能拿来读", () => { expect(authStateFrom(status({ username: "other", email: "other@example.com" }), "qa@example.com")) .toEqual({ state: "mismatch", account: "other@example.com" }); }); test("没登录 / 状态不是 ready → unauthorized", () => { expect(authStateFrom(status(null), "qa@example.com").state).toBe("unauthorized"); expect(authStateFrom(status({ email: "qa@example.com" }, "expired"), "qa@example.com").state).toBe("unauthorized"); }); test("profile 名按人隔离、只含安全字符", () => { expect(profileFor("Jingyuan.Yi@bytedance.com")).toBe("sl-jingyuan.yi-bytedance.com"); expect(profileFor("a+b@x.io")).toBe("sl-a_b-x.io"); expect(() => profileFor("not-an-email")).toThrow(); }); test("从夹杂日志的输出里取最后一个 JSON", () => { expect(lastJson('log line\n{"status":"success","data":{"login_status":"pending"}}\n')?.data?.login_status).toBe("pending"); expect(lastJson("nothing")).toBeNull(); }); }); describe("失败翻译成状态码", () => { test("没装 bytedcli → 503,表单能说清是哪台机器缺东西", async () => { const prev = process.env.BYTEDCLI_BIN; process.env.BYTEDCLI_BIN = "/nonexistent/bytedcli"; try { expect(bytedcliBin()).toBeNull(); const err = await fetchBitsCases("qa@example.com", "https://bits.bytedance.net/devops/1/quality/plan/scenarios/planDetail/2/manualTask/3").catch((e) => e); expect(err).toBeInstanceOf(BitsCasesError); expect((err as BitsCasesError).status).toBe(503); expect((err as BitsCasesError).code).toBe("no-bytedcli"); } finally { if (prev === undefined) delete process.env.BYTEDCLI_BIN; else process.env.BYTEDCLI_BIN = prev; } }); test("认不出的链接在碰 bytedcli 之前就拦下", async () => { const err = await fetchBitsCases("qa@example.com", "https://bits.bytedance.net/devops/1/quality/case/caseDetail/2").catch((e) => e); expect((err as BitsCasesError).status).toBe(422); expect((err as Error).message).toContain("单条用例"); }); });