import { describe, expect, test } from "bun:test"; import { attemptCreateDelegationWithFallback, resolveCandidateCookies, rotateBackupCookies } from "./session-fallback.js"; describe("session-fallback", () => { test("rotateBackupCookies: 初始无历史 Cookie 时返回空备份", () => { const result = rotateBackupCookies(undefined, "cookie-1"); expect(result).toEqual([]); }); test("rotateBackupCookies: 更新 Cookie 时自动归档上一份会话且排除当前 Cookie", () => { const existing = { cookie: "cookie-1", backupCookies: [] }; const result = rotateBackupCookies(existing, "cookie-2"); expect(result).toEqual(["cookie-1"]); }); test("rotateBackupCookies: 连续轮换自动去重并严格限制上限为 5 份", () => { let existing: { cookie?: string; backupCookies?: string[] } = { cookie: "cookie-1", backupCookies: [] }; for (let i = 2; i <= 8; i++) { const newCookie = `cookie-${i}`; const backups = rotateBackupCookies(existing, newCookie); existing = { cookie: newCookie, backupCookies: backups }; } expect(existing.cookie).toBe("cookie-8"); expect(existing.backupCookies?.length).toBe(5); expect(existing.backupCookies).toEqual([ "cookie-7", "cookie-6", "cookie-5", "cookie-4", "cookie-3" ]); }); test("resolveCandidateCookies: 优先返回当前主 Cookie 并依次排列历史长效备份", () => { expect(resolveCandidateCookies(undefined)).toEqual([]); expect(resolveCandidateCookies({})).toEqual([]); const result = resolveCandidateCookies({ cookie: "main-cookie", backupCookies: ["backup-1", "backup-2", "main-cookie"] }); expect(result).toEqual(["main-cookie", "backup-1", "backup-2"]); }); test("attemptCreateDelegationWithFallback: 主 Cookie 成功时直接返回结果", async () => { const tried: (string | undefined)[] = []; const res = await attemptCreateDelegationWithFallback( ["cookie-primary", "cookie-backup-1"], async (cookie) => { tried.push(cookie); return { link: "https://seal.cc/delegate?token=new", token: "new-token" }; } ); expect(res.token).toBe("new-token"); expect(tried).toEqual(["cookie-primary"]); }); test("attemptCreateDelegationWithFallback: 主 Cookie 失败时依次由备份 Cookie 兜底救险", async () => { const tried: (string | undefined)[] = []; const res = await attemptCreateDelegationWithFallback( ["expired-cookie", "valid-backup-cookie"], async (cookie) => { tried.push(cookie); if (cookie === "expired-cookie") { throw new Error("401 Unauthorized"); } return { link: "https://seal.cc/delegate?token=rescued", token: "rescued-token" }; } ); expect(res.token).toBe("rescued-token"); expect(tried).toEqual(["expired-cookie", "valid-backup-cookie"]); }); test("attemptCreateDelegationWithFallback: 全部候选失败时抛出最后的错误", async () => { await expect( attemptCreateDelegationWithFallback( ["bad-1", "bad-2"], async (cookie) => { throw new Error(`Failed with ${cookie}`); } ) ).rejects.toThrow("Failed with bad-2"); }); });