-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathaimock-cli.test.ts
More file actions
686 lines (592 loc) · 19.9 KB
/
Copy pathaimock-cli.test.ts
File metadata and controls
686 lines (592 loc) · 19.9 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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { execFile, type ChildProcess } from "node:child_process";
import { existsSync, mkdtempSync, writeFileSync, rmSync, symlinkSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { runAimockCli, type AimockCliDeps } from "../aimock-cli.js";
import type { AimockConfig } from "../config-loader.js";
const CLI_PATH = resolve(__dirname, "../../dist/aimock-cli.js");
const CLI_AVAILABLE = existsSync(CLI_PATH);
/** Spawn the CLI and collect stdout/stderr/exit code. */
function runCli(
args: string[],
opts: { timeout?: number } = {},
): Promise<{ stdout: string; stderr: string; code: number | null }> {
const timeout = opts.timeout ?? 5000;
return new Promise((res) => {
const cp = execFile("node", [CLI_PATH, ...args], { timeout }, (err, stdout, stderr) => {
const code = cp.exitCode ?? (err && "code" in err ? (err as { code: number }).code : null);
res({ stdout, stderr, code });
});
});
}
/**
* Spawn the CLI expecting a long-running server. Returns the child
* process plus helpers to read accumulated output and send signals.
*/
function spawnCli(args: string[]): {
cp: ChildProcess;
stdout: () => string;
stderr: () => string;
kill: (signal?: NodeJS.Signals) => void;
waitForOutput: (match: RegExp, timeoutMs?: number) => Promise<void>;
} {
let out = "";
let err = "";
const cp = execFile("node", [CLI_PATH, ...args]);
cp.stdout?.on("data", (d) => {
out += d;
});
cp.stderr?.on("data", (d) => {
err += d;
});
const waitForOutput = (match: RegExp, timeoutMs = 5000): Promise<void> =>
new Promise((resolve, reject) => {
const deadline = setTimeout(() => {
reject(new Error(`Timed out waiting for ${match} — stdout: ${out}, stderr: ${err}`));
}, timeoutMs);
const check = () => {
if (match.test(out) || match.test(err)) {
clearTimeout(deadline);
resolve();
return;
}
setTimeout(check, 50);
};
check();
});
return {
cp,
stdout: () => out,
stderr: () => err,
kill: (signal: NodeJS.Signals = "SIGTERM") => cp.kill(signal),
waitForOutput,
};
}
function makeTmpDir(): string {
return mkdtempSync(join(tmpdir(), "aimock-cli-test-"));
}
function writeConfig(dir: string, config: object, name = "aimock.json"): string {
const filePath = join(dir, name);
writeFileSync(filePath, JSON.stringify(config), "utf-8");
return filePath;
}
function writeFixtureFile(dir: string, name = "fixtures.json"): string {
const filePath = join(dir, name);
writeFileSync(
filePath,
JSON.stringify({
fixtures: [
{
match: { userMessage: "hello" },
response: { content: "Hello from aimock test!" },
},
],
}),
"utf-8",
);
return filePath;
}
/* ================================================================== */
/* Integration tests (require dist build) */
/* ================================================================== */
describe.skipIf(!CLI_AVAILABLE)("aimock CLI: --help", () => {
it("prints usage text and exits with code 0", async () => {
const { stdout, code } = await runCli(["--help"]);
expect(stdout).toContain("Usage: aimock");
expect(stdout).toContain("--config");
expect(code).toBe(0);
});
});
describe.skipIf(!CLI_AVAILABLE)("aimock CLI: argument validation", () => {
it("exits with error when --config is missing", async () => {
const { stderr, code } = await runCli([]);
expect(stderr).toContain("--config is required");
expect(code).toBe(1);
});
it("exits with error for missing config file", async () => {
const { stderr, code } = await runCli(["--config", "/nonexistent/aimock.json"]);
expect(stderr).toContain("Failed to load config");
expect(code).toBe(1);
});
});
describe.skipIf(!CLI_AVAILABLE)("aimock CLI: server lifecycle", () => {
let tmpDir: string;
beforeEach(() => {
tmpDir = makeTmpDir();
});
afterEach(() => {
rmSync(tmpDir, { recursive: true, force: true });
});
it("starts server with valid config, responds to requests, exits on SIGTERM", async () => {
const fixturePath = writeFixtureFile(tmpDir);
const configPath = writeConfig(tmpDir, {
llm: { fixtures: fixturePath },
});
const child = spawnCli(["--config", configPath]);
await child.waitForOutput(/listening on/i, 5000);
// Extract the URL from output
const match = child.stdout().match(/listening on (http:\/\/\S+)/);
expect(match).not.toBeNull();
const url = match![1];
// Verify server responds to a request
const resp = await fetch(`${url}/v1/chat/completions`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model: "gpt-4",
messages: [{ role: "user", content: "hello" }],
}),
});
expect(resp.ok).toBe(true);
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
});
it("applies port override from --port flag", async () => {
const configPath = writeConfig(tmpDir, {});
const child = spawnCli(["--config", configPath, "--port", "0"]);
await child.waitForOutput(/listening on/i, 5000);
expect(child.stdout()).toContain("listening on");
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
});
it("exits with error for invalid JSON config", async () => {
const configPath = join(tmpDir, "bad.json");
writeFileSync(configPath, "{ not json", "utf-8");
const { stderr, code } = await runCli(["--config", configPath]);
expect(stderr).toContain("Failed to load config");
expect(code).toBe(1);
});
});
describe.skipIf(!CLI_AVAILABLE)("aimock CLI: npx/bunx symlink invocation (#160)", () => {
let tmpDir: string;
let symlinkPath: string;
beforeEach(() => {
tmpDir = makeTmpDir();
symlinkPath = join(tmpDir, "aimock");
symlinkSync(CLI_PATH, symlinkPath);
});
afterEach(() => {
try {
unlinkSync(symlinkPath);
} catch {
/* already cleaned up */
}
rmSync(tmpDir, { recursive: true, force: true });
});
it("starts when invoked as 'aimock' symlink (npx/bunx scenario)", async () => {
const fixturePath = writeFixtureFile(tmpDir);
const configPath = writeConfig(tmpDir, {
llm: { fixtures: fixturePath },
});
let out = "";
let err = "";
const cp = execFile("node", [symlinkPath, "--config", configPath]);
cp.stdout?.on("data", (d: string) => {
out += d;
});
cp.stderr?.on("data", (d: string) => {
err += d;
});
// Wait for "listening" output — proves the entry-point guard fired
await new Promise<void>((resolve, reject) => {
const deadline = setTimeout(() => {
reject(new Error(`Timed out — stdout: ${out}, stderr: ${err}`));
}, 5000);
const check = () => {
if (/listening on/i.test(out) || /listening on/i.test(err)) {
clearTimeout(deadline);
resolve();
return;
}
setTimeout(check, 50);
};
check();
});
expect(out).toContain("listening on");
cp.kill("SIGTERM");
await new Promise<void>((resolve) => {
cp.on("close", () => resolve());
});
});
});
/* ================================================================== */
/* Unit tests (exercise runAimockCli directly for coverage) */
/* ================================================================== */
/** Helper: call runAimockCli with captured output and a synchronous exit stub. */
function callCli(
argv: string[],
overrides: Partial<AimockCliDeps> = {},
): { logs: string[]; errors: string[]; exitCode: number | null } {
const logs: string[] = [];
const errors: string[] = [];
let exitCode: number | null = null;
runAimockCli({
argv,
log: (msg) => logs.push(msg),
logError: (msg) => errors.push(msg),
exit: (code) => {
exitCode = code;
},
...overrides,
});
return { logs, errors, exitCode };
}
describe("runAimockCli: --help flag", () => {
it("prints help and exits 0", () => {
const { logs, exitCode } = callCli(["--help"]);
expect(exitCode).toBe(0);
expect(logs.join("\n")).toContain("Usage: aimock");
expect(logs.join("\n")).toContain("--config");
expect(logs.join("\n")).toContain("--port");
expect(logs.join("\n")).toContain("--host");
});
});
describe("runAimockCli: missing --config", () => {
it("prints error and exits 1 when no args given", () => {
const { errors, exitCode } = callCli([]);
expect(exitCode).toBe(1);
expect(errors.join("\n")).toContain("--config is required");
});
});
describe("runAimockCli: unknown flag (strict parsing)", () => {
it("prints error and exits 1 for unknown flags", () => {
const { errors, exitCode } = callCli(["--unknown-flag"]);
expect(exitCode).toBe(1);
expect(errors.join("\n")).toContain("Error:");
});
});
describe("runAimockCli: config loading failure", () => {
it("prints error and exits 1 when loadConfig throws an Error", () => {
const { errors, exitCode } = callCli(["--config", "/fake/path.json"], {
loadConfigFn: () => {
throw new Error("ENOENT: no such file");
},
});
expect(exitCode).toBe(1);
expect(errors.join("\n")).toContain("Failed to load config");
expect(errors.join("\n")).toContain("ENOENT: no such file");
});
it("handles non-Error throws from loadConfig", () => {
const { errors, exitCode } = callCli(["--config", "/fake/path.json"], {
loadConfigFn: () => {
throw "string error";
},
});
expect(exitCode).toBe(1);
expect(errors.join("\n")).toContain("string error");
});
});
describe("runAimockCli: successful server start", () => {
// Track shutdown functions so we can clean up signal handlers after each test
let cleanupFn: (() => void) | null = null;
afterEach(() => {
if (cleanupFn) {
cleanupFn();
cleanupFn = null;
}
});
it("calls startFromConfig with correct args and logs the URL", async () => {
const mockStop = vi.fn().mockResolvedValue(undefined);
const mockLlmock = { stop: mockStop };
const startFromConfigFn = vi.fn().mockResolvedValue({
llmock: mockLlmock,
url: "http://127.0.0.1:9876",
});
const loadConfigFn = vi.fn().mockReturnValue({ port: 3000 } as AimockConfig);
const logs: string[] = [];
const errors: string[] = [];
let exitCode: number | null = null;
runAimockCli({
argv: ["--config", "/some/config.json"],
log: (msg) => logs.push(msg),
logError: (msg) => errors.push(msg),
exit: (code) => {
exitCode = code;
},
loadConfigFn,
startFromConfigFn,
onReady: (ctx) => {
cleanupFn = ctx.shutdown;
},
});
// Wait for the async main() to complete
await vi.waitFor(() => {
expect(logs).toContain("aimock server listening on http://127.0.0.1:9876");
});
expect(loadConfigFn).toHaveBeenCalledWith(resolve("/some/config.json"));
expect(startFromConfigFn).toHaveBeenCalledWith(
{ port: 3000 },
{ port: undefined, host: undefined },
);
expect(exitCode).toBeNull(); // no exit — server stays running
expect(errors).toHaveLength(0);
});
it("passes port and host overrides to startFromConfig", async () => {
const startFromConfigFn = vi.fn().mockResolvedValue({
llmock: { stop: vi.fn().mockResolvedValue(undefined) },
url: "http://0.0.0.0:8080",
});
const loadConfigFn = vi.fn().mockReturnValue({} as AimockConfig);
const logs: string[] = [];
runAimockCli({
argv: ["--config", "/c.json", "--port", "8080", "--host", "0.0.0.0"],
log: (msg) => logs.push(msg),
logError: () => {},
exit: () => {},
loadConfigFn,
startFromConfigFn,
onReady: (ctx) => {
cleanupFn = ctx.shutdown;
},
});
await vi.waitFor(() => {
expect(startFromConfigFn).toHaveBeenCalled();
});
expect(startFromConfigFn).toHaveBeenCalledWith({}, { port: 8080, host: "0.0.0.0" });
});
it("passes short flags correctly (-c, -p, -h)", async () => {
const startFromConfigFn = vi.fn().mockResolvedValue({
llmock: { stop: vi.fn().mockResolvedValue(undefined) },
url: "http://localhost:5555",
});
const loadConfigFn = vi.fn().mockReturnValue({} as AimockConfig);
const logs: string[] = [];
runAimockCli({
argv: ["-c", "/c.json", "-p", "5555", "-h", "localhost"],
log: (msg) => logs.push(msg),
logError: () => {},
exit: () => {},
loadConfigFn,
startFromConfigFn,
onReady: (ctx) => {
cleanupFn = ctx.shutdown;
},
});
await vi.waitFor(() => {
expect(startFromConfigFn).toHaveBeenCalled();
});
expect(startFromConfigFn).toHaveBeenCalledWith({}, { port: 5555, host: "localhost" });
});
});
describe("runAimockCli: startFromConfig failure", () => {
it("logs error and exits 1 when startFromConfig rejects", async () => {
const startFromConfigFn = vi.fn().mockRejectedValue(new Error("bind EADDRINUSE"));
const loadConfigFn = vi.fn().mockReturnValue({} as AimockConfig);
const errors: string[] = [];
let exitCode: number | null = null;
runAimockCli({
argv: ["--config", "/c.json"],
log: () => {},
logError: (msg) => errors.push(msg),
exit: (code) => {
exitCode = code;
},
loadConfigFn,
startFromConfigFn,
});
await vi.waitFor(() => {
expect(exitCode).toBe(1);
});
expect(errors.join("\n")).toContain("bind EADDRINUSE");
});
it("handles non-Error rejection from startFromConfig", async () => {
const startFromConfigFn = vi.fn().mockRejectedValue("raw string rejection");
const loadConfigFn = vi.fn().mockReturnValue({} as AimockConfig);
const errors: string[] = [];
let exitCode: number | null = null;
runAimockCli({
argv: ["--config", "/c.json"],
log: () => {},
logError: (msg) => errors.push(msg),
exit: (code) => {
exitCode = code;
},
loadConfigFn,
startFromConfigFn,
});
await vi.waitFor(() => {
expect(exitCode).toBe(1);
});
expect(errors.join("\n")).toContain("raw string rejection");
});
});
describe("runAimockCli: onReady and shutdown", () => {
let cleanupFn: (() => void) | null = null;
afterEach(() => {
if (cleanupFn) {
cleanupFn();
cleanupFn = null;
}
});
it("invokes onReady callback after server starts", async () => {
const mockStop = vi.fn().mockResolvedValue(undefined);
const startFromConfigFn = vi.fn().mockResolvedValue({
llmock: { stop: mockStop },
url: "http://127.0.0.1:0",
});
const loadConfigFn = vi.fn().mockReturnValue({} as AimockConfig);
runAimockCli({
argv: ["--config", "/c.json"],
log: () => {},
logError: () => {},
exit: () => {},
loadConfigFn,
startFromConfigFn,
onReady: (ctx) => {
cleanupFn = ctx.shutdown;
},
});
await vi.waitFor(() => {
expect(cleanupFn).not.toBeNull();
});
});
it("shutdown calls aimock.stop()", async () => {
const mockStop = vi.fn().mockResolvedValue(undefined);
const startFromConfigFn = vi.fn().mockResolvedValue({
llmock: { stop: mockStop },
url: "http://127.0.0.1:0",
});
const loadConfigFn = vi.fn().mockReturnValue({} as AimockConfig);
const logs: string[] = [];
let shutdownFn: (() => void) | null = null;
let exitCode: number | null = null;
runAimockCli({
argv: ["--config", "/c.json"],
log: (msg) => logs.push(msg),
logError: () => {},
exit: (code) => {
exitCode = code;
},
loadConfigFn,
startFromConfigFn,
onReady: (ctx) => {
shutdownFn = ctx.shutdown;
},
});
await vi.waitFor(() => {
expect(shutdownFn).not.toBeNull();
});
// Calling shutdown removes signal handlers and stops the server
shutdownFn!();
cleanupFn = null; // Already cleaned up by shutdown
expect(logs).toContain("Shutting down...");
expect(mockStop).toHaveBeenCalled();
await vi.waitFor(() => {
expect(exitCode).toBe(0);
});
});
it("shutdown logs error and exits 1 when aimock.stop() rejects", async () => {
const mockStop = vi.fn().mockRejectedValue(new Error("close ENOTCONN"));
const startFromConfigFn = vi.fn().mockResolvedValue({
llmock: { stop: mockStop },
url: "http://127.0.0.1:0",
});
const loadConfigFn = vi.fn().mockReturnValue({} as AimockConfig);
const errors: string[] = [];
let shutdownFn: (() => void) | null = null;
let exitCode: number | null = null;
runAimockCli({
argv: ["--config", "/c.json"],
log: () => {},
logError: (msg) => errors.push(msg),
exit: (code) => {
exitCode = code;
},
loadConfigFn,
startFromConfigFn,
onReady: (ctx) => {
shutdownFn = ctx.shutdown;
},
});
await vi.waitFor(() => {
expect(shutdownFn).not.toBeNull();
});
shutdownFn!();
cleanupFn = null;
await vi.waitFor(() => {
expect(exitCode).toBe(1);
});
expect(errors.join("\n")).toContain("Shutdown error");
expect(errors.join("\n")).toContain("close ENOTCONN");
});
});
describe("runAimockCli: port parsing edge case", () => {
let cleanupFn: (() => void) | null = null;
afterEach(() => {
if (cleanupFn) {
cleanupFn();
cleanupFn = null;
}
});
it("passes undefined port when --port is not provided", async () => {
const startFromConfigFn = vi.fn().mockResolvedValue({
llmock: { stop: vi.fn().mockResolvedValue(undefined) },
url: "http://127.0.0.1:0",
});
const loadConfigFn = vi.fn().mockReturnValue({} as AimockConfig);
runAimockCli({
argv: ["--config", "/c.json"],
log: () => {},
logError: () => {},
exit: () => {},
loadConfigFn,
startFromConfigFn,
onReady: (ctx) => {
cleanupFn = ctx.shutdown;
},
});
await vi.waitFor(() => {
expect(startFromConfigFn).toHaveBeenCalled();
});
expect(startFromConfigFn).toHaveBeenCalledWith({}, { port: undefined, host: undefined });
});
it("rejects non-numeric port (NaN)", () => {
const loadConfigFn = vi.fn().mockReturnValue({} as AimockConfig);
const { errors, exitCode } = callCli(["--config", "/c.json", "--port", "abc"], {
loadConfigFn,
});
expect(exitCode).toBe(1);
expect(errors.join("\n")).toContain("invalid port");
});
it("rejects negative port", () => {
const loadConfigFn = vi.fn().mockReturnValue({} as AimockConfig);
const { errors, exitCode } = callCli(["--config", "/c.json", "--port=-1"], { loadConfigFn });
expect(exitCode).toBe(1);
expect(errors.join("\n")).toContain("invalid port");
});
it("rejects port above 65535", () => {
const loadConfigFn = vi.fn().mockReturnValue({} as AimockConfig);
const { errors, exitCode } = callCli(["--config", "/c.json", "--port", "99999"], {
loadConfigFn,
});
expect(exitCode).toBe(1);
expect(errors.join("\n")).toContain("invalid port");
});
it("converts string port to number", async () => {
const startFromConfigFn = vi.fn().mockResolvedValue({
llmock: { stop: vi.fn().mockResolvedValue(undefined) },
url: "http://127.0.0.1:4242",
});
const loadConfigFn = vi.fn().mockReturnValue({} as AimockConfig);
runAimockCli({
argv: ["--config", "/c.json", "--port", "4242"],
log: () => {},
logError: () => {},
exit: () => {},
loadConfigFn,
startFromConfigFn,
onReady: (ctx) => {
cleanupFn = ctx.shutdown;
},
});
await vi.waitFor(() => {
expect(startFromConfigFn).toHaveBeenCalled();
});
expect(startFromConfigFn).toHaveBeenCalledWith({}, { port: 4242, host: undefined });
});
});