concurrent-session-limit.test.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { describe, expect, it } from "vitest";
  2. import { resolveKeyConcurrentSessionLimit } from "@/lib/rate-limit/concurrent-session-limit";
  3. describe("resolveKeyConcurrentSessionLimit", () => {
  4. const cases: Array<{
  5. title: string;
  6. keyLimit: number | null | undefined;
  7. userLimit: number | null | undefined;
  8. expected: number;
  9. }> = [
  10. { title: "Key > 0 时应优先使用 Key", keyLimit: 10, userLimit: 15, expected: 10 },
  11. { title: "Key 为 0 时应回退到 User", keyLimit: 0, userLimit: 15, expected: 15 },
  12. { title: "Key 为 null 时应回退到 User", keyLimit: null, userLimit: 15, expected: 15 },
  13. { title: "Key 为 undefined 时应回退到 User", keyLimit: undefined, userLimit: 15, expected: 15 },
  14. {
  15. title: "Key 为 NaN 时应回退到 User",
  16. keyLimit: Number.NaN,
  17. userLimit: 15,
  18. expected: 15,
  19. },
  20. {
  21. title: "Key 为 Infinity 时应回退到 User",
  22. keyLimit: Number.POSITIVE_INFINITY,
  23. userLimit: 15,
  24. expected: 15,
  25. },
  26. { title: "Key < 0 时应回退到 User", keyLimit: -1, userLimit: 15, expected: 15 },
  27. { title: "Key 为小数时应向下取整", keyLimit: 5.9, userLimit: 15, expected: 5 },
  28. { title: "Key 小数 < 1 时应回退到 User", keyLimit: 0.9, userLimit: 15, expected: 15 },
  29. { title: "User 为小数时应向下取整", keyLimit: 0, userLimit: 7.8, expected: 7 },
  30. {
  31. title: "Key 与 User 均未设置/无效时应返回 0(无限制)",
  32. keyLimit: undefined,
  33. userLimit: null,
  34. expected: 0,
  35. },
  36. {
  37. title: "Key 为 0 且 User 为 Infinity 时应返回 0(无限制)",
  38. keyLimit: 0,
  39. userLimit: Number.POSITIVE_INFINITY,
  40. expected: 0,
  41. },
  42. ];
  43. for (const testCase of cases) {
  44. it(testCase.title, () => {
  45. expect(resolveKeyConcurrentSessionLimit(testCase.keyLimit, testCase.userLimit)).toBe(
  46. testCase.expected
  47. );
  48. });
  49. }
  50. });