File size: 12,315 Bytes
4e7644b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { request } from "./request";

// mock config so URL is predictable and token is empty by default
vi.mock("./config", () => ({
  getApiUrl: (path: string) => `/api${path}`,
  getApiToken: vi.fn(() => ""),
  clearAuthToken: vi.fn(),
}));

vi.mock("./authHeaders", () => ({
  buildAuthHeaders: vi.fn(() => ({})),
}));

import { clearAuthToken } from "./config";
import { buildAuthHeaders } from "./authHeaders";

// Helper: create a mock Response
function mockFetch(
  status: number,
  body?: unknown,
  contentType = "application/json",
) {
  const responseBody =
    body !== undefined
      ? typeof body === "string"
        ? body
        : JSON.stringify(body)
      : "";

  global.fetch = vi.fn().mockResolvedValue({
    ok: status >= 200 && status < 300,
    status,
    statusText:
      status === 200 ? "OK" : status === 401 ? "Unauthorized" : "Error",
    headers: { get: () => contentType },
    json: () => Promise.resolve(body),
    text: () => Promise.resolve(responseBody),
  } as unknown as Response);
}

describe("request", () => {
  beforeEach(() => {
    vi.mocked(buildAuthHeaders).mockReturnValue({});
    Object.defineProperty(window, "location", {
      value: { pathname: "/chat", search: "", hash: "", href: "" },
      writable: true,
    });
  });

  afterEach(() => {
    vi.clearAllMocks();
  });

  // ---------------------------------------------------------------------------
  // Successful requests
  // ---------------------------------------------------------------------------

  it("GET request does not set Content-Type", async () => {
    mockFetch(200, { data: "ok" });
    await request("/models");
    const headers: Headers = (fetch as any).mock.calls[0][1].headers;
    expect(headers.has("Content-Type")).toBe(false);
  });

  it("POST request automatically adds Content-Type: application/json", async () => {
    mockFetch(200, { data: "ok" });
    await request("/models", { method: "POST", body: "{}" });
    const headers: Headers = (fetch as any).mock.calls[0][1].headers;
    expect(headers.get("Content-Type")).toBe("application/json");
  });

  it("PUT request automatically adds Content-Type", async () => {
    mockFetch(200, { status: "ok" });
    await request("/models/active", { method: "PUT", body: "{}" });
    const headers: Headers = (fetch as any).mock.calls[0][1].headers;
    expect(headers.get("Content-Type")).toBe("application/json");
  });

  it("caller-specified Content-Type is not overridden", async () => {
    mockFetch(200, { status: "ok" });
    await request("/upload", {
      method: "POST",
      headers: { "Content-Type": "multipart/form-data" },
    });
    const headers: Headers = (fetch as any).mock.calls[0][1].headers;
    expect(headers.get("Content-Type")).toBe("multipart/form-data");
  });

  it("correctly parses and returns JSON response", async () => {
    mockFetch(200, { id: 1, name: "test" });
    const result = await request<{ id: number; name: string }>("/models");
    expect(result).toEqual({ id: 1, name: "test" });
  });

  it("returns text for non-JSON Content-Type", async () => {
    mockFetch(200, "plain text response", "text/plain");
    const result = await request("/health");
    expect(result).toBe("plain text response");
  });

  it("204 response returns undefined", async () => {
    mockFetch(204, undefined, "");
    const result = await request("/models/active");
    expect(result).toBeUndefined();
  });

  // ---------------------------------------------------------------------------
  // Error handling
  // ---------------------------------------------------------------------------

  it("calls clearAuthToken and redirects to /login on 401", async () => {
    mockFetch(401);
    await expect(request("/models")).rejects.toThrow("Not authenticated");
    expect(clearAuthToken).toHaveBeenCalledOnce();
    expect(window.location.href).toBe("/login?redirect=%2Fchat");
  });

  it("preserves OS paths and the console basename on 401", async () => {
    window.location.pathname = "/console/os/apps/office";
    mockFetch(401);
    await expect(request("/models")).rejects.toThrow("Not authenticated");
    expect(window.location.href).toBe(
      "/console/login?redirect=%2Fos%2Fapps%2Foffice",
    );
  });

  it("does not redirect again when already on /login for 401", async () => {
    window.location.pathname = "/console/login";
    window.location.href = "";
    mockFetch(401);
    await expect(request("/models")).rejects.toThrow("Not authenticated");
    expect(window.location.href).toBe("");
  });

  it("throws error with status code for non-401 errors", async () => {
    global.fetch = vi.fn().mockResolvedValue({
      ok: false,
      status: 500,
      statusText: "Internal Server Error",
      headers: { get: () => "application/json" },
      text: () => Promise.resolve("server exploded"),
    } as unknown as Response);

    await expect(request("/models")).rejects.toThrow("server exploded");
  });

  it("injects Authorization header when token is present", async () => {
    vi.mocked(buildAuthHeaders).mockReturnValue({
      Authorization: "Bearer test-token",
    });
    mockFetch(200, {});
    await request("/models");
    const headers: Headers = (fetch as any).mock.calls[0][1].headers;
    expect(headers.get("Authorization")).toBe("Bearer test-token");
  });

  it("request URL is correctly built by getApiUrl", async () => {
    mockFetch(200, {});
    await request("/models/active");
    expect(fetch).toHaveBeenCalledWith(
      "/api/models/active",
      expect.any(Object),
    );
  });

  // ---------------------------------------------------------------------------
  // Timeout handling
  // ---------------------------------------------------------------------------

  it("aborts request after default timeout (30s)", async () => {
    vi.useFakeTimers();
    const abortSpy = vi.spyOn(AbortController.prototype, "abort");

    global.fetch = vi.fn().mockImplementation((_url, options) => {
      return new Promise((_resolve, reject) => {
        // Listen for abort signal
        if (options?.signal) {
          options.signal.addEventListener("abort", () => {
            reject(new DOMException("The operation was aborted", "AbortError"));
          });
        }
      });
    });

    const requestPromise = request("/slow-endpoint");
    vi.advanceTimersByTime(30000);

    await expect(requestPromise).rejects.toThrow("Request timeout");
    expect(abortSpy).toHaveBeenCalled();

    abortSpy.mockRestore();
    vi.useRealTimers();
  });

  it("respects custom timeout option", async () => {
    vi.useFakeTimers();
    const abortSpy = vi.spyOn(AbortController.prototype, "abort");

    global.fetch = vi.fn().mockImplementation((_url, options) => {
      return new Promise((_resolve, reject) => {
        if (options?.signal) {
          options.signal.addEventListener("abort", () => {
            reject(new DOMException("The operation was aborted", "AbortError"));
          });
        }
      });
    });

    const requestPromise = request("/slow-endpoint", { timeout: 5000 });
    vi.advanceTimersByTime(5000);

    await expect(requestPromise).rejects.toThrow("Request timeout");
    expect(abortSpy).toHaveBeenCalled();

    abortSpy.mockRestore();
    vi.useRealTimers();
  });

  it("completes successfully before timeout", async () => {
    vi.useFakeTimers();
    mockFetch(200, { data: "ok" });

    const requestPromise = request("/fast-endpoint", { timeout: 10000 });
    vi.advanceTimersByTime(100);

    const result = await requestPromise;
    expect(result).toEqual({ data: "ok" });

    vi.useRealTimers();
  });

  it("passes AbortSignal to fetch", async () => {
    mockFetch(200, { data: "ok" });
    await request("/models");

    const fetchOptions = (fetch as any).mock.calls[0][1];
    expect(fetchOptions.signal).toBeDefined();
    expect(fetchOptions.signal).toBeInstanceOf(AbortSignal);
  });

  it("retries on timeout when retries option is set", async () => {
    vi.useFakeTimers();
    let attemptCount = 0;

    global.fetch = vi.fn().mockImplementation((_url, options) => {
      attemptCount++;
      return new Promise((_resolve, reject) => {
        if (options?.signal) {
          options.signal.addEventListener("abort", () => {
            reject(new DOMException("The operation was aborted", "AbortError"));
          });
        }
      });
    });

    const requestPromise = request("/flaky-endpoint", {
      timeout: 1000,
      retries: 2,
      retryDelay: 100,
    });

    // First attempt timeout
    vi.advanceTimersByTime(1000);
    await vi.advanceTimersByTimeAsync(100); // retry delay

    // Second attempt timeout
    vi.advanceTimersByTime(1000);
    await vi.advanceTimersByTimeAsync(100); // retry delay

    // Third attempt timeout
    vi.advanceTimersByTime(1000);

    await expect(requestPromise).rejects.toThrow("Request timeout");
    expect(attemptCount).toBe(3); // initial + 2 retries

    vi.useRealTimers();
  });

  it("succeeds on retry after initial timeout", async () => {
    vi.useFakeTimers();
    let attemptCount = 0;

    global.fetch = vi.fn().mockImplementation((_url, options) => {
      attemptCount++;
      return new Promise((resolve, reject) => {
        if (attemptCount === 1) {
          // First attempt: timeout
          if (options?.signal) {
            options.signal.addEventListener("abort", () => {
              reject(
                new DOMException("The operation was aborted", "AbortError"),
              );
            });
          }
        } else {
          // Second attempt: success
          resolve({
            ok: true,
            status: 200,
            statusText: "OK",
            headers: { get: () => "application/json" },
            json: () => Promise.resolve({ data: "success" }),
            text: () => Promise.resolve(JSON.stringify({ data: "success" })),
          } as unknown as Response);
        }
      });
    });

    const requestPromise = request("/flaky-endpoint", {
      timeout: 1000,
      retries: 1,
      retryDelay: 100,
    });

    // First attempt timeout
    vi.advanceTimersByTime(1000);
    await vi.advanceTimersByTimeAsync(100); // retry delay

    const result = await requestPromise;
    expect(result).toEqual({ data: "success" });
    expect(attemptCount).toBe(2);

    vi.useRealTimers();
  });

  // ---------------------------------------------------------------------------
  // External AbortSignal handling
  // ---------------------------------------------------------------------------

  it("does not send request when caller signal is already aborted", async () => {
    mockFetch(200, { data: "ok" });

    const controller = new AbortController();
    controller.abort();

    await expect(
      request("/models", { signal: controller.signal }),
    ).rejects.toThrow("aborted");

    expect(fetch).not.toHaveBeenCalled();
  });

  it("does not retry when caller manually aborts (not timeout)", async () => {
    let attemptCount = 0;

    global.fetch = vi.fn().mockImplementation((_url, options) => {
      attemptCount++;
      return new Promise((_resolve, reject) => {
        if (options?.signal) {
          options.signal.addEventListener("abort", () => {
            reject(new DOMException("The operation was aborted", "AbortError"));
          });
        }
      });
    });

    const callerController = new AbortController();
    const requestPromise = request("/cancel-endpoint", {
      timeout: 30000,
      retries: 3,
      signal: callerController.signal,
    });

    // Simulate caller aborting immediately (not a timeout)
    callerController.abort();

    await expect(requestPromise).rejects.toThrow("aborted");
    expect(attemptCount).toBe(1); // no retries for external abort
  });

  it("cleans up abort listener on caller signal after successful request", async () => {
    mockFetch(200, { data: "ok" });

    const callerController = new AbortController();
    const removeSpy = vi.spyOn(callerController.signal, "removeEventListener");

    await request("/models", { signal: callerController.signal });

    expect(removeSpy).toHaveBeenCalledWith("abort", expect.any(Function));
    removeSpy.mockRestore();
  });
});