system-config-save.test.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. codexPriorityBillingSource: "requested",
  50. timezone: null,
  51. enableAutoCleanup: false,
  52. cleanupRetentionDays: 30,
  53. cleanupSchedule: "0 3 * * *",
  54. cleanupBatchSize: 1000,
  55. enableClientVersionCheck: false,
  56. verboseProviderError: false,
  57. enableHttp2: false,
  58. interceptAnthropicWarmupRequests: false,
  59. enableThinkingSignatureRectifier: false,
  60. enableThinkingBudgetRectifier: false,
  61. enableBillingHeaderRectifier: true,
  62. enableCodexSessionIdCompletion: false,
  63. enableClaudeMetadataUserIdInjection: false,
  64. enableResponseFixer: false,
  65. responseFixerConfig: {
  66. fixEncoding: false,
  67. fixStreamingJson: false,
  68. fixEmptyResponse: false,
  69. fixContentBlockDelta: false,
  70. maxRetries: 3,
  71. timeout: 5000,
  72. },
  73. quotaDbRefreshIntervalSeconds: 60,
  74. quotaLeasePercent5h: 0.05,
  75. quotaLeasePercentDaily: 0.05,
  76. quotaLeasePercentWeekly: 0.05,
  77. quotaLeasePercentMonthly: 0.05,
  78. quotaLeaseCapUsd: null,
  79. createdAt: new Date(),
  80. updatedAt: new Date(),
  81. });
  82. });
  83. it("should return error when user is not admin", async () => {
  84. getSessionMock.mockResolvedValue({ user: { id: 1, role: "user" } });
  85. const result = await saveSystemSettings({ siteTitle: "New Title" });
  86. expect(result.ok).toBe(false);
  87. expect(result.error).toContain("无权限");
  88. expect(updateSystemSettingsMock).not.toHaveBeenCalled();
  89. });
  90. it("should return error when user is not logged in", async () => {
  91. getSessionMock.mockResolvedValue(null);
  92. const result = await saveSystemSettings({ siteTitle: "New Title" });
  93. expect(result.ok).toBe(false);
  94. expect(result.error).toContain("无权限");
  95. expect(updateSystemSettingsMock).not.toHaveBeenCalled();
  96. });
  97. it("should call updateSystemSettings with validated data", async () => {
  98. const result = await saveSystemSettings({
  99. siteTitle: "New Site Title",
  100. verboseProviderError: true,
  101. });
  102. expect(result.ok).toBe(true);
  103. expect(updateSystemSettingsMock).toHaveBeenCalledWith(
  104. expect.objectContaining({
  105. siteTitle: "New Site Title",
  106. verboseProviderError: true,
  107. })
  108. );
  109. });
  110. it("should invalidate system settings cache after successful save", async () => {
  111. await saveSystemSettings({ siteTitle: "New Title" });
  112. expect(invalidateSystemSettingsCacheMock).toHaveBeenCalled();
  113. });
  114. describe("revalidatePath locale coverage", () => {
  115. it("should revalidate paths for ALL supported locales", async () => {
  116. await saveSystemSettings({ siteTitle: "New Title" });
  117. // Collect all revalidatePath calls
  118. const calls = revalidatePathMock.mock.calls.map((call) => call[0]);
  119. // Check that each locale's settings/config path is revalidated
  120. for (const locale of locales) {
  121. const expectedSettingsPath = `/${locale}/settings/config`;
  122. expect(calls).toContain(expectedSettingsPath);
  123. }
  124. });
  125. it("should revalidate dashboard paths for ALL supported locales", async () => {
  126. await saveSystemSettings({ siteTitle: "New Title" });
  127. const calls = revalidatePathMock.mock.calls.map((call) => call[0]);
  128. // Check that each locale's dashboard path is revalidated
  129. for (const locale of locales) {
  130. const expectedDashboardPath = `/${locale}/dashboard`;
  131. expect(calls).toContain(expectedDashboardPath);
  132. }
  133. });
  134. it("should revalidate root layout", async () => {
  135. await saveSystemSettings({ siteTitle: "New Title" });
  136. // Check that root layout is revalidated
  137. expect(revalidatePathMock).toHaveBeenCalledWith("/", "layout");
  138. });
  139. it("should call revalidatePath at least 2 * locales.length + 1 times", async () => {
  140. await saveSystemSettings({ siteTitle: "New Title" });
  141. // 2 paths per locale (settings/config + dashboard) + 1 for root layout
  142. const expectedMinCalls = locales.length * 2 + 1;
  143. expect(revalidatePathMock).toHaveBeenCalledTimes(expectedMinCalls);
  144. });
  145. });
  146. it("should return updated settings on success", async () => {
  147. const mockUpdated = {
  148. id: 1,
  149. siteTitle: "Updated Title",
  150. allowGlobalUsageView: true,
  151. currencyDisplay: "USD",
  152. billingModelSource: "original",
  153. codexPriorityBillingSource: "actual",
  154. timezone: "America/New_York",
  155. enableAutoCleanup: false,
  156. cleanupRetentionDays: 30,
  157. cleanupSchedule: "0 3 * * *",
  158. cleanupBatchSize: 1000,
  159. enableClientVersionCheck: false,
  160. verboseProviderError: true,
  161. enableHttp2: true,
  162. interceptAnthropicWarmupRequests: false,
  163. enableThinkingSignatureRectifier: false,
  164. enableThinkingBudgetRectifier: false,
  165. enableBillingHeaderRectifier: true,
  166. enableCodexSessionIdCompletion: false,
  167. enableClaudeMetadataUserIdInjection: false,
  168. enableResponseFixer: false,
  169. responseFixerConfig: {
  170. fixEncoding: false,
  171. fixStreamingJson: false,
  172. fixEmptyResponse: false,
  173. fixContentBlockDelta: false,
  174. maxRetries: 3,
  175. timeout: 5000,
  176. },
  177. quotaDbRefreshIntervalSeconds: 60,
  178. quotaLeasePercent5h: 0.05,
  179. quotaLeasePercentDaily: 0.05,
  180. quotaLeasePercentWeekly: 0.05,
  181. quotaLeasePercentMonthly: 0.05,
  182. quotaLeaseCapUsd: null,
  183. createdAt: new Date(),
  184. updatedAt: new Date(),
  185. };
  186. updateSystemSettingsMock.mockResolvedValue(mockUpdated);
  187. const result = await saveSystemSettings({
  188. siteTitle: "Updated Title",
  189. allowGlobalUsageView: true,
  190. currencyDisplay: "USD",
  191. codexPriorityBillingSource: "actual",
  192. timezone: "America/New_York",
  193. verboseProviderError: true,
  194. enableHttp2: true,
  195. });
  196. expect(result.ok).toBe(true);
  197. expect(result.data).toEqual(mockUpdated);
  198. });
  199. it("should handle repository errors gracefully", async () => {
  200. updateSystemSettingsMock.mockRejectedValue(new Error("Database error"));
  201. const result = await saveSystemSettings({ siteTitle: "New Title" });
  202. expect(result.ok).toBe(false);
  203. expect(result.error).toContain("Database error");
  204. });
  205. it("should pass codexPriorityBillingSource through validation and save", async () => {
  206. const result = await saveSystemSettings({
  207. codexPriorityBillingSource: "actual",
  208. });
  209. expect(result.ok).toBe(true);
  210. expect(updateSystemSettingsMock).toHaveBeenCalledWith(
  211. expect.objectContaining({
  212. codexPriorityBillingSource: "actual",
  213. })
  214. );
  215. });
  216. });