-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathtest.test.ts
More file actions
9231 lines (8793 loc) · 322 KB
/
Copy pathtest.test.ts
File metadata and controls
9231 lines (8793 loc) · 322 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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { Command } from 'commander';
import { ApiError } from '../lib/errors.js';
import { GLOBAL_OPTS_HINT } from '../lib/output.js';
import {
type CliFailureContext,
type CliLatestResult,
type CliTest,
type CliTestCode,
type CliTestStep,
type TestDeps,
createTestCommand,
isPresignedCodeUrl,
runCodeGet,
runCodePut,
runCreate,
runCreateBatch,
runCreateFromPlan,
runDelete,
runDiff,
runFailureGet,
runFailureSummary,
runGet,
runExport,
runImport,
runLint,
runList,
runOpen,
runPlanPut,
runResult,
runScaffold,
runSteps,
runTestWaitMany,
runUpdate,
} from './test.js';
function disableExits(cmd: Command): void {
cmd.exitOverride();
cmd.commands.forEach(disableExits);
}
const FE_TEST: CliTest = {
id: 'test_fe',
projectId: 'project_alice',
name: 'Checkout happy path',
type: 'frontend',
createdFrom: 'portal',
status: 'failed',
createdAt: '2026-04-20T11:00:00.000Z',
updatedAt: '2026-05-05T12:34:56.000Z',
};
const BE_TEST: CliTest = {
id: 'test_be',
projectId: 'project_alice',
name: 'Smoke — health check',
type: 'backend',
createdFrom: 'mcp',
status: 'passed',
createdAt: '2026-04-22T09:00:00.000Z',
updatedAt: '2026-05-05T11:00:30.000Z',
};
type FetchInput = Parameters<typeof globalThis.fetch>[0];
function makeFetch(
handler: (url: string, init: RequestInit) => { status?: number; body: unknown },
): typeof globalThis.fetch {
return (async (input: FetchInput, init: RequestInit = {}) => {
const url =
typeof input === 'string'
? input
: input instanceof URL
? input.toString()
: (input as { url: string }).url;
const { status = 200, body } = handler(url, init);
return new Response(JSON.stringify(body), {
status,
headers: { 'content-type': 'application/json' },
});
}) as typeof globalThis.fetch;
}
function makeCreds(
apiKey = 'sk-user-test',
apiUrl = 'http://localhost:13502',
): { credentialsPath: string } {
const dir = mkdtempSync(join(tmpdir(), 'cli-p3-'));
const credentialsPath = join(dir, 'credentials');
mkdirSync(dir, { recursive: true });
writeFileSync(credentialsPath, `[default]\napi_url = ${apiUrl}\napi_key = ${apiKey}\n`, {
mode: 0o600,
});
return { credentialsPath };
}
describe('createTestCommand — surface', () => {
let logSpy: ReturnType<typeof vi.spyOn>;
let errorSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
logSpy.mockRestore();
errorSpy.mockRestore();
});
it('exposes the expected top-level subcommands', () => {
const test = createTestCommand();
const names = test.commands.map(c => c.name()).sort();
expect(names).toEqual([
'artifact',
'cancel',
'code',
'create',
'create-batch',
'delete',
'delete-batch',
'diff',
'export',
'failure',
'flaky',
'get',
'import',
'lint',
'list',
'open',
'plan',
'rerun',
'result',
'run',
'scaffold',
'steps',
'update',
'wait',
]);
});
it('exposes the expected `code` subcommands', () => {
const test = createTestCommand();
const code = test.commands.find(c => c.name() === 'code');
expect(code).toBeDefined();
expect(code!.commands.map(c => c.name()).sort()).toEqual(['get', 'put']);
});
it('exposes the expected `failure` subcommands', () => {
const test = createTestCommand();
const failure = test.commands.find(c => c.name() === 'failure');
expect(failure).toBeDefined();
// M2.1 piece 3 adds `summary`. `get` is the bundle entry point;
// `summary` is the lightweight analysis-only triage card.
expect(failure!.commands.map(c => c.name()).sort()).toEqual(['get', 'summary']);
});
it('list exposes the documented filter and pagination flags (including --cursor alias)', () => {
const test = createTestCommand();
const list = test.commands.find(c => c.name() === 'list')!;
const flagNames = list.options.map(o => o.long);
expect(flagNames).toEqual(
expect.arrayContaining([
'--project',
'--type',
'--created-from',
'--page-size',
'--starting-token',
'--cursor',
'--max-items',
]),
);
});
it('failure get exposes --out and --failed-only flags (P5)', () => {
// P5 implements `failure get`. The only flags are --out (atomic on-disk
// bundle) and --failed-only (§7.4 narrow-budget filter). Pinning the
// surface so a future "consolidate flags" sweep doesn't drop them.
const test = createTestCommand();
const failure = test.commands.find(c => c.name() === 'failure')!;
const failureGet = failure.commands.find(c => c.name() === 'get')!;
const flagNames = failureGet.options.map(o => o.long).sort();
expect(flagNames).toEqual(['--failed-only', '--out']);
});
it('steps exposes pagination flags', () => {
const test = createTestCommand();
const steps = test.commands.find(c => c.name() === 'steps');
expect(steps).toBeDefined();
const flagNames = steps!.options.map(o => o.long);
expect(flagNames).toEqual(
expect.arrayContaining(['--page-size', '--max-items', '--starting-token']),
);
});
it('result exposes --include-analysis (M2.1) + M3.4 piece-5 --history flags', () => {
// M2.1 piece 3 adds `--include-analysis` to `test result`.
// M3.4 piece 5 adds `--history`, `--source`, `--since`, `--page-size`, `--cursor`.
// Issue #165 adds text-table shaping via `--columns` and `--no-header`.
// Pinning the surface so a future flag-consolidation sweep keeps every
// option intentional. Back-compat: bare `test result <id>` (no --history)
// still calls runResult and returns the M2 CliLatestResult shape.
const test = createTestCommand();
const result = test.commands.find(c => c.name() === 'result');
const flagNames = result!.options.map(o => o.long);
expect(flagNames).toEqual([
'--include-analysis',
'--history',
'--source',
'--since',
'--page-size',
'--cursor',
'--columns',
'--no-header',
]);
});
it('code get exposes --out as its only option', () => {
// `--out` lets agents write the response to a file without a shell
// redirect (matters on Windows + when the wire shape carries a
// presigned URL we want to stream straight to disk). Pinning it
// here so a future "remove redundant flag" sweep doesn't take it.
const test = createTestCommand();
const code = test.commands.find(c => c.name() === 'code');
const codeGet = code!.commands.find(c => c.name() === 'get');
const flagNames = codeGet!.options.map(o => o.long);
expect(flagNames).toEqual(['--out']);
});
// -------------------------------------------------------------------------
// GLOBAL_OPTS_HINT sweep — every leaf subcommand must surface the footer
// pointing at `testsprite --help` so users discover --dry-run, --output,
// --profile, --endpoint-url, --verbose, and --debug.
//
// This addresses the dogfood entry (2026-05-15): "M3.3 subcommands omitted
// GLOBAL_OPTS_HINT". The M3.3 fix landed in fix/cli-m3.3-consolidated-fixes;
// this sweep guards the full surface (M2 + M3.x) against future regressions.
// -------------------------------------------------------------------------
function captureHelp(cmd: ReturnType<typeof createTestCommand>): string {
let out = '';
cmd.configureOutput({
writeOut: (str: string) => {
out += str;
},
});
cmd.outputHelp();
return out;
}
it('M3.3: test run --help includes GLOBAL_OPTS_HINT', () => {
const test = createTestCommand();
const run = test.commands.find(c => c.name() === 'run')!;
const help = captureHelp(run);
expect(help).toContain('testsprite --help');
expect(help).toContain('--dry-run');
});
it('M3.3: test wait --help includes GLOBAL_OPTS_HINT', () => {
const test = createTestCommand();
const wait = test.commands.find(c => c.name() === 'wait')!;
const help = captureHelp(wait);
expect(help).toContain('testsprite --help');
expect(help).toContain('--dry-run');
});
it('M3.3: test artifact get --help includes GLOBAL_OPTS_HINT', () => {
const test = createTestCommand();
const artifact = test.commands.find(c => c.name() === 'artifact')!;
const artifactGet = artifact.commands.find(c => c.name() === 'get')!;
const help = captureHelp(artifactGet);
expect(help).toContain('testsprite --help');
expect(help).toContain('--dry-run');
});
it('M3.3: test failure get --help includes GLOBAL_OPTS_HINT', () => {
const test = createTestCommand();
const failure = test.commands.find(c => c.name() === 'failure')!;
const failureGet = failure.commands.find(c => c.name() === 'get')!;
const help = captureHelp(failureGet);
expect(help).toContain('testsprite --help');
expect(help).toContain('--dry-run');
});
it('M3.3: test failure summary --help includes GLOBAL_OPTS_HINT', () => {
const test = createTestCommand();
const failure = test.commands.find(c => c.name() === 'failure')!;
const failureSummary = failure.commands.find(c => c.name() === 'summary')!;
const help = captureHelp(failureSummary);
expect(help).toContain('testsprite --help');
expect(help).toContain('--dry-run');
});
it('M2 sweep: all remaining leaf subcommands include GLOBAL_OPTS_HINT', () => {
// Covers list, get, create, create-batch, steps, result, update, delete,
// code get, code put, plan put — the full M2 surface that the dogfood
// entry (2026-05-13) flagged and fix/cli-dogfood-bundle-2026-05-16 fixed.
const test = createTestCommand();
// Flat leaf commands (direct children of `test`)
const flatLeaves = [
'list',
'get',
'create',
'create-batch',
'steps',
'result',
'update',
'delete',
];
for (const name of flatLeaves) {
const cmd = test.commands.find(c => c.name() === name)!;
expect(cmd, `test ${name} must exist`).toBeDefined();
const help = captureHelp(cmd);
expect(help, `test ${name} --help must include GLOBAL_OPTS_HINT`).toContain(GLOBAL_OPTS_HINT);
}
// Nested: test code get, test code put
const code = test.commands.find(c => c.name() === 'code')!;
for (const name of ['get', 'put']) {
const cmd = code.commands.find(c => c.name() === name)!;
const help = captureHelp(cmd);
expect(help, `test code ${name} --help must include GLOBAL_OPTS_HINT`).toContain(
GLOBAL_OPTS_HINT,
);
}
// Nested: test plan put
const plan = test.commands.find(c => c.name() === 'plan')!;
const planPut = plan.commands.find(c => c.name() === 'put')!;
const planHelp = captureHelp(planPut);
expect(planHelp, 'test plan put --help must include GLOBAL_OPTS_HINT').toContain(
GLOBAL_OPTS_HINT,
);
});
});
describe('runList', () => {
it('passes projectId, type, and createdFrom to the facade query string', async () => {
const { credentialsPath } = makeCreds();
const seen: string[] = [];
const fetchImpl = makeFetch(url => {
seen.push(url);
return { body: { items: [FE_TEST], nextToken: null } };
});
await runList(
{
profile: 'default',
output: 'json',
debug: false,
projectId: 'project_alice',
type: 'frontend',
createdFrom: 'portal',
},
{ credentialsPath, fetchImpl, stdout: () => undefined },
);
expect(seen[0]).toContain('projectId=project_alice');
expect(seen[0]).toContain('type=frontend');
expect(seen[0]).toContain('createdFrom=portal');
});
it('accepts --created-from cli and passes createdFrom=cli to the wire (dogfood 2026-06-04)', async () => {
// End-to-end through parseEnumFlag: backend now stamps createFrom='cli'
// on `testsprite test create` rows, so the filter must accept 'cli'.
// If parseEnumFlag rejected it, this would throw VALIDATION_ERROR before
// any fetch and `seen` would stay empty.
const { credentialsPath } = makeCreds();
const seen: string[] = [];
const fetchImpl = makeFetch(url => {
seen.push(url);
return { body: { items: [], nextToken: null } };
});
const test = createTestCommand({ credentialsPath, fetchImpl, stdout: () => undefined });
await test.parseAsync(['list', '--project', 'project_alice', '--created-from', 'cli'], {
from: 'user',
});
expect(seen[0]).toContain('createdFrom=cli');
});
it('auto-pages until nextToken is null', async () => {
const { credentialsPath } = makeCreds();
let calls = 0;
const fetchImpl = makeFetch(() => {
calls += 1;
if (calls === 1) return { body: { items: [FE_TEST], nextToken: 'cursor-1' } };
return { body: { items: [BE_TEST], nextToken: null } };
});
const out: string[] = [];
const page = await runList(
{ profile: 'default', output: 'json', debug: false, projectId: 'project_alice' },
{ credentialsPath, fetchImpl, stdout: line => out.push(line) },
);
expect(calls).toBe(2);
expect(page.items).toHaveLength(2);
expect(JSON.parse(out[0]!).items).toHaveLength(2);
});
it('--page-size returns one page (no auto-paging) and surfaces the cursor', async () => {
const { credentialsPath } = makeCreds();
const seen: string[] = [];
const fetchImpl = makeFetch(url => {
seen.push(url);
return { body: { items: [FE_TEST], nextToken: 'opaque-A' } };
});
const page = await runList(
{
profile: 'default',
output: 'json',
debug: false,
projectId: 'project_alice',
pageSize: 1,
},
{ credentialsPath, fetchImpl, stdout: () => undefined },
);
expect(seen).toHaveLength(1);
expect(seen[0]).toContain('pageSize=1');
expect(page.nextToken).toBe('opaque-A');
});
it('--max-items caps result count across multiple pages', async () => {
const { credentialsPath } = makeCreds();
let calls = 0;
const fetchImpl = makeFetch(() => {
calls += 1;
return {
body: {
items: [
{ ...FE_TEST, id: `t_${calls}_a` },
{ ...FE_TEST, id: `t_${calls}_b` },
],
nextToken: calls < 3 ? `cursor-${calls}` : null,
},
};
});
const page = await runList(
{
profile: 'default',
output: 'json',
debug: false,
projectId: 'project_alice',
maxItems: 3,
},
{ credentialsPath, fetchImpl, stdout: () => undefined },
);
expect(page.items).toHaveLength(3);
expect(page.nextToken).toBe('cursor-2');
});
it('rejects --type=junk locally with VALIDATION_ERROR (no network call)', async () => {
const test = createTestCommand();
disableExits(test);
await expect(
test.parseAsync(['list', '--project', 'project_alice', '--type', 'junk'], { from: 'user' }),
).rejects.toMatchObject({ code: 'VALIDATION_ERROR' });
});
it('rejects --created-from=junk locally with VALIDATION_ERROR', async () => {
const test = createTestCommand();
disableExits(test);
await expect(
test.parseAsync(['list', '--project', 'project_alice', '--created-from', 'junk'], {
from: 'user',
}),
).rejects.toMatchObject({ code: 'VALIDATION_ERROR' });
});
it('rejects --status=junk before reading credentials', async () => {
const test = createTestCommand();
disableExits(test);
await expect(
test.parseAsync(['list', '--project', 'project_alice', '--status', 'junk'], { from: 'user' }),
).rejects.toMatchObject({ code: 'VALIDATION_ERROR' });
});
it('rejects --page-size=0 locally with VALIDATION_ERROR (no network call)', async () => {
const { credentialsPath } = makeCreds();
const fetchImpl = makeFetch(() => {
throw new Error('network should not be hit');
});
await expect(
runList(
{
profile: 'default',
output: 'json',
debug: false,
projectId: 'project_alice',
pageSize: 0,
},
{ credentialsPath, fetchImpl, stdout: () => undefined },
),
).rejects.toMatchObject({ code: 'VALIDATION_ERROR', details: { field: 'page-size' } });
});
it('rejects invalid --status before requiring credentials', async () => {
const credentialsPath = join(mkdtempSync(join(tmpdir(), 'cli-list-status-')), 'credentials');
const fetchImpl = vi.fn();
await expect(
runList(
{
profile: 'default',
output: 'json',
debug: false,
projectId: 'project_alice',
status: 'notastatus',
},
{
credentialsPath,
fetchImpl: fetchImpl as unknown as typeof fetch,
stdout: () => undefined,
},
),
).rejects.toMatchObject({
code: 'VALIDATION_ERROR',
exitCode: 5,
details: { field: 'status' },
});
expect(fetchImpl).not.toHaveBeenCalled();
});
it('forwards a server-side VALIDATION_ERROR envelope as ApiError exit 5', async () => {
const { credentialsPath } = makeCreds();
const fetchImpl = makeFetch(() => ({
status: 400,
body: {
error: {
code: 'VALIDATION_ERROR',
message: 'bad cursor',
nextAction: 'pass nextToken from a previous response',
requestId: 'req_test',
details: { field: 'cursor' },
},
},
}));
await expect(
runList(
{
profile: 'default',
output: 'json',
debug: false,
projectId: 'project_alice',
startingToken: 'bogus',
},
{ credentialsPath, fetchImpl, stdout: () => undefined },
),
).rejects.toBeInstanceOf(ApiError);
});
it('text mode renders mixed FE/BE rows with header + status column', async () => {
const { credentialsPath } = makeCreds();
const fetchImpl = makeFetch(() => ({
body: { items: [FE_TEST, BE_TEST], nextToken: null },
}));
const out: string[] = [];
await runList(
{
profile: 'default',
output: 'text',
debug: false,
projectId: 'project_alice',
pageSize: 25,
},
{ credentialsPath, fetchImpl, stdout: line => out.push(line) },
);
const block = out.join('\n');
expect(block).toContain('ID');
expect(block).toContain('NAME');
expect(block).toContain('TYPE');
expect(block).toContain('FROM');
expect(block).toContain('STATUS');
expect(block).toContain('UPDATED');
expect(block).toContain('Checkout happy path');
expect(block).toContain('Smoke — health check');
// Both types render explicitly; the agent loop reads `type` directly
// from JSON, but humans glance at the column.
expect(block).toContain('frontend');
expect(block).toContain('backend');
// Both createdFrom variants render — verifies the column doesn't
// accidentally hardcode a value.
expect(block).toContain('portal');
expect(block).toContain('mcp');
});
it('text mode selects/reorders columns and suppresses the header', async () => {
const { credentialsPath } = makeCreds();
const fetchImpl = makeFetch(() => ({
body: { items: [FE_TEST, BE_TEST], nextToken: null },
}));
const out: string[] = [];
await runList(
{
profile: 'default',
output: 'text',
debug: false,
projectId: 'project_alice',
pageSize: 25,
columns: 'status,id',
noHeader: true,
},
{ credentialsPath, fetchImpl, stdout: line => out.push(line) },
);
const lines = out.join('\n').split('\n');
expect(lines[0]).toMatch(/^failed\s+test_fe$/);
expect(lines[1]).toMatch(/^passed\s+test_be$/);
expect(out.join('\n')).not.toContain('STATUS');
expect(out.join('\n')).not.toContain('UPDATED');
});
it('text mode rejects unknown columns with VALIDATION_ERROR before auth/network access', async () => {
await expect(
runList(
{
profile: 'default',
output: 'text',
debug: false,
projectId: 'project_alice',
pageSize: 25,
columns: 'bogus',
},
{ stdout: () => undefined },
),
).rejects.toMatchObject({
code: 'VALIDATION_ERROR',
exitCode: 5,
details: { field: 'columns' },
});
});
it('json mode ignores text-only column flags', async () => {
const { credentialsPath } = makeCreds();
const fetchImpl = makeFetch(() => ({
body: { items: [FE_TEST], nextToken: null },
}));
const out: string[] = [];
await runList(
{
profile: 'default',
output: 'json',
debug: false,
projectId: 'project_alice',
pageSize: 25,
columns: 'bogus',
noHeader: true,
},
{ credentialsPath, fetchImpl, stdout: line => out.push(line) },
);
expect(JSON.parse(out.join('\n')).items[0].id).toBe('test_fe');
});
it('text mode reads "No tests." when items is empty and nextToken is null', async () => {
const { credentialsPath } = makeCreds();
const fetchImpl = makeFetch(() => ({ body: { items: [], nextToken: null } }));
const out: string[] = [];
await runList(
{
profile: 'default',
output: 'text',
debug: false,
projectId: 'project_alice',
pageSize: 25,
},
{ credentialsPath, fetchImpl, stdout: line => out.push(line) },
);
expect(out.join('\n')).toBe('No tests.');
});
it('text mode reads "No tests on this page." with cursor when filtered out', async () => {
const { credentialsPath } = makeCreds();
const fetchImpl = makeFetch(() => ({ body: { items: [], nextToken: 'still-more' } }));
const out: string[] = [];
await runList(
{
profile: 'default',
output: 'text',
debug: false,
projectId: 'project_alice',
pageSize: 25,
},
{ credentialsPath, fetchImpl, stdout: line => out.push(line) },
);
const block = out.join('\n');
expect(block).toContain('No tests on this page.');
expect(block).toContain('nextToken: still-more');
});
it('--starting-token resumes pagination from the supplied cursor', async () => {
const { credentialsPath } = makeCreds();
const seenCursors: Array<string | null> = [];
const fetchImpl = makeFetch(url => {
const match = /cursor=([^&]+)/.exec(url);
seenCursors.push(match ? decodeURIComponent(match[1]!) : null);
return { body: { items: [FE_TEST], nextToken: null } };
});
await runList(
{
profile: 'default',
output: 'json',
debug: false,
projectId: 'project_alice',
startingToken: 'resume-here',
},
{ credentialsPath, fetchImpl, stdout: () => undefined },
);
expect(seenCursors[0]).toBe('resume-here');
});
});
// Fix 2: --cursor alias on `test list`
// Before this fix, `test list --cursor <token>` would emit
// "error: unknown option '--cursor'" (exit 5 via Commander error handling)
// because `test list` only had `--starting-token`.
describe('createTestCommand list — --cursor alias', () => {
it('--cursor is accepted by `test list` without "unknown option" error', async () => {
// This test exercises the Commander-level wiring, which is where the
// --cursor → startingToken merge happens (in the .action() handler).
// `runList` itself has no `cursor` field — the alias is resolved before
// `runList` is called.
const { credentialsPath } = makeCreds();
const seenCursors: Array<string | null> = [];
const fetchImpl = makeFetch(url => {
const match = /cursor=([^&]+)/.exec(url);
seenCursors.push(match ? decodeURIComponent(match[1]!) : null);
return { body: { items: [FE_TEST], nextToken: null } };
});
const deps: TestDeps = { credentialsPath, fetchImpl, stdout: () => undefined };
const test = createTestCommand(deps);
// Commander's .parseAsync with 'user' source parses bare tokens
// and flags relative to the command. --project is required.
await test.parseAsync(
['list', '--project', 'project_alice', '--cursor', 'cursor-alias-token'],
{
from: 'user',
},
);
expect(seenCursors[0]).toBe('cursor-alias-token');
});
it('--starting-token takes precedence over --cursor when both are supplied', async () => {
const { credentialsPath } = makeCreds();
const seenCursors: Array<string | null> = [];
const fetchImpl = makeFetch(url => {
const match = /cursor=([^&]+)/.exec(url);
seenCursors.push(match ? decodeURIComponent(match[1]!) : null);
return { body: { items: [FE_TEST], nextToken: null } };
});
const deps: TestDeps = { credentialsPath, fetchImpl, stdout: () => undefined };
const test = createTestCommand(deps);
await test.parseAsync(
[
'list',
'--project',
'project_alice',
'--starting-token',
'primary-token',
'--cursor',
'alias-token',
],
{ from: 'user' },
);
expect(seenCursors[0]).toBe('primary-token');
});
});
describe('createTestCommand list — required flag', () => {
it('rejects when --project is missing with VALIDATION_ERROR (not commander)', async () => {
const test = createTestCommand();
disableExits(test);
// We deliberately removed `.requiredOption` so the local validator
// (`requireProjectId`) runs and throws the typed envelope. Commander's
// built-in "required option" error would surface as exit 1, breaking
// the CLI error spec §2 contract that "missing required field"
// is a `VALIDATION_ERROR` (exit 5).
try {
await test.parseAsync(['list'], { from: 'user' });
expect.unreachable('expected ApiError');
} catch (err) {
const apiErr = err as { code?: string; exitCode?: number; details?: { field?: string } };
expect(apiErr.code).toBe('VALIDATION_ERROR');
expect(apiErr.exitCode).toBe(5);
expect(apiErr.details?.field).toBe('project');
}
});
it('M2.1 piece 2: --status passes the comma-separated value to the wire', async () => {
const { credentialsPath } = makeCreds();
const seen: string[] = [];
const fetchImpl = makeFetch(url => {
seen.push(url);
return { body: { items: [], nextToken: null } };
});
await runList(
{
profile: 'default',
output: 'json',
debug: false,
projectId: 'project_alice',
status: 'failed,blocked',
},
{ credentialsPath, fetchImpl, stdout: () => undefined },
);
// Server-side filter applied before pagination — the status query
// param must reach the wire so a long-tail of 50+ tests doesn't
// get fetched + filtered client-side.
expect(seen[0]).toMatch(/[?&]status=failed%2Cblocked/);
});
it('M2.1 piece 2: --status rejects unknown tokens locally (exit 5, no fetch)', async () => {
// Defense: a typo like `--status fail` shouldn't silently filter
// to nothing. Fail fast client-side with the accepted set in
// the error envelope.
const { credentialsPath } = makeCreds();
let fetched = false;
const fetchImpl = makeFetch(() => {
fetched = true;
return { body: { items: [], nextToken: null } };
});
await expect(
runList(
{
profile: 'default',
output: 'json',
debug: false,
projectId: 'project_alice',
status: 'fail', // typo for `failed`
},
{ credentialsPath, fetchImpl, stdout: () => undefined },
),
).rejects.toMatchObject({ code: 'VALIDATION_ERROR', exitCode: 5 });
expect(fetched).toBe(false);
});
});
describe('runGet', () => {
it('GETs /tests/{id} and prints the §6.2 fields in text mode', async () => {
const { credentialsPath } = makeCreds();
const seen: string[] = [];
const fetchImpl = makeFetch(url => {
seen.push(url);
return { body: FE_TEST };
});
const out: string[] = [];
const test = await runGet(
{ profile: 'default', output: 'text', debug: false, testId: 'test_fe' },
{ credentialsPath, fetchImpl, stdout: line => out.push(line) },
);
expect(seen[0]).toContain('/tests/test_fe');
expect(test.id).toBe('test_fe');
const block = out.join('\n');
expect(block).toContain('id: test_fe');
expect(block).toContain('projectId: project_alice');
expect(block).toContain('status: failed');
});
it('renders a `blocked` test row (M2.1 piece 1 — distinct from failed)', async () => {
// Regression for the M2.1 contract flip: pre-M2.1 the wire shape
// would have arrived as `status: failed` for the same source row.
// The text renderer must surface `blocked` byte-for-byte without
// collapsing it back to the legacy bucket. Also asserts the
// structured `details` parsed cleanly through the JSON envelope.
const blockedTest: CliTest = {
...FE_TEST,
id: 'test_blocked',
status: 'blocked',
details: {
processingStatus: 'Idle',
testStatus: 'Blocked',
rawStatus: 'ps=Idle; ts=Blocked',
},
};
const { credentialsPath } = makeCreds();
const fetchImpl = makeFetch(() => ({ body: blockedTest }));
const out: string[] = [];
const test = await runGet(
{ profile: 'default', output: 'text', debug: false, testId: 'test_blocked' },
{ credentialsPath, fetchImpl, stdout: line => out.push(line) },
);
expect(test.status).toBe('blocked');
expect(test.details).toEqual({
processingStatus: 'Idle',
testStatus: 'Blocked',
rawStatus: 'ps=Idle; ts=Blocked',
});
expect(out.join('\n')).toContain('status: blocked');
});
it('renders the planSteps count when the facade ships planStepCount (M3.4)', async () => {
const withPlan: CliTest = { ...FE_TEST, planStepCount: 3 };
const { credentialsPath } = makeCreds();
const fetchImpl = makeFetch(() => ({ body: withPlan }));
const out: string[] = [];
await runGet(
{ profile: 'default', output: 'text', debug: false, testId: 'test_fe' },
{ credentialsPath, fetchImpl, stdout: line => out.push(line) },
);
expect(out.join('\n')).toContain('planSteps: 3');
});
it('omits the planSteps line when planStepCount is null or absent (M3.4)', async () => {
const noPlan: CliTest = { ...FE_TEST, planStepCount: null };
const { credentialsPath } = makeCreds();
const fetchImpl = makeFetch(() => ({ body: noPlan }));
const out: string[] = [];
await runGet(
{ profile: 'default', output: 'text', debug: false, testId: 'test_fe' },
{ credentialsPath, fetchImpl, stdout: line => out.push(line) },
);
expect(out.join('\n')).not.toContain('planSteps:');
});
it('renders produces/consumes/category when the facade ships them', async () => {
const withDeps: CliTest = {
...FE_TEST,
produces: ['user_id', 'order_id'],
consumes: ['session_token'],
category: 'teardown',
};
const { credentialsPath } = makeCreds();
const fetchImpl = makeFetch(() => ({ body: withDeps }));
const out: string[] = [];
await runGet(
{ profile: 'default', output: 'text', debug: false, testId: 'test_fe' },
{ credentialsPath, fetchImpl, stdout: line => out.push(line) },
);
const block = out.join('\n');
expect(block).toContain('produces: user_id, order_id');
expect(block).toContain('consumes: session_token');
expect(block).toContain('category: teardown');
});
it('omits produces/consumes/category lines when absent', async () => {
const { credentialsPath } = makeCreds();
const fetchImpl = makeFetch(() => ({ body: FE_TEST }));
const out: string[] = [];
await runGet(
{ profile: 'default', output: 'text', debug: false, testId: 'test_fe' },
{ credentialsPath, fetchImpl, stdout: line => out.push(line) },
);
const block = out.join('\n');
expect(block).not.toContain('produces:');
expect(block).not.toContain('consumes:');
expect(block).not.toContain('category:');
});
it('NOT_FOUND envelope from server propagates as ApiError exit 4', async () => {
const { credentialsPath } = makeCreds();
const fetchImpl = makeFetch(() => ({
status: 404,
body: {
error: {
code: 'NOT_FOUND',
message: 'Resource not found.',
nextAction: 'Check the id with `testsprite test list --project <id>`.',
requestId: 'req_test',
details: { resource: 'test', id: 'test_missing' },
},
},
}));
await expect(
runGet(
{ profile: 'default', output: 'json', debug: false, testId: 'test_missing' },
{ credentialsPath, fetchImpl, stdout: () => undefined },
),
).rejects.toMatchObject({ code: 'NOT_FOUND', exitCode: 4 });
});
it('URL-encodes test ids with `/` or `?` in them', async () => {
const { credentialsPath } = makeCreds();
const seen: string[] = [];
const fetchImpl = makeFetch(url => {
seen.push(url);
return { body: FE_TEST };
});
await runGet(
{ profile: 'default', output: 'json', debug: false, testId: 'odd/id?weird' },
{ credentialsPath, fetchImpl, stdout: () => undefined },
);
expect(seen[0]).toContain('odd%2Fid%3Fweird');
});
it('M2.1 piece 4: renders project: <name> (<id>) when projectName is set', async () => {
const TEST_WITH_PROJECT_NAME: CliTest = {
...FE_TEST,
projectId: 'project_alice',
projectName: 'Checkout',
};
const { credentialsPath } = makeCreds();
const fetchImpl = makeFetch(() => ({ body: TEST_WITH_PROJECT_NAME }));