system-config-save.test.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import { beforeEach, describe, expect, it, vi } from "vitest";
  2. import { locales } from "@/i18n/config";
  3. // Mock dependencies
  4. const getSessionMock = vi.fn();
  5. const revalidatePathMock = vi.fn();
  6. const invalidateSystemSettingsCacheMock = vi.fn();
  7. const updateSystemSettingsMock = vi.fn();
  8. const getSystemSettingsMock = vi.fn();
  9. vi.mock("@/lib/auth", () => ({
  10. getSession: () => getSessionMock(),
  11. }));
  12. vi.mock("next/cache", () => ({
  13. revalidatePath: (...args: unknown[]) => revalidatePathMock(...args),
  14. }));
  15. vi.mock("@/lib/config", () => ({
  16. invalidateSystemSettingsCache: () => invalidateSystemSettingsCacheMock(),
  17. }));
  18. vi.mock("@/lib/logger", () => ({
  19. logger: {
  20. trace: vi.fn(),
  21. debug: vi.fn(),
  22. info: vi.fn(),
  23. warn: vi.fn(),
  24. error: vi.fn(),
  25. },
  26. }));
  27. vi.mock("@/lib/utils/timezone", () => ({
  28. resolveSystemTimezone: vi.fn(async () => "UTC"),
  29. isValidIANATimezone: vi.fn(() => true),
  30. }));
  31. vi.mock("@/repository/system-config", () => ({
  32. getSystemSettings: () => getSystemSettingsMock(),
  33. updateSystemSettings: (...args: unknown[]) => updateSystemSettingsMock(...args),
  34. }));
  35. // Import the action after mocks are set up
  36. import { saveSystemSettings } from "@/actions/system-config";
  37. describe("saveSystemSettings", () => {
  38. beforeEach(() => {
  39. vi.clearAllMocks();
  40. // Default: admin session
  41. getSessionMock.mockResolvedValue({ user: { id: 1, role: "admin" } });
  42. // Default: successful update
  43. updateSystemSettingsMock.mockResolvedValue({
  44. id: 1,
  45. siteTitle: "Test Site",
  46. allowGlobalUsageView: false,
  47. currencyDisplay: "CNY",
  48. billingModelSource: "original",
  49. timezone: null,
  50. enableAutoCleanup: false,
  51. cleanupRetentionDays: 30,
  52. cleanupSchedule: "0 3 * * *",
  53. cleanupBatchSize: 1000,
  54. enableClientVersionCheck: false,
  55. verboseProviderError: false,
  56. enableHttp2: false,
  57. interceptAnthropicWarmupRequests: false,
  58. enableThinkingSignatureRectifier: false,
  59. enableThinkingBudgetRectifier: false,
  60. enableBillingHeaderRectifier: true,
  61. enableCodexSessionIdCompletion: false,
  62. enableClaudeMetadataUserIdInjection: false,
  63. enableResponseFixer: false,
  64. responseFixerConfig: {
  65. fixEncoding: false,
  66. fixStreamingJson: false,
  67. fixEmptyResponse: false,
  68. fixContentBlockDelta: false,
  69. maxRetries: 3,
  70. timeout: 5000,
  71. },
  72. quotaDbRefreshIntervalSeconds: 60,
  73. quotaLeasePercent5h: 0.05,
  74. quotaLeasePercentDaily: 0.05,
  75. quotaLeasePercentWeekly: 0.05,
  76. quotaLeasePercentMonthly: 0.05,
  77. quotaLeaseCapUsd: null,
  78. createdAt: new Date(),
  79. updatedAt: new Date(),
  80. });
  81. });
  82. it("should return error when user is not admin", async () => {
  83. getSessionMock.mockResolvedValue({ user: { id: 1, role: "user" } });
  84. const result = await saveSystemSettings({ siteTitle: "New Title" });
  85. expect(result.ok).toBe(false);
  86. expect(result.error).toContain("无权限");
  87. expect(updateSystemSettingsMock).not.toHaveBeenCalled();
  88. });
  89. it("should return error when user is not logged in", async () => {
  90. getSessionMock.mockResolvedValue(null);
  91. const result = await saveSystemSettings({ siteTitle: "New Title" });
  92. expect(result.ok).toBe(false);
  93. expect(result.error).toContain("无权限");
  94. expect(updateSystemSettingsMock).not.toHaveBeenCalled();
  95. });
  96. it("should call updateSystemSettings with validated data", async () => {
  97. const result = await saveSystemSettings({
  98. siteTitle: "New Site Title",
  99. verboseProviderError: true,
  100. });
  101. expect(result.ok).toBe(true);
  102. expect(updateSystemSettingsMock).toHaveBeenCalledWith(
  103. expect.objectContaining({
  104. siteTitle: "New Site Title",
  105. verboseProviderError: true,
  106. })
  107. );
  108. });
  109. it("should invalidate system settings cache after successful save", async () => {
  110. await saveSystemSettings({ siteTitle: "New Title" });
  111. expect(invalidateSystemSettingsCacheMock).toHaveBeenCalled();
  112. });
  113. describe("revalidatePath locale coverage", () => {
  114. it("should revalidate paths for ALL supported locales", async () => {
  115. await saveSystemSettings({ siteTitle: "New Title" });
  116. // Collect all revalidatePath calls
  117. const calls = revalidatePathMock.mock.calls.map((call) => call[0]);
  118. // Check that each locale's settings/config path is revalidated
  119. for (const locale of locales) {
  120. const expectedSettingsPath = `/${locale}/settings/config`;
  121. expect(calls).toContain(expectedSettingsPath);
  122. }
  123. });
  124. it("should revalidate dashboard paths for ALL supported locales", async () => {
  125. await saveSystemSettings({ siteTitle: "New Title" });
  126. const calls = revalidatePathMock.mock.calls.map((call) => call[0]);
  127. // Check that each locale's dashboard path is revalidated
  128. for (const locale of locales) {
  129. const expectedDashboardPath = `/${locale}/dashboard`;
  130. expect(calls).toContain(expectedDashboardPath);
  131. }
  132. });
  133. it("should revalidate root layout", async () => {
  134. await saveSystemSettings({ siteTitle: "New Title" });
  135. // Check that root layout is revalidated
  136. expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
  137. });
  138. it("should call revalidatePath at least 2 * locales.length + 1 times", async () => {
  139. await saveSystemSettings({ siteTitle: "New Title" });
  140. // 2 paths per locale (settings/config + dashboard) + 1 for root layout
  141. const expectedMinCalls = locales.length * 2 + 1;
  142. expect(revalidatePathMock).toHaveBeenCalledTimes(expectedMinCalls);
  143. });
  144. });
  145. it("should return updated settings on success", async () => {
  146. const mockUpdated = {
  147. id: 1,
  148. siteTitle: "Updated Title",
  149. allowGlobalUsageView: true,
  150. currencyDisplay: "USD",
  151. billingModelSource: "original",
  152. timezone: "America/New_York",
  153. enableAutoCleanup: false,
  154. cleanupRetentionDays: 30,
  155. cleanupSchedule: "0 3 * * *",
  156. cleanupBatchSize: 1000,
  157. enableClientVersionCheck: false,
  158. verboseProviderError: true,
  159. enableHttp2: true,
  160. interceptAnthropicWarmupRequests: false,
  161. enableThinkingSignatureRectifier: false,
  162. enableThinkingBudgetRectifier: false,
  163. enableBillingHeaderRectifier: true,
  164. enableCodexSessionIdCompletion: false,
  165. enableClaudeMetadataUserIdInjection: false,
  166. enableResponseFixer: false,
  167. responseFixerConfig: {
  168. fixEncoding: false,
  169. fixStreamingJson: false,
  170. fixEmptyResponse: false,
  171. fixContentBlockDelta: false,
  172. maxRetries: 3,
  173. timeout: 5000,
  174. },
  175. quotaDbRefreshIntervalSeconds: 60,
  176. quotaLeasePercent5h: 0.05,
  177. quotaLeasePercentDaily: 0.05,
  178. quotaLeasePercentWeekly: 0.05,
  179. quotaLeasePercentMonthly: 0.05,
  180. quotaLeaseCapUsd: null,
  181. createdAt: new Date(),
  182. updatedAt: new Date(),
  183. };
  184. updateSystemSettingsMock.mockResolvedValue(mockUpdated);
  185. const result = await saveSystemSettings({
  186. siteTitle: "Updated Title",
  187. allowGlobalUsageView: true,
  188. currencyDisplay: "USD",
  189. timezone: "America/New_York",
  190. verboseProviderError: true,
  191. enableHttp2: true,
  192. });
  193. expect(result.ok).toBe(true);
  194. expect(result.data).toEqual(mockUpdated);
  195. });
  196. it("should handle repository errors gracefully", async () => {
  197. updateSystemSettingsMock.mockRejectedValue(new Error("Database error"));
  198. const result = await saveSystemSettings({ siteTitle: "New Title" });
  199. expect(result.ok).toBe(false);
  200. expect(result.error).toContain("Database error");
  201. });
  202. });