-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathcontrol-api.test.ts
More file actions
379 lines (332 loc) · 13.8 KB
/
Copy pathcontrol-api.test.ts
File metadata and controls
379 lines (332 loc) · 13.8 KB
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
import { describe, it, expect, afterEach } from "vitest";
import * as http from "node:http";
import type { Fixture, ChatCompletionRequest } from "../types.js";
import { createServer, type ServerInstance } from "../server.js";
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function httpRequest(
url: string,
method: string,
body?: object,
): Promise<{ status: number; body: string }> {
return new Promise((resolve, reject) => {
const parsed = new URL(url);
const opts: http.RequestOptions = {
hostname: parsed.hostname,
port: parsed.port,
path: parsed.pathname + parsed.search,
method,
headers: body ? { "Content-Type": "application/json" } : undefined,
};
const req = http.request(opts, (res) => {
const chunks: Buffer[] = [];
res.on("data", (c: Buffer) => chunks.push(c));
res.on("end", () =>
resolve({
status: res.statusCode ?? 0,
body: Buffer.concat(chunks).toString(),
}),
);
});
req.on("error", reject);
if (body) req.write(JSON.stringify(body));
req.end();
});
}
function httpRaw(
url: string,
method: string,
rawBody: string,
): Promise<{ status: number; body: string }> {
return new Promise((resolve, reject) => {
const parsed = new URL(url);
const opts: http.RequestOptions = {
hostname: parsed.hostname,
port: parsed.port,
path: parsed.pathname + parsed.search,
method,
headers: { "Content-Type": "application/json" },
};
const req = http.request(opts, (res) => {
const chunks: Buffer[] = [];
res.on("data", (c: Buffer) => chunks.push(c));
res.on("end", () =>
resolve({
status: res.statusCode ?? 0,
body: Buffer.concat(chunks).toString(),
}),
);
});
req.on("error", reject);
req.write(rawBody);
req.end();
});
}
function chatRequest(userContent: string): ChatCompletionRequest {
return {
model: "gpt-4",
stream: false,
messages: [{ role: "user", content: userContent }],
};
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe("/__aimock control API", () => {
let instance: ServerInstance | undefined;
afterEach(async () => {
if (instance) {
await new Promise<void>((resolve, reject) =>
instance!.server.close((err) => (err ? reject(err) : resolve())),
);
instance = undefined;
}
});
describe("GET /__aimock/health", () => {
it("returns 200 with status ok", async () => {
instance = await createServer([]);
const res = await httpRequest(`${instance.url}/__aimock/health`, "GET");
expect(res.status).toBe(200);
expect(JSON.parse(res.body)).toEqual({ status: "ok" });
});
});
describe("POST /__aimock/fixtures", () => {
it("adds fixtures and they match requests", async () => {
const fixtures: Fixture[] = [];
instance = await createServer(fixtures);
// Add a fixture via control API
const addRes = await httpRequest(`${instance.url}/__aimock/fixtures`, "POST", {
fixtures: [{ match: { userMessage: "hello" }, response: { content: "Hi there!" } }],
});
expect(addRes.status).toBe(200);
expect(JSON.parse(addRes.body)).toEqual({ added: 1 });
// Verify the fixture works by sending a chat request
const chatRes = await httpRequest(
`${instance.url}/v1/chat/completions`,
"POST",
chatRequest("hello"),
);
expect(chatRes.status).toBe(200);
const chatBody = JSON.parse(chatRes.body);
expect(chatBody.choices[0].message.content).toBe("Hi there!");
});
it("adds multiple fixtures at once", async () => {
const fixtures: Fixture[] = [];
instance = await createServer(fixtures);
const addRes = await httpRequest(`${instance.url}/__aimock/fixtures`, "POST", {
fixtures: [
{ match: { userMessage: "a" }, response: { content: "A" } },
{ match: { userMessage: "b" }, response: { content: "B" } },
],
});
expect(addRes.status).toBe(200);
expect(JSON.parse(addRes.body)).toEqual({ added: 2 });
});
it("returns 400 for invalid JSON", async () => {
instance = await createServer([]);
const res = await httpRaw(`${instance.url}/__aimock/fixtures`, "POST", "not json{{{");
expect(res.status).toBe(400);
const body = JSON.parse(res.body);
expect(body.error).toMatch(/^Invalid JSON:/);
});
it("returns 400 when fixtures array is missing", async () => {
instance = await createServer([]);
const res = await httpRequest(`${instance.url}/__aimock/fixtures`, "POST", {
notFixtures: [],
});
expect(res.status).toBe(400);
const body = JSON.parse(res.body);
expect(body.error).toContain("fixtures");
});
it("returns 400 with details for validation errors", async () => {
instance = await createServer([]);
// A fixture with no recognized response type triggers a validation error
const res = await httpRequest(`${instance.url}/__aimock/fixtures`, "POST", {
fixtures: [{ match: { userMessage: "x" }, response: {} }],
});
expect(res.status).toBe(400);
const body = JSON.parse(res.body);
expect(body.error).toBe("Validation failed");
expect(body.details).toBeInstanceOf(Array);
expect(body.details.length).toBeGreaterThan(0);
expect(body.details[0].severity).toBe("error");
});
});
describe("DELETE /__aimock/fixtures", () => {
it("clears all fixtures", async () => {
const fixtures: Fixture[] = [
{ match: { userMessage: "hello" }, response: { content: "Hi" } },
];
instance = await createServer(fixtures);
// Verify fixture exists
expect(fixtures.length).toBe(1);
const res = await httpRequest(`${instance.url}/__aimock/fixtures`, "DELETE");
expect(res.status).toBe(200);
expect(JSON.parse(res.body)).toEqual({ cleared: true });
expect(fixtures.length).toBe(0);
});
});
describe("POST /__aimock/reset", () => {
it("clears fixtures, journal, and match counts", async () => {
const fixtures: Fixture[] = [
{ match: { userMessage: "hello" }, response: { content: "Hi" } },
];
instance = await createServer(fixtures);
// Make a request to populate journal
await httpRequest(`${instance.url}/v1/chat/completions`, "POST", chatRequest("hello"));
expect(instance.journal.size).toBeGreaterThan(0);
const res = await httpRequest(`${instance.url}/__aimock/reset`, "POST");
expect(res.status).toBe(200);
expect(JSON.parse(res.body)).toMatchObject({ reset: true });
expect(fixtures.length).toBe(0);
expect(instance.journal.size).toBe(0);
});
});
describe("POST /__aimock/reset routes", () => {
it("POST /__aimock/reset/fixtures clears fixtures and journal", async () => {
const fixtures: Fixture[] = [
{ match: { userMessage: "hello" }, response: { content: "Hi" } },
];
instance = await createServer(fixtures);
// Make a request to populate journal
await httpRequest(`${instance.url}/v1/chat/completions`, "POST", chatRequest("hello"));
expect(instance.journal.size).toBeGreaterThan(0);
const res = await httpRequest(`${instance.url}/__aimock/reset/fixtures`, "POST");
expect(res.status).toBe(200);
expect(JSON.parse(res.body)).toEqual({ reset: true });
expect(fixtures.length).toBe(0);
expect(instance.journal.size).toBe(0);
});
it("POST /__aimock/reset/journal clears journal but preserves fixtures", async () => {
const fixtures: Fixture[] = [
{ match: { userMessage: "hello" }, response: { content: "Hi" } },
];
instance = await createServer(fixtures);
// Make a request to populate journal
await httpRequest(`${instance.url}/v1/chat/completions`, "POST", chatRequest("hello"));
expect(instance.journal.size).toBeGreaterThan(0);
const before = fixtures.length;
expect(before).toBeGreaterThan(0);
const res = await httpRequest(`${instance.url}/__aimock/reset/journal`, "POST");
expect(res.status).toBe(200);
expect(JSON.parse(res.body)).toEqual({ reset: true });
expect(fixtures.length).toBe(before); // fixtures preserved
expect(instance.journal.size).toBe(0); // journal cleared
});
it("POST /__aimock/reset/journal preserves fixture match-counts while clearing entries", async () => {
const fixtures: Fixture[] = [
{ match: { userMessage: "hello" }, response: { content: "Hi" } },
];
instance = await createServer(fixtures);
// Make a request so the journal records an entry AND the fixture's
// match-count is incremented to a non-zero value.
await httpRequest(`${instance.url}/v1/chat/completions`, "POST", chatRequest("hello"));
expect(instance.journal.size).toBeGreaterThan(0);
const countBefore = instance.journal.getFixtureMatchCount(fixtures[0]);
expect(countBefore).toBeGreaterThan(0);
// Reset ONLY the journal.
const res = await httpRequest(`${instance.url}/__aimock/reset/journal`, "POST");
expect(res.status).toBe(200);
expect(JSON.parse(res.body)).toEqual({ reset: true });
// Journal entries cleared, but the fixture match-count must survive —
// clearing the journal must not rewind sequenced fixtures to index 0.
expect(instance.journal.size).toBe(0);
expect(instance.journal.getFixtureMatchCount(fixtures[0])).toBe(countBefore);
});
it("POST /__aimock/reset is a deprecated alias that still performs a full reset", async () => {
const fixtures: Fixture[] = [
{ match: { userMessage: "hello" }, response: { content: "Hi" } },
];
instance = await createServer(fixtures);
const res = await httpRequest(`${instance.url}/__aimock/reset`, "POST");
expect(res.status).toBe(200);
const body = JSON.parse(res.body);
expect(body).toMatchObject({ reset: true, deprecated: true });
expect(typeof body.deprecation).toBe("string");
expect(fixtures.length).toBe(0);
});
});
describe("DELETE /v1/_requests", () => {
it("clears journal entries while preserving fixture match-counts", async () => {
const fixtures: Fixture[] = [
{ match: { userMessage: "hello" }, response: { content: "Hi" } },
];
instance = await createServer(fixtures);
// Make a request so the journal records an entry AND the fixture's
// match-count is incremented to a non-zero value.
await httpRequest(`${instance.url}/v1/chat/completions`, "POST", chatRequest("hello"));
expect(instance.journal.size).toBeGreaterThan(0);
const countBefore = instance.journal.getFixtureMatchCount(fixtures[0]);
expect(countBefore).toBeGreaterThan(0);
// Clear ONLY the request journal entries.
const res = await httpRequest(`${instance.url}/v1/_requests`, "DELETE");
expect(res.status).toBe(204);
// Journal entries cleared, but the fixture match-count must survive —
// clearing the request log must not rewind sequenced fixtures to index 0.
expect(instance.journal.size).toBe(0);
expect(instance.journal.getFixtureMatchCount(fixtures[0])).toBe(countBefore);
});
});
describe("GET /__aimock/journal", () => {
it("returns journal entries", async () => {
const fixtures: Fixture[] = [
{ match: { userMessage: "hello" }, response: { content: "Hi" } },
];
instance = await createServer(fixtures);
// Make a request to populate journal
await httpRequest(`${instance.url}/v1/chat/completions`, "POST", chatRequest("hello"));
const res = await httpRequest(`${instance.url}/__aimock/journal`, "GET");
expect(res.status).toBe(200);
const entries = JSON.parse(res.body);
expect(entries).toBeInstanceOf(Array);
expect(entries.length).toBeGreaterThan(0);
expect(entries[0].method).toBe("POST");
expect(entries[0].path).toBe("/v1/chat/completions");
});
it("returns empty array when no requests made", async () => {
instance = await createServer([]);
const res = await httpRequest(`${instance.url}/__aimock/journal`, "GET");
expect(res.status).toBe(200);
expect(JSON.parse(res.body)).toEqual([]);
});
});
describe("POST /__aimock/error", () => {
it("queues a one-shot error", async () => {
const fixtures: Fixture[] = [
{ match: { userMessage: "hello" }, response: { content: "Hi" } },
];
instance = await createServer(fixtures);
// Queue an error
const queueRes = await httpRequest(`${instance.url}/__aimock/error`, "POST", {
status: 429,
body: { message: "Rate limited", type: "rate_limit_error" },
});
expect(queueRes.status).toBe(200);
expect(JSON.parse(queueRes.body)).toEqual({ queued: true });
// First request should get the error
const errRes = await httpRequest(
`${instance.url}/v1/chat/completions`,
"POST",
chatRequest("hello"),
);
expect(errRes.status).toBe(429);
// Second request should succeed normally
const okRes = await httpRequest(
`${instance.url}/v1/chat/completions`,
"POST",
chatRequest("hello"),
);
expect(okRes.status).toBe(200);
const body = JSON.parse(okRes.body);
expect(body.choices[0].message.content).toBe("Hi");
});
});
describe("unknown control path", () => {
it("returns 404 for unknown /__aimock/ paths", async () => {
instance = await createServer([]);
const res = await httpRequest(`${instance.url}/__aimock/unknown`, "GET");
expect(res.status).toBe(404);
});
});
});