-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathcli.test.ts
More file actions
910 lines (816 loc) · 28.8 KB
/
Copy pathcli.test.ts
File metadata and controls
910 lines (816 loc) · 28.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
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { execFile, type ChildProcess } from "node:child_process";
import { createServer as createHttpServer, type Server } from "node:http";
import { existsSync, mkdtempSync, writeFileSync, rmSync, mkdirSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { AddressInfo } from "node:net";
import { createHash } from "node:crypto";
const CLI_PATH = resolve(__dirname, "../../dist/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(), "cli-test-"));
}
function writeFixture(dir: string, name: string): string {
const filePath = join(dir, name);
writeFileSync(
filePath,
JSON.stringify({
fixtures: [
{
match: { userMessage: "hello" },
response: { content: "Hello from test fixture!" },
},
],
}),
"utf-8",
);
return filePath;
}
/* ================================================================== */
describe.skipIf(!CLI_AVAILABLE)("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("--port");
expect(stdout).toContain("--fixtures");
expect(code).toBe(0);
});
});
describe.skipIf(!CLI_AVAILABLE)("CLI: argument validation", () => {
it("rejects --port 99999 (out of range)", async () => {
const { stderr, code } = await runCli(["--port", "99999"]);
expect(stderr).toContain("Invalid port");
expect(code).toBe(1);
});
it("rejects --port=-1 (negative)", async () => {
const { stderr, code } = await runCli(["--port=-1"]);
expect(stderr).toContain("Invalid port");
expect(code).toBe(1);
});
it("rejects --latency=-5 (negative)", async () => {
const { stderr, code } = await runCli(["--latency=-5"]);
expect(stderr).toContain("Invalid latency");
expect(code).toBe(1);
});
it("rejects --chunk-size 0 (below minimum)", async () => {
const { stderr, code } = await runCli(["--chunk-size", "0"]);
expect(stderr).toContain("Invalid chunk-size");
expect(code).toBe(1);
});
it("rejects --journal-max=-5 (negative)", async () => {
const { stderr, code } = await runCli(["--journal-max=-5"]);
expect(stderr).toContain("Invalid journal-max");
expect(stderr).toContain("non-negative");
expect(code).toBe(1);
});
it("rejects --journal-max=-1 (negative)", async () => {
const { stderr, code } = await runCli(["--journal-max=-1"]);
expect(stderr).toContain("Invalid journal-max");
expect(code).toBe(1);
});
it("rejects --journal-max 1.5 (non-integer)", async () => {
const { stderr, code } = await runCli(["--journal-max", "1.5"]);
expect(stderr).toContain("Invalid journal-max");
expect(code).toBe(1);
});
it("rejects --fixture-counts-max=-1 (negative)", async () => {
const { stderr, code } = await runCli(["--fixture-counts-max=-1"]);
expect(stderr).toContain("Invalid fixture-counts-max");
expect(stderr).toContain("non-negative");
expect(code).toBe(1);
});
});
describe.skipIf(!CLI_AVAILABLE)("CLI: fixture loading", () => {
let tmpDir: string;
beforeEach(() => {
tmpDir = makeTmpDir();
});
afterEach(() => {
rmSync(tmpDir, { recursive: true, force: true });
});
it("starts server with a valid fixture file, then exits cleanly on SIGTERM", async () => {
const fixturePath = writeFixture(tmpDir, "test.json");
const child = spawnCli(["--fixtures", fixturePath, "--port", "0"]);
await child.waitForOutput(/listening on/i, 5000);
expect(child.stdout()).toContain("Loaded 1 fixture(s)");
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", (code) => {
expect(code).toBe(0);
resolve();
});
});
});
it("fails with error when --fixtures points to a non-existent path", async () => {
const { stderr, code } = await runCli(["--fixtures", "/nonexistent/path/to/fixtures"]);
expect(stderr).toContain("Fixtures path not found");
expect(code).toBe(1);
});
});
describe.skipIf(!CLI_AVAILABLE)("CLI: --log-level", () => {
let tmpDir: string;
beforeEach(() => {
tmpDir = makeTmpDir();
});
afterEach(() => {
rmSync(tmpDir, { recursive: true, force: true });
});
it("--log-level silent suppresses startup output", async () => {
const fixturePath = writeFixture(tmpDir, "test.json");
const child = spawnCli(["--fixtures", fixturePath, "--port", "0", "--log-level", "silent"]);
// Wait for the server to be ready (listen on port)
// With silent, there should be no [aimock] output
await new Promise((r) => setTimeout(r, 1500));
const stdout = child.stdout();
expect(stdout).not.toContain("[aimock]");
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
});
it("--log-level info shows startup messages", async () => {
const fixturePath = writeFixture(tmpDir, "test.json");
const child = spawnCli(["--fixtures", fixturePath, "--port", "0", "--log-level", "info"]);
await child.waitForOutput(/listening on/i, 5000);
expect(child.stdout()).toContain("[aimock]");
expect(child.stdout()).toContain("Loaded 1 fixture(s)");
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
});
it("--log-level debug starts successfully", async () => {
const fixturePath = writeFixture(tmpDir, "test.json");
const child = spawnCli(["--fixtures", fixturePath, "--port", "0", "--log-level", "debug"]);
await child.waitForOutput(/listening on/i, 5000);
expect(child.stdout()).toContain("[aimock]");
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
});
it("rejects invalid --log-level value", async () => {
const { stderr, code } = await runCli(["--log-level", "verbose"]);
expect(stderr).toContain("Invalid log-level");
expect(code).toBe(1);
});
});
describe.skipIf(!CLI_AVAILABLE)("CLI: --validate-on-load", () => {
let tmpDir: string;
beforeEach(() => {
tmpDir = makeTmpDir();
});
afterEach(() => {
rmSync(tmpDir, { recursive: true, force: true });
});
it("passes validation for valid fixtures", async () => {
const fixturePath = writeFixture(tmpDir, "test.json");
const child = spawnCli(["--fixtures", fixturePath, "--port", "0", "--validate-on-load"]);
await child.waitForOutput(/listening on/i, 5000);
expect(child.stderr()).not.toContain("Validation failed");
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
});
it("exits 1 on invalid fixture (empty content)", async () => {
const filePath = join(tmpDir, "bad.json");
writeFileSync(
filePath,
JSON.stringify({
fixtures: [
{
match: { userMessage: "hello" },
response: { content: "" },
},
],
}),
"utf-8",
);
const { stderr, code } = await runCli(["--fixtures", filePath, "--validate-on-load"]);
expect(stderr).toContain("Validation failed");
expect(code).toBe(1);
});
it("exits 1 on invalid fixture (unparseable toolCalls arguments)", async () => {
const filePath = join(tmpDir, "bad-tool.json");
writeFileSync(
filePath,
JSON.stringify({
fixtures: [
{
match: { userMessage: "weather" },
response: {
toolCalls: [{ name: "get_weather", arguments: "not json" }],
},
},
],
}),
"utf-8",
);
const { stderr, code } = await runCli(["--fixtures", filePath, "--validate-on-load"]);
expect(stderr).toContain("Validation failed");
expect(code).toBe(1);
});
});
describe.skipIf(!CLI_AVAILABLE)("CLI: --watch", () => {
let tmpDir: string;
beforeEach(() => {
tmpDir = makeTmpDir();
});
afterEach(() => {
rmSync(tmpDir, { recursive: true, force: true });
});
it("survives invalid JSON during reload", async () => {
const fixturePath = writeFixture(tmpDir, "test.json");
const child = spawnCli(["--fixtures", fixturePath, "--port", "0", "--watch"]);
await child.waitForOutput(/listening on/i, 5000);
// Write invalid JSON
writeFileSync(fixturePath, "{ not valid json", "utf-8");
// Wait for the reload attempt — server should stay up
await new Promise((r) => setTimeout(r, 1500));
// Server should still be running (not crashed)
expect(child.cp.exitCode).toBeNull();
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
});
it("reloads fixtures when file changes", async () => {
const fixturePath = writeFixture(tmpDir, "test.json");
const child = spawnCli(["--fixtures", fixturePath, "--port", "0", "--watch"]);
await child.waitForOutput(/listening on/i, 5000);
expect(child.stdout()).toContain("Watching");
// Modify the fixture file
writeFileSync(
fixturePath,
JSON.stringify({
fixtures: [
{
match: { userMessage: "goodbye" },
response: { content: "Bye!" },
},
],
}),
"utf-8",
);
// Wait for reload
await child.waitForOutput(/Reloaded/i, 5000);
expect(child.stdout()).toContain("Reloaded 1 fixture(s)");
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
});
});
/* ================================================================== */
/* Remote --fixtures URL support */
/* ================================================================== */
interface HttpHandle {
server: Server;
url: string;
close: () => Promise<void>;
}
function startHttpServer(
handler: (
req: import("node:http").IncomingMessage,
res: import("node:http").ServerResponse,
) => void,
): Promise<HttpHandle> {
return new Promise((res) => {
const server = createHttpServer(handler);
server.listen(0, "127.0.0.1", () => {
const addr = server.address() as AddressInfo;
res({
server,
url: `http://127.0.0.1:${addr.port}`,
close: () =>
new Promise<void>((r) => {
server.close(() => r());
}),
});
});
});
}
const REMOTE_FIXTURE_BODY = JSON.stringify({
fixtures: [
{
match: { userMessage: "hello-remote" },
response: { content: "Hello from remote fixture" },
},
],
});
describe.skipIf(!CLI_AVAILABLE)("CLI: remote --fixtures URLs", () => {
let cacheDir: string;
let envBackup: string | undefined;
let allowPrivateBackup: string | undefined;
beforeEach(() => {
cacheDir = mkdtempSync(join(tmpdir(), "aimock-cli-remote-cache-"));
envBackup = process.env.XDG_CACHE_HOME;
process.env.XDG_CACHE_HOME = cacheDir;
// The remote-fixture SSRF denylist rejects 127.0.0.1 by default; these
// tests fetch from local http servers, so opt in for the subprocess.
allowPrivateBackup = process.env.AIMOCK_ALLOW_PRIVATE_URLS;
process.env.AIMOCK_ALLOW_PRIVATE_URLS = "1";
});
afterEach(() => {
if (envBackup === undefined) delete process.env.XDG_CACHE_HOME;
else process.env.XDG_CACHE_HOME = envBackup;
if (allowPrivateBackup === undefined) delete process.env.AIMOCK_ALLOW_PRIVATE_URLS;
else process.env.AIMOCK_ALLOW_PRIVATE_URLS = allowPrivateBackup;
rmSync(cacheDir, { recursive: true, force: true });
});
it("loads fixtures from an https-style URL served by a local HTTP server", async () => {
const server = await startHttpServer((_req, res) => {
setTimeout(() => {
res.writeHead(200, { "content-type": "application/json" });
res.end(REMOTE_FIXTURE_BODY);
}, 50);
});
try {
const child = spawnCli(["--fixtures", `${server.url}/fx.json`, "--port", "0"]);
await child.waitForOutput(/listening on/i, 8000);
expect(child.stdout()).toContain("Loaded 1 fixture(s)");
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
} finally {
await server.close();
}
});
it("exits non-zero when upstream returns 500 and no cache exists under --validate-on-load", async () => {
const server = await startHttpServer((_req, res) => {
res.writeHead(500);
res.end("nope");
});
try {
const { stderr, code } = await runCli(
["--fixtures", `${server.url}/fx.json`, "--port", "0", "--validate-on-load"],
{ timeout: 10000 },
);
expect(stderr).toMatch(/Failed to resolve --fixtures value/);
expect(stderr).toMatch(/HTTP 500/);
expect(code).toBe(1);
} finally {
await server.close();
}
});
it("falls back to cached copy and warns when upstream returns 500 under --validate-on-load", async () => {
const server = await startHttpServer((_req, res) => {
res.writeHead(500);
res.end("nope");
});
try {
const url = `${server.url}/fx.json`;
// Pre-seed the cache using the same sha256(url) layout as the helper.
const digest = createHash("sha256").update(url).digest("hex");
const cachedDir = join(cacheDir, "aimock", "fixtures", digest);
mkdirSync(cachedDir, { recursive: true });
writeFileSync(join(cachedDir, "fixtures.json"), REMOTE_FIXTURE_BODY, "utf-8");
const child = spawnCli(["--fixtures", url, "--port", "0", "--validate-on-load"]);
await child.waitForOutput(/listening on/i, 8000);
expect(child.stdout() + child.stderr()).toMatch(/using cached copy/);
expect(child.stdout()).toContain("Loaded 1 fixture(s)");
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
} finally {
await server.close();
}
});
it("rejects non-http(s) schemes (e.g. file://) with a clear error", async () => {
const { stderr, code } = await runCli(
["--fixtures", "file:///tmp/does-not-matter.json", "--port", "0"],
{ timeout: 5000 },
);
expect(stderr).toMatch(/Unsupported --fixtures URL scheme "file"/);
expect(code).toBe(1);
});
it("still supports a plain filesystem path (regression guard)", async () => {
const tmp = mkdtempSync(join(tmpdir(), "cli-path-regression-"));
try {
const fp = join(tmp, "local.json");
writeFileSync(fp, REMOTE_FIXTURE_BODY, "utf-8");
const child = spawnCli(["--fixtures", fp, "--port", "0"]);
await child.waitForOutput(/listening on/i, 5000);
expect(child.stdout()).toContain("Loaded 1 fixture(s)");
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
it("loads multiple --fixtures URLs and preserves argv load order", async () => {
// Fixture A responds to userMessage "alpha"; fixture B responds to "beta".
// Both are passed via repeatable --fixtures; both should be loaded and
// the count should reflect argv order (2 fixtures, A first then B).
const bodyA = JSON.stringify({
fixtures: [
{
match: { userMessage: "alpha" },
response: { content: "from A" },
},
],
});
const bodyB = JSON.stringify({
fixtures: [
{
match: { userMessage: "beta" },
response: { content: "from B" },
},
],
});
const serverA = await startHttpServer((_req, res) => {
res.writeHead(200, { "content-type": "application/json" });
res.end(bodyA);
});
const serverB = await startHttpServer((_req, res) => {
res.writeHead(200, { "content-type": "application/json" });
res.end(bodyB);
});
try {
const urlA = `${serverA.url}/a.json`;
const urlB = `${serverB.url}/b.json`;
const child = spawnCli([
"--fixtures",
urlA,
"--fixtures",
urlB,
"--port",
"0",
"--log-level",
"info",
]);
await child.waitForOutput(/listening on/i, 8000);
// Both fixtures loaded and counted.
expect(child.stdout()).toContain("Loaded 2 fixture(s)");
// Both source URLs appear in the "Loaded N fixture(s) from ..." log line —
// verifying argv order: A listed before B.
const loadedLine = child
.stdout()
.split("\n")
.find((l) => l.includes("Loaded 2 fixture(s)"));
expect(loadedLine).toBeDefined();
const idxA = loadedLine!.indexOf(urlA);
const idxB = loadedLine!.indexOf(urlB);
expect(idxA).toBeGreaterThan(-1);
expect(idxB).toBeGreaterThan(idxA);
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
} finally {
await serverA.close();
await serverB.close();
}
});
});
/* ================================================================== */
/* --proxy-only with URL-only --fixtures (v1.14.8 regression) */
/* ================================================================== */
describe.skipIf(!CLI_AVAILABLE)("CLI: --proxy-only with URL-only --fixtures", () => {
let cacheDir: string;
let envBackup: string | undefined;
let allowPrivateBackup: string | undefined;
beforeEach(() => {
cacheDir = mkdtempSync(join(tmpdir(), "aimock-cli-proxy-url-cache-"));
envBackup = process.env.XDG_CACHE_HOME;
process.env.XDG_CACHE_HOME = cacheDir;
// Remote-fixture SSRF denylist rejects 127.0.0.1 by default.
allowPrivateBackup = process.env.AIMOCK_ALLOW_PRIVATE_URLS;
process.env.AIMOCK_ALLOW_PRIVATE_URLS = "1";
});
afterEach(() => {
if (envBackup === undefined) delete process.env.XDG_CACHE_HOME;
else process.env.XDG_CACHE_HOME = envBackup;
if (allowPrivateBackup === undefined) delete process.env.AIMOCK_ALLOW_PRIVATE_URLS;
else process.env.AIMOCK_ALLOW_PRIVATE_URLS = allowPrivateBackup;
rmSync(cacheDir, { recursive: true, force: true });
});
it("starts successfully with --proxy-only and a URL-only --fixtures source", async () => {
const fixtureServer = await startHttpServer((_req, res) => {
res.writeHead(200, { "content-type": "application/json" });
res.end(REMOTE_FIXTURE_BODY);
});
// Dummy upstream provider target — proxy-only never proxies unmatched reqs in this test,
// but --provider-openai must be set so the recordConfig gate accepts the invocation.
const upstream = await startHttpServer((_req, res) => {
res.writeHead(200);
res.end("ok");
});
try {
const child = spawnCli([
"--proxy-only",
"--provider-openai",
upstream.url,
"--fixtures",
`${fixtureServer.url}/fx.json`,
"--port",
"0",
]);
await child.waitForOutput(/listening on/i, 8000);
// Must load the remote fixture and NOT error with the recordBase URL message.
expect(child.stdout()).toContain("Loaded 1 fixture(s)");
expect(child.stderr()).not.toMatch(
/requires a local --fixtures path for the recording destination/,
);
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
} finally {
await fixtureServer.close();
await upstream.close();
}
});
it("preserves --record rejection of URL-only --fixtures (regression guard)", async () => {
// --record writes to disk, so a URL source is genuinely unsupported. Must still error.
const { stderr, code } = await runCli(
[
"--record",
"--provider-openai",
"http://127.0.0.1:59999",
"--fixtures",
"http://127.0.0.1:59998/fx.json",
"--port",
"0",
],
{ timeout: 5000 },
);
expect(stderr).toMatch(/requires a local --fixtures path for the recording destination/);
expect(code).toBe(1);
});
it("accepts --proxy-only with mixed local + URL --fixtures", async () => {
const fixtureServer = await startHttpServer((_req, res) => {
res.writeHead(200, { "content-type": "application/json" });
res.end(REMOTE_FIXTURE_BODY);
});
const upstream = await startHttpServer((_req, res) => {
res.writeHead(200);
res.end("ok");
});
const tmp = mkdtempSync(join(tmpdir(), "cli-mixed-fixtures-"));
try {
const localPath = join(tmp, "local.json");
writeFileSync(
localPath,
JSON.stringify({
fixtures: [{ match: { userMessage: "local" }, response: { content: "local response" } }],
}),
"utf-8",
);
const child = spawnCli([
"--proxy-only",
"--provider-openai",
upstream.url,
"--fixtures",
localPath,
"--fixtures",
`${fixtureServer.url}/fx.json`,
"--port",
"0",
]);
await child.waitForOutput(/listening on/i, 8000);
expect(child.stdout()).toContain("Loaded 2 fixture(s)");
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
} finally {
await fixtureServer.close();
await upstream.close();
rmSync(tmp, { recursive: true, force: true });
}
});
it("starts successfully with --agui-proxy-only and URL-only --fixtures", async () => {
const fixtureServer = await startHttpServer((_req, res) => {
res.writeHead(200, { "content-type": "application/json" });
res.end(REMOTE_FIXTURE_BODY);
});
const aguiUpstream = await startHttpServer((_req, res) => {
res.writeHead(200);
res.end("ok");
});
try {
const child = spawnCli([
"--agui-proxy-only",
"--agui-upstream",
aguiUpstream.url,
"--fixtures",
`${fixtureServer.url}/fx.json`,
"--port",
"0",
]);
await child.waitForOutput(/listening on/i, 8000);
expect(child.stdout()).toContain("Loaded 1 fixture(s)");
expect(child.stderr()).not.toMatch(
/requires a local --fixtures path for the recording destination/,
);
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
} finally {
await fixtureServer.close();
await aguiUpstream.close();
}
});
});
/* ================================================================== */
/* --provider-openrouter (OpenRouter video record upstream) */
/* ================================================================== */
describe.skipIf(!CLI_AVAILABLE)("CLI: --provider-openrouter", () => {
it("--help lists --provider-openrouter", async () => {
const { stdout, code } = await runCli(["--help"]);
expect(stdout).toContain("--provider-openrouter");
expect(code).toBe(0);
});
it("--record --provider-openrouter satisfies the provider gate and boots", async () => {
const tmp = makeTmpDir();
try {
writeFixture(tmp, "fx.json");
const child = spawnCli([
"--record",
"--provider-openrouter",
"http://127.0.0.1:59997",
"--fixtures",
tmp,
"--port",
"0",
]);
await child.waitForOutput(/listening on/i, 8000);
expect(child.stderr()).not.toMatch(/requires at least one --provider-\* flag/);
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
});
describe.skipIf(!CLI_AVAILABLE)("CLI: timeout flags without record/proxy-only", () => {
it("warns when --upstream-timeout-ms is passed without --record/--proxy-only", async () => {
const tmp = makeTmpDir();
try {
writeFixture(tmp, "fx.json");
const child = spawnCli(["--upstream-timeout-ms", "5000", "--fixtures", tmp, "--port", "0"]);
await child.waitForOutput(/upstream-timeout-ms.*--record/i, 8000);
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
it("warns when --body-timeout-ms is passed without --record/--proxy-only", async () => {
const tmp = makeTmpDir();
try {
writeFixture(tmp, "fx.json");
const child = spawnCli(["--body-timeout-ms", "5000", "--fixtures", tmp, "--port", "0"]);
await child.waitForOutput(/body-timeout-ms.*--record/i, 8000);
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
it("warns when a --provider-* flag is passed without --record/--proxy-only", async () => {
const tmp = makeTmpDir();
try {
writeFixture(tmp, "fx.json");
// Same parsed-then-dropped class as the timeout flags: a provider URL
// without --record/--proxy-only configures nothing.
const child = spawnCli([
"--provider-openrouter",
"http://127.0.0.1:59995",
"--fixtures",
tmp,
"--port",
"0",
]);
await child.waitForOutput(/provider-openrouter.*--record/i, 8000);
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
it("does not warn when a --provider-* flag accompanies --record", async () => {
const tmp = makeTmpDir();
try {
writeFixture(tmp, "fx.json");
const child = spawnCli([
"--record",
"--provider-openrouter",
"http://127.0.0.1:59994",
"--fixtures",
tmp,
"--port",
"0",
]);
await child.waitForOutput(/listening on/i, 8000);
// Absence asserted with the SAME pattern the positive test uses.
expect(child.stderr() + child.stdout()).not.toMatch(/provider-openrouter.*--record/i);
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
it("does not warn when the timeout flags accompany --record", async () => {
const tmp = makeTmpDir();
try {
writeFixture(tmp, "fx.json");
const child = spawnCli([
"--record",
"--provider-openrouter",
"http://127.0.0.1:59996",
"--upstream-timeout-ms",
"5000",
"--fixtures",
tmp,
"--port",
"0",
]);
await child.waitForOutput(/listening on/i, 8000);
// Absence asserted with the SAME pattern family the positive tests
// use, so a reworded warn cannot silently pass this negative check.
expect(child.stderr() + child.stdout()).not.toMatch(/upstream-timeout-ms.*--record/i);
expect(child.stderr() + child.stdout()).not.toMatch(/body-timeout-ms.*--record/i);
child.kill("SIGTERM");
await new Promise<void>((resolve) => {
child.cp.on("close", () => resolve());
});
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
});